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
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,8 @@ The settle does not wait for a screen that is slow to appear. On Android, the fi

On mobile, each observation, `describe_screen`, `list_testids` and `accessibility_snapshot` takes one device snapshot (plus the settle retries above). The consumer's `DeviceBackend` takes the snapshot. With the `@metamask/device-mcp` ADB backend (0.6.0 or later), Android snapshots use a signed test-only helper APK by default (`helper-first`). The backend installs it on the device the first time, so the first snapshot takes longer. To use only `uiautomator dump`, set `DEVICE_MCP_ADB_SNAPSHOT=dump` or the backend's `adb.snapshotMode` option. See the device-mcp README. The viewport for `visible` comes from the snapshot's root frames; the device window size is read at most once per session (and not refreshed after a rotation), only when a snapshot has no root frame. Elements that are not part of the app are removed from the tree, the refs, the test IDs and `generate_locators`: on Android, the system status bar and navigation bar windows (a full-width or full-height bar window whose ids are all `com.android.systemui:id/*`; other System UI windows such as the biometric prompt stay); on both platforms, the Expo DevLauncher "Tools" button of development builds (iOS `gearshape.fill` and its "Tools" text). Pass `{ excludeDevOverlay: false }` as the third `MobilePlatformDriver` argument to keep the DevLauncher button. Taps and waits inside `@metamask/device-mcp` still search the whole snapshot.

The `warnings` of the device snapshot (`SnapshotResult.warnings` of `@metamask/device-mcp`) are returned as a top-level `warnings` array in `describe_screen`, `accessibility_snapshot` and observations (also diff observations). There is no `warnings` key when the snapshot has none. Each entry is the device-mcp warning (a code and its details), followed for a known code by what to do. On iOS, `ax-tree-truncated(backend=<name>,depth=<n>,nodes=<n>)` means the idb accessibility read stopped at its size bound, so elements on screen can be missing from `a11y`, `testIds` and the element search of the target tools. `ax-tree-fallback(from=<api>,to=<api>,reason=<reason>)` means the preferred read failed and the other backend served the tree; with `from=axbridge,to=ax` (the full read fails on a very deep screen) the tree is the flat read, where labelled controls usually remain but containers, screen markers and the text parts of rows are missing. For `ax-tree-truncated` the added text tells the agent to look with `screenshot` and tap with `tap_coordinates`; for `ax-tree-fallback` it also says that `wait_for` on a missing container can time out, and to confirm the screen with a control that is present.

The mobile accessibility tree (`describe_screen`, `accessibility_snapshot`, observations) is a flat list in pre-order with no `path` (on the browser, `path` holds the `role:name` of the ancestor dialogs and headings; on mobile the ancestors are native view classes). Layout-only elements are left out (`pruneLayoutOnly` in `src/platform/mobile-hierarchy.ts`): an element with no label, no value, no identifier, and a type that is not a control or a progress indicator. Its kept descendants take its place, in order. Controls are iOS `Button`, `Link`, `TextField`, `SecureTextField`, `SearchField`, `TextView`, `TextArea`, `Switch`, `Toggle`, `Slider`, `Stepper`, `Picker`, `Cell`, `Tab`, `MenuItem` and similar AX types (exact match, without the `XCUIElementType` prefix), and Android classes ending in `Button`, `EditText`, `CheckBox`, `CheckedTextView`, `Switch`, `SeekBar`, `Spinner`, `RatingBar` and similar. The device snapshot has no `clickable` flag, so a layout-only plain React Native view (`RCTViewComponentView` on iOS, `android.view.ViewGroup` on Android) that has no kept children and is at least 24×24 (iOS points, Android pixels) stays as an unlabelled tap target, for example the iOS wallet home action buttons. Node `bounds` are `{ x, y, width, height }`, in that key order. Node refs number the kept nodes only, and ambiguity is computed over them. A node with a testId, label or value that no other kept node shares resolves by that identity: the target tools look it up again at action time. Two other kinds of node get a bounds ref (their snapshot frame and identity) instead: unnamed nodes (unlabelled tap targets, progress indicators, unnamed controls), and `ambiguous` nodes (another kept node has the same testId, or the same label or value and type, so a lookup could find the other one). Only `click` takes a bounds ref: it takes a new snapshot, finds the element with the same type and identity at the same frame (1 pt/px tolerance), and taps it through the same viewport check and hit test as any other mobile tap; the result's `target` ends in ` (bounds)`. When no such element is there any more (the screen changed), it fails with `MM_TARGET_NOT_FOUND` and taps nothing. `type`, `wait_for`, `get_text`, `scroll_to_element` and `long_press` (also as `run_steps` steps) refuse a bounds ref with `MM_TARGET_NOT_FOUND` before any device call; the error's `hint` names `click` and `tap_coordinates` (unnamed) or a unique test ID (ambiguous). On real MetaMask screens: iOS wallet home 177 → 67 nodes (183 kB with `path` → 10 kB), Android wallet home 625 → 242 nodes (649 kB → 35 kB), Android login 47 → 15 nodes. `list_testids` and `generate_locators` are not affected, and `describe_screen` still returns the full `testIds` list next to the tree.

