Skip to content

feat: add mm network, a passive request log for pages and the service worker - #111

Merged
cryptotavares merged 6 commits into
cryptotavares/mmcli-p2-16-logsfrom
cryptotavares/mmcli-p2-17-network
Nov 23, 2026
Merged

cryptotavares merged 6 commits into
cryptotavares/mmcli-p2-16-logsfrom
cryptotavares/mmcli-p2-17-network

Conversation

@cryptotavares

@cryptotavares cryptotavares commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

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 (feat: record request bodies in mock-network #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 (feat: add a session event buffer with one cursor and mm events mark #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 (feat: deliver CDP events from pages and the service worker #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
Transcript (MV3 test extension)
$ 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.

MetaMask test build (first screen, no wallet)
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.

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

… worker

Joins Network.requestWillBeSent / responseReceived / loadingFinished /
loadingFailed from every page and the Extension service worker into one
record per request, keyed by (target kind, target id, request id) and
updated in place: method, redacted URL, type, status, ms, failure and
rpcMethods (always an array; single and batch JSON-RPC bodies). Only
http(s) requests are recorded; others are counted as ignored. A redirect
gives one record per hop.

'mm network configure --rpc-errors' reads JSON-RPC response bodies with
Network.getResponseBody (64 KiB, 8 at a time, 2 s timeout; skipped reads
are counted) and records { code, message } as rpcError. Off by default.
Adds CdpManager.sendToEventTarget for commands on the target of an event.

'mm network' reads with --cursor/--since/--limit/--url/--errors.
@cryptotavares
cryptotavares force-pushed the cryptotavares/mmcli-p2-17-network branch from 48c7db6 to ce385a3 Compare November 18, 2026 18:51
@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
…into cryptotavares/mmcli-p2-17-network

# Conflicts:
#	CHANGELOG.md
@cryptotavares
cryptotavares added this pull request to stack #113 November 19, 2026 16:24
…into cryptotavares/mmcli-p2-17-network

# Conflicts:
#	SKILL.md
#	src/events/session-events.ts
#	src/platform/cdp-manager.test.ts
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).
@pnarayanaswamy

