Repository navigation
feat: HermesClient, a persistent Hermes CDP connection - #54
Conversation
- `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)
8bd97d4 to
268595e
Compare
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.
0c1f01f to
81961c0
Compare
…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
…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
left a comment
There was a problem hiding this comment.
the performance improvements are very nice!
36a2e3d
|
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 upFixed in 5069bf6. A small cleanup follows in 36a2e3d.
2.
|
…ebSocket is terminal
…ts connect completed
… pin-mismatch detection
Round 2: fixes from an internal reviewAll 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). Should-fix
Nits
|
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.Problem
runHermesCdpopens a new WebSocket for each call: a/jsondiscovery 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.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: strictappIdselection, the device pin, the WebSocket URL port check and the blocked methods.send(method, params, { timeoutMs, signal })connects when needed. Responses are matched by id, so many calls can be in flight.timeoutMslimits each step on its own (each connect step, then the response).signal: AbortSignal.timeout(n)limits the total time.on/offfor CDP events and for the lifecycle eventscontextCreated,contextDestroyed,disconnected,reconnected,reconnectFailedandlistenerError.reconnectFailed, and the next failedsendorconnectstarts the loop again.trackContexts: true(off by default), the client enablesRuntimeand 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 stopYellow boxes are new. Red boxes stop the call.
What changes
HermesClientHermesClient, its option types, every event payload type (includingHermesListenerErrorEventandHermesReconnectFailedEvent),HermesCdpErrorInfo,HERMES_ABORTEDrunHermesCdp, call timeoutHERMES_CONNECTION_FAILEDHERMES_TIMEOUTrunHermesCdp, malformed JSON framerunHermesCdp, socket closes mid-call… WebSocket closed before CDP responseHermes CDP connection closed: socket closedrunHermesCdp, everything elseRuntime.enable.No breaking changes to the exported API. Core 0.14.0 maps every Hermes failure except a blocked method to
MM_CDP_FAILEDand keeps the device-mcp code in the message, so only the code inside that message changes.Decisions for reviewers
reconnectFailed, so a client that only listens knows. A later failedsendorconnectrestarts the loop from the first step.sendwhile reconnecting never stops the reconnect loop, and each reconnect opens exactly one socketsendused to stop the loop, and adisconnectedlistener that sent opened a second socket.contextCreated { reason: 'reconnect' }, whatever started itclose()during a connect abandons it, and a laterconnect()starts a fresh oneonPinis not called, and the socket is closed. A reopen never joins the abandoned connect.sendthat joins a connect already in progress waits at most its owntimeoutMstrackContextsis off by defaultRuntimeis enabled, Hermes sends everyconsole.*call to the socket and keeps each logged object untilRuntime.releaseObjectGroup. Core does not use reload events, so it must not pay for them.listenerErrorrunHermesCdpusestrackContexts: falseandmaxAttempts: 0hermes-cdp.tsandhermes-client.tsimport each otherhermes-cdp.tsexplains this.Review guide
Read the files in this order:
src/hermes/hermes-client.tsconnect,send,close. Then#onSocketLost, the reconnect loop and theRuntimecontext events.src/hermes/hermes-cdp.tsrunHermesCdpon the client. The helpers that are now exported for the client.src/index.tssrc/hermes/hermes-client.test.tsTesting
yarn build,yarn lintandyarn testpass (38 files, 981 tests, 6 skipped). Coverage thresholds are unchanged.hermes-client.ts: 96% of lines, 89% of branches.1+1.runHermesCdpHermesClientPage.reloadon the same client (trackContexts: true)contextDestroyedafter 182 ms,contextCreated { reload }after 7.3 s, then1+1works againsendwhile Metro is down, then Metro returnscontextCreated { reconnect }disconnectedlistener that sendscontextCreated