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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,12 @@ 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=<name>,depth=<n>,nodes=<n>)`: 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.
On the IDB backend, `SnapshotResult` reports `warnings` when the read is incomplete. `device_snapshot` prints them on a `Warnings:` line. `warnings` is absent when there are none.

- `ax-tree-truncated(backend=<name>,depth=<n>,nodes=<n>)`: 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. Only reported when the idb client supports `describe-all --format complete`.
- `ax-tree-fallback(from=<api>,to=<api>,reason=<not-responding|error>)`: the preferred `--api` backend failed and the other one served the read, so the tree is that backend's view, not the preferred full-hierarchy read. `from` is the preferred backend (`axbridge` on iOS 18+, `ax` before), `to` the backend that served the read, and `reason` is `not-responding` when idb reports that the app did not respond to an accessibility request, otherwise `error`. In practice `from=axbridge,to=ax` means the full-hierarchy read failed (iOS rejects the XCTest snapshot when the tree is too deep) and `hierarchy` is the flat accessibility read: parent/child relationships are lost and elements can be missing. Treat such a tree as partial: match elements by test ID or label where present, and do not conclude that an element is absent from the screen because it is missing from the tree. A fallback read can also be truncated, and then both warnings are present.

With an idb client that supports `--format complete`, `raw` is the `--format complete` document (`{ backend, truncated, elements, … }`) instead of the tree array.

#### Android snapshot on continuously-redrawing screens

Expand Down
81 changes: 79 additions & 2 deletions src/backends/idb-backend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2175,7 +2175,7 @@ describe('IdbBackend.snapshot accessibility backend selection', () => {
mockSupportsApi.mockResolvedValue(false);
mockExecStrict.mockResolvedValue(JSON.stringify([]));

await backend.snapshot();
const result = await backend.snapshot();

expect(mockExecStrict).toHaveBeenCalledWith(
'/usr/local/bin/idb',
Expand All @@ -2187,6 +2187,7 @@ describe('IdbBackend.snapshot accessibility backend selection', () => {
expect.arrayContaining(['--api']),
connectionOptions,
);
expect(result).not.toHaveProperty('warnings');
});

it('uses the version-chosen --api backend when supported', async () => {
Expand All @@ -2200,13 +2201,14 @@ describe('IdbBackend.snapshot accessibility backend selection', () => {
return JSON.stringify([]);
});

await backend.snapshot();
const result = await backend.snapshot();

expect(mockExecStrict).toHaveBeenCalledWith(
'/usr/local/bin/idb',
describeArgs(['--api', 'axbridge']),
connectionOptions,
);
expect(result).not.toHaveProperty('warnings');
});

it('falls back to the complementary backend when the preferred errors', async () => {
Expand Down Expand Up @@ -2236,6 +2238,72 @@ describe('IdbBackend.snapshot accessibility backend selection', () => {
);
});

it('warns not-responding when axbridge does not respond and ax serves the 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(
'Command failed: idb ui describe-all --api axbridge\nExit code: 1\n' +
'stderr: The application did not respond to an accessibility request before it timed out',
);
}
return JSON.stringify([{ type: 'Button', AXUniqueId: 'log-in-button' }]);
});

const result = await backend.snapshot();

expect(result.warnings).toStrictEqual([
'ax-tree-fallback(from=axbridge,to=ax,reason=not-responding)',
]);
expect(
findElement(result.hierarchy, { identifier: 'log-in-button' }),
).not.toBeNull();
});

it('warns with reason=error when axbridge fails for another reason', 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 JSON.stringify([]);
});

const result = await backend.snapshot();

expect(result.warnings).toStrictEqual([
'ax-tree-fallback(from=axbridge,to=ax,reason=error)',
]);
});

it('warns when ax is preferred and axbridge serves the read', async () => {
mockSupportsApi.mockResolvedValue(true);
mockChooseAxApi.mockReturnValue('ax');
mockExecStrict.mockImplementation(async (_cmd, args) => {
if (args?.includes('describe') && args?.includes('--json')) {
return JSON.stringify({ os_version: '17.4', name: 'iPhone' });
}
if (args?.includes('axbridge')) {
return JSON.stringify([]);
}
throw new Error('ax backend unavailable');
});

const result = await backend.snapshot();

expect(result.warnings).toStrictEqual([
'ax-tree-fallback(from=ax,to=axbridge,reason=error)',
]);
});

it('throws when every backend fails', async () => {
mockSupportsApi.mockResolvedValue(true);
mockChooseAxApi.mockReturnValue('axbridge');
Expand Down Expand Up @@ -2543,6 +2611,7 @@ describe('IdbBackend.snapshot accessibility backend selection', () => {
const result = await backend.snapshot();

expect(result.warnings).toStrictEqual([
'ax-tree-fallback(from=axbridge,to=ax,reason=error)',
'ax-tree-truncated(backend=ax,depth=3,nodes=3)',
]);
expect(result.hierarchy).toStrictEqual(
Expand Down Expand Up @@ -2740,6 +2809,14 @@ describe('IdbBackend.snapshot accessibility backend selection', () => {
expect(ids).not.toContain('no id');
});

it('adds no fallback warning when axbridge serves the read', async () => {
mockApis(async () => JSON.stringify(axTree));

const result = await backend.snapshot();

expect(result).not.toHaveProperty('warnings');
});

it('returns the axbridge tree unchanged when the ax read fails', async () => {
mockApis(async () => {
throw new Error('ax failed');
Expand Down
56 changes: 47 additions & 9 deletions src/backends/idb-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,9 @@ export class IdbBackend implements DeviceBackend {
*
* 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`).
* tree adds an `ax-tree-truncated` warning. A read served by a backend other
* than the preferred one adds an `ax-tree-fallback` warning (both are
* documented on `SnapshotResult.warnings`).
*
* @returns The snapshot.
*/
Expand All @@ -454,7 +456,7 @@ export class IdbBackend implements DeviceBackend {
env: this.#connection.env,
}).catch(() => undefined)
: undefined;
const { raw, api, read } = await this.#describeAll(apis);
const { raw, api, read, preferredError } = await this.#describeAll(apis);
let { hierarchy } = read;
const extra = await supplement;
if (api === 'axbridge' && extra !== undefined) {
Expand All @@ -464,15 +466,19 @@ export class IdbBackend implements DeviceBackend {
);
}
this.#lastHierarchy = hierarchy;
const warnings = read.truncated
? [truncationWarning(read.backend, read.hierarchy)]
: undefined;
const warnings: string[] = [];
if (apis[0] !== null && api !== null && api !== apis[0]) {
warnings.push(fallbackWarning(apis[0], api, preferredError));
}
if (read.truncated) {
warnings.push(truncationWarning(read.backend, read.hierarchy));
}
return {
platform: 'ios',
hierarchy,
raw,
timestamp: Date.now(),
...(warnings && { warnings }),
...(warnings.length > 0 && { warnings }),
};
}

