Skip to content

fix: match mobile test IDs and refs exactly - #143

Open
cryptotavares wants to merge 4 commits into
mainfrom
cryptotavares/exact-testid-match
Open

cryptotavares wants to merge 4 commits into
mainfrom
cryptotavares/exact-testid-match

Conversation

@cryptotavares

@cryptotavares cryptotavares commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Part of the mm CLI v2 effort.

Summary: On mobile, --testid and refs now match only the element with that exact test ID, label or value. A target that is not on the screen fails instead of acting on another element whose ID or label contains it.

Bumps @metamask/device-mcp to ^0.11.0, which ships MetaMask/device-mcp#68 (exact identifier match, ElementQuery.exact) and MetaMask/device-mcp#67 (ax-tree-fallback warning).

Problem

device-mcp falls back to a case-insensitive contains match when no element matches exactly. Core sends --testid x as { identifier: x } and a ref as its identifier: / label: / value: query, so both get that fallback. When the real element is missing (not rendered yet, scrolled away, or a partial accessibility tree), another element matches.

Live on iOS, 2026-12-03 (wallet home, partial accessibility tree, core 0.15.0, device-mcp 0.9.0, amounts sanitized). homepage-balance-breakdown is not on the screen; homepage-balance-breakdown-hero is:

mm wait-for --testid homepage-balance-breakdown --timeout 3000        exit 0  {"found":true, ...}
mm get-text --testid homepage-balance-breakdown --timeout 3000        exit 0  {"text":"$<AMT>, $<AMT>, (<PCT>%), Today", ...}
mm wait-for --testid ACCOUNT-PICKER --timeout 3000                    exit 0  {"found":true, ...}
mm wait-for --testid homepage-balance-breakdown-row --timeout 3000    exit 0  {"found":true, ...}

A click with the same target taps the wrong element. The wallets under test hold real funds.

Solution

device-mcp 0.11.0 matches identifier exactly, so --testid needs no core change beyond the bump. This PR adds exact: true to every ref query, so label and value refs also skip the fuzzy fallback.

flowchart TD
    T["--testid x"] --> Q1["{ identifier: x }"]
    R["ref eN (stable identity)"] --> Q2["parseStableIdentifier + exact: true"]
    Q1 --> D{"device-mcp findElement"}
    Q2 --> D
    D -->|exact match| A[wait-for / get-text / click / type act on it]
    D -->|no exact match| N["Not found. Nothing is tapped or read."]

    classDef new fill:#fff3cd,stroke:#d39e00
    classDef stop fill:#f8d7da,stroke:#c82333
    class Q2 new
    class N stop
Loading

Yellow boxes are new. Red boxes stop the command.

What the user sees

The same commands on the login screen with the device-mcp#68 build (the same code as 0.11.0) linked into the Mobile app (live, iOS):

Command Result Exit
wait-for --testid login-password-input {"found":true} 0
get-text --testid log-in-button {"text":"Unlock"} 0
wait-for --testid login-password (prefix of login-password-input) MM_WAIT_TIMEOUT Timed out waiting for element: {"identifier":"login-password"} 5
get-text --testid login-password MM_GETTEXT_FAILED Timed out waiting for element: … 4
wait-for --testid log-in (prefix of log-in-button) MM_WAIT_TIMEOUT 5
wait-for --testid LOG-IN-BUTTON (case differs) MM_WAIT_TIMEOUT 5

These are the existing codes of a missing mobile target. Nothing new is added to the error table.

Decisions for reviewers

Decision Reason
exact: true on refs only; --testid stays { identifier } device-mcp now matches every identifier exactly. One rule, in one place.
Label and value refs are exact too A ref is built from the exact label or value of a snapshot node, and #127 marks a ref unique with matchesExactly. The lookup now uses the same rule as the uniqueness check.
No rule for changing numbers on mobile The old fallback did not help there either: $2.43 does not contain $2.42. A ref to a label that changed fails as before.
Bump in this PR, as #134 did Only dependencies and the README range sentence carry the version. ElementQuery.exact needs 0.11.0.

