browser-actions.ts 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. import { captureBrowserScreenshot, observeBrowserDownload } from './browser-action-artifacts.js';
  2. import {
  3. buttonName,
  4. classifyBrowserNavigationEvent,
  5. waitExpression,
  6. } from './browser-action-helpers.js';
  7. import { BrowserActionTargetSupport } from './browser-action-targets.js';
  8. import { browserPrintableKeyDescriptor } from './browser-keyboard.js';
  9. import {
  10. asNumber,
  11. asString,
  12. cdp,
  13. delay,
  14. evaluate,
  15. resolveBrowserSnapshotElement,
  16. stringArray,
  17. type BrowserSessionState as SessionState,
  18. } from './browser-state.js';
  19. import type { CDPEditableState, CDPRenderedState } from './cdp-helper-contracts.js';
  20. import { isBrowserOperationInterruption } from './operation-timeout.js';
  21. const DEFAULT_WAIT_TIMEOUT_MS = 30_000;
  22. const ACTION_SETTLE_DELAY_MS = 100;
  23. const CLICK_NAVIGATION_DETECTION_MS = 1_000;
  24. const NAVIGATION_READY_TIMEOUT_MS = 30_000;
  25. const MAX_NAVIGATION_READY_TIMEOUT_MS = 120_000;
  26. const HISTORY_READY_TIMEOUT_MS = 10_000;
  27. const SCROLL_BOUNDARY_EPSILON = 1;
  28. const VERIFIED_FILL_SAMPLE_COUNT = 4;
  29. const VERIFIED_FILL_SAMPLE_DELAY_MS = 50;
  30. interface BrowserScrollSnapshot {
  31. ownerId: string;
  32. kind: 'document' | 'element' | 'unknown';
  33. scrollable: boolean;
  34. scrollTop: number;
  35. scrollLeft: number;
  36. scrollHeight: number;
  37. scrollWidth: number;
  38. clientHeight: number;
  39. clientWidth: number;
  40. }
  41. function normalizeScrollSnapshot(value: unknown, axis: 'x' | 'y'): BrowserScrollSnapshot | null {
  42. if (value === null || typeof value !== 'object' || Array.isArray(value)) return null;
  43. const candidate = value as Record<string, unknown>;
  44. const numericFields = [
  45. 'scrollTop',
  46. 'scrollLeft',
  47. 'scrollHeight',
  48. 'scrollWidth',
  49. 'clientHeight',
  50. 'clientWidth',
  51. ] as const;
  52. if (
  53. (candidate.kind === 'document' ||
  54. candidate.kind === 'element' ||
  55. candidate.kind === 'unknown') &&
  56. typeof candidate.ownerId === 'string' &&
  57. candidate.ownerId.length > 0 &&
  58. typeof candidate.scrollable === 'boolean' &&
  59. numericFields.every(
  60. (field) => typeof candidate[field] === 'number' && Number.isFinite(candidate[field]),
  61. )
  62. ) {
  63. return candidate as unknown as BrowserScrollSnapshot;
  64. }
  65. // Keep the original document-only response shape readable while providers
  66. // and focused test transports move to owner-aware snapshots.
  67. const legacyNumericFields = [
  68. 'x',
  69. 'y',
  70. 'scrollHeight',
  71. 'scrollWidth',
  72. 'clientHeight',
  73. 'clientWidth',
  74. ] as const;
  75. if (
  76. !legacyNumericFields.every(
  77. (field) => typeof candidate[field] === 'number' && Number.isFinite(candidate[field]),
  78. )
  79. ) {
  80. return null;
  81. }
  82. const scrollHeight = candidate.scrollHeight as number;
  83. const scrollWidth = candidate.scrollWidth as number;
  84. const clientHeight = candidate.clientHeight as number;
  85. const clientWidth = candidate.clientWidth as number;
  86. return {
  87. ownerId: 'document',
  88. kind: 'document',
  89. scrollable:
  90. axis === 'y'
  91. ? scrollHeight > clientHeight + SCROLL_BOUNDARY_EPSILON
  92. : scrollWidth > clientWidth + SCROLL_BOUNDARY_EPSILON,
  93. scrollTop: candidate.y as number,
  94. scrollLeft: candidate.x as number,
  95. scrollHeight,
  96. scrollWidth,
  97. clientHeight,
  98. clientWidth,
  99. };
  100. }
  101. interface DocumentReadiness {
  102. readonly url: string;
  103. readonly readyState: string;
  104. readonly timeOrigin: number;
  105. }
  106. interface NavigationHistoryEntry {
  107. readonly id: number;
  108. readonly url: string;
  109. }
  110. interface NavigationHistory {
  111. readonly currentIndex: number;
  112. readonly entries: readonly NavigationHistoryEntry[];
  113. }
  114. interface NavigationEventObservation {
  115. readonly method: 'Page.frameNavigated' | 'Page.navigatedWithinDocument';
  116. readonly params: unknown;
  117. readonly sessionId?: string;
  118. }
  119. function observeMainDocumentNavigation(
  120. session: SessionState,
  121. timeoutMs: number,
  122. mainFrameId?: string,
  123. ): Promise<NavigationEventObservation | undefined> {
  124. const childSessionIds = new Set(
  125. (session.transport.listAttachedFrames?.() ?? []).map((frame) => frame.sessionId),
  126. );
  127. return new Promise((resolve) => {
  128. let finished = false;
  129. let timer: ReturnType<typeof setTimeout> | undefined;
  130. let unsubscribe: (() => void) | undefined;
  131. const signal = session.commandSignal;
  132. const finish = (value: NavigationEventObservation | undefined): void => {
  133. if (finished) return;
  134. finished = true;
  135. if (timer) clearTimeout(timer);
  136. signal?.removeEventListener('abort', onAbort);
  137. unsubscribe?.();
  138. resolve(value);
  139. };
  140. const onAbort = (): void => finish(undefined);
  141. signal?.addEventListener('abort', onAbort, { once: true });
  142. if (signal?.aborted) {
  143. onAbort();
  144. return;
  145. }
  146. unsubscribe = session.transport.onEvent((event) => {
  147. if (
  148. event.method !== 'Page.frameNavigated' &&
  149. event.method !== 'Page.navigatedWithinDocument'
  150. ) {
  151. return;
  152. }
  153. if (event.sessionId && childSessionIds.has(event.sessionId)) return;
  154. const observation: NavigationEventObservation = {
  155. method: event.method,
  156. params: event.params,
  157. ...(event.sessionId ? { sessionId: event.sessionId } : {}),
  158. };
  159. if (classifyBrowserNavigationEvent(observation, session.transport, mainFrameId) !== 'main')
  160. return;
  161. finish(observation);
  162. });
  163. if (finished) {
  164. unsubscribe();
  165. return;
  166. }
  167. timer = setTimeout(() => finish(undefined), timeoutMs);
  168. timer.unref?.();
  169. });
  170. }
  171. export abstract class BrowserActionSupport extends BrowserActionTargetSupport {
  172. protected async navigate(
  173. session: SessionState,
  174. input: Record<string, unknown>,
  175. ): Promise<unknown> {
  176. const url = asString(input.url);
  177. if (!isSupportedBrowserUrl(url)) {
  178. throw new Error('Unsupported Browser URL: expected http(s), file, data, or about URL');
  179. }
  180. const startedAt = Date.now();
  181. const before = await this.readPageSummary(session);
  182. // Register the shared diagnostics listener before the first external
  183. // navigation. Enabling Runtime/Network at the transport layer does not
  184. // buffer events for a CDPHelper listener that has not been attached yet.
  185. await session.cdpHelper.startDOMListener(session.commandSignal);
  186. const beforeTimeOrigin = await this.evaluateMainDocument<number>(
  187. session,
  188. 'performance.timeOrigin',
  189. );
  190. const navigation = await this.sendMainDocumentCommand<{ errorText?: string }>(
  191. session,
  192. 'Page.navigate',
  193. { url },
  194. );
  195. if (navigation.errorText) throw new Error(`NAVIGATION_FAILED: ${navigation.errorText}`);
  196. await this.waitForDocumentReady(
  197. session,
  198. (state) => state.url !== before.url || state.timeOrigin !== beforeTimeOrigin,
  199. NAVIGATION_READY_TIMEOUT_MS,
  200. );
  201. await delay(ACTION_SETTLE_DELAY_MS, session.commandSignal);
  202. this.invalidate(session);
  203. const page = await this.readPageSummary(session);
  204. this.assertNotChromeErrorPage(page, `while navigating to ${url}`);
  205. return {
  206. success: true,
  207. url: page.url,
  208. title: page.title,
  209. durationMs: Date.now() - startedAt,
  210. navigation: {
  211. detected: true,
  212. urlChanged: true,
  213. loaded: true,
  214. generation: session.generation,
  215. },
  216. };
  217. }
  218. protected async history(session: SessionState, direction: 'back' | 'forward'): Promise<unknown> {
  219. const startedAt = Date.now();
  220. const before = await this.readPageSummary(session);
  221. const history = await this.readNavigationHistory(session);
  222. const targetIndex = history.currentIndex + (direction === 'back' ? -1 : 1);
  223. const target = history.entries[targetIndex];
  224. if (!target) {
  225. return {
  226. success: false,
  227. durationMs: Date.now() - startedAt,
  228. url: before.url,
  229. title: before.title,
  230. navigation: { detected: false, urlChanged: false, loaded: true },
  231. };
  232. }
  233. await this.sendMainDocumentCommand(session, 'Page.navigateToHistoryEntry', {
  234. entryId: target.id,
  235. });
  236. await this.waitForHistoryEntryReady(
  237. session,
  238. { index: targetIndex, entryId: target.id },
  239. HISTORY_READY_TIMEOUT_MS,
  240. );
  241. await delay(ACTION_SETTLE_DELAY_MS, session.commandSignal);
  242. this.invalidate(session);
  243. const after = await this.readPageSummary(session);
  244. this.assertNotChromeErrorPage(after, `while navigating ${direction}`);
  245. return {
  246. success: true,
  247. durationMs: Date.now() - startedAt,
  248. url: after.url,
  249. title: after.title,
  250. navigation: {
  251. detected: true,
  252. urlChanged: before.url !== after.url,
  253. loaded: true,
  254. generation: session.generation,
  255. },
  256. };
  257. }
  258. protected async reload(session: SessionState): Promise<unknown> {
  259. const beforeTimeOrigin = await this.evaluateMainDocument<number>(
  260. session,
  261. 'performance.timeOrigin',
  262. );
  263. await this.sendMainDocumentCommand(session, 'Page.reload', { ignoreCache: false });
  264. await this.waitForDocumentReady(
  265. session,
  266. (state) => state.timeOrigin !== beforeTimeOrigin,
  267. NAVIGATION_READY_TIMEOUT_MS,
  268. );
  269. await delay(ACTION_SETTLE_DELAY_MS, session.commandSignal);
  270. this.invalidate(session);
  271. const page = await this.readPageSummary(session);
  272. this.assertNotChromeErrorPage(page, 'while reloading the current page');
  273. return {
  274. success: true,
  275. url: page.url,
  276. title: page.title,
  277. navigation: { detected: true, loaded: true },
  278. };
  279. }
  280. protected async waitForDocumentReady(
  281. session: SessionState,
  282. acceptsUrl: (state: DocumentReadiness) => boolean,
  283. timeoutMs: number,
  284. ): Promise<DocumentReadiness> {
  285. const deadline = Date.now() + timeoutMs;
  286. while (Date.now() <= deadline) {
  287. try {
  288. const state = await this.evaluateMainDocument<DocumentReadiness>(
  289. session,
  290. '({ url: location.href, readyState: document.readyState, timeOrigin: performance.timeOrigin })',
  291. );
  292. if (
  293. acceptsUrl(state) &&
  294. (state.readyState === 'interactive' || state.readyState === 'complete')
  295. ) {
  296. return state;
  297. }
  298. } catch (error) {
  299. if (session.commandSignal?.aborted || isBrowserOperationInterruption(error)) throw error;
  300. // A navigation may briefly destroy the prior execution context.
  301. }
  302. await delay(50, session.commandSignal);
  303. }
  304. throw new Error(`ACTION_TIMEOUT: Browser navigation was not DOM-ready within ${timeoutMs}ms`);
  305. }
  306. protected assertNotChromeErrorPage(page: { readonly url: string }, context: string): void {
  307. if (!page.url.startsWith('chrome-error://')) return;
  308. throw new Error(`NAVIGATION_FAILED: Browser rendered an internal error page ${context}`);
  309. }
  310. protected evaluateMainDocument<T>(session: SessionState, expression: string): Promise<T> {
  311. return session.transport.evaluate<T>(expression, {
  312. ...(session.commandSignal ? { signal: session.commandSignal } : {}),
  313. ...(session.commandTimeoutMs ? { timeoutMs: session.commandTimeoutMs } : {}),
  314. });
  315. }
  316. private sendMainDocumentCommand<T = unknown>(
  317. session: SessionState,
  318. method: string,
  319. params?: Record<string, unknown>,
  320. ): Promise<T> {
  321. return session.transport.send<T>(method, params, undefined, {
  322. ...(session.commandSignal ? { signal: session.commandSignal } : {}),
  323. ...(session.commandTimeoutMs ? { timeoutMs: session.commandTimeoutMs } : {}),
  324. });
  325. }
  326. private async readMainFrameId(session: SessionState): Promise<string | undefined> {
  327. try {
  328. const result = await this.sendMainDocumentCommand<{
  329. frameTree?: { frame?: { id?: string } };
  330. }>(session, 'Page.getFrameTree');
  331. return typeof result.frameTree?.frame?.id === 'string'
  332. ? result.frameTree.frame.id
  333. : undefined;
  334. } catch (error) {
  335. if (isBrowserOperationInterruption(error)) throw error;
  336. return undefined;
  337. }
  338. }
  339. private readNavigationHistory(session: SessionState): Promise<NavigationHistory> {
  340. return this.sendMainDocumentCommand<NavigationHistory>(session, 'Page.getNavigationHistory');
  341. }
  342. private async waitForHistoryEntryReady(
  343. session: SessionState,
  344. target: { index: number; entryId: number },
  345. timeoutMs: number,
  346. ): Promise<DocumentReadiness> {
  347. const deadline = Date.now() + timeoutMs;
  348. while (Date.now() <= deadline) {
  349. try {
  350. const history = await this.readNavigationHistory(session);
  351. const currentEntry = history.entries[history.currentIndex];
  352. if (history.currentIndex === target.index && currentEntry?.id === target.entryId) {
  353. const state = await this.evaluateMainDocument<DocumentReadiness>(
  354. session,
  355. '({ url: location.href, readyState: document.readyState, timeOrigin: performance.timeOrigin })',
  356. );
  357. if (state.readyState === 'interactive' || state.readyState === 'complete') return state;
  358. }
  359. } catch (error) {
  360. if (session.commandSignal?.aborted || isBrowserOperationInterruption(error)) throw error;
  361. // Cross-document history traversal can briefly destroy the old
  362. // execution context. Keep polling the root page until the target
  363. // history entry and its document are both observable.
  364. }
  365. await delay(50, session.commandSignal);
  366. }
  367. throw new Error(`ACTION_TIMEOUT: Browser history was not DOM-ready within ${timeoutMs}ms`);
  368. }
  369. protected async click(session: SessionState, input: Record<string, unknown>): Promise<unknown> {
  370. const startedAt = Date.now();
  371. const before = await this.readPageSummary(session);
  372. const explicitNavigationTimeout = input.__navigationTimeoutMs;
  373. const navigationTimeoutMs =
  374. explicitNavigationTimeout === undefined
  375. ? (session.clickNavigationDetectionMs ?? CLICK_NAVIGATION_DETECTION_MS)
  376. : Math.max(
  377. CLICK_NAVIGATION_DETECTION_MS,
  378. Math.min(
  379. MAX_NAVIGATION_READY_TIMEOUT_MS,
  380. Math.floor(asNumber(explicitNavigationTimeout, CLICK_NAVIGATION_DETECTION_MS)),
  381. ),
  382. );
  383. const target = await this.resolveTarget(session, input);
  384. const coordinateTarget =
  385. input.position !== undefined || input.normalized_position !== undefined;
  386. const hitTarget = coordinateTarget
  387. ? await this.inspectCoordinateHitTarget(
  388. session,
  389. target.contextX ?? target.x,
  390. target.contextY ?? target.y,
  391. )
  392. : undefined;
  393. const clickCount = Math.max(1, Math.floor(asNumber(input.clickCount ?? input.click_count, 1)));
  394. await session.beforePointerAction?.(
  395. {
  396. action: clickCount > 1 ? 'double_click' : 'click',
  397. point: { x: target.x, y: target.y },
  398. },
  399. session.commandSignal,
  400. );
  401. const effectProbe = await this.startClickEffectProbe(
  402. session,
  403. target.contextX ?? target.x,
  404. target.contextY ?? target.y,
  405. );
  406. const downloadEvent = observeBrowserDownload(session, { signal: session.commandSignal });
  407. const mainFrameId = await this.readMainFrameId(session);
  408. const navigationEvent = observeMainDocumentNavigation(
  409. session,
  410. navigationTimeoutMs,
  411. mainFrameId,
  412. );
  413. await this.dispatchMouse(session, target.x, target.y, 'mouseMoved');
  414. const delayMs = Math.max(0, Math.floor(asNumber(input.delay, 50)));
  415. if (delayMs > 0) await delay(delayMs, session.commandSignal);
  416. for (let currentClick = 1; currentClick <= clickCount; currentClick += 1) {
  417. await this.dispatchMouse(session, target.x, target.y, 'mousePressed', {
  418. button: buttonName(input.button),
  419. clickCount: currentClick,
  420. });
  421. if (delayMs > 0) await delay(delayMs, session.commandSignal);
  422. await this.dispatchMouse(session, target.x, target.y, 'mouseReleased', {
  423. button: buttonName(input.button),
  424. clickCount: currentClick,
  425. });
  426. if (currentClick < clickCount && delayMs > 0) {
  427. await delay(delayMs, session.commandSignal);
  428. }
  429. }
  430. const navigationEventResult = await navigationEvent;
  431. await delay(ACTION_SETTLE_DELAY_MS, session.commandSignal);
  432. const download = await downloadEvent;
  433. // A navigation can replace the execution context before the first
  434. // post-click summary is available. The navigation event is the source of
  435. // truth for click-and-wait; keep ordinary click bounded and let its caller
  436. // perform the full ready-state wait.
  437. const after = await this.readPageSummary(session).catch((error) => {
  438. if (isBrowserOperationInterruption(error)) throw error;
  439. return before;
  440. });
  441. const effect = await this.finishClickEffectProbe(session, effectProbe).catch((error) => {
  442. if (isBrowserOperationInterruption(error)) throw error;
  443. return {
  444. observed: false,
  445. mutations: 0,
  446. focusChanged: false,
  447. targetStateChanged: false,
  448. };
  449. });
  450. const navigationDetected =
  451. classifyBrowserNavigationEvent(navigationEventResult, session.transport, mainFrameId) ===
  452. 'main' || before.url !== after.url;
  453. this.invalidateObservation(session);
  454. const result = {
  455. // Ordinary click success means that Browser input was dispatched. DOM
  456. // mutation/focus probes are diagnostics, not proof that the caller's
  457. // business goal completed. Main-document navigation remains the one
  458. // fail-closed exception for this non-navigation action.
  459. success: !navigationDetected,
  460. durationMs: Date.now() - startedAt,
  461. target: {
  462. resolved: true,
  463. rect: target.rect,
  464. ...(coordinateTarget
  465. ? {
  466. resolvedPosition: { x: target.x, y: target.y },
  467. ...(hitTarget ? { hitTarget, rect: hitTarget.rect } : {}),
  468. }
  469. : {}),
  470. },
  471. effect: {
  472. ...effect,
  473. dispatched: true,
  474. verified: false,
  475. verificationRequired: true,
  476. },
  477. navigation: {
  478. detected: navigationDetected,
  479. urlChanged: navigationDetected,
  480. generation: session.generation,
  481. },
  482. } as Record<string, unknown>;
  483. if (download) {
  484. result.download = download;
  485. if (download.state === 'canceled') {
  486. result.success = false;
  487. result.code = 'DOWNLOAD_CANCELED';
  488. result.error = 'Browser download was canceled before completion.';
  489. } else if (download.state !== 'completed') {
  490. // The click and download start were observed. Do not report an action
  491. // failure merely because a large/slow file outlived our observation
  492. // window; callers can inspect the explicit in-progress timeout state.
  493. result.success = true;
  494. result.download = { ...download, observation: 'timeout' };
  495. result.recovery = 'The download is still in progress; do not click again.';
  496. } else {
  497. result.success = true;
  498. }
  499. }
  500. if (navigationDetected) {
  501. result.success = false;
  502. result.code = 'UNEXPECTED_NAVIGATION';
  503. result.error = 'Ordinary click changed the page URL; inspect the new page before continuing.';
  504. result.recovery = 'Inspect the current page and use a newly observed ref.';
  505. }
  506. return result;
  507. }
  508. private async inspectCoordinateHitTarget(
  509. session: SessionState,
  510. x: number,
  511. y: number,
  512. ): Promise<
  513. | {
  514. tag: string;
  515. role: string;
  516. name: string;
  517. text: string;
  518. rect: { x: number; y: number; width: number; height: number };
  519. }
  520. | undefined
  521. > {
  522. return evaluate<
  523. | {
  524. tag: string;
  525. role: string;
  526. name: string;
  527. text: string;
  528. rect: { x: number; y: number; width: number; height: number };
  529. }
  530. | undefined
  531. >(
  532. session,
  533. `(() => {
  534. const point = { x: ${JSON.stringify(x)}, y: ${JSON.stringify(y)} };
  535. let element = document.elementFromPoint(point.x, point.y);
  536. while (element?.shadowRoot && typeof element.shadowRoot.elementFromPoint === 'function') {
  537. const deeper = element.shadowRoot.elementFromPoint(point.x, point.y);
  538. if (!deeper || deeper === element) break;
  539. element = deeper;
  540. }
  541. if (!(element instanceof Element)) return undefined;
  542. const rect = element.getBoundingClientRect();
  543. const text = String(element.textContent || '').replace(/\\s+/gu, ' ').trim();
  544. const name = element.getAttribute('aria-label') || element.getAttribute('title') || text;
  545. return {
  546. tag: String(element.tagName || '').toLowerCase().slice(0, 80),
  547. role: String(element.getAttribute('role') || '').slice(0, 80),
  548. name: String(name || '').slice(0, 300),
  549. text: text.slice(0, 300),
  550. rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
  551. };
  552. })()`,
  553. ).catch((error) => {
  554. if (isBrowserOperationInterruption(error)) throw error;
  555. return undefined;
  556. });
  557. }
  558. private async startClickEffectProbe(
  559. session: SessionState,
  560. x: number,
  561. y: number,
  562. ): Promise<{ key: string; before: string }> {
  563. const key = `__mavisClickProbe_${Date.now()}_${Math.random().toString(36).slice(2)}`;
  564. const before = await evaluate<string>(
  565. session,
  566. `(() => {
  567. const key = ${JSON.stringify(key)};
  568. const pointed = document.elementFromPoint(${x}, ${y});
  569. const state = (node) => node ? JSON.stringify({
  570. tag: node.tagName,
  571. id: node.id,
  572. value: 'value' in node ? String(node.value ?? '') : '',
  573. checked: 'checked' in node ? Boolean(node.checked) : undefined,
  574. pressed: node.getAttribute?.('aria-pressed'),
  575. expanded: node.getAttribute?.('aria-expanded'),
  576. selected: node.getAttribute?.('aria-selected'),
  577. disabled: node.getAttribute?.('aria-disabled'),
  578. className: typeof node.className === 'string' ? node.className : '',
  579. }) : '';
  580. const record = { count: 0, observer: null, beforeTarget: state(pointed), x: ${x}, y: ${y} };
  581. record.observer = new MutationObserver((entries) => { record.count += entries.length; });
  582. record.observer.observe(document, { subtree: true, childList: true, attributes: true, characterData: true });
  583. window[key] = record;
  584. return JSON.stringify({ active: state(document.activeElement), target: record.beforeTarget });
  585. })()`,
  586. );
  587. return { key, before };
  588. }
  589. private async finishClickEffectProbe(
  590. session: SessionState,
  591. probe: { key: string; before: string },
  592. ): Promise<{
  593. observed: boolean;
  594. mutations: number;
  595. focusChanged: boolean;
  596. targetStateChanged: boolean;
  597. }> {
  598. return evaluate(
  599. session,
  600. `(() => {
  601. const key = ${JSON.stringify(probe.key)};
  602. const record = window[key];
  603. if (!record) return { observed: false, mutations: 0, focusChanged: false, targetStateChanged: false };
  604. record.observer?.disconnect();
  605. const pointed = document.elementFromPoint(record.x, record.y);
  606. const state = (node) => node ? JSON.stringify({
  607. tag: node.tagName,
  608. id: node.id,
  609. value: 'value' in node ? String(node.value ?? '') : '',
  610. checked: 'checked' in node ? Boolean(node.checked) : undefined,
  611. pressed: node.getAttribute?.('aria-pressed'),
  612. expanded: node.getAttribute?.('aria-expanded'),
  613. selected: node.getAttribute?.('aria-selected'),
  614. disabled: node.getAttribute?.('aria-disabled'),
  615. className: typeof node.className === 'string' ? node.className : '',
  616. }) : '';
  617. const before = JSON.parse(${JSON.stringify(probe.before)});
  618. const active = state(document.activeElement);
  619. const target = state(pointed);
  620. const focusChanged = before.active !== active;
  621. const targetStateChanged = before.target !== target;
  622. const mutations = Number(record.count || 0);
  623. delete window[key];
  624. return { observed: mutations > 0 || focusChanged || targetStateChanged, mutations, focusChanged, targetStateChanged };
  625. })()`,
  626. );
  627. }
  628. protected async type(session: SessionState, input: Record<string, unknown>): Promise<unknown> {
  629. const startedAt = Date.now();
  630. const beforeGeneration = session.generation;
  631. const target = await this.resolveTarget(session, input, true, false);
  632. const text = asString(input.text);
  633. const delayMs = Math.max(0, Math.floor(asNumber(input.delay, 0)));
  634. const unexpectedNavigation = (dispatched: boolean): Record<string, unknown> => ({
  635. success: false,
  636. code: 'UNEXPECTED_NAVIGATION',
  637. error: 'Typing changed the active Browser page unexpectedly.',
  638. retryable: true,
  639. recovery: 'Inspect the current page before deciding whether to retry.',
  640. durationMs: Date.now() - startedAt,
  641. target: { resolved: true, rect: target.rect },
  642. effect: {
  643. dispatched,
  644. verified: false,
  645. verificationRequired: true,
  646. expectedTextLength: text.length,
  647. },
  648. navigation: { detected: true, generation: session.generation },
  649. });
  650. let inputDispatched = false;
  651. if (session.generation !== beforeGeneration) return unexpectedNavigation(false);
  652. if (target.backendNodeId === undefined) {
  653. const normalizedCoordinateTarget =
  654. input.normalized_position !== undefined &&
  655. input.position === undefined &&
  656. !asString(input.ref) &&
  657. !asString(input.selector);
  658. if (!normalizedCoordinateTarget) throw new Error('TYPE_REQUIRES_ELEMENT_REF');
  659. await session.beforePointerAction?.(
  660. { action: 'type', point: { x: target.x, y: target.y } },
  661. session.commandSignal,
  662. );
  663. await this.dispatchMouse(session, target.x, target.y, 'mouseMoved');
  664. inputDispatched = true;
  665. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  666. await delay(50, session.commandSignal);
  667. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  668. const clickCount = input.clear === true ? 3 : 1;
  669. for (let currentClick = 1; currentClick <= clickCount; currentClick += 1) {
  670. await this.dispatchMouse(session, target.x, target.y, 'mousePressed', {
  671. button: 'left',
  672. clickCount: currentClick,
  673. });
  674. inputDispatched = true;
  675. await delay(50, session.commandSignal);
  676. await this.dispatchMouse(session, target.x, target.y, 'mouseReleased', {
  677. button: 'left',
  678. clickCount: currentClick,
  679. });
  680. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  681. if (currentClick < clickCount) {
  682. await delay(50, session.commandSignal);
  683. if (session.generation !== beforeGeneration) {
  684. return unexpectedNavigation(inputDispatched);
  685. }
  686. }
  687. }
  688. await delay(ACTION_SETTLE_DELAY_MS, session.commandSignal);
  689. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  690. inputDispatched =
  691. (await this.insertText(session, text, delayMs, beforeGeneration)) || inputDispatched;
  692. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  693. await delay(ACTION_SETTLE_DELAY_MS, session.commandSignal);
  694. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  695. this.invalidateObservation(session);
  696. return {
  697. success: true,
  698. durationMs: Date.now() - startedAt,
  699. target: {
  700. resolved: true,
  701. rect: target.rect,
  702. resolvedPosition: { x: target.x, y: target.y },
  703. },
  704. effect: {
  705. dispatched: true,
  706. verified: false,
  707. verificationRequired: true,
  708. expectedTextLength: text.length,
  709. },
  710. };
  711. }
  712. const backendNodeId = target.backendNodeId;
  713. const ref = asString(input.ref);
  714. const observedElement = ref
  715. ? (resolveBrowserSnapshotElement(session, ref)?.element ??
  716. session.elementMap.getElementByOpaqueRef(ref))
  717. : null;
  718. const inspectionOptions = {
  719. ...(session.commandSignal ? { signal: session.commandSignal } : {}),
  720. ...(session.commandTimeoutMs ? { timeoutMs: session.commandTimeoutMs } : {}),
  721. ...(session.commandSessionId ? { commandSessionId: session.commandSessionId } : {}),
  722. };
  723. const inspectTextState = (
  724. expectedText?: string,
  725. ): Promise<CDPEditableState | CDPRenderedState> =>
  726. target.virtualEditor === true
  727. ? session.cdpHelper.inspectRenderedStateByBackendNodeId(
  728. backendNodeId,
  729. expectedText,
  730. inspectionOptions,
  731. )
  732. : session.cdpHelper.inspectEditableStateByBackendNodeId(
  733. backendNodeId,
  734. expectedText,
  735. inspectionOptions,
  736. );
  737. let before: CDPEditableState | CDPRenderedState;
  738. try {
  739. before = await inspectTextState();
  740. } catch (error) {
  741. if (isBrowserOperationInterruption(error)) throw error;
  742. if (session.generation !== beforeGeneration) return unexpectedNavigation(false);
  743. throw error;
  744. }
  745. if (session.generation !== beforeGeneration) return unexpectedNavigation(false);
  746. const targetMetadata = {
  747. resolved: true,
  748. tag: 'tag' in before ? before.tag : (observedElement?.tag ?? ''),
  749. role: 'role' in before ? before.role : (observedElement?.role ?? ''),
  750. contentEditable:
  751. 'contentEditable' in before
  752. ? before.contentEditable
  753. : observedElement?.attributes.contenteditable === 'true',
  754. ...(target.virtualEditor === true ? { virtual: true } : {}),
  755. rect: target.rect,
  756. };
  757. if (target.virtualEditor !== true && 'editable' in before && !before.editable) {
  758. return {
  759. success: false,
  760. code: 'TARGET_NOT_EDITABLE',
  761. error: 'The resolved Browser target is not editable.',
  762. message: 'The resolved Browser target is not editable.',
  763. retryable: false,
  764. recovery: 'Inspect the page and choose an input, textarea, or contenteditable ref.',
  765. durationMs: Date.now() - startedAt,
  766. target: targetMetadata,
  767. effect: { dispatched: false, verified: false, verificationRequired: true },
  768. navigation: { detected: false, generation: session.generation },
  769. };
  770. }
  771. if (target.coordinateSpace !== 'unavailable') {
  772. await session.beforePointerAction?.(
  773. {
  774. action: 'type',
  775. point: { x: target.x, y: target.y },
  776. },
  777. session.commandSignal,
  778. );
  779. }
  780. if (target.virtualEditor === true) {
  781. if (target.coordinateSpace === 'unavailable') {
  782. throw new Error(
  783. 'FRAME_COORDINATES_UNAVAILABLE: virtual editor activation requires safe viewport coordinates',
  784. );
  785. }
  786. inputDispatched = true;
  787. try {
  788. await this.activateVirtualEditor(session, {
  789. x: target.x,
  790. y: target.y,
  791. backendNodeId: target.backendNodeId,
  792. });
  793. } catch (error) {
  794. if (isBrowserOperationInterruption(error)) throw error;
  795. if (session.generation !== beforeGeneration) {
  796. return unexpectedNavigation(inputDispatched);
  797. }
  798. throw error;
  799. }
  800. } else {
  801. await cdp(session, 'DOM.focus', { backendNodeId: target.backendNodeId });
  802. }
  803. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  804. if (input.clear === true) {
  805. inputDispatched = true;
  806. await session.cdpHelper.selectAllAtCurrentFocus({
  807. ...(session.commandSignal ? { signal: session.commandSignal } : {}),
  808. ...(session.commandTimeoutMs ? { timeoutMs: session.commandTimeoutMs } : {}),
  809. });
  810. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  811. await this.dispatchKey(session, 'Backspace', []);
  812. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  813. }
  814. if (target.virtualEditor === true) {
  815. for (const char of text) {
  816. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  817. inputDispatched = true;
  818. await this.dispatchVirtualEditorCharacter(session, char);
  819. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  820. if (delayMs > 0) {
  821. await delay(delayMs, session.commandSignal);
  822. if (session.generation !== beforeGeneration) {
  823. return unexpectedNavigation(inputDispatched);
  824. }
  825. }
  826. }
  827. } else {
  828. inputDispatched =
  829. (await this.insertText(session, text, delayMs, beforeGeneration)) || inputDispatched;
  830. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  831. }
  832. await delay(ACTION_SETTLE_DELAY_MS, session.commandSignal);
  833. const clear = input.clear === true;
  834. const samples: Array<CDPEditableState | CDPRenderedState> = [];
  835. try {
  836. const sampleCount = clear ? VERIFIED_FILL_SAMPLE_COUNT : 1;
  837. for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex += 1) {
  838. if (sampleIndex > 0) {
  839. await delay(VERIFIED_FILL_SAMPLE_DELAY_MS, session.commandSignal);
  840. if (session.generation !== beforeGeneration) {
  841. return unexpectedNavigation(inputDispatched);
  842. }
  843. }
  844. samples.push(await inspectTextState(text));
  845. }
  846. } catch (error) {
  847. if (isBrowserOperationInterruption(error)) throw error;
  848. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  849. throw error;
  850. }
  851. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  852. const after = samples[samples.length - 1];
  853. const previous = samples[samples.length - 2];
  854. if (!after) throw new Error('Browser input verification did not produce a final sample.');
  855. const changed = after.fingerprint !== before.fingerprint;
  856. const matchesExpected = clear
  857. ? previous?.matchesExpected === true &&
  858. after.matchesExpected === true &&
  859. previous.fingerprint === after.fingerprint
  860. : undefined;
  861. const containsExpected = clear
  862. ? undefined
  863. : text.length === 0 || (changed && after.containsExpected === true);
  864. let focused = 'focused' in after ? after.focused === true : false;
  865. if (target.virtualEditor === true) {
  866. const focusedState = await session.cdpHelper.inspectFocusedEditableStateByBackendNodeId(
  867. target.backendNodeId,
  868. inspectionOptions,
  869. );
  870. if (session.generation !== beforeGeneration) return unexpectedNavigation(inputDispatched);
  871. focused =
  872. focusedState.editable === true &&
  873. focusedState.focused === true &&
  874. focusedState.withinTarget === true;
  875. }
  876. const verified =
  877. target.virtualEditor === true && !focused
  878. ? false
  879. : clear
  880. ? matchesExpected === true
  881. : containsExpected === true;
  882. const continuationRef = asString(input.ref);
  883. this.invalidateObservation(session);
  884. if (continuationRef) {
  885. session.keyboardContinuationTarget = {
  886. ref: continuationRef,
  887. backendNodeId: target.backendNodeId,
  888. ...(target.rect ? { rect: target.rect } : {}),
  889. ...(observedElement?.frameId ? { frameId: observedElement.frameId } : {}),
  890. ...(session.commandSessionId ? { commandSessionId: session.commandSessionId } : {}),
  891. };
  892. }
  893. const result = {
  894. success: verified,
  895. durationMs: Date.now() - startedAt,
  896. target: targetMetadata,
  897. effect: {
  898. dispatched: true,
  899. verified,
  900. verificationRequired: true,
  901. focused,
  902. expectedTextLength: text.length,
  903. textLength: after.textLength,
  904. textChanged: changed,
  905. ...(clear ? { matchesExpected } : {}),
  906. ...(!clear ? { containsExpected } : {}),
  907. },
  908. navigation: { detected: false, generation: session.generation },
  909. } as Record<string, unknown>;
  910. if (!verified) {
  911. const virtualEditor = target.virtualEditor === true;
  912. const code =
  913. virtualEditor && !focused
  914. ? 'INPUT_FOCUS_REJECTED'
  915. : clear
  916. ? virtualEditor
  917. ? changed
  918. ? 'INPUT_PARTIAL_EFFECT'
  919. : 'INPUT_EVENT_NOT_CONSUMED'
  920. : 'ACTION_EFFECT_MISMATCH'
  921. : changed
  922. ? 'INPUT_PARTIAL_EFFECT'
  923. : virtualEditor
  924. ? 'INPUT_EVENT_NOT_CONSUMED'
  925. : 'ACTION_EFFECT_NOT_OBSERVED';
  926. const error =
  927. code === 'INPUT_FOCUS_REJECTED'
  928. ? 'The visible editor host no longer owns the current editable focus.'
  929. : clear
  930. ? 'The editable target does not contain the exact requested value after filling.'
  931. : changed
  932. ? 'The editable target does not contain the complete requested text after typing.'
  933. : 'The editable target did not change after typing.';
  934. result.code = code;
  935. result.error = error;
  936. result.message = error;
  937. result.retryable = true;
  938. result.recovery =
  939. code === 'INPUT_FOCUS_REJECTED'
  940. ? 'Inspect the page again and choose the current visible editor ref.'
  941. : 'Inspect the page and retry with the current editable ref.';
  942. }
  943. return result;
  944. }
  945. private async insertText(
  946. session: SessionState,
  947. text: string,
  948. delayMs: number,
  949. expectedGeneration: number,
  950. ): Promise<boolean> {
  951. let dispatched = false;
  952. if (session.generation !== expectedGeneration) return dispatched;
  953. if (delayMs > 0) {
  954. for (const char of text) {
  955. if (session.generation !== expectedGeneration) return dispatched;
  956. await cdp(session, 'Input.insertText', { text: char });
  957. dispatched = true;
  958. if (session.generation !== expectedGeneration) return dispatched;
  959. await delay(delayMs, session.commandSignal);
  960. if (session.generation !== expectedGeneration) return dispatched;
  961. }
  962. return dispatched;
  963. }
  964. await cdp(session, 'Input.insertText', { text });
  965. return true;
  966. }
  967. private async dispatchVirtualEditorCharacter(session: SessionState, char: string): Promise<void> {
  968. const key = browserPrintableKeyDescriptor(char);
  969. if (!key) {
  970. await cdp(session, 'Input.insertText', { text: char });
  971. return;
  972. }
  973. await cdp(session, 'Input.dispatchKeyEvent', {
  974. type: 'keyDown',
  975. key: key.key,
  976. code: key.code,
  977. windowsVirtualKeyCode: key.windowsVirtualKeyCode,
  978. modifiers: key.modifiers,
  979. });
  980. await cdp(session, 'Input.dispatchKeyEvent', {
  981. type: 'char',
  982. key: key.key,
  983. text: char,
  984. unmodifiedText: char,
  985. });
  986. await cdp(session, 'Input.dispatchKeyEvent', {
  987. type: 'keyUp',
  988. key: key.key,
  989. code: key.code,
  990. windowsVirtualKeyCode: key.windowsVirtualKeyCode,
  991. modifiers: key.modifiers,
  992. });
  993. }
  994. private async activateVirtualEditor(
  995. session: SessionState,
  996. target: {
  997. x: number;
  998. y: number;
  999. backendNodeId: number;
  1000. },
  1001. ): Promise<void> {
  1002. await this.dispatchMouse(session, target.x, target.y, 'mouseMoved');
  1003. await delay(50, session.commandSignal);
  1004. await this.dispatchMouse(session, target.x, target.y, 'mousePressed', {
  1005. button: 'left',
  1006. clickCount: 1,
  1007. });
  1008. await delay(50, session.commandSignal);
  1009. await this.dispatchMouse(session, target.x, target.y, 'mouseReleased', {
  1010. button: 'left',
  1011. clickCount: 1,
  1012. });
  1013. await delay(50, session.commandSignal);
  1014. const resolved = await cdp<{ object?: { objectId?: string } }>(session, 'DOM.resolveNode', {
  1015. backendNodeId: target.backendNodeId,
  1016. });
  1017. const objectId = resolved.object?.objectId;
  1018. if (!objectId) throw new Error('INPUT_FOCUS_REJECTED: editor host was not resolved');
  1019. try {
  1020. const focused = await cdp<{
  1021. result?: { value?: { focused?: boolean; editable?: boolean; withinTarget?: boolean } };
  1022. exceptionDetails?: { text?: string };
  1023. }>(session, 'Runtime.callFunctionOn', {
  1024. objectId,
  1025. functionDeclaration: `function () {
  1026. let active = this.ownerDocument?.activeElement || null;
  1027. while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
  1028. const tag = String(active?.tagName || '').toLowerCase();
  1029. const role = String(active?.getAttribute?.('role') || '').toLowerCase();
  1030. const inputType = active instanceof HTMLInputElement
  1031. ? String(active.type || '').toLowerCase()
  1032. : '';
  1033. const editableInput = active instanceof HTMLInputElement && ![
  1034. 'button', 'checkbox', 'file', 'hidden', 'image', 'radio', 'reset', 'submit'
  1035. ].includes(inputType);
  1036. const editable = editableInput || active instanceof HTMLTextAreaElement ||
  1037. active?.isContentEditable === true || role === 'textbox' || role === 'searchbox';
  1038. let withinTarget = false;
  1039. let cursor = active;
  1040. while (cursor) {
  1041. if (cursor === this) {
  1042. withinTarget = true;
  1043. break;
  1044. }
  1045. cursor = cursor.parentNode || cursor.getRootNode?.()?.host || null;
  1046. }
  1047. return { focused: Boolean(active), editable, withinTarget };
  1048. }`,
  1049. returnByValue: true,
  1050. awaitPromise: true,
  1051. });
  1052. if (focused.exceptionDetails) {
  1053. throw new Error(focused.exceptionDetails.text || 'INPUT_FOCUS_REJECTED');
  1054. }
  1055. const state = focused.result?.value;
  1056. if (!state?.focused || !state.editable || !state.withinTarget) {
  1057. throw new Error(
  1058. 'INPUT_FOCUS_REJECTED: activating the editor host did not focus its editable proxy',
  1059. );
  1060. }
  1061. } finally {
  1062. await cdp(session, 'Runtime.releaseObject', { objectId }).catch(() => undefined);
  1063. }
  1064. }
  1065. protected async pressKey(
  1066. session: SessionState,
  1067. input: Record<string, unknown>,
  1068. ): Promise<unknown> {
  1069. const startedAt = Date.now();
  1070. const ref = asString(input.ref);
  1071. const hasTarget = Boolean(ref || asString(input.selector));
  1072. const continuation =
  1073. ref &&
  1074. !session.elementMap.hasOpaqueRef(ref) &&
  1075. session.keyboardContinuationTarget?.ref === ref
  1076. ? session.keyboardContinuationTarget
  1077. : undefined;
  1078. session.keyboardContinuationTarget = undefined;
  1079. const target =
  1080. continuation ??
  1081. (hasTarget ? await this.resolveTarget(session, input, true, false) : undefined);
  1082. if (target && target.backendNodeId === undefined) {
  1083. throw new Error('PRESS_KEY_TARGET_NOT_RESOLVED');
  1084. }
  1085. if (target?.backendNodeId !== undefined) {
  1086. session.commandSessionId = target.commandSessionId;
  1087. await cdp(session, 'DOM.focus', { backendNodeId: target.backendNodeId });
  1088. }
  1089. await this.dispatchKey(session, asString(input.key), stringArray(input.modifiers));
  1090. await delay(ACTION_SETTLE_DELAY_MS, session.commandSignal);
  1091. this.invalidateObservation(session);
  1092. return {
  1093. success: true,
  1094. durationMs: Date.now() - startedAt,
  1095. ...(target ? { target: { resolved: true, rect: target.rect } } : {}),
  1096. effect: { dispatched: true },
  1097. };
  1098. }
  1099. private async inspectScrollSnapshot(
  1100. session: SessionState,
  1101. point: { x: number; y: number } | null,
  1102. axis: 'x' | 'y',
  1103. ): Promise<BrowserScrollSnapshot | null> {
  1104. const command = { point, axis };
  1105. const raw = await evaluate<unknown>(
  1106. session,
  1107. `(() => {
  1108. const command = ${JSON.stringify(command)};
  1109. const documentScroller = document.scrollingElement || document.documentElement;
  1110. const ownerRegistryKey = Symbol.for('mavis.browser.scroll-owner-registry');
  1111. const ownerRegistry = globalThis[ownerRegistryKey] ||
  1112. (globalThis[ownerRegistryKey] = { nextId: 1, ids: new WeakMap() });
  1113. const ownerId = (element) => {
  1114. if (element === documentScroller) return 'document';
  1115. let id = ownerRegistry.ids.get(element);
  1116. if (!id) {
  1117. id = 'element:' + ownerRegistry.nextId++;
  1118. ownerRegistry.ids.set(element, id);
  1119. }
  1120. return id;
  1121. };
  1122. const isScrollable = (element) => {
  1123. if (!(element instanceof Element)) return false;
  1124. const style = getComputedStyle(element);
  1125. const overflow = command.axis === 'y' ? style.overflowY : style.overflowX;
  1126. const allowsUserScroll = overflow === 'auto' || overflow === 'scroll' || overflow === 'overlay';
  1127. const hasOverflow = command.axis === 'y'
  1128. ? element.scrollHeight > element.clientHeight + ${SCROLL_BOUNDARY_EPSILON}
  1129. : element.scrollWidth > element.clientWidth + ${SCROLL_BOUNDARY_EPSILON};
  1130. return allowsUserScroll && hasOverflow;
  1131. };
  1132. const resolveScrollTarget = (point) => {
  1133. let element = point ? document.elementFromPoint(point.x, point.y) : documentScroller;
  1134. if (element instanceof HTMLIFrameElement) return null;
  1135. if (point) {
  1136. while (element && element !== documentScroller && !isScrollable(element)) {
  1137. element = element.parentElement;
  1138. }
  1139. }
  1140. if (!element || (element !== documentScroller && !isScrollable(element))) {
  1141. element = documentScroller;
  1142. }
  1143. return element || null;
  1144. };
  1145. const element = resolveScrollTarget(command.point);
  1146. if (!element) {
  1147. return {
  1148. ownerId: 'unknown',
  1149. kind: 'unknown',
  1150. scrollable: false,
  1151. scrollTop: 0,
  1152. scrollLeft: 0,
  1153. scrollHeight: 0,
  1154. scrollWidth: 0,
  1155. clientHeight: 0,
  1156. clientWidth: 0,
  1157. };
  1158. }
  1159. const hasScrollableExtent = command.axis === 'y'
  1160. ? element.scrollHeight > element.clientHeight + ${SCROLL_BOUNDARY_EPSILON}
  1161. : element.scrollWidth > element.clientWidth + ${SCROLL_BOUNDARY_EPSILON};
  1162. return {
  1163. ownerId: ownerId(element),
  1164. kind: element === documentScroller ? 'document' : 'element',
  1165. scrollable: element === documentScroller ? hasScrollableExtent : isScrollable(element),
  1166. scrollTop: Number(element.scrollTop || 0),
  1167. scrollLeft: Number(element.scrollLeft || 0),
  1168. scrollHeight: Number(element.scrollHeight || 0),
  1169. scrollWidth: Number(element.scrollWidth || 0),
  1170. clientHeight: Number(element.clientHeight || 0),
  1171. clientWidth: Number(element.clientWidth || 0),
  1172. };
  1173. })()`,
  1174. );
  1175. return normalizeScrollSnapshot(raw, axis);
  1176. }
  1177. protected async scroll(session: SessionState, input: Record<string, unknown>): Promise<unknown> {
  1178. const direction = asString(input.direction, 'down');
  1179. const axis = direction === 'left' || direction === 'right' ? 'x' : 'y';
  1180. const viewport = await this.readCssViewport(session);
  1181. const distance = Math.max(1, asNumber(input.distance, Math.round(viewport.height * 0.8)));
  1182. const deltaX = direction === 'left' ? -distance : direction === 'right' ? distance : 0;
  1183. const deltaY = direction === 'up' ? -distance : direction === 'down' ? distance : 0;
  1184. const hasExplicitTarget = ['ref', 'selector', 'position', 'normalized_position'].some((key) =>
  1185. Object.prototype.hasOwnProperty.call(input, key),
  1186. );
  1187. const target = hasExplicitTarget ? await this.resolveTarget(session, input, false) : undefined;
  1188. if (
  1189. target &&
  1190. (!Number.isFinite(target.x) ||
  1191. !Number.isFinite(target.y) ||
  1192. target.x < 0 ||
  1193. target.y < 0 ||
  1194. target.x > viewport.width ||
  1195. target.y > viewport.height)
  1196. ) {
  1197. return {
  1198. success: false,
  1199. code: 'NO_SCROLL_EFFECT',
  1200. error: 'Scroll target is outside the current viewport.',
  1201. retryable: true,
  1202. recovery:
  1203. 'Inspect the current viewport and choose a visible scroll container, ref, selector, or normalized position.',
  1204. effect: {
  1205. observed: false,
  1206. moved: false,
  1207. actualDeltaX: 0,
  1208. actualDeltaY: 0,
  1209. atStart: false,
  1210. atEnd: false,
  1211. },
  1212. };
  1213. }
  1214. const observationPoint = target
  1215. ? { x: target.contextX ?? target.x, y: target.contextY ?? target.y }
  1216. : null;
  1217. const before = await this.inspectScrollSnapshot(session, observationPoint, axis);
  1218. const beforeObserved = before !== null && before.kind !== 'unknown';
  1219. const beforePosition = axis === 'y' ? (before?.scrollTop ?? 0) : (before?.scrollLeft ?? 0);
  1220. const beforeExtent = axis === 'y' ? (before?.scrollHeight ?? 0) : (before?.scrollWidth ?? 0);
  1221. const beforeViewport = axis === 'y' ? (before?.clientHeight ?? 0) : (before?.clientWidth ?? 0);
  1222. const beforeAtRequestedBoundary =
  1223. beforeObserved &&
  1224. Boolean(before?.scrollable) &&
  1225. (direction === 'down' || direction === 'right'
  1226. ? beforePosition + beforeViewport >= beforeExtent - SCROLL_BOUNDARY_EPSILON
  1227. : beforePosition <= SCROLL_BOUNDARY_EPSILON);
  1228. let after = before;
  1229. let usedUnobservedWheelFallback = false;
  1230. if (!beforeAtRequestedBoundary) {
  1231. if (target) {
  1232. usedUnobservedWheelFallback =
  1233. before?.kind === 'unknown' || (beforeObserved && !before?.scrollable);
  1234. await session.beforePointerAction?.(
  1235. { action: 'scroll', point: { x: target.x, y: target.y } },
  1236. session.commandSignal,
  1237. );
  1238. await this.dispatchMouse(session, target.x, target.y, 'mouseMoved');
  1239. await this.dispatchMouse(session, target.x, target.y, 'mouseWheel', { deltaX, deltaY });
  1240. } else {
  1241. // An untargeted scroll owns the document contract. Dispatching a wheel
  1242. // at the viewport center can instead move an unrelated nested
  1243. // container, so use the document scrolling primitive just like the
  1244. // mature Electron path.
  1245. await evaluate(session, `window.scrollBy(${deltaX}, ${deltaY})`);
  1246. }
  1247. await delay(ACTION_SETTLE_DELAY_MS, session.commandSignal);
  1248. after = await this.inspectScrollSnapshot(session, observationPoint, axis);
  1249. }
  1250. const observed =
  1251. before !== null &&
  1252. after !== null &&
  1253. !usedUnobservedWheelFallback &&
  1254. before.kind !== 'unknown' &&
  1255. before.ownerId === after.ownerId;
  1256. const actualDeltaX = observed && before && after ? after.scrollLeft - before.scrollLeft : 0;
  1257. const actualDeltaY = observed && before && after ? after.scrollTop - before.scrollTop : 0;
  1258. const moved =
  1259. observed &&
  1260. ((deltaX !== 0 &&
  1261. Math.sign(actualDeltaX) === Math.sign(deltaX) &&
  1262. Math.abs(actualDeltaX) >= SCROLL_BOUNDARY_EPSILON) ||
  1263. (deltaY !== 0 &&
  1264. Math.sign(actualDeltaY) === Math.sign(deltaY) &&
  1265. Math.abs(actualDeltaY) >= SCROLL_BOUNDARY_EPSILON));
  1266. const finalSnapshot = after ?? before;
  1267. const relevantPosition =
  1268. axis === 'y' ? (finalSnapshot?.scrollTop ?? 0) : (finalSnapshot?.scrollLeft ?? 0);
  1269. const relevantExtent =
  1270. axis === 'y' ? (finalSnapshot?.scrollHeight ?? 0) : (finalSnapshot?.scrollWidth ?? 0);
  1271. const relevantViewport =
  1272. axis === 'y' ? (finalSnapshot?.clientHeight ?? 0) : (finalSnapshot?.clientWidth ?? 0);
  1273. // Keep the existing public effect semantics: only the boundary in the
  1274. // requested direction is reported by this action result.
  1275. const atStart =
  1276. observed &&
  1277. (direction === 'up' || direction === 'left') &&
  1278. relevantPosition <= SCROLL_BOUNDARY_EPSILON;
  1279. const atEnd =
  1280. observed &&
  1281. (direction === 'down' || direction === 'right') &&
  1282. relevantPosition + relevantViewport >= relevantExtent - SCROLL_BOUNDARY_EPSILON;
  1283. const requestedBoundaryReached = direction === 'up' || direction === 'left' ? atStart : atEnd;
  1284. this.invalidateObservation(session);
  1285. const effect = { observed, moved, actualDeltaX, actualDeltaY, atStart, atEnd };
  1286. if (!observed) {
  1287. return {
  1288. success: false,
  1289. code: 'SCROLL_EFFECT_UNVERIFIED',
  1290. error: 'Scroll input was dispatched, but its page effect could not be verified.',
  1291. retryable: true,
  1292. recovery:
  1293. 'Inspect the page once and choose a newly observed scroll target or confirm the intended state before continuing.',
  1294. effect,
  1295. };
  1296. }
  1297. const finalExplicitTargetIsNotScrollable = target !== undefined && !finalSnapshot?.scrollable;
  1298. if (!moved && (finalExplicitTargetIsNotScrollable || !requestedBoundaryReached)) {
  1299. return {
  1300. success: false,
  1301. code: 'NO_SCROLL_EFFECT',
  1302. error: 'Scroll action produced no observable movement.',
  1303. retryable: true,
  1304. recovery:
  1305. 'Inspect the page and choose a different scroll target, selector, ref, or normalized position.',
  1306. effect,
  1307. };
  1308. }
  1309. return {
  1310. success: true,
  1311. effect,
  1312. };
  1313. }
  1314. protected async waitFor(session: SessionState, input: Record<string, unknown>): Promise<unknown> {
  1315. const kind = asString(input.kind);
  1316. const timeoutMs = Math.max(0, Math.floor(asNumber(input.timeout, DEFAULT_WAIT_TIMEOUT_MS)));
  1317. if (kind === 'timeout') {
  1318. await delay(timeoutMs, session.commandSignal);
  1319. return { success: true, kind: 'timeout', waitedMs: timeoutMs };
  1320. }
  1321. const selector = asString(input.selector);
  1322. const text = asString(input.text);
  1323. const url = asString(input.url);
  1324. const load = input.load === true || kind === 'load';
  1325. if (kind === 'selector' && !selector) {
  1326. throw new Error('WAIT_REQUIRES_SELECTOR');
  1327. }
  1328. if (kind === 'text' && !text) throw new Error('WAIT_REQUIRES_TEXT');
  1329. if (kind === 'url' && !url) throw new Error('WAIT_REQUIRES_URL');
  1330. if (!selector && !text && !url && !load) throw new Error('WAIT_REQUIRES_CONDITION');
  1331. const deadline = Date.now() + timeoutMs;
  1332. while (Date.now() <= deadline) {
  1333. const matches = await evaluate<boolean>(session, waitExpression(input));
  1334. if (matches)
  1335. return { success: true, waitedMs: timeoutMs - Math.max(0, deadline - Date.now()) };
  1336. await delay(50, session.commandSignal);
  1337. }
  1338. return { success: false, code: 'ACTION_TIMEOUT', error: 'Browser wait condition timed out.' };
  1339. }
  1340. protected async screenshot(
  1341. session: SessionState,
  1342. input: Record<string, unknown>,
  1343. ): Promise<unknown> {
  1344. if (session.captureScreenshot) {
  1345. if (!session.commandSignal || session.commandTimeoutMs === undefined) {
  1346. throw new Error('SCREENSHOT_CAPTURE_CONTEXT_UNAVAILABLE');
  1347. }
  1348. return session.captureScreenshot(input, {
  1349. signal: session.commandSignal,
  1350. timeoutMs: session.commandTimeoutMs,
  1351. });
  1352. }
  1353. return captureBrowserScreenshot(session, input, () => this.readPageSummary(session));
  1354. }
  1355. }
  1356. function isSupportedBrowserUrl(url: string): boolean {
  1357. return /^(?:https?|file|data|about):/iu.test(url.trim());
  1358. }