Skip to content

feat: HermesClient, a persistent Hermes CDP connection - #54

Merged
cryptotavares merged 36 commits into
mainfrom
cryptotavares/mmcli-p2-02-persistent-hermes
Nov 19, 2026
Merged

cryptotavares merged 36 commits into
mainfrom
cryptotavares/mmcli-p2-02-persistent-hermes

Conversation

@cryptotavares

@cryptotavares cryptotavares commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Part of the mm CLI v2 effort (ticket P2-02, Tier 2). Ships in device-mcp 0.9.0. Core uses it in MetaMask/client-mcp-core#91.

Summary: New HermesClient keeps one verified Hermes CDP socket open for many calls and delivers CDP events. On Android, a Runtime.evaluate drops from 165 ms to 5 ms (p50). runHermesCdp now runs on the client.

Problem

runHermesCdp opens a new WebSocket for each call: a /json discovery fetch, a handshake and an identity probe every time. That costs about 165 ms per call on Android. A one-shot socket also cannot receive CDP events (Runtime.bindingCalled, Network.*, executionContextCreated), so callers cannot follow app reloads or listen for app events.

# 0.8.0: every call
runHermesCdp → GET /json → open WebSocket → identity probe → method → close

Solution

HermesClient (src/hermes/hermes-client.ts) does discovery, the safety checks and the identity probe once per socket, then sends many calls over it. It keeps every fail-closed check of the one-shot path: strict appId selection, the device pin, the WebSocket URL port check and the blocked methods.

  1. Calls: send(method, params, { timeoutMs, signal }) connects when needed. Responses are matched by id, so many calls can be in flight. timeoutMs limits each step on its own (each connect step, then the response). signal: AbortSignal.timeout(n) limits the total time.
  2. Events: on / off for CDP events and for the lifecycle events contextCreated, contextDestroyed, disconnected, reconnected, reconnectFailed and listenerError.
  3. Socket loss (Metro restart): pending calls fail and are not sent again, because they may have run. The client finds the target again and reconnects with backoff. If the loop gives up, it emits reconnectFailed, and the next failed send or connect starts the loop again.
  4. App reload: the socket stays open. With trackContexts: true (off by default), the client enables Runtime and reports the context change, so callers can apply their scripts again.
flowchart TD
    S["send(method)"] --> BL{"blocked method?"}
    BL -->|yes| XB[HERMES_BLOCKED_METHOD]
    BL -->|no| C{"socket open?"}
    C -->|yes| M[send on the open socket, match the response by id]
    C -->|no| D["discover target, check appId, pin and URL, identity probe"]
    D -->|fail| XC[classified failure, as in 0.8.0]
    D -->|ok| E["contextCreated (connect / reconnect)"]
    E --> M
    M --> R[result, HERMES_TIMEOUT or HERMES_ABORTED]
    L[socket lost] --> P[pending calls: HERMES_CONNECTION_FAILED, not resent]
    P --> B["reconnect with backoff: 250 ms doubling to 5 s, 6 attempts"]
    B --> D
    B -->|gave up| RF[reconnectFailed. The next failed send starts the loop again.]
    RL["app reload, same socket (trackContexts)"] --> CD["contextDestroyed, then contextCreated (reload)"]

    classDef new fill:#fff3cd,stroke:#d39e00
    classDef stop fill:#f8d7da,stroke:#c82333
    class C,M,E,R,L,P,B,RF,RL,CD new
    class XB,XC stop
Loading

Yellow boxes are new. Red boxes stop the call.

What changes

Caller 0.8.0 This PR
New: HermesClient – One socket for many calls, CDP events, reconnect, reload events (opt-in)
New exports – HermesClient, its option types, every event payload type (including HermesListenerErrorEvent and HermesReconnectFailedEvent), HermesCdpErrorInfo, HERMES_ABORTED
runHermesCdp, call timeout HERMES_CONNECTION_FAILED HERMES_TIMEOUT
runHermesCdp, malformed JSON frame Fails the call Ignored
runHermesCdp, socket closes mid-call … WebSocket closed before CDP response Hermes CDP connection closed: socket closed
runHermesCdp, everything else – Same checks, same wire traffic (probe and one method). No reconnect, no Runtime.enable.

