Skip to content

feat: deliver CDP events from pages and the service worker - #107

Open
cryptotavares wants to merge 1 commit into
mainfrom
cryptotavares/mmcli-p2-28-cdp-target-events
Open

cryptotavares wants to merge 1 commit into
mainfrom
cryptotavares/mmcli-p2-28-cdp-target-events

Conversation

@cryptotavares

@cryptotavares cryptotavares commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Important

Ready to review on main. The Tier 2 stack (#88–#91) is merged; this PR is rebased onto main and contains one 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.
  • 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 that a <Domain>.enable / .disable is refused with MM_CDP_BLOCKED while a subscription holds that domain on the target: the subscription enabled it and would disable it on its last unsubscribe. --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).

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
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
Worker events after stop and wake (MV3 test extension)
[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"}
Findings for the consumers of this API (P2-15 / P2-16 / P2-17)
  • 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 feat: persistent CDP sessions per target and mm cdp --target sw #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.
Unit tests
 Test Files  64 passed (64)
      Tests  2469 passed (2469)
Type Errors  no errors
All files          |   98.25 |     95.8 |   97.93 |   98.34 |
  cdp-manager.ts   |   99.64 |    95.84 |     100 |   99.63 |
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
  • <Domain>.enable / .disable through send refused while subscribed (MM_CDP_BLOCKED), allowed with --fresh
  • 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)

Add `CdpManager.subscribe({ events, enable?, onEvent, onError? })`. It
attaches to every open page and the running Extension service worker, then
to each new page and each new or restarted worker. On each target it
enables the event domains once, shares the persistent session with `send`
and other subscribers, and delivers `{ target, method, params, t }`.

The service worker session now emits tunneled CDP events instead of
dropping every message without an `id`. New workers are found with
`Target.targetCreated` on the browser session (target discovery is
already on); new pages with the context `page` event. Unsubscribe removes
the listeners and disables domains no one else needs; `dispose()` ends
every subscription.
@cryptotavares
cryptotavares force-pushed the cryptotavares/mmcli-p2-28-cdp-target-events branch from 7d46869 to 73122e8 Compare November 18, 2026 18:39
@cryptotavares
cryptotavares marked this pull request as ready for review November 18, 2026 18:58
@cryptotavares
cryptotavares requested a review from a team as a code owner November 18, 2026 18:58

This branch has not been deployed

No deployments
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.

1 participant