Repository navigation
feat: add mm logs for console errors from pages and the service worker - #110
cryptotavares merged 6 commits into
Conversation
704d697 to
19aa455
Compare
19aa455 to
20224ca
Compare
20224ca to
9ef48e3
Compare
Records Runtime.consoleAPICalled and Runtime.exceptionThrown from every
page and the Extension service worker (through CdpManager.subscribe)
into the session event buffer. Only 'error' is recorded by default
(console.assert and uncaught exceptions included); 'mm logs configure
--levels' widens it for the session. Text is redacted and cut at 2000
characters. Messages replayed by Runtime.enable (older than the source,
or seen already) are dropped. 'mm logs' reads with --cursor/--since/
--limit/--grep and returns { records, cursor, hasMore, gap, summary }.
9ef48e3 to
2b3db17
Compare
…' into cryptotavares/mmcli-p2-16-logs # Conflicts: # CHANGELOG.md
…' into cryptotavares/mmcli-p2-16-logs # Conflicts: # src/events/session-events.ts
The console source passes SessionEvents.reportError as the onError of its CDP subscription, so a target it cannot attach or enable in time is counted in summary.captureErrors instead of being dropped (review of #107).
|
CDP
|
pnarayanaswamy
left a comment
There was a problem hiding this comment.
Re-review on aebd8cc: no new commits since my last pass. Timestamps, dedupe bound, specifiers and onError wiring look right; comments inline.
| return 'null'; | ||
| } | ||
| if (arg.subtype === 'error' && arg.description !== undefined) { | ||
| return arg.description; |
There was a problem hiding this comment.
Error description (message + stack) is returned as-is and later only gets the URL/JWT/Bearer rules. console.error(new Error('decrypt failed for password hunter2')) comes through unredacted. Same for plain string properties ({msg: 'apiKey=xyz'}). Worth either scrubbing or calling it out in SKILL.md, since release validation will consume this.
There was a problem hiding this comment.
Docs only, in 16586ad: SKILL.md now says the record text (console arguments, error messages and stacks, uncaught exceptions) is redacted only for URLs, JWTs, Bearer values and sensitive property names in object previews; a secret in free text, such as new Error('… password hunter2'), is not detected.
| details.exception === undefined | ||
| ? undefined | ||
| : formatArg(details.exception); | ||
| const prefix = details.text ?? 'Uncaught'; |
There was a problem hiding this comment.
Same for uncaught exceptions: details.text + formatArg(details.exception) carry Error.message and the stack. The PR description mentions the string-arg gap but not this path.
There was a problem hiding this comment.
Same docs change in 16586ad: uncaught exceptions are named explicitly in the SKILL.md sentence, and the text description covers their message and stack.
| return; | ||
| } | ||
| const { record, timestamp } = built; | ||
| if (timestamp !== undefined) { |
There was a problem hiding this comment.
Nit: with no CDP timestamp, the replay/dedupe check is skipped entirely. Chrome always sets it today, but falling back to event.t for the key would be safer.
There was a problem hiding this comment.
Not changed: Chrome always sets timestamp on these events, and with no timestamp the record is still kept — only the replay/dedupe filter is skipped.
| ); | ||
| } | ||
| try { | ||
| grep = new RegExp(input.grep, 'u'); |
There was a problem hiding this comment.
--grep is compiled from user input and run synchronously in the daemon over up to ~2 MB (L82). A pattern like (a+)+b blocks the whole daemon, not just this call. At least document it in the help/SKILL.md.
There was a problem hiding this comment.
Documented in 16586ad: the SKILL.md --grep text and the README mm logs row now say the pattern runs in the daemon, so avoid nested quantifiers such as (a+)+.
| failUsage(usage); | ||
| } | ||
| if (integerFlags.has(flag)) { | ||
| const parsed = parseInt(value, 10); |
There was a problem hiding this comment.
Nit: --limit -5 passes (parseInt isn't NaN) and the buffer then quietly reads 1 record. A parsed < 1 check → failUsage would match the other usage errors.
There was a problem hiding this comment.
Fixed in 16586ad: --limit 0 and --limit -5 are usage errors (exit 2), --cursor 0 still passes, and a CLI test covers both.
…' into cryptotavares/mmcli-p2-16-logs
- mm logs/network read flags: a --limit below 1 is a usage error (exit 2); --cursor still accepts 0. - SKILL.md/README: text is redacted only for URLs, JWTs, Bearer values and sensitive object property names, so a secret in free text is not detected. - SKILL.md/README: --grep runs in the daemon, so avoid nested quantifiers.
## 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>
… worker (#111) ## Description > [!IMPORTANT] > **Stacked on #110** (P2-16) → #109 (P2-15) → #107 (P2-28, ready to review on `main`). Review those first. This PR targets #110's branch. #107's, #109's and #110's review fixes are merged in, with fix commits on top for each review round. Release validation needs, for each flow, the backend calls the wallet made, with status, duration, failures and JSON-RPC methods. On the Extension most of that traffic (gas, Blockaid, bridge, intents, Relay, Hyperliquid) comes from the MV3 service worker. `mock-network` only sees hosts it routes and records no timing. The closed #106 did this with Playwright context events. This PR uses our own CDP sessions (#107) instead, so it needs no minimum Playwright version, and a mobile source can later fill the same record format. - **Source** (`src/events/network-source.ts`): `Network.requestWillBeSent` / `responseReceived` / `dataReceived` / `loadingFinished` / `loadingFailed` on every page and the service worker, joined by `(target.kind, target.targetId, requestId)` into **one record per request**, updated in place. A record keeps its first `seq` and gets a `settledSeq` when it ends, that is, when no field of it can change any more (its `rpcError` read, when configured, included). An unfiltered read returns records in `seq` order; a filtered one returns settled records in `settledSeq` order. ``` { seq, settledSeq?, t, target: { kind: 'page'|'sw', id, url }, method, url, type, status?, ms?, failure?, rpcMethods?, rpcError? } ``` - `t`: request start (`wallTime`, epoch ms). - `ms`: CDP monotonic time from the start to the finish or the failure. - `type`: lowercase CDP resource type. - `status` is kept when a request fails after its response; `failure` is then set too. - `failure`: CDP `errorText` (+ blocked reason, + `cors: <CorsErrorStatus>` when Chrome reports one), redacted; `target closed` when the page or worker goes away mid-request or the source restarts; `abandoned` when the request is dropped from the pending limit. - `url`: redacted with the P2-15 rules. - `rpcMethods`: **always an array**, parsed from the JSON-RPC request body (`postData` / `postDataEntries`, up to 64 KiB; single and batch). Absent for non-RPC requests. A method name is cut at 128 characters. - Only `http(s)` URLs are recorded. Others are counted in `stats.ignored`. - A redirect ends its hop with the redirect status and starts a new record (one record per hop). - **`rpcError` `{ code, message }`, opt-in**: `mm network configure --rpc-errors` reads `Network.getResponseBody` for JSON-RPC requests only. - Limits: up to 64 KiB **decoded** (sum of `Network.dataReceived.dataLength`, else `encodedDataLength`), 8 reads at once, 2 s timeout. Skipped reads are counted in `stats.rpcErrorsSkipped`. Off by default. `Network.enable` caps the response buffers (128 KiB per resource, 1 MiB total) since no bodies are kept otherwise. - The read runs on the request's own target session, through the new `CdpManager.sendToEventTarget`, with the target lookup inside the timeout. It never re-attaches a gone target. - **`mm network [--cursor N | --since <iso|ms>] [--limit N] [--url <glob|text>] [--errors] [--settled]`** → `{ records, cursor, hasMore, gap, summary, stats: { pending, ignored, rpcErrorsSkipped } }`. - `--errors`: status ≥ 400, `failure` or `rpcError`. - `--url`: a glob (`*`, `**`) or a substring, like `mock-network requests --url` (#93). - **Settled reads**: an unfiltered read returns every record in start order (`seq`), pending requests included, and its cursor moves past all of them. A read with `--url` or `--errors` returns only **settled** requests, in `settledSeq` order: a request may become a match only when it ends (a 404, a failure, an `rpcError`), so it is returned once by the read that follows its end, even when it started before the cursor. The cursor stays a plain buffer position (one counter shared by appends and settles), so a record that settles after a read always lands above the returned cursor. A cursor continues reads of the same mode. For an unfiltered read, use a cursor from `mm events mark` or from an unfiltered read: a cursor from a filtered or `--settled` read can be past a request that is still open. SKILL.md says this. `--settled` asks for that same settle-order read without a filter (value-less, like `--errors`): one call at the end of a step reads the final status of every request that ended since the mark, including ones started earlier; requests still open are not returned. An unsettled request is never returned by a filtered or `--settled` read, so a request that never ends never matches one. `--since` compares the request start (`t`), not when it ended (documented). - **Pending requests end with their target**: a request whose page closes, whose worker stops or that is still open when the source restarts is finalized with `failure: "target closed"` and stops counting in `stats.pending`; a request dropped from the pending limit is finalized with `failure: "abandoned"`. - **Errors are recorded**: the source passes `SessionEvents.reportError` (#109) as its subscription's `onError`. An attach timeout, a failed `Network.enable`, or `Network.enable` params that another subscriber set first are counted in `summary.captureErrors` instead of being dropped. - **`mm cdp` while recording**: the session holds `Network` on every page and the worker from `mm launch` on. `mm cdp Network.enable` (no params) still succeeds and sends nothing (#107). `Network.disable`, or `Network.enable` with other params, is refused with `MM_CDP_BLOCKED`, because it would stop or change what `mm network` records; `--fresh` still works. SKILL.md says this. - Starts with the session. Passive: it never routes, blocks or changes a request, and it stores no bodies. Read-only, browser-only tool. Also adds the zod schema, CLI help, README, and SKILL.md with the per-flow recipe (`mark` → `network`/`logs --cursor`, `startedAt` check, capture gap). Unknown read flags and missing values exit 2; `configure` takes exactly one of `--rpc-errors` / `--no-rpc-errors`. Part of the mm CLI v2 effort: ticket `P2-17` (Phase 2). **Shared #93 helper:** `--url` uses `mock-network`'s `matchesUrlFilter`, so `mm network --url` and `mm mock-network requests --url` match URLs the same way. ## Breaking changes None. ## Consumer impact | Consumer | Change needed | Done on branch | |---|---|---| | Extension `test/e2e/playwright/llm-workflow/` | none | n/a | | Mobile `tests/llm-workflow/` | none (browser only; mobile source after P2-00 S1/S3) | n/a | The Extension release-validation skill (Consensys/skills#122) can take one `mm events mark` at flow start and read `mm network` / `mm logs` at flow end, falling back to its `mock-network` recorder on older `mm`. The reports importer maps `failure` / `text` / `rpcMethods` / `target`. ## Proof Real daemon (`createServer` from the built `dist/`) + built CLI, headless Chromium, read-only, no funds. Rerun after the review fixes on the rebuilt `dist/` of this head (`ce385a3`): **12/12** harness checks pass (the new `17.5` is the `--settled` end-to-end scenario), the redaction grep finds nothing (18 × `[REDACTED]`), and the 22 `mm events|logs|network` reads take a mean of 96 ms wall-clock (max 130 ms, CLI start included). A live late-settle check on the same `dist/`: a 2 s page `fetch` started before a filtered read (read returns 0 records, cursor 3), then the next read with cursor 3 returns it once (`seq` 3, `settledSeq` 4), and the read after that returns nothing. | Check | Result | |---|---| | Worker `fetch` 200 / 404 / aborted and a page `fetch`: status or `failure`, `ms`, `target.kind` | ✅ `sw … 200 123ms`, `sw … 404 0ms`, `sw … net::ERR_ABORTED 60ms`, `page … 200 122ms` | | Single and batch JSON-RPC POST → `rpcMethods` | ✅ `["eth_call"]`, `["eth_chainId","eth_blockNumber"]` | | `--rpc-errors`: `execution reverted` → `rpcError` | ✅ `{"code":-32000,"message":"execution reverted"}`; the batch without errors has none; `rpcErrorsSkipped` 0 | | After `ServiceWorker.stopAllWorkers` (0 worker targets) and a wake | ✅ new worker requests appear, including the worker's start-up `?boot=1` fetch | | Relaunch | ✅ changes `summary.startedAt`; `seq` restarts; an old cursor reads the new session from the start (`gap: true`) | | Grep for the fake Infura key (path) and `apiKey=supersecret` (query) over every CLI output | ✅ not found; 18 × `[REDACTED]` | | `--limit 3` paging | ✅ 2 pages, no duplicates | | `--errors`, `--url` glob, `events clear` keeps `seq`, bad flag | ✅ (bad flag: exit 2) | | `--settled --cursor <mark>`: only settled requests, in `settledSeq` order, with final status; a repeat with the returned cursor returns none | ✅ `17.5`: 6 settled (csv 22,26,27,29,32,33), `settledSeq` 29 is the `execution reverted` request, repeat 0 records, `gap` false | | MetaMask test build 13.56.0 (`dist/chrome`, first screen, no wallet) | ✅ worker `GET https://accounts.api.cx.metamask.io/v2/supportedNetworks 200 60ms`, `chainid.network` 200, refused e2e fixture ports as `net::ERR_CONNECTION_REFUSED`; 90 `chrome-extension://` loads ignored | | Read cost | ✅ 22 `mm events/logs/network` calls: mean 96 ms wall-clock (CLI start included), max 130 ms | | After #107's review round 4 (head `8b78f0e`), MetaMask e2e build: `mm cdp Network.enable` (page, `sw`), then `Network.disable` and `Network.enable` with other params | ✅ `{}`; then `MM_CDP_BLOCKED` (exit 2). `mm network --cursor <mark>` still records a page and a worker fetch afterwards; `captureErrors` 0 | | Filtered read with an open request | ✅ unit: pending → fails → next `--errors` read returns it once; a record that settles after the read (even one older than the cursor) is returned once; `limit: 1` pages late failures; unfiltered reads unchanged. Live: late-settle check above | <details> <summary>Transcript (MV3 test extension)</summary> ``` $ mm events mark → {"cursor":1,"summary":{"startedAt":1795010960760,"seq":1,...}} $ mm navigate chrome-extension://…/trigger.html?tag=A $ mm network --cursor 1 --limit 3 (2 pages) 2 page GET http://127.0.0.1:47123/ok?from=page 200 122ms 5 sw GET http://127.0.0.1:47123/ok?tag=A&apiKey=[REDACTED] 200 123ms 6 sw GET http://127.0.0.1:47123/missing?tag=A 404 0ms 7 sw POST http://127.0.0.1:47123/v3/[REDACTED] 200 41ms rpc=eth_call 8 sw POST http://127.0.0.1:47123/v3/[REDACTED] 200 43ms rpc=eth_chainId,eth_blockNumber 9 sw GET http://127.0.0.1:47123/slow - 60ms net::ERR_ABORTED $ mm network configure --rpc-errors $ mm network --cursor 12 --errors 15 sw GET …/missing?tag=B 404 1ms 16 sw POST …/v3/[REDACTED] 200 43ms rpc=eth_call rpcError=-32000:execution reverted 18 sw GET …/slow - 58ms net::ERR_ABORTED {"seq":16,"t":1795010963306,"target":{"kind":"sw","id":"D5F965B86CF62F7BC00A489B9B488D12","url":"chrome-extension://ocffhifhkanmalpagbcoojhomhpifmpp/bg.js"}, "method":"POST","url":"http://127.0.0.1:47123/v3/[REDACTED]","type":"fetch","rpcMethods":["eth_call"],"status":200,"ms":43, "rpcError":{"code":-32000,"message":"execution reverted"}} ``` Recorded before #107's review round 4. `summary` now also has `captureErrors` (0 in these runs) and, after an error, `lastCaptureError`. </details> <details> <summary>MetaMask test build (first screen, no wallet)</summary> ``` mark 0 (records already in the buffer since launch: {"console":0,"network":0}) network after mark: 5 records {"sw":4,"page":1}; stats {"pending":0,"ignored":90,"rpcErrorsSkipped":0} 1 sw GET http://localhost:12345/state.json - 245ms net::ERR_CONNECTION_REFUSED 2 sw GET https://chainid.network/chains.json 200 140ms 3 sw GET https://chainid.network/chains.json 200 136ms 4 sw GET https://accounts.api.cx.metamask.io/v2/supportedNetworks 200 60ms 6 page GET http://localhost:9999/ - 1ms net::ERR_CONNECTION_REFUSED logs: 5 sw error SocketBackgroundToMocha WebSocket error: Event ``` The e2e build's onboarding screen sends little: wallet traffic (gas, Blockaid, RPC) needs an unlocked wallet, which this proof does not create. </details> <details> <summary>Unit tests</summary> ``` Test Files 74 passed (74) Tests 2715 passed (2715) Type Errors no errors All files | 98.07 | 95.2 | 97.71 | 98.18 | yarn lint: exit 0 yarn build: exit 0 ``` New: `src/events/network-source.test.ts` (join, in-place update, failure, redirect hops (each hop settles), per-target keys, ignored URLs, `postData`/`postDataEntries`, pending cap, `rpcError` on/off (settles after the read, including skipped and failed reads), base64, decoded vs encoded size, size/concurrency/failure skips, `dataReceived`, `targetDetached` finalization, CORS reason, settle on finish/fail/redirect/start), `src/events/event-buffer.test.ts` (settle order, paging by settle position, gap (a dropped unsettled record, `since`), dropped/cleared records never settle, stale cursor, `since` on `t`, one cursor across kinds), `src/events/json-rpc.test.ts` (method cap), `src/tools/network.test.ts` (late settle after a read, older record, `limit: 1` paging, unfiltered reads unchanged, `settled: true` end-to-end), `src/events/network-source.test.ts` (`abandoned`, `target closed` on restart), `CdpManager sendToEventTarget` and `targetId` (timeout, race), `onError` records subscription errors in `captureErrors`, CLI routing and schemas. </details>
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.errorhook never sees them, andmm cdpcould not reach the worker before #90.src/events/console-source.ts): aCdpManager.subscribe(feat: deliver CDP events from pages and the service worker #107) toRuntime.consoleAPICalledandRuntime.exceptionThrownon 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.assertcounts aserror. An uncaught exception iserrorwithuncaught: true.text: the arguments joined on one line, as DevTools does it: object and array arguments render from the CDPpreview({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,sourceTokenand similar are allowlisted; a named property of an array printsname: value; only plain objects, arrays and proxies render as a record, other subtypes keep theirdescriptionsuch asUint8Array(2)orMap(1)). The preview name check is the query-parameter check, socodeis 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 andBearervalues are redacted, and the text is cut at 2000 characters. A secret written in free text (for examplenew Error('decrypt failed for password …')) is not detected; SKILL.md says so.location: 1-basedurl:line:columnof the call or throw.t: the CDP timestamp (epoch ms).target:{ kind: 'page'|'sw', id, url }.erroronly.mm logs configure --levels error,warningwidens it for the session;warnis accepted forwarning.configureaccepts exactly--levels <list>: an extra argument, another flag or a second--levelsis a usage error (exit 2).Runtime.enablereplays 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 }.--grepis a case-sensitive JS regex of at most 256 characters (retried withoutuwhen that does not compile); a value that starts with--must be escaped (--grep '\-\-x'); unknown flags, missing values and a--limitbelow 1 exit 2. The pattern runs in the daemon, so SKILL.md warns against nested quantifiers such as(a+)+.SessionEvents.reportError(feat: add a session event buffer with one cursor and mm events mark #109) as its subscription'sonError. A page or the worker that cannot be attached or enabled within 5 s is counted insummary.captureErrorsinstead of being dropped, so an agent knows that console records of that target can be missing.Part of the mm CLI v2 effort: ticket
P2-16(Phase 2). Next: P2-17mm network.Breaking changes
None.
Consumer impact
test/e2e/playwright/llm-workflow/tests/llm-workflow/The Extension release-validation skill (Consensys/skills#122) can switch from its page hook to
mm logswhen the command is present.Proof
Real daemon + built CLI. MV3 test extension in headless Chromium (page
console.error, uncaught pageTypeError, workerconsole.errorwith an Infura URL,console.warn,console.log).console.error, uncaught page error, with the righttarget.kindconsole.warnnot recorded by defaultconsole.warnrecorded aftermm logs configure --levels error,warningServiceWorker.stopAllWorkers(0 worker targets) and a wake, new worker errors appear--limit 1paging (3 pages, no duplicates)probe/(headless-Chromium capture + formatter output); a second probe checks preview redaction and subtype descriptionsprobe-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 outputmm logs configurewith an extra argument or a second--levelsevents clearkeepsseq(11 → 11)startedAtapiKeyvalue in any outputTranscript
Recorded before #107's review round 4.
summarynow also hascaptureErrors(0 in these runs) and, after an error,lastCaptureError.Unit tests
New:
src/events/console-source.test.ts(level mapping, argument formatting, truncation, redaction, location, uncaught, replay filter, level config,onErrorrecords a subscription error incaptureErrors),src/tools/logs.test.ts(cursor/since/limit/grep, invalid grep, configure), CLI routing and schemas.