No breaking changes to the exported API. Core 0.14.0 maps every Hermes failure except a blocked method to MM_CDP_FAILED and keeps the device-mcp code in the message, so only the code inside that message changes.

Decisions for reviewers

Decision Reason
Pending calls fail on socket loss and are not resent A call may already have run in the app. Running it twice is not safe.
Reconnect: 250 ms doubling to 5 s, 6 attempts, 10 s per attempt Covers a Metro restart. When the loop gives up, it emits reconnectFailed, so a client that only listens knows. A later failed send or connect restarts the loop from the first step.
A device-pin mismatch while reconnecting is retried. Only a missing WebSocket stops the loop for good. Target selection filters by the pin, so a mismatch never opens a socket. With two simulators, the pinned one can register after the other one.
A send while reconnecting never stops the reconnect loop, and each reconnect opens exactly one socket Fixes from review: a failed send used to stop the loop, and a disconnected listener that sent opened a second socket.
The first connect after a loss emits contextCreated { reason: 'reconnect' }, whatever started it Callers need one signal to apply their scripts again.
close() during a connect abandons it, and a later connect() starts a fresh one No pin is saved, onPin is not called, and the socket is closed. A reopen never joins the abandoned connect.
A send that joins a connect already in progress waits at most its own timeoutMs A short call must not wait for a background attempt's 10 s limit. A background attempt never gets a caller's shorter limit.
trackContexts is off by default While Runtime is enabled, Hermes sends every console.* call to the socket and keeps each logged object until Runtime.releaseObjectGroup. Core does not use reload events, so it must not pay for them.
A throwing listener is isolated and reported as listenerError One bad listener must not stop the delivery of events and responses.
runHermesCdp uses trackContexts: false and maxAttempts: 0 The one-shot path keeps its old wire traffic and cost.
hermes-cdp.ts and hermes-client.ts import each other The client reads the shared helpers only while it connects, never while the module loads. The comment at the top of hermes-cdp.ts explains this.

Review guide

Read the files in this order:

# File What to check
1 src/hermes/hermes-client.ts connect, send, close. Then #onSocketLost, the reconnect loop and the Runtime context events.
2 src/hermes/hermes-cdp.ts runHermesCdp on the client. The helpers that are now exported for the client.
3 src/index.ts New exports
4 src/hermes/hermes-client.test.ts Fake socket and fake timers: reconnect and give-up, abort, close and reopen during a connect, joined-connect timeouts, pin mismatch, reload, listener errors
Testing
  • yarn build, yarn lint and yarn test pass (38 files, 981 tests, 6 skipped). Coverage thresholds are unchanged. hermes-client.ts: 96% of lines, 89% of branches.
  • Bench: the built package, Metro, MetaMask Mobile dev build, read-only 1+1.
Check One-shot runHermesCdp HermesClient
Android, 10 calls in a row, p50 / p95 165 / 295 ms 5 / 14 ms (connect 45 ms)
iOS, same 2.5 / 4.2 ms 0.5 / 0.7 ms (connect 42 ms)
Android Page.reload on the same client (trackContexts: true) – contextDestroyed after 182 ms, contextCreated { reload } after 7.3 s, then 1+1 works again
Fake socket: send while Metro is down, then Metro returns – Reconnects by itself, one contextCreated { reconnect }
Fake socket: a disconnected listener that sends – One open socket, one contextCreated

- `tapElement(query, { element })`: tap an element the caller already
  resolved (core resolves it with `waitForElement`), so a click takes one
  snapshot instead of two. The viewport check still runs on iOS.
- iOS: cache `idb describe --json` (OS version for the describe-all API
  order, window size) per companion connection. It was read before every
  snapshot, tap and swipe (~0.25 s each). Cleared on (re)connect; a failed
  read is not cached; `getDeviceInfo()` still reads fresh.
The release PR generates them from the commit history.
getDeviceInfo replaced the cache with its pending read, so snapshots and
taps waited for it and failed with it, and a failed read emptied the cache.
Now a successful read replaces the cache (unless a reconnect happened
meanwhile); until then, and after a failure, the cached description is
used.
…ving

