mcp-browser-dev-tools 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  exportHarLikeSummary,
3
3
  filterConsoleMessages,
4
+ InFlightRequests,
4
5
  summarizeNetworkRequests,
5
6
  } from "./session-events.mjs";
6
7
  import { DEFAULT_FIREFOX_BIDI_WS_URL } from "./config.mjs";
@@ -9,9 +10,43 @@ import { waitForPageCondition } from "./wait-for.mjs";
9
10
  import {
10
11
  assertEnabled,
11
12
  assertPointerTarget,
13
+ buildInputRecorderExpression,
12
14
  buildPageContextExpression,
13
15
  } from "./page-context.mjs";
14
16
  import { buildBidiKeyActions, buildBidiTextActions } from "./keyboard.mjs";
17
+ import { sendCheckedInput } from "./input-delivery.mjs";
18
+ import {
19
+ applyNetworkOptions,
20
+ describeNetworkState,
21
+ inNetworkTurn,
22
+ mockHeaders,
23
+ takeMatchingRule,
24
+ throttled,
25
+ } from "./network-control.mjs";
26
+ import {
27
+ FrameKeys,
28
+ probeScope,
29
+ addFrameSnapshots,
30
+ frameElementSnapshot,
31
+ parseFrameRef,
32
+ restoreFrameSelector,
33
+ shiftFramePoints,
34
+ unknownFrame,
35
+ takeFileTarget,
36
+ assertFileInput,
37
+ uploadResult,
38
+ describePointer,
39
+ dragEnd,
40
+ dragPath,
41
+ pointerFields,
42
+ takeNextRef,
43
+ wheelScroll,
44
+ } from "./page-context.mjs";
45
+
46
+ const MOUSE_BUTTON_NUMBERS = { left: 0, middle: 1, right: 2 };
47
+ // Each step of a drag takes this long, so the page sees the moves as a
48
+ // gesture rather than one jump.
49
+ const DRAG_MOVE_MS = 16;
15
50
 
16
51
  const POINTER_SOURCE = {
17
52
  type: "pointer",
@@ -28,6 +63,22 @@ function pointerMove(point) {
28
63
  };
29
64
  }
30
65
 
66
+ // The point to send input to: in the frame's own viewport for an element
67
+ // in a frame, else in the top page's.
68
+ function inputPoint(resolved) {
69
+ return resolved.framePoint ?? resolved.point;
70
+ }
71
+
72
+ function withoutFrameInput(result) {
73
+ if (!result || typeof result !== "object") {
74
+ return result;
75
+ }
76
+ const rest = { ...result };
77
+ delete rest.inputContext;
78
+ delete rest.framePoint;
79
+ return rest;
80
+ }
81
+
31
82
  function toErrorMessage(error) {
32
83
  return error instanceof Error ? error.message : String(error);
33
84
  }
@@ -179,6 +230,26 @@ function normalizeWaitUntil(value) {
179
230
  return "complete";
180
231
  }
181
232
 
