Skip to content

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

Merged
cryptotavares merged 3 commits into
mainfrom
cryptotavares/mmcli-p2-28-cdp-target-events
Nov 23, 2026
Merged

cryptotavares merged 3 commits 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. 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 feat: add a session event buffer with one cursor and mm events mark #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
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  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)

Base automatically changed from cryptotavares/mmcli-p2-01-browser-cdp to main November 18, 2026 14:49
@cryptotavares
cryptotavares force-pushed the cryptotavares/mmcli-p2-28-cdp-target-events branch 3 times, most recently from c0dfe35 to 7d46869 Compare November 18, 2026 17:56
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
@cryptotavares
cryptotavares added this pull request to stack #113 November 19, 2026 16:24

@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.

really good addition. It will be very useful for us 🙌 Overall looks good to me. I've added a couple of findings from opus. I think the first 2 are something to consider, and the other are minor/less relevant, but let me know what you think

Comment thread src/platform/cdp-manager.ts Outdated
* @param session - The session the command would run on.
* @param method - The CDP method.
*/
#assertDomainFree(session: EventCdpSession, method: string): void {

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.

The new MM_CDP_BLOCKED rule will break the documented mm cdp Network.enable example once the stack lands.

Once #109 starts the session event sources at mm launch, Runtime and Network are held on every page and on the worker for the whole session. That means mm cdp Network.enable, which is the example in README L692, SKILL L694, the mm cdp help text (mm.ts L1020) and the cdp schema description, will always fail with MM_CDP_BLOCKED. SKILL L735 also now says both "a domain enabled by one call (e.g. Network.enable) stays enabled" and "is refused".

For .enable, refusing doesn't seem necessary. What the caller wants ("the domain is enabled on this session") is already true. Could a held .enable with empty params succeed as a no-op, and be refused only when it has params that would be silently ignored? .disable can stay refused.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Valid. Once #109 starts the sources at launch, Network is held on every target, so the documented mm cdp Network.enable always got MM_CDP_BLOCKED. I reproduced it with a unit test on 34d4b3d.

Fixed in d8102aa, as you suggested:

  • A held <Domain>.enable with no params, or with the subscription's own params (key order ignored), sends nothing. It returns the result of the subscription's enable, which is {} for Network and Runtime.
  • A held .enable with other params is refused with MM_CDP_BLOCKED. The message says the domain is already enabled with params that this call would change.
  • .disable stays refused, and its message says it would stop the subscription's events.
  • --fresh is unchanged.

README, SKILL (both places, so it no longer contradicts itself) and the send docs now say the same thing. #111's SKILL also notes that mm cdp Network.enable is a no-op while mm network holds the domain. The mm cdp Network.enable example in the help text, README, SKILL and the schema description is correct again, so I kept it.

}
this.#subscriptions.add(subscription);