Callers tap the returned frame without a new snapshot. An element that
appears during the wait can still be animating in (a sheet sliding up), so
it is read again until its frame is the same in two reads in a row (at most
3 extra reads, within the timeout). An element already on screen at the
first read is returned at once, as before. Shared by the idb, adb and
Appium backends.
idb ui key takes integer HID codes only, so RETURN/HOME/LOCK/DELETE and
key-sequence cmd+a all failed. pressButton and dismissKeyboard always
threw on iOS, and typeText's clear failed silently (non-strict exec) so
retyping appended to the old value.

- enter -> ui key 40; home/lock -> ui button HOME|LOCK
- back -> throw UNSUPPORTED_ON_IOS (was HOME, which backgrounded the app)
- dismissKeyboard presses Return only when a Keyboard element is shown
- typeText clears with ui key 4 --command + ui key 42, strict
- drop the now-unused non-strict idb path from #idb

BREAKING CHANGE: iOS pressButton('back') throws UNSUPPORTED_ON_IOS.
- inline the now pass-through #exec wrapper (simctl calls use exec directly)
- drop pressButton JSDoc that restates the code and tool description
- restore four companion-recovery tests unrelated to non-strict exec that
  were removed with the non-strict ones
- drop the typeText disposal test, which repeats the existing
  disposal-during-a-command test
React Native keeps off-screen rows in the accessibility tree, so
scrollToElement returned as soon as findElement matched, often after
zero swipes with the element below the fold, and the next tap failed
with 'Element is outside the viewport'.

- success = enough of the frame inside the viewport (4% top/bottom
  inset; half the height, or 44 pt for tall elements); a fixed element
  that a swipe did not move is accepted when it intersects the viewport
- read the screen until it settles after a swipe (momentum)
- return { element, swipes, inViewport: true }; throw
  ScrollToElementError ELEMENT_NOT_FOUND / ELEMENT_NOT_IN_VIEWPORT
  (swipes + last frame)
- direction 'auto' (default): finger direction from the element's
  position; searches toward content below first, turns once at the end
- Android/Appium: scroll swipes from the real screen middle

BREAKING CHANGE: scrollToElement returns ScrollToElementResult instead
of UIElement; the default direction is 'auto' instead of 'down'.
B2: a click on log-in-button reported success while the keyboard
covered it, and nothing happened.

- iOS tapElement/longPress run idb ui describe-point --api axbridge at
  the tap point; when the element there is not the target (or inside
  it), throw TargetObscuredError (TARGET_OBSCURED, obscuredBy, keyboard)
  and do not tap. No element at the point / no --api support: tap.
- Android tapElement/longPress use the shared visibleCenter rule (frame
  clipped to the screen; refuse when outside, incl. zero-height rows);
  wm size cached per backend
- visibleCenter moved to utils/element (shared by idb and adb)
@cryptotavares
cryptotavares force-pushed the cryptotavares/mmcli-p1-42-tap-actionability branch from 8bd97d4 to 268595e Compare November 10, 2026 13:38
One verified Hermes socket serves many calls, so the identity probe and
handshake are paid once. Responses are matched by CDP id and CDP events are
dispatched to on() listeners.

When the app reloads the socket closes: pending calls fail with
HERMES_CONNECTION_FAILED and are not resent, then the client rediscovers the
target and reconnects with exponential backoff, emitting reconnected and
contextCreated. The device pin is enforced on every reconnect.

runHermesCdp now uses the client (one connect, one send, close) with
auto-reconnect disabled, keeping its codes and messages unchanged.
A caller's connect()/send() no longer stops the background reconnect loop:
it used to clear the reconnect timer and reset the backoff, so a send during
the reconnect wait killed auto-reconnect for good.

- Track an unexpected socket loss and restart the loop after a failed
  caller-driven attempt, except after close() and on terminal failures.
- Report a caller-driven connect after a loss as contextCreated with
  reason 'reconnect' and reconnected true.
