Skip to content

fix: keep the launch Metro port for mobile cdp; persistent Hermes connection - #91

Merged
cryptotavares merged 9 commits into
cryptotavares/mmcli-p2-01-browser-cdpfrom
cryptotavares/mmcli-p2-03-hermes-session
Nov 18, 2026
Merged

cryptotavares merged 9 commits into
cryptotavares/mmcli-p2-01-browser-cdpfrom
cryptotavares/mmcli-p2-03-hermes-session

Conversation

@cryptotavares

@cryptotavares cryptotavares commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

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 (feat: HermesClient, a persistent Hermes CDP connection 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).

Unit tests
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.

`mm launch --platform ios|android --metro-port <n>` stored the port on the
session but `mm cdp` and `mm hermes-targets` resolved their target per call
and fell back to `HERMES_METRO_PORT`/8081 (baseline B5), so they could reach
another worktree's Metro.

- `MobilePlatformDriver` options gain `metroPort`, `deviceId` and `appId`;
  `setHermesDefaults` keeps the launch values for later Hermes calls.
- Precedence: per-call flag, then the driver/launch value, then
  `HERMES_METRO_PORT`/`HERMES_APP_ID`, then 8081/platform default.
- `cdp` reuses one persistent device-mcp `HermesClient` per session target
  and is never retargeted: a call with a different port or app id uses a
  one-shot `runHermesCdp`. Releases without `HermesClient` (0.7.0) always
  take the one-shot path.
- `hermes-targets` reports `sessionMetroPort`, `pinnedDeviceId`, `connected`
  and `deviceId`; a CDP failure names the Metro port it tried.
…es/mmcli-p2-03-hermes-session

# Conflicts:
#	CHANGELOG.md
#	README.md
#	SKILL.md
@cryptotavares
cryptotavares added this pull request to stack #92 November 9, 2026 10:12
…es/mmcli-p2-03-hermes-session

# Conflicts:
#	CHANGELOG.md
…r-cdp' into cryptotavares/mmcli-p2-03-hermes-session
The changelog is generated when a release is created.
…r-cdp' into cryptotavares/mmcli-p2-03-hermes-session
…r-cdp' into cryptotavares/mmcli-p2-03-hermes-session

# Conflicts:
#	README.md

@seaona seaona left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Once device-mcp ships HermesClient, state-changing Hermes commands persist the same way as in the previous PR #90. On the emulator, Debugger.enable plus Debugger.pause froze the app's JS until Debugger.resume. The tap didn't act for at least 13 s, and any mm command that needs JS would time out. On mobile the risk is higher than on the browser, for two reasons:

  • --fresh is browser-only and silently ignored on mobile. The only way to get a one-shot call is to pass a different port or app ID.
  • SKILL.md:680 describes the persistent connection only as reuse, with no warning.

@cryptotavares
cryptotavares merged commit 89dbef1 into main Nov 18, 2026
27 checks passed
@cryptotavares
cryptotavares deleted the cryptotavares/mmcli-p2-03-hermes-session branch November 18, 2026 14:49
cryptotavares added a commit to MetaMask/device-mcp that referenced this pull request Nov 19, 2026
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.

```text
# 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.

```mermaid
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
```

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 |

<details>
<summary>Testing</summary>

- `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` |

</details>
cryptotavares added a commit that referenced this pull request Nov 23, 2026
## Description

> [!IMPORTANT]
> **Ready to review on `main`.** The Tier 2 stack (#88–#91) is merged;
this PR is rebased onto `main`. Review round 4 (seaona) added one fix
commit. #109 (P2-15) → #110 (P2-16) → #111 (P2-17) stack on it.

`CdpManager` (#90) keeps one persistent CDP session per target, but it
cannot be used to **listen** to a target:

- The service-worker session drops every tunneled message that has no
`id`. Those messages are the CDP events (`src/platform/cdp-manager.ts`,
`ServiceWorkerCdpSession.#onMessage`).
- The manager attaches only when a command needs a target. A listener
misses pages and workers that nobody has sent a command to yet.

This PR adds an internal event API. Upcoming `mm logs` / `mm network`
(tickets P2-16 / P2-17) will build on it. This PR adds no CLI command
and no new export from the package root.

