@ricsam/browser-mcp 0.3.25 → 0.3.26

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,6 @@
1
1
  import {
2
2
  CLI_VERSION
3
- } from "./chunk-mktre13d.js";
3
+ } from "./chunk-42sbfmcv.js";
4
4
  import {
5
5
  LIMITS,
6
6
  sameScope,
@@ -1767,6 +1767,8 @@ var messages = {
1767
1767
  target_not_actionable: "A pointer could not reach the ref's element where a person would: result.reason says why (covered, hidden, disabled, outside_viewport, no_pointer_input or unstable), and result.cover and result.layer name what covers it (untrusted page data).",
1768
1768
  not_a_form_field: "The ref is not a form field whose value can be set: it takes typed text, as a code editor's input does, or no text at all (result.kind). Nothing was changed.",
1769
1769
  check_state_unchanged: "A click where the checkbox or radio button's widget is drawn did not change its state.",
1770
+ page_busy: "The click's input reached the page, which had not finished handling it within five seconds: a script of the page was still running. Whether the click took effect is unknown.",
1771
+ navigation_loading: "The tab is loading another page that has not arrived yet (result.pendingNavigation, untrusted). Until it does, Chrome answers no read of the page the tab still shows, nor actions on its elements. Nothing was dispatched.",
1770
1772
  option_not_found: "No option of the select matches the request; result.options lists its first options (untrusted page data). Nothing was changed.",
1771
1773
  invalid_browser_input: "The request does not fit this operation or its target element. Nothing was changed.",
1772
1774
  pointer_unknown: "This tab has no known pointer position to click at. Nothing was clicked.",
@@ -3047,6 +3049,19 @@ function snapshotLine(line) {
3047
3049
  const { key: key2, ref, role } = snapshotLineParts(line);
3048
3050
  return { key: key2, ref, role };
3049
3051
  }
3052
+ var BOX = / \[box=(-?\d+),(-?\d+),(-?\d+),(-?\d+)\]$/;
3053
+ function moveLineBox(line, origin) {
3054
+ const indent = line.length - line.trimStart().length;
3055
+ if (!line.startsWith("- ", indent))
3056
+ return line;
3057
+ const { key: key2 } = snapshotLineParts(line);
3058
+ const box = BOX.exec(key2);
3059
+ if (!box)
3060
+ return line;
3061
+ const start = indent + 2 + box.index;
3062
+ const moved = origin ? ` [box=${Math.round(Number(box[1]) + origin.x)},${Math.round(Number(box[2]) + origin.y)},${box[3]},${box[4]}]` : "";
3063
+ return line.slice(0, start) + moved + line.slice(indent + 2 + key2.length);
3064
+ }
3050
3065
 
3051
3066
  // cli/src/browser/password-safe-snapshot.ts
3052
3067
  var requirePlaywright2 = createRequire2(import.meta.url);
@@ -3054,6 +3069,48 @@ var SUPPORTED_PLAYWRIGHT_VERSION2 = "1.63.0";
3054
3069
  var DEFAULT_TIMEOUT_MS = 1e4;
3055
3070
  var UNAVAILABLE = "Password-safe browser snapshots are unavailable with this Playwright runtime. Update r5d-browser before retrying.";
3056
3071
  var MAX_MATCH_DETAILS = 1000;
3072
+ var PAGE = { x: 0, y: 0 };
3073
+ var SCALE_TOLERANCE = 1.5;
3074
+ var FRAME_ELEMENT_PROGRESS = { race: (promise) => Promise.race(Array.isArray(promise) ? promise : [promise]) };
3075
+ var finite = (value, keys) => !!value && typeof value === "object" && keys.every((key2) => Number.isFinite(value[key2]));
3076
+ var isGeometry = (value) => finite(value, ["x", "y", "width", "height"]) && finite(value.parentViewport, ["width", "height"]);
3077
+ var drawnAtScale = (size, viewport) => size.width === undefined || size.height === undefined || Math.abs(viewport.width - size.width) <= SCALE_TOLERANCE && Math.abs(viewport.height - size.height) <= SCALE_TOLERANCE;
3078
+ function iframeGeometryInUtilityWorld(context) {
3079
+ const iframe = Array.isArray(context) ? context[1] : context?.elements?.[0];
3080
+ const view = iframe?.ownerDocument?.defaultView;
3081
+ if (!iframe || !iframe.isConnected || !view)
3082
+ return "detached";
3083
+ const zoom = iframe.currentCSSZoom;
3084
+ if (typeof zoom === "number" && zoom !== 1)
3085
+ return "transformed";
3086
+ const translation = (transform) => {
3087
+ if (transform === "none")
3088
+ return true;
3089
+ try {
3090
+ const matrix = new view.DOMMatrixReadOnly(transform);
3091
+ return matrix.is2D && matrix.a === 1 && matrix.b === 0 && matrix.c === 0 && matrix.d === 1;
3092
+ } catch {
3093
+ return false;
3094
+ }
3095
+ };
3096
+ for (let node = iframe;node; node = node.assignedSlot ?? node.parentElement ?? (node.parentNode?.host ?? null)) {
3097
+ const style2 = view.getComputedStyle(node);
3098
+ if (!translation(style2.transform) || style2.scale !== "none" || style2.rotate !== "none" || style2.translate.trim().split(/\s+/).length > 2 || (style2.offsetPath || "none") !== "none")
3099
+ return "transformed";
3100
+ }
3101
+ const box = iframe.getBoundingClientRect();
3102
+ const style = view.getComputedStyle(iframe);
3103
+ const px = (value) => Number.parseFloat(value) || 0;
3104
+ const left = px(style.borderLeftWidth) + px(style.paddingLeft);
3105
+ const top = px(style.borderTopWidth) + px(style.paddingTop);
3106
+ return {
3107
+ x: box.left + left,
3108
+ y: box.top + top,
3109
+ width: box.width - left - px(style.borderRightWidth) - px(style.paddingRight),
3110
+ height: box.height - top - px(style.borderBottomWidth) - px(style.paddingBottom),
3111
+ parentViewport: { width: view.innerWidth, height: view.innerHeight }
3112
+ };
3113
+ }
3057
3114
  function isServerFrame(value) {
3058
3115
  return !!value && typeof value.selectors?.callOnSelector === "function";
3059
3116
  }
@@ -3364,7 +3421,8 @@ function captureInUtilityWorld({ elements, injected }, options) {
3364
3421
  matches,
3365
3422
  matchCount: visible.length,
3366
3423
  ...eligible.length > visible.length ? { hiddenMatchCount: eligible.length - visible.length } : {},
3367
- ...options.scope && !options.matchesOnly ? { scopeMatchCount: 1 } : {}
3424
+ ...options.scope && !options.matchesOnly ? { scopeMatchCount: 1 } : {},
3425
+ ...options.boxes || options.query ? { viewport: { width: window.innerWidth, height: window.innerHeight } } : {}
3368
3426
  };
3369
3427
  } finally {
3370
3428
  Object.defineProperty(Element.prototype, "getAttribute", attributeDescriptor);
@@ -3374,7 +3432,7 @@ function captureInUtilityWorld({ elements, injected }, options) {
3374
3432
  function validateSnapshot(value) {
3375
3433
  const snapshot = value;
3376
3434
  const box = (item) => !!item && [item.x, item.y, item.width, item.height].every((n) => typeof n === "number" && Number.isFinite(n));
3377
- if (!snapshot || typeof snapshot.text !== "string" || !Array.isArray(snapshot.iframeRefs) || !snapshot.iframeDepths || typeof snapshot.iframeDepths !== "object" || snapshot.iframeRefs.some((ref) => typeof ref !== "string" || !/^(f\d+)?e\d+$/.test(ref)) || Object.entries(snapshot.iframeDepths).some(([ref, depth]) => !/^(f\d+)?e\d+$/.test(ref) || !Number.isInteger(depth) || depth < 0) || snapshot.matches !== undefined && (!Array.isArray(snapshot.matches) || snapshot.matches.some((match) => !match || typeof match.ref !== "string" || !REF_PATTERN.test(match.ref) || typeof match.role !== "string" || typeof match.name !== "string" || !match.states || typeof match.states !== "object" || !box(match.box) || match.ancestors !== undefined && (!Array.isArray(match.ancestors) || match.ancestors.some((ref) => typeof ref !== "string"))))) {
3435
+ if (!snapshot || typeof snapshot.text !== "string" || !Array.isArray(snapshot.iframeRefs) || !snapshot.iframeDepths || typeof snapshot.iframeDepths !== "object" || snapshot.iframeRefs.some((ref) => typeof ref !== "string" || !/^(f\d+)?e\d+$/.test(ref)) || Object.entries(snapshot.iframeDepths).some(([ref, depth]) => !/^(f\d+)?e\d+$/.test(ref) || !Number.isInteger(depth) || depth < 0) || snapshot.matches !== undefined && (!Array.isArray(snapshot.matches) || snapshot.matches.some((match) => !match || typeof match.ref !== "string" || !REF_PATTERN.test(match.ref) || typeof match.role !== "string" || typeof match.name !== "string" || !match.states || typeof match.states !== "object" || !box(match.box) || match.ancestors !== undefined && (!Array.isArray(match.ancestors) || match.ancestors.some((ref) => typeof ref !== "string")))) || snapshot.viewport !== undefined && (!Number.isFinite(snapshot.viewport?.width) || !Number.isFinite(snapshot.viewport?.height))) {
3378
3436
  throw new Error(UNAVAILABLE);
3379
3437
  }
3380
3438
  }
@@ -3431,7 +3489,73 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
3431
3489
  clearTimeout(timer2);
3432
3490
  }
3433
3491
  };
3434
- const captureFrame = async (currentFrame, selector, frameOptions, isMainFrame = false, framePath = []) => {
3492
+ const prefix = (options.frames ?? []).map((selector) => `${selector} >> internal:control=enter-frame >> `).join("");
3493
+ const refScope = options.scope?.startsWith("aria-ref=") ? options.scope : undefined;
3494
+ const geometry = !!(options.boxes || options.query);
3495
+ document2.framesWithoutBoxes = [];
3496
+ const withoutBoxes = (framePath, reason) => {
3497
+ document2.framesWithoutBoxes.push({ framePath, reason });
3498
+ return null;
3499
+ };
3500
+ const iframePlacement = async (parentFrame, selector, parent, framePath) => {
3501
+ if (!parent)
3502
+ return null;
3503
+ let measured;
3504
+ try {
3505
+ measured = (await bounded2(parentFrame.selectors.callOnSelector(selector, { strict: true }, iframeGeometryInUtilityWorld, null)))?.result;
3506
+ } catch {
3507
+ measured = undefined;
3508
+ }
3509
+ if (measured === "transformed")
3510
+ return withoutBoxes(framePath, "transformed");
3511
+ if (!isGeometry(measured))
3512
+ return withoutBoxes(framePath, "unknown");
3513
+ if (!drawnAtScale(parent, measured.parentViewport))
3514
+ return withoutBoxes(framePath, "transformed");
3515
+ return { x: parent.x + measured.x, y: parent.y + measured.y, width: measured.width, height: measured.height };
3516
+ };
3517
+ const selectedPlacement = async () => {
3518
+ const frames = options.frames;
3519
+ let placement = PAGE;
3520
+ for (let index = 0;placement && index < frames.length; index++) {
3521
+ const into = frames.slice(0, index).map((selector) => `${selector} >> internal:control=enter-frame >> `).join("");
3522
+ placement = await iframePlacement(frame, `${into}${frames[index]}`, placement, []);
3523
+ }
3524
+ return placement;
3525
+ };
3526
+ const scopePlacement = async (scopeFrame) => {
3527
+ let x = 0, y = 0, size, inner;
3528
+ try {
3529
+ for (let current = scopeFrame;current !== frame; ) {
3530
+ const parent = current.parentFrame?.();
3531
+ if (!parent || typeof current.frameElement !== "function")
3532
+ return withoutBoxes([], "unknown");
3533
+ const element = await bounded2(current.frameElement(FRAME_ELEMENT_PROGRESS));
3534
+ let measured;
3535
+ try {
3536
+ if (typeof element?.evaluateInUtility === "function")
3537
+ measured = await bounded2(element.evaluateInUtility(iframeGeometryInUtilityWorld, null));
3538
+ } finally {
3539
+ element?.dispose?.();
3540
+ }
3541
+ if (measured === "transformed")
3542
+ return withoutBoxes([], "transformed");
3543
+ if (!isGeometry(measured))
3544
+ return withoutBoxes([], "unknown");
3545
+ if (inner && !drawnAtScale(measured, inner))
3546
+ return withoutBoxes([], "transformed");
3547
+ inner = measured.parentViewport;
3548
+ x += measured.x;
3549
+ y += measured.y;
3550
+ size ??= { width: measured.width, height: measured.height };
3551
+ current = parent;
3552
+ }
3553
+ } catch {
3554
+ return withoutBoxes([], "unknown");
3555
+ }
3556
+ return size ? { x, y, ...size } : PAGE;
3557
+ };
3558
+ const captureFrame = async (currentFrame, selector, frameOptions, isMainFrame = false, framePath = [], placing) => {
3435
3559
  if (!isServerFrame(currentFrame))
3436
3560
  throw new Error(UNAVAILABLE);
3437
3561
  if (Date.now() >= deadline)
@@ -3444,9 +3568,11 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
3444
3568
  throw error;
3445
3569
  captured = null;
3446
3570
  }
3571
+ let placement = await placing;
3447
3572
  if (!captured) {
3448
3573
  if (!isMainFrame) {
3449
3574
  document2.unavailableFrames.push(framePath.at(-1));
3575
+ document2.framesWithoutBoxes = document2.framesWithoutBoxes.filter((item) => item.framePath.join(" ") !== framePath.join(" "));
3450
3576
  return [];
3451
3577
  }
3452
3578
  if (options.scope?.startsWith("aria-ref=")) {
@@ -3456,15 +3582,22 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
3456
3582
  if (options.frames?.length)
3457
3583
  throw new Error("Snapshot frame selection failed. Each frames selector must match exactly one iframe with a loaded document.");
3458
3584
  await bounded2(new Promise((resolve2) => setTimeout(resolve2, 50)));
3459
- return captureFrame(currentFrame, selector, frameOptions, true);
3585
+ return captureFrame(currentFrame, selector, frameOptions, true, framePath, placement);
3460
3586
  }
3461
3587
  if (captured.info?.world !== "utility" || !isServerFrame(captured.frame))
3462
3588
  throw new Error(UNAVAILABLE);
3463
3589
  validateSnapshot(captured.result);
3464
3590
  const snapshot = captured.result;
3591
+ if (placement === PAGE && isMainFrame && refScope && captured.frame !== frame)
3592
+ placement = await scopePlacement(captured.frame);
3593
+ if (placement && snapshot.viewport && !drawnAtScale(placement, snapshot.viewport))
3594
+ placement = withoutBoxes(framePath, "transformed");
3595
+ const unchanged = placement === undefined || placement === PAGE;
3465
3596
  document2.priorityRefs.push(...snapshot.priorityRefs ?? []);
3466
- for (const match of snapshot.matches ?? [])
3467
- document2.matches.push({ ...match, framePath });
3597
+ for (const { box, ...match } of snapshot.matches ?? []) {
3598
+ const page2 = unchanged ? box : placement ? { ...box, x: Math.round(box.x + placement.x), y: Math.round(box.y + placement.y) } : undefined;
3599
+ document2.matches.push({ ...match, ...page2 ? { box: page2 } : {}, framePath });
3600
+ }
3468
3601
  document2.matchCount += snapshot.matchCount ?? 0;
3469
3602
  if (snapshot.scopeMatchCount !== undefined)
3470
3603
  document2.scopeMatchCount = snapshot.scopeMatchCount;
@@ -3478,11 +3611,12 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
3478
3611
  scope: undefined,
3479
3612
  scopeName: undefined,
3480
3613
  rootIsScope: false
3481
- }, false, childPath));
3614
+ }, false, childPath, placement === undefined ? undefined : iframePlacement(captured.frame, `aria-ref=${ref}`, placement, childPath)));
3482
3615
  }));
3483
3616
  const lines = [];
3484
- for (const line of snapshot.text.split(`
3617
+ for (const rendered of snapshot.text.split(`
3485
3618
  `)) {
3619
+ const line = frameOptions.boxes && !unchanged ? moveLineBox(rendered, placement ?? null) : rendered;
3486
3620
  const { role, ref } = snapshotLine(line);
3487
3621
  const child = role === "iframe" && ref ? children.get(ref) : undefined;
3488
3622
  lines.push(child?.length ? `${line}:` : line);
@@ -3493,9 +3627,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
3493
3627
  }
3494
3628
  return lines;
3495
3629
  };
3496
- const prefix = (options.frames ?? []).map((selector) => `${selector} >> internal:control=enter-frame >> `).join("");
3497
- const refScope = options.scope?.startsWith("aria-ref=") ? options.scope : undefined;
3498
- document2.text = (await captureFrame(frame, refScope ?? `${prefix}body,frameset`, refScope ? { ...renderOptions, scope: undefined, rootIsScope: true } : renderOptions, true)).join(`
3630
+ document2.text = (await captureFrame(frame, refScope ?? `${prefix}body,frameset`, refScope ? { ...renderOptions, scope: undefined, rootIsScope: true } : renderOptions, true, [], !geometry ? undefined : options.frames?.length ? await selectedPlacement() : PAGE)).join(`
3499
3631
  `);
3500
3632
  return document2;
3501
3633
  }
@@ -3659,7 +3791,7 @@ function matchKey(match, boxes) {
3659
3791
  for (const state of MATCH_STATES)
3660
3792
  if (match.states[state] !== undefined)
3661
3793
  key2 += ` [${state}=${JSON.stringify(match.states[state])}]`;
3662
- return `${key2} [ref=${match.ref}]${boxes ? ` [box=${[match.box.x, match.box.y, match.box.width, match.box.height].join(",")}]` : ""}`;
3794
+ return `${key2} [ref=${match.ref}]${boxes && match.box ? ` [box=${[match.box.x, match.box.y, match.box.width, match.box.height].join(",")}]` : ""}`;
3663
3795
  }
3664
3796
  var publicMatch = (match, inOutline, framePath) => ({
3665
3797
  ref: match.ref,
@@ -3668,7 +3800,7 @@ var publicMatch = (match, inOutline, framePath) => ({
3668
3800
  ...match.value !== undefined ? { value: match.value } : {},
3669
3801
  ...match.text ? { text: match.text } : {},
3670
3802
  states: match.states,
3671
- box: match.box,
3803
+ ...match.box ? { box: match.box } : {},
3672
3804
  inOutline,
3673
3805
  ...framePath.length ? { framePath } : {}
3674
3806
  });
@@ -3796,6 +3928,10 @@ function renderSnapshot(document2, input) {
3796
3928
  notes.push(document2.restoredFromCache ? "This page was restored from the back/forward cache, and some of its frames cannot be read until it loads again: browser_history reload loads it afresh, without the state it kept." : "Some frames disappeared or were unavailable during capture; refresh before treating the observation as complete.");
3797
3929
  if (unrepresentedMatches)
3798
3930
  notes.push(`${unrepresentedMatches} visible matching elements have no ref: one frame had more than ${MAX_MATCH_DETAILS} matches. Narrow the query or scope it.`);
3931
+ const boxless = document2.framesWithoutBoxes ?? [];
3932
+ const framesWithoutBoxes = input.boxes ? boxless : input.query ? boxless.filter((frame) => document2.matches.some((match) => !match.box && frame.framePath.every((ref, index) => match.framePath[index] === ref))) : [];
3933
+ if (framesWithoutBoxes.length)
3934
+ notes.push("Elements of frames that the page transforms, scales or zooms, or whose iframe could not be measured, have no boxes (completeness.framesWithoutBoxes; an empty framePath is the frame this read started in): their place in the page's viewport is unknown. Click them by ref.");
3799
3935
  if (returned.some((match) => !match.inOutline))
3800
3936
  notes.push("Matches with inOutline false are not shown in the outline (such as a text span inside a table cell), but their refs work with every ref-taking tool. A DOM-backed ref (d12, f1d3) becomes stale once its element leaves the page or its frame navigates.");
3801
3937
  if (nextOffset !== null)
@@ -3813,7 +3949,8 @@ function renderSnapshot(document2, input) {
3813
3949
  depthOmittedLines: depthOmitted,
3814
3950
  characterLimited,
3815
3951
  unavailableFrames: document2.unavailableFrames,
3816
- ...input.query ? { unrepresentedMatches } : {}
3952
+ ...input.query ? { unrepresentedMatches } : {},
3953
+ ...framesWithoutBoxes.length ? { framesWithoutBoxes } : {}
3817
3954
  },
3818
3955
  ...input.query ? { matchCount: document2.matchCount, returnedMatches, offset: input.offset, nextOffset, matches: returned } : {},
3819
3956
  ...notes.length ? { note: notes.join(" ") } : {}
@@ -3821,20 +3958,38 @@ function renderSnapshot(document2, input) {
3821
3958
  }
3822
3959
 
3823
3960
  // cli/src/browser/back-forward-cache.ts
3961
+ var OTHER_DOCUMENT = new Set(["differentDocument", "historyDifferentDocument", "reload", "reloadBypassingCache", "restore", "restoreWithPost"]);
3824
3962
  var REMEMBERED_DOCUMENTS = 32;
3825
3963
  var COMMIT_HEARD_MS = 1000;
3826
3964
 
3827
3965
  class MainFrameDocuments {
3828
3966
  cdp;
3829
3967
  commits = 0;
3968
+ pending;
3830
3969
  current;
3970
+ mainFrameId;
3831
3971
  reached = new Map;
3832
3972
  listeners = new Set;
3833
3973
  constructor(cdp) {
3834
3974
  this.cdp = cdp;
3975
+ cdp.send("Target.getTargetInfo").then(({ targetInfo }) => {
3976
+ this.mainFrameId ??= targetInfo.targetId;
3977
+ }).catch(() => {
3978
+ return;
3979
+ });
3980
+ cdp.on("Page.frameStartedNavigating", ({ frameId, url, navigationType }) => {
3981
+ if (frameId === this.mainFrameId && OTHER_DOCUMENT.has(navigationType))
3982
+ this.pending = { url, since: Date.now() };
3983
+ });
3984
+ cdp.on("Page.frameStoppedLoading", ({ frameId }) => {
3985
+ if (frameId === this.mainFrameId)
3986
+ this.pending = undefined;
3987
+ });
3835
3988
  cdp.on("Page.frameNavigated", ({ frame, type }) => {
3836
3989
  if (frame.parentId)
3837
3990
  return;
3991
+ this.mainFrameId = frame.id;
3992
+ this.pending = undefined;
3838
3993
  const restored = type === "BackForwardCacheRestore";
3839
3994
  this.current = { frameId: frame.id, loaderId: frame.loaderId, url: frame.url + (frame.urlFragment ?? ""), restored, committedAt: ++this.commits };
3840
3995
  const known = this.reached.get(frame.loaderId);
@@ -3925,6 +4080,9 @@ function followDocuments(page, cdp) {
3925
4080
  function commitsHeard(page) {
3926
4081
  return followed2.get(page)?.commits;
3927
4082
  }
4083
+ function pendingNavigation(page) {
4084
+ return followed2.get(page)?.pending;
4085
+ }
3928
4086
  function restoredFromCache(page, since) {
3929
4087
  const documents = followed2.get(page);
3930
4088
  return documents && since !== undefined ? documents.restoredSince(page, since) : undefined;
@@ -4181,371 +4339,79 @@ async function waitForBrowserCondition(page, input, network) {
4181
4339
  return timedOut(counts2);
4182
4340
  }
4183
4341
 
4184
- // cli/src/browser/navigation-observer.ts
4185
- function navigationUrlMatches(pattern, url) {
4186
- if (!pattern)
4187
- return true;
4188
- const source = pattern.split(/(\*\*|\*)/).map((part) => part === "**" ? ".*" : part === "*" ? "[^/]*" : part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("");
4189
- return new RegExp(`^${source}$`).test(url);
4190
- }
4191
- function observeNavigation(page, input) {
4192
- const started = Date.now(), deadline = started + input.timeoutMs;
4193
- const since = commitsHeard(page);
4194
- let settled = false;
4195
- let resolve2;
4196
- const result = new Promise((done) => {
4197
- resolve2 = done;
4342
+ // cli/src/browser/passkey-guard.ts
4343
+ var MAX_PASSKEY_REQUESTS = 16;
4344
+ function passkeyGuardSource(binding, cancelEvent) {
4345
+ const name = JSON.stringify(binding), cancel = JSON.stringify(cancelEvent);
4346
+ return `(() => {
4347
+ const report = globalThis[${name}];
4348
+ try { delete globalThis[${name}]; } catch {}
4349
+ const C = globalThis.CredentialsContainer;
4350
+ if (typeof report !== "function" || !C || !C.prototype || typeof AbortController !== "function") return;
4351
+ const send = (message) => { try { report(JSON.stringify(message)); } catch {} };
4352
+ const pending = new Map();
4353
+ let seq = 0;
4354
+ addEventListener(${cancel}, () => {
4355
+ for (const controller of pending.values()) controller.abort(new DOMException("The passkey prompt was cancelled.", "AbortError"));
4198
4356
  });
4199
- const finish = (matched, code2, error) => {
4200
- if (settled)
4201
- return;
4202
- settled = true;
4203
- clearTimeout(timer2);
4204
- page.off("framenavigated", onNavigation);
4205
- page.off("close", onClose);
4206
- page.off("crash", onClose);
4207
- resolve2({ matched, url: page.url(), elapsedMs: Date.now() - started, waitUntil: input.waitUntil, ...code2 ? { code: code2, error } : {} });
4208
- };
4209
- const onClose = () => finish(false, "navigation_tab_closed", "The tab closed before navigation was observed. Inspect tabs before another action.");
4210
- const onNavigation = (frame) => {
4211
- if (frame !== page.mainFrame() || !navigationUrlMatches(input.url, frame.url()))
4212
- return;
4213
- if (input.waitUntil === "commit") {
4214
- finish(true);
4215
- return;
4216
- }
4217
- waitForLoadState(page, input.waitUntil, Math.max(1, deadline - Date.now()), since).then(() => {
4218
- if (navigationUrlMatches(input.url, page.url()))
4219
- finish(true);
4220
- }, () => {
4221
- return;
4222
- });
4223
- };
4224
- const timer2 = setTimeout(() => finish(false, "navigation_timeout", "Input was dispatched, but the expected navigation was not observed before the deadline. Inspect the page; do not repeat the action solely because this wait timed out."), input.timeoutMs);
4225
- page.on("framenavigated", onNavigation);
4226
- page.on("close", onClose);
4227
- page.on("crash", onClose);
4228
- return { result, dispose: () => finish(false, "navigation_observation_cancelled", "Navigation observation ended.") };
4357
+ for (const name of ["get", "create"]) {
4358
+ const descriptor = Object.getOwnPropertyDescriptor(C.prototype, name);
4359
+ const original = descriptor && descriptor.value;
4360
+ if (typeof original !== "function") continue;
4361
+ const wrapped = { [name](options) {
4362
+ if (!options || typeof options !== "object" || !options.publicKey || options.mediation === "conditional") return original.apply(this, arguments);
4363
+ const id = ++seq, controller = new AbortController();
4364
+ let request;
4365
+ try {
4366
+ let signal = controller.signal;
4367
+ const own = options.signal;
4368
+ if (own && typeof AbortSignal.any === "function") signal = AbortSignal.any([own, controller.signal]);
4369
+ else if (own) {
4370
+ if (own.aborted) controller.abort(own.reason);
4371
+ else own.addEventListener("abort", () => controller.abort(own.reason), { once: true });
4372
+ }
4373
+ // The page's own options, with the combined signal in place of theirs: members on their
4374
+ // prototype chain included, and their getters still run on them. A signal property
4375
+ // the page made non-configurable cannot be replaced that way; it is shadowed instead.
4376
+ const fixed = Object.getOwnPropertyDescriptor(options, "signal");
4377
+ request = fixed && !fixed.configurable
4378
+ ? Object.create(options, { signal: { value: signal, enumerable: true } })
4379
+ : new Proxy(options, { get: (target, key) => (key === "signal" ? signal : Reflect.get(target, key, target)) });
4380
+ } catch {
4381
+ // Not an AbortSignal: Chrome rejects the request itself, as without this script.
4382
+ return original.apply(this, arguments);
4383
+ }
4384
+ const result = original.call(this, request);
4385
+ pending.set(id, controller);
4386
+ send({ state: "open", id, request: name });
4387
+ const done = () => { if (pending.delete(id)) send({ state: "closed", id }); };
4388
+ Promise.resolve(result).then(done, done);
4389
+ return result;
4390
+ } }[name];
4391
+ try { Object.defineProperty(wrapped, "length", { value: original.length }); } catch {}
4392
+ Object.defineProperty(C.prototype, name, Object.assign({}, descriptor, { value: wrapped }));
4393
+ }
4394
+ })();`;
4229
4395
  }
4230
-
4231
- // cli/src/browser/frame-history.ts
4232
- var POLL_MS = 50;
4233
- var UNSEEN_COMMIT_MS = 300;
4234
- var FRAME_LOADED_MS = 5000;
4235
- async function traverseToEntry(page, cdp, entryId, timeoutMs) {
4236
- const deadline = Date.now() + timeoutMs;
4237
- const mainId = await cdp.send("Page.getFrameTree").then(({ frameTree }) => frameTree.frame.id, () => {
4238
- return;
4239
- });
4240
- let mainSeen = false;
4241
- let childSeen = false;
4242
- let sameDocument = false;
4243
- let childFrame;
4244
- let response = null;
4245
- let reachedAt;
4246
- let settle;
4247
- const committed = new Promise((resolve2, reject) => {
4248
- let settled = false;
4249
- settle = (value) => {
4250
- if (settled)
4251
- return;
4252
- settled = true;
4253
- stop();
4254
- if (value instanceof Error)
4255
- reject(value);
4256
- else
4257
- resolve2(value);
4258
- };
4259
- });
4260
- const decide = () => {
4261
- if (mainSeen)
4262
- settle("main");
4263
- else if (reachedAt !== undefined && (childSeen || Date.now() - reachedAt >= UNSEEN_COMMIT_MS))
4264
- settle("child");
4265
- };
4266
- const readEntry = () => void cdp.send("Page.getNavigationHistory").then(({ currentIndex, entries }) => {
4267
- if (entries[currentIndex]?.id === entryId)
4268
- reachedAt ??= Date.now();
4269
- decide();
4270
- }, () => {
4271
- return;
4272
- });
4273
- const seen = (main) => {
4274
- if (main)
4275
- mainSeen = true;
4276
- else
4277
- childSeen = true;
4278
- if (mainSeen)
4279
- decide();
4280
- else
4281
- readEntry();
4282
- };
4283
- const onFrameNavigated = (frame) => {
4284
- if (frame !== page.mainFrame())
4285
- childFrame = frame;
4286
- seen(frame === page.mainFrame());
4287
- };
4288
- const onResponse = (candidate) => {
4289
- if (candidate.frame() === page.mainFrame() && candidate.request().isNavigationRequest())
4290
- response = candidate;
4291
- };
4292
- const onClose = () => settle(new Error("Target page, context or browser has been closed"));
4293
- const onCrash = () => settle(new Error("Target crashed"));
4294
- const onCommit = ({ frame }) => seen(!frame.parentId);
4295
- const onWithinDocument = ({ frameId }) => {
4296
- if (mainId === undefined)
4297
- return;
4298
- if (frameId !== mainId)
4299
- sameDocument = true;
4300
- seen(frameId === mainId);
4301
- };
4302
- page.on("framenavigated", onFrameNavigated);
4303
- page.on("response", onResponse);
4304
- page.on("close", onClose);
4305
- page.on("crash", onCrash);
4306
- cdp.on("Page.frameNavigated", onCommit);
4307
- cdp.on("Page.navigatedWithinDocument", onWithinDocument);
4308
- const poll = setInterval(readEntry, POLL_MS);
4309
- const timer2 = setTimeout(() => settle(new Error(`Timeout ${timeoutMs}ms exceeded waiting for the history entry to commit.`)), Math.max(1, deadline - Date.now()));
4310
- function stop() {
4311
- clearInterval(poll);
4312
- clearTimeout(timer2);
4313
- page.off("framenavigated", onFrameNavigated);
4314
- page.off("response", onResponse);
4315
- page.off("close", onClose);
4316
- page.off("crash", onCrash);
4317
- cdp.off("Page.frameNavigated", onCommit);
4318
- cdp.off("Page.navigatedWithinDocument", onWithinDocument);
4396
+ function parsePasskeyReport(payload) {
4397
+ let value;
4398
+ try {
4399
+ value = JSON.parse(payload);
4400
+ } catch {
4401
+ return null;
4319
4402
  }
4320
- await cdp.send("Page.navigateToHistoryEntry", { entryId }).catch((error) => settle(error instanceof Error ? error : new Error(String(error))));
4321
- if (await committed === "main")
4322
- return { frame: "main", response };
4323
- if (childFrame && !sameDocument && !childFrame.isDetached())
4324
- await childFrame.waitForLoadState("domcontentloaded", { timeout: Math.max(1, Math.min(FRAME_LOADED_MS, deadline - Date.now())) }).catch(() => {
4325
- return;
4326
- });
4327
- return { frame: "child" };
4403
+ if (!value || typeof value !== "object" || Array.isArray(value))
4404
+ return null;
4405
+ const v = value;
4406
+ if (typeof v.id !== "number" || !Number.isSafeInteger(v.id) || v.id < 1)
4407
+ return null;
4408
+ if (v.state === "closed")
4409
+ return { state: "closed", id: v.id };
4410
+ if (v.state === "open" && (v.request === "get" || v.request === "create"))
4411
+ return { state: "open", id: v.id, request: v.request };
4412
+ return null;
4328
4413
  }
4329
-
4330
- // cli/src/browser/frame-input.ts
4331
- var MODIFIER_BITS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
4332
- var BUTTON_BITS = { left: 1, right: 2, middle: 4 };
4333
- function frameOrigin(iframe) {
4334
- const view = iframe.ownerDocument?.defaultView;
4335
- if (!iframe.isConnected || !view)
4336
- return "detached";
4337
- const zoom = iframe.currentCSSZoom;
4338
- if (zoom !== undefined && zoom !== 1)
4339
- return "transformed";
4340
- for (let node = iframe;node; node = node.parentElement ?? (node.getRootNode().host || null)) {
4341
- const style2 = view.getComputedStyle(node);
4342
- if (style2.transform !== "none" || style2.scale !== "none" || style2.rotate !== "none" || style2.translate !== "none")
4343
- return "transformed";
4344
- }
4345
- const box = iframe.getBoundingClientRect();
4346
- const style = view.getComputedStyle(iframe);
4347
- return { x: box.left + iframe.clientLeft + Number.parseFloat(style.paddingLeft), y: box.top + iframe.clientTop + Number.parseFloat(style.paddingTop) };
4348
- }
4349
- function parentHit(iframe, options) {
4350
- const root = iframe.getRootNode();
4351
- const view = iframe.ownerDocument.defaultView;
4352
- if (options.point.x < 0 || options.point.y < 0 || options.point.x >= view.innerWidth || options.point.y >= view.innerHeight)
4353
- return "outside";
4354
- const hit = root.elementFromPoint(options.point.x, options.point.y);
4355
- if (!hit)
4356
- return "outside";
4357
- if (hit === iframe)
4358
- return null;
4359
- const role = hit.getAttribute("role") ?? undefined;
4360
- const field = hit.tagName === "INPUT" || hit.tagName === "TEXTAREA" || hit.tagName === "SELECT";
4361
- const password = hit.tagName === "INPUT" && hit.type === "password";
4362
- const raw = hit.getAttribute("aria-label") ?? hit.getAttribute("title") ?? (field ? [...hit.labels ?? []][0]?.textContent || (password ? "" : hit.getAttribute("placeholder") ?? "") : hit.textContent ?? "");
4363
- const name = raw.replace(/\s+/g, " ").trim().slice(0, options.nameChars);
4364
- return { tag: hit.tagName.toLowerCase(), ...role ? { role } : {}, ...name ? { name } : {} };
4365
- }
4366
-
4367
- class FrameInput {
4368
- page;
4369
- chain;
4370
- inRoot;
4371
- session;
4372
- constructor(page, chain, inRoot, session) {
4373
- this.page = page;
4374
- this.chain = chain;
4375
- this.inRoot = inRoot;
4376
- this.session = session;
4377
- }
4378
- static async of(page, handle) {
4379
- if (!showsRestoredDocument(page))
4380
- return;
4381
- const frame = await handle.ownerFrame().catch(() => null);
4382
- if (!frame?.parentFrame())
4383
- return;
4384
- const chain = [];
4385
- for (let node = frame;node?.parentFrame(); node = node.parentFrame())
4386
- chain.push(node);
4387
- for (let index = 0;index < chain.length; index++) {
4388
- const session = await page.context().newCDPSession(chain[index]).catch(() => {
4389
- return;
4390
- });
4391
- if (session)
4392
- return new FrameInput(page, chain, index + 1, session);
4393
- }
4394
- return;
4395
- }
4396
- async path(point, nameChars) {
4397
- let current = point;
4398
- let root = point;
4399
- for (let index = 0;index < this.chain.length; index++) {
4400
- if (index === this.inRoot - 1)
4401
- root = current;
4402
- const iframe = await this.chain[index].frameElement().catch(() => {
4403
- return;
4404
- });
4405
- if (!iframe)
4406
- return;
4407
- try {
4408
- const origin = await iframe.evaluate(frameOrigin);
4409
- if (origin === "transformed" || origin === "detached")
4410
- return;
4411
- current = { x: current.x + origin.x, y: current.y + origin.y };
4412
- const hit = await iframe.evaluate(parentHit, { point: current, nameChars });
4413
- if (hit === "outside")
4414
- return { kind: "outside_viewport" };
4415
- if (hit)
4416
- return { kind: "covered", cover: hit };
4417
- } catch {
4418
- return;
4419
- } finally {
4420
- iframe.dispose().catch(() => {
4421
- return;
4422
- });
4423
- }
4424
- }
4425
- return { kind: "reached", root };
4426
- }
4427
- async reveal(timeout2) {
4428
- for (const frame of this.chain.toReversed()) {
4429
- const iframe = await frame.frameElement().catch(() => {
4430
- return;
4431
- });
4432
- if (!iframe)
4433
- return;
4434
- try {
4435
- await iframe.scrollIntoViewIfNeeded({ timeout: timeout2 });
4436
- } catch {} finally {
4437
- iframe.dispose().catch(() => {
4438
- return;
4439
- });
4440
- }
4441
- }
4442
- }
4443
- send(type, point, extra) {
4444
- return this.session.send("Input.dispatchMouseEvent", { type, x: point.x, y: point.y, ...extra });
4445
- }
4446
- bits(modifiers) {
4447
- let bits = 0;
4448
- for (const modifier of modifiers)
4449
- bits |= MODIFIER_BITS[modifier === "ControlOrMeta" ? process.platform === "darwin" ? "Meta" : "Control" : modifier];
4450
- return bits;
4451
- }
4452
- async click(point, button, clickCount) {
4453
- await this.send("mouseMoved", point, {});
4454
- for (let count = 1;count <= clickCount; count++) {
4455
- await this.send("mousePressed", point, { button, buttons: BUTTON_BITS[button], clickCount: count });
4456
- await this.send("mouseReleased", point, { button, buttons: 0, clickCount: count });
4457
- }
4458
- }
4459
- async hover(point, modifiers) {
4460
- for (const modifier of modifiers)
4461
- await this.page.keyboard.down(modifier);
4462
- try {
4463
- await this.send("mouseMoved", point, { modifiers: this.bits(modifiers) });
4464
- } finally {
4465
- for (const modifier of modifiers.toReversed())
4466
- await this.page.keyboard.up(modifier);
4467
- }
4468
- }
4469
- dispose() {
4470
- this.session.detach().catch(() => {
4471
- return;
4472
- });
4473
- }
4474
- }
4475
-
4476
- // cli/src/browser/passkey-guard.ts
4477
- var MAX_PASSKEY_REQUESTS = 16;
4478
- function passkeyGuardSource(binding, cancelEvent) {
4479
- const name = JSON.stringify(binding), cancel = JSON.stringify(cancelEvent);
4480
- return `(() => {
4481
- const report = globalThis[${name}];
4482
- try { delete globalThis[${name}]; } catch {}
4483
- const C = globalThis.CredentialsContainer;
4484
- if (typeof report !== "function" || !C || !C.prototype || typeof AbortController !== "function") return;
4485
- const send = (message) => { try { report(JSON.stringify(message)); } catch {} };
4486
- const pending = new Map();
4487
- let seq = 0;
4488
- addEventListener(${cancel}, () => {
4489
- for (const controller of pending.values()) controller.abort(new DOMException("The passkey prompt was cancelled.", "AbortError"));
4490
- });
4491
- for (const name of ["get", "create"]) {
4492
- const descriptor = Object.getOwnPropertyDescriptor(C.prototype, name);
4493
- const original = descriptor && descriptor.value;
4494
- if (typeof original !== "function") continue;
4495
- const wrapped = { [name](options) {
4496
- if (!options || typeof options !== "object" || !options.publicKey || options.mediation === "conditional") return original.apply(this, arguments);
4497
- const id = ++seq, controller = new AbortController();
4498
- let request;
4499
- try {
4500
- let signal = controller.signal;
4501
- const own = options.signal;
4502
- if (own && typeof AbortSignal.any === "function") signal = AbortSignal.any([own, controller.signal]);
4503
- else if (own) {
4504
- if (own.aborted) controller.abort(own.reason);
4505
- else own.addEventListener("abort", () => controller.abort(own.reason), { once: true });
4506
- }
4507
- // The page's own options, with the combined signal in place of theirs: members on their
4508
- // prototype chain included, and their getters still run on them. A signal property
4509
- // the page made non-configurable cannot be replaced that way; it is shadowed instead.
4510
- const fixed = Object.getOwnPropertyDescriptor(options, "signal");
4511
- request = fixed && !fixed.configurable
4512
- ? Object.create(options, { signal: { value: signal, enumerable: true } })
4513
- : new Proxy(options, { get: (target, key) => (key === "signal" ? signal : Reflect.get(target, key, target)) });
4514
- } catch {
4515
- // Not an AbortSignal: Chrome rejects the request itself, as without this script.
4516
- return original.apply(this, arguments);
4517
- }
4518
- const result = original.call(this, request);
4519
- pending.set(id, controller);
4520
- send({ state: "open", id, request: name });
4521
- const done = () => { if (pending.delete(id)) send({ state: "closed", id }); };
4522
- Promise.resolve(result).then(done, done);
4523
- return result;
4524
- } }[name];
4525
- try { Object.defineProperty(wrapped, "length", { value: original.length }); } catch {}
4526
- Object.defineProperty(C.prototype, name, Object.assign({}, descriptor, { value: wrapped }));
4527
- }
4528
- })();`;
4529
- }
4530
- function parsePasskeyReport(payload) {
4531
- let value;
4532
- try {
4533
- value = JSON.parse(payload);
4534
- } catch {
4535
- return null;
4536
- }
4537
- if (!value || typeof value !== "object" || Array.isArray(value))
4538
- return null;
4539
- const v = value;
4540
- if (typeof v.id !== "number" || !Number.isSafeInteger(v.id) || v.id < 1)
4541
- return null;
4542
- if (v.state === "closed")
4543
- return { state: "closed", id: v.id };
4544
- if (v.state === "open" && (v.request === "get" || v.request === "create"))
4545
- return { state: "open", id: v.id, request: v.request };
4546
- return null;
4547
- }
4548
- var PASSKEY_PROMPT_RECOVERY = `Chrome is showing a passkey prompt for this tab. Chrome draws it outside the page, so screenshots and live view don't show it, and it ignores mouse, keyboard and scroll input to the tab until the prompt is completed or cancelled. Only the user can complete it, at the computer that runs this browser (Touch ID or Windows Hello, a security key, or a phone that scans its QR code); Chrome shows it there only while this tab is the active tab of its window (browser_present {mode: "focus"} makes it so). Hand the tab to the user with browser_takeover so they can complete or cancel it, or cancel it with browser_handle_dialog {dialogId, decision: "dismiss"} when choosing another sign-in method is within the user's authorized task. Reloading or navigating the tab also cancels it.`;
4414
+ var PASSKEY_PROMPT_RECOVERY = `Chrome is showing a passkey prompt for this tab. Chrome draws it outside the page, so screenshots and live view don't show it, and it ignores mouse, keyboard and scroll input to the tab until the prompt is completed or cancelled. Only the user can complete it, at the computer that runs this browser (Touch ID or Windows Hello, a security key, or a phone that scans its QR code); Chrome shows it there only while this tab is the active tab of its window (browser_present {mode: "focus"} makes it so). Hand the tab to the user with browser_takeover so they can complete or cancel it, or cancel it with browser_handle_dialog {dialogId, decision: "dismiss"} when choosing another sign-in method is within the user's authorized task. Reloading or navigating the tab also cancels it.`;
4549
4415
 
4550
4416
  // cli/src/browser/http-auth.ts
4551
4417
  var ENABLE_MS = 1500;
@@ -4865,6 +4731,7 @@ class HttpAuthPrompts {
4865
4731
  var PASSKEY_ANNOUNCE_MS = 300;
4866
4732
  var PASSKEY_CANCEL_MS = 2000;
4867
4733
  var PASSKEY_FLUSH_MS = 250;
4734
+ var LOADING_PROBE_MS = 300;
4868
4735
  var PASSKEY_WORLD = "__browser_mcp_passkey__";
4869
4736
  var CAPACITY = 200;
4870
4737
  var RETENTION_MS = 10 * 60000;
@@ -4905,6 +4772,60 @@ function requestUrl(request) {
4905
4772
  return "";
4906
4773
  }
4907
4774
  }
4775
+ var DIALOG_WAIT_MS = 10 * 60000;
4776
+
4777
+ class NavigationDeadline {
4778
+ ms;
4779
+ done;
4780
+ expired;
4781
+ fail;
4782
+ left;
4783
+ since;
4784
+ timer;
4785
+ stopped = false;
4786
+ heldOnce = false;
4787
+ constructor(ms, held, done) {
4788
+ this.ms = ms;
4789
+ this.done = done;
4790
+ this.left = ms;
4791
+ this.expired = new Promise((_resolve, reject) => this.fail = reject);
4792
+ this.expired.catch(() => {
4793
+ return;
4794
+ });
4795
+ this.update(held);
4796
+ }
4797
+ update(held) {
4798
+ if (this.stopped)
4799
+ return;
4800
+ if (held) {
4801
+ this.heldOnce = true;
4802
+ if (this.since === undefined)
4803
+ return;
4804
+ this.left -= Date.now() - this.since;
4805
+ this.since = undefined;
4806
+ clearTimeout(this.timer);
4807
+ } else if (this.since === undefined) {
4808
+ this.since = Date.now();
4809
+ this.timer = setTimeout(() => {
4810
+ this.stop();
4811
+ this.fail(new Error(`Timeout ${this.ms}ms exceeded.`));
4812
+ }, Math.max(0, this.left));
4813
+ }
4814
+ }
4815
+ held() {
4816
+ return !this.stopped && this.since === undefined;
4817
+ }
4818
+ wasHeld() {
4819
+ return this.heldOnce;
4820
+ }
4821
+ stop() {
4822
+ if (this.stopped)
4823
+ return;
4824
+ this.stopped = true;
4825
+ clearTimeout(this.timer);
4826
+ this.done();
4827
+ }
4828
+ }
4908
4829
 
4909
4830
  class BrowserPageEvents {
4910
4831
  page;
@@ -4943,6 +4864,7 @@ class BrowserPageEvents {
4943
4864
  currentAction;
4944
4865
  recentAction;
4945
4866
  httpAuth;
4867
+ deadlines = new Set;
4946
4868
  document = 0;
4947
4869
  constructor(page, passkeyDetection = true, holdHttpAuth) {
4948
4870
  this.page = page;
@@ -5204,7 +5126,7 @@ class BrowserPageEvents {
5204
5126
  }
5205
5127
  async flushPasskeyReports() {
5206
5128
  const cdp = this.cdp;
5207
- if (!cdp || !this.passkeyDetection || this.dialog || this.crashed || this.httpAuth.holdsMainFrame())
5129
+ if (!cdp || !this.passkeyDetection || this.dialog || this.crashed || this.httpAuth.holdsMainFrame() || this.navigationLoading())
5208
5130
  return;
5209
5131
  let timer2;
5210
5132
  await Promise.race([
@@ -5283,6 +5205,8 @@ class BrowserPageEvents {
5283
5205
  return passkey?.announced ? { type: "passkey", message: "", defaultValue: "", request: passkey.request, origin: passkey.origin } : null;
5284
5206
  }
5285
5207
  dialogChanged() {
5208
+ for (const deadline of this.deadlines)
5209
+ deadline.update(this.holdsNavigation());
5286
5210
  const details = this.dialogDetails();
5287
5211
  for (const listener of [...this.dialogListeners]) {
5288
5212
  try {
@@ -5443,6 +5367,22 @@ class BrowserPageEvents {
5443
5367
  session() {
5444
5368
  return this.cdp;
5445
5369
  }
5370
+ navigationLoading() {
5371
+ return !!pendingNavigation(this.page);
5372
+ }
5373
+ async loadingPage() {
5374
+ const pending = pendingNavigation(this.page);
5375
+ const cdp = this.cdp;
5376
+ if (!pending || !cdp)
5377
+ return;
5378
+ let timer2;
5379
+ const answered = await Promise.race([
5380
+ cdp.send("Runtime.evaluate", { expression: "0", silent: true }).then(() => true, () => true),
5381
+ new Promise((resolve2) => timer2 = setTimeout(() => resolve2(false), LOADING_PROBE_MS))
5382
+ ]);
5383
+ clearTimeout(timer2);
5384
+ return answered ? undefined : { url: diagnosticUrl(pending.url), pendingMs: Math.max(0, Date.now() - pending.since) };
5385
+ }
5446
5386
  setCrashed(crashed) {
5447
5387
  this.crashed = crashed;
5448
5388
  if (!crashed)
@@ -5579,7 +5519,20 @@ class BrowserPageEvents {
5579
5519
  pendingAction() {
5580
5520
  return this.pending ? { actionId: this.pending.actionId, status: "pending" } : null;
5581
5521
  }
5522
+ markUnanswered() {
5523
+ if (this.pending)
5524
+ this.pending.unanswered = true;
5525
+ }
5526
+ holdsNavigation() {
5527
+ return !!this.dialog || this.httpAuth.isOpen();
5528
+ }
5529
+ navigationDeadline(ms) {
5530
+ const deadline = new NavigationDeadline(ms, this.holdsNavigation(), () => this.deadlines.delete(deadline));
5531
+ this.deadlines.add(deadline);
5532
+ return deadline;
5533
+ }
5582
5534
  async handleDialog(input, handledBy = "agent", options = {}) {
5535
+ const held = this.pending;
5583
5536
  const auth = await this.httpAuth.answer(input.dialogId, input, handledBy === "viewer" ? { by: "viewer", typed: options.typed } : {
5584
5537
  by: "agent",
5585
5538
  vaultId: typeof input.vaultId === "string" ? input.vaultId : undefined,
@@ -5588,7 +5541,7 @@ class BrowserPageEvents {
5588
5541
  reveal: options.reveal
5589
5542
  });
5590
5543
  if (auth) {
5591
- const pending2 = this.pending;
5544
+ const pending2 = held ?? this.pending;
5592
5545
  const outcome2 = auth.handled === true && auth.signIn !== "rejected" && pending2 ? await this.racePending(pending2, 1000) : undefined;
5593
5546
  return { ...auth, ...auth.handled === true ? { originalAction: outcome2 ?? this.pendingAction() } : {}, dialog: this.activeDialog() };
5594
5547
  }
@@ -5636,7 +5589,7 @@ class BrowserPageEvents {
5636
5589
  this.dialog = undefined;
5637
5590
  this.dialogChanged();
5638
5591
  }
5639
- const pending = this.pending;
5592
+ const pending = held ?? this.pending;
5640
5593
  const outcome = pending ? await this.racePending(pending, 1000) : undefined;
5641
5594
  return {
5642
5595
  handled: true,
@@ -5646,119 +5599,658 @@ class BrowserPageEvents {
5646
5599
  dialog: this.activeDialog()
5647
5600
  };
5648
5601
  }
5649
- async racePending(pending, ms) {
5650
- let timer2;
5602
+ async racePending(pending, ms) {
5603
+ let timer2;
5604
+ try {
5605
+ return await Promise.race([
5606
+ pending.result,
5607
+ new Promise((resolve2) => {
5608
+ timer2 = setTimeout(() => resolve2(undefined), ms);
5609
+ })
5610
+ ]);
5611
+ } finally {
5612
+ clearTimeout(timer2);
5613
+ }
5614
+ }
5615
+ async run(actionId, dispatch) {
5616
+ const holding = !!this.dialog || this.httpAuth.isOpen();
5617
+ if (holding || this.pending) {
5618
+ const httpAuth = this.dialog ? null : this.httpAuth.prompt();
5619
+ return {
5620
+ dispatch: { status: "not_dispatched", code: holding ? "dialog_blocking" : "previous_action_pending" },
5621
+ dialog: this.activeDialog(),
5622
+ ...httpAuth ? { httpAuth, recovery: HTTP_AUTH_RECOVERY } : {},
5623
+ pendingAction: this.pendingAction()
5624
+ };
5625
+ }
5626
+ this.currentAction = actionId;
5627
+ let interruptedByDialog = false;
5628
+ let wake;
5629
+ const interrupted = new Promise((resolve2) => {
5630
+ wake = () => {
5631
+ interruptedByDialog = true;
5632
+ const auth = this.dialog ? undefined : this.httpAuth.requiredResult(actionId);
5633
+ resolve2(auth ?? { dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
5634
+ };
5635
+ this.listeners.add(wake);
5636
+ });
5637
+ const pending = { actionId, settled: false, result: Promise.resolve({}) };
5638
+ const work = Promise.resolve().then(dispatch);
5639
+ pending.result = work.then((result) => {
5640
+ if (interruptedByDialog)
5641
+ this.record("action", { actionId, status: "completed", outcomeVerified: false });
5642
+ return { actionId, status: "completed", result };
5643
+ }, () => {
5644
+ const code2 = pending.unanswered ? "dialog_unanswered" : "executor_uncertain";
5645
+ if (interruptedByDialog)
5646
+ this.record("action", { actionId, status: "unknown", code: code2, retrySafe: false });
5647
+ return { actionId, status: "unknown", code: code2, retrySafe: false };
5648
+ }).finally(() => {
5649
+ pending.settled = true;
5650
+ if (this.pending === pending)
5651
+ this.pending = undefined;
5652
+ this.recentAction = { id: actionId, at: Date.now() };
5653
+ this.currentAction = undefined;
5654
+ this.listeners.delete(wake);
5655
+ });
5656
+ this.pending = pending;
5657
+ return await Promise.race([work, interrupted]);
5658
+ }
5659
+ startDownload(download, downloadId) {
5660
+ const event = this.record("download", {
5661
+ state: "started",
5662
+ downloadId,
5663
+ resourceId: downloadId,
5664
+ readiness: "pending",
5665
+ filename: download.suggestedFilename().slice(0, 255),
5666
+ url: diagnosticUrl(download.url())
5667
+ });
5668
+ this.downloads.set(event.eventId, download);
5669
+ return (data) => {
5670
+ this.record("download", { ...data, downloadId, resourceId: downloadId, transferId: event.eventId, actionId: event.actionId, filename: event.filename });
5671
+ this.downloads.delete(event.eventId);
5672
+ };
5673
+ }
5674
+ chooser(id) {
5675
+ const value = this.choosers.get(id);
5676
+ if (!value || value.document !== this.document || value.event.state !== "open")
5677
+ throw uploadRefusal.chooserExpired();
5678
+ value.event.state = "claimed";
5679
+ this.choosers.delete(id);
5680
+ return value.element;
5681
+ }
5682
+ clearChoosers() {
5683
+ for (const c of this.choosers.values()) {
5684
+ c.event.state = "expired";
5685
+ c.element.dispose().catch(() => {
5686
+ return;
5687
+ });
5688
+ }
5689
+ this.choosers.clear();
5690
+ }
5691
+ async cancelTransfer(id) {
5692
+ const download = this.downloads.get(id), chooser = this.choosers.get(id);
5693
+ if (download) {
5694
+ await download.cancel();
5695
+ return { cancelled: true, eventId: id };
5696
+ }
5697
+ if (chooser) {
5698
+ chooser.event.state = "cancelled";
5699
+ this.choosers.delete(id);
5700
+ await chooser.element.dispose();
5701
+ return { cancelled: true, eventId: id };
5702
+ }
5703
+ return { cancelled: false, code: "transfer_not_active" };
5704
+ }
5705
+ listAssets() {
5706
+ return [...this.assets].map(([assetId, a]) => ({ assetId, url: a.url, size: a.size, mimeType: a.mimeType }));
5707
+ }
5708
+ async assetBytes(id) {
5709
+ const asset = this.assets.get(id);
5710
+ if (!asset || asset.document !== this.document)
5711
+ throw new Error("Asset is no longer in the current document's observed responses.");
5712
+ const body = await asset.response.body();
5713
+ if (body.length > 8 * 1024 * 1024 || body.length > asset.size)
5714
+ throw new Error("Asset exceeds declared size or 8 MiB.");
5715
+ return { bytes: body, mimeType: asset.mimeType };
5716
+ }
5717
+ }
5718
+
5719
+ // cli/src/browser/navigation-observer.ts
5720
+ function navigationUrlMatches(pattern, url) {
5721
+ if (!pattern)
5722
+ return true;
5723
+ const source = pattern.split(/(\*\*|\*)/).map((part) => part === "**" ? ".*" : part === "*" ? "[^/]*" : part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("");
5724
+ return new RegExp(`^${source}$`).test(url);
5725
+ }
5726
+ function observeNavigation(page, input, events) {
5727
+ const started = Date.now();
5728
+ const deadline = events?.navigationDeadline(input.timeoutMs);
5729
+ const bound = started + input.timeoutMs + (deadline ? DIALOG_WAIT_MS : 0);
5730
+ const since = commitsHeard(page);
5731
+ let settled = false;
5732
+ let resolve2;
5733
+ const result = new Promise((done) => {
5734
+ resolve2 = done;
5735
+ });
5736
+ const finish = (matched, code2, error) => {
5737
+ if (settled)
5738
+ return;
5739
+ settled = true;
5740
+ clearTimeout(timer2);
5741
+ deadline?.stop();
5742
+ page.off("framenavigated", onNavigation);
5743
+ page.off("close", onClose);
5744
+ page.off("crash", onClose);
5745
+ resolve2({ matched, url: page.url(), elapsedMs: Date.now() - started, waitUntil: input.waitUntil, ...code2 ? { code: code2, error } : {} });
5746
+ };
5747
+ const onClose = () => finish(false, "navigation_tab_closed", "The tab closed before navigation was observed. Inspect tabs before another action.");
5748
+ const onNavigation = (frame) => {
5749
+ if (frame !== page.mainFrame() || !navigationUrlMatches(input.url, frame.url()))
5750
+ return;
5751
+ if (input.waitUntil === "commit") {
5752
+ finish(true);
5753
+ return;
5754
+ }
5755
+ waitForLoadState(page, input.waitUntil, Math.max(1, bound - Date.now()), since).then(() => {
5756
+ if (navigationUrlMatches(input.url, page.url()))
5757
+ finish(true);
5758
+ }, () => {
5759
+ return;
5760
+ });
5761
+ };
5762
+ const timedOut = () => finish(false, "navigation_timeout", "Input was dispatched, but the expected navigation was not observed before the deadline. Inspect the page; do not repeat the action solely because this wait timed out.");
5763
+ deadline?.expired.catch(timedOut);
5764
+ const timer2 = setTimeout(() => deadline?.held() ? finish(false, "dialog_unanswered", "Input was dispatched, but a dialog that nobody answered still holds the expected navigation. Read browser_events for the dialog and answer or dismiss it; do not repeat the action.") : timedOut(), bound - started);
5765
+ page.on("framenavigated", onNavigation);
5766
+ page.on("close", onClose);
5767
+ page.on("crash", onClose);
5768
+ return { result, dispose: () => finish(false, "navigation_observation_cancelled", "Navigation observation ended.") };
5769
+ }
5770
+
5771
+ // cli/src/browser/frame-history.ts
5772
+ var POLL_MS = 50;
5773
+ var UNSEEN_COMMIT_MS = 300;
5774
+ var FRAME_LOADED_MS = 5000;
5775
+ async function traverseToEntry(page, cdp, entryId, timeoutMs, expired) {
5776
+ const deadline = Date.now() + timeoutMs;
5777
+ const mainId = await cdp.send("Page.getFrameTree").then(({ frameTree }) => frameTree.frame.id, () => {
5778
+ return;
5779
+ });
5780
+ let mainSeen = false;
5781
+ let childSeen = false;
5782
+ let sameDocument = false;
5783
+ let childFrame;
5784
+ let response = null;
5785
+ let reachedAt;
5786
+ let settle;
5787
+ const committed = new Promise((resolve2, reject) => {
5788
+ let settled = false;
5789
+ settle = (value) => {
5790
+ if (settled)
5791
+ return;
5792
+ settled = true;
5793
+ stop();
5794
+ if (value instanceof Error)
5795
+ reject(value);
5796
+ else
5797
+ resolve2(value);
5798
+ };
5799
+ });
5800
+ const decide = () => {
5801
+ if (mainSeen)
5802
+ settle("main");
5803
+ else if (reachedAt !== undefined && (childSeen || Date.now() - reachedAt >= UNSEEN_COMMIT_MS))
5804
+ settle("child");
5805
+ };
5806
+ const readEntry = () => void cdp.send("Page.getNavigationHistory").then(({ currentIndex, entries }) => {
5807
+ if (entries[currentIndex]?.id === entryId)
5808
+ reachedAt ??= Date.now();
5809
+ decide();
5810
+ }, () => {
5811
+ return;
5812
+ });
5813
+ const seen = (main) => {
5814
+ if (main)
5815
+ mainSeen = true;
5816
+ else
5817
+ childSeen = true;
5818
+ if (mainSeen)
5819
+ decide();
5820
+ else
5821
+ readEntry();
5822
+ };
5823
+ const onFrameNavigated = (frame) => {
5824
+ if (frame !== page.mainFrame())
5825
+ childFrame = frame;
5826
+ seen(frame === page.mainFrame());
5827
+ };
5828
+ const onResponse = (candidate) => {
5829
+ if (candidate.frame() === page.mainFrame() && candidate.request().isNavigationRequest())
5830
+ response = candidate;
5831
+ };
5832
+ const onClose = () => settle(new Error("Target page, context or browser has been closed"));
5833
+ const onCrash = () => settle(new Error("Target crashed"));
5834
+ const onCommit = ({ frame }) => seen(!frame.parentId);
5835
+ const onWithinDocument = ({ frameId }) => {
5836
+ if (mainId === undefined)
5837
+ return;
5838
+ if (frameId !== mainId)
5839
+ sameDocument = true;
5840
+ seen(frameId === mainId);
5841
+ };
5842
+ page.on("framenavigated", onFrameNavigated);
5843
+ page.on("response", onResponse);
5844
+ page.on("close", onClose);
5845
+ page.on("crash", onCrash);
5846
+ cdp.on("Page.frameNavigated", onCommit);
5847
+ cdp.on("Page.navigatedWithinDocument", onWithinDocument);
5848
+ const poll = setInterval(readEntry, POLL_MS);
5849
+ const timer2 = setTimeout(() => settle(new Error(`Timeout ${timeoutMs}ms exceeded waiting for the history entry to commit.`)), Math.max(1, deadline - Date.now()));
5850
+ expired?.catch((error) => settle(error instanceof Error ? error : new Error(String(error))));
5851
+ function stop() {
5852
+ clearInterval(poll);
5853
+ clearTimeout(timer2);
5854
+ page.off("framenavigated", onFrameNavigated);
5855
+ page.off("response", onResponse);
5856
+ page.off("close", onClose);
5857
+ page.off("crash", onCrash);
5858
+ cdp.off("Page.frameNavigated", onCommit);
5859
+ cdp.off("Page.navigatedWithinDocument", onWithinDocument);
5860
+ }
5861
+ await cdp.send("Page.navigateToHistoryEntry", { entryId }).catch((error) => settle(error instanceof Error ? error : new Error(String(error))));
5862
+ if (await committed === "main")
5863
+ return { frame: "main", response };
5864
+ if (childFrame && !sameDocument && !childFrame.isDetached())
5865
+ await childFrame.waitForLoadState("domcontentloaded", { timeout: Math.max(1, Math.min(FRAME_LOADED_MS, deadline - Date.now())) }).catch(() => {
5866
+ return;
5867
+ });
5868
+ return { frame: "child" };
5869
+ }
5870
+
5871
+ // cli/src/browser/frame-position.ts
5872
+ import { createRequire as createRequire3 } from "node:module";
5873
+ var requirePlaywright3 = createRequire3(import.meta.url);
5874
+ var SUPPORTED_PLAYWRIGHT_VERSION3 = "1.63.0";
5875
+ var WRAPPED = Symbol.for("browser-mcp.cross-site-frame-position");
5876
+ function contentOffset(model) {
5877
+ const border = model?.border, content = model?.content;
5878
+ const quad = (value) => Array.isArray(value) && value.length === 8 && value.every((n) => typeof n === "number" && Number.isFinite(n));
5879
+ if (!quad(border) || !quad(content))
5880
+ return;
5881
+ const upright = (q) => q[0] === q[6] && q[2] === q[4] && q[1] === q[3] && q[5] === q[7];
5882
+ if (!upright(border) || !upright(content))
5883
+ return;
5884
+ const x = content[0] - border[0], y = content[1] - border[1];
5885
+ return x >= 0 && y >= 0 ? { x, y } : undefined;
5886
+ }
5887
+ async function contentBoxPosition(session, position) {
5888
+ if (!position)
5889
+ return position;
5890
+ try {
5891
+ const frame = session._page.frameManager.frame(session._targetId);
5892
+ const parent = frame?.parentFrame();
5893
+ if (!frame || !parent)
5894
+ return position;
5895
+ const { _client: client } = session._crPage._sessionForFrame(parent);
5896
+ const { backendNodeId } = await client.send("DOM.getFrameOwner", { frameId: frame._id });
5897
+ const { model } = await client.send("DOM.getBoxModel", { backendNodeId });
5898
+ const offset = contentOffset(model);
5899
+ return offset ? { ...position, x: position.x + offset.x, y: position.y + offset.y } : position;
5900
+ } catch {
5901
+ return position;
5902
+ }
5903
+ }
5904
+ function correctCrossSiteFramePositions(page) {
5905
+ try {
5906
+ if (requirePlaywright3("playwright-core/package.json").version !== SUPPORTED_PLAYWRIGHT_VERSION3)
5907
+ return;
5908
+ const connection = page._connection;
5909
+ const server = typeof connection?.toImpl === "function" ? connection.toImpl(page) : undefined;
5910
+ const session = server?.delegate?._mainFrameSession;
5911
+ if (!session || typeof session._targetId !== "string" || typeof session._crPage?._sessionForFrame !== "function" || typeof session._page?.frameManager?.frame !== "function")
5912
+ return;
5913
+ const prototype = Object.getPrototypeOf(session);
5914
+ const original = prototype._framePosition;
5915
+ if (prototype[WRAPPED] || typeof original !== "function" || original.length !== 0)
5916
+ return;
5917
+ prototype._framePosition = async function() {
5918
+ return await contentBoxPosition(this, await original.call(this));
5919
+ };
5920
+ prototype[WRAPPED] = true;
5921
+ } catch {}
5922
+ }
5923
+
5924
+ // cli/src/browser/frame-input.ts
5925
+ var MODIFIER_BITS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
5926
+ var BUTTON_BITS = { left: 1, right: 2, middle: 4 };
5927
+ var DRAG_HANDOVER_MS = 150;
5928
+ function modifierBits(modifiers) {
5929
+ let bits = 0;
5930
+ for (const modifier of modifiers)
5931
+ bits |= MODIFIER_BITS[modifier === "ControlOrMeta" ? process.platform === "darwin" ? "Meta" : "Control" : modifier];
5932
+ return bits;
5933
+ }
5934
+ function buttonBits(buttons) {
5935
+ let bits = 0;
5936
+ for (const button of buttons)
5937
+ bits |= BUTTON_BITS[button];
5938
+ return bits;
5939
+ }
5940
+ function frameOrigin(iframe) {
5941
+ const view = iframe.ownerDocument?.defaultView;
5942
+ if (!iframe.isConnected || !view)
5943
+ return "detached";
5944
+ const zoom = iframe.currentCSSZoom;
5945
+ if (zoom !== undefined && zoom !== 1)
5946
+ return "transformed";
5947
+ for (let node = iframe;node; node = node.parentElement ?? (node.getRootNode().host || null)) {
5948
+ const style2 = view.getComputedStyle(node);
5949
+ if (style2.transform !== "none" || style2.scale !== "none" || style2.rotate !== "none" || style2.translate !== "none")
5950
+ return "transformed";
5951
+ }
5952
+ const box = iframe.getBoundingClientRect();
5953
+ const style = view.getComputedStyle(iframe);
5954
+ return { x: box.left + iframe.clientLeft + Number.parseFloat(style.paddingLeft), y: box.top + iframe.clientTop + Number.parseFloat(style.paddingTop) };
5955
+ }
5956
+ function parentHit(iframe, options) {
5957
+ const root = iframe.getRootNode();
5958
+ const view = iframe.ownerDocument.defaultView;
5959
+ const { point } = options;
5960
+ if (point.x < 0 || point.y < 0 || point.x >= view.innerWidth || point.y >= view.innerHeight)
5961
+ return "outside";
5962
+ const hit = root.elementFromPoint(point.x, point.y);
5963
+ if (!hit)
5964
+ return "outside";
5965
+ if (hit === iframe)
5966
+ return null;
5967
+ const parentOf = (node) => node.parentElement ?? (node.getRootNode().host || null);
5968
+ const summarize = (node) => {
5969
+ const role = node.getAttribute("role") ?? undefined;
5970
+ const field = node.tagName === "INPUT" || node.tagName === "TEXTAREA" || node.tagName === "SELECT";
5971
+ const password = node.tagName === "INPUT" && node.type === "password";
5972
+ const raw = node.getAttribute("aria-label") ?? node.getAttribute("title") ?? (field ? [...node.labels ?? []][0]?.textContent || (password ? "" : node.getAttribute("placeholder") ?? "") : node.textContent ?? "");
5973
+ const name = raw.replace(/\s+/g, " ").trim().slice(0, options.nameChars);
5974
+ return { tag: node.tagName.toLowerCase(), ...role ? { role } : {}, ...name ? { name } : {} };
5975
+ };
5976
+ let layer;
5977
+ const doc = iframe.ownerDocument;
5978
+ for (let node = hit;node && node !== doc.body && node !== doc.documentElement; node = parentOf(node)) {
5979
+ const s = view.getComputedStyle(node);
5980
+ if (node.matches('dialog, [role="dialog"], [role="alertdialog"], [aria-modal="true"], [role="menu"], [role="listbox"], [role="tooltip"], [role="alert"], [role="banner"], [role="region"], header, nav, aside, footer') || s.position === "fixed" || s.position === "sticky") {
5981
+ layer = node;
5982
+ break;
5983
+ }
5984
+ }
5985
+ return {
5986
+ cover: summarize(hit),
5987
+ ...layer && layer !== hit ? { layer: summarize(layer) } : {},
5988
+ ...view.getComputedStyle(iframe).pointerEvents === "none" ? { passThrough: true } : {}
5989
+ };
5990
+ }
5991
+ function iframeAt(point) {
5992
+ let hit = document.elementFromPoint(point.x, point.y);
5993
+ while (hit?.shadowRoot) {
5994
+ const inner = hit.shadowRoot.elementFromPoint(point.x, point.y);
5995
+ if (!inner || inner === hit)
5996
+ break;
5997
+ hit = inner;
5998
+ }
5999
+ if (!hit || hit.tagName !== "IFRAME" && hit.tagName !== "FRAME")
6000
+ return null;
6001
+ const box = hit.getBoundingClientRect();
6002
+ const style = getComputedStyle(hit);
6003
+ const left = box.left + hit.clientLeft + Number.parseFloat(style.paddingLeft);
6004
+ const top = box.top + hit.clientTop + Number.parseFloat(style.paddingTop);
6005
+ const width = hit.clientWidth - Number.parseFloat(style.paddingLeft) - Number.parseFloat(style.paddingRight);
6006
+ const height = hit.clientHeight - Number.parseFloat(style.paddingTop) - Number.parseFloat(style.paddingBottom);
6007
+ return point.x >= left && point.y >= top && point.x < left + width && point.y < top + height ? hit : null;
6008
+ }
6009
+ async function frameChain(handle) {
6010
+ const chain = [];
6011
+ const frame = await handle.ownerFrame().catch(() => null);
6012
+ for (let node = frame;node?.parentFrame(); node = node.parentFrame())
6013
+ chain.push(node);
6014
+ return chain;
6015
+ }
6016
+ async function framePath(chain, point, nameChars, inRoot = 1) {
6017
+ let current = point;
6018
+ let root = point;
6019
+ for (let index = 0;index < chain.length; index++) {
6020
+ if (index === inRoot - 1)
6021
+ root = current;
6022
+ const iframe = await chain[index].frameElement().catch(() => {
6023
+ return;
6024
+ });
6025
+ if (!iframe)
6026
+ return;
6027
+ try {
6028
+ const origin = await iframe.evaluate(frameOrigin);
6029
+ if (origin === "transformed" || origin === "detached")
6030
+ return;
6031
+ current = { x: current.x + origin.x, y: current.y + origin.y };
6032
+ const hit = await iframe.evaluate(parentHit, { point: current, nameChars });
6033
+ if (hit === "outside")
6034
+ return { kind: "outside_viewport" };
6035
+ if (hit)
6036
+ return { kind: "covered", ...hit };
6037
+ } catch {
6038
+ return;
6039
+ } finally {
6040
+ iframe.dispose().catch(() => {
6041
+ return;
6042
+ });
6043
+ }
6044
+ }
6045
+ return { kind: "reached", root, page: current };
6046
+ }
6047
+ async function revealFrames(chain, timeout2) {
6048
+ for (const frame of chain.toReversed()) {
6049
+ const iframe = await frame.frameElement().catch(() => {
6050
+ return;
6051
+ });
6052
+ if (!iframe)
6053
+ return;
6054
+ try {
6055
+ await iframe.scrollIntoViewIfNeeded({ timeout: timeout2 });
6056
+ } catch {} finally {
6057
+ iframe.dispose().catch(() => {
6058
+ return;
6059
+ });
6060
+ }
6061
+ }
6062
+ }
6063
+
6064
+ class FrameTarget {
6065
+ page;
6066
+ frame;
6067
+ session;
6068
+ constructor(page, frame, session) {
6069
+ this.page = page;
6070
+ this.frame = frame;
6071
+ this.session = session;
6072
+ }
6073
+ static async open(page, frame) {
6074
+ const session = await page.context().newCDPSession(frame).catch(() => {
6075
+ return;
6076
+ });
6077
+ return session && new FrameTarget(page, frame, session);
6078
+ }
6079
+ static async forElement(page, chain) {
6080
+ if (!showsRestoredDocument(page) || !chain.length)
6081
+ return;
6082
+ for (let index = 0;index < chain.length; index++) {
6083
+ const target2 = await FrameTarget.open(page, chain[index]);
6084
+ if (target2)
6085
+ return { target: target2, inRoot: index + 1 };
6086
+ }
6087
+ return;
6088
+ }
6089
+ static async at(page, point, reuse) {
6090
+ if (!showsRestoredDocument(page))
6091
+ return;
6092
+ const path9 = [];
6093
+ let frame = page.mainFrame();
6094
+ let local = point;
6095
+ for (let depth = 0;depth < 8; depth++) {
6096
+ const found = await frame.evaluateHandle(iframeAt, local).catch(() => {
6097
+ return;
6098
+ });
6099
+ const iframe = found?.asElement();
6100
+ if (!iframe) {
6101
+ found?.dispose().catch(() => {
6102
+ return;
6103
+ });
6104
+ break;
6105
+ }
6106
+ try {
6107
+ const origin = await iframe.evaluate(frameOrigin).catch(() => "detached");
6108
+ if (origin === "transformed")
6109
+ return;
6110
+ const child = origin === "detached" ? null : await iframe.contentFrame().catch(() => null);
6111
+ if (!child || origin === "detached")
6112
+ break;
6113
+ local = { x: local.x - origin.x, y: local.y - origin.y };
6114
+ frame = child;
6115
+ path9.push({ frame, local });
6116
+ } finally {
6117
+ iframe.dispose().catch(() => {
6118
+ return;
6119
+ });
6120
+ }
6121
+ }
6122
+ for (const step of path9.toReversed()) {
6123
+ const offset = { x: point.x - step.local.x, y: point.y - step.local.y };
6124
+ if (reuse && reuse.frame === step.frame)
6125
+ return { target: reuse, local: step.local, offset };
6126
+ const target2 = await FrameTarget.open(page, step.frame);
6127
+ if (target2)
6128
+ return { target: target2, local: step.local, offset };
6129
+ }
6130
+ return;
6131
+ }
6132
+ mouse(type, point, extra) {
6133
+ return this.session.send("Input.dispatchMouseEvent", { type, x: point.x, y: point.y, ...extra });
6134
+ }
6135
+ move(point, buttons = 0, modifiers = 0) {
6136
+ const button = buttons & BUTTON_BITS.left ? "left" : buttons & BUTTON_BITS.right ? "right" : buttons & BUTTON_BITS.middle ? "middle" : "none";
6137
+ return this.mouse("mouseMoved", point, { button, buttons, modifiers });
6138
+ }
6139
+ press(point, button, clickCount, buttons, modifiers = 0) {
6140
+ return this.mouse("mousePressed", point, { button, buttons, clickCount, modifiers });
6141
+ }
6142
+ release(point, button, clickCount, buttons, modifiers = 0) {
6143
+ return this.mouse("mouseReleased", point, { button, buttons, clickCount, modifiers });
6144
+ }
6145
+ wheel(point, deltaX, deltaY, modifiers = 0) {
6146
+ return this.mouse("mouseWheel", point, { deltaX, deltaY, modifiers });
6147
+ }
6148
+ async click(point, button, clickCount) {
6149
+ await this.move(point);
6150
+ for (let count = 1;count <= clickCount; count++) {
6151
+ await this.press(point, button, count, BUTTON_BITS[button]);
6152
+ await this.release(point, button, count, 0);
6153
+ }
6154
+ }
6155
+ async hover(point, modifiers) {
6156
+ for (const modifier of modifiers)
6157
+ await this.page.keyboard.down(modifier);
5651
6158
  try {
5652
- return await Promise.race([
5653
- pending.result,
5654
- new Promise((resolve2) => {
5655
- timer2 = setTimeout(() => resolve2(undefined), ms);
5656
- })
5657
- ]);
6159
+ await this.move(point, 0, modifierBits(modifiers));
5658
6160
  } finally {
5659
- clearTimeout(timer2);
6161
+ for (const modifier of modifiers.toReversed())
6162
+ await this.page.keyboard.up(modifier);
5660
6163
  }
5661
6164
  }
5662
- async run(actionId, dispatch) {
5663
- const holding = !!this.dialog || this.httpAuth.isOpen();
5664
- if (holding || this.pending) {
5665
- const httpAuth = this.dialog ? null : this.httpAuth.prompt();
5666
- return {
5667
- dispatch: { status: "not_dispatched", code: holding ? "dialog_blocking" : "previous_action_pending" },
5668
- dialog: this.activeDialog(),
5669
- ...httpAuth ? { httpAuth, recovery: HTTP_AUTH_RECOVERY } : {},
5670
- pendingAction: this.pendingAction()
5671
- };
5672
- }
5673
- this.currentAction = actionId;
5674
- let interruptedByDialog = false;
5675
- let wake;
5676
- const interrupted = new Promise((resolve2) => {
5677
- wake = () => {
5678
- interruptedByDialog = true;
5679
- const auth = this.dialog ? undefined : this.httpAuth.requiredResult(actionId);
5680
- resolve2(auth ?? { dispatch: { status: "blocked", actionId, code: "dialog_open" }, dialog: this.activeDialog() });
5681
- };
5682
- this.listeners.add(wake);
5683
- });
5684
- const pending = { actionId, settled: false, result: Promise.resolve({}) };
5685
- const work = Promise.resolve().then(dispatch);
5686
- pending.result = work.then((result) => {
5687
- if (interruptedByDialog)
5688
- this.record("action", { actionId, status: "completed", outcomeVerified: false });
5689
- return { actionId, status: "completed", result };
5690
- }, () => {
5691
- if (interruptedByDialog)
5692
- this.record("action", { actionId, status: "unknown", code: "executor_uncertain", retrySafe: false });
5693
- return { actionId, status: "unknown", code: "executor_uncertain", retrySafe: false };
5694
- }).finally(() => {
5695
- pending.settled = true;
5696
- if (this.pending === pending)
5697
- this.pending = undefined;
5698
- this.recentAction = { id: actionId, at: Date.now() };
5699
- this.currentAction = undefined;
5700
- this.listeners.delete(wake);
5701
- });
5702
- this.pending = pending;
5703
- return await Promise.race([work, interrupted]);
6165
+ drag(type, point, data, modifiers = 0) {
6166
+ return this.session.send("Input.dispatchDragEvent", { type, x: point.x, y: point.y, data, modifiers });
5704
6167
  }
5705
- startDownload(download, downloadId) {
5706
- const event = this.record("download", {
5707
- state: "started",
5708
- downloadId,
5709
- resourceId: downloadId,
5710
- readiness: "pending",
5711
- filename: download.suggestedFilename().slice(0, 255),
5712
- url: diagnosticUrl(download.url())
6168
+ dispose() {
6169
+ this.session.detach().catch(() => {
6170
+ return;
5713
6171
  });
5714
- this.downloads.set(event.eventId, download);
5715
- return (data) => {
5716
- this.record("download", { ...data, downloadId, resourceId: downloadId, transferId: event.eventId, actionId: event.actionId, filename: event.filename });
5717
- this.downloads.delete(event.eventId);
5718
- };
5719
6172
  }
5720
- chooser(id) {
5721
- const value = this.choosers.get(id);
5722
- if (!value || value.document !== this.document || value.event.state !== "open")
5723
- throw uploadRefusal.chooserExpired();
5724
- value.event.state = "claimed";
5725
- this.choosers.delete(id);
5726
- return value.element;
6173
+ }
6174
+
6175
+ class DragInterception {
6176
+ session;
6177
+ caught;
6178
+ heard;
6179
+ constructor(session) {
6180
+ this.session = session;
5727
6181
  }
5728
- clearChoosers() {
5729
- for (const c of this.choosers.values()) {
5730
- c.event.state = "expired";
5731
- c.element.dispose().catch(() => {
6182
+ static async start(page) {
6183
+ const session = await page.context().newCDPSession(page).catch(() => {
6184
+ return;
6185
+ });
6186
+ if (!session)
6187
+ return;
6188
+ const interception = new DragInterception(session);
6189
+ session.on("Input.dragIntercepted", (event) => {
6190
+ interception.caught = event.data;
6191
+ interception.heard?.();
6192
+ });
6193
+ try {
6194
+ await session.send("Input.setInterceptDrags", { enabled: true });
6195
+ return interception;
6196
+ } catch {
6197
+ session.detach().catch(() => {
5732
6198
  return;
5733
6199
  });
6200
+ return;
5734
6201
  }
5735
- this.choosers.clear();
5736
6202
  }
5737
- async cancelTransfer(id) {
5738
- const download = this.downloads.get(id), chooser = this.choosers.get(id);
5739
- if (download) {
5740
- await download.cancel();
5741
- return { cancelled: true, eventId: id };
5742
- }
5743
- if (chooser) {
5744
- chooser.event.state = "cancelled";
5745
- this.choosers.delete(id);
5746
- await chooser.element.dispose();
5747
- return { cancelled: true, eventId: id };
5748
- }
5749
- return { cancelled: false, code: "transfer_not_active" };
6203
+ get data() {
6204
+ return this.caught;
5750
6205
  }
5751
- listAssets() {
5752
- return [...this.assets].map(([assetId, a]) => ({ assetId, url: a.url, size: a.size, mimeType: a.mimeType }));
6206
+ async wait(ms) {
6207
+ if (this.caught)
6208
+ return this.caught;
6209
+ let timer2;
6210
+ await new Promise((resolve2) => {
6211
+ this.heard = resolve2;
6212
+ timer2 = setTimeout(resolve2, ms);
6213
+ });
6214
+ clearTimeout(timer2);
6215
+ this.heard = undefined;
6216
+ return this.caught;
5753
6217
  }
5754
- async assetBytes(id) {
5755
- const asset = this.assets.get(id);
5756
- if (!asset || asset.document !== this.document)
5757
- throw new Error("Asset is no longer in the current document's observed responses.");
5758
- const body = await asset.response.body();
5759
- if (body.length > 8 * 1024 * 1024 || body.length > asset.size)
5760
- throw new Error("Asset exceeds declared size or 8 MiB.");
5761
- return { bytes: body, mimeType: asset.mimeType };
6218
+ async stop() {
6219
+ await this.session.send("Input.setInterceptDrags", { enabled: false }).catch(() => {
6220
+ return;
6221
+ });
6222
+ this.session.detach().catch(() => {
6223
+ return;
6224
+ });
6225
+ }
6226
+ }
6227
+ async function dragOnTarget(target2, from, to, steps, modifiers = 0) {
6228
+ const interception = await DragInterception.start(target2.page);
6229
+ let entered = false;
6230
+ try {
6231
+ await target2.move(from, 0, modifiers);
6232
+ await target2.press(from, "left", 1, BUTTON_BITS.left, modifiers);
6233
+ const count = Math.max(1, Math.round(steps));
6234
+ for (let step = 1;step <= count; step++) {
6235
+ const point = { x: from.x + (to.x - from.x) * step / count, y: from.y + (to.y - from.y) * step / count };
6236
+ const data2 = interception?.data;
6237
+ if (data2) {
6238
+ await target2.drag(entered ? "dragOver" : "dragEnter", point, data2, modifiers);
6239
+ entered = true;
6240
+ } else
6241
+ await target2.move(point, BUTTON_BITS.left, modifiers);
6242
+ }
6243
+ const data = await interception?.wait(DRAG_HANDOVER_MS);
6244
+ if (data) {
6245
+ if (!entered)
6246
+ await target2.drag("dragEnter", to, data, modifiers);
6247
+ await target2.drag("drop", to, data, modifiers);
6248
+ }
6249
+ } finally {
6250
+ await target2.release(to, "left", 1, 0, modifiers).catch(() => {
6251
+ return;
6252
+ });
6253
+ await interception?.stop();
5762
6254
  }
5763
6255
  }
5764
6256
 
@@ -6868,17 +7360,17 @@ var DOCUMENT_SIZE_EXPRESSION = `({
6868
7360
  docHeight: Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight,
6869
7361
  document.body ? document.body.scrollHeight : 0, document.body ? document.body.offsetHeight : 0, document.body ? document.body.clientHeight : 0),
6870
7362
  })`;
6871
- var finite = (value) => typeof value === "number" && Number.isFinite(value);
7363
+ var finite2 = (value) => typeof value === "number" && Number.isFinite(value);
6872
7364
  async function readViewportGeometry(cdp) {
6873
7365
  const v = await evaluateIsolated(cdp, VIEWPORT_EXPRESSION);
6874
- if (!v || typeof v.url !== "string" || ![v.scrollX, v.scrollY, v.width, v.height, v.dpr].every(finite) || !(v.width > 0 && v.height > 0 && v.dpr > 0))
7366
+ if (!v || typeof v.url !== "string" || ![v.scrollX, v.scrollY, v.width, v.height, v.dpr].every(finite2) || !(v.width > 0 && v.height > 0 && v.dpr > 0))
6875
7367
  throw new ObservationError("Viewport geometry is unavailable.");
6876
7368
  const state = { url: v.url, scrollX: v.scrollX, scrollY: v.scrollY, width: v.width, height: v.height, dpr: v.dpr };
6877
7369
  return { state, document: { readyState: v.readyState, visibilityState: v.visibilityState } };
6878
7370
  }
6879
7371
  async function readDocumentSize(cdp) {
6880
7372
  const v = await evaluateIsolated(cdp, DOCUMENT_SIZE_EXPRESSION);
6881
- if (!v || !finite(v.docWidth) || !finite(v.docHeight) || v.docWidth <= 0 || v.docHeight <= 0)
7373
+ if (!v || !finite2(v.docWidth) || !finite2(v.docHeight) || v.docWidth <= 0 || v.docHeight <= 0)
6882
7374
  throw new ObservationError("Document size is unavailable.");
6883
7375
  return { docWidth: v.docWidth, docHeight: v.docHeight };
6884
7376
  }
@@ -7009,6 +7501,10 @@ var MAX_RUN_JS_RESULT_BYTES = 1024 * 1024;
7009
7501
  var MAX_RUN_JS_ARTIFACT_BYTES = 20 * 1024 * 1024;
7010
7502
  var MAX_RUN_JS_ARTIFACT_COUNT = 32;
7011
7503
  var REF_ACTION_TIMEOUT_MS = 5000;
7504
+ var NAVIGATION_LOADING = {
7505
+ navigationLoading: true,
7506
+ note: "The click was made, and the page it opens was still loading when the click's five-second wait for it ended. Wait for that page with browser_wait_for, then read it with browser_read_page; do not repeat the click."
7507
+ };
7012
7508
  var TARGET_WAIT_MS = 5000;
7013
7509
  var MAX_TARGET_CANDIDATES = 10;
7014
7510
  var NAVIGATION_TIMEOUT_MS = 20000;
@@ -7083,6 +7579,49 @@ function refActionError(error, ref, verb) {
7083
7579
  Ref ${ref} comes from the most recent browser_read_page snapshot of this tab. ` + `The ${verb} outcome may be uncertain. ` + BROWSER_RECOVERY, { cause: error });
7084
7580
  }
7085
7581
  var playwrightTimeout = (error) => error instanceof Error && error.name === "TimeoutError";
7582
+ function clickProgress(error) {
7583
+ const lines = (error instanceof Error ? error.message : String(error)).replace(/\u001b\[[\d;]*m/g, "").split(`
7584
+ `).map((line) => line.trim().replace(/^-\s*/, "").replace(/^\d+\s*×\s*/, ""));
7585
+ const attempt = lines.slice(Math.max(lines.lastIndexOf("attempting click action"), lines.lastIndexOf("retrying click action")) + 1);
7586
+ if (attempt.includes("click action done"))
7587
+ return "done";
7588
+ const sent = attempt.lastIndexOf("performing click action");
7589
+ if (sent < 0 || attempt.slice(sent).some((line) => line.endsWith(" intercepts pointer events")))
7590
+ return;
7591
+ return "sent";
7592
+ }
7593
+ var PAGE_BUSY_RECOVERY = "The click may have taken effect. Wait for its result with browser_wait_for (for example the text you expect), then read the page with browser_read_page, before repeating the click.";
7594
+ var pageBusy = (ref) => new RuntimeFault("page_busy", PAGE_BUSY_RECOVERY, false, { ref });
7595
+ var NAVIGATION_LOADING_RECOVERY = "Wait for that page with browser_wait_for (its text, url or a loadState), then read it again. To go elsewhere instead, use browser_navigate, which replaces that navigation. Nothing was dispatched.";
7596
+ function readsDocument(action, input, pointerKnown) {
7597
+ switch (action) {
7598
+ case "read_page":
7599
+ case "inspect":
7600
+ case "screenshot":
7601
+ case "run_js":
7602
+ case "export_page":
7603
+ case "form_input":
7604
+ case "hover":
7605
+ case "select_text":
7606
+ case "edit_text":
7607
+ case "upload_attach":
7608
+ case "clipboard":
7609
+ case "capabilities":
7610
+ case "webmcp_list":
7611
+ case "webmcp_call":
7612
+ return true;
7613
+ case "scroll":
7614
+ if (input.ref === undefined && input.target === undefined && input.x === undefined && !pointerKnown)
7615
+ return true;
7616
+ case "mouse_click":
7617
+ return input.ref !== undefined || input.target !== undefined || input.screenshot !== undefined;
7618
+ case "drag":
7619
+ case "move_mouse":
7620
+ return input.sourceRef !== undefined || input.screenshot !== undefined;
7621
+ default:
7622
+ return false;
7623
+ }
7624
+ }
7086
7625
  function withTimeout(work, ms) {
7087
7626
  let timer2;
7088
7627
  return Promise.race([
@@ -7093,6 +7632,17 @@ function withTimeout(work, ms) {
7093
7632
  ]).finally(() => clearTimeout(timer2));
7094
7633
  }
7095
7634
  var refusal3 = (code2, recovery, details) => new RuntimeFault(code2, recovery, true, details, true);
7635
+ function coveredProbe(probe, path10) {
7636
+ return {
7637
+ kind: "covered",
7638
+ point: probe.point,
7639
+ box: probe.box,
7640
+ ...probe.standIn ? { standIn: probe.standIn } : {},
7641
+ cover: path10.cover,
7642
+ ...path10.layer ? { layer: path10.layer } : {},
7643
+ ...path10.passThrough ? { passThrough: true } : {}
7644
+ };
7645
+ }
7096
7646
  var staleRef = (ref) => refusal3("ref_stale", "Read the page again with browser_read_page and use a current ref. Nothing was dispatched.", { ref });
7097
7647
  var invalidInput = (problem) => refusal3("invalid_browser_input", "Correct the arguments as result.problem says, then send the request again. If the server accepted them, this browser runtime and the server are different versions: ask the user to update the CLI. Nothing was dispatched.", { problem: problem.slice(0, 300) });
7098
7648
  var problemOf = (error) => error instanceof Error ? error.message : "Invalid arguments.";
@@ -7271,6 +7821,7 @@ class BrowserRuntime {
7271
7821
  this.pages.set(id, page);
7272
7822
  this.events.set(page, new BrowserPageEvents(page, this.passkeyDetection, (acting) => this.answersHttpAuth(page, acting)));
7273
7823
  followRestoredFrames(page);
7824
+ correctCrossSiteFramePositions(page);
7274
7825
  page.on("framenavigated", () => {
7275
7826
  const tabId = this.ids.get(page);
7276
7827
  if (tabId)
@@ -7605,6 +8156,7 @@ class BrowserRuntime {
7605
8156
  const button = input.button === "middle" || input.button === "right" ? input.button : "left";
7606
8157
  const clickCount = input.clickCount === 2 ? 2 : 1;
7607
8158
  const modifiers = Array.isArray(input.modifiers) ? input.modifiers : [];
8159
+ const steady = (before, now) => (before?.kind === "element" || before?.kind === "stand_in") && before.kind === now.kind && Math.abs(before.point.x - now.point.x) < 1 && Math.abs(before.point.y - now.point.y) < 1;
7608
8160
  let handle;
7609
8161
  try {
7610
8162
  handle = await locator.elementHandle({ timeout: REF_ACTION_TIMEOUT_MS });
@@ -7615,7 +8167,8 @@ class BrowserRuntime {
7615
8167
  }
7616
8168
  let direct;
7617
8169
  try {
7618
- direct = await FrameInput.of(page, handle);
8170
+ const chain = await frameChain(handle);
8171
+ direct = await FrameTarget.forElement(page, chain);
7619
8172
  let scrolled = false;
7620
8173
  let revealed = false;
7621
8174
  let previous;
@@ -7627,7 +8180,7 @@ class BrowserRuntime {
7627
8180
  if (probe.kind === "outside_viewport" && !scrolled) {
7628
8181
  if (direct && !revealed) {
7629
8182
  revealed = true;
7630
- await direct.reveal(Math.min(remaining(), 2000));
8183
+ await revealFrames(chain, Math.min(remaining(), 2000));
7631
8184
  continue;
7632
8185
  }
7633
8186
  scrolled = true;
@@ -7636,33 +8189,34 @@ class BrowserRuntime {
7636
8189
  });
7637
8190
  continue;
7638
8191
  }
7639
- let blocked = probe;
7640
- if (direct && (probe.kind === "element" || probe.kind === "stand_in")) {
7641
- if (previous?.kind === probe.kind && Math.abs(previous.point.x - probe.point.x) < 1 && Math.abs(previous.point.y - probe.point.y) < 1) {
7642
- const path10 = await direct.path(probe.point, NAME_CHARS);
7643
- if (!path10) {
7644
- direct.dispose();
7645
- direct = undefined;
7646
- continue;
7647
- }
8192
+ const reachable = probe.kind === "element" || probe.kind === "stand_in" ? probe : undefined;
8193
+ const path10 = reachable && chain.length ? await framePath(chain, reachable.point, NAME_CHARS, direct?.inRoot) : undefined;
8194
+ let blocked = reachable && path10?.kind === "covered" ? coveredProbe(reachable, path10) : probe;
8195
+ if (path10?.kind === "covered") {} else if (direct && reachable) {
8196
+ if (!path10) {
8197
+ direct.target.dispose();
8198
+ direct = undefined;
8199
+ continue;
8200
+ }
8201
+ if (steady(previous, reachable)) {
7648
8202
  if (path10.kind === "reached") {
7649
8203
  this.cursor.delete(tabId);
7650
8204
  try {
7651
8205
  if (action === "click")
7652
- await direct.click(path10.root, button, clickCount);
8206
+ await direct.target.click(path10.root, button, clickCount);
7653
8207
  else
7654
- await direct.hover(path10.root, modifiers);
8208
+ await direct.target.hover(path10.root, modifiers);
7655
8209
  } catch (error) {
7656
8210
  throw refActionError(error, ref, action);
7657
8211
  }
7658
- if (probe.kind === "element")
8212
+ if (reachable.kind === "element")
7659
8213
  return { cursorKnown: false };
7660
- return await this.standInResult(page, handle, probe, action, undefined);
8214
+ return await this.standInResult(page, handle, reachable, action, undefined);
7661
8215
  }
7662
8216
  if (path10.kind === "outside_viewport" && (!revealed || !scrolled)) {
7663
8217
  if (!revealed) {
7664
8218
  revealed = true;
7665
- await direct.reveal(Math.min(remaining(), 2000));
8219
+ await revealFrames(chain, Math.min(remaining(), 2000));
7666
8220
  } else {
7667
8221
  scrolled = true;
7668
8222
  await handle.scrollIntoViewIfNeeded({ timeout: Math.min(remaining(), 2000) }).catch(() => {
@@ -7671,10 +8225,10 @@ class BrowserRuntime {
7671
8225
  }
7672
8226
  continue;
7673
8227
  }
7674
- blocked = path10.kind === "covered" ? { kind: "covered", point: probe.point, box: probe.box, cover: path10.cover } : { kind: "outside_viewport" };
8228
+ blocked = { kind: "outside_viewport" };
7675
8229
  }
7676
8230
  } else if (probe.kind === "stand_in") {
7677
- if (previous?.kind === "stand_in" && Math.abs(previous.point.x - probe.point.x) < 1 && Math.abs(previous.point.y - probe.point.y) < 1) {
8231
+ if (steady(previous, probe)) {
7678
8232
  const point = roundPoint(await this.pagePoint(handle, probe));
7679
8233
  this.cursor.delete(tabId);
7680
8234
  if (action === "click")
@@ -7694,13 +8248,21 @@ class BrowserRuntime {
7694
8248
  }
7695
8249
  } else if (!direct && (!standIn || probe.kind === "element")) {
7696
8250
  this.cursor.delete(tabId);
8251
+ const deadline2 = action === "click" ? this.events.get(page)?.navigationDeadline(remaining()) : undefined;
7697
8252
  try {
7698
8253
  if (action === "click")
7699
8254
  await locator.click({ button, clickCount, timeout: remaining() });
7700
8255
  else
7701
8256
  await locator.hover({ timeout: remaining(), modifiers });
7702
8257
  } catch (error) {
8258
+ const made = action === "click" ? await this.madeClick(page, error, deadline2) : undefined;
8259
+ if (made === "busy")
8260
+ throw pageBusy(ref);
8261
+ if (made)
8262
+ return { cursorKnown: false, ...made === "loading" ? NAVIGATION_LOADING : {} };
7703
8263
  throw await this.pointerFailure(error, handle, ref, action);
8264
+ } finally {
8265
+ deadline2?.stop();
7704
8266
  }
7705
8267
  return { cursorKnown: false };
7706
8268
  }
@@ -7709,13 +8271,13 @@ class BrowserRuntime {
7709
8271
  throw refusal3("target_not_actionable", `The ref was not ${action === "click" ? "clicked" : "hovered"}: ${standIn ? `${standInState(standIn)}, and ` : ""}${problem}. Nothing was dispatched. ${next}`, { ref, reason, ...blocked.kind === "covered" ? { cover: blocked.cover, ...blocked.layer ? { layer: blocked.layer } : {} } : {} });
7710
8272
  }
7711
8273
  previous = probe;
7712
- await new Promise((resolve2) => setTimeout(resolve2, probe.kind === "stand_in" || direct ? 50 : 150));
8274
+ await new Promise((resolve2) => setTimeout(resolve2, probe.kind === "stand_in" || direct || path10?.kind === "covered" ? 50 : 150));
7713
8275
  }
7714
8276
  } finally {
7715
8277
  handle.dispose().catch(() => {
7716
8278
  return;
7717
8279
  });
7718
- direct?.dispose();
8280
+ direct?.target.dispose();
7719
8281
  }
7720
8282
  }
7721
8283
  async standInResult(page, handle, probe, action, point) {
@@ -7749,26 +8311,138 @@ class BrowserRuntime {
7749
8311
  async pointerFailure(error, target2, ref, action) {
7750
8312
  if (!playwrightTimeout(error))
7751
8313
  return refActionError(error, ref, action);
7752
- const probe = await withTimeout(probePointer(target2, 2000), 2000).catch(() => ({ kind: "detached" }));
8314
+ let probe = await withTimeout(probePointer(target2, 2000), 2000).catch(() => ({ kind: "detached" }));
8315
+ if (probe.kind === "element" || probe.kind === "stand_in")
8316
+ probe = await withTimeout(this.ancestorCover(target2, probe), 2000).catch(() => {
8317
+ return;
8318
+ }) ?? probe;
7753
8319
  const { reason, problem, next } = pointerProblem(probe);
7754
8320
  return new RuntimeFault("target_not_actionable", `The ${action} on this ref waited ${REF_ACTION_TIMEOUT_MS / 1000} seconds: ${problem}. It probably did not happen, but check the page before repeating it. ${next}`, false, { ref, reason, ...probe.kind === "covered" ? { cover: probe.cover, ...probe.layer ? { layer: probe.layer } : {} } : {} });
7755
8321
  }
8322
+ async madeClick(page, error, deadline) {
8323
+ if (!playwrightTimeout(error))
8324
+ return;
8325
+ const progress = clickProgress(error);
8326
+ if (!progress)
8327
+ return;
8328
+ const loading = () => progress === "done" || !!this.events.get(page)?.navigationLoading();
8329
+ if (deadline?.wasHeld())
8330
+ return await this.heldClickNavigation(page, deadline) === "expired" && loading() ? "loading" : "done";
8331
+ return loading() ? "loading" : "busy";
8332
+ }
8333
+ async heldClickNavigation(page, deadline) {
8334
+ let committed;
8335
+ const commit = new Promise((resolve2) => committed = () => resolve2("commit"));
8336
+ const onCommit = (frame) => {
8337
+ if (frame === page.mainFrame())
8338
+ committed();
8339
+ };
8340
+ let timer2;
8341
+ page.on("framenavigated", onCommit);
8342
+ page.on("close", committed);
8343
+ try {
8344
+ const outcome = await Promise.race([
8345
+ commit,
8346
+ deadline.expired.then(() => "expired", () => "expired"),
8347
+ new Promise((resolve2) => timer2 = setTimeout(() => resolve2("bound"), DIALOG_WAIT_MS))
8348
+ ]);
8349
+ if (outcome === "bound" && deadline.held()) {
8350
+ this.events.get(page)?.markUnanswered();
8351
+ throw new Error(`Timeout ${DIALOG_WAIT_MS}ms exceeded while a dialog held the navigation the click started.`);
8352
+ }
8353
+ return outcome === "commit" ? "commit" : "expired";
8354
+ } finally {
8355
+ clearTimeout(timer2);
8356
+ page.off("framenavigated", onCommit);
8357
+ page.off("close", committed);
8358
+ }
8359
+ }
8360
+ async ancestorCover(target2, probe) {
8361
+ const handle = "count" in target2 ? await target2.elementHandle({ timeout: 1000 }).catch(() => {
8362
+ return;
8363
+ }) : target2;
8364
+ if (!handle)
8365
+ return;
8366
+ try {
8367
+ const chain = await frameChain(handle);
8368
+ const path10 = chain.length ? await framePath(chain, probe.point, NAME_CHARS) : undefined;
8369
+ return path10?.kind === "covered" ? coveredProbe(probe, path10) : undefined;
8370
+ } finally {
8371
+ if (handle !== target2)
8372
+ handle.dispose().catch(() => {
8373
+ return;
8374
+ });
8375
+ }
8376
+ }
7756
8377
  async coveredStandIn(target2) {
7757
8378
  const probe = await probePointer(target2, REF_ACTION_TIMEOUT_MS);
7758
8379
  return "standIn" in probe && !!probe.standIn && probe.kind !== "element";
7759
8380
  }
7760
- async takesDirectInput(page, target2) {
8381
+ async atPoint(page, point, onTarget, onPage) {
8382
+ const routed = await FrameTarget.at(page, point);
8383
+ if (!routed)
8384
+ return await onPage();
8385
+ try {
8386
+ return await onTarget(routed.target, routed.local);
8387
+ } finally {
8388
+ routed.target.dispose();
8389
+ }
8390
+ }
8391
+ async dragInFrame(page, input) {
7761
8392
  if (!showsRestoredDocument(page))
7762
- return false;
8393
+ return;
8394
+ const [from, to] = input.sourceRef ? await Promise.all([input.sourceRef, input.targetRef].map((ref) => this.refPagePoint(page, String(ref)))) : [input.from, input.to];
8395
+ if (!from || !to)
8396
+ return;
8397
+ const start = await FrameTarget.at(page, from);
8398
+ if (!start)
8399
+ return;
8400
+ const end = await FrameTarget.at(page, to, start.target);
8401
+ try {
8402
+ if (end?.target !== start.target)
8403
+ return;
8404
+ const modifiers = input.modifiers ?? [];
8405
+ for (const modifier of modifiers)
8406
+ await page.keyboard.down(modifier);
8407
+ try {
8408
+ await dragOnTarget(start.target, start.local, end.local, Number(input.steps ?? 10), modifierBits(modifiers));
8409
+ } finally {
8410
+ for (const modifier of modifiers.toReversed())
8411
+ await page.keyboard.up(modifier);
8412
+ }
8413
+ return { dispatched: true, outcomeVerified: false };
8414
+ } finally {
8415
+ start.target.dispose();
8416
+ if (end && end.target !== start.target)
8417
+ end.target.dispose();
8418
+ }
8419
+ }
8420
+ async refPagePoint(page, ref) {
8421
+ const handle = await this.refLocator(page, ref).elementHandle({ timeout: REF_ACTION_TIMEOUT_MS }).catch(() => {
8422
+ return;
8423
+ });
8424
+ if (!handle)
8425
+ return;
8426
+ try {
8427
+ const probe = await probePointer(handle);
8428
+ if (probe.kind !== "element" && probe.kind !== "stand_in")
8429
+ return;
8430
+ const path10 = await framePath(await frameChain(handle), probe.point, NAME_CHARS);
8431
+ return path10?.kind === "reached" ? path10.page : undefined;
8432
+ } finally {
8433
+ handle.dispose().catch(() => {
8434
+ return;
8435
+ });
8436
+ }
8437
+ }
8438
+ async inChildFrame(target2) {
7763
8439
  const handle = await target2.elementHandle({ timeout: REF_ACTION_TIMEOUT_MS }).catch(() => {
7764
8440
  return;
7765
8441
  });
7766
8442
  if (!handle)
7767
8443
  return false;
7768
8444
  try {
7769
- const input = await FrameInput.of(page, handle);
7770
- input?.dispose();
7771
- return !!input;
8445
+ return (await frameChain(handle)).length > 0;
7772
8446
  } finally {
7773
8447
  handle.dispose().catch(() => {
7774
8448
  return;
@@ -7781,26 +8455,34 @@ class BrowserRuntime {
7781
8455
  });
7782
8456
  const before = await state();
7783
8457
  if (before.checked === checked)
7784
- return;
8458
+ return {};
7785
8459
  if (before.radio && !checked)
7786
8460
  throw refusal3("invalid_browser_input", "A radio button is unchecked by checking another radio button of its group. Nothing was changed.", { ref });
7787
- if (await this.takesDirectInput(page, locator) || await this.coveredStandIn(locator)) {
7788
- await this.pointAtRef(page, tabId, ref, "click", {});
8461
+ if (await this.inChildFrame(locator) || await this.coveredStandIn(locator)) {
8462
+ const clicked = await this.pointAtRef(page, tabId, ref, "click", {});
8463
+ if (clicked.navigationLoading)
8464
+ return NAVIGATION_LOADING;
7789
8465
  if ((await state()).checked !== checked)
7790
8466
  throw new RuntimeFault("check_state_unchanged", `Take a screenshot to see the state of its widget before trying again; the click may have had another effect.`, false, { ref });
7791
- return;
8467
+ return {};
7792
8468
  }
7793
8469
  this.cursor.delete(tabId);
7794
8470
  try {
7795
8471
  await locator.setChecked(checked, { timeout: REF_ACTION_TIMEOUT_MS });
7796
8472
  } catch (error) {
8473
+ const progress = playwrightTimeout(error) ? clickProgress(error) : undefined;
8474
+ if (progress && this.events.get(page)?.navigationLoading())
8475
+ return NAVIGATION_LOADING;
8476
+ if (progress)
8477
+ throw pageBusy(ref);
7797
8478
  throw await this.pointerFailure(error, locator, ref, "form_input");
7798
8479
  }
8480
+ return {};
7799
8481
  }
7800
8482
  async gotoSettled(page, url) {
7801
8483
  const mark = this.events.get(page)?.frameDocumentMark();
7802
8484
  try {
7803
- await page.goto(url, { waitUntil: "domcontentloaded", timeout: NAVIGATION_TIMEOUT_MS });
8485
+ await this.navigating(page, (timeout2) => page.goto(url, { waitUntil: "domcontentloaded", timeout: timeout2 }));
7804
8486
  } catch (error) {
7805
8487
  const message = error instanceof Error ? error.message : String(error);
7806
8488
  if (/Download is starting/i.test(message))
@@ -7814,6 +8496,25 @@ class BrowserRuntime {
7814
8496
  await this.framesSettled(page, mark);
7815
8497
  return {};
7816
8498
  }
8499
+ async navigating(page, navigate) {
8500
+ const events = this.events.get(page);
8501
+ const deadline = events?.navigationDeadline(NAVIGATION_TIMEOUT_MS);
8502
+ if (!events || !deadline)
8503
+ return await navigate(NAVIGATION_TIMEOUT_MS);
8504
+ const work = navigate(NAVIGATION_TIMEOUT_MS + DIALOG_WAIT_MS, deadline.expired);
8505
+ try {
8506
+ return await Promise.race([work, deadline.expired]);
8507
+ } catch (error) {
8508
+ if (deadline.held() && /Timeout \d+ms exceeded/i.test(error instanceof Error ? error.message : String(error)))
8509
+ events.markUnanswered();
8510
+ throw error;
8511
+ } finally {
8512
+ deadline.stop();
8513
+ work.catch(() => {
8514
+ return;
8515
+ });
8516
+ }
8517
+ }
7817
8518
  async framesSettled(page, mark) {
7818
8519
  if (mark !== undefined)
7819
8520
  await this.events.get(page)?.framesSettled(mark, page.url(), FRAME_DOCUMENT_SETTLE_MS);
@@ -8053,8 +8754,8 @@ class BrowserRuntime {
8053
8754
  outcomeVerified: false
8054
8755
  };
8055
8756
  }
8056
- async traverseHistory(page, delta) {
8057
- const deadline = Date.now() + NAVIGATION_TIMEOUT_MS;
8757
+ async traverseHistory(page, delta, timeout2 = NAVIGATION_TIMEOUT_MS, expired) {
8758
+ const deadline = Date.now() + timeout2;
8058
8759
  const session = this.events.get(page).session();
8059
8760
  const history = await session?.send("Page.getNavigationHistory").catch(() => {
8060
8761
  return;
@@ -8064,13 +8765,13 @@ class BrowserRuntime {
8064
8765
  return;
8065
8766
  const since = commitsHeard(page);
8066
8767
  if (session && history && entry && entry.url === history.entries[history.currentIndex]?.url) {
8067
- const traversed = await traverseToEntry(page, session, entry.id, NAVIGATION_TIMEOUT_MS);
8768
+ const traversed = await traverseToEntry(page, session, entry.id, timeout2, expired);
8068
8769
  if (traversed.frame === "child")
8069
8770
  return { response: null, restoredFromCache: false, frame: traversed.frame };
8070
8771
  await waitForLoadState(page, "domcontentloaded", Math.max(1, deadline - Date.now()), since);
8071
8772
  return { response: traversed.response, restoredFromCache: restoredFromCache(page, since), frame: traversed.frame };
8072
8773
  }
8073
- const options = { timeout: NAVIGATION_TIMEOUT_MS, waitUntil: "commit" };
8774
+ const options = { timeout: timeout2, waitUntil: "commit" };
8074
8775
  const response = await (delta < 0 ? page.goBack(options) : page.goForward(options));
8075
8776
  await waitForLoadState(page, "domcontentloaded", Math.max(1, deadline - Date.now()), since);
8076
8777
  return { response, restoredFromCache: restoredFromCache(page, since), frame: "main" };
@@ -8156,6 +8857,11 @@ class BrowserRuntime {
8156
8857
  passkeyPrompt,
8157
8858
  recovery: PASSKEY_PROMPT_RECOVERY
8158
8859
  };
8860
+ if (page && events && readsDocument(action, input, this.cursor.has(String(input.tabId)))) {
8861
+ const loading = await events.loadingPage();
8862
+ if (loading)
8863
+ throw refusal3("navigation_loading", NAVIGATION_LOADING_RECOVERY, { pendingNavigation: loading });
8864
+ }
8159
8865
  const crash = events?.crash();
8160
8866
  if (page && action !== "close_tab" && !events?.activeDialog() && (!crash || crash === "frame"))
8161
8867
  await this.webmcp.get(page)?.watch(WEBMCP_WATCH_WAIT_MS);
@@ -8221,6 +8927,14 @@ class BrowserRuntime {
8221
8927
  expected = { matched: false, code: "observation_unavailable" };
8222
8928
  }
8223
8929
  }
8930
+ if (await events?.loadingPage())
8931
+ return {
8932
+ ...result,
8933
+ dispatch,
8934
+ expected,
8935
+ outcomeVerified: succeeded && expected?.matched === true,
8936
+ observation: { available: false, navigationLoading: true }
8937
+ };
8224
8938
  try {
8225
8939
  const snapshot = await this.dispatch("read_page", { tabId: input.tabId, maxChars: observation.maxChars }, execution);
8226
8940
  await Promise.all(this.initialization.values());
@@ -8417,10 +9131,19 @@ class BrowserRuntime {
8417
9131
  const expectation = parseNavigationExpectation(input.expectNavigation);
8418
9132
  if (expectation) {
8419
9133
  const { expectNavigation: _expectation, ...dispatchInput } = input;
8420
- const observation = observeNavigation(page, expectation);
9134
+ const events = this.events.get(page);
9135
+ const observation = observeNavigation(page, expectation, events);
8421
9136
  try {
8422
9137
  const dispatched = await this.dispatch(action, dispatchInput, execution);
8423
- return { ...dispatched, navigation: await observation.result };
9138
+ const navigation = await observation.result;
9139
+ if (navigation.code === "dialog_unanswered") {
9140
+ events?.markUnanswered();
9141
+ throw new Error(`Timeout ${expectation.timeoutMs + DIALOG_WAIT_MS}ms exceeded while a dialog held the expected navigation.`);
9142
+ }
9143
+ const { navigationLoading, note: _note, ...made } = dispatched;
9144
+ if (navigationLoading !== true)
9145
+ return { ...dispatched, navigation };
9146
+ return { ...made, ...!navigation.matched && events?.navigationLoading() ? { navigationLoading } : {}, navigation };
8424
9147
  } finally {
8425
9148
  observation.dispose();
8426
9149
  }
@@ -8484,7 +9207,7 @@ class BrowserRuntime {
8484
9207
  for (const ref of [input.sourceRef, input.targetRef])
8485
9208
  await this.liveRef(page, requireRef(ref));
8486
9209
  this.cursor.delete(tabId);
8487
- return { tabId, ...await withFramesDrawn(page, () => drag(page, input)) };
9210
+ return { tabId, ...await withFramesDrawn(page, async () => await this.dragInFrame(page, input) ?? await drag(page, input)) };
8488
9211
  case "select_text": {
8489
9212
  const { ref, match } = await this.actionRef(page, input);
8490
9213
  return { tabId, ...input.target !== undefined ? { ref, ...match ? { match } : {} } : {}, ...await selectText(await this.liveRef(page, ref), input) };
@@ -8540,7 +9263,7 @@ class BrowserRuntime {
8540
9263
  }
8541
9264
  const before = page.url();
8542
9265
  const mark = this.events.get(page).frameDocumentMark();
8543
- const traversed = input.direction === "reload" ? { response: await page.reload({ timeout: NAVIGATION_TIMEOUT_MS, waitUntil: "domcontentloaded" }), restoredFromCache: undefined } : await this.traverseHistory(page, input.direction === "back" ? -1 : 1);
9266
+ const traversed = input.direction === "reload" ? { response: await this.navigating(page, (timeout2) => page.reload({ timeout: timeout2, waitUntil: "domcontentloaded" })), restoredFromCache: undefined } : await this.navigating(page, (timeout2, expired) => this.traverseHistory(page, input.direction === "back" ? -1 : 1, timeout2, expired));
8544
9267
  if (traversed && !traversed.restoredFromCache && !(("frame" in traversed) && traversed.frame === "child"))
8545
9268
  await this.framesSettled(page, mark);
8546
9269
  if (!traversed)
@@ -8837,7 +9560,9 @@ class BrowserRuntime {
8837
9560
  if (!Number.isFinite(x) || !Number.isFinite(y))
8838
9561
  throw invalidInput("move_mouse requires numeric x and y coordinates.");
8839
9562
  this.cursor.delete(tabId);
8840
- await withFramesDrawn(page, () => page.mouse.move(x, y));
9563
+ await withFramesDrawn(page, () => this.atPoint(page, { x, y }, async (target2, local) => {
9564
+ await target2.move(local);
9565
+ }, () => page.mouse.move(x, y)));
8841
9566
  this.cursor.set(tabId, { x, y });
8842
9567
  return { tabId, x, y };
8843
9568
  }
@@ -8860,17 +9585,20 @@ class BrowserRuntime {
8860
9585
  if (!Number.isFinite(x) || !Number.isFinite(y))
8861
9586
  throw new Error("mouse_click by coordinates requires numeric x and y.");
8862
9587
  this.cursor.delete(tabId);
8863
- await withFramesDrawn(page, async () => {
9588
+ await withFramesDrawn(page, () => this.atPoint(page, { x, y }, async (target2, local) => {
9589
+ await target2.click(local, button, clickCount);
9590
+ this.cursor.set(tabId, { x, y });
9591
+ }, async () => {
8864
9592
  await page.mouse.move(x, y);
8865
9593
  this.cursor.set(tabId, { x, y });
8866
9594
  await page.mouse.click(x, y, { button, clickCount });
8867
- });
9595
+ }));
8868
9596
  return { tabId, x, y, button, clickCount };
8869
9597
  }
8870
9598
  const cursor = this.cursor.get(tabId);
8871
9599
  if (!cursor)
8872
9600
  throw refusal3("pointer_unknown", "Pass a ref or a target, or x/y: the center of a box from browser_read_page with boxes: true, or a point in a screenshot with its screenshotId. Nothing was clicked.");
8873
- await withFramesDrawn(page, () => page.mouse.click(cursor.x, cursor.y, { button, clickCount }));
9601
+ await withFramesDrawn(page, () => this.atPoint(page, cursor, (target2, local) => target2.click(local, button, clickCount), () => page.mouse.click(cursor.x, cursor.y, { button, clickCount })));
8874
9602
  return { tabId, ...cursor, button };
8875
9603
  }
8876
9604
  case "scroll": {
@@ -8914,11 +9642,15 @@ class BrowserRuntime {
8914
9642
  this.cursor.delete(tabId);
8915
9643
  const deltaX = direction === "left" ? -amount : direction === "right" ? amount : 0;
8916
9644
  const deltaY = direction === "up" ? -amount : direction === "down" ? amount : 0;
8917
- await withFramesDrawn(page, async () => {
9645
+ await withFramesDrawn(page, () => this.atPoint(page, pointer, async (target2, local) => {
9646
+ await target2.move(local);
9647
+ this.cursor.set(tabId, pointer);
9648
+ await target2.wheel(local, deltaX, deltaY);
9649
+ }, async () => {
8918
9650
  await page.mouse.move(pointer.x, pointer.y);
8919
9651
  this.cursor.set(tabId, pointer);
8920
9652
  await page.mouse.wheel(deltaX, deltaY);
8921
- });
9653
+ }));
8922
9654
  return { tabId, direction, amount, ...pointer };
8923
9655
  }
8924
9656
  case "wait_for": {
@@ -8978,6 +9710,7 @@ class BrowserRuntime {
8978
9710
  throw await this.pointerFailure(error, locator, ref, "form_input");
8979
9711
  }
8980
9712
  const kind = info.kind === "select" && info.multiple ? "multiselect" : info.kind;
9713
+ let clicked = {};
8981
9714
  const expectField = (field) => {
8982
9715
  if (provided[0] !== field)
8983
9716
  throw refusal3("invalid_browser_input", `This element (kind ${kind}) takes ${field}, not ${provided[0]}: pass ${field} instead. Nothing was changed.`, { ref, kind, tag: info.tag });
@@ -9007,7 +9740,7 @@ class BrowserRuntime {
9007
9740
  }
9008
9741
  case "checkable":
9009
9742
  expectField("checked");
9010
- await withFramesDrawn(page, () => this.setCheckedAtRef(page, tabId, locator, ref, input.checked === true));
9743
+ clicked = await withFramesDrawn(page, () => this.setCheckedAtRef(page, tabId, locator, ref, input.checked === true));
9011
9744
  break;
9012
9745
  case "text":
9013
9746
  case "contenteditable":
@@ -9024,7 +9757,7 @@ class BrowserRuntime {
9024
9757
  throw error;
9025
9758
  throw await this.pointerFailure(error, locator, ref, "form_input");
9026
9759
  }
9027
- return { tabId, ref, ...match ? { match } : {}, kind };
9760
+ return { tabId, ref, ...match ? { match } : {}, kind, ...clicked };
9028
9761
  }
9029
9762
  case "keyboard": {
9030
9763
  const keys = Array.isArray(input.keys) ? input.keys : [];
@@ -9190,11 +9923,11 @@ ${code2}
9190
9923
 
9191
9924
  // cli/src/runtime/cancellation.ts
9192
9925
  import { AsyncLocalStorage } from "node:async_hooks";
9193
- import { createRequire as createRequire3 } from "node:module";
9926
+ import { createRequire as createRequire4 } from "node:module";
9194
9927
  var current = new AsyncLocalStorage;
9195
9928
  var installed = new WeakSet;
9196
9929
  function installCancellation(context) {
9197
- const require2 = createRequire3(import.meta.url);
9930
+ const require2 = createRequire4(import.meta.url);
9198
9931
  if (require2("playwright-core/package.json").version !== "1.63.0")
9199
9932
  throw new Error("Cancellation adapter unavailable");
9200
9933
  const connection = context._connection;
@@ -9220,14 +9953,14 @@ function outsideCancellation(work) {
9220
9953
  }
9221
9954
 
9222
9955
  // cli/src/runtime/frame-documents.ts
9223
- import { createRequire as createRequire4 } from "node:module";
9224
- var requirePlaywright3 = createRequire4(import.meta.url);
9225
- var SUPPORTED_PLAYWRIGHT_VERSION3 = "1.63.0";
9956
+ import { createRequire as createRequire5 } from "node:module";
9957
+ var requirePlaywright4 = createRequire5(import.meta.url);
9958
+ var SUPPORTED_PLAYWRIGHT_VERSION4 = "1.63.0";
9226
9959
  var supported;
9227
9960
  function playwrightSupported() {
9228
9961
  if (supported === undefined) {
9229
9962
  try {
9230
- supported = requirePlaywright3("playwright-core/package.json").version === SUPPORTED_PLAYWRIGHT_VERSION3;
9963
+ supported = requirePlaywright4("playwright-core/package.json").version === SUPPORTED_PLAYWRIGHT_VERSION4;
9231
9964
  } catch {
9232
9965
  supported = false;
9233
9966
  }
@@ -9472,6 +10205,9 @@ class NativeRuntime {
9472
10205
  const page = await this.claimPage(tabId, scope);
9473
10206
  await this.track(page);
9474
10207
  this.assertPageAvailable(page);
10208
+ const loading = await this.engine.pageEvents(page)?.loadingPage();
10209
+ if (loading)
10210
+ throw new RuntimeFault("navigation_loading", NAVIGATION_LOADING_RECOVERY, true, { pendingNavigation: loading }, true);
9475
10211
  let frame = page.mainFrame();
9476
10212
  for (const selector of frames) {
9477
10213
  const locator = frame.locator(selector);
@@ -10003,16 +10739,16 @@ var advertisedLocatorFields = Object.fromEntries([
10003
10739
  // backend/live-wire.ts
10004
10740
  var isRuntimeTabId = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
10005
10741
  var MAX_LIVE_FRAME_BYTES = 1500000;
10006
- var finite2 = (value, min, max) => Number.isFinite(value) && value >= min && value <= max;
10742
+ var finite3 = (value, min, max) => Number.isFinite(value) && value >= min && value <= max;
10007
10743
  var uint32 = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4294967295;
10008
- var coordinate = (value) => typeof value === "number" && finite2(value, -1e5, 1e5);
10009
- var delta = (value) => typeof value === "number" && finite2(value, -1e6, 1e6);
10744
+ var coordinate = (value) => typeof value === "number" && finite3(value, -1e5, 1e5);
10745
+ var delta = (value) => typeof value === "number" && finite3(value, -1e6, 1e6);
10010
10746
  var TOOL = /^[a-z][a-z0-9_]{0,63}$/;
10011
10747
  function sanitizeLiveEvent(value) {
10012
10748
  if (!value || typeof value !== "object" || Array.isArray(value))
10013
10749
  return null;
10014
10750
  const e = value;
10015
- if (!isRuntimeTabId(e.runtimeTabId) || !uint32(e.navSeq) || typeof e.at !== "number" || !finite2(e.at, 0, 100000000000000))
10751
+ if (!isRuntimeTabId(e.runtimeTabId) || !uint32(e.navSeq) || typeof e.at !== "number" || !finite3(e.at, 0, 100000000000000))
10016
10752
  return null;
10017
10753
  const base = { runtimeTabId: e.runtimeTabId, navSeq: e.navSeq, at: e.at };
10018
10754
  switch (e.type) {
@@ -10807,6 +11543,8 @@ class TakeoverInput {
10807
11543
  switch (event.kind) {
10808
11544
  case "mouse": {
10809
11545
  await this.syncModifiers(session, this.modifierMask(event.modifiers, event.mac));
11546
+ if (await this.routedMouse(session, event))
11547
+ return;
10810
11548
  if (event.type === "move" || session.pointer.x !== event.x || session.pointer.y !== event.y) {
10811
11549
  session.pointer = { x: event.x, y: event.y };
10812
11550
  await page.mouse.move(event.x, event.y);
@@ -10821,6 +11559,8 @@ class TakeoverInput {
10821
11559
  }
10822
11560
  case "wheel":
10823
11561
  await this.syncModifiers(session, this.modifierMask(event.modifiers, event.mac));
11562
+ if (await this.routedWheel(session, event))
11563
+ return;
10824
11564
  if (session.pointer.x !== event.x || session.pointer.y !== event.y) {
10825
11565
  session.pointer = { x: event.x, y: event.y };
10826
11566
  await page.mouse.move(event.x, event.y);
@@ -10853,6 +11593,88 @@ class TakeoverInput {
10853
11593
  return;
10854
11594
  }
10855
11595
  }
11596
+ async routeAt(session, x, y) {
11597
+ const route = session.route;
11598
+ if (route?.buttons.size)
11599
+ return route;
11600
+ if (session.buttons.size)
11601
+ return;
11602
+ const found = await FrameTarget.at(session.page, { x, y }, route?.target);
11603
+ if (found?.target === route?.target && route) {
11604
+ route.offset = found.offset;
11605
+ return route;
11606
+ }
11607
+ if (route)
11608
+ this.unroute(session);
11609
+ if (!found)
11610
+ return;
11611
+ session.route = { target: found.target, offset: found.offset, buttons: new Set };
11612
+ return session.route;
11613
+ }
11614
+ unroute(session) {
11615
+ const route = session.route;
11616
+ if (!route)
11617
+ return;
11618
+ session.route = undefined;
11619
+ route.target.dispose();
11620
+ route.drag?.stop();
11621
+ session.pointer = { x: Number.NaN, y: Number.NaN };
11622
+ }
11623
+ async routedMouse(session, event) {
11624
+ const route = await this.routeAt(session, event.x, event.y);
11625
+ if (!route)
11626
+ return false;
11627
+ const modifiers = this.modifierMask(event.modifiers, event.mac);
11628
+ const local = { x: event.x - route.offset.x, y: event.y - route.offset.y };
11629
+ const moved = event.type === "move" || session.pointer.x !== event.x || session.pointer.y !== event.y;
11630
+ session.pointer = { x: event.x, y: event.y };
11631
+ const data = route.buttons.size ? route.drag?.data : undefined;
11632
+ if (moved) {
11633
+ if (data) {
11634
+ await route.target.drag(route.entered ? "dragOver" : "dragEnter", local, data, modifiers);
11635
+ route.entered = true;
11636
+ } else
11637
+ await route.target.move(local, buttonBits(route.buttons), modifiers);
11638
+ if (route.buttons.size)
11639
+ route.moved = true;
11640
+ }
11641
+ if (event.type === "down") {
11642
+ if (!route.buttons.size) {
11643
+ route.drag = await DragInterception.start(session.page);
11644
+ route.moved = false;
11645
+ }
11646
+ route.buttons.add(event.button);
11647
+ await route.target.press(local, event.button, event.clickCount, buttonBits(route.buttons), modifiers);
11648
+ } else if (event.type === "up" && route.buttons.has(event.button)) {
11649
+ const dragged = route.buttons.size === 1 ? data ?? (route.moved ? await route.drag?.wait(DRAG_HANDOVER_MS) : undefined) : undefined;
11650
+ route.buttons.delete(event.button);
11651
+ if (dragged) {
11652
+ if (!route.entered)
11653
+ await route.target.drag("dragEnter", local, dragged, modifiers);
11654
+ await route.target.drag("drop", local, dragged, modifiers);
11655
+ }
11656
+ await route.target.release(local, event.button, event.clickCount, buttonBits(route.buttons), modifiers);
11657
+ if (!route.buttons.size) {
11658
+ await route.drag?.stop();
11659
+ route.drag = undefined;
11660
+ route.entered = false;
11661
+ }
11662
+ }
11663
+ return true;
11664
+ }
11665
+ async routedWheel(session, event) {
11666
+ const route = await this.routeAt(session, event.x, event.y);
11667
+ if (!route)
11668
+ return false;
11669
+ const modifiers = this.modifierMask(event.modifiers, event.mac);
11670
+ const local = { x: event.x - route.offset.x, y: event.y - route.offset.y };
11671
+ if (session.pointer.x !== event.x || session.pointer.y !== event.y) {
11672
+ session.pointer = { x: event.x, y: event.y };
11673
+ await route.target.move(local, buttonBits(route.buttons), modifiers);
11674
+ }
11675
+ await route.target.wheel(local, event.deltaX, event.deltaY, modifiers);
11676
+ return true;
11677
+ }
10856
11678
  async syncModifiers(session, mask) {
10857
11679
  for (const [name, bit] of MODIFIERS) {
10858
11680
  const held = [...session.keys].filter(([, key2]) => key2 === name);
@@ -10899,6 +11721,18 @@ class TakeoverInput {
10899
11721
  const buttons = [...session.buttons], keys = new Set(session.keys.values());
10900
11722
  session.buttons.clear();
10901
11723
  session.keys.clear();
11724
+ const route = session.route;
11725
+ if (route) {
11726
+ const local = { x: session.pointer.x - route.offset.x, y: session.pointer.y - route.offset.y };
11727
+ const at = Number.isFinite(local.x) && Number.isFinite(local.y) ? local : { x: 0, y: 0 };
11728
+ if (route.drag?.data && route.buttons.size)
11729
+ await route.target.drag("dragCancel", at, route.drag.data).catch(() => {});
11730
+ for (const button2 of [...route.buttons]) {
11731
+ route.buttons.delete(button2);
11732
+ await route.target.release(at, button2, 1, buttonBits(route.buttons)).catch(() => {});
11733
+ }
11734
+ this.unroute(session);
11735
+ }
10902
11736
  for (const button2 of buttons)
10903
11737
  await session.page.mouse.up({ button: button2 }).catch(() => {});
10904
11738
  for (const key2 of keys)
@@ -11595,7 +12429,7 @@ class SecretVault {
11595
12429
  this.entries.delete(id);
11596
12430
  }
11597
12431
  metadata(e) {
11598
- return { vaultId: e.id, names: Object.keys(e.values), count: Object.keys(e.values).length, expiresAt: e.expiresAt, tabId: e.tabId, generation: e.generation };
12432
+ return { vaultId: e.id, names: Object.keys(e.values), count: Object.keys(e.values).length, expiresAt: e.expiresAt, runtimeTabId: e.tabId, generation: e.generation };
11599
12433
  }
11600
12434
  async capture(scope, tabId, code2, frames) {
11601
12435
  if (code2.length > 65536)