diff --git a/README.md b/README.md index 30853f95..98b68474 100644 --- a/README.md +++ b/README.md @@ -436,6 +436,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 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. | | `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)** | | | `hermes_targets` | Lists and diagnoses the debuggable Hermes targets Metro exposes (iOS and Android), reporting which target would be chosen or why selection is ambiguous. Use to confirm Metro is running and the app is registered. Pass `all` to bypass the appId filter and discover the real appId. Mobile only — there is no browser equivalent. | @@ -688,6 +689,8 @@ mm describe-screen | `mm mock-network requests [--limit ] [--url ] [--bodies]` | Shows recorded matched and missed requests. `--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 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 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 cdp [params-json] [--timeout ] [--target page\|sw\|hermes\|android-webview] [--fresh] [--metro-port

] [--app-id ]` | Sends a raw Chrome DevTools Protocol command against the active session. Escape hatch for when structured tools are insufficient. Works on both browser and mobile — the target runtime and blocked methods differ by platform (see below). Browser targets are the active page (`page`, default) and the Extension service worker (`sw`); `--fresh` uses a one-shot session. On mobile the session keeps the `--metro-port` given to `mm launch`, so later calls use it; a per-call `--metro-port` is only an override. | ```bash diff --git a/SKILL.md b/SKILL.md index ae6086d3..f7d3c490 100644 --- a/SKILL.md +++ b/SKILL.md @@ -42,7 +42,7 @@ The default depends on the tool's category: | Category | Examples | Default `observe` | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | | **Mutating** | click, type, navigate, reload, launch, cleanup, build, clipboard, mock_network, scroll_to_element, device_swipe, long_press, tap_coordinates, dismiss_keyboard, dismiss_alert, open_app, close_app, press_button, device_context, device_clipboard | `diff` | -| **Read-only** | get_state, get_text, inspect, get_context, set_context, events, get_alert_text, screen_recording, device_logs, generate_locators, hermes_targets | `none` | +| **Read-only** | get_state, get_text, inspect, get_context, set_context, events, logs, get_alert_text, screen_recording, device_logs, generate_locators, hermes_targets | `none` | | **Discovery** | describe_screen, list_testids, accessibility_snapshot, screenshot (data is already in `result`) | `none` | | **CDP** | cdp | `none` | | **Batch** | run_steps | `diff` | @@ -761,6 +761,29 @@ Empties the buffer (one kind or all). The cursor keeps counting, so older cursor `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. 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. +#### `mm logs [--cursor | --since ] [--limit ] [--grep ]` + +Console errors and uncaught exceptions of every page and the Extension service worker. Returns `{ records, cursor, hasMore, gap, summary }`, oldest first (default 500, max 2000 per read). While `hasMore` is true, read again with the returned `cursor`. `gap: true` means records after your cursor were dropped (buffer full), or your cursor is from an earlier session (it is above the newest `seq` of this one; the read then starts from the oldest record). `--grep` is a case-sensitive JavaScript regular expression of at most 256 characters. The pattern runs in the daemon, so avoid patterns with nested quantifiers such as `(a+)+`. A value that starts with `--` is read as a missing flag value; escape it, for example `--grep '\-\-x'`. + +```json +{ + "seq": 14, + "t": 1795430400123, + "target": { + "kind": "sw", + "id": "A51F9577…", + "url": "chrome-extension://…/scripts/app-init.js" + }, + "level": "error", + "text": "Fetch failed: https://mainnet.infura.io/v3/[REDACTED]", + "location": "chrome-extension://…/scripts/app-init.js:10:5" +} +``` + +`target.kind` is `page` or `sw`. 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. + ### Mobile device actions (iOS/Android only) These commands require a mobile session (`mm launch --platform ios|android`). On a browser diff --git a/src/cli/mm.test.ts b/src/cli/mm.test.ts index d9bcfe99..99098bbf 100644 --- a/src/cli/mm.test.ts +++ b/src/cli/mm.test.ts @@ -1058,6 +1058,7 @@ describe('printHelp', () => { expect(output).toContain('--pretty'); expect(output).toContain('MM_PRETTY'); expect(output).toContain('mm events mark'); + expect(output).toContain('mm logs configure --levels'); }); }); @@ -3170,6 +3171,84 @@ describe('routeCommand', () => { expectFailure(expect.stringContaining('Usage: mm events'), 2); }); + it('routes logs with read flags', async () => { + await routeCommand( + 'logs', + [ + '--cursor', + '12', + '--limit', + '50', + '--since', + '2026-11-18T10:00:00Z', + '--grep', + 'boom', + ], + 3000, + ); + expect(globalThis.fetch).toHaveBeenLastCalledWith( + 'http://127.0.0.1:3000/tool/logs', + expect.objectContaining({ + body: JSON.stringify({ + cursor: 12, + limit: 50, + since: '2026-11-18T10:00:00Z', + grep: 'boom', + }), + }), + ); + await routeCommand('logs', [], 3000); + expect(globalThis.fetch).toHaveBeenLastCalledWith( + 'http://127.0.0.1:3000/tool/logs', + expect.objectContaining({ body: JSON.stringify({}) }), + ); + // A cursor of 0 is valid (the start of the session). + await routeCommand('logs', ['--cursor', '0'], 3000); + expect(globalThis.fetch).toHaveBeenLastCalledWith( + 'http://127.0.0.1:3000/tool/logs', + expect.objectContaining({ body: JSON.stringify({ cursor: 0 }) }), + ); + }); + + it('routes logs configure', async () => { + await routeCommand( + 'logs', + ['configure', '--levels', 'error, warning'], + 3000, + ); + expect(globalThis.fetch).toHaveBeenLastCalledWith( + 'http://127.0.0.1:3000/tool/logs', + expect.objectContaining({ + body: JSON.stringify({ + action: 'configure', + levels: ['error', 'warning'], + }), + }), + ); + }); + + it.each([ + [['--cursor', 'x']], + [['--limit']], + [['--limit', '0']], + [['--limit', '-5']], + [['--since']], + [['--grep', '--cursor', '1']], + [['--grap', 'x']], + [['--levels', 'warning']], + [['configure']], + [['configure', '--levels', ',']], + [['configure', '--levels', 'warning', '--cursor', '1']], + [['configure', '--levels', 'warning', 'extra']], + [['configure', '--levels', 'warning', '--levels', 'error']], + [['tail']], + ])('exits on bad logs arguments %j', async (args) => { + await expect(routeCommand('logs', args, 3000)).rejects.toThrowError( + 'process.exit', + ); + expectFailure(expect.stringContaining('Usage: mm logs'), 2); + }); + it('exits when mock-network has an unknown action', async () => { await expect( routeCommand('mock-network', ['unknown'], 3000), diff --git a/src/cli/mm.ts b/src/cli/mm.ts index 2a66ac49..a43456bd 100644 --- a/src/cli/mm.ts +++ b/src/cli/mm.ts @@ -1015,6 +1015,10 @@ export async function routeCommand( await routeEventsCommand(args, daemon); break; } + case 'logs': { + await routeLogsCommand(args, daemon); + break; + } case 'cdp': { const cdpMethod = args[0]; if (!cdpMethod) { @@ -1363,6 +1367,97 @@ export async function routeEventsCommand( }); } +const LOGS_USAGE = + 'Usage: mm logs [--cursor | --since ] [--limit ] [--grep ]\n' + + ' mm logs configure --levels '; + +/** + * Parses the read flags shared by `mm logs` and `mm network`. + * + * @param args - CLI arguments. + * @param usage - The usage text to print on a bad flag. + * @param stringFlags - Extra flags that take a string value. + * @returns The read options for the tool. + */ +export function parseEventReadArgs( + args: string[], + usage: string, + stringFlags: readonly string[] = [], +): Record { + const integerFlags = new Set(['--cursor', '--limit']); + const textFlags = new Set(['--since', ...stringFlags]); + const options: Record = {}; + // Every flag takes one value, so the arguments come in flag/value pairs. + // Reject anything else: a mistyped flag must not be silently ignored. + for (let index = 0; index < args.length; index += 2) { + const flag = args[index]; + const value = args[index + 1]; + if ( + flag === undefined || + (!integerFlags.has(flag) && !textFlags.has(flag)) || + value === undefined || + value.startsWith('--') + ) { + failUsage(usage); + } + if (integerFlags.has(flag)) { + const parsed = parseInt(value, 10); + // A cursor may be 0; a limit below 1 would silently read one record. + if (Number.isNaN(parsed) || (flag === '--limit' && parsed < 1)) { + failUsage(usage); + } + options[flag.slice(2)] = parsed; + } else { + options[flag.slice(2)] = value; + } + } + return options; +} + +/** + * Routes `mm logs` to the daemon. + * + * @param args - CLI arguments after `logs`. + * @param daemon - The daemon endpoint (a port or the daemon state). + */ +export async function routeLogsCommand( + args: string[], + daemon: DaemonEndpoint, +): Promise { + if (args[0] === 'configure') { + const levelsArgument = args[2]; + if ( + args.length !== 3 || + args[1] !== '--levels' || + levelsArgument === undefined || + levelsArgument.startsWith('--') + ) { + failUsage(LOGS_USAGE); + } + const levels = levelsArgument + .split(',') + .map((level) => level.trim()) + .filter(Boolean); + if (levels.length === 0) { + failUsage(LOGS_USAGE); + } + await sendRequest(daemon, 'POST', '/tool/logs', { + action: 'configure', + levels, + }); + return; + } + if (args[0] !== undefined && !args[0].startsWith('--')) { + failUsage(LOGS_USAGE); + } + await sendRequest( + daemon, + 'POST', + '/tool/logs', + parseEventReadArgs(args, LOGS_USAGE, ['--grep']), + ); +} + /** * Checks whether a failed request is safe to send again: only a refused * connection (`ECONNREFUSED`), because the daemon never accepted the request. @@ -2260,6 +2355,12 @@ Session events (browser only; recorded from launch on, not during it): 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. + mm logs configure --levels + Levels to record from now on (default: error). Mobile (iOS/Android only): mm device-swipe [--startX ] [--startY ] [--distance ] diff --git a/src/events/console-source.test.ts b/src/events/console-source.test.ts new file mode 100644 index 00000000..e8d7c05e --- /dev/null +++ b/src/events/console-source.test.ts @@ -0,0 +1,680 @@ +import type { BrowserContext } from '@playwright/test'; +import { describe, expect, it, vi } from 'vitest'; + +import { + CONSOLE_EVENTS, + ConsoleSource, + formatConsoleArgs, + toConsoleLevel, + toConsoleRecord, +} from './console-source.js'; +import { REDACTED_VALUE } from './redact.js'; +import { SessionEvents } from './session-events.js'; +import type { + CdpEvent, + CdpManager, + CdpSubscribeOptions, +} from '../platform/cdp-manager.js'; +import type { ConsoleRecord } from '../tools/types/events.js'; + +const INFURA_KEY = '0123456789abcdef0123456789abcdef'; +const SW = { + kind: 'sw' as const, + targetId: 'W1', + url: 'chrome-extension://abcdefghijklmnopabcdefghijklmnop/bg.js', +}; +const PAGE = { + kind: 'page' as const, + targetId: 'P1', + url: `https://dapp.example/?apiKey=secret`, +}; + +/** + * Builds a `Runtime.consoleAPICalled` event. + * + * @param type - The console call type. + * @param args - The arguments. + * @param options - Target and time. + * @param options.target - The event target. + * @param options.timestamp - The CDP timestamp, epoch ms. + * @returns The event. + */ +function consoleEvent( + type: string, + args: unknown[], + options: { target?: CdpEvent['target']; timestamp?: number } = {}, +): CdpEvent { + return { + target: options.target ?? SW, + method: 'Runtime.consoleAPICalled', + params: { + type, + args, + ...(options.timestamp === undefined + ? {} + : { timestamp: options.timestamp }), + stackTrace: { + callFrames: [{ url: SW.url, lineNumber: 9, columnNumber: 4 }], + }, + }, + t: 5000, + }; +} + +/** + * Starts a console source on a fake manager. + * + * @returns The session events and a function that emits a CDP event. + */ +async function startSource(): Promise<{ + events: SessionEvents; + emit: (event: CdpEvent) => void; + options: CdpSubscribeOptions; +}> { + let options: CdpSubscribeOptions | undefined; + const manager = { + subscribe: vi.fn(async (subscribeOptions: CdpSubscribeOptions) => { + options = subscribeOptions; + return { unsubscribe: vi.fn() }; + }), + } as unknown as CdpManager; + const events = new SessionEvents({} as BrowserContext, []); + await new ConsoleSource().start(manager, events); + const subscribed = options as CdpSubscribeOptions; + return { + events, + emit: (event): void => subscribed.onEvent(event), + options: subscribed, + }; +} + +/** + * 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; +} + +describe('toConsoleLevel', () => { + it.each([ + ['error', 'error'], + ['assert', 'error'], + ['warning', 'warning'], + ['info', 'info'], + ['debug', 'debug'], + ['log', 'log'], + ['table', 'log'], + [undefined, 'log'], + ])('%s → %s', (type, level) => { + expect(toConsoleLevel(type)).toBe(level); + }); +}); + +describe('toConsoleRecord', () => { + it('formats console arguments, redacts and locates', () => { + const built = toConsoleRecord( + consoleEvent( + 'error', + [ + { + type: 'string', + value: `failed https://mainnet.infura.io/v3/${INFURA_KEY}`, + }, + { type: 'number', value: 42 }, + { type: 'number', unserializableValue: 'NaN' }, + { type: 'undefined' }, + { type: 'object', subtype: 'null', value: null }, + { + type: 'object', + subtype: 'error', + description: 'Error: boom\n at x', + }, + { + type: 'object', + subtype: 'object', + className: 'Object', + description: 'Object', + objectId: '{"injectedScriptId":1,"id":1}', + preview: { + type: 'object', + overflow: false, + properties: [ + { name: 'code', type: 'number', value: '4001' }, + { name: 'message', type: 'string', value: 'User rejected' }, + ], + }, + }, + { + type: 'object', + subtype: 'array', + className: 'Array', + description: 'Array(2)', + objectId: '{"injectedScriptId":1,"id":2}', + preview: { + type: 'object', + subtype: 'array', + description: 'Array(2)', + overflow: false, + properties: [ + { name: '0', type: 'number', value: '1' }, + { name: '1', type: 'number', value: '2' }, + ], + }, + }, + { + type: 'object', + className: 'Object', + description: 'Object', + preview: { + type: 'object', + overflow: true, + properties: [{ name: 'a', type: 'number', value: '1' }], + }, + }, + { type: 'boolean', value: false }, + { type: 'object', className: 'Object', description: 'Object' }, + ], + { timestamp: 1234.6 }, + ), + ); + expect(built).toStrictEqual({ + timestamp: 1234.6, + record: { + t: 1235, + target: { kind: 'sw', id: 'W1', url: SW.url }, + level: 'error', + text: "failed https://mainnet.infura.io/v3/[REDACTED] 42 NaN undefined null Error: boom\n at x {code: [REDACTED], message: 'User rejected'} [1, 2] {a: 1, …} false Object", + location: `${SW.url}:10:5`, + }, + }); + }); + + it('redacts sensitive preview fields, including nested ones', () => { + const built = toConsoleRecord( + consoleEvent('error', [ + { + type: 'object', + className: 'Object', + description: 'Object', + preview: { + type: 'object', + overflow: false, + properties: [ + { name: 'privateKey', type: 'string', value: '0xdeadbeef' }, + { name: 'mnemonic', type: 'string', value: 'word word word' }, + { name: 'password', type: 'string', value: 'hunter2' }, + { name: 'seedPhrase', type: 'string', value: 'a b c' }, + { + name: 'url', + type: 'string', + value: 'https://rpc.example.com/?apiKey=secret', + }, + { + name: 'nested', + type: 'object', + value: 'Object', + valuePreview: { + type: 'object', + overflow: false, + properties: [ + { + name: 'privateKey', + type: 'string', + value: '0xcafe', + }, + { name: 'ok', type: 'number', value: '1' }, + ], + }, + }, + { name: 'safe', type: 'number', value: '1' }, + ], + }, + }, + ]), + ); + + expect(built?.record.text).toBe( + `{privateKey: ${REDACTED_VALUE}, mnemonic: ${REDACTED_VALUE}, ` + + `password: ${REDACTED_VALUE}, seedPhrase: ${REDACTED_VALUE}, ` + + `url: 'https://rpc.example.com/?apiKey=${REDACTED_VALUE}', ` + + `nested: {privateKey: ${REDACTED_VALUE}, ok: 1}, safe: 1}`, + ); + }); + + it('redacts a named property of an array preview and keeps its name', () => { + const built = toConsoleRecord( + consoleEvent('error', [ + { + type: 'object', + subtype: 'array', + className: 'Array', + description: 'Array(3)', + preview: { + type: 'object', + subtype: 'array', + description: 'Array(3)', + overflow: false, + properties: [ + { name: '0', type: 'string', value: 'one' }, + { name: '1', type: 'number', value: '2' }, + { name: 'privateKey', type: 'string', value: '0xdeadbeef' }, + { name: 'label', type: 'string', value: 'wallet' }, + ], + }, + }, + ]), + ); + + expect(built?.record.text).toBe( + `['one', 2, privateKey: ${REDACTED_VALUE}, label: 'wallet']`, + ); + }); + + it('uses the query rules for preview names and keeps the allowlist', () => { + const build = (names: string[]) => + toConsoleRecord( + consoleEvent('error', [ + { + type: 'object', + className: 'Object', + description: 'Object', + preview: { + type: 'object', + overflow: false, + properties: names.map((name) => ({ + name, + type: 'string', + value: 'secret', + })), + }, + }, + ]), + )?.record.text; + + expect( + build(['token', 'secretKey', 'seed', 'key', 'mnemonicPhrase', 'pk']), + ).toBe( + `{token: ${REDACTED_VALUE}, secretKey: ${REDACTED_VALUE}, ` + + `seed: ${REDACTED_VALUE}, key: ${REDACTED_VALUE}, ` + + `mnemonicPhrase: ${REDACTED_VALUE}, pk: ${REDACTED_VALUE}}`, + ); + expect(build(['publicKey', 'sortKey', 'sourceToken', 'nativeToken'])).toBe( + "{publicKey: 'secret', sortKey: 'secret', sourceToken: 'secret', " + + "nativeToken: 'secret'}", + ); + }); + + it('renders plain objects and proxies, and descriptions for other subtypes', () => { + const preview = ( + subtype: string, + description: string, + properties: { name: string; type: string; value?: string }[] = [], + ) => ({ + type: 'object', + subtype, + description, + preview: { + type: 'object', + subtype, + description, + overflow: false, + properties, + }, + }); + expect( + formatConsoleArgs([ + preview('proxy', 'Proxy', [{ name: 'a', type: 'number', value: '1' }]), + preview('regexp', '/foo/g', [ + { name: 'lastIndex', type: 'number', value: '0' }, + ]), + preview('date', 'Tue Nov 18 2026'), + preview('typedarray', 'Uint8Array(2)', [ + { name: '0', type: 'number', value: '1' }, + ]), + preview('arraybuffer', 'ArrayBuffer(8)'), + preview('promise', 'Promise'), + preview('error', 'Error: boom'), + preview('weakmap', 'WeakMap'), + preview('iterator', 'Array Iterator'), + preview('generator', 'Generator'), + ]), + ).toBe( + '{a: 1} /foo/g Tue Nov 18 2026 Uint8Array(2) ArrayBuffer(8) ' + + 'Promise Error: boom WeakMap Array Iterator Generator', + ); + }); + + it('never prints map or set entry values', () => { + expect( + formatConsoleArgs([ + { + type: 'object', + subtype: 'map', + description: 'Map(1)', + preview: { + type: 'object', + subtype: 'map', + description: 'Map(1)', + overflow: false, + properties: [ + { name: 'privateKey', type: 'string', value: '0xdeadbeef' }, + ], + }, + }, + { + type: 'object', + subtype: 'set', + description: 'Set(1)', + preview: { + type: 'object', + subtype: 'set', + description: 'Set(1)', + overflow: false, + properties: [{ name: '0', type: 'string', value: 'secret' }], + }, + }, + ]), + ).toBe('Map(1) Set(1)'); + }); + + it('fills format specifiers from the following arguments', () => { + const preview = { + type: 'object', + className: 'Object', + description: 'Object', + preview: { + type: 'object', + overflow: false, + properties: [ + { name: 'code', type: 'number', value: '4001' }, + { name: 'message', type: 'string', value: 'User rejected' }, + ], + }, + }; + expect( + formatConsoleArgs([ + { type: 'string', value: 'Failed %s with %d' }, + { type: 'string', value: 'x' }, + { type: 'number', value: 4 }, + preview, + ]), + ).toBe("Failed x with 4 {code: [REDACTED], message: 'User rejected'}"); + expect( + formatConsoleArgs([ + { type: 'string', value: '%cHello %s%c!' }, + { type: 'string', value: 'color: red' }, + { type: 'string', value: 'world' }, + { type: 'string', value: 'font-weight: bold' }, + ]), + ).toBe('Hello world!'); + expect( + formatConsoleArgs([ + { type: 'string', value: '100%% %i %f' }, + { type: 'number', value: 3.9 }, + { type: 'string', value: '2.5' }, + ]), + ).toBe('100% 3 2.5'); + expect(formatConsoleArgs([{ type: 'string', value: 'value %s' }])).toBe( + 'value %s', + ); + }); + + it('uses the delivery time without a CDP timestamp and redacts the target URL', () => { + const event: CdpEvent = { + target: PAGE, + method: 'Runtime.consoleAPICalled', + params: { type: 'warning' }, + t: 777, + }; + expect(toConsoleRecord(event)).toStrictEqual({ + timestamp: undefined, + record: { + t: 777, + target: { + kind: 'page', + id: 'P1', + url: 'https://dapp.example/?apiKey=[REDACTED]', + }, + level: 'warning', + text: '', + }, + }); + }); + + it('builds an uncaught exception record', () => { + const event: CdpEvent = { + target: PAGE, + method: 'Runtime.exceptionThrown', + params: { + timestamp: 900, + exceptionDetails: { + text: 'Uncaught', + exception: { + type: 'object', + subtype: 'error', + description: 'TypeError: uncaught in page', + }, + url: 'https://dapp.example/app.js', + lineNumber: 0, + columnNumber: 7, + }, + }, + t: 1000, + }; + expect(toConsoleRecord(event)?.record).toStrictEqual({ + t: 900, + target: { + kind: 'page', + id: 'P1', + url: 'https://dapp.example/?apiKey=[REDACTED]', + }, + level: 'error', + text: 'Uncaught TypeError: uncaught in page', + location: 'https://dapp.example/app.js:1:8', + uncaught: true, + }); + }); + + it('prefers the stack frame, and does not repeat a description in the text', () => { + const event: CdpEvent = { + target: SW, + method: 'Runtime.exceptionThrown', + params: { + exceptionDetails: { + text: 'Uncaught (in promise) boom', + exception: { type: 'string', value: 'boom' }, + stackTrace: { + callFrames: [{ url: SW.url, lineNumber: 1, columnNumber: 2 }], + }, + }, + }, + t: 50, + }; + expect(toConsoleRecord(event)?.record).toMatchObject({ + t: 50, + text: 'Uncaught (in promise) boom', + location: `${SW.url}:2:3`, + }); + }); + + it('does not drop a short exception value', () => { + const event: CdpEvent = { + target: SW, + method: 'Runtime.exceptionThrown', + params: { + exceptionDetails: { + text: 'Uncaught (in promise)', + exception: { type: 'string', value: 'e' }, + }, + }, + t: 50, + }; + expect(toConsoleRecord(event)?.record.text).toBe('Uncaught (in promise) e'); + }); + + it('handles an exception without details', () => { + const event: CdpEvent = { + target: SW, + method: 'Runtime.exceptionThrown', + params: {}, + t: 50, + }; + expect(toConsoleRecord(event)?.record).toStrictEqual({ + t: 50, + target: { kind: 'sw', id: 'W1', url: SW.url }, + level: 'error', + text: 'Uncaught', + uncaught: true, + }); + }); + + it('ignores other events and frames without a URL', () => { + expect( + toConsoleRecord({ + target: SW, + method: 'Network.dataReceived', + params: {}, + t: 1, + }), + ).toBeUndefined(); + const event: CdpEvent = { + target: SW, + method: 'Runtime.consoleAPICalled', + params: { type: 'error', stackTrace: { callFrames: [{}] } }, + t: 1, + }; + expect(toConsoleRecord(event)?.record.location).toBeUndefined(); + }); +}); + +describe('ConsoleSource', () => { + it('subscribes to the Runtime console events', async () => { + const { options } = await startSource(); + expect(options.events).toStrictEqual(CONSOLE_EVENTS); + }); + + it('records subscription errors in the buffer summary', async () => { + const { events, options } = await startSource(); + + options.onError?.( + new Error('Runtime.enable on page https://dapp.example/ timed out'), + ); + + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 1, + lastCaptureError: + 'Runtime.enable on page https://dapp.example/ timed out', + }); + }); + + it('records only errors by default, and more levels after configure', async () => { + const { events, emit } = await startSource(); + const now = Date.now() + 10; + emit( + consoleEvent('error', [{ type: 'string', value: 'e1' }], { + timestamp: now, + }), + ); + emit( + consoleEvent('warning', [{ type: 'string', value: 'w1' }], { + timestamp: now, + }), + ); + emit( + consoleEvent('assert', [{ type: 'string', value: 'a1' }], { + timestamp: now, + }), + ); + expect(readAll(events).map((record) => record.text)).toStrictEqual([ + 'e1', + 'a1', + ]); + + events.config = { consoleLevels: ['error', 'warning'] }; + emit( + consoleEvent('warning', [{ type: 'string', value: 'w2' }], { + timestamp: now + 1, + }), + ); + emit( + consoleEvent('log', [{ type: 'string', value: 'l1' }], { + timestamp: now + 1, + }), + ); + expect(readAll(events).map((record) => record.text)).toStrictEqual([ + 'e1', + 'a1', + 'w2', + ]); + }); + + it('drops replays: messages older than the source and repeated messages', async () => { + const { events, emit } = await startSource(); + const now = Date.now() + 10; + emit( + consoleEvent('error', [{ type: 'string', value: 'old' }], { + timestamp: now - 60_000, + }), + ); + const fresh = consoleEvent('error', [{ type: 'string', value: 'new' }], { + timestamp: now, + }); + emit(fresh); + emit(fresh); + // Same text on another target is kept. + emit( + consoleEvent('error', [{ type: 'string', value: 'new' }], { + timestamp: now, + target: PAGE, + }), + ); + // Without a CDP timestamp there is nothing to compare: kept. + emit(consoleEvent('error', [{ type: 'string', value: 'no-ts' }])); + emit(consoleEvent('error', [{ type: 'string', value: 'no-ts' }])); + + expect( + readAll(events).map((record) => `${record.target.kind}:${record.text}`), + ).toStrictEqual(['sw:new', 'page:new', 'sw:no-ts', 'sw:no-ts']); + }); + + it('remembers filtered messages, so widening the levels does not record them again', async () => { + const { events, emit } = await startSource(); + const now = Date.now() + 10; + const warning = consoleEvent('warning', [{ type: 'string', value: 'w' }], { + timestamp: now, + }); + // Filtered out, but its replay key is remembered. + emit(warning); + events.config = { consoleLevels: ['error', 'warning'] }; + // The same message again is a replay: not recorded. + emit(warning); + emit( + consoleEvent('warning', [{ type: 'string', value: 'w' }], { + timestamp: now + 1, + }), + ); + expect(readAll(events).map((record) => record.text)).toStrictEqual(['w']); + }); + + it('forgets the oldest remembered message past its limit', async () => { + const { events, emit } = await startSource(); + const now = Date.now() + 10; + const first = consoleEvent('error', [{ type: 'string', value: 'm0' }], { + timestamp: now, + }); + emit(first); + for (let index = 1; index <= 1000; index++) { + emit( + consoleEvent('error', [{ type: 'string', value: `m${index}` }], { + timestamp: now, + }), + ); + } + emit(first); + expect(events.buffer.summary().seq).toBe(1002); + }); +}); diff --git a/src/events/console-source.ts b/src/events/console-source.ts new file mode 100644 index 00000000..23fec1f5 --- /dev/null +++ b/src/events/console-source.ts @@ -0,0 +1,467 @@ +import { toRecordTarget } from './read-options.js'; +import { + isSensitiveQueryParam, + REDACTED_VALUE, + redactText, + redactUrl, +} from './redact.js'; +import type { SessionEventSource, SessionEvents } from './session-events.js'; +import type { + CdpEvent, + CdpManager, + CdpSubscription, +} from '../platform/cdp-manager.js'; +import type { ConsoleLevel, ConsoleRecord } from '../tools/types/events.js'; + +export const CONSOLE_EVENTS = [ + 'Runtime.consoleAPICalled', + 'Runtime.exceptionThrown', +] as const; + +/** Console levels recorded by default. */ +export const DEFAULT_CONSOLE_LEVELS: readonly ConsoleLevel[] = ['error']; + +/** Recent console messages remembered to drop replays. */ +const MAX_REMEMBERED_MESSAGES = 1000; + +type RemoteObjectPreviewProperty = { + name?: string; + type?: string; + subtype?: string; + value?: string; + valuePreview?: RemoteObjectPreview; +}; + +type RemoteObjectPreview = { + type?: string; + subtype?: string; + description?: string; + overflow?: boolean; + properties?: RemoteObjectPreviewProperty[]; +}; + +type RemoteObject = { + type?: string; + subtype?: string; + value?: unknown; + unserializableValue?: string; + description?: string; + preview?: RemoteObjectPreview; +}; + +type CallFrame = { url?: string; lineNumber?: number; columnNumber?: number }; + +type StackTrace = { callFrames?: CallFrame[] }; + +type ConsoleApiCalledParams = { + type?: string; + args?: RemoteObject[]; + timestamp?: number; + stackTrace?: StackTrace; +}; + +type ExceptionThrownParams = { + timestamp?: number; + exceptionDetails?: { + text?: string; + url?: string; + lineNumber?: number; + columnNumber?: number; + exception?: RemoteObject; + stackTrace?: StackTrace; + }; +}; + +/** + * Maps a `Runtime.consoleAPICalled` type to a recorded level. `assert` is + * an error; `dir`, `table`, `trace` and the like are `log`. + * + * @param type - The console call type. + * @returns The level. + */ +export function toConsoleLevel(type: string | undefined): ConsoleLevel { + switch (type) { + case 'error': + case 'assert': + return 'error'; + case 'warning': + case 'info': + case 'debug': + return type; + default: + return 'log'; + } +} + +/** + * Formats one preview property like DevTools: strings are quoted, primitives + * are written as they are, objects show their short description. A nested + * object with its own preview is formatted recursively, so its sensitive + * fields are redacted too. + * + * @param property - The property preview. + * @returns Its text. + */ +function formatPreviewProperty(property: RemoteObjectPreviewProperty): string { + if (property.valuePreview !== undefined) { + const nested = property.valuePreview; + if ((nested.properties?.length ?? 0) > 0 || nested.overflow === true) { + const text = formatPreview(nested); + if (text !== undefined) { + return text; + } + } + } + const value = property.value ?? ''; + switch (property.type) { + case 'string': + return `'${value}'`; + case 'undefined': + return 'undefined'; + case 'accessor': + return '(…)'; + case 'object': + if (property.subtype === 'array') { + return value === '' ? 'Array' : value; + } + // A nested plain object: DevTools shows `{…}` rather than `Object`. + return value === '' || value === 'Object' ? '{…}' : value; + case 'function': + if (value === '') { + return 'ƒ'; + } + return value.startsWith('ƒ') ? value : `ƒ ${value}`; + default: + return value; + } +} + +/** + * Checks whether a preview property name holds a secret. The query-parameter + * rules already include the body field names, so this covers `privateKey`, + * `password`, `token`, `key`, `*token`, `*key`, `*secret`, `seed`, `pass`, … + * with the shared allowlist (`publicKey`, `sortKey`, `sourceToken`, …). + * + * @param name - The property name. + * @returns True if the value must be redacted. + */ +function isSensitivePreviewName(name: string): boolean { + return isSensitiveQueryParam(name); +} + +/** + * Formats an object preview like DevTools: `{a: 1, b: 'x'}` for an object, + * `[1, 2]` for an array, with `…` when the preview overflowed. A property + * whose name is sensitive prints `[REDACTED]` instead of its value, at every + * nesting level and for the named properties of an array; a name that is not + * an array index prints as `name: value`, like DevTools. Console output is + * recorded and published, so a logged private key or mnemonic must not reach + * it. + * + * A plain string property is quoted as DevTools shows it; its contents are + * not scanned for secrets beyond the whole-text pass (`redactText`) that + * redacts URLs, JWTs and `Bearer` tokens afterwards. + * + * Only a plain object, an array and a proxy have their properties rendered. + * Other object subtypes show their description (`Map(2)`, `Date`, `RegExp`, + * `Uint8Array(2)`, `Error: boom`), whose values are not printed. + * + * @param preview - The CDP preview. + * @returns Its text, or undefined when the preview cannot be rendered. + */ +function formatPreview( + preview: RemoteObjectPreview | undefined, +): string | undefined { + if (preview === undefined) { + return undefined; + } + const properties = preview.properties ?? []; + const overflow = preview.overflow === true; + if (preview.subtype === 'array') { + const values = properties.map((property) => { + const name = property.name ?? ''; + // Numeric names are the elements; a named property (`a.privateKey`) + // prints with its name and is redacted when the name is sensitive. + if (/^\d*$/u.test(name)) { + return formatPreviewProperty(property); + } + const value = isSensitivePreviewName(name) + ? REDACTED_VALUE + : formatPreviewProperty(property); + return `${name}: ${value}`; + }); + if (overflow) { + values.push('…'); + } + return `[${values.join(', ')}]`; + } + // The description holds the useful summary, for example `Map(2)`, and no + // entry values: a secret stored in a Map, Set or a weak collection is + // never printed. + if (preview.subtype !== undefined && preview.subtype !== 'proxy') { + return preview.description; + } + if (preview.type !== 'object' && preview.type !== 'function') { + return preview.description; + } + if (properties.length === 0 && !overflow) { + return preview.description; + } + const fields = properties.map((property) => { + const name = property.name ?? '?'; + const value = isSensitivePreviewName(name) + ? REDACTED_VALUE + : formatPreviewProperty(property); + return `${name}: ${value}`; + }); + if (overflow) { + fields.push('…'); + } + return `{${fields.join(', ')}}`; +} + +/** + * Formats one console argument like DevTools does in a single line: the + * value of a primitive, the preview of an object, else its description. + * An `error` subtype keeps its description, which holds the stack. + * + * @param arg - The remote object. + * @returns Its text. + */ +function formatArg(arg: RemoteObject): string { + if (arg.unserializableValue !== undefined) { + return arg.unserializableValue; + } + switch (arg.type) { + case 'string': + return typeof arg.value === 'string' ? arg.value : ''; + case 'undefined': + return 'undefined'; + case 'number': + case 'boolean': + return String(arg.value as number | boolean); + default: + break; + } + if (arg.subtype === 'null') { + return 'null'; + } + if (arg.subtype === 'error' && arg.description !== undefined) { + return arg.description; + } + const preview = formatPreview(arg.preview); + if (preview !== undefined) { + return preview; + } + if (arg.description !== undefined) { + return arg.description; + } + return arg.value === undefined ? '' : JSON.stringify(arg.value); +} + +/** + * Formats the arguments of a console call like DevTools: a leading string is + * a format string, whose `%s`, `%d`, `%i`, `%f`, `%o`, `%O` and `%c` + * specifiers consume the following arguments (`%c` consumes and drops one, + * `%%` writes a literal `%`). Other arguments are appended, space-separated. + * + * @param args - The console arguments. + * @returns The text of the message. + */ +export function formatConsoleArgs(args: RemoteObject[]): string { + const [first, ...rest] = args; + if (first?.type !== 'string' || typeof first.value !== 'string') { + return args.map(formatArg).join(' '); + } + let consumed = 0; + const text = first.value.replace( + /%([%sdifoOc])/gu, + (match, specifier: string) => { + if (specifier === '%') { + return '%'; + } + const arg = rest[consumed]; + if (arg === undefined) { + return match; + } + consumed += 1; + if (specifier === 'c') { + return ''; + } + if (specifier === 'd' || specifier === 'i' || specifier === 'f') { + const raw = arg.unserializableValue ?? arg.value; + const number = typeof raw === 'number' ? raw : Number(raw); + if (!Number.isFinite(number)) { + return 'NaN'; + } + return specifier === 'f' ? String(number) : String(Math.trunc(number)); + } + return formatArg(arg); + }, + ); + return [text, ...rest.slice(consumed).map(formatArg)].join(' '); +} + +/** + * Builds the text of an uncaught exception: the Chrome prefix and the + * exception value, without repeating a value the prefix already ends with. + * + * @param prefix - The `exceptionDetails.text` of Chrome. + * @param description - The formatted exception value. + * @returns The text. + */ +function exceptionText( + prefix: string, + description: string | undefined, +): string { + if (description === undefined) { + return prefix; + } + const trimmed = prefix.trimEnd(); + if ( + trimmed === 'Uncaught' || + trimmed === 'Uncaught (in promise)' || + !trimmed.endsWith(description) + ) { + return `${trimmed} ${description}`; + } + return trimmed; +} + +/** + * Returns `url:line:column` (1-based) of the first frame with a URL. + * + * @param frame - The call frame. + * @returns The redacted location, or undefined without a URL. + */ +function formatLocation(frame: CallFrame | undefined): string | undefined { + if (!frame?.url) { + return undefined; + } + return `${redactUrl(frame.url)}:${(frame.lineNumber ?? 0) + 1}:${ + (frame.columnNumber ?? 0) + 1 + }`; +} + +/** + * Builds the console record of a CDP event, before level filtering. + * + * @param event - A `Runtime.consoleAPICalled` or `Runtime.exceptionThrown` + * event. + * @returns The record without its `seq`, and the CDP timestamp (epoch ms). + */ +export function toConsoleRecord( + event: CdpEvent, +): { record: Omit; timestamp?: number } | undefined { + const target = toRecordTarget(event.target); + if (event.method === 'Runtime.consoleAPICalled') { + const params = event.params as ConsoleApiCalledParams; + const location = formatLocation(params.stackTrace?.callFrames?.[0]); + return { + timestamp: params.timestamp, + record: { + t: Math.round(params.timestamp ?? event.t), + target, + level: toConsoleLevel(params.type), + text: redactText(formatConsoleArgs(params.args ?? [])), + ...(location === undefined ? {} : { location }), + }, + }; + } + if (event.method === 'Runtime.exceptionThrown') { + const params = event.params as ExceptionThrownParams; + const details = params.exceptionDetails ?? {}; + const description = + details.exception === undefined + ? undefined + : formatArg(details.exception); + const prefix = details.text ?? 'Uncaught'; + const text = exceptionText(prefix, description); + const location = formatLocation( + details.stackTrace?.callFrames?.[0] ?? + (details.url === undefined + ? undefined + : { + url: details.url, + lineNumber: details.lineNumber, + columnNumber: details.columnNumber, + }), + ); + return { + timestamp: params.timestamp, + record: { + t: Math.round(params.timestamp ?? event.t), + target, + level: 'error', + text: redactText(text), + ...(location === undefined ? {} : { location }), + uncaught: true, + }, + }; + } + return undefined; +} + +/** + * 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 ConsoleSource implements SessionEventSource { + 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. + * 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 events - The session's events. + * @param startedAt - When this source started, epoch ms. + */ + #onEvent(event: CdpEvent, events: SessionEvents, startedAt: number): void { + const built = toConsoleRecord(event); + if (built === undefined) { + return; + } + const { record, timestamp } = built; + if (timestamp !== undefined) { + if (timestamp < startedAt) { + return; + } + const key = `${record.target.id}\u0000${timestamp}\u0000${record.level}\u0000${record.text}`; + if (this.#remembered.has(key)) { + return; + } + this.#remembered.add(key); + if (this.#remembered.size > MAX_REMEMBERED_MESSAGES) { + const [oldest] = this.#remembered; + this.#remembered.delete(oldest); + } + } + if (!events.config.consoleLevels.includes(record.level)) { + return; + } + events.buffer.append('console', record); + } +} diff --git a/src/events/read-options.test.ts b/src/events/read-options.test.ts new file mode 100644 index 00000000..7b4ed3f8 --- /dev/null +++ b/src/events/read-options.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest'; + +import { parseSince, toRecordTarget } from './read-options.js'; + +describe('parseSince', () => { + it('reads epoch ms, digit strings and ISO dates', () => { + expect(parseSince(undefined)).toBeUndefined(); + expect(parseSince(42)).toBe(42); + expect(parseSince('1700000000000')).toBe(1700000000000); + expect(parseSince('2026-11-18T10:00:00.000Z')).toBe( + Date.parse('2026-11-18T10:00:00.000Z'), + ); + expect(parseSince('not a date')).toBeUndefined(); + }); +}); + +describe('toRecordTarget', () => { + it('renames targetId to id and redacts the URL', () => { + expect( + toRecordTarget({ + kind: 'page', + targetId: 'T', + url: 'https://a.example/?token=x', + }), + ).toStrictEqual({ + kind: 'page', + id: 'T', + url: 'https://a.example/?token=[REDACTED]', + }); + }); +}); diff --git a/src/events/read-options.ts b/src/events/read-options.ts new file mode 100644 index 00000000..552a3d80 --- /dev/null +++ b/src/events/read-options.ts @@ -0,0 +1,43 @@ +import { redactUrl } from './redact.js'; +import type { CdpEventTarget } from '../platform/cdp-manager.js'; +import type { EventRecordTarget } from '../tools/types/events.js'; + +/** Records a read returns when it gives no `limit`. */ +export const DEFAULT_EVENT_READ_LIMIT = 500; + +/** The largest `limit` a read accepts. */ +export const MAX_EVENT_READ_LIMIT = 2000; + +/** + * Parses a `since` value: epoch milliseconds (number or digits) or an ISO + * date. + * + * @param since - The value from the input. + * @returns Epoch milliseconds, or undefined when absent or not a date. + */ +export function parseSince( + since: number | string | undefined, +): number | undefined { + if (since === undefined) { + return undefined; + } + if (typeof since === 'number') { + return since; + } + if (/^\d+$/u.test(since)) { + return Number(since); + } + const parsed = Date.parse(since); + return Number.isNaN(parsed) ? undefined : parsed; +} + +/** + * Converts the target of a CDP event to the target of a record, with its + * URL redacted. + * + * @param target - The CDP event target. + * @returns The record target. + */ +export function toRecordTarget(target: CdpEventTarget): EventRecordTarget { + return { kind: target.kind, id: target.targetId, url: redactUrl(target.url) }; +} diff --git a/src/events/session-events.ts b/src/events/session-events.ts index 79ed8cfd..e06332d2 100644 --- a/src/events/session-events.ts +++ b/src/events/session-events.ts @@ -1,9 +1,11 @@ import type { BrowserContext } from '@playwright/test'; +import { ConsoleSource, DEFAULT_CONSOLE_LEVELS } from './console-source.js'; import { EventBuffer } from './event-buffer.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 { EventConfig } from '../tools/types/events.js'; import { debugWarn, extractErrorMessage } from '../utils'; /** @@ -39,6 +41,9 @@ export class SessionEvents { readonly context: BrowserContext; + /** What the sources record. Sources read it for each event. */ + config: EventConfig = { consoleLevels: [...DEFAULT_CONSOLE_LEVELS] }; + readonly #sources: SessionEventSource[]; #manager: CdpManager | undefined; @@ -153,7 +158,7 @@ export class SessionEvents { * @returns The sources. */ function createSources(): SessionEventSource[] { - return []; + return [new ConsoleSource()]; } const sessions = new WeakMap(); diff --git a/src/tools/events.test.ts b/src/tools/events.test.ts index c585c318..3e971816 100644 --- a/src/tools/events.test.ts +++ b/src/tools/events.test.ts @@ -8,7 +8,11 @@ import { getSessionEvents } from '../events/session-events.js'; import type { ToolContext } from '../types/http.js'; vi.mock('../platform/cdp-manager.js', () => ({ - getCdpManager: vi.fn().mockReturnValue({}), + getCdpManager: vi.fn().mockReturnValue({ + subscribe: vi.fn().mockResolvedValue({ unsubscribe: vi.fn() }), + on: vi.fn(), + off: vi.fn(), + }), })); /** diff --git a/src/tools/logs.test.ts b/src/tools/logs.test.ts new file mode 100644 index 00000000..a6456013 --- /dev/null +++ b/src/tools/logs.test.ts @@ -0,0 +1,156 @@ +import type { BrowserContext } from '@playwright/test'; +import { describe, expect, it, vi } from 'vitest'; + +import { logsTool } from './logs.js'; +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 { ToolContext } from '../types/http.js'; + +vi.mock('../platform/cdp-manager.js', () => ({ + getCdpManager: vi.fn().mockReturnValue({ + subscribe: vi.fn().mockResolvedValue({ unsubscribe: vi.fn() }), + }), +})); + +const TARGET = { + kind: 'sw' as const, + id: 'W', + url: 'chrome-extension://x/bg.js', +}; + +/** + * Builds a tool context around a fake browser context. + * + * @param hasActive - Whether a session is active. + * @returns The context and its browser context. + */ +function createContext(hasActive = true): { + context: ToolContext; + browserContext: BrowserContext; +} { + const browserContext = {} as BrowserContext; + const sessionManager = createMockSessionManager({ hasActive }); + sessionManager.getContext.mockReturnValue(browserContext); + return { + context: { sessionManager } as unknown as ToolContext, + browserContext, + }; +} + +describe('logsTool', () => { + it('fails without a session', async () => { + const { context } = createContext(false); + expect(await logsTool({}, context)).toMatchObject({ + ok: false, + error: { code: ErrorCodes.MM_NO_ACTIVE_SESSION }, + }); + }); + + it('reads console records with cursor, since, limit and grep', async () => { + const { context, browserContext } = createContext(); + const { buffer } = getSessionEvents(browserContext); + buffer.append('console', { + t: 100, + target: TARGET, + level: 'error', + text: 'alpha failed', + }); + buffer.append('network', { t: 150, target: TARGET }); + buffer.append('console', { + t: 200, + target: TARGET, + level: 'error', + text: 'beta failed', + }); + buffer.append('console', { + t: 300, + target: TARGET, + level: 'error', + text: 'alpha again', + }); + + const all = await logsTool({}, context); + expect(all).toMatchObject({ + ok: true, + result: { + cursor: 4, + hasMore: false, + gap: false, + summary: { seq: 4, counts: { console: 3, network: 1 } }, + }, + }); + + const grep = await logsTool({ grep: '^alpha', limit: 1 }, context); + expect(grep).toMatchObject({ + ok: true, + result: { + records: [{ seq: 1, text: 'alpha failed' }], + cursor: 1, + hasMore: true, + }, + }); + + const since = await logsTool({ since: '200', cursor: 3 }, context); + expect(since).toMatchObject({ + ok: true, + result: { records: [{ seq: 4 }], cursor: 4, hasMore: false }, + }); + + const iso = await logsTool( + { since: new Date(250).toISOString(), action: 'read' }, + context, + ); + expect(iso.ok && iso.result).toMatchObject({ records: [{ seq: 4 }] }); + }); + + it('rejects an invalid grep', async () => { + const { context } = createContext(); + expect(await logsTool({ grep: '(' }, context)).toMatchObject({ + ok: false, + error: { code: ErrorCodes.MM_INVALID_INPUT }, + }); + }); + + it('accepts a pattern that is only valid without the u flag', async () => { + const { context, browserContext } = createContext(); + const { buffer } = getSessionEvents(browserContext); + buffer.append('console', { + t: 100, + target: TARGET, + level: 'error', + text: 'foo-bar failed', + }); + const result = await logsTool({ grep: 'foo\\-bar' }, context); + expect(result).toMatchObject({ + ok: true, + result: { records: [{ text: 'foo-bar failed' }] }, + }); + }); + + it('rejects a grep pattern longer than 256 characters', async () => { + const { context } = createContext(); + expect(await logsTool({ grep: 'x'.repeat(257) }, context)).toMatchObject({ + ok: false, + error: { code: ErrorCodes.MM_INVALID_INPUT }, + }); + }); + + it('configure changes the recorded levels', async () => { + const { context, browserContext } = createContext(); + const events = getSessionEvents(browserContext); + expect(events.config.consoleLevels).toStrictEqual(['error']); + + const result = await logsTool( + { action: 'configure', levels: ['error', 'warning', 'error'] }, + context, + ); + + expect(result).toMatchObject({ + ok: true, + result: { action: 'configure', config: { levels: ['error', 'warning'] } }, + }); + expect(events.config.consoleLevels).toStrictEqual(['error', 'warning']); + }); +}); diff --git a/src/tools/logs.ts b/src/tools/logs.ts new file mode 100644 index 00000000..9bdd0e34 --- /dev/null +++ b/src/tools/logs.ts @@ -0,0 +1,85 @@ +import type { ConsoleRecord, LogsInput, LogsResult } from './types'; +import { ErrorCodes } from './types/errors.js'; +import { + createToolError, + createToolSuccess, + requireActiveSession, +} from './utils.js'; +import { + DEFAULT_EVENT_READ_LIMIT, + parseSince, +} from '../events/read-options.js'; +import { getSessionEvents } from '../events/session-events.js'; +import type { ToolContext, ToolResponse } from '../types/http.js'; + +/** Longest accepted `--grep` pattern, to bound regular-expression work. */ +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`). + * + * @param input - Read options, or the `configure` action. + * @param context - The tool execution context. + * @returns A page of console records, or the new config. + */ +export async function logsTool( + input: LogsInput, + context: ToolContext, +): Promise> { + const missingSession = requireActiveSession(context); + if (missingSession) { + return missingSession; + } + + const events = getSessionEvents(context.sessionManager.getContext()); + await events.ensureStarted(); + + if (input.action === 'configure') { + events.config = { + ...events.config, + consoleLevels: [...new Set(input.levels)], + }; + return createToolSuccess({ + action: 'configure', + config: { levels: [...events.config.consoleLevels] }, + summary: events.buffer.summary(), + }); + } + + let grep: RegExp | undefined; + if (input.grep !== undefined) { + if (input.grep.length > MAX_GREP_PATTERN_LENGTH) { + return createToolError( + ErrorCodes.MM_INVALID_INPUT, + `Invalid --grep pattern: longer than ${MAX_GREP_PATTERN_LENGTH} characters`, + ); + } + try { + grep = new RegExp(input.grep, 'u'); + } catch { + try { + // Not valid in unicode mode (for example `foo\-bar`): the same + // JavaScript regular expression without `u` is accepted. + // eslint-disable-next-line require-unicode-regexp -- The fallback exists for patterns that `u` rejects. + grep = new RegExp(input.grep); + } catch (error) { + return createToolError( + ErrorCodes.MM_INVALID_INPUT, + `Invalid --grep pattern: ${(error as Error).message}`, + ); + } + } + } + + return createToolSuccess( + events.buffer.read({ + kind: 'console', + cursor: input.cursor, + since: parseSince(input.since), + limit: input.limit ?? DEFAULT_EVENT_READ_LIMIT, + filter: grep ? (record): boolean => grep.test(record.text) : undefined, + }), + ); +} diff --git a/src/tools/platform-gating.test.ts b/src/tools/platform-gating.test.ts index 9637e292..cac2c162 100644 --- a/src/tools/platform-gating.test.ts +++ b/src/tools/platform-gating.test.ts @@ -15,6 +15,7 @@ describe('isBrowserOnlyTool', () => { expect(isBrowserOnlyTool('clipboard')).toBe(true); expect(isBrowserOnlyTool('mock_network')).toBe(true); expect(isBrowserOnlyTool('events')).toBe(true); + expect(isBrowserOnlyTool('logs')).toBe(true); expect(isBrowserOnlyTool('reload')).toBe(true); expect(isBrowserOnlyTool('build')).toBe(true); expect(isBrowserOnlyTool('inspect')).toBe(true); diff --git a/src/tools/registry.test.ts b/src/tools/registry.test.ts index a26f9595..665ec2df 100644 --- a/src/tools/registry.test.ts +++ b/src/tools/registry.test.ts @@ -23,6 +23,7 @@ describe('toolRegistry', () => { 'clipboard', 'mock_network', 'events', + 'logs', 'run_steps', 'cdp', 'hermes_targets', @@ -42,7 +43,7 @@ describe('toolRegistry', () => { }); it('has the expected number of entries', () => { - expect(toolRegistry.size).toBe(50); + expect(toolRegistry.size).toBe(51); }); it('stores only functions as values', () => { @@ -96,9 +97,12 @@ describe('TOOL_CATEGORIES and getToolCategory', () => { }, ); - it('getToolCategory returns readonly for events', () => { - expect(getToolCategory('events')).toBe('readonly'); - }); + it.each(['events', 'logs'])( + 'getToolCategory returns readonly for %s', + (toolName) => { + expect(getToolCategory(toolName)).toBe('readonly'); + }, + ); it('getToolCategory returns readonly for get_context', () => { expect(getToolCategory('get_context')).toBe('readonly'); @@ -130,6 +134,7 @@ describe('isBrowserOnlyTool', () => { 'clipboard', 'mock_network', 'events', + 'logs', 'reload', 'build', 'inspect', diff --git a/src/tools/registry.ts b/src/tools/registry.ts index 581d7c6a..ce2250b5 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -39,6 +39,7 @@ import { waitForTool, } from './interaction.js'; import { launchTool } from './launch.js'; +import { logsTool } from './logs.js'; import { mockNetworkTool } from './mock-network.js'; import { closeTabTool, @@ -100,6 +101,7 @@ export const toolRegistry = new Map>([ ['get_window_size', getWindowSizeTool], ['mock_network', mockNetworkTool], ['events', eventsTool], + ['logs', logsTool], ['scroll_to_element', scrollToElementTool], ['device_swipe', deviceSwipeTool], ['long_press', longPressTool], @@ -167,7 +169,7 @@ export const TOOL_CATEGORIES: Record = { press_button: 'mutating', device_context: 'mutating', device_clipboard: 'mutating', - // READONLY (14) + // READONLY (15) hermes_targets: 'readonly', get_window_size: 'readonly', get_alert_text: 'readonly', @@ -186,6 +188,7 @@ export const TOOL_CATEGORIES: Record = { get_contract_address: 'readonly', // `events clear` empties the session event buffer; it never touches the UI. events: 'readonly', + logs: 'readonly', // DISCOVERY (4) describe_screen: 'discovery', list_testids: 'discovery', @@ -217,6 +220,7 @@ const BROWSER_ONLY_TOOLS = new Set([ 'clipboard', 'mock_network', 'events', + 'logs', 'reload', 'build', 'inspect', diff --git a/src/tools/types/events.ts b/src/tools/types/events.ts index 70a285eb..2a6b0221 100644 --- a/src/tools/types/events.ts +++ b/src/tools/types/events.ts @@ -67,3 +67,24 @@ export type EventPage = { gap: boolean; summary: EventSummary; }; + +/** Console levels `mm logs` can record. */ +export type ConsoleLevel = 'error' | 'warning' | 'info' | 'log' | 'debug'; + +/** A console message or uncaught exception (`mm logs`). */ +export type ConsoleRecord = EventRecordBase & { + /** `console.assert` is `error`; `dir`, `table`, `trace` are `log`. */ + level: ConsoleLevel; + /** The message, redacted and cut at 2000 characters. */ + text: string; + /** `url:line:column` (1-based) of the call or the throw, when known. */ + location?: string; + /** An uncaught exception, not a console call. */ + uncaught?: true; +}; + +/** What the session records. Changed by `configure`, from then on. */ +export type EventConfig = { + /** Console levels to record. Default `['error']`. */ + consoleLevels: ConsoleLevel[]; +}; diff --git a/src/tools/types/tool-inputs.ts b/src/tools/types/tool-inputs.ts index 9e29b029..685fcbf0 100644 --- a/src/tools/types/tool-inputs.ts +++ b/src/tools/types/tool-inputs.ts @@ -1,4 +1,4 @@ -import type { EventKind } from './events.js'; +import type { ConsoleLevel, EventKind } from './events.js'; import type { SmartContractName } from './seeding.js'; export type TabRole = 'extension' | 'notification' | 'dapp' | 'other'; @@ -313,6 +313,27 @@ export type MockNetworkInput = includeBodies?: boolean; }; +/** Read options shared by `mm logs` and `mm network`. */ +export type EventReadInput = { + /** Only records after this cursor (from `mm events mark` or an earlier read). */ + cursor?: number; + /** Only records at or after this time: epoch ms, or an ISO date. */ + since?: number | string; + /** Maximum records (default 500, max 2000). */ + limit?: number; +}; + +export type LogsInput = + | ({ + action?: 'read'; + /** + * Only messages whose text matches this case-sensitive JavaScript + * regular expression (at most 256 characters). + */ + grep?: string; + } & EventReadInput) + | { action: 'configure'; levels: ConsoleLevel[] }; + export type EventsInput = | { action: 'mark' } | { action: 'clear'; kind?: EventKind }; diff --git a/src/tools/types/tool-outputs.ts b/src/tools/types/tool-outputs.ts index 3b95fa3e..6cc1532e 100644 --- a/src/tools/types/tool-outputs.ts +++ b/src/tools/types/tool-outputs.ts @@ -1,5 +1,11 @@ import type { TestIdItem, A11yNodeTrimmed } from './discovery.js'; -import type { EventKind, EventSummary } from './events.js'; +import type { + ConsoleLevel, + ConsoleRecord, + EventKind, + EventPage, + EventSummary, +} from './events.js'; import type { NetworkMockRequestRecord, NetworkMockRouteRule, @@ -299,6 +305,14 @@ export type EventsResult = summary: EventSummary; }; +export type LogsResult = + | EventPage + | { + action: 'configure'; + config: { levels: ConsoleLevel[] }; + summary: EventSummary; + }; + export type SetContextResult = { previousContext: 'e2e' | 'prod'; newContext: 'e2e' | 'prod'; diff --git a/src/validation/schemas.test.ts b/src/validation/schemas.test.ts index b1c5b521..4ac93cca 100644 --- a/src/validation/schemas.test.ts +++ b/src/validation/schemas.test.ts @@ -20,6 +20,7 @@ import { networkMockRouteRuleSchema, mockNetworkInputSchema, eventsInputSchema, + logsInputSchema, launchInputSchema, scrollToElementInputSchema, clickInputSchema, @@ -562,6 +563,65 @@ describe('eventsInputSchema', () => { }); }); +describe('logsInputSchema', () => { + it('accepts reads and configure', () => { + expect(logsInputSchema.safeParse({}).success).toBe(true); + expect( + logsInputSchema.safeParse({ + action: 'read', + cursor: 0, + since: '2026-11-18T10:00:00Z', + limit: 2000, + grep: 'x', + }).success, + ).toBe(true); + expect(logsInputSchema.safeParse({ since: 5 }).success).toBe(true); + expect(logsInputSchema.safeParse({ since: '123' }).success).toBe(true); + expect( + logsInputSchema.safeParse({ action: 'configure', levels: ['warning'] }) + .success, + ).toBe(true); + expect( + logsInputSchema.safeParse({ + action: 'configure', + levels: ['warn', 'error'], + }), + ).toMatchObject({ success: true, data: { levels: ['warning', 'error'] } }); + }); + + it('accepts observe through the tool schema', () => { + expect( + toolSchemas.logs.safeParse({ grep: 'x', observe: 'full' }).success, + ).toBe(true); + expect( + toolSchemas.logs.safeParse({ + action: 'configure', + levels: ['error'], + observe: 'diff', + }).success, + ).toBe(true); + }); + + it('rejects bad reads and configure', () => { + expect(logsInputSchema.safeParse({ since: 'yesterday' }).success).toBe( + false, + ); + expect(logsInputSchema.safeParse({ limit: 2001 }).success).toBe(false); + expect(logsInputSchema.safeParse({ cursor: -1 }).success).toBe(false); + expect(logsInputSchema.safeParse({ url: 'x' }).success).toBe(false); + expect(logsInputSchema.safeParse({ grep: 'x'.repeat(257) }).success).toBe( + false, + ); + expect( + logsInputSchema.safeParse({ action: 'configure', levels: [] }).success, + ).toBe(false); + expect( + logsInputSchema.safeParse({ action: 'configure', levels: ['verbose'] }) + .success, + ).toBe(false); + }); +}); + describe('launchInputSchema', () => { it('preserves platform field', () => { const input = { platform: 'ios' }; diff --git a/src/validation/schemas.ts b/src/validation/schemas.ts index 37016867..3132fd33 100644 --- a/src/validation/schemas.ts +++ b/src/validation/schemas.ts @@ -862,6 +862,86 @@ export const eventsInputSchema = z.discriminatedUnion('action', [ .strict(), ]); +const eventReadFields = { + cursor: z + .number() + .int() + .min(0) + .describe( + 'Only records after this cursor (from events mark, or the cursor of an earlier read)', + ) + .optional(), + since: z + .union([ + z.number().int().min(0), + z + .string() + .refine( + (value) => /^\d+$/u.test(value) || !Number.isNaN(Date.parse(value)), + { message: 'since must be epoch milliseconds or an ISO date' }, + ), + ]) + .describe('Only records at or after this time: epoch ms or an ISO date') + .optional(), + limit: z + .number() + .int() + .min(1) + .max(2000) + .describe( + 'Maximum records (default 500), oldest first; read again with the returned cursor while hasMore', + ) + .optional(), +}; + +export const consoleLevelSchema = z.enum([ + 'error', + 'warning', + 'info', + 'log', + 'debug', +]); + +// `warn` is the name Chrome uses in a few places; accept it as `warning`. +const consoleLevelInputSchema = z.union([ + consoleLevelSchema, + z.literal('warn').transform((): 'warning' => 'warning'), +]); + +export const logsInputSchema = z.union([ + z + .object({ + action: z.literal('read').optional(), + ...eventReadFields, + // Declared here as well as by `withObserve`: on zod 4.4 (our minimum), + // a strict union member intersected with the observe object rejects + // `observe` instead of merging it. + observe: observeLevelSchema.optional(), + grep: z + .string() + .min(1) + .max(256) + .describe( + 'Only messages whose text matches this case-sensitive JavaScript ' + + 'regular expression (at most 256 characters)', + ) + .optional(), + }) + .strict(), + z + .object({ + action: z.literal('configure'), + observe: observeLevelSchema.optional(), + levels: z + .array(consoleLevelInputSchema) + .min(1) + .describe( + 'Console levels to record from now on (default: error); `warn` is accepted as `warning`', + ), + }) + .strict(), +]); + export const cdpInputSchema = z.object({ method: z .string() @@ -1120,6 +1200,7 @@ export type CdpInputZ = z.infer; export type HermesTargetsInputZ = z.infer; export type MockNetworkInputZ = z.infer; export type EventsInputZ = z.infer; +export type LogsInputZ = z.infer; export type ScrollToElementInputZ = z.infer; export type DeviceSwipeInputZ = z.infer; export type LongPressInputZ = z.infer; @@ -1174,6 +1255,7 @@ export const toolSchemas = { get_window_size: withObserve(getWindowSizeInputSchema), mock_network: withObserve(mockNetworkInputSchema), events: withObserve(eventsInputSchema), + logs: withObserve(logsInputSchema), scroll_to_element: withObserve(scrollToElementInputSchema), device_swipe: withObserve(deviceSwipeInputSchema), long_press: withObserve(longPressInputSchema),