### Session Metadata
Expand Down Expand Up @@ -564,7 +566,7 @@ All responses follow a consistent shape:

```typescript
// Success
{ ok: true, result: T, observations?: { testIds, a11y, animationsSettled? } }
{ ok: true, result: T, observations?: { testIds, a11y, animationsSettled?, warnings? } }

// Error
{ ok: false, error: { code: string, message: string } }
Expand All @@ -590,7 +592,7 @@ When a call waited for animations, its observation has `animationsSettled`: `tru

For `run_steps`, the top-level `observe` sets the level of the one observation collected after the batch. Without it, the `observe` in the last executed step's `args` is used; per-step `observe` on other steps is ignored. `includeObservations` was removed.

Observations contain `testIds`, `a11y` and, when the call waited for animations, `animationsSettled`. They do not include app state; call `get_state` for that.
Observations contain `testIds`, `a11y`, `animationsSettled` when the call waited for animations, and `warnings` when the mobile device read had a problem (see below). They do not include app state; call `get_state` for that.

A call that times out is cancelled: its signal is aborted, it stops at its next step, it collects no observation, and its refs are dropped. `click` and `type` check the signal again after they wait for the target, so a call that timed out during that wait does not click or type. An action that already started is not cancelled. On the browser, the action includes Playwright's own checks inside `locator.click` / `locator.fill` (stable, enabled, not covered), which can wait up to the rest of the call's `timeoutMs`. On mobile, `@metamask/device-mcp` takes no signal: its element wait, tap and `typeText` run until they end, and the driver checks the signal between them.

Expand Down
10 changes: 9 additions & 1 deletion SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,18 @@ mm get-state --observe full # a read that also returns an observation
- `animationsSettled: true` and the screen you expect: go on.
- `animationsSettled: false`, or you are waiting for something that loads (a new screen, a list, a toast): `mm wait-for` the element you expect, e.g. `mm wait-for --testid activity-list` or `mm wait-for --selector "text=Copied"`. It returns as soon as the element is visible, so it is both faster and more reliable than a fixed sleep.

Observations contain `testIds`, `a11y` and (browser, after a mutating or batch call) `animationsSettled` — no app `state`. Call `mm get-state` for state.
Observations contain `testIds`, `a11y`, (browser, after a mutating or batch call) `animationsSettled` and (mobile, see below) `warnings` — no app `state`. Call `mm get-state` for state.

On mobile, each observation and `describe-screen` comes from one device snapshot. The Android system status bar and navigation bar and the Expo DevLauncher "Tools" button (iOS `gearshape.fill`) are not part of the app and are removed from `testIds` and `a11y`. Other system windows, such as the biometric prompt (`com.android.systemui:id/biometric_*`), are kept.