await Promise.all([

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.

Nothing in the subscribe path is time-bounded. Target.getTargetInfo (L1396), .enable (L1338) and newCDPSession are all awaited without #race, and #unsubscribe waits on record.ready (L1477). One stuck target, for example a page paused in the debugger or frozen, blocks subscribe() and unsubscribe() forever. In #110/#111, mm logs, mm network and mm events all await ensureStarted(), which waits on this. Launch has its own 5 s cap, but the stored #starting promise stays pending, so later calls hang. Could each per-target attach be bounded (failures go to onError, and the subscription stays live for the other targets), and could unsubscribe stop waiting on ready after a timeout?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Valid. I reproduced it: subscribe() never settled when Runtime.enable, Target.getTargetInfo or newCDPSession never answered. On #109, a second ensureStarted() hung on the stored #starting promise after the launch's 5 s cap.

Fixed:

  • d8102aa (feat: deliver CDP events from pages and the service worker #107): each attach step is bounded with #race by CDP_ATTACH_STEP_TIMEOUT_MS (5 s). The steps are: open the session, Target.getTargetInfo, list the worker targets, and each <Domain>.enable.
    • A timeout goes to onError and names the step and the target. A page URL is shown without its query.
    • The subscriber is released from that target: its listeners are removed, and the domain is disabled in case the enable lands late. A session that opens after the timeout is detached. The subscription stays live on the other targets, and a later trigger can retry.
    • unsubscribe waits at most one bound for an attach in progress, and each .disable is bounded too.
    • Each bounded step has a test with a never-resolving fake.
  • 94291ed (feat: add a session event buffer with one cursor and mm events mark #109): ensureStarted waits at most 5 s for a start in progress, so later mm events, logs and network calls cannot hang on it.

* Called when a target cannot be attached or enabled, or when `onEvent`
* throws. Errors are dropped when it is missing.
*/
onError?: (error: Error) => void;

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.

Errors are dropped when it is missing. Neither consumer in #110/#111 passes onError, so the re-attach budget report, failed enables and onEvent exceptions all disappear

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Valid. Fixed in two places:

*/
events: readonly string[];
/**
* Parameters of `<Domain>.enable`, by domain, for example

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.

The first subscriber to enable a domain on a target sets them. A second subscriber that passes different Network params, such as maxPostDataSize, gets the first subscriber's values with no warning. In #111 that would silently cut off JSON-RPC request bodies if anything else enabled Network first. Could conflicting params be reported through onError, or the enable be sent again with the merged params?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Valid. No consumer in the stack conflicts today: only mm network passes Network params, and mm logs passes none. But the silent fallback was a trap.

Fixed in d8102aa: a later subscriber whose <Domain>.enable params differ from the ones in effect on a target gets an error through onError. The error names the domain, the target, its own params and the params in effect. #111 records it in captureErrors. The doc on CdpSubscribeOptions.enable states the limit.

I did not merge the params and send the enable again. The session is shared, so a second Network.enable with merged buffer limits (maxTotalBufferSize, maxResourceBufferSize, maxPostDataSize) would change them for every subscriber of that target, including the one that set them first. Merging also has no clear rule when two values differ (which one wins?). Because that is not clearly safe for Network.enable, I documented the limit instead.

/**
* The target a CDP event came from.
*/
export type CdpEventTarget = {

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.

nit: CdpEventTarget ({ kind, targetId, url }) and CdpTargetEvent ({ kind, target? }) are easy to mix up. Maybe rename the second one to CdpTargetLifecycleEvent?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in d8102aa: CdpTargetEvent is now CdpTargetLifecycleEvent. It is not exported from the package root (src/index.ts exports nothing from cdp-manager), so the rename was mechanical. I carried it to #111's network source and its tests in the #111 merge commit d79edcf.

…ttach step

Review of #107:
- A <Domain>.enable with no params (or the subscription's own params) on a
  domain an event subscription holds now sends nothing and returns the
  subscription's enable result, so `mm cdp Network.enable` keeps working once
  the session event sources hold Network. An enable with other params and a
  <Domain>.disable stay refused with MM_CDP_BLOCKED, with a message that says
  why.
- Each attach step of a subscription (opening the session, the target info,
  the worker target list, each <Domain>.enable) and each <Domain>.disable is
  bounded by CDP_ATTACH_STEP_TIMEOUT_MS (5 s). A timeout goes to onError, the
  subscriber is released from that target (listeners off, the domain
  disabled in case the enable lands late), and the subscription stays live
  on the other targets. unsubscribe waits at most one bound for an attach in
  progress.
- Errors of a subscriber without onError go to the debug log.
- Conflicting <Domain>.enable params are reported through onError with the
  target and the domain; the first subscriber's params stay in effect.
- Rename CdpTargetEvent to CdpTargetLifecycleEvent.
cryptotavares added a commit that referenced this pull request Nov 20, 2026
…mmary

Review of #107, carried to #109:
- ensureStarted waits at most 5 s (SESSION_EVENTS_START_WAIT_MS) for a start
  in progress. A start held by a target that does not answer no longer makes
  every later mm events/logs/network call hang on the stored promise.
- SessionEvents.reportError records an event source error: it counts it in
  the buffer summary (captureErrors, lastCaptureError, redacted and cut at
  300 characters) and writes it to the debug log. A source that fails to
  start is recorded the same way.
cryptotavares added a commit that referenced this pull request Nov 20, 2026
The console source passes SessionEvents.reportError as the onError of its CDP subscription, so a target it cannot attach or enable in time is counted in summary.captureErrors instead of being dropped (review of #107).
cryptotavares added a commit that referenced this pull request Nov 20, 2026
The network source passes SessionEvents.reportError as the onError of its CDP subscription, so an attach timeout, a failed Network.enable, or Network.enable params that another subscriber set first are counted in summary.captureErrors instead of being dropped. SKILL says that mm cdp Network.enable succeeds without sending anything while mm network holds the domain (review of #107).
@cryptotavares

Copy link
Copy Markdown
Collaborator Author

Thanks for the review! All five points are addressed. The fixes are in #107 and are carried up the stack with merge commits.

Live check on the Extension (headless, e2e fixture, #111 build):

  • mm cdp Network.enable returns {} on the page and on the worker;
  • mm cdp Network.disable gets MM_CDP_BLOCKED;
  • mm network still records page and worker requests afterwards.

@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.

changes lookgood!

@pnarayanaswamy

Copy link
Copy Markdown
Contributor

Went through the subscribe/unsubscribe/attach races, shared enable timeouts, worker restart and dispose mid-attach. No correctness issue found; previous round is addressed. A few optional follow-ups:

  • #emit (cdp-manager.ts ~L2318) has no try/catch around listeners, unlike #deliver / #report. A throwing targetAttached/targetDetached listener stops later listeners, and in #openEntry it throws after entry.session is already set. Wrapping each call + debugWarn would match the rest of the class.
  • #pageEntry: each re-attach adds another page.once('close', …); the old one becomes a no-op but stays registered. Bounded by MAX_PAGE_REATTACH_FAILURES, so small — a WeakSet guard like #observedWorkers would avoid it.
  • send() has no default timeout, so mm cdp on a frozen target hangs unless the caller passes timeoutMs. dispose() also awaits detach() without a bound.

Note for other reviewers: gh pr diff against current main appears to remove #108's hidden-control code; that's just the branch predating #108. A local merge keeps both.

@pnarayanaswamy pnarayanaswamy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-review on d8102aa: no new commits since my last pass; nothing blocking. Optional follow-ups inline.

* @param payload - The target payload.
*/
#emit(event: CdpManagerEvent, payload: CdpTargetEvent): void {
#emit(event: CdpManagerEvent, payload: CdpTargetLifecycleEvent): void {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

#emit calls listeners without a try/catch, unlike #deliver / #report. A throwing targetAttached/targetDetached listener skips the later ones, and from #openEntry (L2123) it throws after entry.session is already set. Wrapping each call with a debugWarn would match the rest of the class.

!entry.page.isClosed() &&
!this.#pageAttachFailures.get(entry.page)?.reported
) {
await this.#attachPageForSubscribers(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Each re-attach here goes through #pageEntry, which adds another page.once('close', …) (L1840). The old listener becomes a no-op but stays registered. Bounded by MAX_PAGE_REATTACH_FAILURES, so small; a WeakSet guard like #observedWorkers would avoid it.

acquired = await this.#acquireSession(target, options);
}

const held = this.#heldDomainEnable(acquired.session, method, params);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Only a held enable gets a bound here (via held.enabled). Every other send() has no default timeout, so mm cdp on a frozen page/worker hangs unless the caller passes timeoutMs. Same for dispose(), which awaits #detach / session.detach() without a bound. Fine as a follow-up.

@cryptotavares
cryptotavares merged commit f652b3e into main Nov 23, 2026
27 checks passed
@cryptotavares
cryptotavares deleted the cryptotavares/mmcli-p2-28-cdp-target-events branch November 23, 2026 14:01
cryptotavares added a commit that referenced this pull request Nov 23, 2026
…109)

## Description

> [!IMPORTANT]
> **Stacked on #107** (P2-28, ready to review on `main`; review it
first). This PR targets #107's branch. #107's review fixes are merged
in, with fix commits on top for each review round. #110 (P2-16) and #111
(P2-17) stack on it.

`mm logs` (P2-16) and `mm network` (P2-17) are streams. An agent needs
"everything since the start of this flow" in one cheap, paged, redacted
read. It must also know when records were lost (buffer overflow,
relaunch). Today there is no session-level event store:
`CdpManager.subscribe` (#107) delivers events, but nothing keeps them.

This PR adds that store and its bookmark command. The buffer has no
sources yet: P2-16 and P2-17 fill it.

- **One buffer per browser session** (`src/events/event-buffer.ts`),
with one monotonic `seq` shared by all record kinds (starts at 1 per
session). Two kinds, each with its own capacity and drop count:
`console` (1000) and `network` (2000). A full kind drops its oldest
record.
- **Read API** `read({ kind, cursor?, since?, limit, filter? })` → `{
records, cursor, hasMore, gap, summary }`, oldest first. The returned
`cursor` continues the read with no duplicates or holes. `gap: true`
when a record after the cursor (or at/after `since`) was dropped. A
`cursor` above the newest `seq` (from an earlier session) is stale: the
read starts from the oldest record and reports `gap: true`, so a client
that compares cursors notices. With both `cursor` and `since`, `gap` is
approximate (a record dropped after the cursor but before `since` is not
distinguished). `limit` is clamped to at least 1. A record updated in
place later (a network request that finishes) keeps its `seq`, so it is
never returned twice.
- **`summary`** `{ startedAt, seq, counts, dropped, captureErrors,
lastCaptureError? }`. `startedAt` (epoch ms) is new for each session, so
a reader can detect a relaunch. `captureErrors` counts the times a
source could not listen to a page or the service worker (a target that
did not answer within 5 s, a domain that could not be enabled, a source
that did not start). `lastCaptureError` is the newest one, redacted and
cut at 300 characters. An agent sees incomplete capture on every read,
without `DEBUG`.
- **`mm events mark`** → `{ cursor, summary }`. **`mm events clear
[--kind console|network]`** empties the buffer without resetting `seq`
(old cursors stay valid). Unknown arguments (`mark --kind x`, `clear
extra`, a missing `--kind` value) are usage errors (exit 2).
- **Redaction helpers** (`src/events/redact.ts`, from #106's
`redactUrl`): credentials (`user:pass@` → `[REDACTED]@`); host labels
and path segments of 24+ letters/digits (32-hex Infura keys); sensitive
query **and fragment** values (#93's body-field list + `key`, `token`,
`sig`, `jwt`, `session`, `projectId`, `signature`, `credential`, `code`,
…), matched by exact name and by suffix/prefix after normalization
(`infuraProjectId`, `api_token`, `access_key`, `x-api-key`, `authToken`,
`X-Amz-Credential`); `^auth` does not match
`author`/`authors`/`authority` and `^sig` only matches
`sig`/`sign`/`signature`, and a JWT or bare key used as a value is
redacted even under a harmless name. A JWT path segment is always
redacted, and an opaque segment after `v1`–`v4` (≥ 28 chars) is treated
as an API key, so a digitless Alchemy key is caught. `0x` addresses,
64-hex/base58 IDs after
`account(s)`/`address(es)`/`tx`/`transaction(s)`, and UUIDs under a real
path are kept; a UUID that is the only path segment is redacted
(Blast-style gateway). The same rules apply to URLs inside text;
trailing `.,;:!?`, `}` and `*` stay outside the redacted URL, a URL in
`[...]` is matched without its bracket, and a URL with nothing to redact
is left byte-for-byte as it appeared. A `scheme://user:pass@` URL of a
scheme the pattern does not know (`ftp:`, `postgres:`, `redis:`,
`mongodb+srv:`) is redacted by parsing the match, so a path with `:` and
`@` is not mistaken for a credential. Text (not only URLs) also loses
JWTs (`eyJ…`) and `Bearer` values (the value needs 8+ token characters,
so prose such as `the bearer of good news` stays). `passwd`, `pwd`,
`pass`, `bearer`, `seed`, `pk` and `mnemonic…` names are redacted;
`publicKey`, `pubKey`, `sortKey`, `cacheKey`, `primaryKey` and
`sourceToken`…`nativeToken` are allowlisted (not secrets). Trailing
punctuation is stripped in a backward loop, so a long run is linear (0.3
ms on 100 000 dots; the old regex took 4803.9 ms).
- **Auto-start**: `launch` starts the session's event sources on browser
sessions and never fails the launch. The first `events`/`logs`/`network`
call starts them again if the CDP manager was replaced.
- Every call that starts the sources (`launch`, `events`, `logs`,
`network`) waits at most 5 s (`SESSION_EVENTS_START_WAIT_MS`) for a
start in progress; the start keeps going. So a target that does not
answer cannot make later calls hang on the stored start.
- `SessionEvents.reportError` records a source error: it counts it in
`summary.captureErrors`, sets `lastCaptureError` and writes it to the
debug log. It never throws. #110 and #111 pass it as their
subscription's `onError`.
- `events` is a read-only, browser-only tool (zod schema, registry, CLI
help, README, SKILL.md). Mobile returns
`MM_TOOL_NOT_SUPPORTED_ON_PLATFORM`.

Part of the mm CLI v2 effort: ticket `P2-15` (Phase 2). Next: P2-16 `mm
logs` (stacked on this PR), P2-17 `mm network`.

**Shared #93 helper:** `redact.ts` uses `mock-network`'s
`isSensitiveBodyField` (now exported) and `REDACTED_VALUE`, so the body
field list has one source. It adds only the query parameter names
(`key`, `token`, `sig`, …) and the URL segment rule.

## Breaking changes

None.

## Consumer impact

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

## Proof

Ticket platform: unit. The live run also uses the real daemon + built
CLI on an MV3 test extension. The buffer is empty in this PR (no
sources).

| Check | Result |
|---|---|
| Overflow drops the oldest of that kind, counted; cursor before the
oldest kept → `gap: true` | ✅ unit |
| Cursor / `since` paging with `limit`: `hasMore`, no duplicates or
holes; an in-place update is not returned again | ✅ unit |
| `startedAt` changes on a new session; `clear` keeps `seq` | ✅ unit +
live (`startedAt 1795010983961 → 1795010991417` across `cleanup` +
`launch`) |
| Redaction table: Infura key in host and path, `apiKey=`, credentials
(HTTP and non-HTTP schemes), fragment pairs, JWT path and JWT/`Bearer`
in text, suffix/prefix names, digitless key, UUID only as the sole path
segment, `0x` address / 64-hex / base58 kept, URL inside text kept when
clean and byte-identical | ✅ 51 cases, plus a checked 76-URL / 32-text /
10-byte-identity table in the P2-15 proof; trailing punctuation 4803.9
ms → 0.3 ms on 100 000 dots |
| Stale cursor (`cursor > seq`) reads from the oldest record and reports
`gap: true` | ✅ unit |
| Bad flag (`mm events clear --kind`) | ✅ `MM_INVALID_INPUT`, exit 2 |
| A start that never finishes: a later `ensureStarted()` settles after 5
s and does not start the sources again | ✅ unit; reproduced as a hang
before the fix |
| A source error is counted, redacted and cut in `summary`; a source
that fails to start is recorded | ✅ unit; live `captureErrors: 0` on the
MetaMask e2e build with the top of the stack (below) |

<details>
<summary>Transcript</summary>

```
$ mm events mark
{"action":"mark","cursor":0,"summary":{"startedAt":1795010983961,"seq":0,"counts":{"console":0,"network":0},"dropped":{"console":0,"network":0}},...}
$ mm cleanup && mm launch && mm events mark
{"action":"mark","cursor":0,"summary":{"startedAt":1795010991417,"seq":0,...}}
$ mm events clear --kind
{"ok":false,"error":{"code":"MM_INVALID_INPUT","message":"Usage: mm events <mark | clear [--kind console|network]>","retryable":false}}
```

After #107's review round 4, on the MetaMask Extension e2e build with
the top of the stack (#111, `8b78f0e`), where the sources fill the
buffer:

```
$ mm events mark
{"action":"mark","cursor":20,"summary":{"startedAt":1795182411924,"seq":20,"counts":{"console":8,"network":6},"dropped":{"console":0,"network":0},"captureErrors":0},...}
```

</details>

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

```
 Test Files  68 passed (68)
      Tests  2581 passed (2581)
Type Errors  no errors
All files          |   98.29 |    95.95 |   97.83 |    98.4 |
yarn lint: exit 0
yarn build: exit 0
```

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

## Description

> [!IMPORTANT]
> **Stacked on #109** (P2-15), which stacks on #107 (P2-28, ready to
review on `main`). Review those first. This PR targets #109's branch.
#107's and #109's review fixes are merged in, with fix commits on top
for each review round. #111 (P2-17) stacks on it.

Release validation needs the console errors of each flow from every
Extension context. Most Extension errors come from the MV3 background
service worker. A page-level `console.error` hook never sees them, and
`mm cdp` could not reach the worker before #90.

- **Source** (`src/events/console-source.ts`): a `CdpManager.subscribe`
(#107) to `Runtime.consoleAPICalled` and `Runtime.exceptionThrown` on
every page and the service worker. Each event becomes a console record
in the P2-15 buffer: `{ seq, t, target, level, text, location?,
uncaught? }`.
- `level`: `error` | `warning` | `info` | `log` | `debug`.
`console.assert` counts as `error`. An uncaught exception is `error`
with `uncaught: true`.
- `text`: the arguments joined on one line, as DevTools does it: object
and array arguments render from the CDP `preview` (`{message: 'User
rejected', chainId: 1}`, `[1, 2]`, `…` when the preview overflowed; a
property whose name is sensitive (`privateKey`, `mnemonic`, `password`,
`token`, `key`, `*key`/`*token`, `secret`, `seed`, `pass`, `pk`, …)
renders as `[REDACTED]`, nested previews included; `publicKey`,
`sortKey`, `sourceToken` and similar are allowlisted; a named property
of an array prints `name: value`; only plain objects, arrays and proxies
render as a record, other subtypes keep their `description` such as
`Uint8Array(2)` or `Map(1)`). The preview name check is the
query-parameter check, so `code` is redacted too (`{code: [REDACTED]}`),
a safe-side false positive. Format specifiers (`%s %d %i %f %o %O %c`,
`%%`) are filled from the following arguments, and an uncaught exception
value uses the same rendering. URLs, JWTs and `Bearer` values are
redacted, and the text is cut at 2000 characters. A secret written in
free text (for example `new Error('decrypt failed for password …')`) is
not detected; SKILL.md says so.
  - `location`: 1-based `url:line:column` of the call or throw.
  - `t`: the CDP timestamp (epoch ms).
  - `target`: `{ kind: 'page'|'sw', id, url }`.
- **Default: `error` only.** `mm logs configure --levels error,warning`
widens it for the session; `warn` is accepted for `warning`. `configure`
accepts exactly `--levels <list>`: an extra argument, another flag or a
second `--levels` is a usage error (exit 2).
- **Replays dropped**: `Runtime.enable` replays console messages Chrome
kept (P2-28 finding). Messages older than the subscription, and repeats
(same target, timestamp, level, text), are ignored; the replay key is
remembered before the level filter, so a widened level does not replay
an old message.
- **`mm logs [--cursor N | --since <iso|ms>] [--limit N] [--grep
<re>]`** → `{ records, cursor, hasMore, gap, summary }`. `--grep` is a
case-sensitive JS regex of at most 256 characters (retried without `u`
when that does not compile); a value that starts with `--` must be
escaped (`--grep '\-\-x'`); unknown flags, missing values and a
`--limit` below 1 exit 2. The pattern runs in the daemon, so SKILL.md
warns against nested quantifiers such as `(a+)+`.
- **Errors are recorded**: the source passes `SessionEvents.reportError`
(#109) as its subscription's `onError`. A page or the worker that cannot
be attached or enabled within 5 s is counted in `summary.captureErrors`
instead of being dropped, so an agent knows that console records of that
target can be missing.
- Starts with the session (no command needed). Read-only, browser-only
tool; zod schema, CLI help, README, SKILL.md.

Part of the mm CLI v2 effort: ticket `P2-16` (Phase 2). Next: P2-17 `mm
network`.

## Breaking changes

None.

## Consumer impact

| Consumer | Change needed | Done on branch |
|---|---|---|
| Extension `test/e2e/playwright/llm-workflow/` | none | n/a |
| Mobile `tests/llm-workflow/` | none (browser only; Hermes source is a
follow-up) | n/a |

The Extension release-validation skill (Consensys/skills#122) can switch
from its page hook to `mm logs` when the command is present.

## Proof

Real daemon + built CLI. MV3 test extension in headless Chromium (page
`console.error`, uncaught page `TypeError`, worker `console.error` with
an Infura URL, `console.warn`, `console.log`).

| Check | Result |
|---|---|
| Worker and page `console.error`, uncaught page error, with the right
`target.kind` | ✅ |
| `console.warn` not recorded by default | ✅ |
| `console.warn` recorded after `mm logs configure --levels
error,warning` | ✅ |
| After `ServiceWorker.stopAllWorkers` (0 worker targets) and a wake,
new worker errors appear | ✅ |
| `--limit 1` paging (3 pages, no duplicates) | ✅ |
| Object/array/preview formatting, specifiers and exception text on real
CDP payloads | ✅ `probe/` (headless-Chromium capture + formatter
output); a second probe checks preview redaction and subtype
descriptions |
| Round-3 probe: a named array property, broader field names and the
allowlist on a real page | ✅ 14/14 (`probe-r3/`, through the daemon and
built CLI): `['one', 2, privateKey: [REDACTED], label: 'wallet']`,
`{mnemonicPhrase: [REDACTED], pk: [REDACTED], passwd: [REDACTED], seed:
[REDACTED]}`, `{publicKey: '0xpub', sortKey: 'abc', sourceToken:
'0xtoken'}`; no secret value in the output |
| `mm logs configure` with an extra argument or a second `--levels` | ✅
exit 2 (unit) |
| `events clear` keeps `seq` (11 → 11) | ✅ |
| Relaunch changes `startedAt` | ✅ |
| No Infura key / `apiKey` value in any output | ✅ |

<details>
<summary>Transcript</summary>

```
$ mm events mark                                  → cursor 0
$ mm navigate chrome-extension://…/trigger.html?tag=A
$ mm logs --cursor 0
{"records":[
 {"seq":1,"t":…,"target":{"kind":"page","id":"…","url":"chrome-extension://…/trigger.html?tag=A"},"level":"error","text":"page error for A","location":"chrome-extension://…/trigger.js:11:11"},
 {"seq":2,…,"target":{"kind":"page",…},"level":"error","text":"Uncaught TypeError: uncaught in page A\n    at chrome-extension://…/trigger.js:12:28","location":"…/trigger.js:12:28","uncaught":true},
 {"seq":3,…,"target":{"kind":"sw","id":"…","url":"chrome-extension://…/bg.js"},"level":"error","text":"bg flow A failed: https://mainnet.infura.io/v3/[REDACTED]","location":"chrome-extension://…/bg.js:27:11"}],
 "cursor":3,"hasMore":false,"gap":false,"summary":{"startedAt":…,"seq":3,"counts":{"console":3,"network":0},"dropped":{"console":0,"network":0}}}
$ mm logs configure --levels error,warning
# after worker stop + wake:
[8,"page","error","page error for C"] [9,"page","error","Uncaught TypeError: uncaught in page C …"]
[10,"sw","error","bg flow C failed: https://mainnet.infura.io/v3/[REDACTED]"] [11,"sw","warning","bg flow C warning"]
```

Recorded before #107's review round 4. `summary` now also has
`captureErrors` (0 in these runs) and, after an error,
`lastCaptureError`.

</details>

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

```
 Test Files  71 passed (71)
      Tests  2637 passed (2637)
Type Errors  no errors
All files          |   98.08 |    95.05 |   97.89 |   98.18 |
yarn lint: exit 0
yarn build: exit 0
```

New: `src/events/console-source.test.ts` (level mapping, argument
formatting, truncation, redaction, location, uncaught, replay filter,
level config, `onError` records a subscription error in
`captureErrors`), `src/tools/logs.test.ts` (cursor/since/limit/grep,
invalid grep, configure), CLI routing and schemas.

</details>
cryptotavares added a commit that referenced this pull request Nov 23, 2026
… worker (#111)

## Description

> [!IMPORTANT]
> **Stacked on #110** (P2-16) → #109 (P2-15) → #107 (P2-28, ready to
review on `main`). Review those first. This PR targets #110's branch.
#107's, #109's and #110's review fixes are merged in, with fix commits
on top for each review round.

Release validation needs, for each flow, the backend calls the wallet
made, with status, duration, failures and JSON-RPC methods. On the
Extension most of that traffic (gas, Blockaid, bridge, intents, Relay,
Hyperliquid) comes from the MV3 service worker. `mock-network` only sees
hosts it routes and records no timing. The closed #106 did this with
Playwright context events. This PR uses our own CDP sessions (#107)
instead, so it needs no minimum Playwright version, and a mobile source
can later fill the same record format.

- **Source** (`src/events/network-source.ts`):
`Network.requestWillBeSent` / `responseReceived` / `dataReceived` /
`loadingFinished` / `loadingFailed` on every page and the service
worker, joined by `(target.kind, target.targetId, requestId)` into **one
record per request**, updated in place. A record keeps its first `seq`
and gets a `settledSeq` when it ends, that is, when no field of it can
change any more (its `rpcError` read, when configured, included). An
unfiltered read returns records in `seq` order; a filtered one returns
settled records in `settledSeq` order.
  ```
{ seq, settledSeq?, t, target: { kind: 'page'|'sw', id, url }, method,
url, type, status?, ms?, failure?, rpcMethods?, rpcError? }
  ```
  - `t`: request start (`wallTime`, epoch ms).
- `ms`: CDP monotonic time from the start to the finish or the failure.
  - `type`: lowercase CDP resource type.
- `status` is kept when a request fails after its response; `failure` is
then set too.
- `failure`: CDP `errorText` (+ blocked reason, + `cors:
<CorsErrorStatus>` when Chrome reports one), redacted; `target closed`
when the page or worker goes away mid-request or the source restarts;
`abandoned` when the request is dropped from the pending limit.
  - `url`: redacted with the P2-15 rules.
- `rpcMethods`: **always an array**, parsed from the JSON-RPC request
body (`postData` / `postDataEntries`, up to 64 KiB; single and batch).
Absent for non-RPC requests. A method name is cut at 128 characters.
- Only `http(s)` URLs are recorded. Others are counted in
`stats.ignored`.
- A redirect ends its hop with the redirect status and starts a new
record (one record per hop).
- **`rpcError` `{ code, message }`, opt-in**: `mm network configure
--rpc-errors` reads `Network.getResponseBody` for JSON-RPC requests
only.
- Limits: up to 64 KiB **decoded** (sum of
`Network.dataReceived.dataLength`, else `encodedDataLength`), 8 reads at
once, 2 s timeout. Skipped reads are counted in
`stats.rpcErrorsSkipped`. Off by default. `Network.enable` caps the
response buffers (128 KiB per resource, 1 MiB total) since no bodies are
kept otherwise.
- The read runs on the request's own target session, through the new
`CdpManager.sendToEventTarget`, with the target lookup inside the
timeout. It never re-attaches a gone target.
- **`mm network [--cursor N | --since <iso|ms>] [--limit N] [--url
<glob|text>] [--errors] [--settled]`** → `{ records, cursor, hasMore,
gap, summary, stats: { pending, ignored, rpcErrorsSkipped } }`.
  - `--errors`: status ≥ 400, `failure` or `rpcError`.
- `--url`: a glob (`*`, `**`) or a substring, like `mock-network
requests --url` (#93).
- **Settled reads**: an unfiltered read returns every record in start
order (`seq`), pending requests included, and its cursor moves past all
of them. A read with `--url` or `--errors` returns only **settled**
requests, in `settledSeq` order: a request may become a match only when
it ends (a 404, a failure, an `rpcError`), so it is returned once by the
read that follows its end, even when it started before the cursor. The
cursor stays a plain buffer position (one counter shared by appends and
settles), so a record that settles after a read always lands above the
returned cursor. A cursor continues reads of the same mode. For an
unfiltered read, use a cursor from `mm events mark` or from an
unfiltered read: a cursor from a filtered or `--settled` read can be
past a request that is still open. SKILL.md says this. `--settled` asks
for that same settle-order read without a filter (value-less, like
`--errors`): one call at the end of a step reads the final status of
every request that ended since the mark, including ones started earlier;
requests still open are not returned. An unsettled request is never
returned by a filtered or `--settled` read, so a request that never ends
never matches one. `--since` compares the request start (`t`), not when
it ended (documented).
- **Pending requests end with their target**: a request whose page
closes, whose worker stops or that is still open when the source
restarts is finalized with `failure: "target closed"` and stops counting
in `stats.pending`; a request dropped from the pending limit is
finalized with `failure: "abandoned"`.
- **Errors are recorded**: the source passes `SessionEvents.reportError`
(#109) as its subscription's `onError`. An attach timeout, a failed
`Network.enable`, or `Network.enable` params that another subscriber set
first are counted in `summary.captureErrors` instead of being dropped.
- **`mm cdp` while recording**: the session holds `Network` on every
page and the worker from `mm launch` on. `mm cdp Network.enable` (no
params) still succeeds and sends nothing (#107). `Network.disable`, or
`Network.enable` with other params, is refused with `MM_CDP_BLOCKED`,
because it would stop or change what `mm network` records; `--fresh`
still works. SKILL.md says this.
- Starts with the session. Passive: it never routes, blocks or changes a
request, and it stores no bodies. Read-only, browser-only tool. Also
adds the zod schema, CLI help, README, and SKILL.md with the per-flow
recipe (`mark` → `network`/`logs --cursor`, `startedAt` check, capture
gap). Unknown read flags and missing values exit 2; `configure` takes
exactly one of `--rpc-errors` / `--no-rpc-errors`.

Part of the mm CLI v2 effort: ticket `P2-17` (Phase 2).

**Shared #93 helper:** `--url` uses `mock-network`'s `matchesUrlFilter`,
so `mm network --url` and `mm mock-network requests --url` match URLs
the same way.

## Breaking changes

None.

## Consumer impact

| Consumer | Change needed | Done on branch |
|---|---|---|
| Extension `test/e2e/playwright/llm-workflow/` | none | n/a |
| Mobile `tests/llm-workflow/` | none (browser only; mobile source after
P2-00 S1/S3) | n/a |

The Extension release-validation skill (Consensys/skills#122) can take
one `mm events mark` at flow start and read `mm network` / `mm logs` at
flow end, falling back to its `mock-network` recorder on older `mm`. The
reports importer maps `failure` / `text` / `rpcMethods` / `target`.

## Proof

Real daemon (`createServer` from the built `dist/`) + built CLI,
headless Chromium, read-only, no funds. Rerun after the review fixes on
the rebuilt `dist/` of this head (`ce385a3`): **12/12** harness checks
pass (the new `17.5` is the `--settled` end-to-end scenario), the
redaction grep finds nothing (18 × `[REDACTED]`), and the 22 `mm
events|logs|network` reads take a mean of 96 ms wall-clock (max 130 ms,
CLI start included). A live late-settle check on the same `dist/`: a 2 s
page `fetch` started before a filtered read (read returns 0 records,
cursor 3), then the next read with cursor 3 returns it once (`seq` 3,
`settledSeq` 4), and the read after that returns nothing.

| Check | Result |
|---|---|
| Worker `fetch` 200 / 404 / aborted and a page `fetch`: status or
`failure`, `ms`, `target.kind` | ✅ `sw … 200 123ms`, `sw … 404 0ms`, `sw
… net::ERR_ABORTED 60ms`, `page … 200 122ms` |
| Single and batch JSON-RPC POST → `rpcMethods` | ✅ `["eth_call"]`,
`["eth_chainId","eth_blockNumber"]` |
| `--rpc-errors`: `execution reverted` → `rpcError` | ✅
`{"code":-32000,"message":"execution reverted"}`; the batch without
errors has none; `rpcErrorsSkipped` 0 |
| After `ServiceWorker.stopAllWorkers` (0 worker targets) and a wake | ✅
new worker requests appear, including the worker's start-up `?boot=1`
fetch |
| Relaunch | ✅ changes `summary.startedAt`; `seq` restarts; an old
cursor reads the new session from the start (`gap: true`) |
| Grep for the fake Infura key (path) and `apiKey=supersecret` (query)
over every CLI output | ✅ not found; 18 × `[REDACTED]` |
| `--limit 3` paging | ✅ 2 pages, no duplicates |
| `--errors`, `--url` glob, `events clear` keeps `seq`, bad flag | ✅
(bad flag: exit 2) |
| `--settled --cursor <mark>`: only settled requests, in `settledSeq`
order, with final status; a repeat with the returned cursor returns none
| ✅ `17.5`: 6 settled (csv 22,26,27,29,32,33), `settledSeq` 29 is the
`execution reverted` request, repeat 0 records, `gap` false |
| MetaMask test build 13.56.0 (`dist/chrome`, first screen, no wallet) |
✅ worker `GET https://accounts.api.cx.metamask.io/v2/supportedNetworks
200 60ms`, `chainid.network` 200, refused e2e fixture ports as
`net::ERR_CONNECTION_REFUSED`; 90 `chrome-extension://` loads ignored |
| Read cost | ✅ 22 `mm events/logs/network` calls: mean 96 ms wall-clock
(CLI start included), max 130 ms |
| After #107's review round 4 (head `8b78f0e`), MetaMask e2e build: `mm
cdp Network.enable` (page, `sw`), then `Network.disable` and
`Network.enable` with other params | ✅ `{}`; then `MM_CDP_BLOCKED` (exit
2). `mm network --cursor <mark>` still records a page and a worker fetch
afterwards; `captureErrors` 0 |
| Filtered read with an open request | ✅ unit: pending → fails → next
`--errors` read returns it once; a record that settles after the read
(even one older than the cursor) is returned once; `limit: 1` pages late
failures; unfiltered reads unchanged. Live: late-settle check above |

<details>
<summary>Transcript (MV3 test extension)</summary>

```
$ mm events mark          → {"cursor":1,"summary":{"startedAt":1795010960760,"seq":1,...}}
$ mm navigate chrome-extension://…/trigger.html?tag=A
$ mm network --cursor 1 --limit 3     (2 pages)
  2 page GET http://127.0.0.1:47123/ok?from=page 200 122ms
  5 sw GET http://127.0.0.1:47123/ok?tag=A&apiKey=[REDACTED] 200 123ms
  6 sw GET http://127.0.0.1:47123/missing?tag=A 404 0ms
  7 sw POST http://127.0.0.1:47123/v3/[REDACTED] 200 41ms rpc=eth_call
  8 sw POST http://127.0.0.1:47123/v3/[REDACTED] 200 43ms rpc=eth_chainId,eth_blockNumber
  9 sw GET http://127.0.0.1:47123/slow - 60ms net::ERR_ABORTED
$ mm network configure --rpc-errors
$ mm network --cursor 12 --errors
  15 sw GET …/missing?tag=B 404 1ms
  16 sw POST …/v3/[REDACTED] 200 43ms rpc=eth_call rpcError=-32000:execution reverted
  18 sw GET …/slow - 58ms net::ERR_ABORTED

{"seq":16,"t":1795010963306,"target":{"kind":"sw","id":"D5F965B86CF62F7BC00A489B9B488D12","url":"chrome-extension://ocffhifhkanmalpagbcoojhomhpifmpp/bg.js"},
 "method":"POST","url":"http://127.0.0.1:47123/v3/[REDACTED]","type":"fetch","rpcMethods":["eth_call"],"status":200,"ms":43,
 "rpcError":{"code":-32000,"message":"execution reverted"}}
```

Recorded before #107's review round 4. `summary` now also has
`captureErrors` (0 in these runs) and, after an error,
`lastCaptureError`.

</details>

<details>
<summary>MetaMask test build (first screen, no wallet)</summary>

```
mark 0 (records already in the buffer since launch: {"console":0,"network":0})
network after mark: 5 records {"sw":4,"page":1}; stats {"pending":0,"ignored":90,"rpcErrorsSkipped":0}
  1 sw GET http://localhost:12345/state.json - 245ms net::ERR_CONNECTION_REFUSED
  2 sw GET https://chainid.network/chains.json 200 140ms
  3 sw GET https://chainid.network/chains.json 200 136ms
  4 sw GET https://accounts.api.cx.metamask.io/v2/supportedNetworks 200 60ms
  6 page GET http://localhost:9999/ - 1ms net::ERR_CONNECTION_REFUSED
logs: 5 sw error SocketBackgroundToMocha WebSocket error: Event
```

The e2e build's onboarding screen sends little: wallet traffic (gas,
Blockaid, RPC) needs an unlocked wallet, which this proof does not
create.

</details>

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

```
 Test Files  74 passed (74)
      Tests  2715 passed (2715)
Type Errors  no errors
All files          |   98.07 |     95.2 |   97.71 |   98.18 |
yarn lint: exit 0
yarn build: exit 0
```

New: `src/events/network-source.test.ts` (join, in-place update,
failure, redirect hops (each hop settles), per-target keys, ignored
URLs, `postData`/`postDataEntries`, pending cap, `rpcError` on/off
(settles after the read, including skipped and failed reads), base64,
decoded vs encoded size, size/concurrency/failure skips, `dataReceived`,
`targetDetached` finalization, CORS reason, settle on
finish/fail/redirect/start), `src/events/event-buffer.test.ts` (settle
order, paging by settle position, gap (a dropped unsettled record,
`since`), dropped/cleared records never settle, stale cursor, `since` on
`t`, one cursor across kinds), `src/events/json-rpc.test.ts` (method
cap), `src/tools/network.test.ts` (late settle after a read, older
record, `limit: 1` paging, unfiltered reads unchanged, `settled: true`
end-to-end), `src/events/network-source.test.ts` (`abandoned`, `target
closed` on restart), `CdpManager sendToEventTarget` and `targetId`
(timeout, race), `onError` records subscription errors in
`captureErrors`, CLI routing and schemas.

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

3 participants