- Start the loop before emitting `disconnected`, and make a scheduled
  attempt a no-op while connected, so one loss opens one socket.
- Close any socket adopted over a previous one; one contextCreated per
  adopted socket.
- Bound reconnect attempts with the new reconnect.connectTimeoutMs
  (default 10 s) instead of the last caller's timeoutMs.
- Check close() after every await of the connect path: no pin, no onPin,
  no adopted socket, and close the in-flight socket.
- End an aborted send with HERMES_ABORTED even while it is connecting.
- Detect a reload from contextDestroyed even when the socket never reported
  its first execution context.
- Surface a throwing listener through the new listenerError event.
The test still expected HERMES_CONNECTION_FAILED via the finally close, but a
user-method timeout has resolved to HERMES_TIMEOUT since runHermesCdp moved
onto HermesClient.
@cryptotavares
cryptotavares force-pushed the cryptotavares/mmcli-p2-02-persistent-hermes branch from 0c1f01f to 81961c0 Compare November 10, 2026 14:36
Base automatically changed from cryptotavares/mmcli-p1-42-tap-actionability to main November 12, 2026 11:14
…2-02-persistent-hermes

# Conflicts:
#	src/backends/idb-backend.test.ts
#	src/backends/idb-backend.ts
#	src/utils/element.test.ts
#	src/utils/hit-test.test.ts
#	src/utils/hit-test.ts
cryptotavares added a commit to MetaMask/client-mcp-core that referenced this pull request Nov 18, 2026
…nection (#91)

## Description

`mm launch --platform ios|android --metro-port 8085` stored the port,
but `mm cdp` and `mm hermes-targets` resolved it again for each call and
fell back to `HERMES_METRO_PORT` or 8081 (baseline B5). On a machine
with a second Metro on 8081 they reached the wrong app; without one they
failed. Every Hermes call also opened its own WebSocket.

- `MobilePlatformDriver` options gain `metroPort`, `deviceId` and
`appId`. New optional `IPlatformDriver.setHermesDefaults()`: the launch
tool applies `--metro-port` / `--device-id` to the driver after a
successful mobile launch, so B5 is fixed with no consumer change.
- Precedence for each call: per-call `--metro-port` / `--app-id`, then
the driver (launch) value, then `HERMES_METRO_PORT` / `HERMES_APP_ID`,
then 8081 / the platform default. CDP failures name the port they tried.
- When the loaded device-mcp exports `HermesClient`
(MetaMask/device-mcp#54), `cdp` keeps one persistent client per session
target. A per-call port or app id that differs uses a one-shot call, so
the persistent client is never retargeted. The client is closed on
`dispose()`. With device-mcp 0.7.0 (no `HermesClient`), core keeps the
one-shot `runHermesCdp` path (feature-detected).
- `hermes-targets` also reports `sessionMetroPort`, `pinnedDeviceId`,
`connected` and `deviceId` (additive).

Part of the mm CLI v2 effort: ticket `P2-03` (Tier 2).
Stacked on #90 (review that first).
Depends on MetaMask/device-mcp#54: the persistent connection needs a
device-mcp release with `HermesClient`, then a dependency bump here. The
B5 fix works with the released 0.7.0.

## Breaking changes

None. New options and output fields only.

## Consumer impact

| Consumer | Change needed |
|---|---|
| Mobile `tests/llm-workflow/` | Optional: pass `{ metroPort, deviceId,
appId }` when constructing `MobilePlatformDriver` (patch ready). Core
already applies the launch values itself. |

## Proof

Yalc build in Mobile (dev client 8.19.0, iOS sim + Android emulator,
Metro 8085, launched with `--metro-port 8085`), `mm cdp Runtime.evaluate
1+1` without `--metro-port`, 10 runs:

| Check | Before (#79 stack) | After |
|---|---|---|
| Android, 10 calls | 0/10: `hermes-targets` says `metroPort: 8081,
metroDown: true` | **10/10**, `sessionMetroPort: 8085`, p50 15–40 ms |
| iOS, 10 calls | — | **10/10**, p50 2 ms |
| `hermes-targets` after a call | — | `connected: true`,
`pinnedDeviceId` set, `deviceId` = launch device |

The before build reached Metro only with an explicit `--metro-port 8085`
(90 ms per call on Android). The raw client bench is in
MetaMask/device-mcp#54 (Android p50 165 → 5 ms).

<details>
<summary>Unit tests</summary>

```
Test Files  58 passed (58)
     Tests  2178 passed (2178)    (with #89 and #90 merged)
All files  |  97.94 | 95.5 | 97.59 | 98.04 |
```

Covers the precedence table, launch applies the port, one client for two
calls, one-shot on a per-call override, fallback without `HermesClient`,
close on dispose, the pin persisting, and the new `hermes-targets`
fields. `CI=1` thresholds not lowered; `tsc -p tsconfig.build.json` and
`yarn lint` clean.

</details>
itsyoboieltr
itsyoboieltr previously approved these changes Nov 18, 2026

@itsyoboieltr itsyoboieltr left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the performance improvements are very nice!

pnarayanaswamy
pnarayanaswamy previously approved these changes Nov 19, 2026
@cryptotavares

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review. All three points were valid. They are fixed in 5069bf6, f69a403 and 878ac83, plus a small follow-up, 36a2e3d.

1. A listen-only client stops recovering after the loop gives up

Fixed in 5069bf6. A small cleanup follows in 36a2e3d.

  • New reconnectFailed lifecycle event. Its payload is HermesReconnectFailedEvent { attempts, code, message }, from the last failed attempt.
    • It fires once each time the loop gives up, after maxAttempts.
    • It also fires at once on the terminal stops, HERMES_DEVICE_PIN_MISMATCH and HERMES_WEBSOCKET_UNAVAILABLE, with that code.
    • It is in HermesClientEventMap and exported from the package root.
    • It does not fire with maxAttempts: 0, because no loop runs then (for example in runHermesCdp).
  • A caller can restart a stopped loop. After the loop gives up, a failed connect/send restarts it from the first backoff step. Terminal codes never restart it.
    • A failure while the loop is running leaves the loop's schedule as it is.
    • A new #reconnectRunning flag tracks this, so the attempt counter no longer decides it.
    • A generation counter makes an attempt that is still in flight across close(), a success, or a restart do nothing.
  • Unchanged: one socket per reconnect, close() abandons everything, and a single contextCreated { reason: 'reconnect' }.
  • I rewrote the class comment and the maxAttempts doc to match. They now say that a listen-only caller should handle reconnectFailed.
  • Tests (fake timers):
    • A listen-only client gives up, reconnectFailed fires once with attempts: 3, and then nothing happens for 60 s.
    • After give-up, a failed send restarts the loop at the first delay. The client then reconnects with one socket, one reconnected and one contextCreated { reconnect }.
    • A pin mismatch and a missing WebSocket each emit once and are never restarted, by the loop or by a caller.
    • maxAttempts: 0 emits nothing.

2. send's timeoutMs does not bound the wait for a connect that is already running

Fixed in f69a403.

  • A caller that joins a connect: when a connect is already in flight (another caller's or a background attempt), connect()/send() waits for it for at most its own timeoutMs.
    • Then it returns HERMES_TIMEOUT, or the classified connect failure if that came first.
    • The shared connect keeps running for the others.
  • A background attempt that meets a caller's connect: it waits for that connect instead of opening a second socket.
    • If that connect fails, the attempt then runs its own connect with the full connectTimeoutMs.
    • So a short caller timeout can only end the caller's own connect. It never shortens the attempt.
    • I chose this because it was the simplest option that keeps "one socket, never two" without changing who owns the shared promise.
  • What timeoutMs means: it applies to each phase separately, not to their total.
    • It is the connect budget (or the wait for a connect that is already running), and then separately the response budget.
    • This keeps runHermesCdp's behaviour the same. Each of its connect steps and the method still get timeoutMs, and its tests pass unchanged.
    • HermesSendOptions.timeoutMs now documents this. It also says that signal: AbortSignal.timeout(n) bounds the total time.
  • Tests:
    • A send with a 1 s timeout during a 10 s background attempt returns HERMES_TIMEOUT at exactly 1 000 ms, and the attempt still succeeds later.
    • A background attempt that meets a 200 ms caller connect gets its own 10 s discovery budget afterwards.
    • An attempt that meets a caller connect which succeeds opens no second socket.

3. HermesListenerErrorEvent is not exported

Fixed in 878ac83. It is now exported from src/index.ts, next to HermesReconnectFailedEvent (added in 5069bf6).

src/index.test.ts now has an expectTypeOf<HermesClientEventMap>().toEqualTypeOf<{…}>() check written against the root exports.

  • If an event-map payload type is not exported, or the map changes, tsc -p tsconfig.test.json and the editor flag it.
  • CI does not enforce it yet:
    • Vitest only typechecks *.test-d.ts files.
    • Adding one would bring in 11 type errors that already exist in other test files, outside this PR.
  • I can follow up with that cleanup plus a .test-d.ts file if you want CI to enforce it.

@cryptotavares

Copy link
Copy Markdown
Contributor Author

Round 2: fixes from an internal review

All on this branch, after 36a2e3d. This updates my earlier reply in one place: a device-pin mismatch while reconnecting no longer stops the loop for good (see below). runHermesCdp and its tests are unchanged. client-mcp-core's use (send, close, isConnected, metroPort, appId, no listeners) keeps working and no longer sends Runtime.enable.

Should-fix

  • trackContexts is now opt-in (default false) (0ca114e). With Runtime enabled, Hermes sends Runtime.consoleAPICalled with previews for every console.* call. It also keeps each logged object in the ConsoleObjectGroup remote-objects group until a Runtime.releaseObjectGroup that the client never sent. So every core session held every logged object. The option doc now states this cost. I did not add an automatic releaseObjectGroup on contextDestroyed: the objects pile up while the app runs, between reloads, so a release at reload time would not limit that growth. The doc tells callers who enable tracking to send the release themselves.
  • close() now abandons an in-flight connect (71bc1aa). A connect epoch is bumped in close(), and #inFlightConnect is cleared, so a reopen starts a fresh connect. An abandoned connect closes its own socket and never pins, calls onPin, adopts or emits. This fixes:
    • S1: a stale pin;
    • S2: a reopen joining a closed socket;
    • S3: reconnected + contextCreated { reconnect } after close + reopen.
  • A pin mismatch on reconnect is retryable (c94168d). Only HERMES_WEBSOCKET_UNAVAILABLE is terminal, and a caller restart follows the same rule. With two simulators, the client now reconnects once the pinned device registers again, and never adopts the other device.

Nits

  • A socket lost during Runtime.enable no longer emits disconnected for a connection that was never reported. The connect fails, and a reconnect continues the loop (8ee1349).

  • An empty pinnedDeviceId means no pin, as on main (f27edf7).

  • Unreachable branches removed (de910d0, 07c3d9a): in #attemptReconnect and in the same-device check of the pin-mismatch detection.

  • Docs (368506c):

    • every timeout step, and the about 5 × timeoutMs worst case for a cold send;
    • an open socket keeps Node alive, so call close();
    • CDP domain state (Debugger.enable, breakpoints, a pause) now lasts across calls.
  • Tests (0aa6e76, plus the fix commits):

    • S1–S4;
    • close after socket open and during Runtime.enable;
    • send after close();
    • socket.send throwing;
    • pin-mismatch detection edge cases.

    FakeWebSocket.close() on a CONNECTING socket now fires error, then close, as Node does. All real-time delay() tests now use fake timers.

  • Circular import: left as is. Moving the shared helpers is more than a mechanical move, and the cycle is safe in CJS and ESM.

yarn build, yarn lint and yarn test pass: 981 tests passed, 6 skipped. hermes-client.ts coverage is 95.76 / 89.17 / 91.17 / 96.22 (statements / branches / functions / lines).

@cryptotavares
cryptotavares merged commit d4e1655 into main Nov 19, 2026
35 checks passed
@cryptotavares
cryptotavares deleted the cryptotavares/mmcli-p2-02-persistent-hermes branch November 19, 2026 14:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants