Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions README.md

Large diffs are not rendered by default.

60 changes: 58 additions & 2 deletions SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, logs, 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, network, 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` |
Expand Down Expand Up @@ -759,7 +759,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. 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. 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 <n> | --since <iso|epoch-ms>] [--limit <n>] [--grep <regex>]`

Expand All @@ -784,6 +784,62 @@ Console errors and uncaught exceptions of every page and the Extension service w

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 <list>`: any other flag or a second `--levels` is a usage error.

#### `mm network [--cursor <n> | --since <iso|epoch-ms>] [--limit <n>] [--url <glob|text>] [--errors] [--settled]`

HTTP(S) requests of every page and the Extension service worker (gas, security alerts, bridge, RPC: most Extension traffic comes from the worker). 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 or worker goes away before it ends is finalized with `failure: "target closed"`; one dropped from the pending limit is finalized with `failure: "abandoned"`.

```json
{
"seq": 6,
"settledSeq": 11,
"t": 1795430400608,
"target": {
"kind": "sw",
"id": "A51F9577…",
"url": "chrome-extension://…/scripts/app-init.js"
},
"method": "POST",
"url": "https://mainnet.infura.io/v3/[REDACTED]",
"type": "fetch",
"status": 200,
"ms": 42,
"rpcMethods": ["eth_call"],
"rpcError": { "code": -32000, "message": "execution reverted" }
}
```

| Field | Description |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `settledSeq` | Position when the request became final: it ended, with its `rpcError` read when configured. Absent while pending |
| `t` | Request start, epoch ms |
| `url` | Redacted: API keys in the host or path (such as Infura IDs), credentials, and `key`/`token`/`apiKey`-like params |
| `type` | `fetch`, `xhr`, `document`, `script`, … |
| `status` | HTTP status. Absent while pending and when the request failed before a response; a request that fails after its response keeps it |
| `ms` | Start to end of the response or the failure. Absent while pending |
| `failure` | Set when the request fails, before or after its response: for example `net::ERR_ABORTED`, `net::ERR_NAME_NOT_RESOLVED`, `net::ERR_FAILED (cors: …)`, `target closed`, or `abandoned` |
| `rpcMethods` | JSON-RPC methods of the request body; always an array (a batch lists its methods in order) |
| `rpcError` | `{ code, message }` of a JSON-RPC error response. Only after `mm network configure --rpc-errors` |

`--url` takes a glob (`*`, `**`) or plain text the URL must contain. `--errors` keeps status >= 400, `failure` and `rpcError`. Only `http(s)` requests are recorded (`stats.ignored` counts the rest). A redirect gives one record per hop.

An unfiltered read returns every record in start order (`seq`), pending requests included, and the cursor moves past all of them. A filtered read (`--url`, `--errors`) returns only **settled** requests, in `settledSeq` order: a request may become a match only when it ends (a 404, a failure, an `rpcError`), so it is returned by the read that follows its end, once, even when it started before the cursor. `--settled` asks for that same settle-order read without a filter: at the end of a step, read `--settled --cursor <mark>` to get the final status of every request that finished since the mark, including ones started earlier; requests still open are not returned yet. An unsettled request is never returned by a filtered or `--settled` read, so a request that never ends never matches one. In every case `--since` compares the request start (`t`), not when it ended. A cursor from a filtered or `--settled` read continues reads of the same mode; for an unfiltered read, use a cursor from `mm events mark` or an unfiltered read.

`mm network configure --rpc-errors` reads the body of each JSON-RPC response (up to 64 KiB decoded, at most 8 at a time) and records its `error`; `stats.rpcErrorsSkipped` counts the bodies that were too large, too many at once or gone. The decoded size comes from `Network.dataReceived` when Chrome reports it; without those events the compressed `encodedDataLength` is used, which can undercount. `Network.enable` gets small response-buffer limits, since no bodies are kept otherwise. `--no-rpc-errors` turns it off.

The session holds `Network` and `Runtime` enabled on every page and on the service worker from `mm launch` on. `mm cdp Network.enable` (no params) still succeeds and sends nothing; `mm cdp Network.disable`, or a `Network.enable` with other params, is refused with `MM_CDP_BLOCKED`, because it would stop or change what `mm network` records. Use `--fresh` for those.

#### Per-flow recipe

```bash
mm events mark # {"cursor":120,"summary":{"startedAt":1795430400000,...}}
# ...run the flow...
mm network --settled --cursor 120 # final status of every request that ended since the mark
mm network --cursor 120 # repeat with the returned cursor while hasMore is true
mm logs --cursor 120
```

Compare `summary.startedAt` of each read with the one from `mark`. If it changed, the session was relaunched: read again from `--cursor 0` and record a capture gap for the flow. Also record a gap when a read returns `gap: true`. Requests sent during `mm launch` itself are not recorded.

### Mobile device actions (iOS/Android only)

These commands require a mobile session (`mm launch --platform ios|android`). On a browser
Expand Down
70 changes: 70 additions & 0 deletions src/cli/mm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1059,6 +1059,7 @@ describe('printHelp', () => {
expect(output).toContain('MM_PRETTY');
expect(output).toContain('mm events mark');
expect(output).toContain('mm logs configure --levels');
expect(output).toContain('mm network configure --rpc-errors');
});
});

Expand Down Expand Up @@ -3236,6 +3237,7 @@ describe('routeCommand', () => {
[['--grep', '--cursor', '1']],
[['--grap', 'x']],
[['--levels', 'warning']],
[['--error']],
[['configure']],
[['configure', '--levels', ',']],
[['configure', '--levels', 'warning', '--cursor', '1']],
Expand All @@ -3249,6 +3251,74 @@ describe('routeCommand', () => {
expectFailure(expect.stringContaining('Usage: mm logs'), 2);
});

it('routes network with read flags', async () => {
await routeCommand(
'network',
[
'--cursor',
'3',
'--url',
'https://*.api.cx.metamask.io/**',
'--errors',
'--settled',
'--since',
'1700000000000',
],
3000,
);
expect(globalThis.fetch).toHaveBeenLastCalledWith(
'http://127.0.0.1:3000/tool/network',
expect.objectContaining({
body: JSON.stringify({
cursor: 3,
url: 'https://*.api.cx.metamask.io/**',
errors: true,
settled: true,
since: '1700000000000',
}),
}),
);
await routeCommand('network', [], 3000);
expect(globalThis.fetch).toHaveBeenLastCalledWith(
'http://127.0.0.1:3000/tool/network',
expect.objectContaining({ body: JSON.stringify({}) }),
);
});

it('routes network configure', async () => {
await routeCommand('network', ['configure', '--rpc-errors'], 3000);
expect(globalThis.fetch).toHaveBeenLastCalledWith(
'http://127.0.0.1:3000/tool/network',
expect.objectContaining({
body: JSON.stringify({ action: 'configure', rpcErrors: true }),
}),
);
await routeCommand('network', ['configure', '--no-rpc-errors'], 3000);
expect(globalThis.fetch).toHaveBeenLastCalledWith(
'http://127.0.0.1:3000/tool/network',
expect.objectContaining({
body: JSON.stringify({ action: 'configure', rpcErrors: false }),
}),
);
});

it.each([
[['--url']],
[['--cursor', 'abc']],
[['--error']],
[['--errors', 'true']],
[['--settled', 'true']],
[['configure']],
[['configure', '--rpc-errors', '--no-rpc-errors']],
[['configure', '--rpc-errors', 'extra']],
[['requests']],
])('exits on bad network arguments %j', async (args) => {
await expect(routeCommand('network', args, 3000)).rejects.toThrowError(
'process.exit',
);
expectFailure(expect.stringContaining('Usage: mm network'), 2);
});

it('exits when mock-network has an unknown action', async () => {
await expect(
routeCommand('mock-network', ['unknown'], 3000),
Expand Down
76 changes: 71 additions & 5 deletions src/cli/mm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1019,6 +1019,10 @@ export async function routeCommand(
await routeLogsCommand(args, daemon);
break;
}
case 'network': {
await routeNetworkCommand(args, daemon);
break;
}
case 'cdp': {
const cdpMethod = args[0];
if (!cdpMethod) {
Expand Down Expand Up @@ -1372,28 +1376,38 @@ const LOGS_USAGE =
' mm logs configure --levels <error,warning,info,log,debug>';

/**
* Parses the read flags shared by `mm logs` and `mm network`.
* Parses the read flags shared by `mm logs` and `mm network`. Unknown flags,
* missing values and stray arguments are usage errors.
*
* @param args - CLI arguments.
* @param usage - The usage text to print on a bad flag.
* @param stringFlags - Extra flags that take a string value.
* @param booleanFlags - Extra flags that take no value.
* @returns The read options for the tool.
*/
export function parseEventReadArgs(
args: string[],
usage: string,
stringFlags: readonly string[] = [],
booleanFlags: readonly string[] = [],
): Record<string, unknown> {
const integerFlags = new Set(['--cursor', '--limit']);
const textFlags = new Set(['--since', ...stringFlags]);
const booleans = new Set(booleanFlags);
const options: Record<string, unknown> = {};
// 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) {
// Every flag takes one value, or none for a boolean flag. Reject anything
// else: a mistyped flag must not be silently ignored.
for (let index = 0; index < args.length; index += 1) {
const flag = args[index];
if (flag === undefined) {
failUsage(usage);
}
if (booleans.has(flag)) {
options[flag.slice(2)] = true;
continue;
}
const value = args[index + 1];
if (
flag === undefined ||
(!integerFlags.has(flag) && !textFlags.has(flag)) ||
value === undefined ||
value.startsWith('--')
Expand All @@ -1410,6 +1424,7 @@ export function parseEventReadArgs(
} else {
options[flag.slice(2)] = value;
}
index += 1;
}
return options;
}
Expand Down Expand Up @@ -1458,6 +1473,49 @@ export async function routeLogsCommand(
);
}

const NETWORK_USAGE =
'Usage: mm network [--cursor <n> | --since <iso|epoch-ms>] [--limit <n>] [--url <glob|text>] [--errors] [--settled]\n' +
' mm network configure --rpc-errors | --no-rpc-errors';

/**
* Routes `mm network` to the daemon.
*
* @param args - CLI arguments after `network`.
* @param daemon - The daemon endpoint (a port or the daemon state).
*/
export async function routeNetworkCommand(
args: string[],
daemon: DaemonEndpoint,
): Promise<void> {
if (args[0] === 'configure') {
const rest = args.slice(1);
const on = rest.length === 1 && rest[0] === '--rpc-errors';
const off = rest.length === 1 && rest[0] === '--no-rpc-errors';
if (on === off) {
failUsage(NETWORK_USAGE);
}
await sendRequest(daemon, 'POST', '/tool/network', {
action: 'configure',
rpcErrors: on,
});
return;
}
if (args[0] !== undefined && !args[0].startsWith('--')) {
failUsage(NETWORK_USAGE);
}
await sendRequest(
daemon,
'POST',
'/tool/network',
parseEventReadArgs(
args,
NETWORK_USAGE,
['--url'],
['--errors', '--settled'],
),
);
}

/**
* Checks whether a failed request is safe to send again: only a refused
* connection (`ECONNREFUSED`), because the daemon never accepted the request.
Expand Down Expand Up @@ -2361,6 +2419,14 @@ Session events (browser only; recorded from launch on, not during it):
again with the returned cursor while hasMore.
mm logs configure --levels <error,warning,info,log,debug>
Levels to record from now on (default: error).
mm network [--cursor <n> | --since <iso|epoch-ms>] [--limit <n>] [--url <glob|text>] [--errors] [--settled]
HTTP(S) requests of every page and the Extension
service worker: status, ms, failure, rpcMethods.
--errors: status >= 400, failure or rpcError.
--settled: only requests that ended after the cursor,
in settle order (no filter needed).
mm network configure --rpc-errors | --no-rpc-errors
Read JSON-RPC response bodies for rpcError (off).

Mobile (iOS/Android only):
mm device-swipe <up|down|left|right> [--startX <n>] [--startY <n>] [--distance <n>]
Expand Down
2 changes: 1 addition & 1 deletion src/events/console-source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ describe('ConsoleSource', () => {
'a1',
]);

events.config = { consoleLevels: ['error', 'warning'] };
events.config = { consoleLevels: ['error', 'warning'], rpcErrors: false };
emit(
consoleEvent('warning', [{ type: 'string', value: 'w2' }], {
timestamp: now + 1,
Expand Down
Loading
Loading