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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 45 additions & 39 deletions README.md

Large diffs are not rendered by default.

14 changes: 10 additions & 4 deletions SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand All @@ -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 <p>] [--app-id <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
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type {
PlatformScreenshotOptions,
ScreenCapture,
MobilePlatformDriverOptions,
HermesDefaults,
} from './platform';
export { PlaywrightPlatformDriver, MobilePlatformDriver } from './platform';

Expand Down
1 change: 1 addition & 0 deletions src/platform/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type {
WithinScope,
IPlatformDriver,
ScreenCapture,
HermesDefaults,
} from './types.js';

export { PlaywrightPlatformDriver } from './playwright-driver.js';
Expand Down
190 changes: 190 additions & 0 deletions src/platform/mobile-platform-driver.hermes-port.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof vi.fn>;
close: ReturnType<typeof vi.fn>;
};

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',
});
});
});
Loading
Loading