diff --git a/README.md b/README.md index de818f7c..84a8d24f 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 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)** | | @@ -697,9 +697,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. | @@ -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/SKILL.md b/SKILL.md index 1ae79499..81d37763 100644 --- a/SKILL.md +++ b/SKILL.md @@ -781,9 +781,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` @@ -793,7 +793,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 ]` @@ -814,10 +814,19 @@ 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 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: "" }`. + +- **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]` 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..2233f0f5 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 { diff --git a/src/events/hermes-console-source.test.ts b/src/events/hermes-console-source.test.ts new file mode 100644 index 00000000..720bee6d --- /dev/null +++ b/src/events/hermes-console-source.test.ts @@ -0,0 +1,780 @@ +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; + evaluations: SendResult[]; + enableResults: SendResult[]; + failures: Set; + onEnable?: () => void; +}; + +function createClient(): FakeClient { + const listeners = new Map void>>(); + const client = { + 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' }; + client.emit('contextCreated', { + reason: 'connect', + reconnected: false, + target, + }); + 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 + ? (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; +} + +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); + await flush(); + const binding = ( + client.send.mock.calls.find( + ([method]) => method === 'Runtime.addBinding', + )?.[1] as { name: string } + ).name; + return { client, events, source, binding, unsubscribe }; +} + +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, + }, + }; +} + +function bindingEvent( + name: string, + report: unknown, +): { method: string; params: unknown } { + return { + method: 'Runtime.bindingCalled', + params: { name, payload: JSON.stringify(report), executionContextId: 1 }, + }; +} + +function readAll(events: SessionEvents): ConsoleRecord[] { + return events.buffer.read({ kind: 'console', limit: 100 }) + .records; +} + +async function flush(): Promise { + for (let index = 0; index < 5; index++) { + await Promise.resolve(); + } +} + +describe('hookScript', () => { + 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 }; + } + + 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('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); + await flush(); + + 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('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.bindingCalled', + bindingEvent(binding, { + fatal: true, + 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(); + expect(caught?.fatal).toBeUndefined(); + expect(uncaught).toMatchObject({ + seq: 2, + text: 'Error: same\n at uncaught (:2:2)', + uncaught: true, + fatal: true, + }); + }); + + 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 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(); + + 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('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(); + 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 reload contextCreated and counts failed re-enable or reconnect', async () => { + vi.useFakeTimers(); + const { client, events } = await startSource(); + client.send.mockClear(); + + client.emit('contextCreated', { + reason: 'reload', + reconnected: false, + target: { id: 'T1' }, + }); + await flush(); + expect(client.send).not.toHaveBeenCalled(); + + client.send.mockResolvedValue({ + ok: false, + code: 'HERMES_CDP_FAILED', + message: 'nope', + }); + client.emit('contextCreated', { + reason: 'reconnect', + reconnected: true, + target: {}, + }); + await vi.advanceTimersByTimeAsync(61_000); + 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('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: 'not ready', + }); + const events = new SessionEvents(() => client, []); + await new HermesConsoleSource().start(client, events); + + client.emit('contextCreated', { + reason: 'connect', + reconnected: false, + target: { id: 'T2', logicalDeviceId: 'D1', title: 'MetaMask' }, + }); + await flush(); + client.emit('Runtime.consoleAPICalled', consoleEvent('error', 'ready')); + + expect(readAll(events)).toStrictEqual([ + expect.objectContaining({ + text: 'ready', + target: { kind: 'hermes', id: 'T2', url: '' }, + }), + ]); + }); + + 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([ + ['Runtime.addBinding', 'Runtime.addBinding failed: [E] fail'], + ['Runtime.enable', 'Runtime.enable failed: [E] fail'], + ])( + 'retries a failed %s and counts one capture error at the deadline', + async (failing, expected) => { + vi.useFakeTimers(); + const client = createClient(); + 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, + }); + expect(client.listenerCount()).toBeGreaterThan(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(), + ); + }); +}); diff --git a/src/events/hermes-console-source.ts b/src/events/hermes-console-source.ts new file mode 100644 index 00000000..ce90c9a9 --- /dev/null +++ b/src/events/hermes-console-source.ts @@ -0,0 +1,458 @@ +import { randomBytes } from 'node:crypto'; + +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 { + CdpEventTarget, + CdpSubscription, +} from '../platform/cdp-manager.js'; +import type { HermesEventClient } from '../platform/types.js'; +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; +const HOOK_INSTALL_TIMEOUT_MS = 60_000; +const UNCAUGHT_JOIN_MS = 5_000; +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; + +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.__mmLogsHookV1`, then calls the previous + * handler with the same `this` and arguments and returns its result, so the + * 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, evaluating to `installed`, `present` or `not-ready`. + */ +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.__mmLogsHookV1; + if (!state) { + state = { bindings: [], seen: new WeakSet() }; + g.__mmLogsHookV1 = 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 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 #bindingName = `__mmLogs_${randomBytes(6).toString('hex')}`; + + #enabling = 0; + + #hookGeneration = 0; + + #consoleEvents = 0; + + #target: EventRecordTarget = { kind: 'hermes', id: '', url: '' }; + + readonly #recent: { head: string; at: number; record?: ConsoleRecord }[] = []; + + /** + * @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; + let connecting = 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 && + !connecting && + (event.reason === 'connect' || event.reason === 'reconnect') + ) { + this.#target = { kind: 'hermes', id: event.target.id ?? '', url: '' }; + this.#installHook(client, events, true); + } + }; + 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); + } + + let connected; + try { + connected = await client.connect({ + timeoutMs: HERMES_CALL_TIMEOUT_MS, + }); + } finally { + connecting = false; + } + if (!active) { + return { unsubscribe }; + } + if (!connected.ok) { + events.reportError( + new Error( + `Hermes connect failed: [${connected.code}] ${connected.message}`, + ), + ); + return { unsubscribe }; + } + this.#target = { kind: 'hermes', id: connected.target.id ?? '', url: '' }; + this.#installHook(client, events, true); + return { unsubscribe }; + } + + /** + * Adds the binding and enables `Runtime` on the current socket. + * + * @param client - The Hermes client. + */ + async #enableRuntime(client: HermesEventClient): 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; + } + } + + /** + * Installs the hook in the current JS context, retrying until the bundle + * runs. With `enable`, adds the binding and enables `Runtime` first. + * + * @param client - The Hermes client. + * @param events - The session's events. + * @param enable - Whether to enable `Runtime` before evaluating the hook. + */ + #installHook( + client: HermesEventClient, + events: SessionEvents, + enable = false, + ): 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'; + let enabled = !enable; + while (generation === this.#hookGeneration) { + 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}`; + } + } else { + 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( + enabled ? `uncaught-error hook not installed: ${last}` : last, + ), + ); + } + return; + } + await new Promise((resolve) => setTimeout(resolve, HOOK_RETRY_MS)); + } + })().catch(events.reportError); + } + + /** + * Records a `Runtime.consoleAPICalled` event, dropping replays and synthetic + * `#InstanceAgent` messages. + * + * @param client - The Hermes client. + * @param events - The session's events. + * @param params - Event 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 now = Date.now(); + const built = toConsoleRecord({ + target: PLACEHOLDER_TARGET, + method: 'Runtime.consoleAPICalled', + params: (params ?? {}) as Record, + t: now, + }); + if (built === undefined) { + return; + } + const record = { ...built.record, target: this.#target }; + const head = record.level === 'error' ? firstLine(record.text) : undefined; + if (head !== undefined && this.#takeRecent(head, now)) { + return; + } + if (!events.config.consoleLevels.includes(record.level)) { + return; + } + const stored = events.buffer.append('console', record); + if (head !== undefined) { + this.#recent.push({ head, at: now, record: stored }); + this.#recent.splice(0, this.#recent.length - MAX_JOIN_ENTRIES); + } + } + + /** + * Records an uncaught error the hook reported, or marks its console record. + * + * @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 match = this.#takeRecent(head, now, text); + if (match?.record) { + match.record.uncaught = true; + if (report.fatal) { + match.record.fatal = true; + } + return; + } + if (events.config.consoleLevels.includes('error')) { + events.buffer.append('console', { + t: now, + target: this.#target, + level: 'error', + text, + uncaught: true, + ...(report.fatal ? { fatal: true as const } : {}), + }); + } + this.#recent.push({ head, at: now }); + this.#recent.splice(0, this.#recent.length - MAX_JOIN_ENTRIES); + } + + /** + * Takes the newest matching entry within the join window. + * + * @param head - First line of the error text. + * @param now - Current epoch ms. + * @param text - Full error text when matching a console record; omit to match a hook report. + * @returns The matched entry, or undefined. + */ + #takeRecent( + head: string, + now: number, + text?: string, + ): { head: string; at: number; record?: ConsoleRecord } | undefined { + for (let index = this.#recent.length - 1; index >= 0; index -= 1) { + const entry = this.#recent[index]; + if ( + entry.head === head && + now - entry.at <= UNCAUGHT_JOIN_MS && + (text === undefined + ? entry.record === undefined + : entry.record?.text === text) + ) { + this.#recent.splice(index, 1); + return entry; + } + } + return undefined; + } +} 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/session-events.test.ts b/src/events/session-events.test.ts index 859020c5..3293f3b4 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,10 @@ vi.mock('../platform/cdp-manager.js', () => ({ const getCdpManagerMock = vi.mocked(getCdpManager); +function connect(): ReturnType { + return getCdpManager({} as BrowserContext); +} + /** * Creates a source whose start resolves with a fake subscription. * @@ -40,7 +47,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 +59,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 +88,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 +109,30 @@ describe('SessionEvents', () => { expect(source.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 +171,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 +193,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 +210,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 +221,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 +252,74 @@ describe('getSessionEvents', () => { expect(other.buffer.startedAt).toBeGreaterThan(events.buffer.startedAt); }); }); + +describe('getActiveSessionEvents', () => { + 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..1be3839b 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,25 @@ 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[] = []; /** - * @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 +105,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,18 +127,24 @@ export class SessionEvents { } /** - * Starts every source once per CDP manager, or returns the start in + * Starts every source once per connection, or returns the start in * progress. * * @returns Settles when the sources started. Never rejects. */ async #start(): Promise { - const manager = getCdpManager(this.context); - if (manager === this.#manager) { + let connection: Connection; + try { + connection = await this.#connect(); + } catch (error) { + this.reportError(error); + return; + } + if (connection === this.#connection) { await this.#starting; return; } - this.#manager = manager; + this.#connection = connection; const previous = this.#subscriptions; this.#subscriptions = []; const starting = (async (): Promise => { @@ -137,7 +154,7 @@ export class SessionEvents { ), ); const results = await Promise.allSettled( - this.#sources.map(async (source) => source.start(manager, this)), + this.#sources.map(async (source) => source.start(connection, this)), ); const started = results.flatMap((result) => { if (result.status === 'fulfilled') { @@ -146,9 +163,9 @@ export class SessionEvents { 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), @@ -163,17 +180,13 @@ export class SessionEvents { } } -/** - * 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 +198,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'); + } + // 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); + 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..d39a980c 100644 --- a/src/platform/mobile-platform-driver.hermes.test.ts +++ b/src/platform/mobile-platform-driver.hermes.test.ts @@ -808,6 +808,30 @@ describe('MobilePlatformDriver persistent Hermes client', () => { expect(mocks.HermesClient).toHaveBeenCalledTimes(1); }); + 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(); + expect(client).toBe(clients[0]); + 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', + timeoutMs: 30_000, + metroPort: 8087, + }); + expect(mocks.runHermesCdp).toHaveBeenCalledTimes(1); + }); + 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 b87c0799..155f04a9 100644 --- a/src/platform/mobile-platform-driver.ts +++ b/src/platform/mobile-platform-driver.ts @@ -21,6 +21,7 @@ import type { AccessibilityTree, IPlatformDriver, HermesDefaults, + HermesEventClient, TargetType, ClickActionResult, ClickOptions, @@ -233,8 +234,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. @@ -280,6 +281,23 @@ export class MobilePlatformDriver implements IPlatformDriver { session.setPinnedHermesDeviceId(logicalDeviceId); } + /** + * 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. + */ + async getHermesEventClient(): Promise { + const runtime = await loadDeviceMcp(); + const session = await this.#getHermesSession(); + return this.#getHermesClient( + runtime, + session, + this.#resolveHermesTarget(session), + ); + } + /** * Closes the persistent client, if one was created. Idempotent. */ @@ -905,6 +923,15 @@ export class MobilePlatformDriver implements IPlatformDriver { const client = usesSessionTarget ? this.#getHermesClient(runtime, session, sessionTarget) : undefined; + 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 ? await client.send(input.method, input.params, { diff --git a/src/platform/types.ts b/src/platform/types.ts index f849de4d..39a37abd 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, @@ -139,6 +141,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; @@ -322,5 +330,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..8eb41b32 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,34 @@ describe('logsTool', () => { expect(events.config.consoleLevels).toStrictEqual(['error', 'warning']); }); }); + +describe('logsTool on mobile', () => { + 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' }, + }), + send: vi.fn().mockResolvedValue({ + ok: true, + result: { result: { value: 'installed' } }, + }), + on: vi.fn(), + off: vi.fn(), + }); + 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/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..889240bb 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 with `isFatal`. */ + fatal?: true; }; /** What the session records. Changed by `configure`, from then on. */