233
+ // Names a request's type as CDP does where BiDi says enough: a document,
234
+ // fetch, or XHR. Older Firefox releases report neither field, so the type
235
+ // stays unknown.
236
+ export function bidiResourceType(request = {}) {
237
+ const { destination, initiatorType } = request;
238
+ if (destination === undefined && initiatorType === undefined) {
239
+ return null;
240
+ }
241
+ if (destination === "document" || destination === "iframe") {
242
+ return "Document";
243
+ }
244
+ if (initiatorType === "fetch") {
245
+ return "Fetch";
246
+ }
247
+ if (initiatorType === "xmlhttprequest") {
248
+ return "XHR";
249
+ }
250
+ return destination || initiatorType || "Other";
251
+ }
252
+
182
253
  function normalizeFirefoxEvent(method, params = {}) {
183
254
  if (method === "log.entryAdded") {
184
255
  return {
@@ -203,6 +274,22 @@ function normalizeFirefoxEvent(method, params = {}) {
203
274
  requestId: params.request?.request,
204
275
  method: params.request?.method,
205
276
  url: params.request?.url,
277
+ resourceType: bidiResourceType(params.request),
278
+ navigation: params.navigation ?? null,
279
+ source: "protocol",
280
+ };
281
+ }
282
+
283
+ if (method === "network.fetchError") {
284
+ return {
285
+ kind: "network",
286
+ phase: "failed",
287
+ completed: true,
288
+ failed: true,
289
+ timestamp: params.timestamp,
290
+ requestId: params.request?.request,
291
+ url: params.request?.url,
292
+ errorText: params.errorText ?? null,
206
293
  source: "protocol",
207
294
  };
208
295
  }
@@ -342,6 +429,7 @@ class FirefoxBidiTabSession {
342
429
  this.eventBufferSize = options.eventBufferSize ?? 200;
343
430
  this.connectedAt = new Date().toISOString();
344
431
  this.bufferedEvents = [];
432
+ this.inFlight = new InFlightRequests();
345
433
  this.subscription = null;
346
434
  this.closed = false;
347
435
  this.lastNavigationAt = null;
@@ -364,6 +452,7 @@ class FirefoxBidiTabSession {
364
452
  }
365
453
 
366
454
  pushEvent(event) {
455
+ this.inFlight.observe(event);
367
456
  this.bufferedEvents.push(event);
368
457
  if (this.bufferedEvents.length > this.eventBufferSize) {
369
458
  this.bufferedEvents.shift();
@@ -375,6 +464,10 @@ class FirefoxBidiTabSession {
375
464
  return this.bufferedEvents.slice(-safeLimit);
376
465
  }
377
466
 
467
+ pendingRequests() {
468
+ return this.inFlight.list();
469
+ }
470
+
378
471
  getConsoleMessages(limit = 50) {
379
472
  return filterConsoleMessages(this.bufferedEvents, limit);
380
473
  }
@@ -687,6 +780,15 @@ export class FirefoxBidiSessionManager {
687
780
  return;
688
781
  }
689
782
 
783
+ // A paused request is routed by its intercept, not its context, since
784
+ // a tab's intercept also pauses its iframes' requests.
785
+ if (
786
+ message.method === "network.beforeRequestSent" &&
787
+ message.params?.isBlocked
788
+ ) {
789
+ this.routeBlockedRequest(message.params);
790
+ }
791
+
690
792
  const contextId = resolveBidiEventContext(message.method, message.params);
691
793
  if (!contextId) {
692
794
  return;
@@ -816,6 +918,7 @@ export class FirefoxBidiSessionManager {
816
918
  "log.entryAdded",
817
919
  "network.beforeRequestSent",
818
920
  "network.responseCompleted",
921
+ "network.fetchError",
819
922
  "browsingContext.load",
820
923
  "browsingContext.contextDestroyed",
821
924
  "browsingContext.userPromptOpened",
@@ -826,18 +929,41 @@ export class FirefoxBidiSessionManager {
826
929
 
827
930
  session.subscription = subscription.subscription ?? null;
828
931
  this.sessions.set(session.id, session);
932
+ await this.installInputRecorder(session);
829
933
  await this.seedBufferedState(session);
830
934
  return session.getSummary();
831
935
  }
832
936
 
833
937
  async detachSession(sessionId) {
834
938
  const session = this.getSession(sessionId);
939
+ // A network call in progress finishes first, so its intercept and
940
+ // offline setting are known here and removed.
941
+ await inNetworkTurn(session, async () => {
942
+ session.closed = true;
943
+ if (session.interceptId) {
944
+ await this.send("network.removeIntercept", {
945
+ intercept: session.interceptId,
946
+ }).catch(() => {});
947
+ session.interceptId = null;
948
+ }
949
+ if (session.network?.offline) {
950
+ await this.send("emulation.setNetworkConditions", {
951
+ networkConditions: null,
952
+ contexts: [session.target.targetId],
953
+ }).catch(() => {});
954
+ }
955
+ });
835
956
 
836
957
  if (session.subscription) {
837
958
  await this.send("session.unsubscribe", {
838
959
  subscriptions: [session.subscription],
839
960
  }).catch(() => {});
840
961
  }
962
+ if (session.inputRecorderScript) {
963
+ await this.send("script.removePreloadScript", {
964
+ script: session.inputRecorderScript,
965
+ }).catch(() => {});
966
+ }
841
967
 
842
968
  session.closed = true;
843
969
  this.sessions.delete(sessionId);
@@ -892,7 +1018,7 @@ export class FirefoxBidiSessionManager {
892
1018
  return this.send("script.evaluate", {
893
1019
  expression,
894
1020
  target: {
895
- context: session.target.targetId,
1021
+ context: options.context ?? session.target.targetId,
896
1022
  },
897
1023
  awaitPromise: options.awaitPromise ?? true,
898
1024
  resultOwnership: "none",
@@ -905,6 +1031,16 @@ export class FirefoxBidiSessionManager {
905
1031
  }
906
1032
 
907
1033
  async runPageAction(session, payload, options = {}) {
1034
+ const route = parseFrameRef(payload.selector);
1035
+ if (route) {
1036
+ const result = await this.runInFrame(
1037
+ session,
1038
+ route.frameKey,
1039
+ { ...payload, selector: route.selector },
1040
+ options,
1041
+ );
1042
+ return restoreFrameSelector(result, route, payload.selector);
1043
+ }
908
1044
  const result = await this.evaluateInContext(
909
1045
  session,
910
1046
  buildPageContextExpression(
@@ -921,6 +1057,7 @@ export class FirefoxBidiSessionManager {
921
1057
  maxDomDepth: 0,
922
1058
  },
923
1059
  userActivation: options.userActivation ?? false,
1060
+ context: options.context,
924
1061
  },
925
1062
  );
926
1063
 
@@ -1040,80 +1177,251 @@ export class FirefoxBidiSessionManager {
1040
1177
  };
1041
1178
  }
1042
1179
 
1043
- async performActions(session, actions) {
1180
+ // Input for an element in a frame goes to that frame's context, at the
1181
+ // point in its own viewport: Firefox does not route input sent to the top
1182
+ // page into a cross-origin frame.
1183
+ async performActions(session, actions, context = null) {
1044
1184
  await this.send("input.performActions", {
1045
- context: session.target.targetId,
1185
+ context: context ?? session.target.targetId,
1046
1186
  actions,
1047
1187
  });
1048
1188
  }
1049
1189
 
1050
- async performKeyActions(session, actions) {
1051
- await this.performActions(session, [
1052
- { type: "key", id: "mcp-keyboard", actions },
1053
- ]);
1190
+ async performKeyActions(session, actions, context = null) {
1191
+ await this.performActions(
1192
+ session,
1193
+ [{ type: "key", id: "mcp-keyboard", actions }],
1194
+ context,
1195
+ );
1054
1196
  }
1055
1197
 
1056
- async resolvePointerTarget(session, selector) {
1198
+ async resolvePointerTarget(session, selector, options = {}) {
1057
1199
  const target = await this.runPageAction(session, {
1058
1200
  action: "pointer_target",
1059
1201
  selector,
1202
+ ...(options.inputProbe ? { inputProbe: options.inputProbe } : {}),
1203
+ ...(options.scrollIntoView === false ? { scrollIntoView: false } : {}),
1060
1204
  });
1061
1205
  assertPointerTarget(target);
1062
1206
  return target;
1063
1207
  }
1064
1208
 
1065
- async click(sessionId, selector) {
1209
+ // A locator, scrolled into view unless scrollIntoView is false, or
1210
+ // viewport coordinates, which never scroll.
1211
+ async resolvePointer(session, target, options = {}) {
1212
+ if (typeof target === "string") {
1213
+ return this.resolvePointerTarget(session, target, options);
1214
+ }
1215
+ return this.runSnapshotAction(session.id, {
1216
+ action: "point_target",
1217
+ x: target.x,
1218
+ y: target.y,
1219
+ ...(options.inputProbe ? { inputProbe: options.inputProbe } : {}),
1220
+ });
1221
+ }
1222
+
1223
+ async readInputProbe(session, token, disarm, target = null) {
1224
+ try {
1225
+ const probe = await this.runPageAction(session, {
1226
+ action: "input_probe",
1227
+ token,
1228
+ disarm,
1229
+ ...probeScope(target),
1230
+ });
1231
+ return probe.armed ? probe : null;
1232
+ } catch {
1233
+ return null;
1234
+ }
1235
+ }
1236
+
1237
+ async click(sessionId, target, options = {}) {
1066
1238
  const session = this.getSession(sessionId);
1067
- const target = await this.resolvePointerTarget(session, selector);
1068
- if (!target.found) {
1069
- return target;
1239
+ const token = crypto.randomUUID();
1240
+ const resolved = await this.resolvePointer(session, target, {
1241
+ inputProbe: token,
1242
+ });
1243
+ if (!resolved.found) {
1244
+ return resolved;
1245
+ }
1246
+ if (typeof target === "string") {
1247
+ assertEnabled(resolved);
1070
1248
  }
1071
- assertEnabled(target);
1072
1249
 
1073
- await this.performActions(session, [
1074
- {
1075
- ...POINTER_SOURCE,
1076
- actions: [
1077
- pointerMove(target.point),
1078
- { type: "pointerDown", button: 0 },
1079
- { type: "pointerUp", button: 0 },
1080
- ],
1081
- },
1082
- ]);
1250
+ const button = MOUSE_BUTTON_NUMBERS[options.button ?? "left"];
1251
+ const presses = [];
1252
+ for (let count = 0; count < (options.clickCount ?? 1); count += 1) {
1253
+ presses.push(
1254
+ { type: "pointerDown", button },
1255
+ { type: "pointerUp", button },
1256
+ );
1257
+ }
1258
+ const delivery = await sendCheckedInput({
1259
+ send: () =>
1260
+ this.performActions(
1261
+ session,
1262
+ [
1263
+ {
1264
+ ...POINTER_SOURCE,
1265
+ actions: [pointerMove(inputPoint(resolved)), ...presses],
1266
+ },
1267
+ ],
1268
+ resolved.inputContext,
1269
+ ),
1270
+ readProbe: (disarm) =>
1271
+ this.readInputProbe(session, token, disarm, target),
1272
+ describe: `The click on ${describePointer(target)}`,
1273
+ });
1083
1274
 
1084
1275
  return {
1085
1276
  browserFamily: "firefox",
1086
- selector,
1087
1277
  found: true,
1088
1278
  clicked: true,
1089
- point: target.point,
1090
- node: target.node,
1279
+ ...(delivery.resent ? { resent: true } : {}),
1280
+ ...pointerFields(target, resolved, delivery.node ?? resolved.node),
1091
1281
  };
1092
1282
  }
1093
1283
 
1094
- async hover(sessionId, selector) {
1284
+ async hover(sessionId, target) {
1095
1285
  const session = this.getSession(sessionId);
1096
- const target = await this.resolvePointerTarget(session, selector);
1286
+ const resolved = await this.resolvePointer(session, target);
1287
+ if (!resolved.found) {
1288
+ return resolved;
1289
+ }
1290
+
1291
+ await this.performActions(
1292
+ session,
1293
+ [{ ...POINTER_SOURCE, actions: [pointerMove(inputPoint(resolved))] }],
1294
+ resolved.inputContext,
1295
+ );
1296
+
1297
+ return {
1298
+ browserFamily: "firefox",
1299
+ found: true,
1300
+ hovered: true,
1301
+ ...pointerFields(target, resolved),
1302
+ };
1303
+ }
1304
+
1305
+ // Presses at from, moves through dragPath, and releases at to. The press
1306
+ // is checked for delivery on its own; the pointer stays down between the
1307
+ // two performActions calls, since the session keeps its input state.
1308
+ async drag(sessionId, from, to, options = {}) {
1309
+ const session = this.getSession(sessionId);
1310
+ const token = crypto.randomUUID();
1311
+ const source = await this.resolvePointer(session, from, {
1312
+ inputProbe: token,
1313
+ });
1314
+ if (!source.found) {
1315
+ await this.readInputProbe(session, token, true, from);
1316
+ return source;
1317
+ }
1318
+ // The drop point is read without scrolling, so the source stays put.
1319
+ const target = await this.resolvePointer(session, to, {
1320
+ scrollIntoView: false,
1321
+ });
1097
1322
  if (!target.found) {
1323
+ await this.readInputProbe(session, token, true, from);
1098
1324
  return target;
1099
1325
  }
1100
1326
 
1101
- await this.performActions(session, [
1102
- { ...POINTER_SOURCE, actions: [pointerMove(target.point)] },
1103
- ]);
1327
+ // A drag runs in one document: the top page's, or one frame's, with
1328
+ // points in that frame's viewport. Firefox cannot route input between
1329
+ // a frame and another document.
1330
+ if (source.inputContext !== target.inputContext) {
1331
+ await this.readInputProbe(session, token, true, from);
1332
+ throw new Error(
1333
+ "On Firefox, drag works within one document; the source and the drop target are in different frames",
1334
+ );
1335
+ }
1336
+ const context = source.inputContext ?? null;
1337
+ const start = context ? source.framePoint : source.point;
1338
+ const end = context ? target.framePoint : target.point;
1339
+ const html5 = { from: start, to: end };
1340
+ const inContext = context ? { context } : {};
1341
+ const { html5: draggable } = await this.runPageAction(
1342
+ session,
1343
+ { action: "html5_drag", ...html5, check: true },
1344
+ inContext,
1345
+ );
1346
+ if (draggable) {
1347
+ await this.readInputProbe(session, token, true, from);
1348
+ const { dropped } = await this.runPageAction(
1349
+ session,
1350
+ { action: "html5_drag", ...html5 },
1351
+ inContext,
1352
+ );
1353
+ return {
1354
+ browserFamily: "firefox",
1355
+ found: true,
1356
+ dragged: true,
1357
+ html5: true,
1358
+ synthetic: true,
1359
+ dropped,
1360
+ from: dragEnd(from, source),
1361
+ to: dragEnd(to, target),
1362
+ };
1363
+ }
1364
+
1365
+ let delivery;
1366
+ try {
1367
+ delivery = await sendCheckedInput({
1368
+ send: () =>
1369
+ this.performActions(
1370
+ session,
1371
+ [
1372
+ {
1373
+ ...POINTER_SOURCE,
1374
+ actions: [
1375
+ pointerMove(start),
1376
+ { type: "pointerDown", button: 0 },
1377
+ ],
1378
+ },
1379
+ ],
1380
+ context,
1381
+ ),
1382
+ readProbe: (disarm) =>
1383
+ this.readInputProbe(session, token, disarm, from),
1384
+ describe: `The press to drag ${describePointer(from)}`,
1385
+ });
1386
+ await this.performActions(
1387
+ session,
1388
+ [
1389
+ {
1390
+ ...POINTER_SOURCE,
1391
+ actions: [
1392
+ ...dragPath(start, end, options.steps).map((point) => ({
1393
+ ...pointerMove(point),
1394
+ duration: DRAG_MOVE_MS,
1395
+ })),
1396
+ { type: "pointerUp", button: 0 },
1397
+ ],
1398
+ },
1399
+ ],
1400
+ context,
1401
+ );
1402
+ } catch (error) {
1403
+ // A drag that failed partway must not leave the button down for the
1404
+ // next action.
1405
+ await this.send("input.releaseActions", {
1406
+ context: session.target.targetId,
1407
+ }).catch(() => {});
1408
+ throw error;
1409
+ }
1104
1410
 
1105
1411
  return {
1106
1412
  browserFamily: "firefox",
1107
- selector,
1108
1413
  found: true,
1109
- hovered: true,
1110
- point: target.point,
1111
- node: target.node,
1414
+ dragged: true,
1415
+ html5: false,
1416
+ ...(delivery.resent ? { resent: true } : {}),
1417
+ from: dragEnd(from, source),
1418
+ to: dragEnd(to, target),
1112
1419
  };
1113
1420
  }
1114
1421
 
1115
1422
  async type(sessionId, selector, text, options = {}) {
1116
1423
  const session = this.getSession(sessionId);
1424
+ const token = crypto.randomUUID();
1117
1425
  const prepared = await this.runPageAction(
1118
1426
  session,
1119
1427
  {
@@ -1121,34 +1429,250 @@ export class FirefoxBidiSessionManager {
1121
1429
  selector,
1122
1430
  text,
1123
1431
  clear: options.clear,
1432
+ inputProbe: token,
1124
1433
  },
1125
1434
  { userActivation: true },
1126
1435
  );
1127
1436
  if (!prepared.found || prepared.method !== "native") {
1128
- return prepared;
1437
+ return withoutFrameInput(prepared);
1129
1438
  }
1130
1439
 
1131
- if (text) {
1132
- await this.performKeyActions(session, buildBidiTextActions(text));
1133
- } else if (options.clear !== false) {
1134
- await this.performKeyActions(session, buildBidiKeyActions("Backspace"));
1440
+ let delivery = { node: null, resent: false };
1441
+ if (text || options.clear !== false) {
1442
+ const actions = text
1443
+ ? buildBidiTextActions(text)
1444
+ : buildBidiKeyActions("Backspace");
1445
+ delivery = await sendCheckedInput({
1446
+ send: () =>
1447
+ this.performKeyActions(session, actions, prepared.inputContext),
1448
+ readProbe: (disarm) =>
1449
+ this.readInputProbe(session, token, disarm, selector),
1450
+ describe: `The text for "${selector}"`,
1451
+ });
1452
+ } else {
1453
+ await this.readInputProbe(session, token, true, selector);
1135
1454
  }
1136
1455
 
1137
- const typed = await this.runPageAction(session, {
1138
- action: "inspect",
1139
- selector,
1140
- scrollIntoView: false,
1141
- });
1456
+ let node = delivery.node;
1457
+ if (!node) {
1458
+ const typed = await this.runPageAction(session, {
1459
+ action: "inspect",
1460
+ selector,
1461
+ scrollIntoView: false,
1462
+ });
1463
+ node = typed.found ? typed.node : prepared.node;
1464
+ }
1142
1465
 
1143
1466
  return {
1144
1467
  browserFamily: "firefox",
1145
1468
  selector,
1146
1469
  found: true,
1147
1470
  typedText: text,
1148
- node: typed.found ? typed.node : prepared.node,
1471
+ ...(delivery.resent ? { resent: true } : {}),
1472
+ node,
1149
1473
  };
1150
1474
  }
1151
1475
 
1476
+ // Sets files on a file input. WebDriver BiDi sets them on an element; a
1477
+ // button that opens a chooser from script needs its hidden input passed.
1478
+ // BiDi URL patterns cannot express globs, so the tab's requests are all
1479
+ // intercepted while there are rules or extra headers, and each is matched
1480
+ // here. Throttling has no BiDi command.
1481
+ async setNetwork(sessionId, options) {
1482
+ const session = this.getSession(sessionId);
1483
+ // One call at a time per tab, so two calls cannot each add an intercept.
1484
+ return inNetworkTurn(session, () => {
1485
+ if (session.closed) {
1486
+ throw new Error(`Session ${sessionId} was detached`);
1487
+ }
1488
+ return this.applyNetwork(session, options);
1489
+ });
1490
+ }
1491
+
1492
+ async applyNetwork(session, options) {
1493
+ const state = applyNetworkOptions(session.network, options);
1494
+ if (throttled(state)) {
1495
+ throw new Error(
1496
+ "latencyMs, downloadKbps, and uploadKbps are Chromium only; Firefox has no network throttling over WebDriver BiDi",
1497
+ );
1498
+ }
1499
+ if (options.offline !== undefined || options.reset) {
1500
+ try {
1501
+ await this.send("emulation.setNetworkConditions", {
1502
+ networkConditions: state.offline ? { type: "offline" } : null,
1503
+ contexts: [session.target.targetId],
1504
+ });
1505
+ } catch (error) {
1506
+ if (state.offline) {
1507
+ throw new Error(
1508
+ `This Firefox cannot emulate offline: ${toErrorMessage(error)}`,
1509
+ { cause: error },
1510
+ );
1511
+ }
1512
+ }
1513
+ }
1514
+ // The rules apply before the intercept exists, so the first request it
1515
+ // pauses is already answered by them.
1516
+ session.network = state;
1517
+ const intercepting =
1518
+ state.rules.length > 0 || Object.keys(state.headers).length > 0;
1519
+ if (intercepting && !session.interceptId) {
1520
+ this.addingIntercepts = (this.addingIntercepts ?? 0) + 1;
1521
+ try {
1522
+ const added = await this.send("network.addIntercept", {
1523
+ phases: ["beforeRequestSent"],
1524
+ contexts: [session.target.targetId],
1525
+ });
1526
+ session.interceptId = added.intercept;
1527
+ if (session.closed) {
1528
+ await this.send("network.removeIntercept", {
1529
+ intercept: added.intercept,
1530
+ }).catch(() => {});
1531
+ session.interceptId = null;
1532
+ }
1533
+ } finally {
1534
+ this.addingIntercepts -= 1;
1535
+ for (const params of (this.unrouted ?? []).splice(0)) {
1536
+ this.routeBlockedRequest(params);
1537
+ }
1538
+ }
1539
+ } else if (!intercepting && session.interceptId) {
1540
+ const intercept = session.interceptId;
1541
+ session.interceptId = null;
1542
+ await this.send("network.removeIntercept", { intercept }).catch(() => {});
1543
+ }
1544
+ return { browserFamily: "firefox", ...describeNetworkState(state) };
1545
+ }
1546
+
1547
+ // Every intercept on this connection is one of ours. A paused request no
1548
+ // session claims either belongs to an intercept still being added, and
1549
+ // waits for it, or to one just removed, and is let go.
1550
+ routeBlockedRequest(params) {
1551
+ const owner = Array.from(this.sessions.values()).find(
1552
+ (session) =>
1553
+ session.interceptId && params.intercepts?.includes(session.interceptId),
1554
+ );
1555
+ if (owner) {
1556
+ void this.handleBlockedRequest(owner, params);
1557
+ } else if (this.addingIntercepts > 0) {
1558
+ (this.unrouted ??= []).push(params);
1559
+ } else {
1560
+ this.send("network.continueRequest", {
1561
+ request: params.request?.request,
1562
+ }).catch(() => {});
1563
+ }
1564
+ }
1565
+
1566
+ async handleBlockedRequest(session, params) {
1567
+ const request = params.request?.request;
1568
+ const rule = takeMatchingRule(session.network, params.request?.url ?? "");
1569
+ const stringValue = (value) => ({ type: "string", value });
1570
+ try {
1571
+ if (rule?.action === "block") {
1572
+ await this.send("network.failRequest", { request });
1573
+ } else if (rule) {
1574
+ await this.send("network.provideResponse", {
1575
+ request,
1576
+ statusCode: rule.status,
1577
+ headers: mockHeaders(rule).map(({ name, value }) => ({
1578
+ name,
1579
+ value: stringValue(value),
1580
+ })),
1581
+ body: stringValue(rule.body),
1582
+ });
1583
+ } else {
1584
+ const extra = session.network?.headers ?? {};
1585
+ const names = new Set(
1586
+ Object.keys(extra).map((name) => name.toLowerCase()),
1587
+ );
1588
+ const headers =
1589
+ names.size === 0
1590
+ ? undefined
1591
+ : [
1592
+ ...(params.request?.headers ?? []).filter(
1593
+ (header) => !names.has(header.name.toLowerCase()),
1594
+ ),
1595
+ ...Object.entries(extra).map(([name, value]) => ({
1596
+ name,
1597
+ value: stringValue(String(value)),
1598
+ })),
1599
+ ];
1600
+ await this.send("network.continueRequest", {
1601
+ request,
1602
+ ...(headers ? { headers } : {}),
1603
+ });
1604
+ }
1605
+ } catch {
1606
+ // Release the request if it is still paused; it may also have gone
1607
+ // away, for example because the page navigated.
1608
+ await this.send("network.continueRequest", { request }).catch(() => {});
1609
+ }
1610
+ }
1611
+
1612
+ // The page's report; Firefox has no counters like Chromium's over BiDi.
1613
+ async getPerformance(sessionId) {
1614
+ const report = await this.runPageAction(this.getSession(sessionId), {
1615
+ action: "performance",
1616
+ });
1617
+ return { ...report, metrics: null };
1618
+ }
1619
+
1620
+ async startTrace() {
1621
+ throw new Error(
1622
+ "record_trace is Chromium only; Firefox has no tracing over WebDriver BiDi",
1623
+ );
1624
+ }
1625
+
1626
+ async stopTrace() {
1627
+ return this.startTrace();
1628
+ }
1629
+
1630
+ async uploadFiles(sessionId, selector, files) {
1631
+ const session = this.getSession(sessionId);
1632
+ const token = crypto.randomUUID();
1633
+ const target = await this.runPageAction(session, {
1634
+ action: "file_input",
1635
+ selector,
1636
+ token,
1637
+ clear: files.length === 0,
1638
+ });
1639
+ if (!target.found) {
1640
+ return target;
1641
+ }
1642
+ if (target.cleared) {
1643
+ return uploadResult("firefox", selector, files);
1644
+ }
1645
+ if (!target.fileInput) {
1646
+ throw new Error(
1647
+ `"${selector}" is not a file input and has none inside; on Firefox, pass the <input type="file">, which may be hidden`,
1648
+ );
1649
+ }
1650
+ // The input and the files go to the document it is in, a frame's for a
1651
+ // frame ref.
1652
+ const route = parseFrameRef(selector);
1653
+ const context = route
1654
+ ? this.frameKeys(session).get(route.frameKey)?.id
1655
+ : undefined;
1656
+ const handle = await this.evaluateInContext(
1657
+ session,
1658
+ takeFileTarget(token),
1659
+ {
1660
+ context,
1661
+ },
1662
+ );
1663
+ const sharedId = handle.result?.sharedId;
1664
+ assertFileInput(target, files);
1665
+ await this.send("input.setFiles", {
1666
+ context: context ?? session.target.targetId,
1667
+ element: { sharedId },
1668
+ files,
1669
+ });
1670
+ return uploadResult("firefox", selector, files, {
1671
+ multiple: target.multiple,
1672
+ accept: target.accept,
1673
+ });
1674
+ }
1675
+
1152
1676
  async select(sessionId, selector, options = {}) {
1153
1677
  return this.runPageAction(
1154
1678
  this.getSession(sessionId),
@@ -1165,31 +1689,82 @@ export class FirefoxBidiSessionManager {
1165
1689
  async pressKey(sessionId, key, selector = null) {
1166
1690
  const session = this.getSession(sessionId);
1167
1691
  const actions = buildBidiKeyActions(key);
1692
+ const token = crypto.randomUUID();
1168
1693
  const focused = await this.runPageAction(
1169
1694
  session,
1170
1695
  {
1171
1696
  action: "focus",
1172
1697
  selector,
1698
+ inputProbe: token,
1173
1699
  },
1174
1700
  { userActivation: true },
1175
1701
  );
1176
1702
  if (!focused.found) {
1177
- return focused;
1703
+ return withoutFrameInput(focused);
1178
1704
  }
1179
1705
 
1180
- await this.performKeyActions(session, actions);
1706
+ const delivery = await sendCheckedInput({
1707
+ send: () =>
1708
+ this.performKeyActions(session, actions, focused.inputContext),
1709
+ readProbe: (disarm) =>
1710
+ this.readInputProbe(session, token, disarm, selector),
1711
+ describe: `The key press "${key}"`,
1712
+ });
1181
1713
 
1182
1714
  return {
1183
1715
  browserFamily: "firefox",
1184
1716
  key,
1185
1717
  dispatched: true,
1718
+ ...(delivery.resent ? { resent: true } : {}),
1186
1719
  target: focused.target,
1187
1720
  };
1188
1721
  }
1189
1722
 
1723
+ // A selector alone scrolls its element into view and deltas alone scroll
1724
+ // the page. Coordinates, or a selector with deltas, send a real mouse
1725
+ // wheel there, which scrolls whatever is under the pointer.
1190
1726
  async scroll(sessionId, options = {}) {
1727
+ const session = this.getSession(sessionId);
1728
+ if (wheelScroll(options)) {
1729
+ const target = options.selector ?? { x: options.x, y: options.y };
1730
+ const resolved = await this.resolvePointer(session, target);
1731
+ if (!resolved.found) {
1732
+ return resolved;
1733
+ }
1734
+ const wheel = {
1735
+ deltaX: options.deltaX ?? 0,
1736
+ deltaY: options.deltaY ?? 0,
1737
+ };
1738
+ const at = inputPoint(resolved);
1739
+ await this.performActions(
1740
+ session,
1741
+ [
1742
+ {
1743
+ type: "wheel",
1744
+ id: "mcp-wheel",
1745
+ actions: [
1746
+ {
1747
+ type: "scroll",
1748
+ x: Math.round(at.x),
1749
+ y: Math.round(at.y),
1750
+ ...wheel,
1751
+ origin: "viewport",
1752
+ },
1753
+ ],
1754
+ },
1755
+ ],
1756
+ resolved.inputContext,
1757
+ );
1758
+ return {
1759
+ browserFamily: "firefox",
1760
+ found: true,
1761
+ scrolled: true,
1762
+ wheel,
1763
+ ...pointerFields(target, resolved),
1764
+ };
1765
+ }
1191
1766
  return this.runPageAction(
1192
- this.getSession(sessionId),
1767
+ session,
1193
1768
  {
1194
1769
  action: "scroll",
1195
1770
  selector: options.selector,
@@ -1367,9 +1942,193 @@ export class FirefoxBidiSessionManager {
1367
1942
  };
1368
1943
  }
1369
1944
 
1945
+ async runSnapshotAction(sessionId, payload) {
1946
+ const session = this.getSession(sessionId);
1947
+ const result = await this.runPageAction(session, {
1948
+ ...payload,
1949
+ refStart: session.refStart ?? 1,
1950
+ });
1951
+ return takeNextRef(session, result);
1952
+ }
1953
+
1370
1954
  async snapshotControls(sessionId) {
1371
- return this.runPageAction(this.getSession(sessionId), {
1372
- action: "controls_snapshot",
1955
+ return this.runSnapshotAction(sessionId, { action: "controls_snapshot" });
1956
+ }
1957
+
1958
+ async trackChanges(sessionId, phase, options = {}) {
1959
+ const { frameKey, ...rest } = options;
1960
+ if (!frameKey) {
1961
+ return this.runSnapshotAction(sessionId, {
1962
+ action: `change_${phase}`,
1963
+ ...rest,
1964
+ });
1965
+ }
1966
+ // In a frame, refs number on from the frame's own last snapshot. A frame
1967
+ // that is gone ends tracking as a lost baseline does.
1968
+ const session = this.getSession(sessionId);
1969
+ const entry = this.frameKeys(session).get(frameKey);
1970
+ const result = entry
1971
+ ? await this.runInFrame(
1972
+ session,
1973
+ frameKey,
1974
+ { action: `change_${phase}`, ...rest, refStart: entry.refStart ?? 1 },
1975
+ { offset: false },
1976
+ ).catch(() => null)
1977
+ : null;
1978
+ if (!result || result.error?.startsWith("Unknown frame")) {
1979
+ if (phase === "baseline") {
1980
+ throw new Error(`Unknown frame ${frameKey}`);
1981
+ }
1982
+ return { document: "same", lost: true };
1983
+ }
1984
+ return takeNextRef(entry, result);
1985
+ }
1986
+
1987
+ frameKeys(session) {
1988
+ return (session.frameKeys ??= new FrameKeys());
1989
+ }
1990
+
1991
+ // The tab's iframes, outermost first, each with its parent's context.
1992
+ async listFrames(session) {
1993
+ const { contexts } = await this.send("browsingContext.getTree", {
1994
+ root: session.target.targetId,
1995
+ });
1996
+ const frames = [];
1997
+ const walk = (node) => {
1998
+ for (const child of node.children ?? []) {
1999
+ frames.push({
2000
+ id: child.context,
2001
+ url: child.url,
2002
+ parent: node.context,
2003
+ });
2004
+ walk(child);
2005
+ }
2006
+ };
2007
+ for (const root of contexts ?? []) {
2008
+ walk(root);
2009
+ }
2010
+ return frames;
2011
+ }
2012
+
2013
+ // Where the frame's viewport starts in the top page's viewport: the
2014
+ // content box of its owner element, found with the context locator in its
2015
+ // parent, plus the parent's own offset; null when the frame is gone or
2016
+ // hidden. With scroll, each owner is scrolled into view first.
2017
+ async frameOffset(session, frame, scroll = false) {
2018
+ const frames = await this.listFrames(session);
2019
+ const byId = new Map(frames.map((entry) => [entry.id, entry]));
2020
+ const chain = [];
2021
+ for (
2022
+ let entry = byId.get(frame.id);
2023
+ entry;
2024
+ entry = byId.get(entry.parent)
2025
+ ) {
2026
+ chain.unshift(entry);
2027
+ }
2028
+ if (chain.length === 0) {
2029
+ return null;
2030
+ }
2031
+ let offset = { x: 0, y: 0 };
2032
+ for (const entry of chain) {
2033
+ const located = await this.send("browsingContext.locateNodes", {
2034
+ context: entry.parent,
2035
+ locator: { type: "context", value: { context: entry.id } },
2036
+ }).catch(() => null);
2037
+ const sharedId = located?.nodes?.[0]?.sharedId;
2038
+ if (!sharedId) {
2039
+ return null;
2040
+ }
2041
+ const box = await this.send("script.callFunction", {
2042
+ functionDeclaration: `(element, scroll) => {
2043
+ if (scroll) element.scrollIntoView({ block: "center", inline: "center" });
2044
+ const rect = element.getBoundingClientRect();
2045
+ if (rect.width === 0 || rect.height === 0) return null;
2046
+ const style = getComputedStyle(element);
2047
+ return [
2048
+ rect.left + element.clientLeft + parseFloat(style.paddingLeft),
2049
+ rect.top + element.clientTop + parseFloat(style.paddingTop),
2050
+ ];
2051
+ }`,
2052
+ target: { context: entry.parent },
2053
+ arguments: [{ sharedId }, { type: "boolean", value: scroll }],
2054
+ awaitPromise: false,
2055
+ resultOwnership: "none",
2056
+ }).catch(() => null);
2057
+ const values = box?.result?.value;
2058
+ if (box?.type !== "success" || !Array.isArray(values)) {
2059
+ return null;
2060
+ }
2061
+ offset = {
2062
+ x: offset.x + values[0].value,
2063
+ y: offset.y + values[1].value,
2064
+ };
2065
+ }
2066
+ return offset;
2067
+ }
2068
+
2069
+ // Runs a page action in a frame's browsing context.
2070
+ async runInFrame(session, frameKey, payload, options = {}) {
2071
+ const frame = this.frameKeys(session).get(frameKey);
2072
+ if (!frame) {
2073
+ return unknownFrame(frameKey, payload.selector);
2074
+ }
2075
+ const positioned = options.offset !== false;
2076
+ const before = positioned
2077
+ ? await this.frameOffset(
2078
+ session,
2079
+ frame,
2080
+ options.scroll ?? payload.scrollIntoView !== false,
2081
+ )
2082
+ : { x: 0, y: 0 };
2083
+ if (!before) {
2084
+ return unknownFrame(frameKey, payload.selector);
2085
+ }
2086
+ const result = await this.runPageAction(session, payload, {
2087
+ ...options,
2088
+ context: frame.id,
2089
+ });
2090
+ if (!result || typeof result !== "object") {
2091
+ return result;
2092
+ }
2093
+ // The action may have scrolled the frame's ancestors, moving the frame.
2094
+ const offset =
2095
+ positioned && (result.point || result.node?.box)
2096
+ ? ((await this.frameOffset(session, frame)) ?? before)
2097
+ : before;
2098
+ return {
2099
+ ...shiftFramePoints(result, offset),
2100
+ inputContext: frame.id,
2101
+ ...(result.point ? { framePoint: result.point } : {}),
2102
+ };
2103
+ }
2104
+
2105
+ // The top page's headings and controls, then each iframe's.
2106
+ async snapshotPage(sessionId, options = {}) {
2107
+ const session = this.getSession(sessionId);
2108
+ const runInFrame = (key, payload, runOptions) =>
2109
+ this.runInFrame(session, key, payload, runOptions);
2110
+ const route = parseFrameRef(options.selector);
2111
+ if (route) {
2112
+ return frameElementSnapshot({
2113
+ route,
2114
+ frameKeys: this.frameKeys(session),
2115
+ runInFrame,
2116
+ options,
2117
+ });
2118
+ }
2119
+ const result = await this.runSnapshotAction(sessionId, {
2120
+ action: "snapshot",
2121
+ ...options,
2122
+ });
2123
+ if (options.selector) {
2124
+ return result;
2125
+ }
2126
+ return addFrameSnapshots({
2127
+ result,
2128
+ frames: await this.listFrames(session).catch(() => []),
2129
+ frameKeys: this.frameKeys(session),
2130
+ runInFrame,
2131
+ options,
1373
2132
  });
1374
2133
  }
1375
2134
 
@@ -1388,6 +2147,26 @@ export class FirefoxBidiSessionManager {
1388
2147
  });
1389
2148
  }
1390
2149
 
2150
+ // Counts trusted input from the start of every later document, and from
2151
+ // now on in the current one, so input actions can check that their input
2152
+ // arrived. Without it they are reported as sent, unchecked.
2153
+ async installInputRecorder(session) {
2154
+ try {
2155
+ const preload = await this.send("script.addPreloadScript", {
2156
+ functionDeclaration: `() => ${buildInputRecorderExpression(true)}`,
2157
+ contexts: [session.target.targetId],
2158
+ });
2159
+ session.inputRecorderScript = preload?.script ?? null;
2160
+ await this.evaluateInContext(
2161
+ session,
2162
+ buildInputRecorderExpression(false),
2163
+ { awaitPromise: false },
2164
+ );
2165
+ } catch {
2166
+ // Ignore recorder failures so attach still succeeds.
2167
+ }
2168
+ }
2169
+
1391
2170
  async seedBufferedState(session) {
1392
2171
  try {
1393
2172
  const snapshot = await this.runPageAction(session, {
@@ -1413,6 +2192,10 @@ export class FirefoxBidiSessionManager {
1413
2192
  }
1414
2193
  }
1415
2194
 
2195
+ pendingRequests(sessionId) {
2196
+ return this.getSession(sessionId).pendingRequests();
2197
+ }
2198
+
1416
2199
  getEvents(sessionId, limit) {
1417
2200
  return this.getSession(sessionId).getEvents(limit);
1418
2201
  }