diff --git a/README.md b/README.md index 70ddce0..b43bc23 100644 --- a/README.md +++ b/README.md @@ -236,6 +236,8 @@ Elements are identified by accessibility attributes — not internal refs. Match ¹ `enter` sends HID key 40 (Return); `home` and `lock` use `idb ui button HOME|LOCK`. iOS has no back button, so `back` fails with `UNSUPPORTED_ON_IOS`. `device_type` clears the focused field first with Command+A (`idb ui key 4 --command`) and Backspace (`idb ui key 42`). +On the IDB backend, when the idb client supports `idb ui describe-all --format complete`, `SnapshotResult` also reports `warnings` when the read is incomplete. Today the only warning is `ax-tree-truncated(backend=,depth=,nodes=)`: the idb companion stopped the accessibility read at its size bound, so elements on screen can be missing from `hierarchy`. `backend` is the idb backend that served the read (left out when idb names none), and `depth` and `nodes` are the deepest level and the element count of the tree that came back. `device_snapshot` prints the warnings on a `Warnings:` line. `warnings` is absent when there are none. With such a client, `raw` is the `--format complete` document (`{ backend, truncated, elements, … }`) instead of the tree array. + #### Android snapshot on continuously-redrawing screens `uiautomator dump` calls `UiAutomation.waitForIdle` internally, which never @@ -323,7 +325,8 @@ The `device-mcp` MCP server CLI passes no option, so it uses On the ADB backend, each `SnapshotResult` also reports `source` (`'dump'` or `'instrument'`, the path that produced the tree) and `captureMs` (the capture -time, including failed attempts and fallbacks). +time, including failed attempts and fallbacks). For the iOS `warnings` field, +see [Backend Implementation](#backend-implementation). The helper is a `testOnly` APK installed with `adb install -t`, so it only installs on developer emulators/attached devices, never on locked-down or diff --git a/src/backends/__fixtures__/idb-describe-all-login-complete.json b/src/backends/__fixtures__/idb-describe-all-login-complete.json new file mode 100644 index 0000000..43e77b5 --- /dev/null +++ b/src/backends/__fixtures__/idb-describe-all-login-complete.json @@ -0,0 +1,255 @@ +{ + "automation": { + "asserted": false, + "enabled": true + }, + "backend": "axbridge-exclusive", + "coverage": null, + "elements": [ + { + "type": "Application", + "label": "MetaMask", + "enabled": null, + "frame": { + "x": 0, + "y": 0, + "width": 402, + "height": 874 + }, + "children": [ + { + "type": "Window", + "frame": { + "x": 0, + "y": 0, + "width": 402, + "height": 874 + }, + "children": [ + { + "type": "Other", + "frame": { + "x": 0, + "y": 0, + "width": 402, + "height": 874 + }, + "children": [ + { + "type": "Other", + "identifier": "login", + "frame": { + "x": 0, + "y": 0, + "width": 402, + "height": 874 + }, + "children": [ + { + "type": "Other", + "frame": { + "x": 0, + "y": 120, + "width": 402, + "height": 400 + }, + "children": [ + { + "type": "Image", + "identifier": "fox-logo", + "frame": { + "x": 151, + "y": 140, + "width": 100, + "height": 100 + }, + "children": [] + }, + { + "type": "StaticText", + "label": "Welcome back", + "identifier": "login-title", + "frame": { + "x": 24, + "y": 260, + "width": 354, + "height": 36 + }, + "children": [] + }, + { + "type": "Other", + "frame": { + "x": 24, + "y": 320, + "width": 354, + "height": 52 + }, + "children": [ + { + "type": "SecureTextField", + "label": "Password", + "identifier": "login-password-input", + "value": null, + "frame": { + "x": 24, + "y": 320, + "width": 354, + "height": 52 + }, + "children": [] + } + ] + }, + { + "type": "Button", + "label": "Unlock", + "identifier": "log-in-button", + "enabled": false, + "frame": { + "x": 24, + "y": 396, + "width": 354, + "height": 48 + }, + "children": [] + }, + { + "type": "Button", + "label": "Forgot password?", + "identifier": "reset-wallet-button", + "frame": { + "x": 24, + "y": 460, + "width": 354, + "height": 32 + }, + "children": [] + } + ] + }, + { + "type": "Other", + "identifier": "login-info-modal", + "frame": { + "x": 0, + "y": 520, + "width": 402, + "height": 354 + }, + "children": [ + { + "type": "StaticText", + "label": "Unlock with Face ID?", + "frame": { + "x": 24, + "y": 548, + "width": 354, + "height": 24 + }, + "children": [] + }, + { + "type": "StaticText", + "label": "You can turn this on later in Settings.", + "frame": { + "x": 24, + "y": 580, + "width": 354, + "height": 40 + }, + "children": [] + }, + { + "type": "Other", + "frame": { + "x": 24, + "y": 640, + "width": 354, + "height": 116 + }, + "children": [ + { + "type": "Button", + "label": "Enable", + "identifier": "login-info-modal-enable-button", + "frame": { + "x": 24, + "y": 640, + "width": 354, + "height": 48 + }, + "children": [] + }, + { + "type": "Button", + "label": "Not now", + "identifier": "login-info-modal-dismiss-button", + "frame": { + "x": 24, + "y": 704, + "width": 354, + "height": 48 + }, + "children": [] + } + ] + } + ] + } + ] + } + ] + } + ] + }, + { + "type": "Other", + "label": "Status bar", + "frame": { + "x": 0, + "y": 0, + "width": 402, + "height": 54 + }, + "children": [ + { + "type": "StaticText", + "label": "9:41", + "frame": { + "x": 40, + "y": 18, + "width": 40, + "height": 20 + }, + "children": [] + } + ] + } + ] + } + ], + "frames": null, + "interaction": null, + "modal": null, + "narrowing": null, + "profile": null, + "screen": { + "coordinate_space": "screen", + "display": { + "rotation": 0, + "scale": 3 + }, + "height": 874, + "width": 402 + }, + "target": { + "kind": "frontmost", + "match_key": null, + "pid": null, + "value": null, + "x": null, + "y": null + }, + "truncated": false +} diff --git a/src/backends/idb-backend.test.ts b/src/backends/idb-backend.test.ts index 5d4c935..7b3fc90 100644 --- a/src/backends/idb-backend.test.ts +++ b/src/backends/idb-backend.test.ts @@ -5,7 +5,12 @@ import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { parseIdbHierarchy, mapIdbElement, IdbBackend } from './idb-backend.js'; +import { + parseIdbDescribeAll, + parseIdbHierarchy, + mapIdbElement, + IdbBackend, +} from './idb-backend.js'; import { IdbUnavailableError } from './idb-errors.js'; import type { UIElement } from './types.js'; import { findElement, generateLocators } from '../utils/element.js'; @@ -49,6 +54,7 @@ vi.mock('../utils/platform.js', () => ({ resolveIdbPath: vi.fn().mockResolvedValue('/usr/local/bin/idb'), idbSupportsApiSelection: vi.fn().mockResolvedValue(false), idbSupportsNestedDescribe: vi.fn().mockResolvedValue(false), + idbSupportsCompleteDescribe: vi.fn().mockResolvedValue(false), chooseAxApi: vi.fn().mockReturnValue(null), detectPlatform: vi.fn(), detectAllDevices: vi.fn(), @@ -61,6 +67,9 @@ const mockReadFile = vi.mocked(readFile); const mockSupportsApi = vi.mocked(platformModule.idbSupportsApiSelection); const mockChooseAxApi = vi.mocked(platformModule.chooseAxApi); const mockSupportsNested = vi.mocked(platformModule.idbSupportsNestedDescribe); +const mockSupportsComplete = vi.mocked( + platformModule.idbSupportsCompleteDescribe, +); describe('parseIdbHierarchy', () => { it('treats an empty children array on a root object as a leaf', () => { @@ -185,6 +194,108 @@ describe('parseIdbHierarchy with synthetic flat and nested fixtures', () => { .map((loc) => loc.description) .sort(); + it('maps the --format complete document like the nested tree', () => { + const complete = parseIdbDescribeAll( + fixture('idb-describe-all-login-complete.json'), + ); + + expect(complete).toStrictEqual({ + hierarchy: nested, + format: 'complete', + truncated: false, + backend: 'axbridge-exclusive', + }); + expect( + parseIdbHierarchy(fixture('idb-describe-all-login-complete.json')), + ).toStrictEqual(nested); + }); + + it('reads truncated from the --format complete document', () => { + const document = JSON.parse( + fixture('idb-describe-all-login-complete.json'), + ) as Record; + + const read = parseIdbDescribeAll( + JSON.stringify({ ...document, truncated: true }), + ); + + expect(read.truncated).toBe(true); + expect(read.hierarchy).toStrictEqual(nested); + }); + + it.each([ + ['flat', 'idb-describe-all-login-flat.json'], + ['nested', 'idb-describe-all-login-nested.json'], + ])('reads the %s format as legacy and not truncated', (_name, file) => { + const read = parseIdbDescribeAll(fixture(file)); + + expect(read.format).toBe('legacy'); + expect(read.truncated).toBe(false); + expect(read.backend).toBeUndefined(); + expect(read.hierarchy).toStrictEqual(parseIdbHierarchy(fixture(file))); + }); + + it('reads output that is not JSON as invalid', () => { + expect(parseIdbDescribeAll('oops')).toMatchObject({ + format: 'invalid', + truncated: false, + hierarchy: [{ type: 'raw', label: 'oops' }], + }); + }); + + it.each(['null', '42', '"text"', 'true'])( + 'reads a JSON root that is neither an array nor an object (%s) as invalid', + (raw) => { + expect(parseIdbDescribeAll(raw)).toStrictEqual({ + hierarchy: [ + { + type: 'raw', + label: raw, + frame: { x: 0, y: 0, width: 0, height: 0 }, + enabled: true, + }, + ], + format: 'invalid', + truncated: false, + }); + }, + ); + + it('reads a document with backend null as complete, without a backend', () => { + const document = JSON.parse( + fixture('idb-describe-all-login-complete.json'), + ) as Record; + + expect( + parseIdbDescribeAll( + JSON.stringify({ ...document, backend: null, truncated: true }), + ), + ).toStrictEqual({ + hierarchy: nested, + format: 'complete', + truncated: true, + }); + }); + + it.each([ + ['missing', {}], + ['null', { elements: null }], + ])( + 'reads a document whose elements are %s as complete and empty', + (_name, elements) => { + expect( + parseIdbDescribeAll( + JSON.stringify({ backend: 'ax', truncated: false, ...elements }), + ), + ).toStrictEqual({ + hierarchy: [], + format: 'complete', + truncated: false, + backend: 'ax', + }); + }, + ); + it('preserves tree shape and maps both formats identically in pre-order', () => { expect(flat.every((el) => el.children === undefined)).toBe(true); expect(nested).toHaveLength(1); @@ -2269,6 +2380,286 @@ describe('IdbBackend.snapshot accessibility backend selection', () => { expect(hierarchy[0].children?.[0].children).toBeUndefined(); }); + describe('--format complete', () => { + // Three levels: Application > Other > Button. + const tree = [ + { + type: 'Application', + label: 'MetaMask', + frame: { x: 0, y: 0, width: 402, height: 874 }, + children: [ + { + type: 'Other', + frame: { x: 0, y: 0, width: 402, height: 874 }, + children: [ + { + type: 'Button', + label: 'Unlock', + identifier: 'log-in-button', + frame: { x: 24, y: 396, width: 354, height: 48 }, + children: [], + }, + ], + }, + ], + }, + ]; + const document = (truncated: boolean, servedBy = 'axbridge-exclusive') => + JSON.stringify({ + backend: servedBy, + elements: tree, + modal: null, + screen: { width: 402, height: 874 }, + target: { kind: 'frontmost' }, + truncated, + }); + + const describeCalls = (): string[][] => + mockExecStrict.mock.calls + .filter(([, args]) => args?.[1] === 'describe-all') + .map(([, args]) => args); + + beforeEach(() => { + mockSupportsApi.mockResolvedValue(false); + mockSupportsNested.mockResolvedValue(true); + mockSupportsComplete.mockResolvedValue(true); + }); + + afterEach(() => { + mockSupportsComplete.mockResolvedValue(false); + }); + + it('requests --format complete instead of --nested', async () => { + mockExecStrict.mockResolvedValue(document(false)); + + await backend.snapshot(); + + expect(describeCalls()).toStrictEqual([ + describeArgs(['--format', 'complete']), + ]); + }); + + it('passes --format complete with every --api attempt and the ax supplement', async () => { + mockSupportsApi.mockResolvedValue(true); + mockChooseAxApi.mockReturnValue('axbridge'); + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.includes('describe') && args?.includes('--json')) { + return JSON.stringify({ os_version: '26.1', name: 'iPhone' }); + } + if (args?.includes('axbridge')) { + throw new Error('axbridge backend requested accessibility failed'); + } + return document(false, 'ax'); + }); + + await backend.snapshot(); + + expect(describeCalls()).toStrictEqual( + expect.arrayContaining([ + describeArgs(['--api', 'axbridge', '--format', 'complete']), + describeArgs(['--api', 'ax', '--format', 'complete']), + ]), + ); + expect(describeCalls().every((args) => !args.includes('--nested'))).toBe( + true, + ); + }); + + it('returns the nested tree and the raw document, without warnings', async () => { + const raw = document(false); + mockExecStrict.mockResolvedValue(raw); + + const result = await backend.snapshot(); + + expect(result.raw).toBe(raw); + expect(result.hierarchy).toStrictEqual( + parseIdbHierarchy(JSON.stringify(tree)), + ); + expect(result.hierarchy[0].children?.[0].children?.[0].identifier).toBe( + 'log-in-button', + ); + expect(result).not.toHaveProperty('warnings'); + }); + + it('warns when the companion truncated the tree', async () => { + mockExecStrict.mockResolvedValue(document(true)); + + const result = await backend.snapshot(); + + expect(result.warnings).toStrictEqual([ + 'ax-tree-truncated(backend=axbridge-exclusive,depth=3,nodes=3)', + ]); + expect(result.hierarchy).toStrictEqual( + parseIdbHierarchy(JSON.stringify(tree)), + ); + }); + + it('measures the warning on the read, not on the ax supplement', async () => { + mockSupportsApi.mockResolvedValue(true); + mockChooseAxApi.mockReturnValue('axbridge'); + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.includes('describe') && args?.includes('--json')) { + return JSON.stringify({ os_version: '27.0', name: 'iPhone' }); + } + if (args?.includes('axbridge')) { + return document(true); + } + return JSON.stringify({ + backend: 'ax', + truncated: false, + elements: [ + { + type: 'Button', + identifier: 'extra-button', + frame: { x: 1, y: 1, width: 10, height: 10 }, + }, + ], + }); + }); + + const result = await backend.snapshot(); + + expect( + findElement(result.hierarchy, { identifier: 'extra-button' }), + ).not.toBeNull(); + expect(result.warnings).toStrictEqual([ + 'ax-tree-truncated(backend=axbridge-exclusive,depth=3,nodes=3)', + ]); + }); + + it('reports backend=ax when the ax fallback serves a truncated read', async () => { + mockSupportsApi.mockResolvedValue(true); + mockChooseAxApi.mockReturnValue('axbridge'); + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.includes('describe') && args?.includes('--json')) { + return JSON.stringify({ os_version: '27.0', name: 'iPhone' }); + } + if (args?.includes('axbridge')) { + throw new Error('axbridge backend requested accessibility failed'); + } + return document(true, 'ax'); + }); + + const result = await backend.snapshot(); + + expect(result.warnings).toStrictEqual([ + 'ax-tree-truncated(backend=ax,depth=3,nodes=3)', + ]); + expect(result.hierarchy).toStrictEqual( + parseIdbHierarchy(JSON.stringify(tree)), + ); + }); + + it.each([ + ['empty', ''], + ['null', null], + ])( + 'leaves out a backend that is %s and keeps --format complete', + async (_name, servedBy) => { + mockExecStrict.mockResolvedValue( + JSON.stringify({ + backend: servedBy, + elements: tree, + truncated: true, + }), + ); + + const result = await backend.snapshot(); + await backend.snapshot(); + + expect(result.warnings).toStrictEqual([ + 'ax-tree-truncated(depth=3,nodes=3)', + ]); + expect(describeCalls()).toStrictEqual([ + describeArgs(['--format', 'complete']), + describeArgs(['--format', 'complete']), + ]); + }, + ); + + it('falls back to --nested for good when the companion ignores --format complete', async () => { + // A companion that predates format selection answers with a flat tree. + const flat = JSON.stringify([ + { type: 'Application', frame: { x: 0, y: 0, width: 402, height: 874 } }, + ]); + const nested = JSON.stringify(tree); + mockExecStrict.mockImplementation(async (_cmd, args) => + args?.includes('--format') ? flat : nested, + ); + + const first = await backend.snapshot(); + const second = await backend.snapshot(); + + expect(describeCalls()).toStrictEqual([ + describeArgs(['--format', 'complete']), + describeArgs(['--nested']), + describeArgs(['--nested']), + ]); + for (const result of [first, second]) { + expect(result.raw).toBe(nested); + expect(result.hierarchy).toStrictEqual(parseIdbHierarchy(nested)); + expect(result).not.toHaveProperty('warnings'); + } + }); + + it.each(['not json', 'null'])( + 'keeps requesting --format complete after the output %s', + async (first) => { + mockExecStrict.mockResolvedValueOnce(first); + mockExecStrict.mockResolvedValue(document(false)); + + await backend.snapshot(); + await backend.snapshot(); + + expect(describeCalls()).toStrictEqual([ + describeArgs(['--format', 'complete']), + describeArgs(['--format', 'complete']), + ]); + }, + ); + }); + + it.each([ + ['no --format complete, --nested', true, ['--nested']], + ['no --format complete, no --nested', false, []], + ])( + 'keeps the output of an idb without --format complete (%s)', + async (_name, nestedSupported, extra) => { + mockSupportsApi.mockResolvedValue(false); + mockSupportsNested.mockResolvedValue(nestedSupported); + mockSupportsComplete.mockResolvedValue(false); + const raw = JSON.stringify([ + { + type: 'Application', + AXLabel: 'MetaMask', + frame: { x: 0, y: 0, width: 402, height: 874 }, + children: [ + { + type: 'Button', + AXUniqueId: 'log-in-button', + frame: { x: 24, y: 396, width: 354, height: 48 }, + }, + ], + }, + ]); + mockExecStrict.mockResolvedValue(raw); + + const result = await backend.snapshot(); + + expect(mockExecStrict).toHaveBeenCalledExactlyOnceWith( + '/usr/local/bin/idb', + describeArgs(extra), + connectionOptions, + ); + expect(result).toStrictEqual({ + platform: 'ios', + hierarchy: parseIdbHierarchy(raw), + raw, + timestamp: expect.any(Number), + }); + }, + ); + describe('ax supplement for axbridge', () => { const node = ( id: string | null, diff --git a/src/backends/idb-backend.ts b/src/backends/idb-backend.ts index f0dfd38..8a7a3a2 100644 --- a/src/backends/idb-backend.ts +++ b/src/backends/idb-backend.ts @@ -39,6 +39,7 @@ import { import { chooseAxApi, idbSupportsApiSelection, + idbSupportsCompleteDescribe, idbSupportsNestedDescribe, resolveIdbPath, } from '../utils/platform.js'; @@ -113,6 +114,13 @@ export class IdbBackend implements DeviceBackend { #idbSupportsNested = false; + /** + * Whether to request `describe-all --format complete`. Set from the client's + * help text; cleared when the companion answers such a request in an older + * format (it predates format selection). + */ + #idbSupportsComplete = false; + #recordingProcess: ChildProcess | null = null; #recordingPath: string | null = null; @@ -196,9 +204,14 @@ export class IdbBackend implements DeviceBackend { try { if (!this.#probed) { this.#idbPath = await resolveIdbPath(); - [this.#idbSupportsApi, this.#idbSupportsNested] = await Promise.all([ + [ + this.#idbSupportsApi, + this.#idbSupportsNested, + this.#idbSupportsComplete, + ] = await Promise.all([ idbSupportsApiSelection(this.#idbPath), idbSupportsNestedDescribe(this.#idbPath), + idbSupportsCompleteDescribe(this.#idbPath), ]); this.#probed = true; } @@ -425,6 +438,10 @@ export class IdbBackend implements DeviceBackend { * its identified elements missing from the `axbridge` tree are added to it. * `raw` stays the `axbridge` output. * + * When the idb client supports it, the read uses `--format complete`, which + * also reports whether the companion cut the tree at its size bound; a cut + * tree adds an `ax-tree-truncated` warning (see `SnapshotResult.warnings`). + * * @returns The snapshot. */ async snapshot(): Promise { @@ -437,8 +454,8 @@ export class IdbBackend implements DeviceBackend { env: this.#connection.env, }).catch(() => undefined) : undefined; - const { raw, api } = await this.#describeAll(apis); - let hierarchy = parseIdbHierarchy(raw); + const { raw, api, read } = await this.#describeAll(apis); + let { hierarchy } = read; const extra = await supplement; if (api === 'axbridge' && extra !== undefined) { hierarchy = addMissingIdentifiedElements( @@ -447,11 +464,15 @@ export class IdbBackend implements DeviceBackend { ); } this.#lastHierarchy = hierarchy; + const warnings = read.truncated + ? [truncationWarning(read.backend, read.hierarchy)] + : undefined; return { platform: 'ios', hierarchy, raw, timestamp: Date.now(), + ...(warnings && { warnings }), }; } @@ -466,35 +487,63 @@ export class IdbBackend implements DeviceBackend { if (api !== null) { args.push('--api', api); } - if (this.#idbSupportsNested) { + // idb rejects --nested together with --format. + if (this.#idbSupportsComplete) { + args.push('--format', 'complete'); + } else if (this.#idbSupportsNested) { args.push('--nested'); } return args; } + /** + * Run `idb ui describe-all` for one accessibility backend and parse it. + * When `--format complete` was requested but the companion predates format + * selection (it answers with a flat tree), stop requesting it and read + * again in the format used before, so the tree keeps its nesting. + * + * @param api - The `--api` value, or null to omit it. + * @returns The raw output and the parsed read. + */ + async #describeAllOnce( + api: 'ax' | 'axbridge' | null, + ): Promise<{ raw: string; read: IdbDescribeAll }> { + const requestedComplete = this.#idbSupportsComplete; + const raw = await this.#execStrict( + this.#idbPath, + this.#describeAllArgs(api), + ); + const read = parseIdbDescribeAll(raw); + if (!requestedComplete || read.format !== 'legacy') { + return { raw, read }; + } + this.#idbSupportsComplete = false; + const legacy = await this.#execStrict( + this.#idbPath, + this.#describeAllArgs(api), + ); + return { raw: legacy, read: parseIdbDescribeAll(legacy) }; + } + /** * Run `idb ui describe-all`, trying the version-appropriate accessibility * backend first and falling back to the others if it errors. This keeps * snapshots working across iOS 17-26 regardless of the user's idb client. * * @param apis - The `--api` values to try, in order. - * @returns The raw JSON hierarchy from the first backend that succeeds, and - * that backend. + * @returns The raw output of the first backend that succeeds, its parsed + * read, and that backend. * @throws When every attempted backend fails. */ - async #describeAll( - apis: ('ax' | 'axbridge' | null)[], - ): Promise<{ raw: string; api: 'ax' | 'axbridge' | null }> { + async #describeAll(apis: ('ax' | 'axbridge' | null)[]): Promise<{ + raw: string; + read: IdbDescribeAll; + api: 'ax' | 'axbridge' | null; + }> { let lastError: unknown; for (const api of apis) { try { - return { - raw: await this.#execStrict( - this.#idbPath, - this.#describeAllArgs(api), - ), - api, - }; + return { ...(await this.#describeAllOnce(api)), api }; } catch (error) { if (error instanceof IdbUnavailableError) { // Already reconnected and retried; another --api will not help. @@ -1266,33 +1315,133 @@ function collectTextsFromChildren( } } +/** One parsed `idb ui describe-all` read. */ +type IdbDescribeAll = { + hierarchy: UIElement[]; + /** + * `complete`: the `--format complete` document; `legacy`: a flat or nested + * tree; `invalid`: not JSON, or JSON that is neither an array nor an object. + */ + format: 'complete' | 'legacy' | 'invalid'; + /** `--format complete` only: the companion cut the tree at its bound. */ + truncated: boolean; + /** + * `--format complete` only: the backend that served the read, when the + * document names one. + */ + backend?: string; +}; + /** - * Parse flat or nested idb output. Legacy object roots expose their children - * at the top level; array roots keep their tree shape. + * Parse any `idb ui describe-all` output: the `--format complete` document + * (`{ backend, elements, truncated, screen, … }`, whose `elements` is the + * nested tree), or a flat or nested tree. Legacy object roots expose their + * children at the top level; array roots keep their tree shape. * * @param raw - The raw stdout of `idb ui describe-all`. - * @returns The hierarchy, or a `raw` element when parsing fails. + * @returns The read; its hierarchy is a `raw` element when parsing fails. */ -export function parseIdbHierarchy(raw: string): UIElement[] { - try { - const parsed = JSON.parse(raw); - if (Array.isArray(parsed)) { - return parsed.map(mapIdbElement); - } - if (Array.isArray(parsed.children) && parsed.children.length > 0) { - return parsed.children.map(mapIdbElement); - } - return [mapIdbElement(parsed)]; - } catch { - return [ +export function parseIdbDescribeAll(raw: string): IdbDescribeAll { + const invalid: IdbDescribeAll = { + hierarchy: [ { type: 'raw', label: raw.slice(0, 200), frame: { x: 0, y: 0, width: 0, height: 0 }, enabled: true, }, - ]; + ], + format: 'invalid', + truncated: false, + }; + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return invalid; + } + if (Array.isArray(parsed)) { + return { + hierarchy: parsed.map(mapIdbElement), + format: 'legacy', + truncated: false, + }; + } + if (typeof parsed !== 'object' || parsed === null) { + return invalid; + } + const root = parsed as Record; + // Same test as idb's own (`_warn_if_complete_downgraded`): only the + // complete document has a `backend` key. + if ('backend' in root) { + return { + hierarchy: Array.isArray(root.elements) + ? root.elements.map(mapIdbElement) + : [], + format: 'complete', + truncated: root.truncated === true, + ...(typeof root.backend === 'string' && + root.backend !== '' && { backend: root.backend }), + }; + } + const hierarchy = + Array.isArray(root.children) && root.children.length > 0 + ? root.children.map(mapIdbElement) + : [mapIdbElement(root)]; + return { hierarchy, format: 'legacy', truncated: false }; +} + +/** + * Parse any `idb ui describe-all` output into a hierarchy (see + * `parseIdbDescribeAll`). + * + * @param raw - The raw stdout of `idb ui describe-all`. + * @returns The hierarchy, or a `raw` element when parsing fails. + */ +export function parseIdbHierarchy(raw: string): UIElement[] { + return parseIdbDescribeAll(raw).hierarchy; +} + +/** + * The `ax-tree-truncated` warning of a cut read (format documented on + * `SnapshotResult.warnings`). + * + * @param backend - The backend that served the read, when reported. + * @param hierarchy - The tree the read returned. + * @returns The warning. + */ +function truncationWarning( + backend: string | undefined, + hierarchy: UIElement[], +): string { + const { depth, nodes } = treeSize(hierarchy); + const details = [ + ...(backend ? [`backend=${backend}`] : []), + `depth=${depth}`, + `nodes=${nodes}`, + ]; + return `ax-tree-truncated(${details.join(',')})`; +} + +/** + * The deepest level (top-level elements are level 1) and the element count of + * a tree. + * + * @param elements - The tree. + * @returns Its depth and node count. + */ +function treeSize(elements: UIElement[]): { depth: number; nodes: number } { + let depth = 0; + let nodes = 0; + const stack = elements.map((element) => ({ element, level: 1 })); + for (let next = stack.pop(); next; next = stack.pop()) { + nodes += 1; + depth = Math.max(depth, next.level); + for (const child of next.element.children ?? []) { + stack.push({ element: child, level: next.level + 1 }); + } } + return { depth, nodes }; } /** diff --git a/src/backends/types.ts b/src/backends/types.ts index d1d7c49..2b79ff0 100644 --- a/src/backends/types.ts +++ b/src/backends/types.ts @@ -37,6 +37,20 @@ export type SnapshotResult = { * ADB capture time in ms, including retries and fallbacks, excluding queue wait. */ captureMs?: number; + /** + * Problems with the capture that the caller should know about. Absent when + * there are none. Each entry starts with a stable code; details, when + * present, follow in parentheses as comma-separated `key=value` pairs. + * + * - `ax-tree-truncated(backend=,depth=,nodes=)` (iOS): the + * accessibility read stopped at the idb companion's size bound, so + * elements on screen can be missing from `hierarchy`. `backend` is the + * backend that served the read (as idb names it; left out when idb names + * none), `depth` the deepest level and `nodes` the number of elements of + * the tree that came back. Only reported when the idb client supports + * `describe-all --format complete`. + */ + warnings?: string[]; }; export type TapResult = { diff --git a/src/tools/snapshot.test.ts b/src/tools/snapshot.test.ts new file mode 100644 index 0000000..e9181de --- /dev/null +++ b/src/tools/snapshot.test.ts @@ -0,0 +1,89 @@ +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { describe, it, expect, vi } from 'vitest'; + +import { registerSnapshotTool } from './snapshot.js'; +import type { DeviceBackend, SnapshotResult } from '../backends/types.js'; + +type ToolHandler = () => Promise<{ + content: { type: string; text: string }[]; + isError?: boolean; +}>; + +const snapshotResult: SnapshotResult = { + platform: 'ios', + hierarchy: [ + { + type: 'Button', + label: 'Unlock', + identifier: 'log-in-button', + frame: { x: 24, y: 396, width: 354, height: 48 }, + enabled: true, + }, + ], + raw: '[]', + timestamp: Date.UTC(2026, 10, 16), +}; + +async function runTool( + snapshot: DeviceBackend['snapshot'], +): ReturnType { + const server = { registerTool: vi.fn() } as unknown as McpServer; + registerSnapshotTool(server, { snapshot } as unknown as DeviceBackend); + const { calls } = (server.registerTool as ReturnType).mock; + expect(calls[0][0]).toBe('device_snapshot'); + return (calls[0][2] as ToolHandler)(); +} + +describe('registerSnapshotTool', () => { + it('prints the platform, timestamp and elements, without a warnings line', async () => { + const result = await runTool(vi.fn().mockResolvedValue(snapshotResult)); + + expect(result.content[0].text).toBe( + [ + 'Platform: ios', + 'Timestamp: 2026-11-16T00:00:00.000Z', + 'Elements:', + '[Button] label="Unlock" id="log-in-button" (24,396 354x48)', + ].join('\n'), + ); + }); + + it.each([[[]], [undefined]])( + 'prints no warnings line for warnings %j', + async (warnings) => { + const result = await runTool( + vi.fn().mockResolvedValue({ ...snapshotResult, warnings }), + ); + + expect(result.content[0].text).not.toContain('Warnings:'); + }, + ); + + it('prints the warnings before the elements', async () => { + const result = await runTool( + vi.fn().mockResolvedValue({ + ...snapshotResult, + warnings: [ + 'ax-tree-truncated(backend=axbridge-exclusive,depth=51,nodes=166)', + 'other-warning', + ], + }), + ); + + expect(result.content[0].text.split('\n').slice(0, 4)).toStrictEqual([ + 'Platform: ios', + 'Timestamp: 2026-11-16T00:00:00.000Z', + 'Warnings: ax-tree-truncated(backend=axbridge-exclusive,depth=51,nodes=166); other-warning', + 'Elements:', + ]); + }); + + it('returns an error result when the snapshot fails', async () => { + const result = await runTool( + vi.fn().mockRejectedValue(new Error('describe-all failed')), + ); + + expect(result.isError).toBe(true); + expect(result.content[0].text).toContain('describe-all failed'); + }); +}); diff --git a/src/tools/snapshot.ts b/src/tools/snapshot.ts index 1fc78c0..d440b40 100644 --- a/src/tools/snapshot.ts +++ b/src/tools/snapshot.ts @@ -30,6 +30,9 @@ export function registerSnapshotTool( text: [ `Platform: ${result.platform}`, `Timestamp: ${new Date(result.timestamp).toISOString()}`, + ...(result.warnings?.length + ? [`Warnings: ${result.warnings.join('; ')}`] + : []), `Elements:`, formatted, ].join('\n'), diff --git a/src/utils/platform.test.ts b/src/utils/platform.test.ts index c872eb0..07bc25e 100644 --- a/src/utils/platform.test.ts +++ b/src/utils/platform.test.ts @@ -6,6 +6,7 @@ import { detectAllDevices, detectPlatform, idbSupportsApiSelection, + idbSupportsCompleteDescribe, idbSupportsNestedDescribe, resolveIdbPath, MultipleDevicesError, @@ -850,6 +851,62 @@ describe('idbSupportsNestedDescribe', () => { }); }); +describe('idbSupportsCompleteDescribe', () => { + beforeEach(() => { + vi.resetAllMocks(); + }); + + it.each([ + { + name: 'unified client', + stdout: [ + 'usage: idb ui describe-all [-h] [--udid UDID] [--nested]', + ' [--format {default,nested,complete}]', + ' --format {default,nested,complete}', + ].join('\n'), + exitCode: 0, + supported: true, + }, + { + name: 'no complete value', + stdout: '[--format {default,nested}] [--nested]', + exitCode: 0, + supported: false, + }, + { + name: 'complete outside --format', + stdout: '[--nested]\n a complete description of the screen', + exitCode: 0, + supported: false, + }, + { + name: 'no --format', + stdout: 'usage: idb ui describe-all [--udid UDID] [--nested]', + exitCode: 0, + supported: false, + }, + { + name: 'non-zero exit', + stdout: '[--format {default,nested,complete}]', + exitCode: 2, + supported: false, + }, + ])( + 'detects --format complete support: $name', + async ({ stdout, exitCode, supported }) => { + mockExec.mockResolvedValue({ stdout, stderr: '', exitCode }); + + expect(await idbSupportsCompleteDescribe('idb')).toBe(supported); + }, + ); + + it('is false when the help probe fails', async () => { + mockExec.mockRejectedValue(new Error('ENOENT')); + + expect(await idbSupportsCompleteDescribe('/bad/idb')).toBe(false); + }); +}); + describe('chooseAxApi', () => { it('returns null when the CLI does not support --api', () => { expect(chooseAxApi('26.1', false)).toBeNull(); diff --git a/src/utils/platform.ts b/src/utils/platform.ts index 221d0ea..2923ed2 100644 --- a/src/utils/platform.ts +++ b/src/utils/platform.ts @@ -218,6 +218,22 @@ export async function idbSupportsNestedDescribe( return help === null ? false : /(?:^|[\s[])--nested(?=[\s\]]|$)/mu.test(help); } +/** + * Probe support for the consolidated document + * (`describe-all --format complete`), which also reports truncation. + * + * @param idbPath - The `idb` executable to probe. + * @returns True when `--format` lists `complete`. + */ +export async function idbSupportsCompleteDescribe( + idbPath: string, +): Promise { + const help = await readDescribeAllHelp(idbPath); + return help === null + ? false + : /(?:^|[\s[])--format \{[^}]*\bcomplete\b[^}]*\}/mu.test(help); +} + const pendingHelpReads = new Map>(); /**