diff --git a/README.md b/README.md
index 4011f4d0..6410075b 100644
--- a/README.md
+++ b/README.md
@@ -245,7 +245,7 @@ type ISessionManager = {
Core captures `sessionManager.getPlatformDriver?.()` before calling the consumer's `cleanup()`, then calls the driver's optional `dispose()` hook. Disposal runs even when consumer cleanup fails. This applies to `mm cleanup`, forced relaunch, failed launch, daemon shutdown, and server startup rollback. A failed disposal fails that cleanup call and is retained for a later attempt. The daemon owns that retention (one per `createServer` instance), so a later `mm cleanup`, forced relaunch, or daemon stop retries it, whatever wrapper of the session manager a tool receives. Only the current session's cleanup and disposal can fail a call. Drivers retained from earlier sessions are retried best-effort and in parallel. When they fail again, the daemon writes a `[WARN]` line to its log, and the current cleanup or launch continues. Tools reach this retention through `ToolContext.cleanupSession()`; without it (a context built outside the daemon), the tools fall back to retention per session-manager object.
-`MobilePlatformDriver.dispose()` delegates to its backend's optional `dispose()` hook. Core requires `@metamask/device-mcp` 0.8.0 or later. On iOS, the device-mcp `IdbBackend` uses a private IDB companion per backend, and disposal stops only that backend's companion and recording. The ADB backend has no disposal hook, so disposal does nothing on Android. The consumer must create its backend from device-mcp 0.8.0 or later to get companion teardown.
+`MobilePlatformDriver.dispose()` delegates to its backend's optional `dispose()` hook. Core depends on `@metamask/device-mcp` ^0.9.0, so the consumer must create its backend from the same ^0.9.0 range: the Android fixes and the `dispose()` hook live in the consumer's copy of device-mcp. On iOS, the device-mcp `IdbBackend` uses a private IDB companion per backend, and disposal stops only that backend's companion and recording. The ADB backend has no disposal hook, so disposal does nothing on Android.
Consumers must expose a session-owned driver through `getPlatformDriver()` and create a fresh driver/backend for each launch. If launch fails before the driver is exposed, the consumer must dispose that locally held driver in its own failure path. Direct calls to a consumer's `cleanup()` also remain the consumer's responsibility.
@@ -710,7 +710,7 @@ The `params-json` argument must be a valid JSON object. The `--timeout` flag set
| 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`. `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.
+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. The session keeps one Hermes connection for its Metro port and app id and reuses it across calls.
```bash
# Mobile (Hermes) — the session keeps the launch Metro port
diff --git a/SKILL.md b/SKILL.md
index c9005976..3298d622 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -337,7 +337,7 @@ If the page closes after clicking (e.g., confirmation popup), the response inclu
**Browser hidden checkbox or radio:** toggles often keep the real ` ` (and its test id) at 1×1 pixel under decorative elements, for example `mm click --testid basic-functionality-toggle`. When the target is such an input and it has one label (a wrapping `` or ``), the label is clicked instead, which toggles the input, and the response includes `clickedLabel: true`. A hidden input without a label, or whose label has a link or button inside (for example "I agree to the terms"), is clicked as before.
-**Mobile:** before tapping, iOS hit-tests the tap point. When another element is on top of the target (the keyboard, a sheet, an overlay), nothing is tapped and the click fails with `MM_TARGET_OBSCURED`; the message names the covering element. A target outside the screen fails with `MM_TARGET_NOT_VISIBLE` (run `mm scroll-to-element` first). `--dismiss-keyboard` closes the keyboard when it is the cover and taps once more (the result has `keyboardDismissed: true`). With an observation (not `--observe none`) the result has `screenChanged`: `false` means the screen looks the same as before the click; that is normal for some taps (the open tab) but a hint for a button that should navigate.
+**Mobile:** before tapping, the device hit-tests the tap point (iOS; Android with device-mcp 0.9.0 and later). When another element is on top of the target (the keyboard, a sheet, an overlay), nothing is tapped and the click fails with `MM_TARGET_OBSCURED`; the message names the covering element. A target outside the screen fails with `MM_TARGET_NOT_VISIBLE` (run `mm scroll-to-element` first). `--dismiss-keyboard` closes the keyboard when it is the cover and taps once more (the result has `keyboardDismissed: true`). With an observation (not `--observe none`) the result has `screenChanged`: `false` means the screen looks the same as before the click; that is normal for some taps (the open tab) but a hint for a button that should navigate.
```
mm click --testid log-in-button --dismiss-keyboard
@@ -736,7 +736,7 @@ 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.
+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. The session keeps one Hermes connection for its Metro port and app id and reuses it across calls. 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.
@@ -771,7 +771,7 @@ Taps raw screen coordinates. Prefer element targeting when possible.
#### `mm dismiss-keyboard`
-Dismisses the on-screen keyboard.
+Dismisses the on-screen keyboard. On Android it then checks that the keyboard is gone, and fails with `MM_DEVICE_ACTION_FAILED` when it is still shown.
#### `mm dismiss-alert [--accept]`
diff --git a/package.json b/package.json
index 1e9dde7e..6abd0aeb 100644
--- a/package.json
+++ b/package.json
@@ -62,7 +62,7 @@
"hono": "^4.12.25"
},
"dependencies": {
- "@metamask/device-mcp": "^0.8.0",
+ "@metamask/device-mcp": "^0.9.0",
"cosmiconfig": "^9.0.0",
"express": "^5.2.1",
"zod": "^4.4.3"
diff --git a/src/platform/mobile-platform-driver.hermes-port.test.ts b/src/platform/mobile-platform-driver.hermes-port.test.ts
index 014f274d..8cd64ca6 100644
--- a/src/platform/mobile-platform-driver.hermes-port.test.ts
+++ b/src/platform/mobile-platform-driver.hermes-port.test.ts
@@ -4,7 +4,6 @@ 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
@@ -15,7 +14,7 @@ vi.mock('./device-mcp-runtime.js', async () => {
loadDeviceMcp: async () => ({
...actual,
runHermesCdp: mocks.runHermesCdp,
- HermesClient: mocks.hasHermesClient ? mocks.HermesClient : undefined,
+ HermesClient: mocks.HermesClient,
}),
};
});
@@ -47,7 +46,6 @@ 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,
diff --git a/src/platform/mobile-platform-driver.hermes.test.ts b/src/platform/mobile-platform-driver.hermes.test.ts
index e408c7bb..ab2b2b64 100644
--- a/src/platform/mobile-platform-driver.hermes.test.ts
+++ b/src/platform/mobile-platform-driver.hermes.test.ts
@@ -11,9 +11,6 @@ const mocks = vi.hoisted(() => ({
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.
@@ -26,7 +23,7 @@ vi.mock('./device-mcp-runtime.js', () => ({
LEGACY_SYNTHETIC_TITLE:
'React Native Experimental (Improved Chrome Reloads)',
HermesSession: mocks.HermesSession,
- ...(mocks.hasHermesClient ? { HermesClient: mocks.HermesClient } : {}),
+ HermesClient: mocks.HermesClient,
}),
}));
@@ -40,19 +37,23 @@ function createBackend(
return { platform, ...overrides } as unknown as DeviceBackend;
}
+// The cdp calls in this describe pass a per-call metroPort that differs from
+// the session target, so they take the one-shot path; the persistent client
+// has its own describe.
describe('MobilePlatformDriver hermes delegation', () => {
beforeEach(() => {
- mocks.hasHermesClient = false;
mocks.HermesSession.mockImplementation(() => ({
resolve: mocks.resolve,
getPinnedHermesDeviceId: mocks.getPinnedHermesDeviceId,
setPinnedHermesDeviceId: mocks.setPinnedHermesDeviceId,
}));
- mocks.resolve.mockReturnValue({
- metroPort: 8081,
- appId: 'io.metamask',
- pinnedDeviceId: undefined,
- });
+ mocks.resolve.mockImplementation(
+ ({ metroPort, appId }: { metroPort?: number; appId?: string }) => ({
+ metroPort: metroPort ?? 8081,
+ appId: appId ?? 'io.metamask',
+ pinnedDeviceId: mocks.getPinnedHermesDeviceId(),
+ }),
+ );
mocks.getPinnedHermesDeviceId.mockReturnValue(undefined);
});
@@ -67,9 +68,21 @@ describe('MobilePlatformDriver hermes delegation', () => {
// Created on first use (device-mcp is loaded lazily), once per driver.
expect(mocks.HermesSession).not.toHaveBeenCalled();
- await iosDriver.cdp({ method: 'Runtime.evaluate', timeoutMs: 1000 });
- await iosDriver.cdp({ method: 'Runtime.evaluate', timeoutMs: 1000 });
- await androidDriver.cdp({ method: 'Runtime.evaluate', timeoutMs: 1000 });
+ await iosDriver.cdp({
+ method: 'Runtime.evaluate',
+ timeoutMs: 1000,
+ metroPort: 8087,
+ });
+ await iosDriver.cdp({
+ method: 'Runtime.evaluate',
+ timeoutMs: 1000,
+ metroPort: 8087,
+ });
+ await androidDriver.cdp({
+ method: 'Runtime.evaluate',
+ timeoutMs: 1000,
+ metroPort: 8087,
+ });
expect(mocks.HermesSession).toHaveBeenCalledTimes(2);
expect(mocks.HermesSession).toHaveBeenNthCalledWith(1, {
@@ -85,8 +98,16 @@ describe('MobilePlatformDriver hermes delegation', () => {
const driver = new MobilePlatformDriver(createBackend('ios'));
await Promise.all([
- driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 1000 }),
- driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 1000 }),
+ driver.cdp({
+ method: 'Runtime.evaluate',
+ timeoutMs: 1000,
+ metroPort: 8087,
+ }),
+ driver.cdp({
+ method: 'Runtime.evaluate',
+ timeoutMs: 1000,
+ metroPort: 8087,
+ }),
]);
expect(mocks.HermesSession).toHaveBeenCalledTimes(1);
@@ -106,6 +127,7 @@ describe('MobilePlatformDriver hermes delegation', () => {
method: 'Runtime.evaluate',
params: { expression: '1+1' },
timeoutMs: 30_000,
+ metroPort: 8087,
});
expect(mocks.resolve).toHaveBeenCalledWith({
@@ -118,7 +140,7 @@ describe('MobilePlatformDriver hermes delegation', () => {
method: 'Runtime.evaluate',
params: { expression: '1+1' },
timeoutMs: 30_000,
- metroPort: 8081,
+ metroPort: 8087,
appId: 'io.metamask',
pinnedDeviceId: undefined,
}),
@@ -133,7 +155,11 @@ describe('MobilePlatformDriver hermes delegation', () => {
});
const driver = new MobilePlatformDriver(createBackend());
- await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 });
+ await driver.cdp({
+ method: 'Runtime.evaluate',
+ timeoutMs: 30_000,
+ metroPort: 8087,
+ });
expect(mocks.setPinnedHermesDeviceId).toHaveBeenCalledWith('device-42');
});
@@ -146,7 +172,11 @@ describe('MobilePlatformDriver hermes delegation', () => {
});
const driver = new MobilePlatformDriver(createBackend());
- await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 });
+ await driver.cdp({
+ method: 'Runtime.evaluate',
+ timeoutMs: 30_000,
+ metroPort: 8087,
+ });
expect(mocks.setPinnedHermesDeviceId).not.toHaveBeenCalled();
});
@@ -163,6 +193,7 @@ describe('MobilePlatformDriver hermes delegation', () => {
const outcome = await driver.cdp({
method: 'Runtime.terminateExecution',
timeoutMs: 30_000,
+ metroPort: 8087,
});
expect(outcome.ok).toBe(false);
@@ -183,6 +214,7 @@ describe('MobilePlatformDriver hermes delegation', () => {
const outcome = await driver.cdp({
method: 'Runtime.evaluate',
timeoutMs: 30_000,
+ metroPort: 8087,
});
expect(outcome.ok).toBe(false);
@@ -411,7 +443,6 @@ describe('MobilePlatformDriver hermes delegation', () => {
describe('MobilePlatformDriver webview cdp routing', () => {
beforeEach(() => {
- mocks.hasHermesClient = false;
mocks.HermesSession.mockImplementation(() => ({
resolve: mocks.resolve,
getPinnedHermesDeviceId: mocks.getPinnedHermesDeviceId,
@@ -450,11 +481,13 @@ describe('MobilePlatformDriver webview cdp routing', () => {
});
it('defaults to the Hermes path when target is omitted', async () => {
- mocks.resolve.mockReturnValue({
- metroPort: 8081,
- appId: 'io.metamask',
- pinnedDeviceId: undefined,
- });
+ mocks.resolve.mockImplementation(
+ ({ metroPort, appId }: { metroPort?: number; appId?: string }) => ({
+ metroPort: metroPort ?? 8081,
+ appId: appId ?? 'io.metamask',
+ pinnedDeviceId: undefined,
+ }),
+ );
mocks.getPinnedHermesDeviceId.mockReturnValue(undefined);
mocks.runHermesCdp.mockResolvedValue({ ok: true, result: { value: 2 } });
const webviewCdp = vi.fn();
@@ -462,7 +495,13 @@ describe('MobilePlatformDriver webview cdp routing', () => {
createBackend('android', { webviewCdp }),
);
- await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 });
+ // A per-call port differs from the session target, so this takes the
+ // one-shot path; the omitted target still routes to Hermes.
+ await driver.cdp({
+ method: 'Runtime.evaluate',
+ timeoutMs: 30_000,
+ metroPort: 8087,
+ });
expect(mocks.runHermesCdp).toHaveBeenCalledTimes(1);
expect(webviewCdp).not.toHaveBeenCalled();
@@ -578,7 +617,6 @@ describe('MobilePlatformDriver persistent Hermes client', () => {
beforeEach(() => {
clients.length = 0;
- mocks.hasHermesClient = true;
mocks.HermesSession.mockImplementation(() => ({
resolve: mocks.resolve,
getPinnedHermesDeviceId: mocks.getPinnedHermesDeviceId,
@@ -610,7 +648,6 @@ describe('MobilePlatformDriver persistent Hermes client', () => {
afterEach(() => {
vi.clearAllMocks();
- mocks.hasHermesClient = false;
});
it('creates one client for the session port and reuses it across calls', async () => {
@@ -823,25 +860,6 @@ describe('MobilePlatformDriver persistent Hermes client', () => {
}
});
- 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',
diff --git a/src/platform/mobile-platform-driver.test.ts b/src/platform/mobile-platform-driver.test.ts
index 1a93960d..6de4f246 100644
--- a/src/platform/mobile-platform-driver.test.ts
+++ b/src/platform/mobile-platform-driver.test.ts
@@ -1,3 +1,4 @@
+import { TargetObscuredError } from '@metamask/device-mcp';
import type { DeviceBackend, UIElement } from '@metamask/device-mcp';
import { describe, it, expect, vi, afterEach } from 'vitest';
@@ -558,6 +559,51 @@ describe('MobilePlatformDriver', () => {
expect(backend.tapElement).toHaveBeenCalledTimes(2);
});
+ it('dismisses the keyboard for the Android TargetObscuredError of device-mcp', async () => {
+ const target = makeElement({ identifier: 'sheet-header-close-button' });
+ const keyboardError = new TargetObscuredError(
+ target,
+ makeElement({ type: 'android.widget.FrameLayout' }),
+ { x: 50, y: 22 },
+ {
+ keyboard: true,
+ obscuredByDescription: 'android.widget.FrameLayout',
+ },
+ );
+ const backend = createMockBackend({
+ platform: 'android',
+ waitForElement: vi.fn().mockResolvedValue(target),
+ tapElement: vi
+ .fn()
+ .mockRejectedValueOnce(keyboardError)
+ .mockResolvedValueOnce({
+ success: true,
+ x: 50,
+ y: 22,
+ targetDescription: '',
+ }),
+ });
+ const driver = new MobilePlatformDriver(backend);
+
+ const result = await driver.click(
+ 'testId',
+ 'sheet-header-close-button',
+ new Map(),
+ 5000,
+ undefined,
+ undefined,
+ { dismissKeyboard: true },
+ );
+
+ expect(result).toStrictEqual({
+ clicked: true,
+ target: 'testId:sheet-header-close-button',
+ keyboardDismissed: true,
+ });
+ expect(backend.dismissKeyboard).toHaveBeenCalledTimes(1);
+ expect(backend.tapElement).toHaveBeenCalledTimes(2);
+ });
+
it('does not tap again when the request is aborted while dismissing', async () => {
const controller = new AbortController();
const backend = createMockBackend({
@@ -1101,6 +1147,31 @@ describe('MobilePlatformDriver', () => {
expect(refMap.get('e2')).toBe('label:Email|type:TextField');
});
+ it('reads a snapshot that has device-mcp warnings and does not report them', async () => {
+ const backend = createMockBackend({
+ snapshot: vi.fn().mockResolvedValue({
+ platform: 'ios',
+ hierarchy: [makeElement({ label: 'Submit', identifier: 'submit' })],
+ raw: '[]',
+ timestamp: Date.now(),
+ warnings: ['ax-tree-truncated(backend=axbridge,depth=60,nodes=900)'],
+ }),
+ });
+ const driver = new MobilePlatformDriver(backend);
+
+ const capture = await driver.captureScreen();
+
+ expect(Object.keys(capture).sort()).toStrictEqual([
+ 'getTestIds',
+ 'nodes',
+ 'refMap',
+ ]);
+ expect(capture.nodes.map(({ testId }) => testId)).toStrictEqual([
+ 'submit',
+ ]);
+ expect(await capture.getTestIds()).toHaveLength(1);
+ });
+
it('omits bounds for elements with zero-size frames', async () => {
const backend = createMockBackend({
snapshot: vi.fn().mockResolvedValue({
diff --git a/src/platform/mobile-platform-driver.ts b/src/platform/mobile-platform-driver.ts
index 46d61542..d1d9340b 100644
--- a/src/platform/mobile-platform-driver.ts
+++ b/src/platform/mobile-platform-driver.ts
@@ -1,6 +1,7 @@
import type {
DeviceBackend,
ElementQuery,
+ HermesClient,
HermesSession,
HermesSessionResolved,
HermesTarget,
@@ -86,51 +87,6 @@ export type MobilePlatformDriverOptions = {
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;
-};
-
/**
* Platform driver for mobile devices backed by @metamask/device-mcp.
* Wraps DeviceBackend behind the IPlatformDriver interface so the
@@ -153,7 +109,7 @@ export class MobilePlatformDriver implements IPlatformDriver {
// 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;
+ #hermesClient: HermesClient | undefined;
// Session defaults kept from the launch (or the driver options). Undefined
// leaves the choice to device-mcp: env `HERMES_METRO_PORT` /
@@ -254,20 +210,22 @@ export class MobilePlatformDriver implements IPlatformDriver {
/**
* 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.
+ * use. Returns undefined when the cached client was built for another
+ * target: the caller then uses the one-shot path, so the client is never
+ * retargeted. The client is created without `trackContexts` and without
+ * listeners, so it never sends `Runtime.enable`.
*
* @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.
+ * @returns The client, or undefined when the cached client is for another
+ * target.
*/
#getHermesClient(
runtime: DeviceMcpRuntime,
session: HermesSession,
target: HermesSessionResolved,
- ): HermesClientLike | undefined {
+ ): HermesClient | undefined {
const existing = this.#hermesClient;
if (existing) {
return existing.metroPort === target.metroPort &&
@@ -275,11 +233,8 @@ export class MobilePlatformDriver implements IPlatformDriver {
? existing
: undefined;
}
- const Client = (runtime as HermesClientRuntime).HermesClient;
- if (typeof Client !== 'function') {
- return undefined;
- }
- const client = new (Client as HermesClientConstructor)({
+ const { HermesClient: Client } = runtime;
+ const client = new Client({
metroPort: target.metroPort,
appId: target.appId,
pinnedDeviceId: target.pinnedDeviceId,
@@ -860,8 +815,7 @@ export class MobilePlatformDriver implements IPlatformDriver {
* 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.
+ * so the persistent client is never retargeted.
*
* @param input - The CDP command input.
* @returns A discriminated CDP outcome. A failure names the Metro port used.
@@ -892,8 +846,7 @@ export class MobilePlatformDriver implements IPlatformDriver {
/**
* 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`.
+ * call whose target differs from the session's.
*
* @param runtime - The loaded device-mcp module.
* @param session - This driver's Hermes session.
diff --git a/src/tools/device.test.ts b/src/tools/device.test.ts
index 71ed418e..a86c93bb 100644
--- a/src/tools/device.test.ts
+++ b/src/tools/device.test.ts
@@ -638,6 +638,24 @@ describe('dismissKeyboardTool', () => {
}
});
+ it('returns MM_DEVICE_ACTION_FAILED when the Android keyboard stays shown', async () => {
+ const message =
+ 'Keyboard still shown after ESCAPE and BACK. ' +
+ 'Use device_snapshot to inspect the current UI hierarchy.';
+ const dismissKeyboard = vi.fn().mockRejectedValue(new Error(message));
+ const context = createContext({ driver: { dismissKeyboard } });
+
+ const result = await dismissKeyboardTool({}, context);
+
+ expect(result).toStrictEqual({
+ ok: false,
+ error: expect.objectContaining({
+ code: ErrorCodes.MM_DEVICE_ACTION_FAILED,
+ message: `Dismissing keyboard failed: ${message}`,
+ }),
+ });
+ });
+
it('returns MM_DEVICE_ACTION_FAILED when the driver throws', async () => {
const dismissKeyboard = vi.fn().mockRejectedValue(new Error('kb boom'));
const context = createContext({ driver: { dismissKeyboard } });
diff --git a/src/tools/error-classification.test.ts b/src/tools/error-classification.test.ts
index 3cb07e52..dab08614 100644
--- a/src/tools/error-classification.test.ts
+++ b/src/tools/error-classification.test.ts
@@ -4,6 +4,7 @@
* Tests error pattern matching and classification for various tool handlers.
*/
+import { TargetObscuredError } from '@metamask/device-mcp';
import { describe, it, expect } from 'vitest';
import {
@@ -254,6 +255,38 @@ describe('error-classification', () => {
});
});
+ it('maps the Android keyboard TargetObscuredError of device-mcp to MM_TARGET_OBSCURED', () => {
+ const error = new TargetObscuredError(
+ {
+ type: 'android.widget.Button',
+ identifier: 'sheet-header-close-button',
+ frame: { x: 0, y: 2000, width: 100, height: 44 },
+ enabled: true,
+ },
+ {
+ type: 'android.widget.FrameLayout',
+ frame: { x: 0, y: 1500, width: 1080, height: 900 },
+ enabled: true,
+ },
+ { x: 50, y: 2022 },
+ {
+ keyboard: true,
+ obscuredByDescription: 'android.widget.FrameLayout',
+ },
+ );
+
+ expect(
+ classifyInteractionError(error, ErrorCodes.MM_CLICK_FAILED),
+ ).toStrictEqual({
+ code: ErrorCodes.MM_TARGET_OBSCURED,
+ message:
+ 'TARGET_OBSCURED: android.widget.Button id="sheet-header-close-button" ' +
+ 'is covered at (50, 2022) by the keyboard: android.widget.FrameLayout. ' +
+ 'Nothing was tapped. ' +
+ 'Dismiss the keyboard (device_dismiss_keyboard) and retry.',
+ });
+ });
+
it('maps ELEMENT_NOT_IN_VIEWPORT to MM_TARGET_NOT_VISIBLE', () => {
const error = Object.assign(
new Error('Element is outside the 1080x2400 viewport'),
diff --git a/yarn.lock b/yarn.lock
index 71e68f41..6445e589 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -926,7 +926,7 @@ __metadata:
"@lavamoat/allow-scripts": "npm:^3.0.4"
"@lavamoat/preinstall-always-fail": "npm:^2.0.0"
"@metamask/auto-changelog": "npm:^5.3.0"
- "@metamask/device-mcp": "npm:^0.8.0"
+ "@metamask/device-mcp": "npm:^0.9.0"
"@metamask/eslint-config": "npm:^15.0.0"
"@metamask/eslint-config-nodejs": "npm:^15.0.0"
"@metamask/eslint-config-typescript": "npm:^15.0.0"
@@ -968,15 +968,15 @@ __metadata:
languageName: unknown
linkType: soft
-"@metamask/device-mcp@npm:^0.8.0":
- version: 0.8.0
- resolution: "@metamask/device-mcp@npm:0.8.0"
+"@metamask/device-mcp@npm:^0.9.0":
+ version: 0.9.0
+ resolution: "@metamask/device-mcp@npm:0.9.0"
dependencies:
"@modelcontextprotocol/sdk": "npm:^1.32.0"
zod: "npm:^4.6.6"
bin:
device-mcp: ./dist/cli/device-mcp.mjs
- checksum: 10/92e0321ec1edfd9c686ce786ee29b87cb35f0af8e14d5ea90d355d9db18a50bb325a32e7042cade447ae61c8d540c8556481c6f5f0eadc343501173f9affb186
+ checksum: 10/edffb339e331a1b2f7ad175ca24d277dfc08e75d4f7e7dcf14a1c72ab0abb659783e4025b72934386af135d0b9cbaabaa2ba2962336f0b646b29a29d51b5bdf5
languageName: node
linkType: hard