Copy link
Copy Markdown
Contributor
  • Cursor continuation with open requests (SKILL.md L825, event-buffer.ts #readSettled) — SKILL.md says "every cursor … also continues … an unfiltered read once hasMore is false". That doesn't hold when a request is still open:

    1. R starts and stays open (seq 6)
    2. S starts and ends (seq 7, settledSeq 8)
    3. mm network --settled --cursor 0 → S, cursor 8
    4. mm network --cursor 8 never returns R (6 ≤ 8); it only reappears through a settled read.

    The documented mark-based recipe isn't affected. Either cap the returned cursor below the oldest open request's seq, or drop that sentence.

  • EventBuffer.settle(kind, record) doesn't check that record belongs to kind. A wrong caller would consume a seq and set settledSeq on the wrong record. A one-line membership guard would cover it.

  • Design (follow-up is fine): appends and settles sharing one counter makes seq skip values, makes every settled read filter + sort the whole buffer, and is where the gap above comes from. Separate append/settle counters with an ordered settled list would be simpler; cursors wouldn't carry across modes, but they already don't fully.

  • Minor: a request that fails after responseReceived keeps both status and failure, while SKILL.md describes failure as failing before a response.

@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 8b78f0e: no new commits since my last pass. One docs/behaviour mismatch on cursors, rest minor; comments inline.

hasMore && last !== undefined
? last.settledSeq
: Math.max(cursor, this.#seq),
hasMore,

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.

When a settled read is exhausted, the cursor jumps to this.#seq, past the seq of requests that are still open. Scenario:

  1. R starts and stays open (seq 6)
  2. S starts and ends (seq 7, settledSeq 8)
  3. mm network --settled --cursor 0 → S, cursor 8
  4. mm network --cursor 8 never returns R (6 ≤ 8); it only comes back through a settled read.

The mark-based recipe isn't affected. Fix: cap this cursor below the oldest open record's seq, or drop the claim in SKILL.md L825.

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.

Docs fixed in 921d44c, code unchanged: SKILL.md now says a cursor from a filtered or --settled read continues reads of the same mode; for an unfiltered read, use a cursor from mm events mark or an unfiltered read. Changing the cursor contract is a larger change than this PR.

Comment thread SKILL.md Outdated

`--url` takes a glob (`*`, `**`) or plain text the URL must contain. `--errors` keeps status >= 400, `failure` and `rpcError`. Only `http(s)` requests are recorded (`stats.ignored` counts the rest). A redirect gives one record per hop.

An unfiltered read returns every record in start order (`seq`), pending requests included, and the cursor moves past all of them. A filtered read (`--url`, `--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 by the read that follows its end, once, even when it started before the cursor. `--settled` asks for that same settle-order read without a filter: at the end of a step, read `--settled --cursor <mark>` to get the final status of every request that finished since the mark, including ones started earlier; requests still open are not returned yet. An unsettled request is never returned by a filtered or `--settled` read, so a request that never ends never matches one. In every case `--since` compares the request start (`t`), not when it ended. Every cursor is a buffer position, so it also continues a read of the other kind or an unfiltered read once `hasMore` is false.

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.

"so it also continues … an unfiltered read once hasMore is false": not true while a request is still open (see the comment on event-buffer.ts L310).

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.

Same fix in 921d44c: the sentence no longer says a cursor continues an unfiltered read. The README network rows and the tool/schema descriptions do not repeat the old claim.

* @param kind - The record kind.
* @param record - The record to settle.
*/
settle(kind: EventKind, record: EventRecordBase): 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.

settle(kind, record) doesn't check that record belongs to kind. A wrong caller would consume a seq and set settledSeq on the wrong record. A membership guard (state.records.includes(record)) would cover it.

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.

Not changed: settle() has one internal caller, and an includes check would add a linear scan to every settle. A wrong caller is a programming error rather than an input the buffer must tolerate.

const maxRecords =
Number.isFinite(limit) && limit >= 1 ? Math.floor(limit) : 1;
const state = this.#kinds[kind];
const settled = (state.records as RecordType[])

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.

Design note, follow-up is fine: appends and settles sharing one counter means seq skips values, every settled read filters + sorts the whole buffer, and the cursor gap above comes from this. Separate append/settle counters plus an ordered settled list would be simpler; cursors wouldn't carry across modes, but they already don't fully.

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.

Not changed here; noted as a follow-up. The current cursor semantics are now documented in SKILL.md.

reasons.push(`cors: ${params.corsErrorStatus.corsError}`);
}
const reason = reasons.length === 0 ? '' : ` (${reasons.join('; ')})`;
pending.record.failure = redactText(

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.

Minor: when loadingFailed comes after responseReceived, the record keeps status and gets failure. SKILL.md describes failure as failing before a response. Either clear status or adjust the doc.

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.

Docs fixed in 921d44c: the status row now says it is absent while pending and when the request failed before a response, and that a request that fails after its response keeps it; the failure row says it can come before or after the response.

- A cursor from a filtered or --settled read continues reads of the same
  mode; for an unfiltered read, use a mark or unfiltered-read cursor.
- status is absent while pending and when a request failed before a
  response; a request that fails after its response keeps it and gets a
  failure too.
@cryptotavares

Copy link
Copy Markdown
Collaborator Author

Thanks Priya — #110 is merged into the branch (01f3eab) and docs commit 921d44c fixes the two doc claims; no code changed for them. yarn build, yarn lint and CI=1 yarn test pass (74 files, 2715 tests; coverage 98.07 / 95.2 / 97.71 / 98.18).

@cryptotavares
cryptotavares merged commit da46a66 into main Nov 23, 2026
27 checks passed
@cryptotavares
cryptotavares deleted the cryptotavares/mmcli-p2-17-network branch November 23, 2026 14:01
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>
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>
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