Repository navigation
feat: add a session event buffer with one cursor and mm events mark - #109
Conversation
5c2279c to
72c8e8b
Compare
72c8e8b to
54fe280
Compare
54fe280 to
65ef5ed
Compare
65ef5ed to
00ddbcc
Compare
Adds one buffer per browser session for console and network records (filled by mm logs and mm network sources in follow-ups). Records share one monotonic seq, so a single 'mm events mark' bookmarks both kinds. Reads are paged with cursor/since/limit and report hasMore, gap (records after the cursor were dropped) and a summary whose startedAt changes on relaunch. Adds URL/text redaction helpers applied before a record enters the buffer. The buffer starts with the session at launch; 'mm events' is browser only and read-only.
00ddbcc to
d75e3ac
Compare
…rget-events' into cryptotavares/mmcli-p2-15-events # Conflicts: # CHANGELOG.md
seaona
left a comment
There was a problem hiding this comment.
Looks good! Just some minor request, that could be supported later
| mm cdp <method> [params-json] [--timeout <ms>] [--target page|sw|hermes|android-webview] [--fresh] [--url-filter <substr>] [--metro-port <p>] [--app-id <id>] | ||
| mm hermes-targets [--all] [--metro-port <p>] [--app-id <id>] (mobile only) | ||
|
|
||
| Session events (browser only; recorded from launch on, not during it): |
There was a problem hiding this comment.
This limitation is something that we may want to support (can be added later), because extension start-up is typically a point were errors happen: background initialisation failures and the worker's first console errors.
There was a problem hiding this comment.
Yes agree. But that is just because currently we are not supporting onboarding yet. But once we do, we need to enable it for onboarding as well
…rget-events' into cryptotavares/mmcli-p2-15-events
…mmary Review of #107, carried to #109: - ensureStarted waits at most 5 s (SESSION_EVENTS_START_WAIT_MS) for a start in progress. A start held by a target that does not answer no longer makes every later mm events/logs/network call hang on the stored promise. - SessionEvents.reportError records an event source error: it counts it in the buffer summary (captureErrors, lastCaptureError, redacted and cut at 300 characters) and writes it to the debug log. A source that fails to start is recorded the same way.
|
Buffer logic looks right to me (cursor/gap, per-kind drop, stale cursor,
|
pnarayanaswamy
left a comment
There was a problem hiding this comment.
Re-review on 94291ed: no new commits since my last pass. Buffer logic looks right; comments inline.
| } | ||
| const name = decodeQueryName(pair.slice(0, separator)); | ||
| const value = decodeQueryName(pair.slice(separator + 1)); | ||
| return isSensitiveQueryParam(name) || JWT_PATTERN.test(value) |
There was a problem hiding this comment.
The description says "a JWT or bare key used as a value is redacted even under a harmless name", but with a = only JWT_PATTERN is checked on the value. These come back unchanged:
https://x.io/?data=0123456789abcdef0123456789abcdefhttps://x.io/#state=AbCdEfGhIjKlMnOpQrStUvWxYzAbCdEf
Either || isSecretUrlSegment(value) here, or adjust the description.
There was a problem hiding this comment.
Fixed in 9a87408. The value check is now isSecretUrlSegment(value) || isOpaquePathKey(value): data=0123456789abcdef0123456789abcdef is caught by isSecretUrlSegment, and #state=AbCdEfGhIjKlMnOpQrStUvWxYzAbCdEf has no digit, so it needs isOpaquePathKey. Both URLs are test cases, and the doc comment now says a key-like value is redacted even under a harmless name.
| * @param segment - A path segment or host label. | ||
| * @returns True if the segment must be redacted. | ||
| */ | ||
| export function isSecretUrlSegment(segment: string): boolean { |
There was a problem hiding this comment.
Over-redaction: a base58 address or 64-hex hash as a path segment without a tx/address word before it is treated as a key, e.g. https://block.io/1BoatSLRHtKNngkdXEeobR76b53LETtpyT → [REDACTED]. Minor, but loses signal for explorer-style URLs.
There was a problem hiding this comment.
Not changed: this is the safe side of the segment rule, and it is documented in the PR body (base58/64-hex IDs are kept only after account(s)/address(es)/tx/transaction(s)). Tightening it would let an explorer-style URL keep a value that is an API key elsewhere.
| import { debugWarn, extractErrorMessage } from '../utils'; | ||
|
|
||
| /** How long a launch waits for the session event sources to attach. */ | ||
| const SESSION_EVENTS_START_WAIT_MS = 5_000; |
There was a problem hiding this comment.
Duplicate of SESSION_EVENTS_START_WAIT_MS exported from session-events.ts. Importing it avoids the two drifting.
There was a problem hiding this comment.
Fixed in 9a87408. The duplicate constant is removed; launch now calls ensureStarted() directly, so there is no wait constant in launch.ts to drift from session-events.ts.
| ).ensureStarted(); | ||
| // Do not hold the launch on a slow attach: the sources keep starting. | ||
| let timer: ReturnType<typeof setTimeout> | undefined; | ||
| await Promise.race([ |
There was a problem hiding this comment.
ensureStarted() already races the same 5 s bound internally, so this outer race can't fire first. Calling ensureStarted() directly inside the try/catch would be enough.
There was a problem hiding this comment.
Fixed in 9a87408. The outer timer is removed and startSessionEvents just awaits ensureStarted() in the existing try/catch. The fake-timer test that relied on the outer race is replaced by a test that a rejecting start does not fail the launch.
| } | ||
|
|
||
| const events = getSessionEvents(context.sessionManager.getContext()); | ||
| await events.ensureStarted(); |
There was a problem hiding this comment.
Nit: clear doesn't need running sources, but still waits on ensureStarted() (up to 5 s if a target hangs). Could skip it for action === 'clear'.
There was a problem hiding this comment.
Not changed: clear is used at the start of a flow, where starting the sources is wanted, and the wait is bounded at 5 s. Skipping it would make the following logs/network call pay the start instead.
- Redact a key-like query or fragment value even under a harmless name (isSecretUrlSegment/isOpaquePathKey), not only a JWT. - Remove the duplicate SESSION_EVENTS_START_WAIT_MS and the outer race in launch: ensureStarted already bounds the wait at 5 s and never rejects.
|
Thanks Priya — fix commit 9a87408 has both items, plus the two |
| return isSensitiveQueryParam(name) || | ||
| isSecretUrlSegment(value) || | ||
| isOpaquePathKey(value) |
There was a problem hiding this comment.
Thanks for the fix — the two URLs from my earlier comment are redacted now. One regression from it though: isOpaquePathKey has no digit requirement, so any base58 value of 28+ chars is now redacted regardless of the parameter name. Comparing redactUrl on 94291ed vs 9a87408:
| Value | Before | Now |
|---|---|---|
bridge quote srcTokenAddress=So11111111111111111111111111111111111111112 (wSOL) |
kept | [REDACTED] |
destWalletAddress=7EcDhSYGxXyscszYEp35KHN8vvw3svAuLKTzXwCFLtV (Solana wallet) |
kept | [REDACTED] |
hash=5VERv8NMvzbJ…SZkQUW (Solana tx signature) |
kept | [REDACTED] |
address=0x… / txHash=0x… (EVM) |
kept | kept |
That drops the token and wallet values mm network needs for Solana bridge/swap release validation. My original suggestion caused this, sorry.
Suggestion: skip the value check when the parameter name marks an identifier (address, account, wallet, token, hash, tx, signature, mint, also as a suffix like destWalletAddress / srcTokenAddress), the same idea as IDENTIFIER_PATH_WORDS for paths, and add a Solana-address test that stays unredacted. Base64 cursors like next=aGVsbG8… getting redacted is a harmless side effect.
## 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>
#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>
… 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 #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) andmm 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.
src/events/event-buffer.ts), with one monotonicseqshared by all record kinds (starts at 1 per session). Two kinds, each with its own capacity and drop count:console(1000) andnetwork(2000). A full kind drops its oldest record.read({ kind, cursor?, since?, limit, filter? })→{ records, cursor, hasMore, gap, summary }, oldest first. The returnedcursorcontinues the read with no duplicates or holes.gap: truewhen a record after the cursor (or at/aftersince) was dropped. Acursorabove the newestseq(from an earlier session) is stale: the read starts from the oldest record and reportsgap: true, so a client that compares cursors notices. With bothcursorandsince,gapis approximate (a record dropped after the cursor but beforesinceis not distinguished).limitis clamped to at least 1. A record updated in place later (a network request that finishes) keeps itsseq, 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.captureErrorscounts 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).lastCaptureErroris the newest one, redacted and cut at 300 characters. An agent sees incomplete capture on every read, withoutDEBUG.mm events mark→{ cursor, summary }.mm events clear [--kind console|network]empties the buffer without resettingseq(old cursors stay valid). Unknown arguments (mark --kind x,clear extra, a missing--kindvalue) are usage errors (exit 2).src/events/redact.ts, from feat: add mm network-log, a passive request and console log with service-worker traffic #106'sredactUrl): credentials (user:pass@→[REDACTED]@); host labels and path segments of 24+ letters/digits (32-hex Infura keys); sensitive query and fragment values (feat: record request bodies in mock-network #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);^authdoes not matchauthor/authors/authorityand^sigonly matchessig/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 afterv1–v4(≥ 28 chars) is treated as an API key, so a digitless Alchemy key is caught.0xaddresses, 64-hex/base58 IDs afteraccount(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. Ascheme://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…) andBearervalues (the value needs 8+ token characters, so prose such asthe bearer of good newsstays).passwd,pwd,pass,bearer,seed,pkandmnemonic…names are redacted;publicKey,pubKey,sortKey,cacheKey,primaryKeyandsourceToken…nativeTokenare 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).launchstarts the session's event sources on browser sessions and never fails the launch. The firstevents/logs/networkcall starts them again if the CDP manager was replaced.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.reportErrorrecords a source error: it counts it insummary.captureErrors, setslastCaptureErrorand writes it to the debug log. It never throws. feat: add mm logs for console errors from pages and the service worker #110 and feat: add mm network, a passive request log for pages and the service worker #111 pass it as their subscription'sonError.eventsis a read-only, browser-only tool (zod schema, registry, CLI help, README, SKILL.md). Mobile returnsMM_TOOL_NOT_SUPPORTED_ON_PLATFORM.Part of the mm CLI v2 effort: ticket
P2-15(Phase 2). Next: P2-16mm logs(stacked on this PR), P2-17mm network.Shared #93 helper:
redact.tsusesmock-network'sisSensitiveBodyField(now exported) andREDACTED_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
test/e2e/playwright/llm-workflow/tests/llm-workflow/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).
gap: truesincepaging withlimit:hasMore, no duplicates or holes; an in-place update is not returned againstartedAtchanges on a new session;clearkeepsseqstartedAt 1795010983961 → 1795010991417acrosscleanup+launch)apiKey=, credentials (HTTP and non-HTTP schemes), fragment pairs, JWT path and JWT/Bearerin text, suffix/prefix names, digitless key, UUID only as the sole path segment,0xaddress / 64-hex / base58 kept, URL inside text kept when clean and byte-identicalcursor > seq) reads from the oldest record and reportsgap: truemm events clear --kind)MM_INVALID_INPUT, exit 2ensureStarted()settles after 5 s and does not start the sources againsummary; a source that fails to start is recordedcaptureErrors: 0on the MetaMask e2e build with the top of the stack (below)Transcript
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:Unit tests