Review guide

# File What to check
1 src/platform/mobile-platform-driver.ts resolveTargetToQuery, a11yRef case: { ...parseStableIdentifier(resolution), exact: true }.
2 src/platform/mobile-platform-driver.test.ts Ref assertions now carry exact: true. New test "finds a test ID or ref only by its exact identity" runs the driver on device-mcp's real findElement.
3 SKILL.md One sentence in the mobile tree section: exact, case-sensitive matching.
4 package.json, yarn.lock, README.md @metamask/device-mcp ^0.11.0.
Testing
  • With device-mcp 0.11.0 from npm, after merging main: yarn build, yarn lint and CI=1 yarn test pass (76 files, 2976 tests). Coverage: 98.13 / 95.54 / 97.53 / 98.23 (statements / branches / functions / lines), above the floors.
  • New test, on device-mcp's own findElement with a wallet home that lacks homepage-balance-breakdown:
    • --testid homepage-balance-breakdown and --testid HOMEPAGE-BALANCE-BREAKDOWN-HERO → not found;
    • ref label:Send|type:StaticText with only Send feedback → not found;
    • ref value:2.4|type:StaticText with only $2.43 → not found;
    • --testid homepage-balance-breakdown-hero → found.
  • Mutation check: without exact: true, 17 tests fail.
  • Live, iOS sim, read-only (one unlock, no taps other than Unlock):
    • Before (npm core 0.15.0, device-mcp 0.9.0), wallet home: the four false passes above.
    • After (device-mcp#68 linked), login screen: the table above. The relaunch after the yalc swap locked the wallet, and the session allows one unlock, so wallet home was not re-checked live. The new test covers that tree offline.
Docs changed
  • SKILL.md: mobile --testid and refs match the whole, case-sensitive testId, label or text, and fail when it is not on the screen.
  • README.md: the device-mcp range the consumer must match is ^0.11.0.

Ref queries ask device-mcp for an exact match (ElementQuery.exact), so a
label or value ref never falls back to a partial match. --testid relies on
device-mcp matching identifiers exactly. Needs the device-mcp release with
MetaMask/device-mcp#68.
cryptotavares added a commit to MetaMask/device-mcp that referenced this pull request Dec 4, 2026
Part of the mm CLI v2 effort. Core follow-up:
MetaMask/client-mcp-core#143 (draft, needs this release).

> **Summary:** An element query's `identifier` now matches only the
whole, case-sensitive identifier. A test ID that is not on screen fails
instead of matching another element whose ID contains it. A new
`ElementQuery.exact` turns off the fuzzy fallback for `label`, `text`
and `type`.

## Problem

`findElement` tries an exact match first, then falls back to the first
fuzzy match (case-insensitive equality, then **contains**) for every
field, `identifier` included. When the requested element is missing (not
rendered yet, scrolled away, or a partial accessibility tree), a longer
test ID that contains it matches instead. `waitForElement` then passes,
`getElementText` reads the wrong element, and `tapElement` taps it.

Live on iOS (wallet home, the accessibility tree fell back to a partial
read, `homepage-balance-breakdown` absent; device-mcp 0.9.0, amounts
sanitized):

```text
mm wait-for --testid homepage-balance-breakdown --timeout 3000
→ {"found":true,"target":"testId:homepage-balance-breakdown"}                         exit 0
mm get-text --testid homepage-balance-breakdown --timeout 3000
→ {"text":"$<AMT>, $<AMT>, (<PCT>%), Today","target":"testId:homepage-balance-breakdown"}  exit 0
   (the text of homepage-balance-breakdown-hero)
```

A `click` with the same target would tap
`homepage-balance-breakdown-hero`. The same applies to `account-picker`
→ `account-picker-avatar`, `wallet-screen` → `wallet-screen-…`, and on
Android to a short ID (`title`) → `io.metamask:id/title`. The wallets
under test hold real funds.

## Solution

`matchesQuery` compares `identifier` with `exactMatch` in both passes.
`findElement` skips the fuzzy pass when `query.exact` is set. The match
rule stays in one function, so every caller gets it: the three backends
(`tapElement`, `longPress`, `getElementText`), `pollForElement`
(`waitForElement`) and `scrollToElement`.

```mermaid
flowchart TD
    Q["findElement(hierarchy, query)"] --> E{"exact pass:<br/>every field equal"}
    E -->|found| R[return the element]
    E -->|none| X{"query.exact?"}
    X -->|yes| N["null: Element not found / wait times out"]
    X -->|no| F{"fuzzy pass:<br/>identifier still exact,<br/>label / text / type: ignore case, contains"}
    F -->|found| R
    F -->|none| N2["null: Element not found / wait times out"]

    classDef new fill:#fff3cd,stroke:#d39e00
    classDef stop fill:#f8d7da,stroke:#c82333
    class X,F new
    class N,N2 stop
```

Yellow boxes are new. Red boxes stop the lookup.

## What changes

Each query run against the same tree through the published 0.9.0 build
and this branch's build:

| Query | Before | After |
|---|---|---|
| `{ identifier: 'homepage-balance-breakdown' }` (only `…-hero` on
screen) | `homepage-balance-breakdown-hero` | `null` |
| `{ identifier: 'account-picker' }` (both on screen) | `account-picker`
| `account-picker` |
| `{ identifier: 'ACCOUNT-PICKER' }` | `account-picker-avatar` | `null`
|
| `{ identifier: 'title' }` (Android `io.metamask:id/title`) |
`io.metamask:id/title` | `null` |
| `{ label: 'Send' }` (only `Send feedback`) | `Send feedback` | `Send
feedback` (no change) |
| `{ label: 'Send', exact: true }` | `Send feedback` | `null` |

## Decisions for reviewers

| Decision | Reason |
|---|---|
| `identifier` is always exact, with no opt-out | An identifier is an
ID. A partial ID match has no safe use, and every caller (core's
`--testid` and refs, the MCP tools) means one element. |
| **Breaking** (`fix!`): needs a minor bump (0.x) | A caller that relied
on a partial or case-insensitive identifier now gets `Element not
found`. On Android this includes a bare ID without the `package:id/`
prefix. |
| Keep fuzzy `label` / `text` / `type` by default | The MCP tools serve
humans and agents who type a label by hand (`device_tap_element { label:
"Confirm" }`), and `dismissAlert` looks up its button labels with it. |
| `exact` is a library field, not an MCP tool parameter | Its only
caller is core, which builds ref queries from exact snapshot text. The
tools keep their current schema. |
| Hit test unchanged | `hit-test.ts` and `android-hit-test.ts` compare
the hit with the target by equality and frame. They do not call
`matchesQuery`. |

## Review guide

Read the files in this order:

| # | File | What to check |
|---|---|---|
| 1 | `src/utils/element.ts` | `exactMatch` on `identifier` in
`matchesQuery`; the `query.exact` guard in `findElement`. |
| 2 | `src/backends/types.ts` | `ElementQuery.exact`. |
| 3 | `src/tools/*.ts` | Each tool description adds: "`label`, `text`
and `type` match partially (case-insensitive) when no element matches
exactly." |
| 4 | Tests | `element.test.ts` (match rules),
`wait-for-element.test.ts` (wait times out), `idb-backend.test.ts` and
`adb-backend.test.ts` (no tap). |
| 5 | `README.md` | "Element Identification": how each field matches. |

<details>
<summary>Testing</summary>

- `yarn build`, `yarn lint` and `yarn test` pass (990 passed, 6 skipped,
after merging `main`). Coverage did not drop: all files 83.04%
statements, `element.ts` 97.24%.
- New or changed tests:
- a missing identifier that is a substring or a prefix of another, or
differs only in case → `findElement` returns `null`; the whole
identifier still matches;
- `pollForElement` times out when only `confirm-footer` and `Confirm`
are on screen for `confirm`;
- iOS `tapElement({ identifier: 'homepage-balance-breakdown' })` with
only `…-hero` on screen → `Element not found`, no `idb ui tap`;
- Android `tapElement({ identifier: 'title' })` with
`io.metamask:id/title` on screen → `Element not found`, no `input tap`;
- label and text keep the fuzzy fallback (`send` → `Send feedback`,
`RESEND` → `Resend`); with `exact: true` they do not;
- an identifier stays exact when the label falls back to a partial
match.
- Mutation check: reverting `exactMatch` to `match` for `identifier`, or
removing the `query.exact` guard, fails these tests.
- Live, iOS sim, read-only, this build linked into the Mobile app with
yalc (core 0.15.0 unchanged), login screen:

  | Command | Before (0.9.0) | After |
  |---|---|---|
| `wait-for --testid homepage-balance-breakdown` (wallet home, only
`…-hero` present) | exit 0, false pass | not re-run: the relaunch after
the swap locked the wallet (one unlock per session) |
  | `wait-for --testid login-password-input` | — | exit 0 |
| `wait-for` / `get-text --testid login-password` (prefix) | — | exit 5
`MM_WAIT_TIMEOUT` / exit 4 `MM_GETTEXT_FAILED` |
| `wait-for --testid log-in` (prefix), `LOG-IN-BUTTON` (case) | — | exit
5 `MM_WAIT_TIMEOUT` |
  | `get-text --testid log-in-button` | — | exit 0 `"Unlock"` |

- Core needs MetaMask/client-mcp-core#143 to pass `exact: true` for
refs; `--testid` needs only this release.

</details>

<details>
<summary>Docs changed</summary>

- `README.md` "Element Identification": `identifier` exact and
case-sensitive; `label`, `text`, `type` exact first, then partial and
case-insensitive; `exact: true` (library API only) turns off the partial
match.

</details>
@socket-security

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Updated@​metamask/​device-mcp@​0.10.0 ⏵ 0.11.093 +5100100 +198 +180

View full report

@socket-security

Copy link
Copy Markdown

Warning

MetaMask internal reviewing guidelines:

  • Do not ignore-all
  • Each alert has instructions on how to review if you don't know what it means. If lost, ask your Security Liaison or the supply-chain group
  • Copy-paste ignore lines for specific packages or a group of one kind with a note on what research you did to deem it safe.
    @SocketSecurity ignore npm/PACKAGE@VERSION
Priority Alert  (click "▶" to expand/collapse) Action
Low priority
Potential code anomaly (AI signal): npm @metamask/device-mcp is 96.0% likely to have a medium risk anomaly

Notes: This module implements Hermes CDP discovery and command execution. Its main security concern is that executeVerifiedCdpCommand() connects to the discovery-provided WebSocket URL without calling the available localhost/port validation helper, allowing a malicious discovery response to trigger a connection to an unintended host. It also sends caller-supplied CDP methods and parameters, while the exported blocked-method check is not applied in this function. No credential theft or other clear malware behavior is present; severity is a security warning dependent on control of the discovery response or caller inputs.

Confidence: 0.96

Severity: 0.55

From: package.json → npm/@metamask/device-mcp@0.11.0

ℹ Read more on: This package | This alert | What is an AI-detected potential code anomaly?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: An AI system found a low-risk anomaly in this package. It may still be fine to use, but you should check that it is safe before proceeding.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/@metamask/device-mcp@0.11.0. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn

View full report

@cryptotavares
cryptotavares marked this pull request as ready for review December 4, 2026 19:19
@cryptotavares
cryptotavares requested a review from a team as a code owner December 4, 2026 19:19

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant