diff --git a/README.md b/README.md index 62ffc5bd..a6d7017b 100644 --- a/README.md +++ b/README.md @@ -624,14 +624,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 @@ -679,13 +679,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. Add `"record":{"body":true}` to a rule to record the bodies of the requests it matches. A rule with `record` and no `response` forwards the real request unchanged. | -| `mm mock-network clear` | Clears route mocks and recorded requests. | -| `mm mock-network list` | Lists active route mocks. | -| `mm mock-network requests [--limit ] [--url ] [--bodies]` | Shows recorded matched and missed requests. `--url` keeps only matching URLs. `--bodies` adds the recorded (redacted) request bodies and headers. | -| `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. Add `"record":{"body":true}` to a rule to record the bodies of the requests it matches. A rule with `record` and no `response` forwards the real request unchanged. | +| `mm mock-network clear` | Clears route mocks and recorded requests. | +| `mm mock-network list` | Lists active route mocks. | +| `mm mock-network requests [--limit ] [--url ] [--bodies]` | Shows recorded matched and missed requests. `--url` keeps only matching URLs. `--bodies` adds the recorded (redacted) request bodies and headers. | +| `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"}' @@ -701,27 +701,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 @@ -732,17 +736,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 8681452e..f8cc991c 100644 --- a/SKILL.md +++ b/SKILL.md @@ -700,7 +700,11 @@ 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 @@ -715,8 +719,8 @@ mm cdp Runtime.evaluate '{"expression":"document.querySelector(\'#personalSign\' | `--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. | +| `--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. @@ -730,11 +734,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 f69df301..e408c7bb 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, @@ -405,6 +411,7 @@ describe('MobilePlatformDriver hermes delegation', () => { describe('MobilePlatformDriver webview cdp routing', () => { beforeEach(() => { + mocks.hasHermesClient = false; mocks.HermesSession.mockImplementation(() => ({ resolve: mocks.resolve, getPinnedHermesDeviceId: mocks.getPinnedHermesDeviceId, @@ -550,3 +557,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 bfc8a1cd..46d61542 100644 --- a/src/platform/mobile-platform-driver.ts +++ b/src/platform/mobile-platform-driver.ts @@ -2,11 +2,13 @@ import type { DeviceBackend, ElementQuery, HermesSession, + HermesSessionResolved, HermesTarget, ScrollToElementResult, UIElement, } from '@metamask/device-mcp'; +import type { DeviceMcpRuntime } from './device-mcp-runtime.js'; import { loadDeviceMcp } from './device-mcp-runtime.js'; import { filterAppHierarchy, @@ -16,6 +18,7 @@ import { import type { Viewport } from './mobile-hierarchy.js'; import type { IPlatformDriver, + HermesDefaults, TargetType, ClickActionResult, ClickOptions, @@ -66,6 +69,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; }; /** @@ -85,6 +148,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; @@ -99,6 +179,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, @@ -108,6 +191,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(); + } } /** @@ -122,6 +230,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 @@ -129,6 +320,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; @@ -662,21 +854,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, @@ -684,23 +916,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}`, - }; } /** @@ -743,6 +964,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. @@ -756,12 +979,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 { @@ -778,6 +1007,7 @@ export class MobilePlatformDriver implements IPlatformDriver { metroDown: true, targetsDiscovered: 0, candidates: [], + ...sessionFields, }; } throw error; @@ -801,6 +1031,7 @@ export class MobilePlatformDriver implements IPlatformDriver { metroDown: false, targetsDiscovered: targets.length, candidates: displayCandidates.map(toHermesTargetInfo), + ...sessionFields, }; const selection = selectHermesTarget( @@ -845,6 +1076,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 bf7f1cea..18bba465 100644 --- a/src/platform/types.ts +++ b/src/platform/types.ts @@ -111,6 +111,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; @@ -287,5 +301,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 577ed7b7..b258ff8b 100644 --- a/src/tools/types/tool-outputs.ts +++ b/src/tools/types/tool-outputs.ts @@ -221,6 +221,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; @@ -230,6 +231,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 = {