- `ServiceWorkerCdpSession` now emits tunneled CDP events by name (`on`
/ `off`), like a Playwright `CDPSession` does.
- New `CdpManager.subscribe({ events, enable?, onEvent, onError? })`:
- It attaches **eagerly** to every open page and to the running
Extension service worker.
- It also attaches to each new page (tab, popup, dapp page) and to each
new or restarted worker.
- It sends `<Domain>.enable` once per target and delivers `{ target: {
kind, targetId, url }, method, params, t }`.
- Subscribers and `send` share **one session per target**. Each event
name has one CDP listener, and each domain has one reference count. On
unsubscribe, the manager removes listeners and disables domains that no
other subscriber needs. `dispose()` ends every subscription.
- If a page session fails while the page is still open, the manager
attaches to the page again, up to 3 times within 30 s; after that the
failure is reported to `onError` once and the page is no longer
re-attached (a new subscription or page clears the budget). If
Playwright reports `close` for a worker whose CDP target is still live,
the manager attaches to the worker again.
- Target loss is not an error: a page that closed or an MV3 worker that
stopped mid-attach is not reported to `onError`, and a closed session
stays quiet too. When the target is still alive, the dead session is
dropped so the subscribers are re-attached at once on a fresh session; a
gone target is left to the target lifecycle. The manager also
re-attaches when the target comes back.
- **Each attach step is bounded** by `CDP_ATTACH_STEP_TIMEOUT_MS` (5 s):
opening the session, `Target.getTargetInfo`, listing the worker targets,
each `<Domain>.enable` and each `.disable`.
- A timeout is reported to `onError` and names the step and the target.
A page URL is shown without its query.
- The timed-out target is released: listeners are removed and the domain
is disabled in case the enable lands late. A session that opens after
the timeout is detached. The other targets stay live, and a later attach
trigger retries.
  - `unsubscribe` waits at most one bound for an attach in progress.
- **Errors without `onError`** go to the debug log (`debugWarn`). They
are never thrown into CDP event dispatch.
- **Conflicting `enable` params:** the first subscriber's
`<Domain>.enable` params stay in effect on a target. A later subscriber
with other params gets an error through `onError` that names the domain,
the target and both param sets. The params are not merged: a second
`Network.enable` would change the buffer limits for every subscriber of
that target.
- The lifecycle payload type `CdpTargetEvent` is renamed
`CdpTargetLifecycleEvent`, so it is not confused with `CdpEventTarget`
(`{ kind, targetId, url }`). It is not exported from the package root.
- `send` and `getSession` prefer the worker target that subscribers are
already attached to, so a restarted worker does not move a later `send`
back to the old target.
- `send`, `--fresh` and the "never resend a command" rule do not change,
except for a domain that a subscription holds on the target:
- `<Domain>.enable` with no params, or with the params in effect (any
key order), sends nothing and returns the subscription's enable result
(`{}` for Network and Runtime). So the documented `mm cdp
Network.enable` keeps working once #109 starts the event sources at
launch.
- `<Domain>.enable` with other params, and any `<Domain>.disable`, are
refused with `MM_CDP_BLOCKED`. The message says why: the call would
change, or stop, the events the subscription receives.
  - `--fresh` sessions are not refused. README/SKILL document it.

### How new targets are found

| Target | Signal | Why |
|---|---|---|
| Page / popup / dapp tab | Playwright `context.on('page')` +
`context.newCDPSession(page)` | Playwright already gives page sessions
that emit events. |
| Extension service worker | `Target.targetCreated` on the browser
session (target discovery is already on from #90), plus Playwright
`serviceworker` as a backup. Then `Target.attachToTarget` (`flatten:
false`), as #90 does. | Playwright cannot open a CDP session on a
`Worker`. |

`Target.setAutoAttach` was **not** used. At the browser level, Chrome
supports only `flatten: true` ("Only flatten protocol is supported with
browser level auto-attach"). Flat sessions cannot be driven through
`Target.sendMessageToTarget` ("When using flat protocol, messages are
routed to the target via the sessionId attribute"). Playwright's
`CDPSession` does not expose a way to send on a child `sessionId`.
Auto-attach would also attach to every target, including Playwright's
own pages. Both probes are in the proof
(`probes/auto-attach-spike.txt`).

## Breaking changes

None. The change is additive and internal (`CdpManager` is not exported
from the package root).

## Consumer impact

| Consumer | Change needed | Done on branch |
|---|---|---|
| Extension `test/e2e/playwright/llm-workflow/` | none | n/a |
| Mobile `tests/llm-workflow/` | none | n/a |

## Proof

Ticket `P2-28` (Phase 2, outside the current stack). The proof drives
`CdpManager.subscribe` from the built `dist/` in a script, because this
PR adds no CLI command. After the review fixes (head `73122e8`) the
happy path is unchanged, so the live results below still apply; the
behaviour fixes are unit tested (below).

**Review round 4 (head `d8102aa`):** the held-`.enable` bug and the
unbounded attach were first reproduced with failing unit tests on
`34d4b3d` (a held `Network.enable` threw `MM_CDP_BLOCKED`; `subscribe()`
never settled after 60 s of fake time when `Runtime.enable`,
`Target.getTargetInfo` or `newCDPSession` never answered). Live check
through the CLI on the MetaMask Extension e2e build (headless, e2e
fixture), with the top of the stack (#111, `8b78f0e`), which starts the
event sources at launch:

| Check | Result |
|---|---|
| MV3 test extension: `Network.requestWillBeSent` / `responseReceived` /
`loadingFinished` / `loadingFailed`, `Runtime.consoleAPICalled` /
`exceptionThrown` from the **page** and from the **service worker** | ✅
all 6 event types from both target kinds (118 events) |
| Page that existed before `subscribe` (eager attach) | ✅ |
| Tab opened after `subscribe` (auto attach) | ✅ |
| Worker stop (`ServiceWorker.stopAllWorkers`), then wake from a new
Extension page | ✅ worker events arrive again after the wake, including
the worker's top-level start-up `console.log` + `fetch` |
| `send` on `sw` while subscribed; `--fresh` | ✅ `ok` / `2`; while the
worker is stopped, `send` still fails fast after 2 s with #90's
stopped-worker error |
| Two subscribers | ✅ one session per target, one `enable` per domain;
the second subscriber (Runtime only) receives exactly the Runtime events
of the first |
| Duplicate events / cross-target leaks / out-of-order `t` | ✅ 0 / 0 / 0
|
| After `unsubscribe` | ✅ 0 events |
| Round 4: `mm cdp Network.enable` while the session holds `Network`
(page and `--target sw`) | ✅ exit 0, `{}` |
| Round 4: `mm cdp Network.disable` (page and `--target sw`);
`Network.enable '{"maxPostDataSize":1}'` | ✅ exit 2, `MM_CDP_BLOCKED`,
with the reason |
| Round 4: `mm network` after those calls | ✅ records a page fetch and a
worker fetch; `captureErrors` 0 |
| MetaMask Extension test build 13.56.0 (`dist/chrome`, no wallet
created, first screen only) | ✅ 657 events from `home.html` and the
worker, before and after a worker stop and wake; `--target sw` probe
`typeof stateHooks` = `object`, and its `console.warn` arrives as an
`sw` event |

<details>
<summary>Worker events after stop and wake (MV3 test
extension)</summary>

```
[12:32:25.972] worker stopped: targets before ["A51F9577"], after []
[12:32:27.974] send to the stopped worker: The Extension service worker is not running (MV3 workers stop when idle). Intera...
[12:32:28.047] targetAttached page (C-wake)
[12:32:28.887] worker targets after wake: ["A51F9577"]
C-wake sw {'Runtime.consoleAPICalled': 4, 'Network.requestWillBeSent': 6, 'Network.responseReceived': 5, 'Network.loadingFinished': 5, 'Network.loadingFailed': 1}
C-after-wake sw {'Network.requestWillBeSent': 5, 'Network.responseReceived': 4, 'Network.loadingFinished': 4, 'Runtime.consoleAPICalled': 3, 'Network.loadingFailed': 1, 'Runtime.exceptionThrown': 1}

{"phase":"C-wake","kind":"sw","targetId":"A51F9577","method":"Runtime.consoleAPICalled","detail":"log: bg boot"}
{"phase":"C-wake","kind":"sw","targetId":"A51F9577","method":"Network.requestWillBeSent","requestId":"17445.25","detail":"GET http://127.0.0.1:47123/ok?boot=1"}
```

</details>

<details>
<summary>Findings for the consumers of this API (P2-15 / P2-16 /
P2-17)</summary>

- **The worker target ID does not identify a worker run.** After
`ServiceWorker.stopAllWorkers` (or `ServiceWorker.stopWorker`) and a
wake, Chrome reused the **same** target ID, and the same CDP session
kept working, with its domains still enabled. A restart is marked by
`Inspector.targetCrashed` → `Runtime.executionContextsCleared` →
`Runtime.executionContextCreated` on that session
(`probes/restart-signal.txt`). If a worker comes back as a **new**
target, the manager attaches to it and enables its domains again (unit
tested).
- **Idle stop**: in headless Chromium with a test extension and no open
Extension page, the worker was stopped after 90 s
(`Target.targetDestroyed`) with or without a subscription. An attached
subscriber therefore does not keep the worker alive
(`probes/idle-*.txt`).
- **`chrome.runtime.reload()`** closes Extension pages, and
`chrome-extension://` URLs are then blocked (`ERR_BLOCKED_BY_CLIENT`).
It is not a usable restart in tests (the same result as #90).
- **Start-up traffic**: a worker that starts while a subscription is
active delivered its top-level start-up `console.log` and `fetch`.
Network traffic sent before `subscribe` is not delivered.
`Runtime.enable` replays console messages that Chrome kept, so a late
subscriber can get older console events (`probes/late-subscribe.txt`).
- **Volume**: the MetaMask first screen (`home.html` + worker, about 8 s
per phase) gave about 330 events per phase for these 6 event names.
Console events were the largest part.
- **Order and time**: events of one target arrive in CDP order. `t` is
`Date.now()` in the daemon when the event is delivered (not the CDP
`timestamp` / `wallTime`, which are in `params`). Events from different
targets interleave by arrival time.
- **`requestId`** is unique per target only. Use `(target.kind,
target.targetId, requestId)` as the key.

</details>

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

```
 Test Files  64 passed (64)
      Tests  2484 passed (2484)
Type Errors  no errors
All files          |   98.27 |    95.76 |   97.97 |   98.36 |
  cdp-manager.ts: 99.7 lines, 95.5 branches
yarn lint: exit 0
yarn build: exit 0
```

New tests in `src/platform/cdp-manager.test.ts`, `CdpManager subscribe`:
- events from the page and the worker, with target tags
- no leaks between targets
- a new page is attached automatically
- worker restart with a new target ID, and with the same target ID;
domains are enabled again
- Playwright `close` of a worker whose target is still live
- one session and one `enable` per domain for several subscribers
- `send` / `--fresh` while subscribed (a command is never resent)
- `unsubscribe` and `dispose`
- error reporting
- worker destroyed while `Runtime.enable` is pending → no error
- cached worker target preferred by `send` when the target list holds
the old and the new one
- through `send` while subscribed: a held `<Domain>.enable` with no or
the same params answers without sending; `.enable` with other params and
`.disable` are refused (`MM_CDP_BLOCKED`); all are allowed with
`--fresh`; a held `.enable` fails the same way the subscription's enable
failed
- a never-answering `newCDPSession`, `Target.getTargetInfo`, page or
worker `enable` and worker target list: each is reported, the other
targets stay live, and a late session is detached
- `unsubscribe` does not wait on an enable that never answers; each
`.disable` is bounded
- conflicting `enable` params are reported with the target and the
domain (nested and list params; key order ignored)
- errors go to the debug log when there is no `onError`
- a live page whose `enable` or target-info call fails on a closed
session is dropped and re-attached on a fresh session; a subscription
whose first attach failed is retried on a later attach trigger; a page
whose sessions keep closing is reported once and no longer re-attached
(120 tests in `cdp-manager.test.ts`)

</details>
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.

2 participants