Repository navigation
feat: add mm network, a passive request log for pages and the service worker - #111
Conversation
d064833 to
7e49d95
Compare
7e49d95 to
c5140f5
Compare
c5140f5 to
48c7db6
Compare
… 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.
48c7db6 to
ce385a3
Compare
…into cryptotavares/mmcli-p2-17-network # Conflicts: # CHANGELOG.md
…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
left a comment
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
When a settled read is exhausted, the cursor jumps to this.#seq, past the seq of requests that are still open. Scenario:
- R starts and stays open (
seq6) - S starts and ends (
seq7,settledSeq8) mm network --settled --cursor 0→ S, cursor 8mm network --cursor 8never 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.
There was a problem hiding this comment.
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.
|
|
||
| `--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. |
There was a problem hiding this comment.
"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).
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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[]) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
…into cryptotavares/mmcli-p2-17-network
- 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.
## 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>
…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>
#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>
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-networkonly 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.src/events/network-source.ts):Network.requestWillBeSent/responseReceived/dataReceived/loadingFinished/loadingFailedon 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 firstseqand gets asettledSeqwhen it ends, that is, when no field of it can change any more (itsrpcErrorread, when configured, included). An unfiltered read returns records inseqorder; a filtered one returns settled records insettledSeqorder.t: request start (wallTime, epoch ms).ms: CDP monotonic time from the start to the finish or the failure.type: lowercase CDP resource type.statusis kept when a request fails after its response;failureis then set too.failure: CDPerrorText(+ blocked reason, +cors: <CorsErrorStatus>when Chrome reports one), redacted;target closedwhen the page or worker goes away mid-request or the source restarts;abandonedwhen 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.http(s)URLs are recorded. Others are counted instats.ignored.rpcError{ code, message }, opt-in:mm network configure --rpc-errorsreadsNetwork.getResponseBodyfor JSON-RPC requests only.Network.dataReceived.dataLength, elseencodedDataLength), 8 reads at once, 2 s timeout. Skipped reads are counted instats.rpcErrorsSkipped. Off by default.Network.enablecaps the response buffers (128 KiB per resource, 1 MiB total) since no bodies are kept otherwise.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,failureorrpcError.--url: a glob (*,**) or a substring, likemock-network requests --url(feat: record request bodies in mock-network #93).seq), pending requests included, and its cursor moves past all of them. A read with--urlor--errorsreturns only settled requests, insettledSeqorder: a request may become a match only when it ends (a 404, a failure, anrpcError), 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 frommm events markor from an unfiltered read: a cursor from a filtered or--settledread can be past a request that is still open. SKILL.md says this.--settledasks 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--settledread, so a request that never ends never matches one.--sincecompares the request start (t), not when it ended (documented).failure: "target closed"and stops counting instats.pending; a request dropped from the pending limit is finalized withfailure: "abandoned".SessionEvents.reportError(feat: add a session event buffer with one cursor and mm events mark #109) as its subscription'sonError. An attach timeout, a failedNetwork.enable, orNetwork.enableparams that another subscriber set first are counted insummary.captureErrorsinstead of being dropped.mm cdpwhile recording: the session holdsNetworkon every page and the worker frommm launchon.mm cdp Network.enable(no params) still succeeds and sends nothing (feat: deliver CDP events from pages and the service worker #107).Network.disable, orNetwork.enablewith other params, is refused withMM_CDP_BLOCKED, because it would stop or change whatmm networkrecords;--freshstill works. SKILL.md says this.mark→network/logs --cursor,startedAtcheck, capture gap). Unknown read flags and missing values exit 2;configuretakes exactly one of--rpc-errors/--no-rpc-errors.Part of the mm CLI v2 effort: ticket
P2-17(Phase 2).Shared #93 helper:
--urlusesmock-network'smatchesUrlFilter, somm network --urlandmm mock-network requests --urlmatch URLs the same way.Breaking changes
None.
Consumer impact
test/e2e/playwright/llm-workflow/tests/llm-workflow/The Extension release-validation skill (Consensys/skills#122) can take one
mm events markat flow start and readmm network/mm logsat flow end, falling back to itsmock-networkrecorder on oldermm. The reports importer mapsfailure/text/rpcMethods/target.Proof
Real daemon (
createServerfrom the builtdist/) + built CLI, headless Chromium, read-only, no funds. Rerun after the review fixes on the rebuiltdist/of this head (ce385a3): 12/12 harness checks pass (the new17.5is the--settledend-to-end scenario), the redaction grep finds nothing (18 ×[REDACTED]), and the 22mm events|logs|networkreads take a mean of 96 ms wall-clock (max 130 ms, CLI start included). A live late-settle check on the samedist/: a 2 s pagefetchstarted before a filtered read (read returns 0 records, cursor 3), then the next read with cursor 3 returns it once (seq3,settledSeq4), and the read after that returns nothing.fetch200 / 404 / aborted and a pagefetch: status orfailure,ms,target.kindsw … 200 123ms,sw … 404 0ms,sw … net::ERR_ABORTED 60ms,page … 200 122msrpcMethods["eth_call"],["eth_chainId","eth_blockNumber"]--rpc-errors:execution reverted→rpcError{"code":-32000,"message":"execution reverted"}; the batch without errors has none;rpcErrorsSkipped0ServiceWorker.stopAllWorkers(0 worker targets) and a wake?boot=1fetchsummary.startedAt;seqrestarts; an old cursor reads the new session from the start (gap: true)apiKey=supersecret(query) over every CLI output[REDACTED]--limit 3paging--errors,--urlglob,events clearkeepsseq, bad flag--settled --cursor <mark>: only settled requests, insettledSeqorder, with final status; a repeat with the returned cursor returns none17.5: 6 settled (csv 22,26,27,29,32,33),settledSeq29 is theexecution revertedrequest, repeat 0 records,gapfalsedist/chrome, first screen, no wallet)GET https://accounts.api.cx.metamask.io/v2/supportedNetworks 200 60ms,chainid.network200, refused e2e fixture ports asnet::ERR_CONNECTION_REFUSED; 90chrome-extension://loads ignoredmm events/logs/networkcalls: mean 96 ms wall-clock (CLI start included), max 130 ms8b78f0e), MetaMask e2e build:mm cdp Network.enable(page,sw), thenNetwork.disableandNetwork.enablewith other params{}; thenMM_CDP_BLOCKED(exit 2).mm network --cursor <mark>still records a page and a worker fetch afterwards;captureErrors0--errorsread returns it once; a record that settles after the read (even one older than the cursor) is returned once;limit: 1pages late failures; unfiltered reads unchanged. Live: late-settle check aboveTranscript (MV3 test extension)
Recorded before #107's review round 4.
summarynow also hascaptureErrors(0 in these runs) and, after an error,lastCaptureError.MetaMask test build (first screen, no wallet)
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
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,rpcErroron/off (settles after the read, including skipped and failed reads), base64, decoded vs encoded size, size/concurrency/failure skips,dataReceived,targetDetachedfinalization, 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,sinceont, 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: 1paging, unfiltered reads unchanged,settled: trueend-to-end),src/events/network-source.test.ts(abandoned,target closedon restart),CdpManager sendToEventTargetandtargetId(timeout, race),onErrorrecords subscription errors incaptureErrors, CLI routing and schemas.