browser-core.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. import type { ClipboardProvider } from './clipboard.js';
  2. import { classifyBrowserNavigationEvent } from './browser-action-helpers.js';
  3. import { BrowserExtendedActionSupport } from './browser-extended-actions.js';
  4. import { isHoverSemanticSnapshot, resolveBrowserHoverSemantic } from './browser-hover-semantic.js';
  5. import {
  6. asNumber,
  7. asString,
  8. delay,
  9. inputCoordinate,
  10. isRecord,
  11. invalidateBrowserFrame,
  12. resolveBrowserSnapshotElement,
  13. type ElementRecord,
  14. type BrowserScreenshotCapture,
  15. type BrowserSessionState,
  16. } from './browser-state.js';
  17. import type { BrowserTransport } from './browser-transport.js';
  18. import { CDPHelper } from './cdp-helper.js';
  19. import { ElementMapManager } from './element-map-manager.js';
  20. import { isBrowserOperationInterruption, withTimeout } from './operation-timeout.js';
  21. const DEFAULT_ACTION_TIMEOUT_MS = 30_000;
  22. const DEFAULT_COMMAND_TIMEOUT_MS = 15_000;
  23. const MAX_ACTION_TIMEOUT_MS = 120_000;
  24. const MAX_ACTION_WITH_COMPLETION_BUFFER_MS = 125_000;
  25. const NAVIGATION_ACTION_TIMEOUT_MS = 35_000;
  26. const TEXT_INPUT_COMPLETION_BUFFER_MS = 30_000;
  27. const TEXT_INPUT_CDP_EVENT_ESTIMATE_MS = 20;
  28. const ACTION_COMPLETION_BUFFER_MS = 1_000;
  29. const HOVER_SEMANTIC_SAMPLE_DELAY_MS = 160;
  30. const HOVER_SEMANTIC_SAMPLE_COUNT = 6;
  31. export interface BrowserCoreOptions<TAction extends string> {
  32. provider: string;
  33. version: number;
  34. actions: readonly TAction[];
  35. }
  36. export interface BrowserCoreContext {
  37. readonly sessionId: string;
  38. }
  39. export interface BrowserCoreSessionOptions {
  40. readonly clipboardProvider?: ClipboardProvider;
  41. /** Reuse a provider-neutral helper already owned by this exact page transport. */
  42. readonly cdpHelper?: CDPHelper;
  43. readonly actionTimeoutMs?: number;
  44. readonly commandTimeoutMs?: number;
  45. readonly inputCoordinateScaleProvider?: () => number;
  46. /** Optional provider presentation step; it must not perform the Browser action itself. */
  47. readonly beforePointerAction?: (
  48. event: { action: string; point: { x: number; y: number } },
  49. signal?: AbortSignal,
  50. ) => Promise<void> | void;
  51. readonly clickNavigationDetectionMs?: number;
  52. /** Optional provider capture seam for presentation-aware screenshots. */
  53. readonly captureScreenshot?: BrowserScreenshotCapture;
  54. }
  55. /** Snapshot-scoped identity returned to provider adapters for an opaque ref. */
  56. export interface BrowserCoreResolvedTarget {
  57. readonly element: ElementRecord;
  58. readonly snapshotId: string;
  59. readonly generation: number;
  60. readonly frameId: string;
  61. readonly frameRef: string | null;
  62. }
  63. /**
  64. * Shared top layer for Browser providers.
  65. *
  66. * It owns the provider contract and action gate. Provider implementations
  67. * only supply the action executor; semantic snapshots, refs, query and
  68. * effect-verification code are kept below this same contract rather than
  69. * introducing a second Electron/native provider API.
  70. */
  71. export class BrowserCore<TAction extends string = string> {
  72. private readonly actionSet: ReadonlySet<TAction>;
  73. constructor(private readonly options: BrowserCoreOptions<TAction>) {
  74. this.actionSet = new Set(options.actions);
  75. }
  76. getCapabilities() {
  77. return {
  78. provider: this.options.provider,
  79. version: this.options.version,
  80. actions: this.options.actions,
  81. } as const;
  82. }
  83. assertAction(action: string): asserts action is TAction {
  84. if (!this.actionSet.has(action as TAction)) {
  85. throw new Error(`Unsupported ${this.options.provider} Browser action: ${action}`);
  86. }
  87. }
  88. assertContext(ctx: BrowserCoreContext): string {
  89. const sessionId = ctx.sessionId.trim();
  90. if (!sessionId) throw new Error('Browser tool requires an active session');
  91. return sessionId;
  92. }
  93. assertNotAborted(signal?: AbortSignal): void {
  94. if (signal?.aborted) throw new Error('Operation aborted');
  95. }
  96. createSession(
  97. transport: BrowserTransport,
  98. options: BrowserCoreSessionOptions = {},
  99. ): BrowserCoreSession {
  100. return new BrowserCoreSession(transport, options);
  101. }
  102. }
  103. /**
  104. * The single provider-neutral Browser Core execution path.
  105. *
  106. * Providers create a transport and hand it to this class. Snapshot/ref state,
  107. * pagination, input dispatch, effect validation and action deadlines remain
  108. * here, so Electron and native Headless cannot silently grow separate action
  109. * implementations.
  110. */
  111. export class BrowserCoreSession extends BrowserExtendedActionSupport {
  112. private readonly state: BrowserSessionState;
  113. private readonly ownsCdpHelper: boolean;
  114. private readonly actionTimeoutMs: number;
  115. private readonly commandTimeoutMs: number;
  116. private active = false;
  117. private poisoned = false;
  118. private externalNavigationGeneration = 0;
  119. private readonly navigationEventDisposer: () => void;
  120. constructor(transport: BrowserTransport, options: BrowserCoreSessionOptions = {}) {
  121. super(options.clipboardProvider);
  122. if (options.cdpHelper && options.cdpHelper.getTransport() !== transport) {
  123. throw new Error('Browser Core CDP helper must own the supplied page transport');
  124. }
  125. const cdpHelper = options.cdpHelper ?? new CDPHelper(transport);
  126. this.ownsCdpHelper = options.cdpHelper === undefined;
  127. this.state = {
  128. transport,
  129. cdpHelper,
  130. elementMap: new ElementMapManager(),
  131. generation: 0,
  132. ...(options.inputCoordinateScaleProvider
  133. ? { inputCoordinateScaleProvider: options.inputCoordinateScaleProvider }
  134. : {}),
  135. ...(options.beforePointerAction ? { beforePointerAction: options.beforePointerAction } : {}),
  136. ...(options.captureScreenshot ? { captureScreenshot: options.captureScreenshot } : {}),
  137. ...(options.clickNavigationDetectionMs !== undefined
  138. ? {
  139. clickNavigationDetectionMs: Math.max(
  140. 1,
  141. Math.min(30_000, Math.floor(options.clickNavigationDetectionMs)),
  142. ),
  143. }
  144. : {}),
  145. };
  146. this.actionTimeoutMs = positiveDeadline(options.actionTimeoutMs, DEFAULT_ACTION_TIMEOUT_MS);
  147. this.commandTimeoutMs = positiveDeadline(options.commandTimeoutMs, DEFAULT_COMMAND_TIMEOUT_MS);
  148. this.navigationEventDisposer = transport.onEvent((event) => {
  149. const params = isRecord(event.params) ? event.params : {};
  150. const frame = isRecord(params.frame) ? params.frame : {};
  151. const frameId = asString(frame.id) || asString(params.frameId);
  152. const commandSessionId = event.sessionId || asString(params.sessionId);
  153. const mainFrameId = this.state.cdpHelper.getMainFrameId();
  154. const navigationScope = classifyBrowserNavigationEvent(event, transport, mainFrameId);
  155. if (event.method === 'Page.frameNavigated') {
  156. if (navigationScope === 'child') {
  157. invalidateBrowserFrame(this.state, {
  158. ...(frameId ? { frameId } : {}),
  159. ...(commandSessionId ? { commandSessionId } : {}),
  160. });
  161. } else if (navigationScope === 'main') {
  162. this.invalidate(this.state);
  163. }
  164. } else if (event.method === 'Page.navigatedWithinDocument') {
  165. if (navigationScope === 'child') {
  166. invalidateBrowserFrame(this.state, {
  167. ...(frameId ? { frameId } : {}),
  168. ...(commandSessionId ? { commandSessionId } : {}),
  169. });
  170. } else if (navigationScope === 'main') {
  171. this.invalidate(this.state);
  172. }
  173. } else if (event.method === 'Page.frameDetached' && frameId) {
  174. if (mainFrameId && frameId === mainFrameId) this.invalidate(this.state);
  175. else invalidateBrowserFrame(this.state, { frameId });
  176. } else if (event.method === 'Target.detachedFromTarget' && asString(params.sessionId)) {
  177. invalidateBrowserFrame(this.state, { commandSessionId: asString(params.sessionId) });
  178. }
  179. });
  180. }
  181. get transport(): BrowserTransport {
  182. return this.state.transport;
  183. }
  184. get generation(): number {
  185. return this.state.generation;
  186. }
  187. /** A failed interruption reset requires the provider to recreate this session. */
  188. get requiresRecreation(): boolean {
  189. return this.poisoned;
  190. }
  191. /** Provider adapter escape hatch for actions that remain provider-specific. */
  192. resolveOpaqueRef(ref: string): ElementRecord | null {
  193. // Some focused white-box fixtures predate retained snapshots and seed only
  194. // ElementMap. Once a snapshot store exists, it is the sole production ref
  195. // authority so expiry/pruning cannot be bypassed through ElementMap.
  196. const allowFixtureFallback = this.state.snapshotAuthorityEstablished !== true;
  197. return (
  198. resolveBrowserSnapshotElement(this.state, ref)?.element ??
  199. (allowFixtureFallback ? this.state.elementMap.getElementByOpaqueRef(ref) : null)
  200. );
  201. }
  202. /**
  203. * Resolve an opaque ref together with the frame identity from the exact
  204. * snapshot that issued it. Adapters must use this atomic result when they
  205. * validate a public `{ ref, frame }` pair; consulting the latest snapshot's
  206. * frame map separately can incorrectly reject a retained ref.
  207. */
  208. resolveOpaqueTarget(ref: string): BrowserCoreResolvedTarget | null {
  209. const resolved = resolveBrowserSnapshotElement(this.state, ref);
  210. if (!resolved) return null;
  211. const frameId = resolved.element.frameId ?? 'main';
  212. return {
  213. element: resolved.element,
  214. snapshotId: resolved.snapshot.id,
  215. generation: resolved.snapshot.generation,
  216. frameId,
  217. frameRef: resolved.snapshot.frameRefs?.get(frameId) ?? null,
  218. };
  219. }
  220. resolveFrameRef(frameId = 'main'): string | null {
  221. return this.state.snapshot?.frameRefs?.get(frameId) ?? null;
  222. }
  223. /** Release the lifecycle listener before the provider closes its transport. */
  224. dispose(): void {
  225. this.navigationEventDisposer();
  226. if (this.ownsCdpHelper) this.state.cdpHelper.stopDOMListener();
  227. }
  228. /** Invalidate opaque refs after navigation observed outside Browser Core. */
  229. synchronizeGeneration(generation: number): void {
  230. const normalized = Math.max(0, Math.floor(generation));
  231. if (normalized === this.externalNavigationGeneration) return;
  232. this.externalNavigationGeneration = normalized;
  233. this.invalidate(this.state);
  234. }
  235. async execute(
  236. action: string,
  237. input: Record<string, unknown>,
  238. signal?: AbortSignal,
  239. ): Promise<unknown> {
  240. if (this.active) throw new Error('BROWSER_SESSION_BUSY: another Browser action is running');
  241. if (this.poisoned) {
  242. throw new Error(
  243. 'BROWSER_SESSION_POISONED: Browser connection recovery failed; recreate the Browser session and inspect the page before continuing',
  244. );
  245. }
  246. if (signal?.aborted) throw new Error('ABORTED: Browser action was cancelled');
  247. const requestedTimeoutMs = asNumber(input.timeout, this.actionTimeoutMs);
  248. const ref = asString(input.ref);
  249. const textTarget =
  250. ref && (action === 'fill' || action === 'type')
  251. ? (resolveBrowserSnapshotElement(this.state, ref)?.element ??
  252. this.state.elementMap.getElementByOpaqueRef(ref))
  253. : null;
  254. const timeoutMs = actionDeadline(
  255. action,
  256. input,
  257. requestedTimeoutMs,
  258. this.actionTimeoutMs,
  259. textTarget?.virtualEditor === true,
  260. );
  261. // Validate the complete action deadline before claiming the session. The
  262. // deadline calculation can reject synchronously (for example, delayed
  263. // input that cannot fit within the maximum action budget); such a rejected
  264. // request must not leave the session permanently busy.
  265. this.active = true;
  266. const controller = new AbortController();
  267. let timedOut = false;
  268. const forwardAbort = (): void => controller.abort();
  269. signal?.addEventListener('abort', forwardAbort, { once: true });
  270. const timer = setTimeout(() => {
  271. timedOut = true;
  272. controller.abort();
  273. }, timeoutMs);
  274. timer.unref?.();
  275. this.state.commandSignal = controller.signal;
  276. this.state.commandTimeoutMs = Math.min(this.commandTimeoutMs, timeoutMs);
  277. const recoveryGeneration = this.state.cdpHelper.getInterruptionRecoveryState().generation;
  278. const abortResult = new Promise<never>((_resolve, reject) => {
  279. controller.signal.addEventListener(
  280. 'abort',
  281. () => {
  282. void this.state.transport.stopLoading().catch(() => undefined);
  283. reject(
  284. new Error(
  285. timedOut
  286. ? `ACTION_TIMEOUT: Browser action exceeded ${timeoutMs}ms`
  287. : 'ABORTED: Browser action was cancelled',
  288. ),
  289. );
  290. },
  291. { once: true },
  292. );
  293. });
  294. let startResult: Promise<void> | undefined;
  295. let actionResult: Promise<unknown> | undefined;
  296. try {
  297. // A provider may have reset its CDP connection after the previous
  298. // command was cancelled. Starting here makes handler/session recovery a
  299. // precondition for every Core action, not just page scans.
  300. startResult = this.state.transport.start(controller.signal);
  301. await Promise.race([startResult, abortResult]);
  302. actionResult = this.executeAction(action, input);
  303. // Observe a late rejection after cancellation instead of leaking an
  304. // unhandled promise while the transport discards the late CDP response.
  305. actionResult.catch(() => undefined);
  306. return await Promise.race([actionResult, abortResult]);
  307. } catch (error) {
  308. // A provider command can hit its own deadline before the encompassing
  309. // action timer fires. Either interruption leaves an already-sent CDP
  310. // side effect uncertain, so never release the action gate until the
  311. // connection has been reset or the session has been poisoned.
  312. if (controller.signal.aborted || isBrowserOperationInterruption(error)) {
  313. if (!controller.signal.aborted) {
  314. void this.state.transport.stopLoading().catch(() => undefined);
  315. }
  316. const recoveryDeadline = Date.now() + this.commandTimeoutMs;
  317. const recovered = await this.recoverInterruptedOperation(
  318. recoveryGeneration,
  319. Math.max(1, recoveryDeadline - Date.now()),
  320. );
  321. const settled = await this.settleInterruptedOperation(
  322. startResult,
  323. actionResult,
  324. Math.max(1, recoveryDeadline - Date.now()),
  325. );
  326. this.invalidate(this.state);
  327. this.poisoned = !recovered || !settled;
  328. }
  329. throw error;
  330. } finally {
  331. clearTimeout(timer);
  332. signal?.removeEventListener('abort', forwardAbort);
  333. this.state.commandSignal = undefined;
  334. this.state.commandTimeoutMs = undefined;
  335. this.state.commandSessionId = undefined;
  336. this.active = false;
  337. }
  338. }
  339. private async recoverInterruptedOperation(
  340. recoveryGeneration: number,
  341. timeoutMs: number,
  342. ): Promise<boolean> {
  343. const helperRecovery = this.state.cdpHelper.getInterruptionRecoveryState();
  344. if (helperRecovery.generation !== recoveryGeneration) {
  345. return helperRecovery.succeeded;
  346. }
  347. return this.state.cdpHelper.recoverTransportAfterInterruption(timeoutMs, true);
  348. }
  349. private async settleInterruptedOperation(
  350. startResult: Promise<void> | undefined,
  351. actionResult: Promise<unknown> | undefined,
  352. timeoutMs: number,
  353. ): Promise<boolean> {
  354. const pending = [startResult, actionResult].filter(
  355. (candidate): candidate is Promise<unknown> => candidate !== undefined,
  356. );
  357. if (pending.length === 0) return true;
  358. try {
  359. await withTimeout(
  360. Promise.allSettled(pending).then(() => undefined),
  361. timeoutMs,
  362. 'Browser interrupted action settlement',
  363. );
  364. return true;
  365. } catch {
  366. return false;
  367. }
  368. }
  369. private async executeAction(action: string, input: Record<string, unknown>): Promise<unknown> {
  370. if (action !== 'press_key') this.state.keyboardContinuationTarget = undefined;
  371. switch (action) {
  372. case 'inspect':
  373. return this.inspect(this.state, input);
  374. case 'query':
  375. return this.query(this.state, input);
  376. case 'navigate':
  377. return this.navigate(this.state, input);
  378. case 'back':
  379. return this.history(this.state, 'back');
  380. case 'forward':
  381. return this.history(this.state, 'forward');
  382. case 'reload':
  383. return this.reload(this.state);
  384. case 'click':
  385. return this.click(this.state, input);
  386. case 'click_and_wait_for_navigation':
  387. return this.clickAndWaitForNavigation(input, this.actionTimeoutMs);
  388. case 'double_click':
  389. return this.click(this.state, { ...input, clickCount: 2 });
  390. case 'drag':
  391. return this.drag(input);
  392. case 'fill':
  393. return this.type(this.state, { ...input, clear: true });
  394. case 'type':
  395. return this.type(this.state, input);
  396. case 'press_key':
  397. return this.pressKey(this.state, input);
  398. case 'check':
  399. return this.setChecked(this.state, input, true);
  400. case 'uncheck':
  401. return this.setChecked(this.state, input, false);
  402. case 'select_option':
  403. return this.selectOption(this.state, input);
  404. case 'upload_files':
  405. return this.uploadFiles(this.state, input);
  406. case 'paste':
  407. return this.paste(this.state, input);
  408. case 'scroll':
  409. return this.scroll(this.state, input);
  410. case 'hover':
  411. return this.hover(input);
  412. case 'wait':
  413. case 'wait_for':
  414. return this.waitFor(this.state, input);
  415. case 'get_dom':
  416. return this.query(this.state, { ...input, kind: 'dom' });
  417. case 'screenshot':
  418. return this.screenshot(this.state, input);
  419. case 'verify_text':
  420. return this.verifyText(input);
  421. case 'inspect_editable_targets':
  422. return this.query(this.state, { ...input, kind: 'editable' });
  423. case 'open_tab':
  424. throw new Error('PROVIDER_LIFECYCLE_ACTION: open_tab must be handled by the provider');
  425. default:
  426. throw new Error(`Unsupported Browser Core action: ${String(action)}`);
  427. }
  428. }
  429. private async clickAndWaitForNavigation(
  430. input: Record<string, unknown>,
  431. defaultTimeoutMs: number,
  432. ): Promise<unknown> {
  433. const timeoutMs = Math.max(
  434. 1_000,
  435. Math.min(
  436. MAX_ACTION_TIMEOUT_MS,
  437. positiveDeadline(asNumber(input.timeout, defaultTimeoutMs), defaultTimeoutMs),
  438. ),
  439. );
  440. const before = await this.readPageSummary(this.state);
  441. const beforeTimeOrigin = await this.evaluateMainDocument<number>(
  442. this.state,
  443. 'performance.timeOrigin',
  444. );
  445. const result = await this.click(this.state, {
  446. ...input,
  447. __navigationTimeoutMs: timeoutMs,
  448. });
  449. if (!isRecord(result)) return result;
  450. const navigation = isRecord(result.navigation) ? result.navigation : {};
  451. const detected = result.code === 'UNEXPECTED_NAVIGATION' || navigation.detected === true;
  452. if (!detected) {
  453. return {
  454. ...result,
  455. success: false,
  456. code: 'ACTION_TIMEOUT',
  457. error: 'The click did not produce an observable main-document navigation.',
  458. recovery: 'Inspect the current page before deciding whether to retry.',
  459. };
  460. }
  461. try {
  462. const ready = await this.waitForDocumentReady(
  463. this.state,
  464. (state) => state.url !== before.url || state.timeOrigin !== beforeTimeOrigin,
  465. timeoutMs,
  466. );
  467. const page = await this.readPageSummary(this.state);
  468. this.assertNotChromeErrorPage(page, 'after the click');
  469. const normalized: Record<string, unknown> = { ...result, success: true, url: page.url };
  470. delete normalized.code;
  471. delete normalized.error;
  472. delete normalized.recovery;
  473. normalized.title = page.title;
  474. normalized.navigation = {
  475. ...navigation,
  476. detected: true,
  477. urlChanged: page.url !== before.url,
  478. loaded: true,
  479. awaited: true,
  480. readyState: ready.readyState,
  481. generation: this.state.generation,
  482. };
  483. return normalized;
  484. } catch (error) {
  485. if (isBrowserOperationInterruption(error)) throw error;
  486. return {
  487. ...result,
  488. success: false,
  489. code: 'NAVIGATION_FAILED',
  490. error: error instanceof Error ? error.message : String(error),
  491. recovery: 'Inspect the current page before deciding whether to retry.',
  492. };
  493. }
  494. }
  495. private async hover(input: Record<string, unknown>): Promise<unknown> {
  496. const startedAt = Date.now();
  497. const target = await this.resolveTarget(this.state, input);
  498. const hoverPoint = inputCoordinate(this.state, { x: target.x, y: target.y });
  499. const ref = asString(input.ref);
  500. const fallbackText = ref ? (this.state.elementMap.getElementByOpaqueRef(ref)?.text ?? '') : '';
  501. const captureSemantic = async () => {
  502. if (target.backendNodeId === undefined) return null;
  503. const snapshot = await this.state.cdpHelper
  504. .captureHoverSemanticSnapshotByBackendNodeId(target.backendNodeId, {
  505. ...(this.state.commandSignal ? { signal: this.state.commandSignal } : {}),
  506. ...(this.state.commandTimeoutMs ? { timeoutMs: this.state.commandTimeoutMs } : {}),
  507. ...(this.state.commandSessionId ? { commandSessionId: this.state.commandSessionId } : {}),
  508. })
  509. .catch((error) => {
  510. if (isBrowserOperationInterruption(error)) throw error;
  511. return null;
  512. });
  513. return isHoverSemanticSnapshot(snapshot) ? snapshot : null;
  514. };
  515. const before = await captureSemantic();
  516. await this.state.beforePointerAction?.(
  517. { action: 'hover', point: { x: target.x, y: target.y } },
  518. this.state.commandSignal,
  519. );
  520. await this.state.transport.send(
  521. 'Input.dispatchMouseEvent',
  522. { type: 'mouseMoved', ...hoverPoint },
  523. undefined,
  524. { signal: this.state.commandSignal, timeoutMs: this.state.commandTimeoutMs },
  525. );
  526. const hovered =
  527. target.backendNodeId === undefined
  528. ? true
  529. : await this.callBackendNode<boolean>(
  530. this.state,
  531. target.backendNodeId,
  532. `function () { return this.matches(':hover') || this.contains(document.elementFromPoint(${target.contextX ?? target.x}, ${target.contextY ?? target.y})); }`,
  533. ).catch((error) => {
  534. if (isBrowserOperationInterruption(error)) throw error;
  535. return false;
  536. });
  537. let after = null;
  538. let semanticEffect = resolveBrowserHoverSemantic(before, after, fallbackText);
  539. if (target.backendNodeId !== undefined) {
  540. for (let sample = 0; sample < HOVER_SEMANTIC_SAMPLE_COUNT; sample += 1) {
  541. await delay(HOVER_SEMANTIC_SAMPLE_DELAY_MS, this.state.commandSignal);
  542. after = await captureSemantic();
  543. semanticEffect = resolveBrowserHoverSemantic(before, after, fallbackText);
  544. if (semanticEffect.semantic.name) break;
  545. }
  546. }
  547. return {
  548. success: hovered,
  549. durationMs: Date.now() - startedAt,
  550. target: { resolved: true, ...(target.rect ? { rect: target.rect } : {}) },
  551. effect: {
  552. dispatched: true,
  553. verified: hovered,
  554. hovered,
  555. tooltipObserved: semanticEffect.tooltipObserved,
  556. semantic: semanticEffect.semantic,
  557. },
  558. };
  559. }
  560. private async drag(input: Record<string, unknown>): Promise<unknown> {
  561. const sourceInput = isRecord(input.source) ? input.source : input;
  562. const targetInput = isRecord(input.target) ? input.target : undefined;
  563. if (!targetInput) throw new Error('DRAG_REQUIRES_TARGET');
  564. await this.resolveTarget(this.state, sourceInput);
  565. await this.resolveTarget(this.state, targetInput);
  566. // Resolving the target may scroll the same container that owns the source.
  567. // Measure both endpoints again without another scroll before dispatching.
  568. const source = await this.resolveTarget(this.state, sourceInput, false);
  569. const target = await this.resolveTarget(this.state, targetInput, false);
  570. const viewport = await this.readCssViewport(this.state);
  571. if (
  572. !dragTargetIsVisible(source.rect, viewport) ||
  573. !dragTargetIsVisible(target.rect, viewport)
  574. ) {
  575. throw new Error(
  576. 'ELEMENT_NOT_INTERACTABLE: drag source and target are not simultaneously visible',
  577. );
  578. }
  579. await this.state.beforePointerAction?.(
  580. { action: 'drag', point: { x: source.x, y: source.y } },
  581. this.state.commandSignal,
  582. );
  583. const dragResult = await this.state.cdpHelper.dispatchDragGesture(
  584. inputCoordinate(this.state, { x: source.x, y: source.y }),
  585. inputCoordinate(this.state, { x: target.x, y: target.y }),
  586. {
  587. interceptTimeoutMs: Math.min(this.state.commandTimeoutMs ?? 2_000, 2_000),
  588. commandTimeoutMs: this.state.commandTimeoutMs,
  589. signal: this.state.commandSignal,
  590. },
  591. );
  592. await this.state.beforePointerAction?.(
  593. { action: 'drag', point: { x: target.x, y: target.y } },
  594. this.state.commandSignal,
  595. );
  596. this.invalidateObservation(this.state);
  597. return {
  598. success: true,
  599. ...dragResult,
  600. // A completed CDP gesture proves dispatch, not that the application
  601. // accepted the drop or changed business state. Keep that distinction
  602. // explicit so agents verify the page after dragging.
  603. effect: { dispatched: true, verified: false, verificationRequired: true },
  604. };
  605. }
  606. private async verifyText(input: Record<string, unknown>): Promise<unknown> {
  607. const result = await this.query(this.state, {
  608. kind: 'text',
  609. ...(typeof input.selector === 'string' ? { selector: input.selector } : {}),
  610. maxChars: 50_000,
  611. });
  612. const actual = asString(isRecord(result) ? result.text : '');
  613. const expected = Array.isArray(input.texts)
  614. ? input.texts.map(String)
  615. : typeof input.text === 'string'
  616. ? [input.text]
  617. : [];
  618. const caseSensitive = input.caseSensitive === true;
  619. const haystack = caseSensitive ? actual : actual.toLocaleLowerCase();
  620. const matches = expected.map((item) => {
  621. const needle = caseSensitive ? item : item.toLocaleLowerCase();
  622. return input.exact === true ? haystack.trim() === needle.trim() : haystack.includes(needle);
  623. });
  624. return {
  625. success: matches.length > 0 && matches.every(Boolean),
  626. expected,
  627. matches,
  628. text: actual.slice(0, 2_000),
  629. };
  630. }
  631. }
  632. function dragTargetIsVisible(
  633. rect: { x: number; y: number; width: number; height: number } | undefined,
  634. viewport: { width: number; height: number },
  635. ): boolean {
  636. return Boolean(
  637. rect &&
  638. rect.width > 0 &&
  639. rect.height > 0 &&
  640. rect.x >= 0 &&
  641. rect.y >= 0 &&
  642. rect.x + rect.width <= viewport.width &&
  643. rect.y + rect.height <= viewport.height,
  644. );
  645. }
  646. function positiveDeadline(value: number | undefined, fallback: number): number {
  647. return typeof value === 'number' && Number.isFinite(value) && value > 0
  648. ? Math.floor(value)
  649. : fallback;
  650. }
  651. function actionDeadline(
  652. action: string,
  653. input: Record<string, unknown>,
  654. requestedMs: number,
  655. fallback: number,
  656. focusedKeyboard = false,
  657. ): number {
  658. const requested = Math.min(MAX_ACTION_TIMEOUT_MS, positiveDeadline(requestedMs, fallback));
  659. if (action === 'fill' || action === 'type') {
  660. const text = asString(input.text);
  661. const rawDelay = input.delay;
  662. const delayMs =
  663. typeof rawDelay === 'number' ? rawDelay : typeof rawDelay === 'string' ? Number(rawDelay) : 0;
  664. if (text.length > 0 && Number.isFinite(delayMs) && (delayMs > 0 || focusedKeyboard)) {
  665. const characters = Array.from(text);
  666. const delayedInputMs = characters.length * Math.max(0, delayMs);
  667. const cdpDispatchMs = focusedKeyboard
  668. ? characters.reduce(
  669. (count, character) => count + (/^[\x20-\x7E]$/u.test(character) ? 3 : 1),
  670. action === 'fill' || input.clear === true ? 4 : 0,
  671. ) * TEXT_INPUT_CDP_EVENT_ESTIMATE_MS
  672. : 0;
  673. const required = Math.ceil(delayedInputMs + cdpDispatchMs) + TEXT_INPUT_COMPLETION_BUFFER_MS;
  674. if (required > MAX_ACTION_TIMEOUT_MS) {
  675. throw new Error(
  676. `INPUT_DURATION_EXCEEDS_DEADLINE: Delayed input requires ${required}ms but the maximum safe Browser action budget is ${MAX_ACTION_TIMEOUT_MS}ms`,
  677. );
  678. }
  679. return Math.max(requested, required);
  680. }
  681. }
  682. if (action === 'click_and_wait_for_navigation') {
  683. return Math.min(MAX_ACTION_TIMEOUT_MS, requested + ACTION_COMPLETION_BUFFER_MS);
  684. }
  685. if (action === 'upload_files') {
  686. return Math.min(MAX_ACTION_WITH_COMPLETION_BUFFER_MS, requested + ACTION_COMPLETION_BUFFER_MS);
  687. }
  688. if (action === 'navigate' || action === 'reload') {
  689. // The readiness probe owns a 30s window after page summaries, diagnostics
  690. // setup and the navigation CDP command. Keep those preconditions outside
  691. // the readiness budget instead of letting the default 30s action timer
  692. // cancel an otherwise valid slow navigation.
  693. return Math.max(requested, NAVIGATION_ACTION_TIMEOUT_MS);
  694. }
  695. if (action !== 'wait' && action !== 'wait_for') return requested;
  696. // `wait.timeout` is the condition budget. Keep a small cleanup margin so a
  697. // successful timeout wait is not cancelled by the enclosing action timer.
  698. return Math.min(MAX_ACTION_TIMEOUT_MS, requested + 1_000);
  699. }