From 3cb4e4ba74b5988a44189ba25a36b14b721895f2 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 3 Dec 2026 13:32:40 +0000 Subject: [PATCH 1/8] feat: mm logs on mobile (Hermes console errors and uncaught exceptions) --- README.md | 8 +- SKILL.md | 29 +- src/cli/mm.ts | 7 +- src/events/console-source.test.ts | 5 +- src/events/console-source.ts | 90 ++- src/events/hermes-console-source.test.ts | 714 ++++++++++++++++++ src/events/hermes-console-source.ts | 466 ++++++++++++ src/events/network-source.test.ts | 3 +- src/events/read-options.ts | 13 +- src/events/session-events.test.ts | 173 ++++- src/events/session-events.ts | 168 +++-- .../mobile-platform-driver.hermes.test.ts | 49 ++ src/platform/mobile-platform-driver.ts | 45 +- src/platform/types.ts | 14 + src/tools/events.ts | 4 +- src/tools/launch.test.ts | 42 +- src/tools/launch.ts | 25 +- src/tools/logs.test.ts | 56 ++ src/tools/logs.ts | 8 +- src/tools/platform-gating.test.ts | 15 +- src/tools/registry.test.ts | 4 +- src/tools/registry.ts | 2 - src/tools/types/events.ts | 13 +- 23 files changed, 1774 insertions(+), 179 deletions(-) create mode 100644 src/events/hermes-console-source.test.ts create mode 100644 src/events/hermes-console-source.ts diff --git a/README.md b/README.md index ceacfc69..10178d3e 100644 --- a/README.md +++ b/README.md @@ -440,8 +440,8 @@ The daemon routes `POST /tool/:name` requests through the registry, applies Zod | `run_steps` | Executes a batch of tool invocations sequentially. Supports `stopOnError` to halt on first failure, a top-level `observe` level for the single observation collected after the batch (default `diff`; without one, the last executed step's `observe` is used), and `batchTimeoutMs` (1 000–30 000 ms) to set an overall deadline (checked between steps; remaining steps are skipped, partial results are returned). The daemon queue and the CLI wait for the deadline plus the slowest step's own timeout, so a step in progress is never cut off by `MM_QUEUE_TIMEOUT`; without `batchTimeoutMs` the call keeps the daemon queue default (30 s, or 180 s when the host sets it). Accepts tool aliases like `navigate_home` / `navigate-home`. Returns per-step results with timing. | | **Advanced** | | | `mock_network` | Adds, clears, lists, and inspects targeted Playwright network mocks on the active browser context. Unmatched same-origin requests are continued unchanged. A rule with `record` and no `response` records the real request and forwards it unchanged. Rules can opt in to record request bodies and headers (redacted). | -| `events` | Bookmarks or clears the session event buffer that `mm logs` and `mm network` read: `mark` returns the current cursor (one cursor for both) and `summary.startedAt`; `clear` empties it without resetting the cursor. The buffer starts with a browser session and keeps the newest 1000 console and 2000 network records. Browser only. | -| `logs` | Read-only. Console errors and uncaught exceptions of every page and the Extension service worker, from the session event buffer: `{ records, cursor, hasMore, gap, summary }`, oldest first, with `cursor`/`since`/`limit`/`grep`. Records `error` only by default; `configure` widens the levels for the session (`warn` is accepted as `warning`). Object and array arguments are rendered from their CDP preview (a sensitive property name prints `[REDACTED]`), and a leading format string fills its `%s`/`%d`/`%o` specifiers. URLs in the text and the values of sensitive object fields (`privateKey`, `mnemonic`, `password`, …) are redacted; plain string contents are not scanned (JWTs and `Bearer` tokens excepted). Text is cut at 2000 characters. Browser only. | +| `events` | Bookmarks or clears the session event buffer that `mm logs` and `mm network` read: `mark` returns the current cursor (one cursor for both) and `summary.startedAt`; `clear` empties it without resetting the cursor. The buffer starts with the session and keeps the newest 1000 console and 2000 network records. | +| `logs` | Read-only. Console errors and uncaught exceptions of every page and the Extension service worker, or of the app's Hermes runtime on mobile (`target.kind: "hermes"`; uncaught errors come from an observe-only wrapper of the `ErrorUtils` global handler, marked `uncaught` and `fatal` for the red box, and it is installed again after a JS reload; native crashes are not captured), from the session event buffer: `{ records, cursor, hasMore, gap, summary }`, oldest first, with `cursor`/`since`/`limit`/`grep`. Records `error` only by default; `configure` widens the levels for the session (`warn` is accepted as `warning`). Object and array arguments are rendered from their CDP preview (a sensitive property name prints `[REDACTED]`), and a leading format string fills its `%s`/`%d`/`%o` specifiers. URLs in the text and the values of sensitive object fields (`privateKey`, `mnemonic`, `password`, …) are redacted; plain string contents are not scanned (JWTs and `Bearer` tokens excepted). Text is cut at 2000 characters. | | `network` | Read-only, passive. HTTP(S) requests of every page and the Extension service worker, from the session event buffer: one record per request with method, redacted URL, type, status, duration (`ms`), `failure`, JSON-RPC `rpcMethods` and, after `configure` with `rpcErrors`, the JSON-RPC `rpcError`. Filters: `cursor`, `since`, `limit`, `url` (glob or text), `errors`, `settled`; a filtered or `settled` read returns settled requests only, ordered by `settledSeq`. Never routes or changes a request; no bodies are stored. Browser only. | | `cdp` | Sends a raw Chrome DevTools Protocol command, dispatched through the active platform driver. **Browser:** targets the active page (`target: "page"`, default) or the Extension service worker (`target: "sw"`) on a persistent CDP session shared across calls, so enabled domains and listeners survive; `fresh: true` uses a one-shot session. Full Runtime/DOM/Network/Page surface; destructive methods (`Browser.close`, `Target.closeTarget`, etc.) are blocked. **Mobile (iOS/Android):** targets the app's React Native Hermes JS runtime via Metro's inspector proxy (delegates to `@metamask/device-mcp`, needs a DEBUG build with Metro running); only the JS-engine subset exists (`Runtime`, `Debugger`, `Log`, `HeapProfiler` — no DOM/Page/Network) and `Runtime.terminateExecution` / `Inspector.detached` are blocked. Optional `metroPort` / `appId` are mobile-only (ignored on browser). Categorized as `cdp`: no observation is collected and refs are not refreshed, so run `describe_screen` after a call that changes state. See [Browser vs Mobile CDP](#browser-vs-mobile-hermes-cdp). | | **Hermes (mobile only)** | | @@ -695,9 +695,9 @@ mm describe-screen | `mm mock-network clear` | Clears route mocks and recorded requests. | | `mm mock-network list` | Lists active route mocks. | | `mm mock-network requests [--limit ] [--url ] [--bodies]` | Shows recorded matched and missed requests, with URLs redacted like `mm network`. `--url` keeps only matching URLs. `--bodies` adds the recorded (redacted) request bodies and headers. | -| `mm events mark` | Returns the current cursor of the session event buffer and `summary.startedAt`. Take it at the start of a flow and pass it to `mm logs` / `mm network` at the end. Browser only. | +| `mm events mark` | Returns the current cursor of the session event buffer and `summary.startedAt`. Take it at the start of a flow and pass it to `mm logs` / `mm network` at the end. | | `mm events clear [--kind console\|network]` | Empties the session event buffer (one kind or all). The cursor keeps counting, so older cursors stay valid. | -| `mm logs [--cursor \| --since ] [--limit ] [--grep ]` | Console errors and uncaught exceptions of every page and the Extension service worker since the cursor. Read again with the returned `cursor` while `hasMore`; `gap: true` also means the cursor is from an earlier session (the read restarts from the oldest record). `--grep` is a case-sensitive JavaScript regex of at most 256 characters; the pattern runs in the daemon, so avoid nested quantifiers such as `(a+)+`; a value that starts with `--` must be escaped (`--grep '\-\-x'`). Browser only. | +| `mm logs [--cursor \| --since ] [--limit ] [--grep ]` | Console errors and uncaught exceptions of every page and the Extension service worker (mobile: of the app's Hermes runtime) since the cursor. Read again with the returned `cursor` while `hasMore`; `gap: true` also means the cursor is from an earlier session (the read restarts from the oldest record). `--grep` is a case-sensitive JavaScript regex of at most 256 characters; the pattern runs in the daemon, so avoid nested quantifiers such as `(a+)+`; a value that starts with `--` must be escaped (`--grep '\-\-x'`). | | `mm logs configure --levels ` | Changes the recorded console levels for the session (default `error`; `warn` is accepted as `warning`). Only `--levels ` is accepted; any other flag or a second `--levels` is a usage error. | | `mm network [--cursor \| --since ] [--limit ] [--url ] [--errors] [--settled]` | HTTP(S) requests of every page and the Extension service worker since the cursor: status, `ms`, `failure`, `rpcMethods`. `--errors` keeps status >= 400, failures and `rpcError`. An unfiltered read returns every record in start order, pending requests included. A filtered read (`--url`, `--errors`) returns only settled requests, in `settledSeq` order, so a request that becomes a match when it ends is returned once by the next read, even when it started before the cursor; `--settled` does the same without a filter, for the end of a step. `--since` compares the request start (`t`). A request whose page or worker goes away is finalized with `failure: "target closed"`; one dropped from the pending limit as `"abandoned"`. Requests during `mm launch` are not recorded. Browser only. | | `mm network configure --rpc-errors \| --no-rpc-errors` | Reads JSON-RPC response bodies (up to 64 KiB decoded, 8 at a time) and records their `error` as `rpcError`. Off by default. | diff --git a/SKILL.md b/SKILL.md index 206a93f7..2e872f9c 100644 --- a/SKILL.md +++ b/SKILL.md @@ -773,9 +773,9 @@ mm hermes-targets mm hermes-targets --all ``` -### Session events (browser only) +### Session events -From `mm launch` on, the daemon records events from every page, the Extension's background service worker, the MV3 offscreen document and its snaps iframes into one buffer per session. `mm logs` and `mm network` read it. All kinds share one cursor (`seq`), so one `mark` covers both. Traffic during `mm launch` itself (for example self-onboarding) is not recorded. Mobile sessions return `MM_TOOL_NOT_SUPPORTED_ON_PLATFORM`. +From `mm launch` on, the daemon records events from every page, the Extension's background service worker, the MV3 offscreen document and its snaps iframes into one buffer per session. `mm logs` and `mm network` read it. All kinds share one cursor (`seq`), so one `mark` covers both. Traffic during `mm launch` itself (for example self-onboarding) is not recorded. On mobile, `mm events` and `mm logs` read the console of the app's Hermes runtime (see [`mm logs` on mobile](#mm-logs-on-mobile)); `mm network` returns `MM_TOOL_NOT_SUPPORTED_ON_PLATFORM`. #### `mm events mark` @@ -785,7 +785,7 @@ Returns `{ cursor, summary }`. Take it at the start of a flow. Empties the buffer (one kind or all). The cursor keeps counting, so older cursors stay valid. -`summary` is `{ startedAt, seq, counts: { console, network }, dropped: { console, network }, captureErrors, lastCaptureError? }`. `startedAt` (epoch ms) changes when the session is relaunched; `seq` then starts at 1 again. Every appended record and every settled network request (a request that ended) takes the next `seq`, so `seq` can skip values. The buffer keeps the newest 1000 console and 2000 network records; older ones are dropped and counted. `captureErrors` counts the times the session could not listen to a page or the service worker (for example a target that did not answer within 5 s, or a domain that could not be enabled); `lastCaptureError` is the newest one, redacted. When it grows during a flow, events of that target can be missing. A call that starts the recording waits at most 5 s for a target that does not answer. +`summary` is `{ startedAt, seq, counts: { console, network }, dropped: { console, network }, captureErrors, lastCaptureError? }`. `startedAt` (epoch ms) changes when the session is relaunched; `seq` then starts at 1 again. Every appended record and every settled network request (a request that ended) takes the next `seq`, so `seq` can skip values. The buffer keeps the newest 1000 console and 2000 network records; older ones are dropped and counted. `captureErrors` counts the times the session could not listen to a page or the service worker (for example a target that did not answer within 5 s, or a domain that could not be enabled); `lastCaptureError` is the newest one, redacted. On mobile it also counts a lost Hermes connection and an uncaught-error wrapper that could not be installed within 60 s of a reload. When it grows during a flow, events of that target can be missing. A call that starts the recording waits at most 5 s for a target that does not answer. #### `mm logs [--cursor | --since ] [--limit ] [--grep ]` @@ -806,10 +806,31 @@ Console errors and uncaught exceptions of every page, the Extension service work } ``` -`target.kind` is `page`, `sw`, `offscreen` (the MV3 offscreen document) or `iframe` (a snaps iframe of the offscreen document; its `url` is empty until the iframe loads). Uncaught exceptions have `"uncaught": true`. `text` (console arguments, error messages and stacks, uncaught exceptions) is cut at 2000 characters and redacted only for URLs, JWTs, `Bearer` values and sensitive property names in object previews (`privateKey`, `mnemonic`, `password`, …); a secret in free text, such as `new Error('… password hunter2')`, is not detected. `t` is the CDP time of the message (epoch ms). +`target.kind` is `page`, `sw`, `offscreen` (the MV3 offscreen document), `iframe` (a snaps iframe of the offscreen document; its `url` is empty until the iframe loads) or `hermes` (mobile). Uncaught exceptions have `"uncaught": true`. `text` (console arguments, error messages and stacks, uncaught exceptions) is cut at 2000 characters and redacted only for URLs, JWTs, `Bearer` values and sensitive property names in object previews (`privateKey`, `mnemonic`, `password`, …); a secret in free text, such as `new Error('… password hunter2')`, is not detected. `t` is the CDP time of the message (epoch ms). Only `error` (including `console.assert` and uncaught exceptions) is recorded by default. `mm logs configure --levels error,warning` records more levels from then on, for this session (`warn` is accepted as `warning`). Non-error objects and arrays are rendered from their CDP preview (`{message: 'User rejected', chainId: 1}`, `[1, 2]`); a named property of an array prints as `name: value`, and a sensitive property name prints `[REDACTED]`. A leading format string fills `%s`, `%d`, `%i`, `%f`, `%o`, `%O`, `%c` from its arguments. `mm logs configure` accepts only `--levels `: any other flag or a second `--levels` is a usage error. +#### `mm logs` on mobile + +On iOS and Android, `mm logs` records the `console.*` calls of the app's Hermes JS runtime (dev builds with Metro), through the session's Hermes connection, from `mm launch` on. The output shape, levels, limits, `--grep` and redaction are the same as on the browser. Records have `target: { kind: "hermes", id: , url: "" }`. + +```json +{ + "seq": 45, + "t": 1796304265075, + "target": { "kind": "hermes", "id": "9d2d6b8a…-1", "url": "" }, + "level": "error", + "text": "Error: mm-p2-29 uncaught\n at anonymous (:1:178)", + "uncaught": true, + "fatal": true +} +``` + +- **Uncaught errors:** the daemon wraps the app's `ErrorUtils` global handler. The wrapper only reports the error to the daemon and then calls the app's handler unchanged, so the red box / LogBox and the app's error handling still happen. The record of an uncaught error has `"uncaught": true`, and `"fatal": true` when React Native reported it as fatal (the full-screen "Uncaught Error" LogBox in dev). An uncaught error is one record, not two (React Native also logs it with `console.error`). A dev LogBox can be closed with its **Dismiss** button; `mm logs` does not close it. +- **Reloads:** a JS reload (Metro reload, `DevSettings.reload()`) keeps recording. The daemon installs the wrapper again when the new bundle has run (about 4 s after the reload on Android, about 14 s on iOS dev builds). Until then, an uncaught error is still recorded from its `console.error`, without `uncaught`. A reload adds no record and no field. When Metro drops the connection, the daemon reconnects and counts it in `summary.captureErrors`; messages sent while it was down are missing. +- **Not captured:** native crashes and native logs (use `mm device-logs`); console messages from before the session connected (Hermes sends them again on connect, and they are dropped); messages sent while the connection was down; release builds (no Metro, no Hermes inspector). Levels other than `error` are recorded only after `mm logs configure --levels`, as on the browser. +- The session keeps `Runtime` enabled on its Hermes connection: `mm cdp Runtime.enable` succeeds without sending anything, and `mm cdp Runtime.disable` is refused with `MM_CDP_BLOCKED`. `t` is the app's console time (epoch ms), or the daemon time for an uncaught error the console did not log. + #### `mm network [--cursor | --since ] [--limit ] [--url ] [--errors] [--settled]` HTTP(S) requests of every page, the Extension service worker (gas, security alerts, bridge, RPC: most Extension traffic comes from the worker), the offscreen document and its snaps iframes (`target.kind` as in `mm logs`). It only listens: it never mocks, blocks or changes a request, and it stores no bodies (use `mm mock-network` for that). One record per request, created when it starts and updated in place when it ends; it keeps its first `seq` and gets a `settledSeq` when it ends. Same paging as `mm logs`, plus `stats: { pending, ignored, rpcErrorsSkipped }`. A request whose page, worker, offscreen document or iframe goes away before it ends (the offscreen document goes away when it is recreated) is finalized with `failure: "target closed"`; one dropped from the pending limit is finalized with `failure: "abandoned"`. diff --git a/src/cli/mm.ts b/src/cli/mm.ts index e755f6d8..4247bee7 100644 --- a/src/cli/mm.ts +++ b/src/cli/mm.ts @@ -2574,15 +2574,16 @@ Advanced: mm cdp [params-json] [--timeout ] [--target page|sw|hermes|android-webview] [--fresh] [--url-filter ] [--metro-port

] [--app-id ] mm hermes-targets [--all] [--metro-port

] [--app-id ] (mobile only) -Session events (browser only; recorded from launch on, not during it): +Session events (recorded from launch on, not during it; network: browser only): mm events mark Current cursor and summary.startedAt. Take one at the start of a flow; pass the cursor to logs/network. mm events clear [--kind console|network] Empty the buffer; the cursor keeps counting. mm logs [--cursor | --since ] [--limit ] [--grep ] Console errors and uncaught exceptions of every page - and the Extension service worker. Oldest first; read - again with the returned cursor while hasMore. + and the Extension service worker (mobile: the app's + Hermes runtime). Oldest first; read again with the + returned cursor while hasMore. mm logs configure --levels Levels to record from now on (default: error). mm network [--cursor | --since ] [--limit ] [--url ] [--errors] [--settled] diff --git a/src/events/console-source.test.ts b/src/events/console-source.test.ts index 13a0fff6..2360862b 100644 --- a/src/events/console-source.test.ts +++ b/src/events/console-source.test.ts @@ -1,4 +1,3 @@ -import type { BrowserContext } from '@playwright/test'; import { describe, expect, it, vi } from 'vitest'; import { @@ -78,7 +77,7 @@ async function startSource(): Promise<{ return { unsubscribe: vi.fn() }; }), } as unknown as CdpManager; - const events = new SessionEvents({} as BrowserContext, []); + const events = new SessionEvents(() => manager, []); await new ConsoleSource().start(manager, events); const subscribed = options as CdpSubscribeOptions; return { @@ -649,7 +648,7 @@ describe('ConsoleSource', () => { }); // Filtered out, but its replay key is remembered. emit(warning); - events.config = { consoleLevels: ['error', 'warning'] }; + events.config = { consoleLevels: ['error', 'warning'], rpcErrors: false }; // The same message again is a replay: not recorded. emit(warning); emit( diff --git a/src/events/console-source.ts b/src/events/console-source.ts index 23fec1f5..d8875d6b 100644 --- a/src/events/console-source.ts +++ b/src/events/console-source.ts @@ -1,3 +1,4 @@ +import type { RecordSourceTarget } from './read-options.js'; import { toRecordTarget } from './read-options.js'; import { isSensitiveQueryParam, @@ -351,7 +352,7 @@ function formatLocation(frame: CallFrame | undefined): string | undefined { * @returns The record without its `seq`, and the CDP timestamp (epoch ms). */ export function toConsoleRecord( - event: CdpEvent, + event: ConsoleEvent, ): { record: Omit; timestamp?: number } | undefined { const target = toRecordTarget(event.target); if (event.method === 'Runtime.consoleAPICalled') { @@ -402,56 +403,46 @@ export function toConsoleRecord( return undefined; } +/** A console event and the target it came from. */ +export type ConsoleEvent = Omit & { + target: RecordSourceTarget; +}; + /** - * Records console messages and uncaught exceptions of every page and the - * Extension service worker, at the levels in the session config. - * - * `Runtime.enable` replays the messages Chrome kept for a target. Replays - * are dropped: messages from before the source started, and messages seen - * already (same target, time, level and text). + * Appends console records to the session buffer, at the levels in the + * session config, and drops replays: messages from before the source + * started, and messages seen already (same target, time, level and text). */ -export class ConsoleSource implements SessionEventSource { +export class ConsoleRecorder { readonly #remembered = new Set(); /** - * @param manager - The session's CDP manager. - * @param events - The session's events. - * @returns The subscription. - */ - async start( - manager: CdpManager, - events: SessionEvents, - ): Promise { - const startedAt = Date.now(); - return manager.subscribe({ - events: CONSOLE_EVENTS, - onEvent: (event) => this.#onEvent(event, events, startedAt), - onError: events.reportError, - }); - } - - /** - * Records one event when it is not a replay and its level is recorded. + * Records one message when it is not a replay and its level is recorded. * The replay key is remembered before the level filter, so widening the * levels later does not record the replayed messages again. * - * @param event - The CDP event. + * @param built - The record and its CDP timestamp, from + * {@link toConsoleRecord}. * @param events - The session's events. - * @param startedAt - When this source started, epoch ms. + * @param startedAt - When the source started, epoch ms. + * @returns The stored record, or undefined when it was not recorded. */ - #onEvent(event: CdpEvent, events: SessionEvents, startedAt: number): void { - const built = toConsoleRecord(event); + add( + built: ReturnType, + events: Pick, + startedAt: number, + ): ConsoleRecord | undefined { if (built === undefined) { - return; + return undefined; } const { record, timestamp } = built; if (timestamp !== undefined) { if (timestamp < startedAt) { - return; + return undefined; } const key = `${record.target.id}\u0000${timestamp}\u0000${record.level}\u0000${record.text}`; if (this.#remembered.has(key)) { - return; + return undefined; } this.#remembered.add(key); if (this.#remembered.size > MAX_REMEMBERED_MESSAGES) { @@ -460,8 +451,37 @@ export class ConsoleSource implements SessionEventSource { } } if (!events.config.consoleLevels.includes(record.level)) { - return; + return undefined; } - events.buffer.append('console', record); + return events.buffer.append('console', record); + } +} + +/** + * Records console messages and uncaught exceptions of every page and the + * Extension service worker, at the levels in the session config. + * + * `Runtime.enable` replays the messages Chrome kept for a target. Replays + * are dropped (see {@link ConsoleRecorder}). + */ +export class ConsoleSource implements SessionEventSource { + readonly #recorder = new ConsoleRecorder(); + + /** + * @param manager - The session's CDP manager. + * @param events - The session's events. + * @returns The subscription. + */ + async start( + manager: CdpManager, + events: SessionEvents, + ): Promise { + const startedAt = Date.now(); + return manager.subscribe({ + events: CONSOLE_EVENTS, + onEvent: (event) => + this.#recorder.add(toConsoleRecord(event), events, startedAt), + onError: events.reportError, + }); } } diff --git a/src/events/hermes-console-source.test.ts b/src/events/hermes-console-source.test.ts new file mode 100644 index 00000000..128264fe --- /dev/null +++ b/src/events/hermes-console-source.test.ts @@ -0,0 +1,714 @@ +import { runInNewContext } from 'node:vm'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { hookScript, HermesConsoleSource } from './hermes-console-source.js'; +import { SessionEvents } from './session-events.js'; +import type { HermesEventClient } from '../platform/types.js'; +import type { ConsoleRecord } from '../tools/types/events.js'; + +const INFURA_KEY = '0123456789abcdef0123456789abcdef'; + +type SendResult = + | { ok: true; result: unknown } + | { + ok: false; + code: string; + message: string; + }; + +type FakeClient = HermesEventClient & { + emit: (name: string, payload: unknown) => void; + listenerCount: () => number; + send: ReturnType; + connect: ReturnType; + /** Answers of `Runtime.evaluate`, in order; the last one repeats. */ + evaluations: SendResult[]; + /** Called while `Runtime.enable` waits for its response. */ + onEnable?: () => void; +}; + +/** + * Creates a fake persistent Hermes client. + * + * @returns The client. + */ +function createClient(): FakeClient { + const listeners = new Map void>>(); + const client = { + evaluations: [ + { ok: true, result: { result: { value: 'installed' } } }, + ] as SendResult[], + connect: vi.fn().mockResolvedValue({ + ok: true, + target: { id: 'T1', logicalDeviceId: 'D1', title: 'MetaMask' }, + }), + send: vi.fn(async (method: string): Promise => { + if (method === 'Runtime.enable') { + client.onEnable?.(); + } + if (method === 'Runtime.evaluate') { + return client.evaluations.length > 1 + ? (client.evaluations.shift() as SendResult) + : client.evaluations[0]; + } + return { ok: true, result: {} }; + }), + on: vi.fn((name: string, listener: (payload: unknown) => void) => { + let set = listeners.get(name); + if (!set) { + set = new Set(); + listeners.set(name, set); + } + set.add(listener); + }), + off: vi.fn((name: string, listener: (payload: unknown) => void) => { + listeners.get(name)?.delete(listener); + }), + emit: (name: string, payload: unknown): void => { + for (const listener of listeners.get(name) ?? []) { + listener(payload); + } + }, + listenerCount: (): number => + [...listeners.values()].reduce((sum, set) => sum + set.size, 0), + }; + return client as unknown as FakeClient; +} + +/** + * Starts a Hermes console source on a fake client. + * + * @returns The client, session events and the binding name of the source. + */ +async function startSource(): Promise<{ + client: FakeClient; + events: SessionEvents; + source: HermesConsoleSource; + binding: string; + unsubscribe: () => Promise; +}> { + const client = createClient(); + const events = new SessionEvents(() => client, []); + const source = new HermesConsoleSource(); + const { unsubscribe } = await source.start(client, events); + const binding = ( + client.send.mock.calls.find( + ([method]) => method === 'Runtime.addBinding', + )?.[1] as { name: string } + ).name; + return { client, events, source, binding, unsubscribe }; +} + +/** + * Builds the parameters of a Hermes `Runtime.consoleAPICalled` event. + * + * @param type - The console call type. + * @param text - The string argument. + * @param extra - More parameters. + * @returns The event. + */ +function consoleEvent( + type: string, + text: string, + extra: Record = {}, +): { method: string; params: unknown } { + return { + method: 'Runtime.consoleAPICalled', + params: { + type, + args: [{ type: 'string', value: text }], + executionContextId: 1, + timestamp: 1, + stackTrace: { + callFrames: [ + { + url: `http://localhost:8085/index.bundle?platform=ios&token=${INFURA_KEY}`, + lineNumber: 9, + columnNumber: 4, + }, + ], + }, + ...extra, + }, + }; +} + +/** + * Builds a `Runtime.bindingCalled` event of the hook. + * + * @param name - The binding name. + * @param report - The hook report. + * @returns The event. + */ +function bindingEvent( + name: string, + report: unknown, +): { method: string; params: unknown } { + return { + method: 'Runtime.bindingCalled', + params: { name, payload: JSON.stringify(report), executionContextId: 1 }, + }; +} + +/** + * Reads every console record. + * + * @param events - The session events. + * @returns The records. + */ +function readAll(events: SessionEvents): ConsoleRecord[] { + return events.buffer.read({ kind: 'console', limit: 100 }) + .records; +} + +/** + * Lets pending promise callbacks run. + */ +async function flush(): Promise { + for (let index = 0; index < 5; index++) { + await Promise.resolve(); + } +} + +describe('hookScript', () => { + /** + * Builds a fake React Native global with `ErrorUtils` and a binding. + * + * @param bindings - Binding names to define. + * @returns The global, the original handler and the binding calls. + */ + function createGlobal(bindings: string[]): { + sandbox: Record; + original: ReturnType; + calls: Record; + } { + const original = vi.fn().mockReturnValue('handled'); + let handler: unknown = original; + const calls: Record = {}; + const sandbox: Record = { + ErrorUtils: { + getGlobalHandler: (): unknown => handler, + setGlobalHandler: (next: unknown): void => { + handler = next; + }, + }, + }; + for (const name of bindings) { + calls[name] = []; + sandbox[name] = (payload: string): void => { + calls[name]?.push(payload); + }; + } + sandbox.__r = (): undefined => undefined; + sandbox.globalThis = sandbox; + return { sandbox, original, calls }; + } + + /** + * Calls the current global handler of a fake global. + * + * @param sandbox - The fake global. + * @param args - The handler arguments. + * @returns What the handler returned. + */ + function callHandler( + sandbox: Record, + ...args: unknown[] + ): unknown { + const utils = sandbox.ErrorUtils as { getGlobalHandler: () => unknown }; + return (utils.getGlobalHandler() as (...rest: unknown[]) => unknown)( + ...args, + ); + } + + it('is not ready before the bundle ran', () => { + expect(runInNewContext(hookScript('__b'), {})).toBe('not-ready'); + const { sandbox } = createGlobal([]); + delete sandbox.__r; + expect(runInNewContext(hookScript('__b'), sandbox)).toBe('not-ready'); + }); + + it('installs once, reports the error, then calls the previous handler unchanged', () => { + const { sandbox, original, calls } = createGlobal(['__b']); + + expect(runInNewContext(hookScript('__b'), sandbox)).toBe('installed'); + expect(runInNewContext(hookScript('__b'), sandbox)).toBe('present'); + + const error = new Error('boom'); + error.stack = 'Error: boom\n at x (index.bundle:1:2)'; + const thisValue = { me: true }; + const utils = sandbox.ErrorUtils as { getGlobalHandler: () => unknown }; + const handler = utils.getGlobalHandler() as ( + this: unknown, + ...rest: unknown[] + ) => unknown; + expect(handler.call(thisValue, error, true)).toBe('handled'); + + expect(calls.__b).toStrictEqual([ + JSON.stringify({ + fatal: true, + text: 'Error: boom\n at x (index.bundle:1:2)', + }), + ]); + expect(original).toHaveBeenCalledTimes(1); + expect(original.mock.calls[0]).toStrictEqual([error, true]); + expect(original.mock.instances[0]).toBe(thisValue); + }); + + it('reports to every session binding, once per error', () => { + const { sandbox, calls } = createGlobal(['__a', '__b']); + runInNewContext(hookScript('__a'), sandbox); + expect(runInNewContext(hookScript('__b'), sandbox)).toBe('present'); + + const error = new Error('once'); + callHandler(sandbox, error, false); + callHandler(sandbox, error, false); + callHandler(sandbox, 'plain', false); + + expect(calls.__a).toHaveLength(2); + expect(calls.__b).toHaveLength(2); + expect(JSON.parse(calls.__a?.[1])).toStrictEqual({ + fatal: false, + text: 'plain', + }); + }); + + it('wraps a handler the app set after the hook, and keeps the chain', () => { + const { sandbox, original, calls } = createGlobal(['__b']); + runInNewContext(hookScript('__b'), sandbox); + const appHandler = vi.fn(); + ( + sandbox.ErrorUtils as { setGlobalHandler: (next: unknown) => void } + ).setGlobalHandler(appHandler); + + expect(runInNewContext(hookScript('__b'), sandbox)).toBe('installed'); + callHandler(sandbox, new Error('later'), false); + + expect(calls.__b).toHaveLength(1); + expect(appHandler).toHaveBeenCalledTimes(1); + expect(original).not.toHaveBeenCalled(); + }); + + it('calls the previous handler when reporting fails', () => { + const { sandbox, original } = createGlobal([]); + sandbox.__b = (): never => { + throw new Error('binding broken'); + }; + runInNewContext(hookScript('__b'), sandbox); + + callHandler(sandbox, new Error('x'), true); + + expect(original).toHaveBeenCalledTimes(1); + }); +}); + +describe('HermesConsoleSource', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it('connects, adds a session binding, enables Runtime and installs the hook', async () => { + const { client, binding } = await startSource(); + + expect(binding).toMatch(/^__mmLogs_[0-9a-f]{12}$/u); + expect(client.send.mock.calls.map(([method]) => method)).toStrictEqual([ + 'Runtime.addBinding', + 'Runtime.enable', + 'Runtime.evaluate', + ]); + const [, params] = client.send.mock.calls[2] as [ + string, + { expression: string; returnByValue: boolean }, + ]; + expect(params).toStrictEqual({ + expression: hookScript(binding), + returnByValue: true, + }); + }); + + it('uses another binding name in another session', async () => { + const first = await startSource(); + const second = await startSource(); + expect(first.binding).not.toBe(second.binding); + }); + + it('records console messages with target.kind hermes, redacted', async () => { + const { client, events } = await startSource(); + + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent( + 'error', + `mm-p2-29 probe https://mainnet.infura.io/v3/${INFURA_KEY}`, + ), + ); + + expect(readAll(events)).toStrictEqual([ + { + seq: 1, + t: expect.any(Number), + target: { kind: 'hermes', id: 'T1', url: '' }, + level: 'error', + text: 'mm-p2-29 probe https://mainnet.infura.io/v3/[REDACTED]', + location: + 'http://localhost:8085/index.bundle?platform=ios&token=[REDACTED]:10:5', + }, + ]); + }); + + it('applies the session levels', async () => { + const { client, events } = await startSource(); + + client.emit('Runtime.consoleAPICalled', consoleEvent('warning', 'w1')); + events.config = { consoleLevels: ['error', 'warning'], rpcErrors: false }; + client.emit('Runtime.consoleAPICalled', consoleEvent('warning', 'w2')); + client.emit('Runtime.consoleAPICalled', consoleEvent('log', 'l1')); + + expect(readAll(events).map((record) => record.text)).toStrictEqual(['w2']); + }); + + it('drops the replay that arrives before the Runtime.enable response, and synthetic messages', async () => { + const client = createClient(); + client.onEnable = (): void => { + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent('error', 'replayed'), + ); + }; + const events = new SessionEvents(() => client, []); + await new HermesConsoleSource().start(client, events); + + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent('error', 'note', { context: 'main#InstanceAgent' }), + ); + client.emit('Runtime.consoleAPICalled', consoleEvent('error', 'fresh')); + + expect(readAll(events).map((record) => record.text)).toStrictEqual([ + 'fresh', + ]); + }); + + it('marks the console error of an uncaught error that the hook reports after it', async () => { + const { client, events, binding } = await startSource(); + + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent( + 'error', + 'Error: mm-p2-29 uncaught\n at anonymous (:1:35)', + ), + ); + client.emit( + 'Runtime.bindingCalled', + bindingEvent(binding, { + fatal: true, + text: 'Error: mm-p2-29 uncaught\n at anonymous (:1:35)', + }), + ); + + expect(readAll(events)).toStrictEqual([ + expect.objectContaining({ + seq: 1, + text: 'Error: mm-p2-29 uncaught\n at anonymous (:1:35)', + uncaught: true, + fatal: true, + }), + ]); + }); + + it('records the hook report first and drops the console error that follows', async () => { + const { client, events, binding } = await startSource(); + + client.emit( + 'Runtime.bindingCalled', + bindingEvent(binding, { + fatal: false, + text: `Error: key https://mainnet.infura.io/v3/${INFURA_KEY}\n at f (:1:1)`, + }), + ); + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent( + 'error', + `Error: key https://mainnet.infura.io/v3/${INFURA_KEY}\n at f (:1:1)`, + ), + ); + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent('error', 'another error'), + ); + + expect(readAll(events)).toStrictEqual([ + { + seq: 1, + t: expect.any(Number), + target: { kind: 'hermes', id: 'T1', url: '' }, + level: 'error', + text: 'Error: key https://mainnet.infura.io/v3/[REDACTED]\n at f (:1:1)', + uncaught: true, + }, + expect.objectContaining({ seq: 2, text: 'another error' }), + ]); + }); + + it('ignores other bindings and payloads that are not reports', async () => { + const { client, events, binding } = await startSource(); + + client.emit( + 'Runtime.bindingCalled', + bindingEvent('__other', { fatal: true, text: 'x' }), + ); + client.emit('Runtime.bindingCalled', { + method: 'Runtime.bindingCalled', + params: { name: binding, payload: 'not json' }, + }); + client.emit('Runtime.bindingCalled', bindingEvent(binding, { text: 1 })); + client.emit('Runtime.bindingCalled', { + method: 'Runtime.bindingCalled', + params: { name: binding, payload: 7 }, + }); + + expect(readAll(events)).toStrictEqual([]); + }); + + it('reinstalls the hook after a reload (a new execution context)', async () => { + const { client, binding } = await startSource(); + client.send.mockClear(); + + client.emit('Runtime.executionContextCreated', { + method: 'Runtime.executionContextCreated', + params: { context: { id: 2, name: 'main', origin: '' } }, + }); + await flush(); + + expect(client.send).toHaveBeenCalledWith( + 'Runtime.evaluate', + { expression: hookScript(binding), returnByValue: true }, + expect.anything(), + ); + expect(client.send).not.toHaveBeenCalledWith( + 'Runtime.enable', + undefined, + expect.anything(), + ); + }); + + it('retries the hook until the bundle has run', async () => { + vi.useFakeTimers(); + const client = createClient(); + client.evaluations = [ + { ok: true, result: { result: { value: 'not-ready' } } }, + { + ok: true, + result: { exceptionDetails: { text: "Property '__r' doesn't exist" } }, + }, + { ok: true, result: { result: { value: 'installed' } } }, + ]; + const events = new SessionEvents(() => client, []); + await new HermesConsoleSource().start(client, events); + + await vi.advanceTimersByTimeAsync(1_000); + + const evaluations = client.send.mock.calls.filter( + ([method]) => method === 'Runtime.evaluate', + ); + expect(evaluations).toHaveLength(3); + expect(events.buffer.summary().captureErrors).toBe(0); + }); + + it('counts a hook that cannot be installed in time as a capture error', async () => { + vi.useFakeTimers(); + const client = createClient(); + client.evaluations = [ + { ok: false, code: 'HERMES_TIMEOUT', message: 'timed out' }, + ]; + const events = new SessionEvents(() => client, []); + await new HermesConsoleSource().start(client, events); + + await vi.advanceTimersByTimeAsync(61_000); + + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 1, + lastCaptureError: + 'uncaught-error hook not installed: [HERMES_TIMEOUT] timed out', + }); + }); + + it('stops a pending hook install when a reload starts a new one', async () => { + vi.useFakeTimers(); + const client = createClient(); + client.evaluations = [ + { ok: true, result: { result: { value: 'not-ready' } } }, + ]; + const events = new SessionEvents(() => client, []); + await new HermesConsoleSource().start(client, events); + client.emit('Runtime.executionContextCreated', { + method: 'Runtime.executionContextCreated', + params: {}, + }); + await vi.advanceTimersByTimeAsync(61_000); + + // Only the newest install reports. + expect(events.buffer.summary().captureErrors).toBe(1); + }); + + it('enables again on a new socket and counts the lost connection', async () => { + const { client, events, binding } = await startSource(); + client.send.mockClear(); + + client.emit('disconnected', { reason: '[CONNECTION_LOST]' }); + client.emit('contextCreated', { + reason: 'reconnect', + reconnected: true, + target: { id: 'T2', logicalDeviceId: 'D1', title: 'MetaMask' }, + }); + await flush(); + client.emit('Runtime.consoleAPICalled', consoleEvent('error', 'after')); + + expect(client.send.mock.calls.map(([method]) => method)).toStrictEqual([ + 'Runtime.addBinding', + 'Runtime.enable', + 'Runtime.evaluate', + ]); + expect(client.send.mock.calls[0]?.[1]).toStrictEqual({ name: binding }); + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 1, + lastCaptureError: 'Hermes connection lost: [CONNECTION_LOST]', + }); + expect(readAll(events)).toStrictEqual([ + expect.objectContaining({ + text: 'after', + target: { kind: 'hermes', id: 'T2', url: '' }, + }), + ]); + }); + + it('ignores contextCreated of the first connect and of a reload', async () => { + const { client } = await startSource(); + client.send.mockClear(); + + client.emit('contextCreated', { + reason: 'reload', + reconnected: false, + target: { id: 'T1' }, + }); + await flush(); + + expect(client.send).not.toHaveBeenCalled(); + }); + + it('counts a failed re-enable and a failed reconnect loop', async () => { + const { client, events } = await startSource(); + client.send.mockResolvedValue({ + ok: false, + code: 'HERMES_CDP_FAILED', + message: 'nope', + }); + + client.emit('contextCreated', { + reason: 'reconnect', + reconnected: true, + target: {}, + }); + await flush(); + client.emit('reconnectFailed', { + attempts: 6, + code: 'HERMES_TARGET_NOT_FOUND', + message: 'gone', + }); + + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 2, + lastCaptureError: + 'Hermes reconnect failed: [HERMES_TARGET_NOT_FOUND] gone', + }); + }); + + it('fails to start when it cannot connect or enable, and removes its listeners', async () => { + const client = createClient(); + const events = new SessionEvents(() => client, []); + client.connect.mockResolvedValueOnce({ + ok: false, + code: 'HERMES_TARGET_NOT_FOUND', + message: 'no target', + }); + await expect( + new HermesConsoleSource().start(client, events), + ).rejects.toThrowError( + 'Hermes connect failed: [HERMES_TARGET_NOT_FOUND] no target', + ); + expect(client.listenerCount()).toBe(0); + + client.send.mockImplementation(async (method: string) => + method === 'Runtime.enable' + ? { ok: false, code: 'HERMES_CDP_FAILED', message: 'enable' } + : { ok: true, result: {} }, + ); + await expect( + new HermesConsoleSource().start(client, events), + ).rejects.toThrowError('Runtime.enable failed: [HERMES_CDP_FAILED] enable'); + + client.send.mockResolvedValue({ + ok: false, + code: 'HERMES_CDP_FAILED', + message: 'binding', + }); + await expect( + new HermesConsoleSource().start(client, events), + ).rejects.toThrowError( + 'Runtime.addBinding failed: [HERMES_CDP_FAILED] binding', + ); + expect(client.listenerCount()).toBe(0); + }); + + it('stops recording after unsubscribe', async () => { + const { client, events, unsubscribe } = await startSource(); + + await unsubscribe(); + client.emit('Runtime.consoleAPICalled', consoleEvent('error', 'late')); + + expect(client.listenerCount()).toBe(0); + expect(readAll(events)).toStrictEqual([]); + }); + + it('releases the console object group from time to time', async () => { + const { client } = await startSource(); + + for (let index = 0; index < 200; index++) { + client.emit('Runtime.consoleAPICalled', consoleEvent('log', 'x')); + } + + expect(client.send).toHaveBeenCalledWith( + 'Runtime.releaseObjectGroup', + { objectGroup: 'ConsoleObjectGroup' }, + expect.anything(), + ); + }); + + it('shares the cursor and gap of the session buffer', async () => { + const client = createClient(); + const events = new SessionEvents(() => client, []); + await new HermesConsoleSource().start(client, events); + const mark = events.buffer.seq; + + for (let index = 0; index < 1001; index++) { + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent('error', `e${index}`), + ); + } + + const page = events.buffer.read({ + kind: 'console', + cursor: mark, + limit: 2, + }); + expect(page).toMatchObject({ hasMore: true, gap: true, cursor: 3 }); + expect(page.records.map((record) => record.text)).toStrictEqual([ + 'e1', + 'e2', + ]); + expect(page.summary.dropped.console).toBe(1); + }); +}); diff --git a/src/events/hermes-console-source.ts b/src/events/hermes-console-source.ts new file mode 100644 index 00000000..e004331f --- /dev/null +++ b/src/events/hermes-console-source.ts @@ -0,0 +1,466 @@ +import { randomBytes } from 'node:crypto'; + +import type { ConsoleEvent } from './console-source.js'; +import { ConsoleRecorder, toConsoleRecord } from './console-source.js'; +import type { RecordSourceTarget } from './read-options.js'; +import { redactText } from './redact.js'; +import type { SessionEventSource, SessionEvents } from './session-events.js'; +import type { CdpSubscription } from '../platform/cdp-manager.js'; +import type { HermesEventClient } from '../platform/types.js'; +import type { ConsoleRecord } from '../tools/types/events.js'; + +/** Timeout of each CDP call of the source. */ +const HERMES_CALL_TIMEOUT_MS = 5_000; + +/** Pause between two attempts to install the uncaught-error hook. */ +const HOOK_RETRY_MS = 500; + +/** + * How long the source tries to install the hook after a new JS context. The + * app's bundle must have run first: about 4 s on Android and 14 s on iOS dev + * builds. + */ +const HOOK_INSTALL_TIMEOUT_MS = 60_000; + +/** How long an uncaught error and its console message are matched. */ +const UNCAUGHT_JOIN_MS = 5_000; + +/** Recent records and reports kept for the match. */ +const MAX_JOIN_ENTRIES = 20; + +/** + * Console events after which the source releases the console object group: + * Hermes keeps every object argument of a console call until then. + */ +const RELEASE_OBJECTS_EVERY = 200; + +/** Longest error text the hook sends. */ +const MAX_HOOK_TEXT_LENGTH = 8_000; + +/** + * Builds the script that wraps the `ErrorUtils` global handler of the current + * JS context. The wrapper sends `{ fatal, text }` of each error once to every + * binding listed in `globalThis.__mmLogsHook`, then calls the previous + * handler with the same `this` and arguments and returns its result, so the + * app's handling (red box, LogBox, crash) does not change. It reads nothing + * else and changes no other app state. When the app replaced the wrapper, the + * new handler is wrapped in turn. + * + * @param bindingName - The binding of this session. + * @returns The script. It evaluates to `installed`, `present` (the wrapper + * is the global handler already; the binding is added) or `not-ready` (the + * app's bundle has not run yet). + */ +export function hookScript(bindingName: string): string { + return `(function () { + var g = globalThis; + var utils = g.ErrorUtils; + if (typeof g.__r !== 'function' || !utils || typeof utils.getGlobalHandler !== 'function') return 'not-ready'; + var current = utils.getGlobalHandler(); + if (typeof current !== 'function') return 'not-ready'; + var state = g.__mmLogsHook; + if (!state) { + state = { bindings: [], seen: new WeakSet() }; + g.__mmLogsHook = state; + } + if (state.bindings.indexOf(${JSON.stringify(bindingName)}) < 0) state.bindings.push(${JSON.stringify(bindingName)}); + if (current === state.hook) return 'present'; + var hook = function (error, isFatal) { + try { + var isObject = error !== null && (typeof error === 'object' || typeof error === 'function'); + if (!isObject || !state.seen.has(error)) { + if (isObject) state.seen.add(error); + var text = isObject + ? (typeof error.stack === 'string' && error.stack) || String(error.name) + ': ' + String(error.message) + : String(error); + var payload = JSON.stringify({ fatal: isFatal === true, text: text.slice(0, ${MAX_HOOK_TEXT_LENGTH}) }); + for (var i = 0; i < state.bindings.length; i++) { + var binding = g[state.bindings[i]]; + if (typeof binding === 'function') binding(payload); + } + } + } catch (ignored) {} + return current.apply(this, arguments); + }; + state.hook = hook; + utils.setGlobalHandler(hook); + return 'installed'; +})()`; +} + +/** + * Returns the first line of a text. + * + * @param text - The text. + * @returns Its first line. + */ +function firstLine(text: string): string { + const end = text.indexOf('\n'); + return end === -1 ? text : text.slice(0, end); +} + +/** + * Reads the hook payload of a `Runtime.bindingCalled` event. + * + * @param payload - The binding payload. + * @returns The report, or undefined when the payload is not one. + */ +function parseHookPayload( + payload: unknown, +): { fatal: boolean; text: string } | undefined { + if (typeof payload !== 'string') { + return undefined; + } + try { + const parsed = JSON.parse(payload) as { fatal?: unknown; text?: unknown }; + if (typeof parsed.text !== 'string') { + return undefined; + } + return { fatal: parsed.fatal === true, text: parsed.text }; + } catch { + return undefined; + } +} + +/** + * Records the console messages of the app's Hermes runtime (mobile), at the + * levels in the session config, through the session's persistent Hermes + * client. + * + * `Runtime.exceptionThrown` never fires on Hermes: an uncaught error only + * arrives as the `console.error` that React Native logs for it. To mark it + * `uncaught` (and `fatal`, when it shows the red box), the source installs an + * observe-only wrapper of the `ErrorUtils` global handler ({@link hookScript}) + * that reports through a binding of this session, again after each JS reload. + * + * `Runtime.enable` replays the messages Hermes kept before its response: + * those are dropped. + */ +export class HermesConsoleSource implements SessionEventSource { + readonly #recorder = new ConsoleRecorder(); + + readonly #bindingName = `__mmLogs_${randomBytes(6).toString('hex')}`; + + /** `Runtime.enable` calls without a response yet. */ + #enabling = 0; + + /** Bumped to stop a running hook install. */ + #hookGeneration = 0; + + #consoleEvents = 0; + + #target: RecordSourceTarget = { kind: 'hermes', targetId: '', url: '' }; + + /** Recent error records, to mark the one an uncaught error logged. */ + readonly #recentErrors: { record: ConsoleRecord; at: number }[] = []; + + /** Recent uncaught errors recorded from the hook, to drop their console message. */ + readonly #recentUncaught: { head: string; at: number }[] = []; + + /** + * @param client - The session's persistent Hermes client. + * @param events - The session's events. + * @returns The subscription. + */ + async start( + client: HermesEventClient, + events: SessionEvents, + ): Promise { + let active = true; + const onConsole = (event: { params: unknown }): void => { + if (active) { + this.#onConsole(client, events, event.params); + } + }; + const onBinding = (event: { params: unknown }): void => { + const params = event.params as { name?: unknown; payload?: unknown }; + if (active && params?.name === this.#bindingName) { + this.#onUncaught(events, params.payload); + } + }; + const onExecutionContext = (): void => { + // The context of the source's own `Runtime.enable` is not a reload. + if (active && this.#enabling === 0) { + this.#installHook(client, events); + } + }; + const onContextCreated = (event: { + reason: string; + target: { id?: string }; + }): void => { + if (active && event.reason === 'reconnect') { + this.#setTarget(event.target); + this.#enable(client, events).catch(events.reportError); + } + }; + const onDisconnected = (event: { reason: string }): void => { + if (active) { + events.reportError( + new Error(`Hermes connection lost: ${event.reason}`), + ); + } + }; + const onReconnectFailed = (event: { + code: string; + message: string; + }): void => { + if (active) { + events.reportError( + new Error( + `Hermes reconnect failed: [${event.code}] ${event.message}`, + ), + ); + } + }; + const listeners: [string, (payload: never) => void][] = [ + ['Runtime.consoleAPICalled', onConsole], + ['Runtime.bindingCalled', onBinding], + ['Runtime.executionContextCreated', onExecutionContext], + ['contextCreated', onContextCreated], + ['disconnected', onDisconnected], + ['reconnectFailed', onReconnectFailed], + ]; + const on = client.on.bind(client) as ( + name: string, + listener: (payload: never) => void, + ) => void; + const off = client.off.bind(client) as typeof on; + const unsubscribe = async (): Promise => { + active = false; + this.#hookGeneration += 1; + for (const [name, listener] of listeners) { + off(name, listener); + } + }; + for (const [name, listener] of listeners) { + on(name, listener); + } + + try { + const connected = await client.connect({ + timeoutMs: HERMES_CALL_TIMEOUT_MS, + }); + if (!connected.ok) { + throw new Error( + `Hermes connect failed: [${connected.code}] ${connected.message}`, + ); + } + this.#setTarget(connected.target); + await this.#enable(client, events); + } catch (error) { + await unsubscribe(); + throw error; + } + return { unsubscribe }; + } + + /** + * Keeps the Metro target ID of the connection for the records. + * + * @param target - The connected target. + * @param target.id - Metro's target ID. + */ + #setTarget(target: { id?: string }): void { + this.#target = { kind: 'hermes', targetId: target.id ?? '', url: '' }; + } + + /** + * Adds the binding and enables `Runtime` on the current socket, then + * installs the hook. Console messages that arrive before the + * `Runtime.enable` response are replays and are dropped. + * + * @param client - The Hermes client. + * @param events - The session's events. + */ + async #enable( + client: HermesEventClient, + events: SessionEvents, + ): Promise { + this.#enabling += 1; + try { + const bound = await client.send( + 'Runtime.addBinding', + { name: this.#bindingName }, + { timeoutMs: HERMES_CALL_TIMEOUT_MS }, + ); + if (!bound.ok) { + throw new Error( + `Runtime.addBinding failed: [${bound.code}] ${bound.message}`, + ); + } + const enabled = await client.send('Runtime.enable', undefined, { + timeoutMs: HERMES_CALL_TIMEOUT_MS, + }); + if (!enabled.ok) { + throw new Error( + `Runtime.enable failed: [${enabled.code}] ${enabled.message}`, + ); + } + } finally { + this.#enabling -= 1; + } + this.#installHook(client, events); + } + + /** + * Installs the hook in the current JS context, retrying until the app's + * bundle has run. A newer install, or the end of the subscription, stops + * this one. Never rejects: a hook that cannot be installed is a capture + * error. + * + * @param client - The Hermes client. + * @param events - The session's events. + */ + #installHook( + client: HermesEventClient, + events: SessionEvents, + ): void { + this.#hookGeneration += 1; + const generation = this.#hookGeneration; + const deadline = Date.now() + HOOK_INSTALL_TIMEOUT_MS; + const expression = hookScript(this.#bindingName); + (async (): Promise => { + let last = 'not-ready'; + while (generation === this.#hookGeneration) { + const outcome = await client.send( + 'Runtime.evaluate', + { expression, returnByValue: true }, + { timeoutMs: HERMES_CALL_TIMEOUT_MS }, + ); + if (outcome.ok) { + const value = (outcome.result as { result?: { value?: unknown } }) + ?.result?.value; + if (value === 'installed' || value === 'present') { + return; + } + last = typeof value === 'string' ? value : 'no result'; + } else { + last = `[${outcome.code}] ${outcome.message}`; + } + if (Date.now() >= deadline) { + if (generation === this.#hookGeneration) { + events.reportError( + new Error(`uncaught-error hook not installed: ${last}`), + ); + } + return; + } + await new Promise((resolve) => setTimeout(resolve, HOOK_RETRY_MS)); + } + })().catch(events.reportError); + } + + /** + * Records one console message, unless it is a replay, a synthetic message + * of the React Native backend, or the console message of an uncaught error + * the hook recorded already. + * + * @param client - The Hermes client. + * @param events - The session's events. + * @param params - The `Runtime.consoleAPICalled` parameters. + */ + #onConsole( + client: HermesEventClient, + events: SessionEvents, + params: unknown, + ): void { + this.#consoleEvents += 1; + if (this.#consoleEvents % RELEASE_OBJECTS_EVERY === 0) { + client + .send( + 'Runtime.releaseObjectGroup', + { objectGroup: 'ConsoleObjectGroup' }, + { timeoutMs: HERMES_CALL_TIMEOUT_MS }, + ) + .catch(() => undefined); + } + const context = (params as { context?: unknown } | undefined)?.context; + if ( + this.#enabling > 0 || + (typeof context === 'string' && context.endsWith('#InstanceAgent')) + ) { + return; + } + const event: ConsoleEvent = { + target: this.#target, + method: 'Runtime.consoleAPICalled', + params: (params ?? {}) as Record, + t: Date.now(), + }; + const built = toConsoleRecord(event); + const now = Date.now(); + if (built?.record.level === 'error') { + const head = firstLine(built.record.text); + const index = this.#recentUncaught.findIndex( + (entry) => entry.head === head && now - entry.at <= UNCAUGHT_JOIN_MS, + ); + if (index !== -1) { + this.#recentUncaught.splice(index, 1); + return; + } + } + // Device timestamps are not compared with the daemon clock: replays are + // dropped by the `Runtime.enable` boundary instead. + const stored = this.#recorder.add(built, events, 0); + if (stored?.level === 'error') { + this.#recentErrors.push({ record: stored, at: now }); + this.#recentErrors.splice( + 0, + this.#recentErrors.length - MAX_JOIN_ENTRIES, + ); + } + } + + /** + * Records an uncaught error the hook reported. When its console message + * was recorded already, that record is marked instead. + * + * @param events - The session's events. + * @param payload - The binding payload. + */ + #onUncaught( + events: SessionEvents, + payload: unknown, + ): void { + const report = parseHookPayload(payload); + if (report === undefined) { + return; + } + const text = redactText(report.text); + const head = firstLine(text); + const now = Date.now(); + const index = this.#recentErrors.findIndex( + (entry) => + entry.record.uncaught === undefined && + firstLine(entry.record.text) === head && + now - entry.at <= UNCAUGHT_JOIN_MS, + ); + if (index !== -1) { + const [{ record }] = this.#recentErrors.splice(index, 1); + record.uncaught = true; + if (report.fatal) { + record.fatal = true; + } + return; + } + this.#recorder.add( + { + record: { + t: now, + target: { kind: 'hermes', id: this.#target.targetId, url: '' }, + level: 'error', + text, + uncaught: true, + ...(report.fatal ? { fatal: true as const } : {}), + }, + }, + events, + 0, + ); + this.#recentUncaught.push({ head, at: now }); + this.#recentUncaught.splice( + 0, + this.#recentUncaught.length - MAX_JOIN_ENTRIES, + ); + } +} diff --git a/src/events/network-source.test.ts b/src/events/network-source.test.ts index 99be992e..99987693 100644 --- a/src/events/network-source.test.ts +++ b/src/events/network-source.test.ts @@ -1,4 +1,3 @@ -import type { BrowserContext } from '@playwright/test'; import { describe, expect, it, vi } from 'vitest'; import { MAX_RPC_REQUEST_BYTES } from './json-rpc.js'; @@ -75,7 +74,7 @@ async function startSource( }, ), } as unknown as CdpManager; - const events = new SessionEvents({} as BrowserContext, []); + const events = new SessionEvents(() => manager, []); const source = new NetworkSource(); const subscription = await source.start(manager, events); const subscribed = options as CdpSubscribeOptions; diff --git a/src/events/read-options.ts b/src/events/read-options.ts index 552a3d80..4444bc08 100644 --- a/src/events/read-options.ts +++ b/src/events/read-options.ts @@ -31,13 +31,18 @@ export function parseSince( return Number.isNaN(parsed) ? undefined : parsed; } +/** The target of an event: a browser CDP target, or the mobile Hermes runtime. */ +export type RecordSourceTarget = Omit & { + kind: EventRecordTarget['kind']; +}; + /** - * Converts the target of a CDP event to the target of a record, with its - * URL redacted. + * Converts the target of an event to the target of a record, with its URL + * redacted. * - * @param target - The CDP event target. + * @param target - The event target. * @returns The record target. */ -export function toRecordTarget(target: CdpEventTarget): EventRecordTarget { +export function toRecordTarget(target: RecordSourceTarget): EventRecordTarget { return { kind: target.kind, id: target.targetId, url: redactUrl(target.url) }; } diff --git a/src/events/session-events.test.ts b/src/events/session-events.test.ts index 859020c5..2ecab46d 100644 --- a/src/events/session-events.test.ts +++ b/src/events/session-events.test.ts @@ -3,11 +3,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { SessionEventSource } from './session-events.js'; import { + getActiveSessionEvents, getSessionEvents, SESSION_EVENTS_START_WAIT_MS, SessionEvents, } from './session-events.js'; import { getCdpManager } from '../platform/cdp-manager.js'; +import type { IPlatformDriver } from '../platform/types.js'; +import type { ISessionManager } from '../server/session-manager.js'; vi.mock('../platform/cdp-manager.js', () => ({ getCdpManager: vi.fn(), @@ -15,6 +18,15 @@ vi.mock('../platform/cdp-manager.js', () => ({ const getCdpManagerMock = vi.mocked(getCdpManager); +/** + * Returns the CDP manager of a fake browser context. + * + * @returns The manager. + */ +function connect(): ReturnType { + return getCdpManager({} as BrowserContext); +} + /** * Creates a source whose start resolves with a fake subscription. * @@ -40,7 +52,7 @@ describe('SessionEvents', () => { const manager = { id: 1 }; getCdpManagerMock.mockReturnValue(manager as never); const { source } = createSource(); - const events = new SessionEvents({} as BrowserContext, [source]); + const events = new SessionEvents(connect, [source]); await Promise.all([events.ensureStarted(), events.ensureStarted()]); await events.ensureStarted(); @@ -52,7 +64,7 @@ describe('SessionEvents', () => { it('restarts the sources on a new CDP manager, ending the old subscriptions', async () => { getCdpManagerMock.mockReturnValueOnce({ id: 1 } as never); const { source, unsubscribe } = createSource(); - const events = new SessionEvents({} as BrowserContext, [source]); + const events = new SessionEvents(connect, [source]); await events.ensureStarted(); const second = { id: 2 }; @@ -81,7 +93,7 @@ describe('SessionEvents', () => { ) .mockResolvedValue({ unsubscribe: unsubscribeSecond }), }; - const events = new SessionEvents({} as BrowserContext, [source]); + const events = new SessionEvents(connect, [source]); getCdpManagerMock.mockReturnValue({ id: 1 } as never); const firstRun = events.ensureStarted(); @@ -102,11 +114,78 @@ describe('SessionEvents', () => { expect(source.start).toHaveBeenCalledTimes(2); }); + it('starts a failed source again on the next call, without restarting the others', async () => { + getCdpManagerMock.mockReturnValue({ id: 1 } as never); + const failing = { + start: vi + .fn() + .mockRejectedValueOnce(new Error('not yet')) + .mockResolvedValue({ unsubscribe: vi.fn() }), + }; + const { source, unsubscribe } = createSource(); + const events = new SessionEvents(connect, [failing, source]); + + await events.ensureStarted(); + await events.ensureStarted(); + await events.ensureStarted(); + + expect(failing.start).toHaveBeenCalledTimes(2); + expect(source.start).toHaveBeenCalledTimes(1); + expect(unsubscribe).not.toHaveBeenCalled(); + }); + + it('lets concurrent calls wait for the same retry of a failed source', async () => { + getCdpManagerMock.mockReturnValue({ id: 1 } as never); + let finishRetry: (value: { + unsubscribe: () => Promise; + }) => void = () => undefined; + const failing = { + start: vi + .fn() + .mockRejectedValueOnce(new Error('not yet')) + .mockImplementationOnce( + async () => + new Promise((resolve) => { + finishRetry = resolve; + }), + ), + }; + const events = new SessionEvents(connect, [failing]); + await events.ensureStarted(); + + const first = events.ensureStarted(); + const second = events.ensureStarted(); + await vi.waitFor(() => expect(failing.start).toHaveBeenCalledTimes(2)); + finishRetry({ unsubscribe: vi.fn() }); + await Promise.all([first, second]); + + expect(failing.start).toHaveBeenCalledTimes(2); + }); + + it('records a connection that cannot be made, and tries again later', async () => { + const { source } = createSource(); + const failingConnect = vi + .fn() + .mockRejectedValueOnce(new Error('no client')) + .mockResolvedValue({ id: 1 }); + const events = new SessionEvents(failingConnect, [source]); + + await events.ensureStarted(); + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 1, + lastCaptureError: 'no client', + }); + expect(source.start).not.toHaveBeenCalled(); + + await events.ensureStarted(); + expect(source.start).toHaveBeenCalledTimes(1); + }); + it('keeps the other sources when one fails to start', async () => { getCdpManagerMock.mockReturnValueOnce({ id: 1 } as never); const failing = { start: vi.fn().mockRejectedValue(new Error('boom')) }; const { source, unsubscribe } = createSource(); - const events = new SessionEvents({} as BrowserContext, [failing, source]); + const events = new SessionEvents(connect, [failing, source]); expect(await events.ensureStarted()).toBeUndefined(); @@ -145,7 +224,7 @@ describe('SessionEvents start bound and errors', () => { const source = { start: vi.fn(async () => new Promise(() => undefined)), }; - const events = new SessionEvents({} as BrowserContext, [source]); + const events = new SessionEvents(connect, [source]); const first = track(events.ensureStarted()); await vi.advanceTimersByTimeAsync(SESSION_EVENTS_START_WAIT_MS); @@ -167,7 +246,7 @@ describe('SessionEvents start bound and errors', () => { it('returns as soon as the sources started', async () => { getCdpManagerMock.mockReturnValue({ id: 1 } as never); const { source } = createSource(); - const events = new SessionEvents({} as BrowserContext, [source]); + const events = new SessionEvents(connect, [source]); expect(await events.ensureStarted()).toBeUndefined(); expect(source.start).toHaveBeenCalledTimes(1); @@ -184,7 +263,7 @@ describe('SessionEvents start bound and errors', () => { ), ), }; - const events = new SessionEvents({} as BrowserContext, [failing]); + const events = new SessionEvents(connect, [failing]); await events.ensureStarted(); @@ -195,7 +274,7 @@ describe('SessionEvents start bound and errors', () => { }); it('reportError counts, redacts and cuts an error, and never throws', () => { - const events = new SessionEvents({} as BrowserContext, []); + const events = new SessionEvents(connect, []); events.reportError(new Error('x'.repeat(400))); expect(events.buffer.summary().lastCaptureError).toBe( @@ -226,3 +305,81 @@ describe('getSessionEvents', () => { expect(other.buffer.startedAt).toBeGreaterThan(events.buffer.startedAt); }); }); + +describe('getActiveSessionEvents', () => { + /** + * Builds a session manager with a platform driver. + * + * @param driver - The platform driver. + * @param context - The browser context. + * @returns The session manager. + */ + function createManager( + driver: Partial | undefined, + context: BrowserContext = {} as BrowserContext, + ): ISessionManager { + return { + getPlatformDriver: () => driver as IPlatformDriver | undefined, + getContext: () => context, + } as unknown as ISessionManager; + } + + it('returns the browser context events without a mobile driver', () => { + const context = {} as BrowserContext; + + expect(getActiveSessionEvents(createManager(undefined, context))).toBe( + getSessionEvents(context), + ); + expect( + getActiveSessionEvents( + createManager({ getPlatform: () => 'browser' }, context), + ), + ).toBe(getSessionEvents(context)); + }); + + it('returns one instance per mobile driver, started on its Hermes client', async () => { + const client = { + connect: vi + .fn() + .mockResolvedValue({ ok: false, code: 'X', message: 'down' }), + send: vi.fn(), + on: vi.fn(), + off: vi.fn(), + }; + const driver = { + getPlatform: (): 'ios' => 'ios', + getHermesEventClient: vi.fn().mockResolvedValue(client), + }; + const manager = createManager(driver); + + const events = getActiveSessionEvents(manager); + expect(getActiveSessionEvents(manager)).toBe(events); + expect(getActiveSessionEvents(createManager({ ...driver }))).not.toBe( + events, + ); + + await events.ensureStarted(); + expect(driver.getHermesEventClient).toHaveBeenCalledTimes(1); + expect(client.on).toHaveBeenCalledWith( + 'Runtime.consoleAPICalled', + expect.any(Function), + ); + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 1, + lastCaptureError: 'Hermes connect failed: [X] down', + }); + }); + + it('records a mobile driver without a Hermes client as a capture error', async () => { + const events = getActiveSessionEvents( + createManager({ getPlatform: () => 'android' }), + ); + + await events.ensureStarted(); + + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 1, + lastCaptureError: 'No Hermes client for the session target', + }); + }); +}); diff --git a/src/events/session-events.ts b/src/events/session-events.ts index 73be9a66..1c0969c2 100644 --- a/src/events/session-events.ts +++ b/src/events/session-events.ts @@ -2,10 +2,13 @@ import type { BrowserContext } from '@playwright/test'; import { ConsoleSource, DEFAULT_CONSOLE_LEVELS } from './console-source.js'; import { EventBuffer } from './event-buffer.js'; +import { HermesConsoleSource } from './hermes-console-source.js'; import { NetworkSource } from './network-source.js'; import { redactText, truncateText } from './redact.js'; import type { CdpManager, CdpSubscription } from '../platform/cdp-manager.js'; import { getCdpManager } from '../platform/cdp-manager.js'; +import type { HermesEventClient, IPlatformDriver } from '../platform/types.js'; +import type { ISessionManager } from '../server/session-manager.js'; import type { EventConfig, NetworkStats } from '../tools/types/events.js'; import { debugWarn, extractErrorMessage } from '../utils'; @@ -20,28 +23,30 @@ export const SESSION_EVENTS_START_WAIT_MS = 5_000; const MAX_CAPTURE_ERROR_LENGTH = 300; /** - * A producer of event records: it listens to CDP events of every page and - * the Extension service worker and writes records into the session buffer. + * A producer of event records: it listens to CDP events of the session's + * connection (the CDP manager of a browser session, the Hermes client of a + * mobile session) and writes records into the session buffer. */ -export type SessionEventSource = { +export type SessionEventSource = { /** - * Starts listening. Called once per CDP manager of the session. + * Starts listening. Called once per connection of the session. * - * @param manager - The session's CDP manager. - * @param events - The session's events: its buffer and browser context. + * @param connection - The session's connection. + * @param events - The session's events. * @returns The subscription to end when the session stops. */ - start(manager: CdpManager, events: SessionEvents): Promise; + start( + connection: Connection, + events: SessionEvents, + ): Promise; }; /** - * The event buffer and event sources of one browser session. + * The event buffer and event sources of one session. */ -export class SessionEvents { +export class SessionEvents { readonly buffer = new EventBuffer(); - readonly context: BrowserContext; - /** What the sources record. Sources read it for each event. */ config: EventConfig = { consoleLevels: [...DEFAULT_CONSOLE_LEVELS], @@ -55,20 +60,28 @@ export class SessionEvents { rpcErrorsSkipped: 0, }; - readonly #sources: SessionEventSource[]; + readonly #connect: () => Connection | Promise; + + readonly #sources: SessionEventSource[]; - #manager: CdpManager | undefined; + #connection: Connection | undefined; #starting: Promise | undefined; #subscriptions: CdpSubscription[] = []; + /** Sources of the current connection that have not started. */ + #failed: SessionEventSource[] = []; + /** - * @param context - The browser context of the session. + * @param connect - Returns the session's current connection. * @param sources - The sources that fill the buffer. */ - constructor(context: BrowserContext, sources: SessionEventSource[]) { - this.context = context; + constructor( + connect: () => Connection | Promise, + sources: SessionEventSource[], + ) { + this.#connect = connect; this.#sources = sources; } @@ -95,9 +108,10 @@ export class SessionEvents { }; /** - * Starts every source, once per CDP manager. Safe to call often: a call - * while the sources run does nothing. When the context's CDP manager was - * replaced (disposed and created again), the sources start on the new one. + * Starts every source, once per connection. Safe to call often: a call + * while the sources run does nothing. When the connection was replaced (a + * CDP manager disposed and created again, a new Hermes client), the + * sources start on the new one. * Failures are recorded (see {@link reportError}), never thrown: events * are best-effort. * @@ -116,39 +130,64 @@ export class SessionEvents { } /** - * Starts every source once per CDP manager, or returns the start in - * progress. + * Starts every source once per connection, or returns the start in + * progress. A source that failed to start is started again by the next + * call. * * @returns Settles when the sources started. Never rejects. */ async #start(): Promise { - const manager = getCdpManager(this.context); - if (manager === this.#manager) { - await this.#starting; + let connection: Connection; + try { + connection = await this.#connect(); + } catch (error) { + this.reportError(error); return; } - this.#manager = manager; + if (connection === this.#connection) { + const current = this.#starting; + await current; + if (this.#starting !== current) { + await this.#starting; + return; + } + if (this.#failed.length === 0 || this.#connection !== connection) { + return; + } + } else { + this.#connection = connection; + this.#failed = this.#sources; + } const previous = this.#subscriptions; - this.#subscriptions = []; + const sources = this.#failed; + const restart = sources === this.#sources; + this.#failed = []; + if (restart) { + this.#subscriptions = []; + } const starting = (async (): Promise => { - await Promise.all( - previous.map(async (subscription) => - subscription.unsubscribe().catch(() => undefined), - ), - ); + if (restart) { + await Promise.all( + previous.map(async (subscription) => + subscription.unsubscribe().catch(() => undefined), + ), + ); + } const results = await Promise.allSettled( - this.#sources.map(async (source) => source.start(manager, this)), + sources.map(async (source) => source.start(connection, this)), ); - const started = results.flatMap((result) => { + const failed: SessionEventSource[] = []; + const started = results.flatMap((result, index) => { if (result.status === 'fulfilled') { return [result.value]; } + failed.push(sources[index]); this.reportError(result.reason); return []; }); - if (this.#manager !== manager) { - // The CDP manager was replaced while the sources started: these - // subscriptions belong to the old manager, not to this session. + if (this.#connection !== connection) { + // The connection was replaced while the sources started: these + // subscriptions belong to the old one, not to this session. await Promise.all( started.map(async (subscription) => subscription.unsubscribe().catch(() => undefined), @@ -156,24 +195,21 @@ export class SessionEvents { ); return; } - this.#subscriptions = started; + this.#subscriptions.push(...started); + this.#failed.push(...failed); })(); this.#starting = starting; await starting; } } -/** - * Creates the sources of a new session. - * - * @returns The sources. - */ -function createSources(): SessionEventSource[] { - return [new ConsoleSource(), new NetworkSource()]; -} - const sessions = new WeakMap(); +const mobileSessions = new WeakMap< + IPlatformDriver, + SessionEvents +>(); + /** * Returns the events of a browser session, creating them (and a new buffer * with a new `startedAt`) on first use. A relaunched session has a new @@ -185,8 +221,46 @@ const sessions = new WeakMap(); export function getSessionEvents(context: BrowserContext): SessionEvents { let events = sessions.get(context); if (!events) { - events = new SessionEvents(context, createSources()); + events = new SessionEvents( + () => getCdpManager(context), + [new ConsoleSource(), new NetworkSource()], + ); sessions.set(context, events); } return events; } + +/** + * Returns the events of the active session: those of its mobile driver (the + * app's Hermes runtime) on iOS and Android, else those of its browser + * context. A relaunched session has a new driver or browser context, so it + * gets a new buffer. + * + * @param sessionManager - The session manager. + * @returns The session's events. + */ +export function getActiveSessionEvents( + sessionManager: ISessionManager, +): SessionEvents | SessionEvents { + const driver = sessionManager.getPlatformDriver?.(); + if (driver === undefined || driver.getPlatform() === 'browser') { + return getSessionEvents(sessionManager.getContext()); + } + let events = mobileSessions.get(driver); + if (!events) { + events = new SessionEvents(async () => { + const client = await driver.getHermesEventClient?.(); + if (client === undefined) { + throw new Error('No Hermes client for the session target'); + } + // Reconnects a client whose reconnect loop gave up; the source + // enables again on its `contextCreated` (`reconnect`). + client + .connect({ timeoutMs: SESSION_EVENTS_START_WAIT_MS }) + .catch(() => undefined); + return client; + }, [new HermesConsoleSource()]); + mobileSessions.set(driver, events); + } + return events; +} diff --git a/src/platform/mobile-platform-driver.hermes.test.ts b/src/platform/mobile-platform-driver.hermes.test.ts index ab2b2b64..0210e307 100644 --- a/src/platform/mobile-platform-driver.hermes.test.ts +++ b/src/platform/mobile-platform-driver.hermes.test.ts @@ -808,6 +808,55 @@ describe('MobilePlatformDriver persistent Hermes client', () => { expect(mocks.HermesClient).toHaveBeenCalledTimes(1); }); + it('gives the session client to the event sources', async () => { + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + + const client = await driver.getHermesEventClient(); + await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); + + expect(client).toBe(clients[0]); + expect(mocks.HermesClient).toHaveBeenCalledTimes(1); + expect(clients[0].send).toHaveBeenCalledTimes(1); + }); + + it('keeps Runtime enabled for the event sources on the session client', async () => { + const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { + metroPort: 8085, + }); + expect( + await driver.cdp({ method: 'Runtime.enable', timeoutMs: 30_000 }), + ).toStrictEqual({ ok: true, result: { value: 2 } }); + clients[0].send.mockClear(); + + await driver.getHermesEventClient(); + + expect( + await driver.cdp({ method: 'Runtime.enable', timeoutMs: 30_000 }), + ).toStrictEqual({ ok: true, result: {} }); + expect( + await driver.cdp({ method: 'Runtime.disable', timeoutMs: 30_000 }), + ).toMatchObject({ ok: false, code: 'MM_CDP_BLOCKED' }); + expect(clients[0].send).not.toHaveBeenCalled(); + + mocks.runHermesCdp.mockResolvedValue({ ok: true, result: {} }); + await driver.cdp({ + method: 'Runtime.disable', + timeoutMs: 30_000, + metroPort: 8087, + }); + expect(mocks.runHermesCdp).toHaveBeenCalledTimes(1); + + driver.setHermesDefaults({ metroPort: 8086 }); + await driver.cdp({ method: 'Runtime.disable', timeoutMs: 30_000 }); + expect(clients[1].send).toHaveBeenCalledWith( + 'Runtime.disable', + undefined, + expect.anything(), + ); + }); + it('closes the client on dispose', async () => { const disposeBackend = vi.fn().mockResolvedValue(undefined); const driver = new MobilePlatformDriver( diff --git a/src/platform/mobile-platform-driver.ts b/src/platform/mobile-platform-driver.ts index e3e53dfe..de830912 100644 --- a/src/platform/mobile-platform-driver.ts +++ b/src/platform/mobile-platform-driver.ts @@ -20,6 +20,7 @@ import type { Viewport } from './mobile-hierarchy.js'; import type { IPlatformDriver, HermesDefaults, + HermesEventClient, TargetType, ClickActionResult, ClickOptions, @@ -131,6 +132,9 @@ export class MobilePlatformDriver implements IPlatformDriver { // lazily), so releasing it in dispose() must tolerate it being absent. #hermesClient: HermesClient | undefined; + // Set once the session event sources use the persistent client. + #runtimeHeld = false; + // Session defaults kept from the launch (or the driver options). Undefined // leaves the choice to device-mcp: env `HERMES_METRO_PORT` / // `HERMES_APP_ID`, else the platform default. @@ -232,8 +236,8 @@ export class MobilePlatformDriver implements IPlatformDriver { * Returns the persistent client of the session target, creating it on first * use. Returns undefined when the cached client was built for another * target: the caller then uses the one-shot path, so the client is never - * retargeted. The client is created without `trackContexts` and without - * listeners, so it never sends `Runtime.enable`. + * retargeted. The client is created without `trackContexts`: only the + * session event sources (`mm logs`) send `Runtime.enable` on it. * * @param runtime - The loaded device-mcp module. * @param session - This driver's Hermes session. @@ -279,12 +283,34 @@ export class MobilePlatformDriver implements IPlatformDriver { session.setPinnedHermesDeviceId(logicalDeviceId); } + /** + * Returns the persistent client of the session target for the session + * event sources (`mm logs`), which hold `Runtime` enabled on it. From then + * on, `cdp` answers `Runtime.enable` without sending it and refuses + * `Runtime.disable` on that client. + * + * @returns The client, or undefined when the cached client is for another + * target. + */ + async getHermesEventClient(): Promise { + const runtime = await loadDeviceMcp(); + const session = await this.#getHermesSession(); + const client = this.#getHermesClient( + runtime, + session, + this.#resolveHermesTarget(session), + ); + this.#runtimeHeld = client !== undefined; + return client; + } + /** * Closes the persistent client, if one was created. Idempotent. */ #closeHermesClient(): void { const client = this.#hermesClient; this.#hermesClient = undefined; + this.#runtimeHeld = false; client?.close(); } @@ -896,6 +922,21 @@ export class MobilePlatformDriver implements IPlatformDriver { const client = usesSessionTarget ? this.#getHermesClient(runtime, session, sessionTarget) : undefined; + if (client && this.#runtimeHeld) { + // `Runtime.enable` again would replay old console messages as new. + if (input.method === 'Runtime.enable') { + return { ok: true, result: {} }; + } + if (input.method === 'Runtime.disable') { + return { + ok: false, + code: ErrorCodes.MM_CDP_BLOCKED, + message: + 'CDP method "Runtime.disable" is refused on the session Hermes ' + + 'connection: it would stop the console events `mm logs` records.', + }; + } + } const outcome = client ? await client.send(input.method, input.params, { diff --git a/src/platform/types.ts b/src/platform/types.ts index 3b15ab07..952d4b8b 100644 --- a/src/platform/types.ts +++ b/src/platform/types.ts @@ -1,3 +1,5 @@ +import type { HermesClient } from '@metamask/device-mcp'; + import type { ScreenshotResult, ExtensionState, @@ -135,6 +137,12 @@ export type HermesDefaults = { appId?: string; }; +/** The part of the session's persistent Hermes client that event sources use. */ +export type HermesEventClient = Pick< + HermesClient, + 'connect' | 'send' | 'on' | 'off' +>; + export type IPlatformDriver = { /** Release resources owned by this driver. Idempotent; does not shut down the device. */ dispose?(): Promise; @@ -318,5 +326,11 @@ export type IPlatformDriver = { */ setHermesDefaults?(defaults: HermesDefaults): void; + /** + * Mobile: the session's persistent Hermes client, for the session event + * sources (`mm logs`). Undefined when the client cannot be created. + */ + getHermesEventClient?(): Promise; + generateLocators?(): Promise; }; diff --git a/src/tools/events.ts b/src/tools/events.ts index efae4d2b..7fd5293c 100644 --- a/src/tools/events.ts +++ b/src/tools/events.ts @@ -1,6 +1,6 @@ import type { EventsInput, EventsResult } from './types'; import { createToolSuccess, requireActiveSession } from './utils.js'; -import { getSessionEvents } from '../events/session-events.js'; +import { getActiveSessionEvents } from '../events/session-events.js'; import type { ToolContext, ToolResponse } from '../types/http.js'; /** @@ -23,7 +23,7 @@ export async function eventsTool( return missingSession; } - const events = getSessionEvents(context.sessionManager.getContext()); + const events = getActiveSessionEvents(context.sessionManager); await events.ensureStarted(); const { buffer } = events; diff --git a/src/tools/launch.test.ts b/src/tools/launch.test.ts index 8f9c3856..f007091c 100644 --- a/src/tools/launch.test.ts +++ b/src/tools/launch.test.ts @@ -13,11 +13,11 @@ import { DriverLifecycle } from '../server/cleanup-session.js'; import type { SessionLaunchResult } from '../server/session-manager.js'; import { createMockSessionManager } from './test-utils/mock-factories.js'; import { ErrorCodes } from './types/errors.js'; -import { getSessionEvents } from '../events/session-events.js'; +import { getActiveSessionEvents } from '../events/session-events.js'; import type { ToolContext } from '../types/http.js'; vi.mock('../events/session-events.js', () => ({ - getSessionEvents: vi.fn(), + getActiveSessionEvents: vi.fn(), })); const ensureStarted = vi.fn(); @@ -41,51 +41,27 @@ describe('launchTool', () => { beforeEach(() => { vi.clearAllMocks(); ensureStarted.mockResolvedValue(undefined); - vi.mocked(getSessionEvents).mockReturnValue({ + vi.mocked(getActiveSessionEvents).mockReturnValue({ ensureStarted, - } as unknown as ReturnType); + } as unknown as ReturnType); }); describe('session events', () => { - it('starts the session events of a browser session', async () => { + it('starts the session events of the session', async () => { const context = createMockContext({ hasActive: false }); - const browserContext = {}; - vi.mocked(context.sessionManager.getContext).mockReturnValue( - browserContext as ReturnType, - ); const result = await launchTool({}, context); expect(result.ok).toBe(true); - expect(getSessionEvents).toHaveBeenCalledWith(browserContext); + expect(getActiveSessionEvents).toHaveBeenCalledWith( + context.sessionManager, + ); expect(ensureStarted).toHaveBeenCalledTimes(1); }); - it('does not start them on mobile', async () => { - const context = createMockContext({ hasActive: false }); - context.sessionManager.getPlatformDriver = () => - ({ getPlatform: () => 'ios' }) as unknown as NonNullable< - ReturnType< - NonNullable - > - >; - - await launchTool({ platform: 'ios' }, context); - - expect(getSessionEvents).not.toHaveBeenCalled(); - }); - - it('does not start them for a mobile launch input without a driver', async () => { - const context = createMockContext({ hasActive: false }); - - await launchTool({ platform: 'android' }, context); - - expect(getSessionEvents).not.toHaveBeenCalled(); - }); - it('never fails the launch when they fail to start', async () => { const context = createMockContext({ hasActive: false }); - vi.mocked(getSessionEvents).mockImplementation(() => { + vi.mocked(getActiveSessionEvents).mockImplementation(() => { throw new Error('no context'); }); diff --git a/src/tools/launch.ts b/src/tools/launch.ts index 90c01186..4eeac15f 100644 --- a/src/tools/launch.ts +++ b/src/tools/launch.ts @@ -1,7 +1,7 @@ import type { LaunchInput, LaunchPrerequisite, LaunchResult } from './types'; import { ErrorCodes } from './types'; import { createToolError, createToolSuccess } from './utils.js'; -import { getSessionEvents } from '../events/session-events.js'; +import { getActiveSessionEvents } from '../events/session-events.js'; import { cleanupSession } from '../server/cleanup-session.js'; import type { ISessionManager, @@ -56,28 +56,17 @@ function applyHermesDefaults( } /** - * Starts the session event buffer of a browser session (`mm logs`, - * `mm network`), so it records from launch on. Best-effort: a failure never - * fails the launch, and the next `events`/`logs`/`network` call retries. + * Starts the session event buffer (`mm logs`, `mm network`), so it records + * from launch on. Best-effort: a failure never fails the launch, and the + * next `events`/`logs`/`network` call retries. * * @param context - The tool execution context. - * @param input - The launch input. */ -async function startSessionEvents( - context: ToolContext, - input: LaunchInput, -): Promise { +async function startSessionEvents(context: ToolContext): Promise { try { - const platform = - context.sessionManager.getPlatformDriver?.()?.getPlatform() ?? - input.platform ?? - 'browser'; - if (platform !== 'browser') { - return; - } // `ensureStarted` is bounded (5 s) and never rejects: it does not hold // the launch on a slow attach, and the sources keep starting. - await getSessionEvents(context.sessionManager.getContext()).ensureStarted(); + await getActiveSessionEvents(context.sessionManager).ensureStarted(); } catch (error) { debugWarn('launch.session-events', error); } @@ -134,7 +123,7 @@ export async function launchTool( }); const { metroPort, deviceId, ...launchResult } = result; applyHermesDefaults(sessionManager, input, { metroPort, deviceId }); - await startSessionEvents(context, input); + await startSessionEvents(context); const isProdMode = sessionManager.getEnvironmentMode() === 'prod'; return createToolSuccess({ diff --git a/src/tools/logs.test.ts b/src/tools/logs.test.ts index a6456013..3c2e261d 100644 --- a/src/tools/logs.test.ts +++ b/src/tools/logs.test.ts @@ -6,6 +6,7 @@ import { createMockSessionManager } from './test-utils/mock-factories.js'; import { ErrorCodes } from './types/errors.js'; import type { ConsoleRecord } from './types/events.js'; import { getSessionEvents } from '../events/session-events.js'; +import type { IPlatformDriver } from '../platform/types.js'; import type { ToolContext } from '../types/http.js'; vi.mock('../platform/cdp-manager.js', () => ({ @@ -154,3 +155,58 @@ describe('logsTool', () => { expect(events.config.consoleLevels).toStrictEqual(['error', 'warning']); }); }); + +describe('logsTool on mobile', () => { + it('reads the Hermes console records of the mobile session', async () => { + const client = { + connect: vi.fn().mockResolvedValue({ + ok: true, + target: { id: 'H1', logicalDeviceId: 'D', title: 'MetaMask' }, + }), + send: vi.fn().mockResolvedValue({ + ok: true, + result: { result: { value: 'installed' } }, + }), + on: vi.fn(), + off: vi.fn(), + }; + const sessionManager = createMockSessionManager({ hasActive: true }); + const driver = { + getPlatform: () => 'ios', + getHermesEventClient: async () => client, + } as unknown as IPlatformDriver; + sessionManager.getPlatformDriver = (): IPlatformDriver => driver; + const context = { sessionManager } as unknown as ToolContext; + + const marked = await logsTool({}, context); + const onConsole = client.on.mock.calls.find( + ([name]) => name === 'Runtime.consoleAPICalled', + )?.[1] as (event: { params: unknown }) => void; + onConsole({ + params: { + type: 'error', + args: [{ type: 'string', value: 'mm-p2-29 probe' }], + }, + }); + const mark = + marked.ok && 'cursor' in marked.result ? marked.result.cursor : -1; + const result = await logsTool({ cursor: mark, grep: 'p2-29' }, context); + + expect(result).toMatchObject({ + ok: true, + result: { + records: [ + { + target: { kind: 'hermes', id: 'H1', url: '' }, + level: 'error', + text: 'mm-p2-29 probe', + }, + ], + gap: false, + hasMore: false, + summary: { captureErrors: 0 }, + }, + }); + expect(sessionManager.getContext).not.toHaveBeenCalled(); + }); +}); diff --git a/src/tools/logs.ts b/src/tools/logs.ts index 9bdd0e34..d06dd7cb 100644 --- a/src/tools/logs.ts +++ b/src/tools/logs.ts @@ -9,7 +9,7 @@ import { DEFAULT_EVENT_READ_LIMIT, parseSince, } from '../events/read-options.js'; -import { getSessionEvents } from '../events/session-events.js'; +import { getActiveSessionEvents } from '../events/session-events.js'; import type { ToolContext, ToolResponse } from '../types/http.js'; /** Longest accepted `--grep` pattern, to bound regular-expression work. */ @@ -17,8 +17,8 @@ export const MAX_GREP_PATTERN_LENGTH = 256; /** * Reads console errors and uncaught exceptions of every page and the - * Extension service worker (`mm logs`), or changes the recorded levels - * (`mm logs configure`). + * Extension service worker, or of the app's Hermes runtime on mobile + * (`mm logs`), or changes the recorded levels (`mm logs configure`). * * @param input - Read options, or the `configure` action. * @param context - The tool execution context. @@ -33,7 +33,7 @@ export async function logsTool( return missingSession; } - const events = getSessionEvents(context.sessionManager.getContext()); + const events = getActiveSessionEvents(context.sessionManager); await events.ensureStarted(); if (input.action === 'configure') { diff --git a/src/tools/platform-gating.test.ts b/src/tools/platform-gating.test.ts index f832aa66..82b6fbc3 100644 --- a/src/tools/platform-gating.test.ts +++ b/src/tools/platform-gating.test.ts @@ -14,8 +14,6 @@ describe('isBrowserOnlyTool', () => { expect(isBrowserOnlyTool('wait_for_notification')).toBe(true); expect(isBrowserOnlyTool('clipboard')).toBe(true); expect(isBrowserOnlyTool('mock_network')).toBe(true); - expect(isBrowserOnlyTool('events')).toBe(true); - expect(isBrowserOnlyTool('logs')).toBe(true); expect(isBrowserOnlyTool('network')).toBe(true); expect(isBrowserOnlyTool('reload')).toBe(true); expect(isBrowserOnlyTool('build')).toBe(true); @@ -38,6 +36,8 @@ describe('isBrowserOnlyTool', () => { expect(isBrowserOnlyTool('list_testids')).toBe(false); expect(isBrowserOnlyTool('accessibility_snapshot')).toBe(false); expect(isBrowserOnlyTool('get_text')).toBe(false); + expect(isBrowserOnlyTool('events')).toBe(false); + expect(isBrowserOnlyTool('logs')).toBe(false); expect(isBrowserOnlyTool('cdp')).toBe(false); }); @@ -93,6 +93,17 @@ describe('checkPlatformGate', () => { expect(checkPlatformGate('navigate', undefined)).toBeUndefined(); }); + it.each(['events', 'logs'])('allows %s on mobile platforms', (tool) => { + expect(checkPlatformGate(tool, 'ios')).toBeUndefined(); + expect(checkPlatformGate(tool, 'android')).toBeUndefined(); + }); + + it('keeps network browser only', () => { + expect(checkPlatformGate('network', 'ios')).toMatchObject({ + code: 'MM_TOOL_NOT_SUPPORTED_ON_PLATFORM', + }); + }); + it('blocks browser-only tools on a mobile platform', () => { expect(checkPlatformGate('navigate', 'ios')).toStrictEqual({ code: 'MM_TOOL_NOT_SUPPORTED_ON_PLATFORM', diff --git a/src/tools/registry.test.ts b/src/tools/registry.test.ts index 6bed796e..d6db8bd5 100644 --- a/src/tools/registry.test.ts +++ b/src/tools/registry.test.ts @@ -134,8 +134,6 @@ describe('isBrowserOnlyTool', () => { 'wait_for_notification', 'clipboard', 'mock_network', - 'events', - 'logs', 'network', 'reload', 'build', @@ -156,6 +154,8 @@ describe('isBrowserOnlyTool', () => { 'get_text', 'cdp', 'hermes_targets', + 'events', + 'logs', ])('returns false for %s', (toolName) => { expect(isBrowserOnlyTool(toolName)).toBe(false); }); diff --git a/src/tools/registry.ts b/src/tools/registry.ts index e7d15572..90a28fa4 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -222,8 +222,6 @@ const BROWSER_ONLY_TOOLS = new Set([ 'wait_for_notification', 'clipboard', 'mock_network', - 'events', - 'logs', 'network', 'reload', 'build', diff --git a/src/tools/types/events.ts b/src/tools/types/events.ts index c2bc52f1..f87d7549 100644 --- a/src/tools/types/events.ts +++ b/src/tools/types/events.ts @@ -11,13 +11,16 @@ export type EventRecordTarget = { /** * `page` (tab, popup, side panel), `sw` (Extension service worker), * `offscreen` (MV3 offscreen document), `iframe` (an out-of-process iframe - * of the offscreen document, such as a snaps iframe), or `hermes` (mobile, - * later). + * of the offscreen document, such as a snaps iframe), or `hermes` (the + * app's Hermes JS runtime on mobile). */ kind: 'page' | 'sw' | 'offscreen' | 'iframe' | 'hermes'; - /** The CDP target ID. Chrome can reuse a service worker's ID after a restart. */ + /** + * The CDP target ID (mobile: Metro's Hermes target ID). Chrome can reuse a + * service worker's ID after a restart. + */ id: string; - /** The target URL (redacted). */ + /** The target URL (redacted). Empty for `hermes`. */ url: string; }; @@ -86,6 +89,8 @@ export type ConsoleRecord = EventRecordBase & { location?: string; /** An uncaught exception, not a console call. */ uncaught?: true; + /** Mobile: an uncaught exception React Native reported as fatal (the red box). */ + fatal?: true; }; /** What the session records. Changed by `configure`, from then on. */ From 496d5af8d93f7b45815d221b3af59f217081241f Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 4 Dec 2026 12:03:01 +0000 Subject: [PATCH 2/8] refactor: keep ConsoleSource unchanged for Hermes logs --- src/events/console-source.test.ts | 2 +- src/events/console-source.ts | 90 +++++++----------- src/events/hermes-console-source.ts | 138 ++++++++++++---------------- src/events/read-options.ts | 13 +-- 4 files changed, 97 insertions(+), 146 deletions(-) diff --git a/src/events/console-source.test.ts b/src/events/console-source.test.ts index 2360862b..2233f0f5 100644 --- a/src/events/console-source.test.ts +++ b/src/events/console-source.test.ts @@ -648,7 +648,7 @@ describe('ConsoleSource', () => { }); // Filtered out, but its replay key is remembered. emit(warning); - events.config = { consoleLevels: ['error', 'warning'], rpcErrors: false }; + events.config = { consoleLevels: ['error', 'warning'] }; // The same message again is a replay: not recorded. emit(warning); emit( diff --git a/src/events/console-source.ts b/src/events/console-source.ts index d8875d6b..23fec1f5 100644 --- a/src/events/console-source.ts +++ b/src/events/console-source.ts @@ -1,4 +1,3 @@ -import type { RecordSourceTarget } from './read-options.js'; import { toRecordTarget } from './read-options.js'; import { isSensitiveQueryParam, @@ -352,7 +351,7 @@ function formatLocation(frame: CallFrame | undefined): string | undefined { * @returns The record without its `seq`, and the CDP timestamp (epoch ms). */ export function toConsoleRecord( - event: ConsoleEvent, + event: CdpEvent, ): { record: Omit; timestamp?: number } | undefined { const target = toRecordTarget(event.target); if (event.method === 'Runtime.consoleAPICalled') { @@ -403,46 +402,56 @@ export function toConsoleRecord( return undefined; } -/** A console event and the target it came from. */ -export type ConsoleEvent = Omit & { - target: RecordSourceTarget; -}; - /** - * Appends console records to the session buffer, at the levels in the - * session config, and drops replays: messages from before the source - * started, and messages seen already (same target, time, level and text). + * Records console messages and uncaught exceptions of every page and the + * Extension service worker, at the levels in the session config. + * + * `Runtime.enable` replays the messages Chrome kept for a target. Replays + * are dropped: messages from before the source started, and messages seen + * already (same target, time, level and text). */ -export class ConsoleRecorder { +export class ConsoleSource implements SessionEventSource { readonly #remembered = new Set(); /** - * Records one message when it is not a replay and its level is recorded. + * @param manager - The session's CDP manager. + * @param events - The session's events. + * @returns The subscription. + */ + async start( + manager: CdpManager, + events: SessionEvents, + ): Promise { + const startedAt = Date.now(); + return manager.subscribe({ + events: CONSOLE_EVENTS, + onEvent: (event) => this.#onEvent(event, events, startedAt), + onError: events.reportError, + }); + } + + /** + * Records one event when it is not a replay and its level is recorded. * The replay key is remembered before the level filter, so widening the * levels later does not record the replayed messages again. * - * @param built - The record and its CDP timestamp, from - * {@link toConsoleRecord}. + * @param event - The CDP event. * @param events - The session's events. - * @param startedAt - When the source started, epoch ms. - * @returns The stored record, or undefined when it was not recorded. + * @param startedAt - When this source started, epoch ms. */ - add( - built: ReturnType, - events: Pick, - startedAt: number, - ): ConsoleRecord | undefined { + #onEvent(event: CdpEvent, events: SessionEvents, startedAt: number): void { + const built = toConsoleRecord(event); if (built === undefined) { - return undefined; + return; } const { record, timestamp } = built; if (timestamp !== undefined) { if (timestamp < startedAt) { - return undefined; + return; } const key = `${record.target.id}\u0000${timestamp}\u0000${record.level}\u0000${record.text}`; if (this.#remembered.has(key)) { - return undefined; + return; } this.#remembered.add(key); if (this.#remembered.size > MAX_REMEMBERED_MESSAGES) { @@ -451,37 +460,8 @@ export class ConsoleRecorder { } } if (!events.config.consoleLevels.includes(record.level)) { - return undefined; + return; } - return events.buffer.append('console', record); - } -} - -/** - * Records console messages and uncaught exceptions of every page and the - * Extension service worker, at the levels in the session config. - * - * `Runtime.enable` replays the messages Chrome kept for a target. Replays - * are dropped (see {@link ConsoleRecorder}). - */ -export class ConsoleSource implements SessionEventSource { - readonly #recorder = new ConsoleRecorder(); - - /** - * @param manager - The session's CDP manager. - * @param events - The session's events. - * @returns The subscription. - */ - async start( - manager: CdpManager, - events: SessionEvents, - ): Promise { - const startedAt = Date.now(); - return manager.subscribe({ - events: CONSOLE_EVENTS, - onEvent: (event) => - this.#recorder.add(toConsoleRecord(event), events, startedAt), - onError: events.reportError, - }); + events.buffer.append('console', record); } } diff --git a/src/events/hermes-console-source.ts b/src/events/hermes-console-source.ts index e004331f..9655e506 100644 --- a/src/events/hermes-console-source.ts +++ b/src/events/hermes-console-source.ts @@ -1,31 +1,22 @@ import { randomBytes } from 'node:crypto'; -import type { ConsoleEvent } from './console-source.js'; -import { ConsoleRecorder, toConsoleRecord } from './console-source.js'; -import type { RecordSourceTarget } from './read-options.js'; -import { redactText } from './redact.js'; +import { toConsoleRecord } from './console-source.js'; +import { MAX_RECORDED_TEXT_LENGTH, redactText } from './redact.js'; import type { SessionEventSource, SessionEvents } from './session-events.js'; -import type { CdpSubscription } from '../platform/cdp-manager.js'; +import type { + CdpEventTarget, + CdpSubscription, +} from '../platform/cdp-manager.js'; import type { HermesEventClient } from '../platform/types.js'; -import type { ConsoleRecord } from '../tools/types/events.js'; +import type { + ConsoleRecord, + EventRecordTarget, +} from '../tools/types/events.js'; -/** Timeout of each CDP call of the source. */ const HERMES_CALL_TIMEOUT_MS = 5_000; - -/** Pause between two attempts to install the uncaught-error hook. */ const HOOK_RETRY_MS = 500; - -/** - * How long the source tries to install the hook after a new JS context. The - * app's bundle must have run first: about 4 s on Android and 14 s on iOS dev - * builds. - */ const HOOK_INSTALL_TIMEOUT_MS = 60_000; - -/** How long an uncaught error and its console message are matched. */ const UNCAUGHT_JOIN_MS = 5_000; - -/** Recent records and reports kept for the match. */ const MAX_JOIN_ENTRIES = 20; /** @@ -34,22 +25,24 @@ const MAX_JOIN_ENTRIES = 20; */ const RELEASE_OBJECTS_EVERY = 200; -/** Longest error text the hook sends. */ -const MAX_HOOK_TEXT_LENGTH = 8_000; +const MAX_HOOK_TEXT_LENGTH = MAX_RECORDED_TEXT_LENGTH * 4; + +const PLACEHOLDER_TARGET: CdpEventTarget = { + kind: 'page', + targetId: '', + url: '', +}; /** * Builds the script that wraps the `ErrorUtils` global handler of the current * JS context. The wrapper sends `{ fatal, text }` of each error once to every - * binding listed in `globalThis.__mmLogsHook`, then calls the previous + * binding listed in `globalThis.__mmLogsHookV1`, then calls the previous * handler with the same `this` and arguments and returns its result, so the - * app's handling (red box, LogBox, crash) does not change. It reads nothing - * else and changes no other app state. When the app replaced the wrapper, the - * new handler is wrapped in turn. + * app's handling does not change. When the app replaced the wrapper, the new + * handler is wrapped in turn. * * @param bindingName - The binding of this session. - * @returns The script. It evaluates to `installed`, `present` (the wrapper - * is the global handler already; the binding is added) or `not-ready` (the - * app's bundle has not run yet). + * @returns The script, evaluating to `installed`, `present` or `not-ready`. */ export function hookScript(bindingName: string): string { return `(function () { @@ -58,10 +51,10 @@ export function hookScript(bindingName: string): string { if (typeof g.__r !== 'function' || !utils || typeof utils.getGlobalHandler !== 'function') return 'not-ready'; var current = utils.getGlobalHandler(); if (typeof current !== 'function') return 'not-ready'; - var state = g.__mmLogsHook; + var state = g.__mmLogsHookV1; if (!state) { state = { bindings: [], seen: new WeakSet() }; - g.__mmLogsHook = state; + g.__mmLogsHookV1 = state; } if (state.bindings.indexOf(${JSON.stringify(bindingName)}) < 0) state.bindings.push(${JSON.stringify(bindingName)}); if (current === state.hook) return 'present'; @@ -123,38 +116,22 @@ function parseHookPayload( } /** - * Records the console messages of the app's Hermes runtime (mobile), at the - * levels in the session config, through the session's persistent Hermes - * client. - * - * `Runtime.exceptionThrown` never fires on Hermes: an uncaught error only - * arrives as the `console.error` that React Native logs for it. To mark it - * `uncaught` (and `fatal`, when it shows the red box), the source installs an - * observe-only wrapper of the `ErrorUtils` global handler ({@link hookScript}) - * that reports through a binding of this session, again after each JS reload. - * - * `Runtime.enable` replays the messages Hermes kept before its response: - * those are dropped. + * Records console messages and uncaught errors of the app's Hermes runtime + * (mobile) through the session's persistent Hermes client. */ export class HermesConsoleSource implements SessionEventSource { - readonly #recorder = new ConsoleRecorder(); - readonly #bindingName = `__mmLogs_${randomBytes(6).toString('hex')}`; - /** `Runtime.enable` calls without a response yet. */ #enabling = 0; - /** Bumped to stop a running hook install. */ #hookGeneration = 0; #consoleEvents = 0; - #target: RecordSourceTarget = { kind: 'hermes', targetId: '', url: '' }; + #target: EventRecordTarget = { kind: 'hermes', id: '', url: '' }; - /** Recent error records, to mark the one an uncaught error logged. */ readonly #recentErrors: { record: ConsoleRecord; at: number }[] = []; - /** Recent uncaught errors recorded from the hook, to drop their console message. */ readonly #recentUncaught: { head: string; at: number }[] = []; /** @@ -255,13 +232,13 @@ export class HermesConsoleSource implements SessionEventSource, - t: Date.now(), - }; - const built = toConsoleRecord(event); - const now = Date.now(); - if (built?.record.level === 'error') { - const head = firstLine(built.record.text); + t: now, + }); + if (built === undefined) { + return; + } + const record = { ...built.record, target: this.#target }; + if (record.level === 'error') { + const head = firstLine(record.text); const index = this.#recentUncaught.findIndex( (entry) => entry.head === head && now - entry.at <= UNCAUGHT_JOIN_MS, ); @@ -399,10 +379,11 @@ export class HermesConsoleSource implements SessionEventSource('console', record); + if (stored.level === 'error') { this.#recentErrors.push({ record: stored, at: now }); this.#recentErrors.splice( 0, @@ -412,8 +393,7 @@ export class HermesConsoleSource implements SessionEventSource('console', { + t: now, + target: this.#target, + level: 'error', + text, + uncaught: true, + ...(report.fatal ? { fatal: true as const } : {}), + }); + } this.#recentUncaught.push({ head, at: now }); this.#recentUncaught.splice( 0, diff --git a/src/events/read-options.ts b/src/events/read-options.ts index 4444bc08..552a3d80 100644 --- a/src/events/read-options.ts +++ b/src/events/read-options.ts @@ -31,18 +31,13 @@ export function parseSince( return Number.isNaN(parsed) ? undefined : parsed; } -/** The target of an event: a browser CDP target, or the mobile Hermes runtime. */ -export type RecordSourceTarget = Omit & { - kind: EventRecordTarget['kind']; -}; - /** - * Converts the target of an event to the target of a record, with its URL - * redacted. + * Converts the target of a CDP event to the target of a record, with its + * URL redacted. * - * @param target - The event target. + * @param target - The CDP event target. * @returns The record target. */ -export function toRecordTarget(target: RecordSourceTarget): EventRecordTarget { +export function toRecordTarget(target: CdpEventTarget): EventRecordTarget { return { kind: target.kind, id: target.targetId, url: redactUrl(target.url) }; } From 2b91971f52372db8ad5335dc1e5a7d607234ca7e Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 4 Dec 2026 12:04:36 +0000 Subject: [PATCH 3/8] refactor: enable Hermes logs on connect instead of retrying failed sources --- src/events/hermes-console-source.test.ts | 124 ++++++++++++++++++----- src/events/hermes-console-source.ts | 33 ++++-- src/events/session-events.test.ts | 48 --------- src/events/session-events.ts | 53 +++------- 4 files changed, 135 insertions(+), 123 deletions(-) diff --git a/src/events/hermes-console-source.test.ts b/src/events/hermes-console-source.test.ts index 128264fe..c1e95360 100644 --- a/src/events/hermes-console-source.test.ts +++ b/src/events/hermes-console-source.test.ts @@ -625,43 +625,115 @@ describe('HermesConsoleSource', () => { }); }); - it('fails to start when it cannot connect or enable, and removes its listeners', async () => { + it('does not enable twice when start connect emits contextCreated', async () => { const client = createClient(); + client.connect.mockImplementationOnce(async () => { + const target = { id: 'T1', logicalDeviceId: 'D1', title: 'MetaMask' }; + client.emit('contextCreated', { + reason: 'connect', + reconnected: false, + target, + }); + return { ok: true, target }; + }); const events = new SessionEvents(() => client, []); + await new HermesConsoleSource().start(client, events); + await flush(); + + expect( + client.send.mock.calls.filter(([method]) => method === 'Runtime.enable'), + ).toHaveLength(1); + }); + + it('enables once a client that failed to connect on start connects later', async () => { + const client = createClient(); client.connect.mockResolvedValueOnce({ ok: false, code: 'HERMES_TARGET_NOT_FOUND', - message: 'no target', + message: 'not ready', }); - await expect( - new HermesConsoleSource().start(client, events), - ).rejects.toThrowError( - 'Hermes connect failed: [HERMES_TARGET_NOT_FOUND] no target', - ); - expect(client.listenerCount()).toBe(0); + const events = new SessionEvents(() => client, []); + await new HermesConsoleSource().start(client, events); - client.send.mockImplementation(async (method: string) => - method === 'Runtime.enable' - ? { ok: false, code: 'HERMES_CDP_FAILED', message: 'enable' } - : { ok: true, result: {} }, - ); - await expect( - new HermesConsoleSource().start(client, events), - ).rejects.toThrowError('Runtime.enable failed: [HERMES_CDP_FAILED] enable'); + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 1, + lastCaptureError: + 'Hermes connect failed: [HERMES_TARGET_NOT_FOUND] not ready', + }); + expect(client.send).not.toHaveBeenCalled(); - client.send.mockResolvedValue({ - ok: false, - code: 'HERMES_CDP_FAILED', - message: 'binding', + client.emit('contextCreated', { + reason: 'connect', + reconnected: false, + target: { id: 'T2', logicalDeviceId: 'D1', title: 'MetaMask' }, }); - await expect( - new HermesConsoleSource().start(client, events), - ).rejects.toThrowError( - 'Runtime.addBinding failed: [HERMES_CDP_FAILED] binding', - ); - expect(client.listenerCount()).toBe(0); + await flush(); + client.emit('Runtime.consoleAPICalled', consoleEvent('error', 'ready')); + + expect(client.send.mock.calls.map(([method]) => method)).toStrictEqual([ + 'Runtime.addBinding', + 'Runtime.enable', + 'Runtime.evaluate', + ]); + expect(readAll(events)).toStrictEqual([ + expect.objectContaining({ + text: 'ready', + target: { kind: 'hermes', id: 'T2', url: '' }, + }), + ]); }); + it.each([ + { + label: 'connect', + setup: (client: FakeClient): void => { + client.connect.mockResolvedValueOnce({ + ok: false, + code: 'HERMES_TARGET_NOT_FOUND', + message: 'no target', + }); + }, + expected: 'Hermes connect failed: [HERMES_TARGET_NOT_FOUND] no target', + }, + { + label: 'Runtime.enable', + setup: (client: FakeClient): void => { + client.send.mockImplementation(async (method: string) => + method === 'Runtime.enable' + ? { ok: false, code: 'HERMES_CDP_FAILED', message: 'enable' } + : { ok: true, result: {} }, + ); + }, + expected: 'Runtime.enable failed: [HERMES_CDP_FAILED] enable', + }, + { + label: 'Runtime.addBinding', + setup: (client: FakeClient): void => { + client.send.mockResolvedValue({ + ok: false, + code: 'HERMES_CDP_FAILED', + message: 'binding', + }); + }, + expected: 'Runtime.addBinding failed: [HERMES_CDP_FAILED] binding', + }, + ])( + 'records a $label failure on start without throwing and keeps listening', + async ({ setup, expected }) => { + const client = createClient(); + setup(client); + const events = new SessionEvents(() => client, []); + + await new HermesConsoleSource().start(client, events); + + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 1, + lastCaptureError: expected, + }); + expect(client.listenerCount()).toBeGreaterThan(0); + }, + ); + it('stops recording after unsubscribe', async () => { const { client, events, unsubscribe } = await startSource(); diff --git a/src/events/hermes-console-source.ts b/src/events/hermes-console-source.ts index 9655e506..bf09874c 100644 --- a/src/events/hermes-console-source.ts +++ b/src/events/hermes-console-source.ts @@ -144,6 +144,7 @@ export class HermesConsoleSource implements SessionEventSource, ): Promise { let active = true; + let connecting = true; const onConsole = (event: { params: unknown }): void => { if (active) { this.#onConsole(client, events, event.params); @@ -165,7 +166,11 @@ export class HermesConsoleSource implements SessionEventSource { - if (active && event.reason === 'reconnect') { + if ( + active && + !connecting && + (event.reason === 'connect' || event.reason === 'reconnect') + ) { this.#setTarget(event.target); this.#enable(client, events).catch(events.reportError); } @@ -213,21 +218,27 @@ export class HermesConsoleSource implements SessionEventSource { expect(source.start).toHaveBeenCalledTimes(2); }); - it('starts a failed source again on the next call, without restarting the others', async () => { - getCdpManagerMock.mockReturnValue({ id: 1 } as never); - const failing = { - start: vi - .fn() - .mockRejectedValueOnce(new Error('not yet')) - .mockResolvedValue({ unsubscribe: vi.fn() }), - }; - const { source, unsubscribe } = createSource(); - const events = new SessionEvents(connect, [failing, source]); - - await events.ensureStarted(); - await events.ensureStarted(); - await events.ensureStarted(); - - expect(failing.start).toHaveBeenCalledTimes(2); - expect(source.start).toHaveBeenCalledTimes(1); - expect(unsubscribe).not.toHaveBeenCalled(); - }); - - it('lets concurrent calls wait for the same retry of a failed source', async () => { - getCdpManagerMock.mockReturnValue({ id: 1 } as never); - let finishRetry: (value: { - unsubscribe: () => Promise; - }) => void = () => undefined; - const failing = { - start: vi - .fn() - .mockRejectedValueOnce(new Error('not yet')) - .mockImplementationOnce( - async () => - new Promise((resolve) => { - finishRetry = resolve; - }), - ), - }; - const events = new SessionEvents(connect, [failing]); - await events.ensureStarted(); - - const first = events.ensureStarted(); - const second = events.ensureStarted(); - await vi.waitFor(() => expect(failing.start).toHaveBeenCalledTimes(2)); - finishRetry({ unsubscribe: vi.fn() }); - await Promise.all([first, second]); - - expect(failing.start).toHaveBeenCalledTimes(2); - }); - it('records a connection that cannot be made, and tries again later', async () => { const { source } = createSource(); const failingConnect = vi diff --git a/src/events/session-events.ts b/src/events/session-events.ts index 1c0969c2..1be3839b 100644 --- a/src/events/session-events.ts +++ b/src/events/session-events.ts @@ -70,9 +70,6 @@ export class SessionEvents { #subscriptions: CdpSubscription[] = []; - /** Sources of the current connection that have not started. */ - #failed: SessionEventSource[] = []; - /** * @param connect - Returns the session's current connection. * @param sources - The sources that fill the buffer. @@ -131,8 +128,7 @@ export class SessionEvents { /** * Starts every source once per connection, or returns the start in - * progress. A source that failed to start is started again by the next - * call. + * progress. * * @returns Settles when the sources started. Never rejects. */ @@ -145,43 +141,25 @@ export class SessionEvents { return; } if (connection === this.#connection) { - const current = this.#starting; - await current; - if (this.#starting !== current) { - await this.#starting; - return; - } - if (this.#failed.length === 0 || this.#connection !== connection) { - return; - } - } else { - this.#connection = connection; - this.#failed = this.#sources; + await this.#starting; + return; } + this.#connection = connection; const previous = this.#subscriptions; - const sources = this.#failed; - const restart = sources === this.#sources; - this.#failed = []; - if (restart) { - this.#subscriptions = []; - } + this.#subscriptions = []; const starting = (async (): Promise => { - if (restart) { - await Promise.all( - previous.map(async (subscription) => - subscription.unsubscribe().catch(() => undefined), - ), - ); - } + await Promise.all( + previous.map(async (subscription) => + subscription.unsubscribe().catch(() => undefined), + ), + ); const results = await Promise.allSettled( - sources.map(async (source) => source.start(connection, this)), + this.#sources.map(async (source) => source.start(connection, this)), ); - const failed: SessionEventSource[] = []; - const started = results.flatMap((result, index) => { + const started = results.flatMap((result) => { if (result.status === 'fulfilled') { return [result.value]; } - failed.push(sources[index]); this.reportError(result.reason); return []; }); @@ -195,8 +173,7 @@ export class SessionEvents { ); return; } - this.#subscriptions.push(...started); - this.#failed.push(...failed); + this.#subscriptions = started; })(); this.#starting = starting; await starting; @@ -253,8 +230,8 @@ export function getActiveSessionEvents( if (client === undefined) { throw new Error('No Hermes client for the session target'); } - // Reconnects a client whose reconnect loop gave up; the source - // enables again on its `contextCreated` (`reconnect`). + // Connects a client that was not ready or gave up reconnecting; the + // source enables on `contextCreated`. client .connect({ timeoutMs: SESSION_EVENTS_START_WAIT_MS }) .catch(() => undefined); From ede949c9b81427b3fae7567e740cfccc2e1cb0be Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 4 Dec 2026 12:05:39 +0000 Subject: [PATCH 4/8] fix: mark the newest same-head error as uncaught --- src/events/hermes-console-source.test.ts | 30 ++++++++++ src/events/hermes-console-source.ts | 73 +++++++++++++----------- 2 files changed, 70 insertions(+), 33 deletions(-) diff --git a/src/events/hermes-console-source.test.ts b/src/events/hermes-console-source.test.ts index c1e95360..a8b732e2 100644 --- a/src/events/hermes-console-source.test.ts +++ b/src/events/hermes-console-source.test.ts @@ -417,6 +417,36 @@ describe('HermesConsoleSource', () => { ]); }); + it('marks the newest console error when two share a first line', async () => { + const { client, events, binding } = await startSource(); + + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent('error', 'Error: same\n at caught (:1:1)'), + ); + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent('error', 'Error: same\n at uncaught (:2:2)'), + ); + client.emit( + 'Runtime.bindingCalled', + bindingEvent(binding, { + fatal: true, + text: 'Error: same\n at uncaught (:2:2)', + }), + ); + + const [caught, uncaught] = readAll(events); + expect(caught?.uncaught).toBeUndefined(); + expect(caught?.fatal).toBeUndefined(); + expect(uncaught).toMatchObject({ + seq: 2, + text: 'Error: same\n at uncaught (:2:2)', + uncaught: true, + fatal: true, + }); + }); + it('records the hook report first and drops the console error that follows', async () => { const { client, events, binding } = await startSource(); diff --git a/src/events/hermes-console-source.ts b/src/events/hermes-console-source.ts index bf09874c..31d1066e 100644 --- a/src/events/hermes-console-source.ts +++ b/src/events/hermes-console-source.ts @@ -130,9 +130,7 @@ export class HermesConsoleSource implements SessionEventSource entry.head === head && now - entry.at <= UNCAUGHT_JOIN_MS, - ); - if (index !== -1) { - this.#recentUncaught.splice(index, 1); - return; - } + const head = record.level === 'error' ? firstLine(record.text) : undefined; + if (head !== undefined && this.#takeRecent(head, now, false)) { + return; } if (!events.config.consoleLevels.includes(record.level)) { return; } const stored = events.buffer.append('console', record); - if (stored.level === 'error') { - this.#recentErrors.push({ record: stored, at: now }); - this.#recentErrors.splice( - 0, - this.#recentErrors.length - MAX_JOIN_ENTRIES, - ); + if (head !== undefined) { + this.#recent.push({ head, at: now, record: stored }); + this.#recent.splice(0, this.#recent.length - MAX_JOIN_ENTRIES); } } @@ -420,17 +409,11 @@ export class HermesConsoleSource implements SessionEventSource - entry.record.uncaught === undefined && - firstLine(entry.record.text) === head && - now - entry.at <= UNCAUGHT_JOIN_MS, - ); - if (index !== -1) { - const [{ record }] = this.#recentErrors.splice(index, 1); - record.uncaught = true; + const match = this.#takeRecent(head, now, true); + if (match?.record) { + match.record.uncaught = true; if (report.fatal) { - record.fatal = true; + match.record.fatal = true; } return; } @@ -444,10 +427,34 @@ export class HermesConsoleSource implements SessionEventSource= 0; index -= 1) { + const entry = this.#recent[index]; + if ( + entry.head === head && + now - entry.at <= UNCAUGHT_JOIN_MS && + (entry.record !== undefined) === hasRecord + ) { + this.#recent.splice(index, 1); + return entry; + } + } + return undefined; } } From a30f008aa2dbe0e2581038f9446fcf0529ae6a4b Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 4 Dec 2026 12:28:25 +0000 Subject: [PATCH 5/8] refactor: drop the Runtime.enable short-circuit --- .../mobile-platform-driver.hermes.test.ts | 33 +++-------------- src/platform/mobile-platform-driver.ts | 36 ++++++------------- 2 files changed, 15 insertions(+), 54 deletions(-) diff --git a/src/platform/mobile-platform-driver.hermes.test.ts b/src/platform/mobile-platform-driver.hermes.test.ts index 0210e307..d39a980c 100644 --- a/src/platform/mobile-platform-driver.hermes.test.ts +++ b/src/platform/mobile-platform-driver.hermes.test.ts @@ -808,38 +808,21 @@ describe('MobilePlatformDriver persistent Hermes client', () => { expect(mocks.HermesClient).toHaveBeenCalledTimes(1); }); - it('gives the session client to the event sources', async () => { + it('shares the session client with event sources and refuses Runtime.disable on it', async () => { const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { metroPort: 8085, }); const client = await driver.getHermesEventClient(); - await driver.cdp({ method: 'Runtime.evaluate', timeoutMs: 30_000 }); - expect(client).toBe(clients[0]); - expect(mocks.HermesClient).toHaveBeenCalledTimes(1); - expect(clients[0].send).toHaveBeenCalledTimes(1); - }); - - it('keeps Runtime enabled for the event sources on the session client', async () => { - const driver = new MobilePlatformDriver(createBackend(), 'io.metamask', { - metroPort: 8085, - }); - expect( - await driver.cdp({ method: 'Runtime.enable', timeoutMs: 30_000 }), - ).toStrictEqual({ ok: true, result: { value: 2 } }); - clients[0].send.mockClear(); - - await driver.getHermesEventClient(); - - expect( - await driver.cdp({ method: 'Runtime.enable', timeoutMs: 30_000 }), - ).toStrictEqual({ ok: true, result: {} }); expect( await driver.cdp({ method: 'Runtime.disable', timeoutMs: 30_000 }), ).toMatchObject({ ok: false, code: 'MM_CDP_BLOCKED' }); expect(clients[0].send).not.toHaveBeenCalled(); + await driver.cdp({ method: 'Runtime.enable', timeoutMs: 30_000 }); + expect(clients[0].send).toHaveBeenCalledTimes(1); + mocks.runHermesCdp.mockResolvedValue({ ok: true, result: {} }); await driver.cdp({ method: 'Runtime.disable', @@ -847,14 +830,6 @@ describe('MobilePlatformDriver persistent Hermes client', () => { metroPort: 8087, }); expect(mocks.runHermesCdp).toHaveBeenCalledTimes(1); - - driver.setHermesDefaults({ metroPort: 8086 }); - await driver.cdp({ method: 'Runtime.disable', timeoutMs: 30_000 }); - expect(clients[1].send).toHaveBeenCalledWith( - 'Runtime.disable', - undefined, - expect.anything(), - ); }); it('closes the client on dispose', async () => { diff --git a/src/platform/mobile-platform-driver.ts b/src/platform/mobile-platform-driver.ts index de830912..2e50d49c 100644 --- a/src/platform/mobile-platform-driver.ts +++ b/src/platform/mobile-platform-driver.ts @@ -132,9 +132,6 @@ export class MobilePlatformDriver implements IPlatformDriver { // lazily), so releasing it in dispose() must tolerate it being absent. #hermesClient: HermesClient | undefined; - // Set once the session event sources use the persistent client. - #runtimeHeld = false; - // Session defaults kept from the launch (or the driver options). Undefined // leaves the choice to device-mcp: env `HERMES_METRO_PORT` / // `HERMES_APP_ID`, else the platform default. @@ -284,10 +281,8 @@ export class MobilePlatformDriver implements IPlatformDriver { } /** - * Returns the persistent client of the session target for the session - * event sources (`mm logs`), which hold `Runtime` enabled on it. From then - * on, `cdp` answers `Runtime.enable` without sending it and refuses - * `Runtime.disable` on that client. + * Returns the persistent client of the session target for session event + * sources (`mm logs`). * * @returns The client, or undefined when the cached client is for another * target. @@ -295,13 +290,11 @@ export class MobilePlatformDriver implements IPlatformDriver { async getHermesEventClient(): Promise { const runtime = await loadDeviceMcp(); const session = await this.#getHermesSession(); - const client = this.#getHermesClient( + return this.#getHermesClient( runtime, session, this.#resolveHermesTarget(session), ); - this.#runtimeHeld = client !== undefined; - return client; } /** @@ -310,7 +303,6 @@ export class MobilePlatformDriver implements IPlatformDriver { #closeHermesClient(): void { const client = this.#hermesClient; this.#hermesClient = undefined; - this.#runtimeHeld = false; client?.close(); } @@ -922,20 +914,14 @@ export class MobilePlatformDriver implements IPlatformDriver { const client = usesSessionTarget ? this.#getHermesClient(runtime, session, sessionTarget) : undefined; - if (client && this.#runtimeHeld) { - // `Runtime.enable` again would replay old console messages as new. - if (input.method === 'Runtime.enable') { - return { ok: true, result: {} }; - } - if (input.method === 'Runtime.disable') { - return { - ok: false, - code: ErrorCodes.MM_CDP_BLOCKED, - message: - 'CDP method "Runtime.disable" is refused on the session Hermes ' + - 'connection: it would stop the console events `mm logs` records.', - }; - } + if (client && input.method === 'Runtime.disable') { + return { + ok: false, + code: ErrorCodes.MM_CDP_BLOCKED, + message: + 'CDP method "Runtime.disable" is refused on the session Hermes ' + + 'connection: it would stop the console events `mm logs` records.', + }; } const outcome = client From 3ad7a08782140c03d9bb4cc7e59d8f44b6953044 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 4 Dec 2026 12:28:25 +0000 Subject: [PATCH 6/8] refactor: trim Hermes logs tests, comments and docs --- README.md | 2 +- SKILL.md | 22 +-- src/events/hermes-console-source.test.ts | 216 ++++++----------------- src/events/hermes-console-source.ts | 28 ++- src/events/session-events.test.ts | 12 -- src/tools/logs.test.ts | 54 ++---- src/tools/types/events.ts | 2 +- 7 files changed, 86 insertions(+), 250 deletions(-) diff --git a/README.md b/README.md index 10178d3e..74499811 100644 --- a/README.md +++ b/README.md @@ -441,7 +441,7 @@ The daemon routes `POST /tool/:name` requests through the registry, applies Zod | **Advanced** | | | `mock_network` | Adds, clears, lists, and inspects targeted Playwright network mocks on the active browser context. Unmatched same-origin requests are continued unchanged. A rule with `record` and no `response` records the real request and forwards it unchanged. Rules can opt in to record request bodies and headers (redacted). | | `events` | Bookmarks or clears the session event buffer that `mm logs` and `mm network` read: `mark` returns the current cursor (one cursor for both) and `summary.startedAt`; `clear` empties it without resetting the cursor. The buffer starts with the session and keeps the newest 1000 console and 2000 network records. | -| `logs` | Read-only. Console errors and uncaught exceptions of every page and the Extension service worker, or of the app's Hermes runtime on mobile (`target.kind: "hermes"`; uncaught errors come from an observe-only wrapper of the `ErrorUtils` global handler, marked `uncaught` and `fatal` for the red box, and it is installed again after a JS reload; native crashes are not captured), from the session event buffer: `{ records, cursor, hasMore, gap, summary }`, oldest first, with `cursor`/`since`/`limit`/`grep`. Records `error` only by default; `configure` widens the levels for the session (`warn` is accepted as `warning`). Object and array arguments are rendered from their CDP preview (a sensitive property name prints `[REDACTED]`), and a leading format string fills its `%s`/`%d`/`%o` specifiers. URLs in the text and the values of sensitive object fields (`privateKey`, `mnemonic`, `password`, …) are redacted; plain string contents are not scanned (JWTs and `Bearer` tokens excepted). Text is cut at 2000 characters. | +| `logs` | Read-only. Console errors and uncaught exceptions of every page and the Extension service worker, or the app's Hermes runtime on mobile (see SKILL.md), from the session event buffer: `{ records, cursor, hasMore, gap, summary }`, oldest first, with `cursor`/`since`/`limit`/`grep`. Records `error` only by default; `configure` widens the levels for the session (`warn` is accepted as `warning`). Object and array arguments are rendered from their CDP preview (a sensitive property name prints `[REDACTED]`), and a leading format string fills its `%s`/`%d`/`%o` specifiers. URLs in the text and the values of sensitive object fields (`privateKey`, `mnemonic`, `password`, …) are redacted; plain string contents are not scanned (JWTs and `Bearer` tokens excepted). Text is cut at 2000 characters. | | `network` | Read-only, passive. HTTP(S) requests of every page and the Extension service worker, from the session event buffer: one record per request with method, redacted URL, type, status, duration (`ms`), `failure`, JSON-RPC `rpcMethods` and, after `configure` with `rpcErrors`, the JSON-RPC `rpcError`. Filters: `cursor`, `since`, `limit`, `url` (glob or text), `errors`, `settled`; a filtered or `settled` read returns settled requests only, ordered by `settledSeq`. Never routes or changes a request; no bodies are stored. Browser only. | | `cdp` | Sends a raw Chrome DevTools Protocol command, dispatched through the active platform driver. **Browser:** targets the active page (`target: "page"`, default) or the Extension service worker (`target: "sw"`) on a persistent CDP session shared across calls, so enabled domains and listeners survive; `fresh: true` uses a one-shot session. Full Runtime/DOM/Network/Page surface; destructive methods (`Browser.close`, `Target.closeTarget`, etc.) are blocked. **Mobile (iOS/Android):** targets the app's React Native Hermes JS runtime via Metro's inspector proxy (delegates to `@metamask/device-mcp`, needs a DEBUG build with Metro running); only the JS-engine subset exists (`Runtime`, `Debugger`, `Log`, `HeapProfiler` — no DOM/Page/Network) and `Runtime.terminateExecution` / `Inspector.detached` are blocked. Optional `metroPort` / `appId` are mobile-only (ignored on browser). Categorized as `cdp`: no observation is collected and refs are not refreshed, so run `describe_screen` after a call that changes state. See [Browser vs Mobile CDP](#browser-vs-mobile-hermes-cdp). | | **Hermes (mobile only)** | | diff --git a/SKILL.md b/SKILL.md index 2e872f9c..68b44fc3 100644 --- a/SKILL.md +++ b/SKILL.md @@ -812,24 +812,12 @@ Only `error` (including `console.assert` and uncaught exceptions) is recorded by #### `mm logs` on mobile -On iOS and Android, `mm logs` records the `console.*` calls of the app's Hermes JS runtime (dev builds with Metro), through the session's Hermes connection, from `mm launch` on. The output shape, levels, limits, `--grep` and redaction are the same as on the browser. Records have `target: { kind: "hermes", id: , url: "" }`. +On iOS and Android dev builds (with Metro), `mm logs` records `console.*` calls of the app's Hermes runtime from `mm launch` on, using the same output shape, levels, limits, `--grep` and redaction as the browser, with `target: { kind: "hermes", id: , url: "" }`. -```json -{ - "seq": 45, - "t": 1796304265075, - "target": { "kind": "hermes", "id": "9d2d6b8a…-1", "url": "" }, - "level": "error", - "text": "Error: mm-p2-29 uncaught\n at anonymous (:1:178)", - "uncaught": true, - "fatal": true -} -``` - -- **Uncaught errors:** the daemon wraps the app's `ErrorUtils` global handler. The wrapper only reports the error to the daemon and then calls the app's handler unchanged, so the red box / LogBox and the app's error handling still happen. The record of an uncaught error has `"uncaught": true`, and `"fatal": true` when React Native reported it as fatal (the full-screen "Uncaught Error" LogBox in dev). An uncaught error is one record, not two (React Native also logs it with `console.error`). A dev LogBox can be closed with its **Dismiss** button; `mm logs` does not close it. -- **Reloads:** a JS reload (Metro reload, `DevSettings.reload()`) keeps recording. The daemon installs the wrapper again when the new bundle has run (about 4 s after the reload on Android, about 14 s on iOS dev builds). Until then, an uncaught error is still recorded from its `console.error`, without `uncaught`. A reload adds no record and no field. When Metro drops the connection, the daemon reconnects and counts it in `summary.captureErrors`; messages sent while it was down are missing. -- **Not captured:** native crashes and native logs (use `mm device-logs`); console messages from before the session connected (Hermes sends them again on connect, and they are dropped); messages sent while the connection was down; release builds (no Metro, no Hermes inspector). Levels other than `error` are recorded only after `mm logs configure --levels`, as on the browser. -- The session keeps `Runtime` enabled on its Hermes connection: `mm cdp Runtime.enable` succeeds without sending anything, and `mm cdp Runtime.disable` is refused with `MM_CDP_BLOCKED`. `t` is the app's console time (epoch ms), or the daemon time for an uncaught error the console did not log. +- **Uncaught errors:** an observe-only wrapper of `ErrorUtils` reports each error to the daemon and calls the app's handler unchanged, producing one record with `"uncaught": true` (and `"fatal": true` when React Native passed `isFatal`; the app's own handler may still swallow the error, as MetaMask does for Ledger and Keystone errors, so `fatal` does not always mean a red box). +- **Reloads and reconnects:** recording continues across JS reloads (`DevSettings.reload()`, Metro reload) with no reload marker, and the wrapper reinstalls once the new bundle runs (errors before then still appear from `console.error` without `uncaught`). Lost Metro connections reconnect and increment `summary.captureErrors`. +- **Overhead and `Runtime`:** while a session is open, the app serializes every `console.*` call with previews, like an open DevTools; `mm cdp Runtime.disable` on the session connection is refused with `MM_CDP_BLOCKED`. +- **Not captured:** native crashes and native logs (use `mm device-logs`), pre-connect Hermes replays, messages sent while disconnected, and release builds without Metro. #### `mm network [--cursor | --since ] [--limit ] [--url ] [--errors] [--settled]` diff --git a/src/events/hermes-console-source.test.ts b/src/events/hermes-console-source.test.ts index a8b732e2..5bb95bdd 100644 --- a/src/events/hermes-console-source.test.ts +++ b/src/events/hermes-console-source.test.ts @@ -21,26 +21,25 @@ type FakeClient = HermesEventClient & { listenerCount: () => number; send: ReturnType; connect: ReturnType; - /** Answers of `Runtime.evaluate`, in order; the last one repeats. */ evaluations: SendResult[]; - /** Called while `Runtime.enable` waits for its response. */ onEnable?: () => void; }; -/** - * Creates a fake persistent Hermes client. - * - * @returns The client. - */ function createClient(): FakeClient { const listeners = new Map void>>(); const client = { evaluations: [ { ok: true, result: { result: { value: 'installed' } } }, ] as SendResult[], - connect: vi.fn().mockResolvedValue({ - ok: true, - target: { id: 'T1', logicalDeviceId: 'D1', title: 'MetaMask' }, + onEnable: undefined as (() => void) | undefined, + connect: vi.fn(async () => { + const target = { id: 'T1', logicalDeviceId: 'D1', title: 'MetaMask' }; + client.emit('contextCreated', { + reason: 'connect', + reconnected: false, + target, + }); + return { ok: true, target }; }), send: vi.fn(async (method: string): Promise => { if (method === 'Runtime.enable') { @@ -75,11 +74,6 @@ function createClient(): FakeClient { return client as unknown as FakeClient; } -/** - * Starts a Hermes console source on a fake client. - * - * @returns The client, session events and the binding name of the source. - */ async function startSource(): Promise<{ client: FakeClient; events: SessionEvents; @@ -99,14 +93,6 @@ async function startSource(): Promise<{ return { client, events, source, binding, unsubscribe }; } -/** - * Builds the parameters of a Hermes `Runtime.consoleAPICalled` event. - * - * @param type - The console call type. - * @param text - The string argument. - * @param extra - More parameters. - * @returns The event. - */ function consoleEvent( type: string, text: string, @@ -133,13 +119,6 @@ function consoleEvent( }; } -/** - * Builds a `Runtime.bindingCalled` event of the hook. - * - * @param name - The binding name. - * @param report - The hook report. - * @returns The event. - */ function bindingEvent( name: string, report: unknown, @@ -150,20 +129,11 @@ function bindingEvent( }; } -/** - * Reads every console record. - * - * @param events - The session events. - * @returns The records. - */ function readAll(events: SessionEvents): ConsoleRecord[] { return events.buffer.read({ kind: 'console', limit: 100 }) .records; } -/** - * Lets pending promise callbacks run. - */ async function flush(): Promise { for (let index = 0; index < 5; index++) { await Promise.resolve(); @@ -171,12 +141,6 @@ async function flush(): Promise { } describe('hookScript', () => { - /** - * Builds a fake React Native global with `ErrorUtils` and a binding. - * - * @param bindings - Binding names to define. - * @returns The global, the original handler and the binding calls. - */ function createGlobal(bindings: string[]): { sandbox: Record; original: ReturnType; @@ -204,13 +168,6 @@ describe('hookScript', () => { return { sandbox, original, calls }; } - /** - * Calls the current global handler of a fake global. - * - * @param sandbox - The fake global. - * @param args - The handler arguments. - * @returns What the handler returned. - */ function callHandler( sandbox: Record, ...args: unknown[] @@ -326,12 +283,6 @@ describe('HermesConsoleSource', () => { }); }); - it('uses another binding name in another session', async () => { - const first = await startSource(); - const second = await startSource(); - expect(first.binding).not.toBe(second.binding); - }); - it('records console messages with target.kind hermes, redacted', async () => { const { client, events } = await startSource(); @@ -424,10 +375,6 @@ describe('HermesConsoleSource', () => { 'Runtime.consoleAPICalled', consoleEvent('error', 'Error: same\n at caught (:1:1)'), ); - client.emit( - 'Runtime.consoleAPICalled', - consoleEvent('error', 'Error: same\n at uncaught (:2:2)'), - ); client.emit( 'Runtime.bindingCalled', bindingEvent(binding, { @@ -435,6 +382,10 @@ describe('HermesConsoleSource', () => { text: 'Error: same\n at uncaught (:2:2)', }), ); + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent('error', 'Error: same\n at uncaught (:2:2)'), + ); const [caught, uncaught] = readAll(events); expect(caught?.uncaught).toBeUndefined(); @@ -447,6 +398,30 @@ describe('HermesConsoleSource', () => { }); }); + it('marks the newest of two identical console errors when the hook reports after', async () => { + const { client, events, binding } = await startSource(); + + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent('error', 'Error: dup\n at f (:1:1)'), + ); + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent('error', 'Error: dup\n at f (:1:1)'), + ); + client.emit( + 'Runtime.bindingCalled', + bindingEvent(binding, { + fatal: true, + text: 'Error: dup\n at f (:1:1)', + }), + ); + + const [first, second] = readAll(events); + expect(first?.uncaught).toBeUndefined(); + expect(second).toMatchObject({ seq: 2, uncaught: true, fatal: true }); + }); + it('records the hook report first and drops the console error that follows', async () => { const { client, events, binding } = await startSource(); @@ -614,8 +589,8 @@ describe('HermesConsoleSource', () => { ]); }); - it('ignores contextCreated of the first connect and of a reload', async () => { - const { client } = await startSource(); + it('ignores reload contextCreated and counts failed re-enable or reconnect', async () => { + const { client, events } = await startSource(); client.send.mockClear(); client.emit('contextCreated', { @@ -624,18 +599,13 @@ describe('HermesConsoleSource', () => { target: { id: 'T1' }, }); await flush(); - expect(client.send).not.toHaveBeenCalled(); - }); - it('counts a failed re-enable and a failed reconnect loop', async () => { - const { client, events } = await startSource(); client.send.mockResolvedValue({ ok: false, code: 'HERMES_CDP_FAILED', message: 'nope', }); - client.emit('contextCreated', { reason: 'reconnect', reconnected: true, @@ -655,26 +625,6 @@ describe('HermesConsoleSource', () => { }); }); - it('does not enable twice when start connect emits contextCreated', async () => { - const client = createClient(); - client.connect.mockImplementationOnce(async () => { - const target = { id: 'T1', logicalDeviceId: 'D1', title: 'MetaMask' }; - client.emit('contextCreated', { - reason: 'connect', - reconnected: false, - target, - }); - return { ok: true, target }; - }); - const events = new SessionEvents(() => client, []); - await new HermesConsoleSource().start(client, events); - await flush(); - - expect( - client.send.mock.calls.filter(([method]) => method === 'Runtime.enable'), - ).toHaveLength(1); - }); - it('enables once a client that failed to connect on start connects later', async () => { const client = createClient(); client.connect.mockResolvedValueOnce({ @@ -685,13 +635,6 @@ describe('HermesConsoleSource', () => { const events = new SessionEvents(() => client, []); await new HermesConsoleSource().start(client, events); - expect(events.buffer.summary()).toMatchObject({ - captureErrors: 1, - lastCaptureError: - 'Hermes connect failed: [HERMES_TARGET_NOT_FOUND] not ready', - }); - expect(client.send).not.toHaveBeenCalled(); - client.emit('contextCreated', { reason: 'connect', reconnected: false, @@ -700,11 +643,6 @@ describe('HermesConsoleSource', () => { await flush(); client.emit('Runtime.consoleAPICalled', consoleEvent('error', 'ready')); - expect(client.send.mock.calls.map(([method]) => method)).toStrictEqual([ - 'Runtime.addBinding', - 'Runtime.enable', - 'Runtime.evaluate', - ]); expect(readAll(events)).toStrictEqual([ expect.objectContaining({ text: 'ready', @@ -714,46 +652,22 @@ describe('HermesConsoleSource', () => { }); it.each([ - { - label: 'connect', - setup: (client: FakeClient): void => { - client.connect.mockResolvedValueOnce({ - ok: false, - code: 'HERMES_TARGET_NOT_FOUND', - message: 'no target', - }); - }, - expected: 'Hermes connect failed: [HERMES_TARGET_NOT_FOUND] no target', - }, - { - label: 'Runtime.enable', - setup: (client: FakeClient): void => { - client.send.mockImplementation(async (method: string) => - method === 'Runtime.enable' - ? { ok: false, code: 'HERMES_CDP_FAILED', message: 'enable' } - : { ok: true, result: {} }, - ); - }, - expected: 'Runtime.enable failed: [HERMES_CDP_FAILED] enable', - }, - { - label: 'Runtime.addBinding', - setup: (client: FakeClient): void => { - client.send.mockResolvedValue({ - ok: false, - code: 'HERMES_CDP_FAILED', - message: 'binding', - }); - }, - expected: 'Runtime.addBinding failed: [HERMES_CDP_FAILED] binding', - }, + ['connect', 'Hermes connect failed: [E] fail'], + ['Runtime.addBinding', 'Runtime.addBinding failed: [E] fail'], + ['Runtime.enable', 'Runtime.enable failed: [E] fail'], ])( - 'records a $label failure on start without throwing and keeps listening', - async ({ setup, expected }) => { + 'records a %s start failure without throwing and keeps listening', + async (failing, expected) => { const client = createClient(); - setup(client); + const failure = { ok: false as const, code: 'E', message: 'fail' }; + if (failing === 'connect') { + client.connect.mockResolvedValueOnce(failure); + } else { + client.send.mockImplementation(async (method: string) => + method === failing ? failure : { ok: true, result: {} }, + ); + } const events = new SessionEvents(() => client, []); - await new HermesConsoleSource().start(client, events); expect(events.buffer.summary()).toMatchObject({ @@ -787,30 +701,4 @@ describe('HermesConsoleSource', () => { expect.anything(), ); }); - - it('shares the cursor and gap of the session buffer', async () => { - const client = createClient(); - const events = new SessionEvents(() => client, []); - await new HermesConsoleSource().start(client, events); - const mark = events.buffer.seq; - - for (let index = 0; index < 1001; index++) { - client.emit( - 'Runtime.consoleAPICalled', - consoleEvent('error', `e${index}`), - ); - } - - const page = events.buffer.read({ - kind: 'console', - cursor: mark, - limit: 2, - }); - expect(page).toMatchObject({ hasMore: true, gap: true, cursor: 3 }); - expect(page.records.map((record) => record.text)).toStrictEqual([ - 'e1', - 'e2', - ]); - expect(page.summary.dropped.console).toBe(1); - }); }); diff --git a/src/events/hermes-console-source.ts b/src/events/hermes-console-source.ts index 31d1066e..2db85658 100644 --- a/src/events/hermes-console-source.ts +++ b/src/events/hermes-console-source.ts @@ -251,9 +251,7 @@ export class HermesConsoleSource implements SessionEventSource= 0; index -= 1) { const entry = this.#recent[index]; if ( entry.head === head && now - entry.at <= UNCAUGHT_JOIN_MS && - (entry.record !== undefined) === hasRecord + (text === undefined + ? entry.record === undefined + : entry.record?.text === text) ) { this.#recent.splice(index, 1); return entry; diff --git a/src/events/session-events.test.ts b/src/events/session-events.test.ts index 0156eb3b..3293f3b4 100644 --- a/src/events/session-events.test.ts +++ b/src/events/session-events.test.ts @@ -18,11 +18,6 @@ vi.mock('../platform/cdp-manager.js', () => ({ const getCdpManagerMock = vi.mocked(getCdpManager); -/** - * Returns the CDP manager of a fake browser context. - * - * @returns The manager. - */ function connect(): ReturnType { return getCdpManager({} as BrowserContext); } @@ -259,13 +254,6 @@ describe('getSessionEvents', () => { }); describe('getActiveSessionEvents', () => { - /** - * Builds a session manager with a platform driver. - * - * @param driver - The platform driver. - * @param context - The browser context. - * @returns The session manager. - */ function createManager( driver: Partial | undefined, context: BrowserContext = {} as BrowserContext, diff --git a/src/tools/logs.test.ts b/src/tools/logs.test.ts index 3c2e261d..8eb41b32 100644 --- a/src/tools/logs.test.ts +++ b/src/tools/logs.test.ts @@ -157,8 +157,8 @@ describe('logsTool', () => { }); describe('logsTool on mobile', () => { - it('reads the Hermes console records of the mobile session', async () => { - const client = { + it('uses the mobile driver Hermes event client instead of browser context', async () => { + const getHermesEventClient = vi.fn().mockResolvedValue({ connect: vi.fn().mockResolvedValue({ ok: true, target: { id: 'H1', logicalDeviceId: 'D', title: 'MetaMask' }, @@ -169,44 +169,20 @@ describe('logsTool on mobile', () => { }), on: vi.fn(), off: vi.fn(), - }; - const sessionManager = createMockSessionManager({ hasActive: true }); - const driver = { - getPlatform: () => 'ios', - getHermesEventClient: async () => client, - } as unknown as IPlatformDriver; - sessionManager.getPlatformDriver = (): IPlatformDriver => driver; - const context = { sessionManager } as unknown as ToolContext; - - const marked = await logsTool({}, context); - const onConsole = client.on.mock.calls.find( - ([name]) => name === 'Runtime.consoleAPICalled', - )?.[1] as (event: { params: unknown }) => void; - onConsole({ - params: { - type: 'error', - args: [{ type: 'string', value: 'mm-p2-29 probe' }], - }, - }); - const mark = - marked.ok && 'cursor' in marked.result ? marked.result.cursor : -1; - const result = await logsTool({ cursor: mark, grep: 'p2-29' }, context); - - expect(result).toMatchObject({ - ok: true, - result: { - records: [ - { - target: { kind: 'hermes', id: 'H1', url: '' }, - level: 'error', - text: 'mm-p2-29 probe', - }, - ], - gap: false, - hasMore: false, - summary: { captureErrors: 0 }, - }, }); + const sessionManager = createMockSessionManager({ hasActive: true }); + sessionManager.getPlatformDriver = (): IPlatformDriver => + ({ + getPlatform: () => 'ios', + getHermesEventClient, + }) as unknown as IPlatformDriver; + + const result = await logsTool({}, { + sessionManager, + } as unknown as ToolContext); + + expect(result.ok).toBe(true); + expect(getHermesEventClient).toHaveBeenCalledTimes(1); expect(sessionManager.getContext).not.toHaveBeenCalled(); }); }); diff --git a/src/tools/types/events.ts b/src/tools/types/events.ts index f87d7549..889240bb 100644 --- a/src/tools/types/events.ts +++ b/src/tools/types/events.ts @@ -89,7 +89,7 @@ export type ConsoleRecord = EventRecordBase & { location?: string; /** An uncaught exception, not a console call. */ uncaught?: true; - /** Mobile: an uncaught exception React Native reported as fatal (the red box). */ + /** Mobile: an uncaught exception React Native reported with `isFatal`. */ fatal?: true; }; From eddddc9fc7caf5927cd79bd382b23e864c7590ea Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 4 Dec 2026 16:12:20 +0000 Subject: [PATCH 7/8] fix: retry a failed Hermes Runtime.enable --- README.md | 2 +- src/events/hermes-console-source.test.ts | 98 +++++++++++++++++++++--- src/events/hermes-console-source.ts | 76 ++++++++++-------- 3 files changed, 134 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 66a48f5c..84a8d24f 100644 --- a/README.md +++ b/README.md @@ -723,7 +723,7 @@ The `params-json` argument must be a valid JSON object. The `--timeout` flag set | ------------------- | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Target runtime | The active page or the Extension service worker (`--target sw`), each on a persistent session | The app's Hermes JS engine, via Metro's inspector proxy | | Available domains | Full Chrome surface — `Runtime`, `DOM`, `Network`, `Page`, `Accessibility`, … | JS-engine subset only — `Runtime`, `Debugger`, `Log`, `HeapProfiler` (no `DOM` / `Page` / `Network`) | -| Blocked methods | `Browser.close`, `Target.closeTarget`, `Target.disposeBrowserContext`, `Browser.crashGpuProcess` | `Runtime.terminateExecution`, `Inspector.detached` | +| Blocked methods | `Browser.close`, `Target.closeTarget`, `Target.disposeBrowserContext`, `Browser.crashGpuProcess` | `Runtime.terminateExecution`, `Inspector.detached`, `Runtime.disable` (on the session connection) | | `metroPort`/`appId` | Ignored | Default to the session's (the launch `--metro-port`, else `HERMES_METRO_PORT`, else `8081`; app id: `HERMES_APP_ID`, else the platform default). A per-call flag overrides them for that call only. | | Prerequisite | An active browser session | An active mobile session with a DEBUG build and Metro running | | Errors | `MM_CDP_BLOCKED` / `MM_CDP_FAILED`; `MM_INVALID_INPUT` for a mobile-only target | `MM_CDP_BLOCKED` / `MM_CDP_FAILED` (the underlying `HERMES_*` code is preserved in the message, with the Metro port used); `MM_INVALID_INPUT` for a browser-only target | diff --git a/src/events/hermes-console-source.test.ts b/src/events/hermes-console-source.test.ts index 5bb95bdd..720bee6d 100644 --- a/src/events/hermes-console-source.test.ts +++ b/src/events/hermes-console-source.test.ts @@ -22,6 +22,8 @@ type FakeClient = HermesEventClient & { send: ReturnType; connect: ReturnType; evaluations: SendResult[]; + enableResults: SendResult[]; + failures: Set; onEnable?: () => void; }; @@ -31,6 +33,8 @@ function createClient(): FakeClient { evaluations: [ { ok: true, result: { result: { value: 'installed' } } }, ] as SendResult[], + enableResults: [] as SendResult[], + failures: new Set(), onEnable: undefined as (() => void) | undefined, connect: vi.fn(async () => { const target = { id: 'T1', logicalDeviceId: 'D1', title: 'MetaMask' }; @@ -42,8 +46,15 @@ function createClient(): FakeClient { return { ok: true, target }; }), send: vi.fn(async (method: string): Promise => { + if (client.failures.has(method)) { + return { ok: false, code: 'E', message: 'fail' }; + } if (method === 'Runtime.enable') { client.onEnable?.(); + const result = client.enableResults.shift(); + if (result) { + return result; + } } if (method === 'Runtime.evaluate') { return client.evaluations.length > 1 @@ -85,6 +96,7 @@ async function startSource(): Promise<{ const events = new SessionEvents(() => client, []); const source = new HermesConsoleSource(); const { unsubscribe } = await source.start(client, events); + await flush(); const binding = ( client.send.mock.calls.find( ([method]) => method === 'Runtime.addBinding', @@ -328,6 +340,7 @@ describe('HermesConsoleSource', () => { }; const events = new SessionEvents(() => client, []); await new HermesConsoleSource().start(client, events); + await flush(); client.emit( 'Runtime.consoleAPICalled', @@ -422,6 +435,24 @@ describe('HermesConsoleSource', () => { expect(second).toMatchObject({ seq: 2, uncaught: true, fatal: true }); }); + it('records two console errors that share a first line and differ below it', async () => { + const { client, events } = await startSource(); + + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent('error', 'Error: same\n at a (:1:1)'), + ); + client.emit( + 'Runtime.consoleAPICalled', + consoleEvent('error', 'Error: same\n at b (:2:2)'), + ); + + expect(readAll(events).map((record) => record.text)).toStrictEqual([ + 'Error: same\n at a (:1:1)', + 'Error: same\n at b (:2:2)', + ]); + }); + it('records the hook report first and drops the console error that follows', async () => { const { client, events, binding } = await startSource(); @@ -522,6 +553,38 @@ describe('HermesConsoleSource', () => { expect(events.buffer.summary().captureErrors).toBe(0); }); + it('retries a failed Runtime.enable, then records', async () => { + vi.useFakeTimers(); + const client = createClient(); + client.enableResults = [ + { ok: false, code: 'HERMES_TIMEOUT', message: 'timed out' }, + ]; + const events = new SessionEvents(() => client, []); + await new HermesConsoleSource().start(client, events); + + await flush(); + await vi.advanceTimersByTimeAsync(500); + await flush(); + + const binding = ( + client.send.mock.calls.find( + ([method]) => method === 'Runtime.addBinding', + )?.[1] as { name: string } + ).name; + client.emit('Runtime.consoleAPICalled', consoleEvent('error', 'after')); + + expect(client.send).toHaveBeenCalledWith( + 'Runtime.evaluate', + { expression: hookScript(binding), returnByValue: true }, + expect.anything(), + ); + expect(readAll(events).map((record) => record.text)).toStrictEqual([ + 'after', + ]); + expect(events.buffer.summary().captureErrors).toBe(0); + expect(client.listenerCount()).toBeGreaterThan(0); + }); + it('counts a hook that cannot be installed in time as a capture error', async () => { vi.useFakeTimers(); const client = createClient(); @@ -590,6 +653,7 @@ describe('HermesConsoleSource', () => { }); it('ignores reload contextCreated and counts failed re-enable or reconnect', async () => { + vi.useFakeTimers(); const { client, events } = await startSource(); client.send.mockClear(); @@ -611,7 +675,7 @@ describe('HermesConsoleSource', () => { reconnected: true, target: {}, }); - await flush(); + await vi.advanceTimersByTimeAsync(61_000); client.emit('reconnectFailed', { attempts: 6, code: 'HERMES_TARGET_NOT_FOUND', @@ -651,25 +715,37 @@ describe('HermesConsoleSource', () => { ]); }); + it('records a failed connect without throwing and keeps listening', async () => { + const client = createClient(); + client.connect.mockResolvedValueOnce({ + ok: false as const, + code: 'E', + message: 'fail', + }); + const events = new SessionEvents(() => client, []); + await new HermesConsoleSource().start(client, events); + + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 1, + lastCaptureError: 'Hermes connect failed: [E] fail', + }); + expect(client.listenerCount()).toBeGreaterThan(0); + }); + it.each([ - ['connect', 'Hermes connect failed: [E] fail'], ['Runtime.addBinding', 'Runtime.addBinding failed: [E] fail'], ['Runtime.enable', 'Runtime.enable failed: [E] fail'], ])( - 'records a %s start failure without throwing and keeps listening', + 'retries a failed %s and counts one capture error at the deadline', async (failing, expected) => { + vi.useFakeTimers(); const client = createClient(); - const failure = { ok: false as const, code: 'E', message: 'fail' }; - if (failing === 'connect') { - client.connect.mockResolvedValueOnce(failure); - } else { - client.send.mockImplementation(async (method: string) => - method === failing ? failure : { ok: true, result: {} }, - ); - } + client.failures.add(failing); const events = new SessionEvents(() => client, []); await new HermesConsoleSource().start(client, events); + await vi.advanceTimersByTimeAsync(61_000); + expect(events.buffer.summary()).toMatchObject({ captureErrors: 1, lastCaptureError: expected, diff --git a/src/events/hermes-console-source.ts b/src/events/hermes-console-source.ts index 2db85658..0207e885 100644 --- a/src/events/hermes-console-source.ts +++ b/src/events/hermes-console-source.ts @@ -12,6 +12,7 @@ import type { ConsoleRecord, EventRecordTarget, } from '../tools/types/events.js'; +import { extractErrorMessage } from '../utils'; const HERMES_CALL_TIMEOUT_MS = 5_000; const HOOK_RETRY_MS = 500; @@ -169,8 +170,8 @@ export class HermesConsoleSource implements SessionEventSource { @@ -235,31 +236,31 @@ export class HermesConsoleSource implements SessionEventSource, + ): void { + this.#installHook(client, events, true); } /** - * Registers the binding, enables `Runtime`, and installs the hook. + * Adds the binding and enables `Runtime` on the current socket. * * @param client - The Hermes client. - * @param events - The session's events. */ - async #enable( - client: HermesEventClient, - events: SessionEvents, - ): Promise { + async #enableRuntime(client: HermesEventClient): Promise { this.#enabling += 1; try { const bound = await client.send( @@ -283,18 +284,20 @@ export class HermesConsoleSource implements SessionEventSource, + enable = false, ): void { this.#hookGeneration += 1; const generation = this.#hookGeneration; @@ -302,26 +305,39 @@ export class HermesConsoleSource implements SessionEventSource => { let last = 'not-ready'; + let enabled = !enable; while (generation === this.#hookGeneration) { - const outcome = await client.send( - 'Runtime.evaluate', - { expression, returnByValue: true }, - { timeoutMs: HERMES_CALL_TIMEOUT_MS }, - ); - if (outcome.ok) { - const value = (outcome.result as { result?: { value?: unknown } }) - ?.result?.value; - if (value === 'installed' || value === 'present') { - return; + if (enabled) { + const outcome = await client.send( + 'Runtime.evaluate', + { expression, returnByValue: true }, + { timeoutMs: HERMES_CALL_TIMEOUT_MS }, + ); + if (outcome.ok) { + const value = (outcome.result as { result?: { value?: unknown } }) + ?.result?.value; + if (value === 'installed' || value === 'present') { + return; + } + last = typeof value === 'string' ? value : 'no result'; + } else { + last = `[${outcome.code}] ${outcome.message}`; } - last = typeof value === 'string' ? value : 'no result'; } else { - last = `[${outcome.code}] ${outcome.message}`; + try { + await this.#enableRuntime(client); + enabled = true; + continue; + } catch (error) { + last = extractErrorMessage(error); + } } if (Date.now() >= deadline) { if (generation === this.#hookGeneration) { events.reportError( - new Error(`uncaught-error hook not installed: ${last}`), + new Error( + enabled ? `uncaught-error hook not installed: ${last}` : last, + ), ); } return; From 82e12d9736035ec87acb85859485f8436762ecfe Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 4 Dec 2026 16:53:43 +0000 Subject: [PATCH 8/8] refactor: call #installHook directly --- src/events/hermes-console-source.ts | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/src/events/hermes-console-source.ts b/src/events/hermes-console-source.ts index 0207e885..ce90c9a9 100644 --- a/src/events/hermes-console-source.ts +++ b/src/events/hermes-console-source.ts @@ -171,7 +171,7 @@ export class HermesConsoleSource implements SessionEventSource { @@ -237,22 +237,8 @@ export class HermesConsoleSource implements SessionEventSource, - ): void { this.#installHook(client, events, true); + return { unsubscribe }; } /**