From 6f66c2391a6f3c0393177b39e708b76796bfbf31 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Mon, 9 Nov 2026 09:38:31 +0000 Subject: [PATCH 1/2] fix: keep the launch Metro port for mobile cdp `mm launch --platform ios|android --metro-port ` stored the port on the session but `mm cdp` and `mm hermes-targets` resolved their target per call and fell back to `HERMES_METRO_PORT`/8081 (baseline B5), so they could reach another worktree's Metro. - `MobilePlatformDriver` options gain `metroPort`, `deviceId` and `appId`; `setHermesDefaults` keeps the launch values for later Hermes calls. - Precedence: per-call flag, then the driver/launch value, then `HERMES_METRO_PORT`/`HERMES_APP_ID`, then 8081/platform default. - `cdp` reuses one persistent device-mcp `HermesClient` per session target and is never retargeted: a call with a different port or app id uses a one-shot `runHermesCdp`. Releases without `HermesClient` (0.7.0) always take the one-shot path. - `hermes-targets` reports `sessionMetroPort`, `pinnedDeviceId`, `connected` and `deviceId`; a CDP failure names the Metro port it tried. --- CHANGELOG.md | 3 + README.md | 196 +++++----- SKILL.md | 30 +- src/index.ts | 1 + src/platform/index.ts | 1 + ...mobile-platform-driver.hermes-port.test.ts | 190 ++++++++++ .../mobile-platform-driver.hermes.test.ts | 339 ++++++++++++++++++ src/platform/mobile-platform-driver.ts | 302 ++++++++++++++-- src/platform/types.ts | 21 ++ src/tools/launch.test.ts | 68 ++++ src/tools/launch.ts | 24 ++ src/tools/types/tool-outputs.ts | 9 + 12 files changed, 1054 insertions(+), 130 deletions(-) create mode 100644 src/platform/mobile-platform-driver.hermes-port.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ac2fb72e..d58ad1af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- feat: `MobilePlatformDriver` options `metroPort`, `deviceId` and `appId` keep the session's Metro port, device and Hermes app id on the driver, and `IPlatformDriver.setHermesDefaults` lets the launch apply `--metro-port` / `--device-id` after a successful mobile launch; `mm hermes-targets` now reports `sessionMetroPort`, `pinnedDeviceId`, `connected` and `deviceId`. - feat: `mm cdp --target sw` sends CDP commands to the browser Extension's background service worker, and browser CDP sessions are now persistent per target (active page, service worker) instead of one-shot, so enabled domains and listeners survive across calls; a dead session (page or service-worker restart) is re-attached on the next call. New `mm cdp --fresh` keeps the old one-shot session, detached after the command. Browser and mobile reject the other platform's `--target` values with `MM_INVALID_INPUT`. - feat: `scroll_to_element` (`mm scroll-to-element`) now works on the browser: it waits for the target and scrolls it into view with `locator.scrollIntoViewIfNeeded()`, with `timeoutMs` and `within` support - feat: report `animationsSettled` in browser observations after a call that waits for animations, and document `mm wait-for` (including `--selector "text=..."`) as the replacement for `sleep` @@ -18,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- Mobile `mm cdp` keeps one persistent Hermes connection per session (Metro port and app id) and reuses it across calls instead of opening one WebSocket per call; a per-call `--metro-port` / `--app-id` that differs from the session's uses a one-shot connection, and the device pin still persists per session. Needs a device-mcp release with `HermesClient`; with device-mcp 0.7.0 each call opens its own connection. - **BREAKING:** `mm` failures are structured. A failed command prints one JSON line on stdout, `{"ok":false,"error":{"code","message","hint"?,"retryable"},"meta"?}`, instead of `Error: ` on stderr, and exits with a code per error class: 2 usage/validation, 3 no session or daemon down/lost, 4 target not found or not actionable, 5 timeout, 6 platform/device unavailable, 1 anything else (7 is reserved for a version mismatch). The daemon's `error.code` now reaches the caller. `exitCodeForError`, `isRetryableError`, `defaultHintForError`, `CliExitCodes` and `DaemonErrorCodes` are exported, and `ErrorCodes` adds `MM_BATCH_TIMEOUT`, the `MM_CLIPBOARD_*` codes and the CLI codes `MM_DAEMON_NOT_RUNNING`, `MM_DAEMON_START_FAILED`, `MM_DAEMON_ALREADY_RUNNING`, `MM_DAEMON_CONNECTION_LOST` and `MM_REQUEST_TIMEOUT`. Click and type timeouts say "state unknown". `launch` keeps any `MM_*` code thrown by a consumer, not only known codes. - Mobile `click` never reports a tap that hit something else: device-mcp refuses a tap when another element covers the target, and the click fails with the new `MM_TARGET_OBSCURED` (`MM_TARGET_NOT_VISIBLE` when the target is off screen). `click --dismiss-keyboard` closes a covering keyboard and taps once more (`keyboardDismissed: true`). With an observation, a mobile click result has `screenChanged`. The hit-test needs a device-mcp release with MetaMask/device-mcp#51. - Start the CLI faster: find the project root without running `git` and do not load zod. Load `@metamask/device-mcp` only when a mobile session uses it, so browser daemons start without it. @@ -26,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Mobile `mm cdp` and `mm hermes-targets` keep the `--metro-port` given at launch. Before, a later command without `--metro-port` fell back to `HERMES_METRO_PORT` or 8081, so it could not connect when Metro ran on another port. A per-call `--metro-port` still wins, and a CDP connection failure now names the Metro port it tried. - `mm` resends a request only when the daemon refused the connection (`ECONNREFUSED`, read from Node's `error.cause.code`). It no longer resends after a reset, broken pipe or socket error, which can come after the daemon got the request (a resent `click` could tap twice); those fail at once with `MM_DAEMON_CONNECTION_LOST` (exit 3). Before, every network failure matched `fetch failed` and was resent up to 3 times. ## [0.13.1] diff --git a/README.md b/README.md index f12a34a7..f211d9b2 100644 --- a/README.md +++ b/README.md @@ -392,63 +392,63 @@ The daemon routes `POST /tool/:name` requests through the registry, applies Zod **Registered tools:** -| Tool | Description | -| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Lifecycle** | | -| `build` | Triggers an extension build using the configured `BuildCapability`. Accepts build type and force options. | -| `launch` | Launches a new browser session with the configured extension. Supports state modes (`default`, `onboarding`, `custom`), fixture presets, tag metadata, and optional contract seeding on start. | -| `cleanup` | Tears down the active browser session and cleans up all resources (browser, services, fixtures). | -| **Interaction** | | -| `click` | Clicks an element identified by a11y ref, test ID, or CSS selector. Waits for the element to be visible before clicking. Supports `within` to scope the target inside a parent element. | -| `type` | Types text into an input element identified by a11y ref, test ID, or CSS selector. Clears the field first, then sets the new value (uses Playwright's `fill()`). Supports `within` scoping. On the browser, a read-only or disabled element fails at once with `MM_ELEMENT_NOT_EDITABLE` instead of waiting for the timeout. | -| `wait_for` | Waits for an element to become visible on the page within a configurable timeout. Supports `within` to scope the target inside a parent element. | -| `scroll_to_element` | Scrolls until an element (a11y ref, test ID, or selector) is visible. Browser: waits for the element (`timeoutMs`, default 15 000), then scrolls it into view, also inside a scrollable container; supports `within`; ignores `direction` and `maxAttempts`. Mobile: swipes until the target is inside the viewport, not only in the UI tree, and returns `swipes`, `inViewport` and `bounds`; `direction` is the content direction (`down` reveals content below), default `auto` picks it from the element's position; `maxAttempts` = maximum swipes (default 10); fails with `MM_TARGET_NOT_VISIBLE` (found, not in view) or `MM_TARGET_NOT_FOUND`; `within` is rejected. | -| `get_text` | Reads the text content of an element identified by a11y ref, test ID, or CSS selector. Returns the text, target descriptor, and character length. Supports `within` scoping. Categorized as read-only (no observations in response). | -| `inspect` | Browser only. Reads an element's attributes, `disabled` and `readOnly` flags, computed `styles` (`styles` input, default `color`, `background-color`, `opacity`, `cursor`) and `effectiveOpacity` (opacity including ancestors), so two elements can be compared by value. Read in an isolated world, so Extension page restrictions do not apply. Supports `within` scoping. Categorized as read-only. | -| `clipboard` | Reads from or writes to the system clipboard via Chrome DevTools Protocol. Useful for pasting seed phrases or copying addresses. | -| **Navigation** | | -| `navigate` | Navigates the browser to a named screen (`home`, `settings`, `notification`) or an arbitrary URL. | -| `reload` | Reloads the active page, keeping its URL and hash route. Discards in-memory page state such as cached API data, so the page fetches again through the current network mocks. Browser only. | -| `switch_to_tab` | Switches the active page to a tab matching a given role (e.g., `extension`, `dapp`) or URL prefix. | -| `close_tab` | Closes a browser tab matching a given role or URL. Falls back to the extension tab if the active tab is closed. | -| `wait_for_notification` | Waits for the extension notification popup to appear within a timeout. Returns the notification page URL. | -| **Discovery** | | -| `describe_screen` | Captures a comprehensive screen snapshot: extension state, visible test IDs, trimmed a11y tree with refs, and optional screenshot. | -| `accessibility_snapshot` | Captures a trimmed accessibility tree of the current page with deterministic refs (`e1`, `e2`, ...). Supports scoping to a root CSS selector. | -| `list_testids` | Collects all visible `data-testid` attributes from the current page with text previews and visibility status. | -| **State** | | -| `get_state` | Retrieves the current extension state (URL, screen, network, balance, account) and tracked tab information. On mobile the state is partial (`source: 'stub'`): fields that were not read from the app are omitted, not guessed. | -| `get_context` | Returns the current environment context (`e2e` or `prod`), session status, available capabilities, and whether context switching is allowed. | -| `set_context` | Switches the session environment between `e2e` and `prod` modes. Blocked while a session is active. | -| **Screenshots** | | -| `screenshot` | Captures a screenshot of the current page. Supports naming, full-page capture, scoping to a CSS selector, and optional base64 output. | -| **Contracts** | | -| `seed_contract` | Deploys a single smart contract to the local Anvil chain by name. Requires `ContractSeedingCapability`. | -| `seed_contracts` | Deploys multiple smart contracts in sequence. Returns both successful deployments and individual failures. | -| `get_contract_address` | Looks up the deployed address of a contract by name from the session's deployment registry. | -| `list_contracts` | Lists all contracts deployed in the current session with addresses and deployment timestamps. | -| **Batching** | | -| `run_steps` | Executes a batch of tool invocations sequentially. Supports `stopOnError` to halt on first failure, a top-level `observe` level for the single observation collected after the batch (default `diff`; without one, the last executed step's `observe` is used), and `batchTimeoutMs` (1 000–30 000 ms) to set an overall deadline (checked between steps; remaining steps are skipped). The whole `run_steps` call has the default 30 s request limit, so to get partial results set `batchTimeoutMs` below it (for example 20 000) and keep batches short. Accepts tool aliases like `navigate_home` / `navigate-home`. Returns per-step results with timing. | -| **Advanced** | | -| `mock_network` | Adds, clears, lists, and inspects targeted Playwright network mocks on the active browser context. Unmatched same-origin requests are continued unchanged. | +| Tool | Description | +| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Lifecycle** | | +| `build` | Triggers an extension build using the configured `BuildCapability`. Accepts build type and force options. | +| `launch` | Launches a new browser session with the configured extension. Supports state modes (`default`, `onboarding`, `custom`), fixture presets, tag metadata, and optional contract seeding on start. | +| `cleanup` | Tears down the active browser session and cleans up all resources (browser, services, fixtures). | +| **Interaction** | | +| `click` | Clicks an element identified by a11y ref, test ID, or CSS selector. Waits for the element to be visible before clicking. Supports `within` to scope the target inside a parent element. | +| `type` | Types text into an input element identified by a11y ref, test ID, or CSS selector. Clears the field first, then sets the new value (uses Playwright's `fill()`). Supports `within` scoping. On the browser, a read-only or disabled element fails at once with `MM_ELEMENT_NOT_EDITABLE` instead of waiting for the timeout. | +| `wait_for` | Waits for an element to become visible on the page within a configurable timeout. Supports `within` to scope the target inside a parent element. | +| `scroll_to_element` | Scrolls until an element (a11y ref, test ID, or selector) is visible. Browser: waits for the element (`timeoutMs`, default 15 000), then scrolls it into view, also inside a scrollable container; supports `within`; ignores `direction` and `maxAttempts`. Mobile: swipes until the target is inside the viewport, not only in the UI tree, and returns `swipes`, `inViewport` and `bounds`; `direction` is the content direction (`down` reveals content below), default `auto` picks it from the element's position; `maxAttempts` = maximum swipes (default 10); fails with `MM_TARGET_NOT_VISIBLE` (found, not in view) or `MM_TARGET_NOT_FOUND`; `within` is rejected. | +| `get_text` | Reads the text content of an element identified by a11y ref, test ID, or CSS selector. Returns the text, target descriptor, and character length. Supports `within` scoping. Categorized as read-only (no observations in response). | +| `inspect` | Browser only. Reads an element's attributes, `disabled` and `readOnly` flags, computed `styles` (`styles` input, default `color`, `background-color`, `opacity`, `cursor`) and `effectiveOpacity` (opacity including ancestors), so two elements can be compared by value. Read in an isolated world, so Extension page restrictions do not apply. Supports `within` scoping. Categorized as read-only. | +| `clipboard` | Reads from or writes to the system clipboard via Chrome DevTools Protocol. Useful for pasting seed phrases or copying addresses. | +| **Navigation** | | +| `navigate` | Navigates the browser to a named screen (`home`, `settings`, `notification`) or an arbitrary URL. | +| `reload` | Reloads the active page, keeping its URL and hash route. Discards in-memory page state such as cached API data, so the page fetches again through the current network mocks. Browser only. | +| `switch_to_tab` | Switches the active page to a tab matching a given role (e.g., `extension`, `dapp`) or URL prefix. | +| `close_tab` | Closes a browser tab matching a given role or URL. Falls back to the extension tab if the active tab is closed. | +| `wait_for_notification` | Waits for the extension notification popup to appear within a timeout. Returns the notification page URL. | +| **Discovery** | | +| `describe_screen` | Captures a comprehensive screen snapshot: extension state, visible test IDs, trimmed a11y tree with refs, and optional screenshot. | +| `accessibility_snapshot` | Captures a trimmed accessibility tree of the current page with deterministic refs (`e1`, `e2`, ...). Supports scoping to a root CSS selector. | +| `list_testids` | Collects all visible `data-testid` attributes from the current page with text previews and visibility status. | +| **State** | | +| `get_state` | Retrieves the current extension state (URL, screen, network, balance, account) and tracked tab information. On mobile the state is partial (`source: 'stub'`): fields that were not read from the app are omitted, not guessed. | +| `get_context` | Returns the current environment context (`e2e` or `prod`), session status, available capabilities, and whether context switching is allowed. | +| `set_context` | Switches the session environment between `e2e` and `prod` modes. Blocked while a session is active. | +| **Screenshots** | | +| `screenshot` | Captures a screenshot of the current page. Supports naming, full-page capture, scoping to a CSS selector, and optional base64 output. | +| **Contracts** | | +| `seed_contract` | Deploys a single smart contract to the local Anvil chain by name. Requires `ContractSeedingCapability`. | +| `seed_contracts` | Deploys multiple smart contracts in sequence. Returns both successful deployments and individual failures. | +| `get_contract_address` | Looks up the deployed address of a contract by name from the session's deployment registry. | +| `list_contracts` | Lists all contracts deployed in the current session with addresses and deployment timestamps. | +| **Batching** | | +| `run_steps` | Executes a batch of tool invocations sequentially. Supports `stopOnError` to halt on first failure, a top-level `observe` level for the single observation collected after the batch (default `diff`; without one, the last executed step's `observe` is used), and `batchTimeoutMs` (1 000–30 000 ms) to set an overall deadline (checked between steps; remaining steps are skipped). The whole `run_steps` call has the default 30 s request limit, so to get partial results set `batchTimeoutMs` below it (for example 20 000) and keep batches short. Accepts tool aliases like `navigate_home` / `navigate-home`. Returns per-step results with timing. | +| **Advanced** | | +| `mock_network` | Adds, clears, lists, and inspects targeted Playwright network mocks on the active browser context. Unmatched same-origin requests are continued unchanged. | | `cdp` | Sends a raw Chrome DevTools Protocol command, dispatched through the active platform driver. **Browser:** targets the active page (`target: "page"`, default) or the Extension service worker (`target: "sw"`) on a persistent CDP session shared across calls, so enabled domains and listeners survive; `fresh: true` uses a one-shot session. Full Runtime/DOM/Network/Page surface; destructive methods (`Browser.close`, `Target.closeTarget`, etc.) are blocked. **Mobile (iOS/Android):** targets the app's React Native Hermes JS runtime via Metro's inspector proxy (delegates to `@metamask/device-mcp`, needs a DEBUG build with Metro running); only the JS-engine subset exists (`Runtime`, `Debugger`, `Log`, `HeapProfiler` — no DOM/Page/Network) and `Runtime.terminateExecution` / `Inspector.detached` are blocked. Optional `metroPort` / `appId` are mobile-only (ignored on browser). Categorized as `cdp`: no observation is collected and refs are not refreshed, so run `describe_screen` after a call that changes state. See [Browser vs Mobile CDP](#browser-vs-mobile-hermes-cdp). | -| **Hermes (mobile only)** | | -| `hermes_targets` | Lists and diagnoses the debuggable Hermes targets Metro exposes (iOS and Android), reporting which target would be chosen or why selection is ambiguous. Use to confirm Metro is running and the app is registered. Pass `all` to bypass the appId filter and discover the real appId. Mobile only — there is no browser equivalent. | -| **Mobile (iOS/Android only)** | | -| `device_swipe` | Swipes the screen in a `direction` (`up`/`down`/`left`/`right`), with optional `startX`/`startY`/`distance`. Mobile only. | -| `long_press` | Long-presses an element (a11y ref, test ID, or selector) for an optional `durationMs`. Mobile only. | -| `tap_coordinates` | Taps raw `x`/`y` screen coordinates. Mobile only. | -| `dismiss_keyboard` | Dismisses the on-screen keyboard. Mobile only. | -| `dismiss_alert` | Dismisses a native alert, accepting it when `accept` is true. Mobile only. | -| `get_alert_text` | Returns the text of a visible native alert. Read-only. Mobile only. | -| `open_app` | Launches or foregrounds an app by `bundleId`. Mobile only. | -| `close_app` | Terminates an app by `bundleId`. Mobile only. | -| `press_button` | Presses a hardware/system button. One of `home`, `back`, `enter`, `lock`. Mobile only. | -| `device_context` | Lists native/webview contexts (`list`) or switches to one (`switch` + `name`). Mobile only. | -| `device_clipboard` | Reads (`read`) or writes (`write` + `text`) the device clipboard. Distinct from the browser `clipboard` tool (which uses CDP). Mobile only. | -| `screen_recording` | Starts (`start`, optional `outputPath`) or stops (`stop`) a screen recording. When provided, `outputPath` is sandboxed to the configured `artifactsDir` (paths escaping it are rejected). Read-only. Mobile only. | -| `device_logs` | Fetches device logs with optional `durationSeconds` and `filter`. Read-only. Mobile only. | -| `generate_locators` | Generates ranked locator suggestions (identifier > label > text > type, with confidence) for every interactive element on the current screen, by walking the device snapshot. Read-only. Mobile only. | +| **Hermes (mobile only)** | | +| `hermes_targets` | Lists and diagnoses the debuggable Hermes targets Metro exposes (iOS and Android), reporting which target would be chosen or why selection is ambiguous. Use to confirm Metro is running and the app is registered. Pass `all` to bypass the appId filter and discover the real appId. Mobile only — there is no browser equivalent. | +| **Mobile (iOS/Android only)** | | +| `device_swipe` | Swipes the screen in a `direction` (`up`/`down`/`left`/`right`), with optional `startX`/`startY`/`distance`. Mobile only. | +| `long_press` | Long-presses an element (a11y ref, test ID, or selector) for an optional `durationMs`. Mobile only. | +| `tap_coordinates` | Taps raw `x`/`y` screen coordinates. Mobile only. | +| `dismiss_keyboard` | Dismisses the on-screen keyboard. Mobile only. | +| `dismiss_alert` | Dismisses a native alert, accepting it when `accept` is true. Mobile only. | +| `get_alert_text` | Returns the text of a visible native alert. Read-only. Mobile only. | +| `open_app` | Launches or foregrounds an app by `bundleId`. Mobile only. | +| `close_app` | Terminates an app by `bundleId`. Mobile only. | +| `press_button` | Presses a hardware/system button. One of `home`, `back`, `enter`, `lock`. Mobile only. | +| `device_context` | Lists native/webview contexts (`list`) or switches to one (`switch` + `name`). Mobile only. | +| `device_clipboard` | Reads (`read`) or writes (`write` + `text`) the device clipboard. Distinct from the browser `clipboard` tool (which uses CDP). Mobile only. | +| `screen_recording` | Starts (`start`, optional `outputPath`) or stops (`stop`) a screen recording. When provided, `outputPath` is sandboxed to the configured `artifactsDir` (paths escaping it are rejected). Read-only. Mobile only. | +| `device_logs` | Fetches device logs with optional `durationSeconds` and `filter`. Read-only. Mobile only. | +| `generate_locators` | Generates ranked locator suggestions (identifier > label > text > type, with confidence) for every interactive element on the current screen, by walking the device snapshot. Read-only. Mobile only. | ### Accessibility References @@ -618,14 +618,14 @@ mm describe-screen ### Lifecycle -| Command | Description | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `mm launch [--context e2e\|prod] [--state default\|onboarding\|custom] [--extension-path ] [--force]` | Auto-starts the daemon if needed, then launches a headed Chrome session with the configured extension. Use `--context` to set the environment context before launching. Use `--state` to control wallet initialization. Use `--extension-path` to override the extension directory. Use `--force` to replace an existing session. | -| `mm launch --platform ios\|android [--device-id ] [--app-bundle ] [--metro-port ] [--reinstall] [--reset-app-data] [--allow-fox-code-mismatch]` | Launches a mobile session. Use `--device-id` to target a specific device (auto-detected when exactly one is connected). Use `--app-bundle` to install a specific app artifact before launching. Use `--metro-port` to attach to a running Metro bundler (development builds). `--reinstall` and `--reset-app-data` are **destructive** to the app container and wallet state; `--allow-fox-code-mismatch` bypasses the consumer's app-identity guard. Consumers decide how to honor these — see [Mobile launch options](#mobile-launch-options). | -| `mm cleanup [--shutdown]` | Stops the browser, tears down test services (fixture server, Anvil, mock server), and releases session resources. Add `--shutdown` to also terminate the daemon process. | -| `mm stop [--force]` | Stops the daemon process (symmetric to `mm serve`). Sends a best-effort cleanup before shutdown. Use `--force` to remove stale `.mm-server` state from crashed daemons. | -| `mm status` | Displays the daemon's current status: PID, port, uptime, allocated sub-ports, and whether a browser session is active. | -| `mm serve [--background]` | Manually starts the HTTP daemon without launching a browser session. Use `--background` to detach the process. Fails if a daemon is already running for this worktree. | +| Command | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mm launch [--context e2e\|prod] [--state default\|onboarding\|custom] [--extension-path ] [--force]` | Auto-starts the daemon if needed, then launches a headed Chrome session with the configured extension. Use `--context` to set the environment context before launching. Use `--state` to control wallet initialization. Use `--extension-path` to override the extension directory. Use `--force` to replace an existing session. | +| `mm launch --platform ios\|android [--device-id ] [--app-bundle ] [--metro-port ] [--reinstall] [--reset-app-data] [--allow-fox-code-mismatch]` | Launches a mobile session. Use `--device-id` to target a specific device (auto-detected when exactly one is connected). Use `--app-bundle` to install a specific app artifact before launching. Use `--metro-port` to attach to a running Metro bundler (development builds); the session keeps it for later `mm cdp` and `mm hermes-targets` calls. `--reinstall` and `--reset-app-data` are **destructive** to the app container and wallet state; `--allow-fox-code-mismatch` bypasses the consumer's app-identity guard. Consumers decide how to honor these — see [Mobile launch options](#mobile-launch-options). | +| `mm cleanup [--shutdown]` | Stops the browser, tears down test services (fixture server, Anvil, mock server), and releases session resources. Add `--shutdown` to also terminate the daemon process. | +| `mm stop [--force]` | Stops the daemon process (symmetric to `mm serve`). Sends a best-effort cleanup before shutdown. Use `--force` to remove stale `.mm-server` state from crashed daemons. | +| `mm status` | Displays the daemon's current status: PID, port, uptime, allocated sub-ports, and whether a browser session is active. | +| `mm serve [--background]` | Manually starts the HTTP daemon without launching a browser session. Use `--background` to detach the process. Fails if a daemon is already running for this worktree. | ### Interaction @@ -669,13 +669,13 @@ mm describe-screen ### Advanced -| Command | Description | -| ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `mm mock-network add ''` | Adds targeted route mocks during an active session. Pass either a single rule, an array of rules, or an object with a `routes` array. | -| `mm mock-network clear` | Clears route mocks and recorded requests. | -| `mm mock-network list` | Lists active route mocks. | -| `mm mock-network requests [--limit ]` | Shows recorded matched and missed requests. | -| `mm cdp [params-json] [--timeout ] [--target page\|sw\|hermes\|android-webview] [--fresh] [--metro-port

] [--app-id ]` | Sends a raw Chrome DevTools Protocol command against the active session. Escape hatch for when structured tools are insufficient. Works on both browser and mobile — the target runtime and blocked methods differ by platform (see below). Browser targets are the active page (`page`, default) and the Extension service worker (`sw`); `--fresh` uses a one-shot session. | +| Command | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `mm mock-network add ''` | Adds targeted route mocks during an active session. Pass either a single rule, an array of rules, or an object with a `routes` array. | +| `mm mock-network clear` | Clears route mocks and recorded requests. | +| `mm mock-network list` | Lists active route mocks. | +| `mm mock-network requests [--limit ]` | Shows recorded matched and missed requests. | +| `mm cdp [params-json] [--timeout ] [--target page\|sw\|hermes\|android-webview] [--fresh] [--metro-port

] [--app-id ]` | Sends a raw Chrome DevTools Protocol command against the active session. Escape hatch for when structured tools are insufficient. Works on both browser and mobile — the target runtime and blocked methods differ by platform (see below). Browser targets are the active page (`page`, default) and the Extension service worker (`sw`); `--fresh` uses a one-shot session. On mobile the session keeps the `--metro-port` given to `mm launch`, so later calls use it; a per-call `--metro-port` is only an override. | ```bash mm cdp Runtime.evaluate '{"expression":"document.title"}' @@ -691,27 +691,31 @@ The `params-json` argument must be a valid JSON object. The `--timeout` flag set `cdp` dispatches through the active platform driver, so the same command works on a browser or a mobile session — but the two targets are not interchangeable: -| Aspect | Browser (Playwright) | Mobile (React Native Hermes) | -| ------------------- | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | -| Target runtime | The active page or the Extension service worker (`--target sw`), each on a persistent session | The app's Hermes JS engine, via Metro's inspector proxy | -| Available domains | Full Chrome surface — `Runtime`, `DOM`, `Network`, `Page`, `Accessibility`, … | JS-engine subset only — `Runtime`, `Debugger`, `Log`, `HeapProfiler` (no `DOM` / `Page` / `Network`) | -| Blocked methods | `Browser.close`, `Target.closeTarget`, `Target.disposeBrowserContext`, `Browser.crashGpuProcess` | `Runtime.terminateExecution`, `Inspector.detached` | -| `metroPort`/`appId` | Ignored | Select the Metro inspector port (default `8081`) and target app (`io.metamask.MetaMask` iOS / `io.metamask` Android) | -| Prerequisite | An active browser session | An active mobile session with a DEBUG build and Metro running | -| Errors | `MM_CDP_BLOCKED` / `MM_CDP_FAILED`; `MM_INVALID_INPUT` for a mobile-only target | `MM_CDP_BLOCKED` / `MM_CDP_FAILED` (the underlying `HERMES_*` code is preserved in the message); `MM_INVALID_INPUT` for a browser-only target | +| Aspect | Browser (Playwright) | Mobile (React Native Hermes) | +| ------------------- | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Target runtime | The active page or the Extension service worker (`--target sw`), each on a persistent session | The app's Hermes JS engine, via Metro's inspector proxy | +| Available domains | Full Chrome surface — `Runtime`, `DOM`, `Network`, `Page`, `Accessibility`, … | JS-engine subset only — `Runtime`, `Debugger`, `Log`, `HeapProfiler` (no `DOM` / `Page` / `Network`) | +| Blocked methods | `Browser.close`, `Target.closeTarget`, `Target.disposeBrowserContext`, `Browser.crashGpuProcess` | `Runtime.terminateExecution`, `Inspector.detached` | +| `metroPort`/`appId` | Ignored | Default to the session's (the launch `--metro-port`, else `HERMES_METRO_PORT`, else `8081`; app id: `HERMES_APP_ID`, else the platform default). A per-call flag overrides them for that call only. | +| Prerequisite | An active browser session | An active mobile session with a DEBUG build and Metro running | +| Errors | `MM_CDP_BLOCKED` / `MM_CDP_FAILED`; `MM_INVALID_INPUT` for a mobile-only target | `MM_CDP_BLOCKED` / `MM_CDP_FAILED` (the underlying `HERMES_*` code is preserved in the message, with the Metro port used); `MM_INVALID_INPUT` for a browser-only target | -On mobile, `Runtime.evaluate` nests its value at `result.result.value`. Metro defaults can also be set globally via the `HERMES_METRO_PORT` / `HERMES_APP_ID` env vars on the `@metamask/device-mcp` backend. +On mobile, `Runtime.evaluate` nests its value at `result.result.value`. `cdp` and `hermes-targets` use the Metro port the session was launched with (`mm launch --metro-port`), then the `HERMES_METRO_PORT` env var, then `8081`; `--metro-port` / `--app-id` on a call only override it for that call, and such a call opens a one-shot connection. The app id defaults to `HERMES_APP_ID`, else the platform default. When device-mcp exports `HermesClient` (needs a device-mcp release with MetaMask/device-mcp P2-02), the session keeps one Hermes connection for its Metro port and app id and reuses it across calls; otherwise each call opens its own connection. ```bash -# Mobile (Hermes) — evaluate JS in the running app +# Mobile (Hermes) — the session keeps the launch Metro port +mm launch --platform ios --metro-port 8085 +mm cdp Runtime.evaluate '{"expression":"1+1","returnByValue":true}' + +# Override the port for this call only mm cdp Runtime.evaluate '{"expression":"1+1","returnByValue":true}' --app-id io.metamask --metro-port 8081 ``` #### Hermes targets (mobile only) -| Command | Description | -| -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `mm hermes-targets [--all] [--metro-port

] [--app-id ]` | Lists and diagnoses the debuggable Hermes targets Metro exposes, reporting which target would be chosen or why selection is ambiguous. Pass `--all` to bypass the appId filter and discover the real appId. Mobile only — there is no browser equivalent. | +| Command | Description | +| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mm hermes-targets [--all] [--metro-port

] [--app-id ]` | Lists and diagnoses the debuggable Hermes targets Metro exposes, reporting which target would be chosen or why selection is ambiguous. Pass `--all` to bypass the appId filter and discover the real appId. The report also says which Metro port the session keeps (`sessionMetroPort`), which device is pinned (`pinnedDeviceId`), whether the persistent connection is open (`connected`), and the session device (`deviceId`). Mobile only — there is no browser equivalent. | ```bash mm hermes-targets @@ -722,17 +726,19 @@ mm hermes-targets --all `mm launch --platform ios|android` accepts additional options that the core validates and forwards verbatim to the consumer's `ISessionManager.launch()`. -The core does **not** act on them itself — it owns no install or device -lifecycle. Each consumer decides how (or whether) to honor them: - -| Option | Field | Meaning | -| --------------------------- | ---------------------- | -------------------------------------------------------------------------------- | -| `--device-id ` | `deviceId` | Target a specific device. Auto-detected when exactly one is connected. | -| `--app-bundle ` | `appBundlePath` | App artifact to install before launching (iOS `.app`, Android `.apk`). | -| `--metro-port ` | `metroPort` | Metro bundler / inspector proxy port for watch-mode attach (development builds). | -| `--reinstall` | `reinstall` | **Destructive.** Uninstall and reinstall the app, discarding its container. | -| `--reset-app-data` | `resetAppData` | **Destructive.** Clear app data, discarding existing wallet state. | -| `--allow-fox-code-mismatch` | `allowFoxCodeMismatch` | **Dangerous.** Bypass the consumer's app-identity compatibility guard. | +The core owns no install or device lifecycle; each consumer decides how (or +whether) to honor them. After a successful launch, core also keeps `metroPort` +and `deviceId` as the session's Hermes defaults, so later `mm cdp` and +`mm hermes-targets` calls use them without a per-call flag. + +| Option | Field | Meaning | +| --------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| `--device-id ` | `deviceId` | Target a specific device. Auto-detected when exactly one is connected. | +| `--app-bundle ` | `appBundlePath` | App artifact to install before launching (iOS `.app`, Android `.apk`). | +| `--metro-port ` | `metroPort` | Metro bundler / inspector proxy port for watch-mode attach (development builds). Kept for later `mm cdp` / `mm hermes-targets` calls. | +| `--reinstall` | `reinstall` | **Destructive.** Uninstall and reinstall the app, discarding its container. | +| `--reset-app-data` | `resetAppData` | **Destructive.** Clear app data, discarding existing wallet state. | +| `--allow-fox-code-mismatch` | `allowFoxCodeMismatch` | **Dangerous.** Bypass the consumer's app-identity compatibility guard. | ```bash # Reuse whatever is already installed on the only booted device diff --git a/SKILL.md b/SKILL.md index 490d3a27..08f5e868 100644 --- a/SKILL.md +++ b/SKILL.md @@ -611,29 +611,33 @@ mm cdp Runtime.evaluate '{"expression":"typeof globalThis.stateHooks","returnByV # Browser — one-shot session, detached after the command mm cdp Runtime.evaluate '{"expression":"1+1","returnByValue":true}' --fresh -# Mobile (Hermes, default) — evaluate JS in the running React Native app +# Mobile (Hermes, default) — the session keeps the launch Metro port +mm launch --platform ios --metro-port 8085 +mm cdp Runtime.evaluate '{"expression":"1+1","returnByValue":true}' + +# Mobile (Hermes) — override the port for this call only mm cdp Runtime.evaluate '{"expression":"1+1","returnByValue":true}' --app-id io.metamask --metro-port 8081 # Mobile (Android WebView) — drive the DOM of the in-app browser mm cdp Runtime.evaluate '{"expression":"document.querySelector(\'#personalSign\').click()"}' --target android-webview ``` -| Argument | Description | -| --------------- | ------------------------------------------------------------------------------------------------------------------------- | -| `` | CDP method name (e.g., `Runtime.evaluate`, `DOM.getDocument` on browser; `Runtime.evaluate`, `Debugger.enable` on mobile) | -| `[params-json]` | Optional JSON object with method-specific parameters | -| `--timeout` | Per-command timeout in ms (default: 30 000, max: 30 000) | +| Argument | Description | +| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `` | CDP method name (e.g., `Runtime.evaluate`, `DOM.getDocument` on browser; `Runtime.evaluate`, `Debugger.enable` on mobile) | +| `[params-json]` | Optional JSON object with method-specific parameters | +| `--timeout` | Per-command timeout in ms (default: 30 000, max: 30 000) | | `--target` | Browser: `page` (default) or `sw` (Extension service worker). Mobile: `hermes` (default, RN JS runtime) or `android-webview` (in-app WebView DOM). Each platform rejects the other's targets with `MM_INVALID_INPUT`. | -| `--fresh` | **Browser only** — run the command on a one-shot CDP session and detach it afterwards instead of the persistent session. | -| `--url-filter` | **`--target android-webview` only** — select the WebView page whose URL contains this substring. | -| `--metro-port` | **Mobile (Hermes) only** — override the Metro inspector proxy port (default: 8081). Ignored on browser. | -| `--app-id` | **Mobile (Hermes) only** — override the expected app bundle identifier. Ignored on browser. | +| `--fresh` | **Browser only** — run the command on a one-shot CDP session and detach it afterwards instead of the persistent session. | +| `--url-filter` | **`--target android-webview` only** — select the WebView page whose URL contains this substring. | +| `--metro-port` | **Mobile (Hermes) only** — override the Metro inspector proxy port for this call. Defaults to the launch `--metro-port`, then `HERMES_METRO_PORT`, then 8081. Ignored on browser. | +| `--app-id` | **Mobile (Hermes) only** — override the expected app bundle identifier for this call. Ignored on browser. | **Three CDP targets:** the same command reaches different runtimes. | Aspect | Browser (Playwright) | Mobile — Hermes (`--target hermes`, default) | Mobile — Android WebView (`--target android-webview`) | | ----------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- | -| Target | The active page or the Extension service worker (`--target sw`), each on a persistent session | The app's Hermes JS engine, via Metro's inspector proxy (needs a DEBUG build with Metro running) | The web page inside a debuggable in-app Android WebView, via adb (needs `setWebContentsDebuggingEnabled(true)`) | +| Target | The active page or the Extension service worker (`--target sw`), each on a persistent session | The app's Hermes JS engine, via Metro's inspector proxy (needs a DEBUG build with Metro running) | The web page inside a debuggable in-app Android WebView, via adb (needs `setWebContentsDebuggingEnabled(true)`) | | Available domains | Full Chrome surface (`Runtime`, `DOM`, `Network`, `Page`, …) | JS-engine subset only (`Runtime`, `Debugger`, `Log`, `HeapProfiler`) — no `DOM`/`Page`/`Network` | Full Chrome surface (`Runtime`, `DOM`, `Network`, `Page`, `Input`) | | Use it for | Web page DOM in the browser | The React Native app's own JavaScript | The web page DOM inside the app's in-app browser | | Blocked methods | `Browser.close`, `Target.closeTarget`, `Target.disposeBrowserContext`, `Browser.crashGpuProcess` | `Runtime.terminateExecution`, `Inspector.detached` | `Browser.close`, `Target.closeTarget`, `Target.disposeBrowserContext`, `Browser.crashGpuProcess` | @@ -641,11 +645,13 @@ mm cdp Runtime.evaluate '{"expression":"document.querySelector(\'#personalSign\' Browser commands share one persistent CDP session per target, so a domain enabled by one call (e.g. `Network.enable`) stays enabled for the next calls on the same target. Use `--fresh` for a command that must run on its own session, detached afterwards. After an Extension service-worker restart the stale session is dropped and the next call re-attaches. +On mobile, `cdp` and `hermes-targets` use the Metro port the session was launched with (`mm launch --metro-port`), then the `HERMES_METRO_PORT` env var, then 8081. A per-call `--metro-port` / `--app-id` overrides it for that call only. When device-mcp exports `HermesClient` (needs a device-mcp release with MetaMask/device-mcp P2-02) the session keeps one Hermes connection for its Metro port and app id and reuses it across calls; otherwise each call opens its own connection. A mobile failure names the Metro port it used. + Blocked methods return `MM_CDP_BLOCKED` on either platform; other failures return `MM_CDP_FAILED` (on mobile the underlying `HERMES_*` code is preserved in the message). Each platform rejects the other platform's `--target` values with `MM_INVALID_INPUT`. The tool returns no observation by default — pass `--observe full` (or run `describe-screen`) to re-sync if the call changed runtime/page state. #### `mm hermes-targets [--all] [--metro-port

] [--app-id ]` -**Mobile only.** Lists and diagnoses the debuggable Hermes targets Metro currently exposes, reporting which target would be chosen or why selection is ambiguous. Use it to confirm Metro is running and the app is registered. Pass `--all` to bypass the appId filter and discover the real appId. +**Mobile only.** Lists and diagnoses the debuggable Hermes targets Metro currently exposes, reporting which target would be chosen or why selection is ambiguous. Use it to confirm Metro is running and the app is registered. Pass `--all` to bypass the appId filter and discover the real appId. It uses the session's Metro port (the launch `--metro-port`) unless `--metro-port` overrides it, and reports `sessionMetroPort`, the pinned `logicalDeviceId` (`pinnedDeviceId`), whether the persistent connection is open (`connected`), and the session `deviceId`. ```bash mm hermes-targets diff --git a/src/index.ts b/src/index.ts index e3cded3e..32d849da 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,7 @@ export type { PlatformScreenshotOptions, ScreenCapture, MobilePlatformDriverOptions, + HermesDefaults, } from './platform'; export { PlaywrightPlatformDriver, MobilePlatformDriver } from './platform'; diff --git a/src/platform/index.ts b/src/platform/index.ts index 142561f5..ea08b3a5 100644 --- a/src/platform/index.ts +++ b/src/platform/index.ts @@ -8,6 +8,7 @@ export type { WithinScope, IPlatformDriver, ScreenCapture, + HermesDefaults, } from './types.js'; export { PlaywrightPlatformDriver } from './playwright-driver.js'; diff --git a/src/platform/mobile-platform-driver.hermes-port.test.ts b/src/platform/mobile-platform-driver.hermes-port.test.ts new file mode 100644 index 00000000..014f274d --- /dev/null +++ b/src/platform/mobile-platform-driver.hermes-port.test.ts @@ -0,0 +1,190 @@ +import type { DeviceBackend } from '@metamask/device-mcp'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + runHermesCdp: vi.fn(), + HermesClient: vi.fn(), + hasHermesClient: true, +})); + +// Uses the real `HermesSession` of device-mcp, so the port precedence is +// exercised end to end (per call > driver default > env > 8081). +vi.mock('./device-mcp-runtime.js', async () => { + const actual = await import('@metamask/device-mcp'); + return { + loadDeviceMcp: async () => ({ + ...actual, + runHermesCdp: mocks.runHermesCdp, + HermesClient: mocks.hasHermesClient ? mocks.HermesClient : undefined, + }), + }; +}); + +// Imported AFTER vi.mock so the driver binds to the mocked device-mcp runtime. +const { MobilePlatformDriver } = await import('./mobile-platform-driver.js'); + +function createBackend(): DeviceBackend { + return { platform: 'ios' } as unknown as DeviceBackend; +} + +type HermesClientStub = { + metroPort: number; + appId: string; + isConnected: boolean; + send: ReturnType; + close: ReturnType; +}; + +type HermesClientOptions = { + metroPort: number; + appId: string; + pinnedDeviceId?: string; + onPin?: (logicalDeviceId: string) => void; +}; + +const clients: HermesClientStub[] = []; + +describe('MobilePlatformDriver Hermes port precedence', () => { + beforeEach(() => { + clients.length = 0; + mocks.hasHermesClient = true; + mocks.runHermesCdp.mockResolvedValue({ ok: true, result: { value: 2 } }); + mocks.HermesClient.mockImplementation(function ( + this: unknown, + options: HermesClientOptions, + ): HermesClientStub { + const client: HermesClientStub = { + metroPort: options.metroPort, + appId: options.appId, + isConnected: false, + send: vi.fn().mockResolvedValue({ ok: true, result: { value: 2 } }), + close: vi.fn(), + }; + clients.push(client); + return client; + }); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.unstubAllEnvs(); + }); + + it.each([ + { name: 'the 8081 default', expected: 8081, persistent: true }, + { + name: 'HERMES_METRO_PORT', + env: '8099', + expected: 8099, + persistent: true, + }, + { + name: 'the driver option over the env', + env: '8099', + option: 8085, + expected: 8085, + persistent: true, + }, + { + name: 'a per-call metroPort over the driver option', + env: '8099', + option: 8085, + perCall: 8087, + expected: 8087, + persistent: false, + }, + { + name: 'a per-call metroPort over the env', + env: '8099', + perCall: 8087, + expected: 8087, + persistent: false, + }, + ])( + 'uses $name', + async ({ + env, + option, + perCall, + expected, + persistent, + }: { + env?: string; + option?: number; + perCall?: number; + expected: number; + persistent: boolean; + }) => { + if (env !== undefined) { + vi.stubEnv('HERMES_METRO_PORT', env); + } + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + ...(option === undefined ? {} : { metroPort: option }), + }); + + await driver.cdp({ + method: 'Runtime.evaluate', + timeoutMs: 30_000, + ...(perCall === undefined ? {} : { metroPort: perCall }), + }); + + if (persistent) { + expect(mocks.HermesClient).toHaveBeenCalledTimes(1); + expect(mocks.HermesClient.mock.calls[0][0]).toMatchObject({ + metroPort: expected, + }); + expect(mocks.runHermesCdp).not.toHaveBeenCalled(); + } else { + expect(mocks.HermesClient).not.toHaveBeenCalled(); + expect(mocks.runHermesCdp.mock.calls[0][0]).toMatchObject({ + metroPort: expected, + }); + } + }, + ); + + it('names the Metro port the call used in an error', async () => { + mocks.runHermesCdp.mockResolvedValue({ + ok: false, + code: 'HERMES_TARGET_NOT_FOUND', + message: 'No Hermes debug target found', + }); + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + + const outcome = await driver.cdp({ + method: 'Runtime.evaluate', + timeoutMs: 30_000, + metroPort: 8087, + }); + + expect(outcome.ok).toBe(false); + if (!outcome.ok) { + expect(mocks.runHermesCdp.mock.calls[0][0]).toMatchObject({ + metroPort: 8087, + }); + expect(outcome.message).toContain('Metro port 8087'); + } + }); + + it('keeps the device pin across calls and a recreated client', async () => { + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + const first = mocks.HermesClient.mock.calls[0][0] as HermesClientOptions; + first.onPin?.('device-1'); + + driver.setHermesDefaults({ metroPort: 8086 }); + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + expect(clients[0].close).toHaveBeenCalledTimes(1); + expect(mocks.HermesClient).toHaveBeenCalledTimes(2); + expect(mocks.HermesClient.mock.calls[1][0]).toMatchObject({ + metroPort: 8086, + pinnedDeviceId: 'device-1', + }); + }); +}); diff --git a/src/platform/mobile-platform-driver.hermes.test.ts b/src/platform/mobile-platform-driver.hermes.test.ts index eb2c9eb7..ab55a4c3 100644 --- a/src/platform/mobile-platform-driver.hermes.test.ts +++ b/src/platform/mobile-platform-driver.hermes.test.ts @@ -10,6 +10,10 @@ const mocks = vi.hoisted(() => ({ getPinnedHermesDeviceId: vi.fn(), setPinnedHermesDeviceId: vi.fn(), HermesSession: vi.fn(), + HermesClient: vi.fn(), + // device-mcp 0.7.0 has no HermesClient; only the tests that exercise the + // persistent client enable it. + hasHermesClient: false, })); // The driver loads device-mcp on first use through this module. @@ -22,6 +26,7 @@ vi.mock('./device-mcp-runtime.js', () => ({ LEGACY_SYNTHETIC_TITLE: 'React Native Experimental (Improved Chrome Reloads)', HermesSession: mocks.HermesSession, + ...(mocks.hasHermesClient ? { HermesClient: mocks.HermesClient } : {}), }), })); @@ -37,6 +42,7 @@ function createBackend( describe('MobilePlatformDriver hermes delegation', () => { beforeEach(() => { + mocks.hasHermesClient = false; mocks.HermesSession.mockImplementation(() => ({ resolve: mocks.resolve, getPinnedHermesDeviceId: mocks.getPinnedHermesDeviceId, @@ -366,6 +372,7 @@ describe('MobilePlatformDriver hermes delegation', () => { describe('MobilePlatformDriver webview cdp routing', () => { beforeEach(() => { + mocks.hasHermesClient = false; mocks.HermesSession.mockImplementation(() => ({ resolve: mocks.resolve, getPinnedHermesDeviceId: mocks.getPinnedHermesDeviceId, @@ -511,3 +518,335 @@ describe('MobilePlatformDriver webview cdp routing', () => { } }); }); + +type HermesClientStub = { + metroPort: number; + appId: string; + isConnected: boolean; + send: ReturnType; + close: ReturnType; +}; + +type HermesClientOptions = { + metroPort: number; + appId: string; + pinnedDeviceId?: string; + onPin?: (logicalDeviceId: string) => void; +}; + +describe('MobilePlatformDriver persistent Hermes client', () => { + const clients: HermesClientStub[] = []; + + beforeEach(() => { + clients.length = 0; + mocks.hasHermesClient = true; + mocks.HermesSession.mockImplementation(() => ({ + resolve: mocks.resolve, + getPinnedHermesDeviceId: mocks.getPinnedHermesDeviceId, + setPinnedHermesDeviceId: mocks.setPinnedHermesDeviceId, + })); + mocks.resolve.mockImplementation( + ({ metroPort, appId }: { metroPort?: number; appId?: string }) => ({ + metroPort: metroPort ?? 8081, + appId: appId ?? 'io.metamask', + pinnedDeviceId: mocks.getPinnedHermesDeviceId(), + }), + ); + mocks.getPinnedHermesDeviceId.mockReturnValue(undefined); + mocks.HermesClient.mockImplementation(function ( + this: unknown, + options: HermesClientOptions, + ): HermesClientStub { + const client: HermesClientStub = { + metroPort: options.metroPort, + appId: options.appId, + isConnected: false, + send: vi.fn().mockResolvedValue({ ok: true, result: { value: 2 } }), + close: vi.fn(), + }; + clients.push(client); + return client; + }); + }); + + afterEach(() => { + vi.clearAllMocks(); + mocks.hasHermesClient = false; + }); + + it('creates one client for the session port and reuses it across calls', async () => { + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + + await driver.cdp({ + method: 'Runtime.evaluate', + params: { expression: '1+1' }, + timeoutMs: 30_000, + }); + await driver.cdp({ + method: 'Runtime.evaluate', + params: { expression: '2+2' }, + timeoutMs: 30_000, + }); + + expect(mocks.HermesClient).toHaveBeenCalledTimes(1); + expect(mocks.HermesClient).toHaveBeenCalledWith({ + metroPort: 8085, + appId: 'io.metamask', + pinnedDeviceId: undefined, + onPin: expect.any(Function), + }); + expect(clients[0].send).toHaveBeenCalledTimes(2); + expect(mocks.runHermesCdp).not.toHaveBeenCalled(); + }); + + it('uses a one-shot call for a per-call metroPort and keeps the session client', async () => { + mocks.runHermesCdp.mockResolvedValue({ ok: true, result: { value: 2 } }); + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + + await driver.cdp({ + method: 'Runtime.evaluate', + timeoutMs: 30_000, + metroPort: 8087, + }); + + expect(mocks.HermesClient).not.toHaveBeenCalled(); + expect(mocks.runHermesCdp).toHaveBeenCalledWith( + expect.objectContaining({ metroPort: 8087, appId: 'io.metamask' }), + ); + + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + expect(mocks.HermesClient).toHaveBeenCalledTimes(1); + expect(mocks.HermesClient).toHaveBeenCalledWith( + expect.objectContaining({ metroPort: 8085 }), + ); + expect(mocks.runHermesCdp).toHaveBeenCalledTimes(1); + }); + + it('uses a one-shot call for a per-call appId and keeps the session client', async () => { + mocks.runHermesCdp.mockResolvedValue({ ok: true, result: null }); + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + appId: 'app.session', + }); + + await driver.cdp({ + method: 'Runtime.evaluate', + timeoutMs: 30_000, + appId: 'app.other', + }); + + expect(mocks.HermesClient).not.toHaveBeenCalled(); + expect(mocks.runHermesCdp).toHaveBeenCalledWith( + expect.objectContaining({ metroPort: 8085, appId: 'app.other' }), + ); + + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + expect(mocks.HermesClient).toHaveBeenCalledWith( + expect.objectContaining({ metroPort: 8085, appId: 'app.session' }), + ); + }); + + it('persists the pin the client resolved on its first probe', async () => { + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + const options = mocks.HermesClient.mock.calls[0][0] as HermesClientOptions; + options.onPin?.('device-9'); + + expect(mocks.setPinnedHermesDeviceId).toHaveBeenCalledWith('device-9'); + }); + + it('creates the client with the pin the session already keeps', async () => { + mocks.getPinnedHermesDeviceId.mockReturnValue('device-7'); + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + expect(mocks.HermesClient).toHaveBeenCalledWith( + expect.objectContaining({ pinnedDeviceId: 'device-7' }), + ); + }); + + it('does not overwrite an existing pin from the client probe', async () => { + mocks.getPinnedHermesDeviceId.mockReturnValue('device-existing'); + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + const options = mocks.HermesClient.mock.calls[0][0] as HermesClientOptions; + options.onPin?.('device-new'); + + expect(mocks.setPinnedHermesDeviceId).not.toHaveBeenCalled(); + }); + + it('applies the launch defaults set after the driver is created', async () => { + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + driver.setHermesDefaults({ metroPort: 8086, deviceId: 'device-launch' }); + + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + expect(mocks.HermesClient).toHaveBeenCalledWith( + expect.objectContaining({ metroPort: 8086 }), + ); + }); + + it('drops the client when setHermesDefaults changes the session target', async () => { + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + driver.setHermesDefaults({ metroPort: 8086 }); + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + expect(clients[0].close).toHaveBeenCalledTimes(1); + expect(mocks.HermesClient).toHaveBeenCalledTimes(2); + expect(mocks.HermesClient).toHaveBeenLastCalledWith( + expect.objectContaining({ metroPort: 8086 }), + ); + }); + + it('keeps the client when setHermesDefaults only reports the device', async () => { + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + driver.setHermesDefaults({ deviceId: 'device-launch' }); + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + expect(clients[0].close).not.toHaveBeenCalled(); + expect(mocks.HermesClient).toHaveBeenCalledTimes(1); + }); + + it('closes the client on dispose', async () => { + const disposeBackend = vi.fn().mockResolvedValue(undefined); + const driver = new MobilePlatformDriver( + createBackend('ios', { dispose: disposeBackend }), + 'io.metamask', + { metroPort: 8085 }, + ); + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + await driver.dispose(); + await driver.dispose(); + + expect(clients[0].close).toHaveBeenCalledTimes(1); + expect(disposeBackend).toHaveBeenCalledTimes(1); + }); + + it('names the Metro port in a failure', async () => { + mocks.HermesClient.mockImplementation(function ( + this: unknown, + options: HermesClientOptions, + ): HermesClientStub { + const client: HermesClientStub = { + metroPort: options.metroPort, + appId: options.appId, + isConnected: false, + send: vi.fn().mockResolvedValue({ + ok: false, + code: 'HERMES_TARGET_NOT_FOUND', + message: 'No Hermes debug target found', + }), + close: vi.fn(), + }; + clients.push(client); + return client; + }); + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + + const outcome = await driver.cdp({ + method: 'Runtime.evaluate', + timeoutMs: 30_000, + }); + + expect(outcome.ok).toBe(false); + if (!outcome.ok) { + expect(outcome.code).toBe('MM_CDP_FAILED'); + expect(outcome.message).toContain('HERMES_TARGET_NOT_FOUND'); + expect(outcome.message).toContain('Metro port 8085'); + } + }); + + it('falls back to the one-shot path when device-mcp has no HermesClient', async () => { + mocks.hasHermesClient = false; + mocks.runHermesCdp.mockResolvedValue({ ok: true, result: { value: 2 } }); + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + + const outcome = await driver.cdp({ + method: 'Runtime.evaluate', + timeoutMs: 30_000, + }); + + expect(outcome).toStrictEqual({ ok: true, result: { value: 2 } }); + expect(mocks.HermesClient).not.toHaveBeenCalled(); + expect(mocks.runHermesCdp).toHaveBeenCalledWith( + expect.objectContaining({ metroPort: 8085 }), + ); + }); + + it('reports the session port, pin, connection and device in hermes-targets', async () => { + const target = { + id: 'page-1', + title: 'MetaMask', + appId: 'io.metamask', + webSocketDebuggerUrl: 'ws://localhost:8085/x', + reactNative: { logicalDeviceId: 'dev-1' }, + }; + mocks.fetchDiscoveryTargets.mockResolvedValue([target]); + mocks.selectHermesTarget.mockReturnValue({ ok: true, target }); + mocks.getPinnedHermesDeviceId.mockReturnValue('dev-1'); + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + deviceId: 'device-launch', + }); + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + clients[0].isConnected = true; + + const result = await driver.hermesTargets({}); + + expect(result).toMatchObject({ + metroPort: 8085, + sessionMetroPort: 8085, + pinnedDeviceId: 'dev-1', + connected: true, + deviceId: 'device-launch', + }); + expect(mocks.fetchDiscoveryTargets).toHaveBeenCalledWith( + 8085, + expect.any(Number), + ); + }); + + it('reports the session port when a per-call metroPort overrides the report', async () => { + mocks.fetchDiscoveryTargets.mockRejectedValue(new Error('fetch failed')); + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + + const result = await driver.hermesTargets({ metroPort: 8087 }); + + expect(result.metroPort).toBe(8087); + expect(result.sessionMetroPort).toBe(8085); + expect(result.metroDown).toBe(true); + expect(result.connected).toBe(false); + }); +}); diff --git a/src/platform/mobile-platform-driver.ts b/src/platform/mobile-platform-driver.ts index 14d87e4f..59cfd5f7 100644 --- a/src/platform/mobile-platform-driver.ts +++ b/src/platform/mobile-platform-driver.ts @@ -2,10 +2,12 @@ import type { DeviceBackend, ElementQuery, HermesSession, + HermesSessionResolved, HermesTarget, UIElement, } from '@metamask/device-mcp'; +import type { DeviceMcpRuntime } from './device-mcp-runtime.js'; import { loadDeviceMcp } from './device-mcp-runtime.js'; import { filterAppHierarchy, @@ -15,6 +17,7 @@ import { import type { Viewport } from './mobile-hierarchy.js'; import type { IPlatformDriver, + HermesDefaults, TargetType, ClickActionResult, ClickOptions, @@ -65,6 +68,66 @@ export type MobilePlatformDriverOptions = { * the accessibility tree and the test IDs. Default true. */ excludeDevOverlay?: boolean; + /** + * Metro inspector proxy port kept for this session. `cdp` and + * `hermes-targets` use it instead of falling back to another port, unless + * the call passes its own `metroPort`. Default: `HERMES_METRO_PORT`, else + * 8081. + */ + metroPort?: number; + /** Device the session runs on. Informational: reported by `hermes-targets`. */ + deviceId?: string; + /** + * Hermes app bundle identifier of the session. Default: `HERMES_APP_ID`, + * else the device-mcp platform default (`io.metamask.MetaMask` on iOS, + * `io.metamask` on Android). + */ + appId?: string; +}; + +/** + * The part of device-mcp's `HermesClient` this driver uses. Declared + * structurally because device-mcp 0.7.0, which core also supports, does not + * export the client. + */ +type HermesClientLike = { + /** The Metro port the client was created for. */ + readonly metroPort: number; + /** The app id the client was created for. */ + readonly appId: string; + /** Whether a verified socket is currently open. */ + readonly isConnected: boolean; + /** + * Sends one CDP command over the persistent socket. + * + * @param method - The CDP method. + * @param params - The CDP method parameters. + * @param options - Per-call timeout. + * @param options.timeoutMs - Per-call timeout in milliseconds. + * @returns The raw CDP result or a classified failure. + */ + send( + method: string, + params: Record | undefined, + options: { timeoutMs: number }, + ): Promise; + /** Closes the socket and stops reconnecting. */ + close(): void; +}; + +/** Constructor of device-mcp's `HermesClient`. */ +type HermesClientConstructor = new (options: { + metroPort: number; + appId: string; + pinnedDeviceId?: string; + onPin?: (logicalDeviceId: string) => void; +}) => HermesClientLike; + +/** The run-time export to feature-detect `HermesClient` on. */ +type HermesClientRuntime = { + // The device-mcp export keeps its public name. + // eslint-disable-next-line @typescript-eslint/naming-convention + HermesClient?: unknown; }; /** @@ -84,6 +147,23 @@ export class MobilePlatformDriver implements IPlatformDriver { // Created on first use, because device-mcp is loaded on first use. #hermesSession: HermesSession | undefined; + // One persistent connection per session target (Metro port + app id), + // created on the first Hermes cdp call that uses the session target. A call + // with a different port or app id takes the one-shot path instead, so this + // client is never retargeted. Created on first use (device-mcp is loaded + // lazily), so releasing it in dispose() must tolerate it being absent. + #hermesClient: HermesClientLike | undefined; + + // Session defaults kept from the launch (or the driver options). Undefined + // leaves the choice to device-mcp: env `HERMES_METRO_PORT` / + // `HERMES_APP_ID`, else the platform default. + #metroPort: number | undefined; + + #appId: string | undefined; + + // Informational: the device this session runs on, shown by hermes-targets. + #deviceId: string | undefined; + readonly #excludeDevOverlay: boolean; #windowSize: Viewport | undefined; @@ -98,6 +178,9 @@ export class MobilePlatformDriver implements IPlatformDriver { * button of development builds from the accessibility tree and the test * IDs (default true). Android System UI (status bar, navigation bar) is * always removed. + * @param options.metroPort - Metro inspector proxy port of the session. + * @param options.deviceId - Device of the session (informational). + * @param options.appId - Hermes app bundle identifier of the session. */ constructor( backend: DeviceBackend, @@ -107,6 +190,31 @@ export class MobilePlatformDriver implements IPlatformDriver { this.#backend = backend; this.#bundleId = bundleId; this.#excludeDevOverlay = options.excludeDevOverlay ?? true; + this.#metroPort = options.metroPort; + this.#appId = options.appId; + this.#deviceId = options.deviceId; + } + + /** + * Keeps the session defaults the launch resolved, so later `cdp` and + * `hermes-targets` calls use the same Metro port and device. A changed + * session target drops the persistent client; the next call creates one for + * the new target instead of retargeting the old connection. + * + * @param defaults - The defaults to keep. Absent fields are left unchanged. + */ + setHermesDefaults(defaults: HermesDefaults): void { + const previousPort = this.#metroPort; + const previousAppId = this.#appId; + this.#metroPort = defaults.metroPort ?? this.#metroPort; + this.#appId = defaults.appId ?? this.#appId; + this.#deviceId = defaults.deviceId ?? this.#deviceId; + if ( + this.#hermesClient && + (this.#metroPort !== previousPort || this.#appId !== previousAppId) + ) { + this.#closeHermesClient(); + } } /** @@ -121,6 +229,89 @@ export class MobilePlatformDriver implements IPlatformDriver { return this.#hermesSession; } + /** + * Resolves the effective Hermes target of a call: per-call overrides over + * this session's defaults (kept from the launch), over the device-mcp + * env/default. + * + * @param session - This driver's Hermes session. + * @param overrides - Optional per-call overrides. + * @param overrides.metroPort - Per-call Metro inspector proxy port. + * @param overrides.appId - Per-call Hermes app id. + * @returns The resolved target, with the session's device pin. + */ + #resolveHermesTarget( + session: HermesSession, + overrides: { metroPort?: number; appId?: string } = {}, + ): HermesSessionResolved { + return session.resolve({ + metroPort: overrides.metroPort ?? this.#metroPort, + appId: overrides.appId ?? this.#appId, + platform: this.#backend.platform, + }); + } + + /** + * Returns the persistent client of the session target, creating it on first + * use. Returns undefined when device-mcp has no `HermesClient` (0.7.0) or + * the cached client was built for another target: the caller then uses the + * one-shot path, so the client is never retargeted. + * + * @param runtime - The loaded device-mcp module. + * @param session - This driver's Hermes session. + * @param target - The session target (Metro port and app id). + * @returns The client, or undefined when unavailable. + */ + #getHermesClient( + runtime: DeviceMcpRuntime, + session: HermesSession, + target: HermesSessionResolved, + ): HermesClientLike | undefined { + const existing = this.#hermesClient; + if (existing) { + return existing.metroPort === target.metroPort && + existing.appId === target.appId + ? existing + : undefined; + } + const Client = (runtime as HermesClientRuntime).HermesClient; + if (typeof Client !== 'function') { + return undefined; + } + const client = new (Client as HermesClientConstructor)({ + metroPort: target.metroPort, + appId: target.appId, + pinnedDeviceId: target.pinnedDeviceId, + onPin: (logicalDeviceId): void => + this.#pinHermesDevice(session, logicalDeviceId), + }); + this.#hermesClient = client; + return client; + } + + /** + * Keeps the device pin of the session on the first successful identity + * probe, so later calls cannot switch to another device. + * + * @param session - This driver's Hermes session. + * @param logicalDeviceId - The `logicalDeviceId` the probe resolved. + */ + #pinHermesDevice(session: HermesSession, logicalDeviceId: string): void { + if (session.getPinnedHermesDeviceId() !== undefined) { + return; + } + session.setPinnedHermesDeviceId(logicalDeviceId); + } + + /** + * Closes the persistent client, if one was created. Idempotent. + */ + #closeHermesClient(): void { + const client = this.#hermesClient; + this.#hermesClient = undefined; + client?.close(); + } + /** * Release only this backend's resources. `DeviceBackend.dispose()` is * optional: backends without it (for example the ADB backend) have nothing @@ -128,6 +319,7 @@ export class MobilePlatformDriver implements IPlatformDriver { */ async dispose(): Promise { this.#disposing ??= (async (): Promise => { + this.#closeHermesClient(); await this.#backend.dispose?.(); })().catch((error: unknown) => { this.#disposing = undefined; @@ -682,21 +874,61 @@ export class MobilePlatformDriver implements IPlatformDriver { } /** - * Drives the React Native Hermes JS runtime via Metro. Unchanged behavior. + * Drives the React Native Hermes JS runtime via Metro. + * + * A call that uses the session target (the launch Metro port and app id, or + * no per-call override) goes through this driver's persistent + * `HermesClient`, created on first use and reused after. A call with a + * different `metroPort` or `appId` uses a one-shot `runHermesCdp` instead, + * so the persistent client is never retargeted. Releases of device-mcp + * without `HermesClient` (0.7.0) always take the one-shot path. * * @param input - The CDP command input. - * @returns A discriminated CDP outcome. + * @returns A discriminated CDP outcome. A failure names the Metro port used. */ async #hermesCdp(input: CdpInput): Promise { - const { runHermesCdp } = await loadDeviceMcp(); + const runtime = await loadDeviceMcp(); const session = await this.#getHermesSession(); - const resolved = session.resolve({ + const sessionTarget = this.#resolveHermesTarget(session); + const resolved = this.#resolveHermesTarget(session, { metroPort: input.metroPort, appId: input.appId, - platform: this.#backend.platform, }); + const usesSessionTarget = + resolved.metroPort === sessionTarget.metroPort && + resolved.appId === sessionTarget.appId; + const client = usesSessionTarget + ? this.#getHermesClient(runtime, session, sessionTarget) + : undefined; + + const outcome = client + ? await client.send(input.method, input.params, { + timeoutMs: input.timeoutMs, + }) + : await this.#runOneShotHermesCdp(runtime, session, resolved, input); + + return toHermesCdpOutcome(outcome, resolved.metroPort); + } - const outcome = await runHermesCdp({ + /** + * Runs one CDP command with a fresh discovery fetch and WebSocket, for a + * call whose target differs from the session's or for a device-mcp release + * without `HermesClient`. + * + * @param runtime - The loaded device-mcp module. + * @param session - This driver's Hermes session. + * @param resolved - The resolved target of this call. + * @param input - The CDP command input. + * @returns The raw device-mcp result. + */ + async #runOneShotHermesCdp( + runtime: DeviceMcpRuntime, + session: HermesSession, + resolved: HermesSessionResolved, + input: CdpInput, + ): Promise { + const { runHermesCdp } = runtime; + return runHermesCdp({ method: input.method, params: input.params, timeoutMs: input.timeoutMs, @@ -704,23 +936,12 @@ export class MobilePlatformDriver implements IPlatformDriver { appId: resolved.appId, pinnedDeviceId: resolved.pinnedDeviceId, onPin: (logicalDeviceId) => { - if (session.getPinnedHermesDeviceId() === undefined) { - session.setPinnedHermesDeviceId(logicalDeviceId); - } + this.#pinHermesDevice(session, logicalDeviceId); + // The persistent client, if one exists, was created without this pin: + // recreate it on the next call so it cannot select another device. + this.#closeHermesClient(); }, }); - - if (outcome.ok) { - return { ok: true, result: outcome.result }; - } - return { - ok: false, - code: - outcome.code === HERMES_BLOCKED_METHOD_CODE - ? ErrorCodes.MM_CDP_BLOCKED - : ErrorCodes.MM_CDP_FAILED, - message: `[${outcome.code}] ${outcome.message}`, - }; } /** @@ -763,6 +984,8 @@ export class MobilePlatformDriver implements IPlatformDriver { /** * Lists and diagnoses the debuggable Hermes targets Metro currently exposes, * reporting which target would be chosen (or why selection is ambiguous). + * The report also says which Metro port the session keeps, which device is + * pinned, and whether the persistent client is connected. * * @param input - Optional Metro port / appId overrides and an `all` flag to * bypass the appId filter for discovery. @@ -776,12 +999,18 @@ export class MobilePlatformDriver implements IPlatformDriver { LEGACY_SYNTHETIC_TITLE, } = await loadDeviceMcp(); const session = await this.#getHermesSession(); - const resolved = session.resolve({ + const sessionTarget = this.#resolveHermesTarget(session); + const resolved = this.#resolveHermesTarget(session, { metroPort: input.metroPort, appId: input.appId, - platform: this.#backend.platform, }); const filterBypassed = Boolean(input.all); + const sessionFields = { + sessionMetroPort: sessionTarget.metroPort, + pinnedDeviceId: session.getPinnedHermesDeviceId(), + connected: this.#hermesClient?.isConnected === true, + deviceId: this.#deviceId, + }; let targets: HermesTarget[]; try { @@ -798,6 +1027,7 @@ export class MobilePlatformDriver implements IPlatformDriver { metroDown: true, targetsDiscovered: 0, candidates: [], + ...sessionFields, }; } throw error; @@ -821,6 +1051,7 @@ export class MobilePlatformDriver implements IPlatformDriver { metroDown: false, targetsDiscovered: targets.length, candidates: displayCandidates.map(toHermesTargetInfo), + ...sessionFields, }; const selection = selectHermesTarget( @@ -865,6 +1096,31 @@ export class MobilePlatformDriver implements IPlatformDriver { } } +/** + * Maps a device-mcp Hermes result to the agent-facing CDP outcome. A failure + * names the Metro port that was used, so a wrong port (B5) is visible. + * + * @param outcome - The result of the persistent client or the one-shot call. + * @param metroPort - The Metro inspector proxy port the call used. + * @returns The CDP outcome. + */ +function toHermesCdpOutcome( + outcome: CdpOutcome, + metroPort: number, +): CdpOutcome { + if (outcome.ok) { + return outcome; + } + return { + ok: false, + code: + outcome.code === HERMES_BLOCKED_METHOD_CODE + ? ErrorCodes.MM_CDP_BLOCKED + : ErrorCodes.MM_CDP_FAILED, + message: `[${outcome.code}] ${outcome.message} (Metro port ${metroPort})`, + }; +} + /** * Projects a raw Metro Hermes target into the trimmed shape returned to agents. * diff --git a/src/platform/types.ts b/src/platform/types.ts index a0d34eff..83396d43 100644 --- a/src/platform/types.ts +++ b/src/platform/types.ts @@ -93,6 +93,20 @@ export type ScreenCapture = { getTestIds(limit?: number): Promise; }; +/** + * Hermes defaults of a mobile session, kept from the launch so `cdp` and + * `hermes-targets` do not fall back to another Metro port or device between + * calls. A per-call option still overrides them. + */ +export type HermesDefaults = { + /** Metro inspector proxy port of the session. */ + metroPort?: number; + /** Device the session runs on (informational). */ + deviceId?: string; + /** Hermes app bundle identifier of the session. */ + appId?: string; +}; + export type IPlatformDriver = { /** Release resources owned by this driver. Idempotent; does not shut down the device. */ dispose?(): Promise; @@ -249,5 +263,12 @@ export type IPlatformDriver = { hermesTargets?(input: HermesTargetsInput): Promise; + /** + * Mobile: keeps the session defaults for the Hermes tools (the launch Metro + * port, device and app id), so they apply to later calls without the caller + * passing them again. Browser drivers do not implement it. + */ + setHermesDefaults?(defaults: HermesDefaults): void; + generateLocators?(): Promise; }; diff --git a/src/tools/launch.test.ts b/src/tools/launch.test.ts index c8ef8bfb..5042e17e 100644 --- a/src/tools/launch.test.ts +++ b/src/tools/launch.test.ts @@ -254,6 +254,74 @@ describe('launchTool', () => { }); }); + describe('hermes session defaults', () => { + it('keeps the launch metroPort and device on the session driver', async () => { + const context = createMockContext({ hasActive: false }); + const setHermesDefaults = vi.fn(); + context.sessionManager.getPlatformDriver = () => + ({ setHermesDefaults }) as unknown as NonNullable< + ToolContext['driver'] + >; + + const result = await launchTool( + { platform: 'ios', metroPort: 8085, deviceId: 'UDID-1' }, + context, + ); + + expect(result.ok).toBe(true); + expect(setHermesDefaults).toHaveBeenCalledWith({ + metroPort: 8085, + deviceId: 'UDID-1', + }); + }); + + it('does not touch the driver when the launch sets no Hermes default', async () => { + const context = createMockContext({ hasActive: false }); + const setHermesDefaults = vi.fn(); + context.sessionManager.getPlatformDriver = () => + ({ setHermesDefaults }) as unknown as NonNullable< + ToolContext['driver'] + >; + + await launchTool({ stateMode: 'default' }, context); + + expect(setHermesDefaults).not.toHaveBeenCalled(); + }); + + it('works with a driver that has no Hermes defaults (browser)', async () => { + const context = createMockContext({ hasActive: false }); + context.sessionManager.getPlatformDriver = () => + ({}) as unknown as NonNullable; + + const result = await launchTool( + { platform: 'browser', metroPort: 8085 }, + context, + ); + + expect(result.ok).toBe(true); + }); + + it('does not apply defaults when the launch fails', async () => { + const context = createMockContext({ hasActive: false }); + const setHermesDefaults = vi.fn(); + context.sessionManager.getPlatformDriver = () => + ({ setHermesDefaults, dispose: vi.fn() }) as unknown as NonNullable< + ToolContext['driver'] + >; + vi.spyOn(context.sessionManager, 'launch').mockRejectedValue( + new Error('device failed'), + ); + + const result = await launchTool( + { platform: 'ios', metroPort: 8085 }, + context, + ); + + expect(result.ok).toBe(false); + expect(setHermesDefaults).not.toHaveBeenCalled(); + }); + }); + describe('session already running', () => { it('returns error when session already active', async () => { const context = createMockContext({ hasActive: true }); diff --git a/src/tools/launch.ts b/src/tools/launch.ts index c73d73a2..4d7fd770 100644 --- a/src/tools/launch.ts +++ b/src/tools/launch.ts @@ -2,6 +2,7 @@ import type { LaunchInput, LaunchPrerequisite, LaunchResult } from './types'; import { ErrorCodes } from './types'; import { createToolError, createToolSuccess } from './utils.js'; import { cleanupSession } from '../server/cleanup-session.js'; +import type { ISessionManager } from '../server/session-manager.js'; import type { ToolContext, ToolResponse } from '../types/http.js'; import { debugWarn, extractErrorMessage } from '../utils'; @@ -23,6 +24,28 @@ const PROD_MODE_PREREQUISITES: LaunchPrerequisite[] = [ }, ]; +/** + * Keeps the launch Metro port and device on the session's driver, so later + * `cdp` and `hermes-targets` calls use the launched target without passing a + * per-call flag (B5). Drivers that do not implement `setHermesDefaults` (the + * browser driver) are left alone. + * + * @param sessionManager - The session manager that owns the driver. + * @param input - The launch input. + */ +function applyHermesDefaults( + sessionManager: ISessionManager, + input: LaunchInput, +): void { + if (input.metroPort === undefined && input.deviceId === undefined) { + return; + } + sessionManager.getPlatformDriver?.()?.setHermesDefaults?.({ + ...(input.metroPort === undefined ? {} : { metroPort: input.metroPort }), + ...(input.deviceId === undefined ? {} : { deviceId: input.deviceId }), + }); +} + /** * Launches a new browser session with the configured extension. * @@ -72,6 +95,7 @@ export async function launchTool( } throw error; }); + applyHermesDefaults(sessionManager, input); const isProdMode = sessionManager.getEnvironmentMode() === 'prod'; return createToolSuccess({ diff --git a/src/tools/types/tool-outputs.ts b/src/tools/types/tool-outputs.ts index 791adf3f..574cf2b1 100644 --- a/src/tools/types/tool-outputs.ts +++ b/src/tools/types/tool-outputs.ts @@ -195,6 +195,7 @@ export type HermesTargetInfo = { }; export type HermesTargetsResult = { + /** The Metro port this report used (per-call override, else the session's). */ metroPort: number; expectedAppId: string; filterBypassed: boolean; @@ -204,6 +205,14 @@ export type HermesTargetsResult = { chosen?: { id?: string; logicalDeviceId?: string }; ambiguous?: string; noTargetReason?: { code: string; message: string }; + /** The Metro port the session keeps (the launch `--metro-port`). */ + sessionMetroPort?: number; + /** The pinned Hermes `logicalDeviceId` of the session, once a call pinned one. */ + pinnedDeviceId?: string; + /** Whether the persistent Hermes connection of the session is open. */ + connected?: boolean; + /** The device the session runs on, when the launch or consumer reported it. */ + deviceId?: string; }; export type GetWindowSizeResult = { From 191675a980fbd3add770dad62dd04aef4993d488 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Mon, 16 Nov 2026 17:46:04 +0000 Subject: [PATCH 2/2] chore: drop manual CHANGELOG entries The changelog is generated when a release is created. --- CHANGELOG.md | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5324579c..d195c9dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,30 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -### Added - -- feat: `MobilePlatformDriver` options `metroPort`, `deviceId` and `appId` keep the session's Metro port, device and Hermes app id on the driver, and `IPlatformDriver.setHermesDefaults` lets the launch apply `--metro-port` / `--device-id` after a successful mobile launch; `mm hermes-targets` now reports `sessionMetroPort`, `pinnedDeviceId`, `connected` and `deviceId`. -- feat: `mm cdp --target sw` sends CDP commands to the browser Extension's background service worker, and browser CDP sessions are now persistent per target (active page, service worker) instead of one-shot, so enabled domains and listeners survive across calls; a dead session (page or service-worker restart) is re-attached on the next call. New `mm cdp --fresh` keeps the old one-shot session, detached after the command. Browser and mobile reject the other platform's `--target` values with `MM_INVALID_INPUT`. -- feat: an observation that exceeds `OBSERVATION_TIMEOUT_MS` (8 s) no longer costs the call. The action response stays `ok` and carries `observations: { timedOut: true }` with no tree, and the timed-out observation does not replace the diff baseline, so the agent knows the screen was not read -- feat: add `MM_QUEUE_TIMEOUT`. When the daemon's request queue expires it now returns a normal `{ok:false,error}` tool response (not HTTP 500 `TOOL_EXECUTION_FAILED`), mapped to exit 5, not retryable, with the state-unknown hint; `RequestQueue` rejects a dedicated `QueueTimeoutError` - -### Changed - -- Mobile `mm cdp` keeps one persistent Hermes connection per session (Metro port and app id) and reuses it across calls instead of opening one WebSocket per call; a per-call `--metro-port` / `--app-id` that differs from the session's uses a one-shot connection, and the device pin still persists per session. Needs a device-mcp release with `HermesClient`; with device-mcp 0.7.0 each call opens its own connection. -- One timeout budget end to end. A shared `resolveActionTimeoutMs()`, `resolveBatchActionTimeoutMs()` and `computeTimeoutBudget()` give every layer a nesting budget (`http > queue > action + observation`): the CLI derives its HTTP abort from the same action budget as the daemon queue, and from the daemon queue default for tools with no action budget. The daemon publishes that default in `.mm-server` (`requestTimeoutMs`, absent in older state files) and the CLI nests above it, so it no longer aborts before the daemon answers. `run_steps` also budgets for its slowest step, because it checks its deadline only between steps. Timeout defaults after this change (daemon queue default 30 s, or 180 s when the host sets `requestTimeoutMs` as the Mobile workflow does); none is shorter than the time the daemon may take: - - `click`, `type`, `get_text`, `inspect`, `hover`, `wait_for`: the daemon queue already derived from the zod default (25 s) before this change; the CLI abort goes from the flat 30 s to 32 s. - - `cdp`: CLI 35 s → 47 s (queue 40 s, unchanged). `wait_for_notification`: CLI 30 s → 32 s (queue 25 s, unchanged). - - `run_steps` with `batchTimeoutMs`: the daemon queue is the batch deadline plus the slowest step's own timeout plus the observation, and never less than its queue default; the CLI adds the settle wait and a margin. Before, both used 30 s (180 s on Mobile), so a step slower than the batch deadline hit `MM_QUEUE_TIMEOUT` and the partial results were lost. - - `run_steps` without `batchTimeoutMs`: CLI 30 s → 37 s (187 s with a 180 s daemon queue); the queue is unchanged. `run_steps` now ignores a top-level `timeoutMs`, which the daemon schema strips anyway. - - `navigate`, `describe_screen`, `screenshot` and the other tools without an action budget: CLI 30 s → 37 s (187 s on Mobile), so the abort nests above the queue default plus its settle wait. `launch` is `max(120 s, 37 s)` = 120 s (187 s on Mobile); `cleanup` 30 s → 37 s (187 s on Mobile). - - Browser `scroll_to_element`: daemon queue 30 s → 25 s (action 15 s + observation 8 s + 2 s margin), so it still covers the action and its observation; the CLI is 37 s (32 s before) and takes the larger value because mobile keeps the queue default. - - An explicit `--timeout` on an interaction command keeps the same derived abort as before (19 s for `--timeout 2000`). For `cdp` and `wait-for-notification` the CLI abort now derives from the action budget too: `cdp --timeout 1000` 35 s → 18 s, `wait-for-notification --timeout 1000` 30 s → 18 s; both still nest above the daemon queue. - -### Fixed - -- Mobile `mm cdp` and `mm hermes-targets` keep the `--metro-port` given at launch. Before, a later command without `--metro-port` fell back to `HERMES_METRO_PORT` or 8081, so it could not connect when Metro ran on another port. A per-call `--metro-port` still wins, and a CDP connection failure now names the Metro port it tried. -- Mobile observations retry a screen that is still tearing down after a navigating tap (Android: the old screen, half removed, still carried the previous screen's test IDs). One extra snapshot is allowed when the new tree lost a large part of its nodes but kept the last screen's test IDs; a tap that does not change the screen still costs the same single retry, and the diff stays empty. - ## [0.14.0] ### Added