browser-action-targets.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import { DEFAULT_BROWSER_VIEWPORT } from './browser-constants.js';
  2. import { modifierBit } from './browser-action-helpers.js';
  3. import { browserKeyDescriptor } from './browser-keyboard.js';
  4. import { BrowserQuerySupport } from './browser-query.js';
  5. import { isBrowserOperationInterruption } from './operation-timeout.js';
  6. import {
  7. asString,
  8. cdp,
  9. clearBrowserSnapshots,
  10. evaluate,
  11. inputCoordinate,
  12. inputCoordinateScale,
  13. invalidateBrowserObservations,
  14. isRecord,
  15. resolveBrowserSnapshotElement,
  16. type PageSummary,
  17. type Rect,
  18. type BrowserSessionState as SessionState,
  19. } from './browser-state.js';
  20. export abstract class BrowserActionTargetSupport extends BrowserQuerySupport {
  21. protected async resolveTarget(
  22. session: SessionState,
  23. input: Record<string, unknown>,
  24. scrollIntoView = true,
  25. requireCoordinates = true,
  26. ): Promise<{
  27. x: number;
  28. y: number;
  29. contextX?: number;
  30. contextY?: number;
  31. rect?: Rect;
  32. backendNodeId?: number;
  33. virtualEditor?: boolean;
  34. commandSessionId?: string;
  35. coordinateSpace?: 'main-frame-viewport' | 'frame-local' | 'unavailable';
  36. }> {
  37. const ref = asString(input.ref);
  38. if (ref) {
  39. const allowFixtureFallback = session.snapshotAuthorityEstablished !== true;
  40. const retained = resolveBrowserSnapshotElement(session, ref);
  41. // Production refs are owned by retained snapshots so TTL/generation
  42. // checks cannot be bypassed by the legacy ElementMap mirror. The narrow
  43. // no-snapshot fallback keeps white-box provider fixtures compatible.
  44. const element =
  45. retained?.element ??
  46. (allowFixtureFallback ? session.elementMap.getElementByOpaqueRef(ref) : null);
  47. if (!element)
  48. throw new Error('STALE_ELEMENT_REF: element ref is not from the current inspect snapshot');
  49. const elementSnapshot = retained?.snapshot ?? session.snapshot;
  50. const requestedFrame = asString(input.frame);
  51. if (requestedFrame) {
  52. const expectedFrame = elementSnapshot?.frameRefs?.get(element.frameId ?? 'main');
  53. if (!expectedFrame || requestedFrame !== expectedFrame) {
  54. throw new Error(
  55. 'STALE_ELEMENT_REF: element frame no longer matches the inspect snapshot',
  56. );
  57. }
  58. }
  59. if (requireCoordinates && element.coordinateSpace === 'unavailable') {
  60. throw new Error(
  61. 'FRAME_COORDINATES_UNAVAILABLE: the inspected frame cannot be addressed safely by viewport coordinates',
  62. );
  63. }
  64. session.commandSessionId = element.commandSessionId;
  65. const viewport = elementSnapshot?.page.viewport ?? DEFAULT_BROWSER_VIEWPORT;
  66. const fullyVisible =
  67. element.rect.x >= 0 &&
  68. element.rect.y >= 0 &&
  69. element.rect.x + element.rect.width <= viewport.width &&
  70. element.rect.y + element.rect.height <= viewport.height;
  71. if (scrollIntoView && !fullyVisible) {
  72. await cdp(session, 'DOM.scrollIntoViewIfNeeded', { backendNodeId: element.backendNodeId });
  73. await this.centerBackendNodeInView(session, element.backendNodeId);
  74. }
  75. const measuredRect = await this.readBox(session, element.backendNodeId).catch((error) => {
  76. if (isBrowserOperationInterruption(error)) throw error;
  77. return undefined;
  78. });
  79. if (!measuredRect && requireCoordinates) {
  80. throw new Error(
  81. element.commandSessionId
  82. ? 'FRAME_COORDINATES_UNAVAILABLE: the inspected frame target could not be measured safely in the current page'
  83. : 'STALE_ELEMENT_REF: inspected target no longer has a live box in the current page',
  84. );
  85. }
  86. const frameOffset = element.frameOffset ?? { x: 0, y: 0 };
  87. const localRect =
  88. measuredRect && measuredRect.width > 0 && measuredRect.height > 0
  89. ? measuredRect
  90. : {
  91. ...element.rect,
  92. x: element.rect.x - frameOffset.x,
  93. y: element.rect.y - frameOffset.y,
  94. };
  95. const rect = {
  96. ...localRect,
  97. x: localRect.x + frameOffset.x,
  98. y: localRect.y + frameOffset.y,
  99. };
  100. return {
  101. x: rect.x + rect.width / 2,
  102. y: rect.y + rect.height / 2,
  103. contextX: localRect.x + localRect.width / 2,
  104. contextY: localRect.y + localRect.height / 2,
  105. rect,
  106. backendNodeId: element.backendNodeId,
  107. virtualEditor: element.virtualEditor,
  108. ...(element.coordinateSpace ? { coordinateSpace: element.coordinateSpace } : {}),
  109. ...(element.commandSessionId ? { commandSessionId: element.commandSessionId } : {}),
  110. };
  111. }
  112. const selector = asString(input.selector);
  113. if (selector) {
  114. const rect = await evaluate<Rect | null>(
  115. session,
  116. `(() => {
  117. const element = document.querySelector(${JSON.stringify(selector)});
  118. if (!element) return null;
  119. let r = element.getBoundingClientRect();
  120. const fullyVisible = r.x >= 0 && r.y >= 0 &&
  121. r.x + r.width <= innerWidth && r.y + r.height <= innerHeight;
  122. if (${scrollIntoView ? 'true' : 'false'} && !fullyVisible) {
  123. element.scrollIntoView({ block: 'center', inline: 'center' });
  124. r = element.getBoundingClientRect();
  125. }
  126. return { x: r.x, y: r.y, width: r.width, height: r.height };
  127. })()`,
  128. );
  129. if (!rect) throw new Error('TARGET_NOT_FOUND: selector did not match an element');
  130. const backendNodeId = await this.resolveSelectorBackendNode(session, selector);
  131. return {
  132. x: rect.x + rect.width / 2,
  133. y: rect.y + rect.height / 2,
  134. rect,
  135. ...(backendNodeId === undefined ? {} : { backendNodeId }),
  136. };
  137. }
  138. const viewport = await this.readCssViewport(session);
  139. const position = resolveViewportPosition(input, viewport);
  140. return {
  141. x: position.x,
  142. y: position.y,
  143. rect: { x: position.x, y: position.y, width: 1, height: 1 },
  144. };
  145. }
  146. protected async readCssViewport(
  147. session: SessionState,
  148. ): Promise<{ width: number; height: number }> {
  149. try {
  150. return await session.cdpHelper.getCssViewportSize();
  151. } catch (error) {
  152. if (isBrowserOperationInterruption(error)) throw error;
  153. const viewport = session.snapshot?.page.viewport;
  154. if (
  155. viewport &&
  156. Number.isFinite(viewport.width) &&
  157. Number.isFinite(viewport.height) &&
  158. viewport.width > 0 &&
  159. viewport.height > 0
  160. ) {
  161. return viewport;
  162. }
  163. throw new Error('VIEWPORT_UNAVAILABLE: current CSS viewport metrics are unavailable');
  164. }
  165. }
  166. private async resolveSelectorBackendNode(
  167. session: SessionState,
  168. selector: string,
  169. ): Promise<number | undefined> {
  170. const document = await cdp<{ root?: { nodeId?: number } }>(session, 'DOM.getDocument', {
  171. depth: 0,
  172. pierce: true,
  173. });
  174. const rootNodeId = document.root?.nodeId;
  175. if (rootNodeId === undefined) return undefined;
  176. const match = await cdp<{ nodeId?: number }>(session, 'DOM.querySelector', {
  177. nodeId: rootNodeId,
  178. selector,
  179. });
  180. if (match.nodeId === undefined || match.nodeId === 0) return undefined;
  181. const described = await cdp<{ node?: { backendNodeId?: number } }>(
  182. session,
  183. 'DOM.describeNode',
  184. { nodeId: match.nodeId },
  185. );
  186. return described.node?.backendNodeId;
  187. }
  188. private async centerBackendNodeInView(
  189. session: SessionState,
  190. backendNodeId: number,
  191. ): Promise<void> {
  192. const resolved = await cdp<{ object?: { objectId?: string } }>(session, 'DOM.resolveNode', {
  193. backendNodeId,
  194. });
  195. const objectId = resolved.object?.objectId;
  196. if (!objectId) return;
  197. try {
  198. await cdp(session, 'Runtime.callFunctionOn', {
  199. objectId,
  200. functionDeclaration: `function () {
  201. this.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'center' });
  202. }`,
  203. returnByValue: true,
  204. awaitPromise: true,
  205. });
  206. } finally {
  207. await cdp(session, 'Runtime.releaseObject', { objectId }).catch(() => undefined);
  208. }
  209. }
  210. protected async dispatchMouse(
  211. session: SessionState,
  212. x: number,
  213. y: number,
  214. type: 'mouseMoved' | 'mousePressed' | 'mouseReleased' | 'mouseWheel',
  215. extra: Record<string, unknown> = {},
  216. ): Promise<void> {
  217. const point = inputCoordinate(session, { x, y });
  218. const scale = inputCoordinateScale(session);
  219. const scaledExtra =
  220. type === 'mouseWheel'
  221. ? {
  222. ...extra,
  223. ...(typeof extra.deltaX === 'number' ? { deltaX: extra.deltaX * scale } : {}),
  224. ...(typeof extra.deltaY === 'number' ? { deltaY: extra.deltaY * scale } : {}),
  225. }
  226. : extra;
  227. await session.transport.send(
  228. 'Input.dispatchMouseEvent',
  229. { type, ...point, ...scaledExtra },
  230. undefined,
  231. {
  232. ...(session.commandSignal ? { signal: session.commandSignal } : {}),
  233. ...(session.commandTimeoutMs ? { timeoutMs: session.commandTimeoutMs } : {}),
  234. },
  235. );
  236. }
  237. protected async dispatchKey(
  238. session: SessionState,
  239. key: string,
  240. modifiers: string[],
  241. ): Promise<void> {
  242. const modifierMask = modifiers.reduce((mask, modifier) => mask | modifierBit(modifier), 0);
  243. const descriptor = browserKeyDescriptor(key);
  244. await cdp(session, 'Input.dispatchKeyEvent', {
  245. type: 'keyDown',
  246. key: descriptor.key,
  247. code: descriptor.code,
  248. modifiers: modifierMask,
  249. ...(descriptor.windowsVirtualKeyCode === undefined
  250. ? {}
  251. : { windowsVirtualKeyCode: descriptor.windowsVirtualKeyCode }),
  252. ...(descriptor.text === undefined || modifierMask !== 0
  253. ? {}
  254. : { text: descriptor.text, unmodifiedText: descriptor.text }),
  255. });
  256. await cdp(session, 'Input.dispatchKeyEvent', {
  257. type: 'keyUp',
  258. key: descriptor.key,
  259. code: descriptor.code,
  260. modifiers: modifierMask,
  261. ...(descriptor.windowsVirtualKeyCode === undefined
  262. ? {}
  263. : { windowsVirtualKeyCode: descriptor.windowsVirtualKeyCode }),
  264. });
  265. }
  266. protected async readBox(session: SessionState, backendNodeId: number): Promise<Rect> {
  267. const result = await cdp<{
  268. model?: { border?: number[]; content?: number[]; width?: number; height?: number };
  269. }>(session, 'DOM.getBoxModel', { backendNodeId });
  270. const quad = result.model?.border ?? result.model?.content;
  271. if (!quad || quad.length < 8) throw new Error('Element box unavailable');
  272. const xs = [quad[0], quad[2], quad[4], quad[6]];
  273. const ys = [quad[1], quad[3], quad[5], quad[7]];
  274. if ([...xs, ...ys].some((value) => typeof value !== 'number')) {
  275. throw new Error('Element box has invalid coordinates');
  276. }
  277. const numericXs = xs as number[];
  278. const numericYs = ys as number[];
  279. const x = Math.min(...numericXs);
  280. const y = Math.min(...numericYs);
  281. return {
  282. x,
  283. y,
  284. width: Math.max(...numericXs) - x,
  285. height: Math.max(...numericYs) - y,
  286. };
  287. }
  288. protected async readPageSummary(session: SessionState): Promise<PageSummary> {
  289. return session.transport.evaluate<PageSummary>(
  290. `(() => {
  291. const root = document.scrollingElement || document.documentElement;
  292. return {
  293. url: location.href,
  294. title: document.title,
  295. viewport: { width: innerWidth, height: innerHeight },
  296. scrollPosition: { x: root?.scrollLeft || 0, y: root?.scrollTop || 0 },
  297. pageHeight: Math.max(root?.scrollHeight || 0, document.body?.scrollHeight || 0),
  298. pageWidth: Math.max(root?.scrollWidth || 0, document.body?.scrollWidth || 0),
  299. };
  300. })()`,
  301. {
  302. ...(session.commandSignal ? { signal: session.commandSignal } : {}),
  303. ...(session.commandTimeoutMs ? { timeoutMs: session.commandTimeoutMs } : {}),
  304. },
  305. );
  306. }
  307. protected async readFocusedText(session: SessionState, virtualEditor = false): Promise<string> {
  308. return evaluate<string>(
  309. session,
  310. `(() => {
  311. const element = document.activeElement;
  312. if (!element) return '';
  313. if (${virtualEditor ? 'true' : 'false'}) {
  314. const editor = element.closest('.dcg-mq-editable-field');
  315. if (editor) return String(editor.textContent || editor.innerText || '').trim();
  316. }
  317. if ('value' in element) return String(element.value || '');
  318. return String(element.textContent || '').trim();
  319. })()`,
  320. );
  321. }
  322. protected invalidate(session: SessionState): void {
  323. session.generation += 1;
  324. session.frameEpochs?.clear();
  325. session.elementMap.clearOpaqueRefs();
  326. clearBrowserSnapshots(session);
  327. session.keyboardContinuationTarget = undefined;
  328. }
  329. protected invalidateObservation(session: SessionState): void {
  330. invalidateBrowserObservations(session);
  331. }
  332. }
  333. export function resolveViewportPosition(
  334. input: Record<string, unknown>,
  335. viewport: { width: number; height: number },
  336. ): { x: number; y: number } {
  337. const absolute = readPoint(input.position);
  338. const normalized = readPoint(input.normalized_position);
  339. if (!absolute && !normalized) {
  340. throw new Error('Browser target requires ref, selector, position, or normalized_position');
  341. }
  342. let position: { x: number; y: number };
  343. if (absolute) {
  344. position = absolute;
  345. } else {
  346. if (!normalized) throw new Error('Browser target requires valid coordinates');
  347. position = {
  348. x: Math.round(normalized.x * viewport.width),
  349. y: Math.round(normalized.y * viewport.height),
  350. };
  351. }
  352. if (
  353. position.x < 0 ||
  354. position.y < 0 ||
  355. position.x >= viewport.width ||
  356. position.y >= viewport.height
  357. ) {
  358. throw new Error('POSITION_OUT_OF_VIEWPORT: position must be inside the current viewport');
  359. }
  360. return position;
  361. }
  362. function readPoint(value: unknown): { x: number; y: number } | undefined {
  363. if (!isRecord(value)) return undefined;
  364. const x = typeof value.x === 'number' && Number.isFinite(value.x) ? value.x : undefined;
  365. const y = typeof value.y === 'number' && Number.isFinite(value.y) ? value.y : undefined;
  366. return x === undefined || y === undefined ? undefined : { x, y };
  367. }