**Mobile `warnings`.** When the device read has a problem, `describe-screen`, `accessibility-snapshot` and observations carry a top-level `warnings` array; without one there is no `warnings` key. Each entry is a code, its details, then what to do. On iOS there are two codes: `ax-tree-truncated` (the read stopped at the device's size limit) and `ax-tree-fallback` (the full read failed, for example on a very deep screen, and a flat read served the tree). Example:

```json
"warnings": ["ax-tree-truncated(backend=axbridge-exclusive,depth=51,nodes=166): the tree hit the device read limit, so elements on screen can be missing from a11y and testIds. See them with `mm screenshot`; tap one with `mm tap-coordinates <x> <y>` (same units as `bounds`)."]
```

With either code, an element you can see can be missing from `a11y` and `testIds`, and a `--testid` or ref target for it can fail with `MM_TARGET_NOT_FOUND` (the target commands search the same device read). Do not conclude that the element is not on screen: run `mm screenshot`, find it, and tap it with `mm tap-coordinates <x> <y>`. After `ax-tree-fallback`, labelled controls usually remain, but containers and screen markers (for example `wallet-screen`) are often missing, so `mm wait-for --testid` on them can time out on the right screen: confirm the screen with a control that is present instead.

On Android, a navigating tap can be observed while the new screen is still mounting: the screen-level test IDs are already there but much of the tree is not (P1-32 saw 51 of 360 nodes). The settle retries a screen that is still tearing down (the old screen's test IDs with most of its nodes gone), not one that is still filling in. When an observation looks partial, run `mm describe-screen` before acting on it.

**Android: the first visit to a tab can return the old screen.** A screen that mounts for the first time in the session (for example the Explore or Money tab after an app restart) can take about 2 s to appear (measured on Explore, Android emulator, dev build). The tap works, but the click's observation can still show the old screen, whole or partly removed, and `mm describe-screen` right after the click shows it too. `screenChanged` does not help here: the tapped button's press feedback alone can make it `true`. So after a tap that should open a new screen:
Expand Down
89 changes: 83 additions & 6 deletions src/platform/mobile-platform-driver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1147,29 +1147,106 @@ describe('MobilePlatformDriver', () => {
expect(refMap.get('e2')).toBe('label:Email|type:TextField');
});

it('reads a snapshot that has device-mcp warnings and does not report them', async () => {
it('adds what to do to a truncated-tree warning, in the tree and the capture', async () => {
const backend = createMockBackend({
snapshot: vi.fn().mockResolvedValue({
platform: 'ios',
hierarchy: [makeElement({ label: 'Submit', identifier: 'submit' })],
raw: '[]',
timestamp: Date.now(),
warnings: ['ax-tree-truncated(backend=axbridge,depth=60,nodes=900)'],
warnings: [
'ax-tree-truncated(backend=axbridge-exclusive,depth=51,nodes=166)',
'future-code(x=1)',
],
}),
});
const driver = new MobilePlatformDriver(backend);
const expected = [
'ax-tree-truncated(backend=axbridge-exclusive,depth=51,nodes=166): the tree hit the device read limit, so elements on screen can be missing from a11y and testIds. See them with `mm screenshot`; tap one with `mm tap-coordinates <x> <y>` (same units as `bounds`).',
'future-code(x=1)',
];

const capture = await driver.captureScreen();
const tree = await driver.getAccessibilityTree();

expect(capture.warnings).toStrictEqual(expected);
expect(capture.nodes.map(({ testId }) => testId)).toStrictEqual([
'submit',
]);
expect(tree.warnings).toStrictEqual(expected);
});

it('adds what to do to a flat-fallback warning', async () => {
const backend = createMockBackend({
snapshot: vi.fn().mockResolvedValue({
platform: 'ios',
hierarchy: [makeElement({ label: 'Send', identifier: 'send' })],
raw: '[]',
timestamp: Date.now(),
warnings: [
'ax-tree-fallback(from=axbridge,to=ax,reason=not-responding)',
],
}),
});
const driver = new MobilePlatformDriver(backend);

const { warnings } = await driver.getAccessibilityTree();

expect(warnings).toStrictEqual([
'ax-tree-fallback(from=axbridge,to=ax,reason=not-responding): the full read failed, so containers, screen markers and row texts can be missing and `wait-for` on them can time out. Confirm the screen with a control that is present or `mm screenshot`; tap a missing element with `mm tap-coordinates <x> <y>` (same units as `bounds`).',
]);
});

it('adds what to do to each warning when a fallback read is also truncated', async () => {
const backend = createMockBackend({
snapshot: vi.fn().mockResolvedValue({
platform: 'ios',
hierarchy: [makeElement({ label: 'Send', identifier: 'send' })],
raw: '[]',
timestamp: Date.now(),
warnings: [
'ax-tree-fallback(from=axbridge,to=ax,reason=error)',
'ax-tree-truncated(backend=ax,depth=51,nodes=166)',
],
}),
});
const driver = new MobilePlatformDriver(backend);

const { warnings } = await driver.captureScreen();

expect(warnings).toHaveLength(2);
expect(warnings?.[0]).toMatch(
/^ax-tree-fallback\(from=axbridge,to=ax,reason=error\): the full read failed, /u,
);
expect(warnings?.[1]).toMatch(
/^ax-tree-truncated\(backend=ax,depth=51,nodes=166\): the tree hit the device read limit, /u,
);
});

it('has no warnings key when the snapshot has no warnings', async () => {
const snapshot = {
platform: 'ios',
hierarchy: [makeElement({ label: 'Submit', identifier: 'submit' })],
raw: '[]',
timestamp: Date.now(),
};
const backend = createMockBackend({
snapshot: vi
.fn()
.mockResolvedValueOnce(snapshot)
.mockResolvedValueOnce({ ...snapshot, warnings: [] }),
});
const driver = new MobilePlatformDriver(backend);

const capture = await driver.captureScreen();
const tree = await driver.getAccessibilityTree();

expect(Object.keys(capture).sort()).toStrictEqual([
'getTestIds',
'nodes',
'refMap',
]);
expect(capture.nodes.map(({ testId }) => testId)).toStrictEqual([
'submit',
]);
expect(await capture.getTestIds()).toHaveLength(1);
expect(Object.keys(tree).sort()).toStrictEqual(['nodes', 'refMap']);
});

it('omits bounds for elements with zero-size frames', async () => {
Expand Down
35 changes: 30 additions & 5 deletions src/platform/mobile-platform-driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
} from './mobile-hierarchy.js';
import type { Viewport } from './mobile-hierarchy.js';
import type {
AccessibilityTree,
IPlatformDriver,
HermesDefaults,
TargetType,
Expand Down Expand Up @@ -508,9 +509,12 @@ export class MobilePlatformDriver implements IPlatformDriver {
*/
async getAccessibilityTree(
_rootSelector?: string,
): Promise<{ nodes: A11yNodeTrimmed[]; refMap: Map<string, string> }> {
const { hierarchy } = await this.#snapshotApp();
return normalizeSnapshot(hierarchy, this.#backend.platform);
): Promise<AccessibilityTree> {
const { hierarchy, warnings } = await this.#snapshotApp();
return {
...normalizeSnapshot(hierarchy, this.#backend.platform),
...(warnings === undefined ? {} : { warnings }),
};
}

/**
Expand All @@ -532,9 +536,10 @@ export class MobilePlatformDriver implements IPlatformDriver {
* @returns The nodes, refMap and a test ID reader for the same snapshot.
*/
async captureScreen(): Promise<ScreenCapture> {
const { hierarchy, viewport } = await this.#snapshotApp();
const { hierarchy, viewport, warnings } = await this.#snapshotApp();
return {
...normalizeSnapshot(hierarchy, this.#backend.platform),
...(warnings === undefined ? {} : { warnings }),
getTestIds: async (limit?: number) =>
this.#testIdsOf(hierarchy, viewport, limit),
};
Expand All @@ -545,11 +550,12 @@ export class MobilePlatformDriver implements IPlatformDriver {
* elements that are not part of the app (see `filterAppHierarchy`), so the
* tree, the refs and the test IDs all use the same filtered hierarchy.
*
* @returns The filtered hierarchy and the viewport of the snapshot.
* @returns The filtered hierarchy, viewport and warnings.
*/
async #snapshotApp(): Promise<{
hierarchy: UIElement[];
viewport: Viewport | undefined;
warnings: string[] | undefined;
}> {
const snapshot = await this.#backend.snapshot();
const { platform } = this.#backend;
Expand All @@ -559,6 +565,9 @@ export class MobilePlatformDriver implements IPlatformDriver {
excludeDevOverlay: this.#excludeDevOverlay,
}),
viewport: viewportFromHierarchy(snapshot.hierarchy, platform),
warnings: snapshot.warnings?.length
? snapshot.warnings.map(withAdvice)
: undefined,
};
}

Expand Down Expand Up @@ -1280,6 +1289,22 @@ type BoundsRef = {
matches?: number;
};

const WARNING_ADVICE: Record<string, string> = {
'ax-tree-truncated':
'the tree hit the device read limit, so elements on screen can be missing from a11y and testIds. See them with `mm screenshot`; tap one with `mm tap-coordinates <x> <y>` (same units as `bounds`).',
'ax-tree-fallback':
'the full read failed, so containers, screen markers and row texts can be missing and `wait-for` on them can time out. Confirm the screen with a control that is present or `mm screenshot`; tap a missing element with `mm tap-coordinates <x> <y>` (same units as `bounds`).',
};

/**
* @param warning - A device-mcp warning.
* @returns The warning with its advice.
*/
function withAdvice(warning: string): string {
const advice = WARNING_ADVICE[warning.split('(', 1)[0] ?? ''];
return advice ? `${warning}: ${advice}` : warning;
}

const BOUNDS_REF_PREFIX = 'bounds:';

/** Frame tolerance, in points (iOS) or pixels (Android). */
Expand Down
12 changes: 8 additions & 4 deletions src/platform/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,17 @@ export type WithinScope = {
value: string;
};

export type AccessibilityTree = {
nodes: A11yNodeTrimmed[];
refMap: Map<string, string>;
warnings?: string[];
};

/**
* One snapshot of the screen: the accessibility tree, and the test IDs of the
* same snapshot.
*/
export type ScreenCapture = {
nodes: A11yNodeTrimmed[];
refMap: Map<string, string>;
export type ScreenCapture = AccessibilityTree & {
/**
* Lists the test IDs of this snapshot (no new snapshot).
*
Expand Down Expand Up @@ -220,7 +224,7 @@ export type IPlatformDriver = {
getAccessibilityTree(
rootSelector?: string,
frame?: FrameSnapshotTarget,
): Promise<{ nodes: A11yNodeTrimmed[]; refMap: Map<string, string> }>;
): Promise<AccessibilityTree>;

getTestIds(limit?: number): Promise<TestIdItem[]>;

Expand Down
Loading
Loading