Expand Down Expand Up @@ -532,23 +538,33 @@ export class IdbBackend implements DeviceBackend {
*
* @param apis - The `--api` values to try, in order.
* @returns The raw output of the first backend that succeeds, its parsed
* read, and that backend.
* read, that backend, and the preferred backend's error when a later one
* served the read.
* @throws When every attempted backend fails.
*/
async #describeAll(apis: ('ax' | 'axbridge' | null)[]): Promise<{
raw: string;
read: IdbDescribeAll;
api: 'ax' | 'axbridge' | null;
preferredError?: unknown;
}> {
let preferredError: unknown;
let lastError: unknown;
for (const api of apis) {
for (const [index, api] of apis.entries()) {
try {
return { ...(await this.#describeAllOnce(api)), api };
return {
...(await this.#describeAllOnce(api)),
api,
...(index > 0 && { preferredError }),
};
} catch (error) {
if (error instanceof IdbUnavailableError) {
// Already reconnected and retried; another --api will not help.
throw error;
}
if (index === 0) {
preferredError = error;
}
lastError = error;
}
}
Expand Down Expand Up @@ -1430,6 +1446,28 @@ function truncationWarning(
return `ax-tree-truncated(${details.join(',')})`;
}

/** The idb error text when the app does not answer an accessibility request. */
const NOT_RESPONDING = 'did not respond to an accessibility request';

/**
* The `ax-tree-fallback` warning of a read served by a backend other than the
* preferred one (format documented on `SnapshotResult.warnings`).
*
* @param from - The preferred `--api`.
* @param to - The `--api` that served the read.
* @param error - The preferred backend's error.
* @returns The warning.
*/
function fallbackWarning(
from: 'ax' | 'axbridge',
to: 'ax' | 'axbridge',
error: unknown,
): string {
const text = error instanceof Error ? error.message : String(error);
const reason = text.includes(NOT_RESPONDING) ? 'not-responding' : 'error';
return `ax-tree-fallback(from=${from},to=${to},reason=${reason})`;
}

/**
* The deepest level (top-level elements are level 1) and the element count of
* a tree.
Expand Down
7 changes: 7 additions & 0 deletions src/backends/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ export type SnapshotResult = {
* 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`.
* - `ax-tree-fallback(from=<api>,to=<api>,reason=<not-responding|error>)`
* (iOS): the preferred `--api` backend failed and another one served the
* read, so `hierarchy` is that backend's view, not the preferred full
* hierarchy. `from` is the preferred backend (`axbridge` on iOS 18+,
* `ax` before), `to` the one that served the read, and `reason` is
* `not-responding` when the preferred error says the app did not respond
* to an accessibility request, otherwise `error`.
*/
warnings?: string[];
};
Expand Down
4 changes: 2 additions & 2 deletions src/tools/snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,16 @@ describe('registerSnapshotTool', () => {
vi.fn().mockResolvedValue({
...snapshotResult,
warnings: [
'ax-tree-fallback(from=axbridge,to=ax,reason=not-responding)',
'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',
'Warnings: ax-tree-fallback(from=axbridge,to=ax,reason=not-responding); ax-tree-truncated(backend=axbridge-exclusive,depth=51,nodes=166)',
'Elements:',
]);
});
Expand Down
Loading