browser-extended-actions.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. import { BrowserActionSupport } from './browser-actions.js';
  2. import {
  3. asNumber,
  4. cdp,
  5. delay,
  6. stringArray,
  7. type BrowserSessionState as SessionState,
  8. } from './browser-state.js';
  9. import { IsolatedClipboardProvider, type ClipboardProvider } from './clipboard.js';
  10. const ACTION_SETTLE_DELAY_MS = 100;
  11. interface CheckableState {
  12. checkable: boolean;
  13. checked: boolean;
  14. }
  15. interface SelectMutationState {
  16. selectable: boolean;
  17. multiple: boolean;
  18. missingValues: string[];
  19. selectedValues: string[];
  20. }
  21. interface SelectState {
  22. selectable: boolean;
  23. multiple: boolean;
  24. selectedValues: string[];
  25. }
  26. export abstract class BrowserExtendedActionSupport extends BrowserActionSupport {
  27. protected readonly clipboardProvider: ClipboardProvider;
  28. protected constructor(clipboardProvider: ClipboardProvider = new IsolatedClipboardProvider()) {
  29. super();
  30. this.clipboardProvider = clipboardProvider;
  31. }
  32. protected async setChecked(
  33. session: SessionState,
  34. input: Record<string, unknown>,
  35. checked: boolean,
  36. ): Promise<unknown> {
  37. const startedAt = Date.now();
  38. const target = await this.resolveTarget(session, input, true, true);
  39. if (target.backendNodeId === undefined) throw new Error('CHECK_REQUIRES_ELEMENT_REF');
  40. const before = await this.callBackendNode<CheckableState>(
  41. session,
  42. target.backendNodeId,
  43. `function () {
  44. const type = this instanceof HTMLInputElement ? String(this.type || '').toLowerCase() : '';
  45. const checkable = type === 'checkbox' || type === 'radio';
  46. return { checkable, checked: checkable ? Boolean(this.checked) : false };
  47. }`,
  48. );
  49. if (!before?.checkable) {
  50. return {
  51. success: false,
  52. code: 'TARGET_NOT_CHECKABLE',
  53. error: 'Browser check target is not a checkbox or radio input.',
  54. durationMs: Date.now() - startedAt,
  55. target: { resolved: true, rect: target.rect },
  56. effect: { dispatched: false, verified: false },
  57. };
  58. }
  59. if (before.checked !== checked) {
  60. await session.beforePointerAction?.(
  61. { action: checked ? 'check' : 'uncheck', point: { x: target.x, y: target.y } },
  62. session.commandSignal,
  63. );
  64. await this.dispatchMouse(session, target.x, target.y, 'mouseMoved');
  65. await delay(50, session.commandSignal);
  66. await this.dispatchMouse(session, target.x, target.y, 'mousePressed', {
  67. button: 'left',
  68. clickCount: 1,
  69. });
  70. await this.dispatchMouse(session, target.x, target.y, 'mouseReleased', {
  71. button: 'left',
  72. clickCount: 1,
  73. });
  74. await delay(ACTION_SETTLE_DELAY_MS, session.commandSignal);
  75. }
  76. const after = await this.callBackendNode<CheckableState>(
  77. session,
  78. target.backendNodeId,
  79. `function () {
  80. const type = this instanceof HTMLInputElement ? String(this.type || '').toLowerCase() : '';
  81. const checkable = type === 'checkbox' || type === 'radio';
  82. return { checkable, checked: checkable ? Boolean(this.checked) : false };
  83. }`,
  84. );
  85. const dispatched = before.checked !== checked;
  86. const verified = after?.checkable === true && after.checked === checked;
  87. this.invalidateObservation(session);
  88. const result = {
  89. success: verified,
  90. durationMs: Date.now() - startedAt,
  91. target: { resolved: true, rect: target.rect },
  92. effect: { dispatched, verified, checked: after?.checked },
  93. } as Record<string, unknown>;
  94. if (!verified) {
  95. result.code = after?.checkable === false ? 'TARGET_NOT_CHECKABLE' : 'CHECK_STATE_NOT_APPLIED';
  96. result.error =
  97. after?.checkable === false
  98. ? 'Browser check target is no longer a checkbox or radio input.'
  99. : `Browser ${checked ? 'check' : 'uncheck'} was dispatched, but the requested state was not retained.`;
  100. result.recovery =
  101. 'Inspect the current target state before retrying; the page may reject or control this field.';
  102. }
  103. return result;
  104. }
  105. protected async selectOption(
  106. session: SessionState,
  107. input: Record<string, unknown>,
  108. ): Promise<unknown> {
  109. const startedAt = Date.now();
  110. const target = await this.resolveTarget(session, input, true, false);
  111. if (target.backendNodeId === undefined) throw new Error('SELECT_REQUIRES_ELEMENT_REF');
  112. const values = Array.from(new Set(stringArray(input.values)));
  113. if (values.length === 0) throw new Error('SELECT_REQUIRES_VALUES');
  114. const mutation = await this.callBackendNode<SelectMutationState>(
  115. session,
  116. target.backendNodeId,
  117. `function (wanted) {
  118. if (!(this instanceof HTMLSelectElement)) {
  119. return {
  120. selectable: false,
  121. multiple: false,
  122. missingValues: [],
  123. selectedValues: [],
  124. };
  125. }
  126. const values = Array.from(new Set(Array.isArray(wanted) ? wanted.map(String) : []));
  127. const options = Array.from(this.options || []);
  128. const multiple = Boolean(this.multiple);
  129. if (!multiple && values.length > 1) {
  130. return {
  131. selectable: true,
  132. multiple,
  133. missingValues: [],
  134. selectedValues: Array.from(this.selectedOptions, (option) => String(option.value)),
  135. };
  136. }
  137. const available = new Set(options.map((option) => String(option.value)));
  138. const missingValues = values.filter((value) => !available.has(value));
  139. if (missingValues.length > 0) {
  140. return {
  141. selectable: true,
  142. multiple,
  143. missingValues,
  144. selectedValues: Array.from(this.selectedOptions, (option) => String(option.value)),
  145. };
  146. }
  147. const requested = new Set(values);
  148. for (const option of options) option.selected = requested.has(String(option.value));
  149. this.dispatchEvent(new Event('input', { bubbles: true }));
  150. this.dispatchEvent(new Event('change', { bubbles: true }));
  151. return {
  152. selectable: true,
  153. multiple,
  154. missingValues: [],
  155. selectedValues: Array.from(this.selectedOptions, (option) => String(option.value)),
  156. };
  157. }`,
  158. [{ value: values }],
  159. );
  160. if (!mutation?.selectable) {
  161. return {
  162. success: false,
  163. code: 'TARGET_NOT_SELECT',
  164. error: 'Browser select_option target is not a select element.',
  165. durationMs: Date.now() - startedAt,
  166. target: { resolved: true, rect: target.rect },
  167. effect: { dispatched: false, verified: false, selectedValues: [] },
  168. };
  169. }
  170. if (values.length > 1 && mutation.multiple !== true) {
  171. return {
  172. success: false,
  173. code: 'SELECT_MULTIPLE_VALUES_NOT_ALLOWED',
  174. error: 'Browser select_option received multiple values for a single-select element.',
  175. durationMs: Date.now() - startedAt,
  176. target: { resolved: true, rect: target.rect },
  177. effect: {
  178. dispatched: false,
  179. verified: false,
  180. selectedValues: mutation.selectedValues,
  181. },
  182. recovery: 'Choose exactly one option value for this select element.',
  183. };
  184. }
  185. if (mutation.missingValues.length > 0) {
  186. return {
  187. success: false,
  188. code: 'SELECT_OPTION_NOT_FOUND',
  189. error: `Browser select_option could not find requested option value(s): ${mutation.missingValues.join(', ')}`,
  190. durationMs: Date.now() - startedAt,
  191. target: { resolved: true, rect: target.rect },
  192. effect: {
  193. dispatched: false,
  194. verified: false,
  195. selectedValues: mutation.selectedValues,
  196. },
  197. };
  198. }
  199. await delay(ACTION_SETTLE_DELAY_MS, session.commandSignal);
  200. const after = await this.callBackendNode<SelectState>(
  201. session,
  202. target.backendNodeId,
  203. `function () {
  204. if (!(this instanceof HTMLSelectElement)) {
  205. return { selectable: false, multiple: false, selectedValues: [] };
  206. }
  207. return {
  208. selectable: true,
  209. multiple: Boolean(this.multiple),
  210. selectedValues: Array.from(this.selectedOptions, (option) => String(option.value)),
  211. };
  212. }`,
  213. );
  214. const selectedValues = after?.selectedValues ?? [];
  215. const verified =
  216. after?.selectable === true &&
  217. after.multiple === mutation.multiple &&
  218. sameStringSet(selectedValues, values);
  219. this.invalidateObservation(session);
  220. const result = {
  221. success: verified,
  222. durationMs: Date.now() - startedAt,
  223. target: { resolved: true, rect: target.rect },
  224. effect: { dispatched: true, verified, selectedValues },
  225. } as Record<string, unknown>;
  226. if (!verified) {
  227. result.code = after?.selectable === false ? 'TARGET_NOT_SELECT' : 'SELECT_STATE_NOT_APPLIED';
  228. result.error =
  229. after?.selectable === false
  230. ? 'Browser select_option target is no longer a select element.'
  231. : 'Browser select_option was dispatched, but the requested selection was not retained.';
  232. result.recovery =
  233. 'Inspect the current selected value before retrying; the page may reject or control this field.';
  234. }
  235. return result;
  236. }
  237. protected async uploadFiles(
  238. session: SessionState,
  239. input: Record<string, unknown>,
  240. ): Promise<unknown> {
  241. const startedAt = Date.now();
  242. const beforeGeneration = session.generation;
  243. const target = await this.resolveTarget(session, input, false, false);
  244. if (target.backendNodeId === undefined) throw new Error('UPLOAD_REQUIRES_ELEMENT_REF');
  245. const authorizedFiles = Array.isArray(input.files)
  246. ? input.files
  247. .filter((file): file is Record<string, unknown> =>
  248. Boolean(file && typeof file === 'object' && !Array.isArray(file)),
  249. )
  250. .map((file) => (typeof file.filePath === 'string' ? file.filePath : ''))
  251. .filter(Boolean)
  252. : [];
  253. const paths = stringArray(input.paths).concat(authorizedFiles);
  254. if (paths.length === 0) throw new Error('UPLOAD_REQUIRES_PATHS');
  255. const requestedTimeout = Number(input.timeout);
  256. const chooserTimeoutMs =
  257. Number.isFinite(requestedTimeout) && requestedTimeout > 0
  258. ? Math.min(120_000, Math.floor(requestedTimeout))
  259. : 30_000;
  260. // The mature chooser workflow currently operates on the root CDP session.
  261. // Preserve the existing session-scoped direct input behavior for OOPIFs;
  262. // main-frame buttons and custom controls use the chooser-aware path.
  263. const upload = session.commandSessionId
  264. ? await this.uploadFilesInAttachedFrame(session, target.backendNodeId, paths)
  265. : await session.cdpHelper.uploadFilesByBackendNodeId(target.backendNodeId, paths, {
  266. timeoutMs: chooserTimeoutMs,
  267. ...(session.commandSignal ? { signal: session.commandSignal } : {}),
  268. });
  269. const observedGeneration = session.generation;
  270. const navigationDetected = observedGeneration !== beforeGeneration;
  271. const verified = upload.filesAttached === paths.length && !navigationDetected;
  272. this.invalidateObservation(session);
  273. const result = {
  274. success: verified,
  275. durationMs: Date.now() - startedAt,
  276. filesAttached: upload.filesAttached,
  277. chooserOpened: upload.chooserOpened,
  278. target: { resolved: true, rect: target.rect },
  279. effect: {
  280. dispatched: true,
  281. verified,
  282. fileCount: upload.filesAttached,
  283. chooserOpened: upload.chooserOpened,
  284. },
  285. navigation: {
  286. detected: navigationDetected,
  287. generation: observedGeneration,
  288. },
  289. } as Record<string, unknown>;
  290. if (navigationDetected) {
  291. result.code = 'UNEXPECTED_NAVIGATION';
  292. result.error = 'File upload changed the active Browser page unexpectedly.';
  293. result.retryable = true;
  294. result.recovery =
  295. 'Inspect the current page before deciding whether the upload should be repeated.';
  296. }
  297. return result;
  298. }
  299. private async uploadFilesInAttachedFrame(
  300. session: SessionState,
  301. backendNodeId: number,
  302. paths: string[],
  303. ): Promise<{ filesAttached: number; chooserOpened: false }> {
  304. await cdp(session, 'DOM.setFileInputFiles', { backendNodeId, files: paths });
  305. const filesAttached = await this.callBackendNode<number>(
  306. session,
  307. backendNodeId,
  308. 'function () { return this.files ? this.files.length : 0; }',
  309. );
  310. if (filesAttached !== paths.length) {
  311. throw new Error('FILE_UPLOAD_NOT_OBSERVED: selected file count did not match');
  312. }
  313. return { filesAttached, chooserOpened: false };
  314. }
  315. protected async paste(session: SessionState, input: Record<string, unknown>): Promise<unknown> {
  316. const startedAt = Date.now();
  317. const targetInput = input.ref || input.selector ? input : undefined;
  318. const target = targetInput
  319. ? await this.resolveTarget(session, targetInput, true, false)
  320. : { x: 0, y: 0, rect: undefined, backendNodeId: undefined };
  321. if (target.backendNodeId !== undefined) {
  322. await cdp(session, 'DOM.focus', { backendNodeId: target.backendNodeId });
  323. if (input.clear === true) {
  324. await session.cdpHelper.selectAllAtCurrentFocus({
  325. ...(session.commandSignal ? { signal: session.commandSignal } : {}),
  326. ...(session.commandTimeoutMs ? { timeoutMs: session.commandTimeoutMs } : {}),
  327. });
  328. await this.dispatchKey(session, 'Backspace', []);
  329. }
  330. }
  331. const explicitText = typeof input.text === 'string' ? input.text : undefined;
  332. const text = explicitText ?? (await this.clipboardProvider.read()).text;
  333. if (text.length === 0 && typeof input.html !== 'string') {
  334. throw new Error('PASTE_REQUIRES_CONTENT');
  335. }
  336. if (typeof input.html === 'string' && text.length === 0) {
  337. throw new Error('PASTE_HTML_REQUIRES_PLAIN_TEXT_FALLBACK');
  338. }
  339. await cdp(session, 'Input.insertText', { text });
  340. const waitMs = Math.max(0, Math.floor(asNumber(input.waitMs, ACTION_SETTLE_DELAY_MS)));
  341. if (waitMs > 0) await delay(waitMs, session.commandSignal);
  342. this.invalidateObservation(session);
  343. return {
  344. success: true,
  345. durationMs: Date.now() - startedAt,
  346. target: { resolved: Boolean(targetInput), ...(target.rect ? { rect: target.rect } : {}) },
  347. effect: {
  348. dispatched: true,
  349. verified: false,
  350. verificationRequired: true,
  351. textLength: text.length,
  352. },
  353. };
  354. }
  355. protected async callBackendNode<T = unknown>(
  356. session: SessionState,
  357. backendNodeId: number,
  358. functionDeclaration: string,
  359. args: Array<Record<string, unknown>> = [],
  360. ): Promise<T> {
  361. const resolved = await cdp<{ object?: { objectId?: string } }>(session, 'DOM.resolveNode', {
  362. backendNodeId,
  363. });
  364. const objectId = resolved.object?.objectId;
  365. if (!objectId) throw new Error('TARGET_NOT_RESOLVED');
  366. try {
  367. const result = await cdp<{
  368. result?: { value?: unknown };
  369. exceptionDetails?: { text?: string };
  370. }>(session, 'Runtime.callFunctionOn', {
  371. objectId,
  372. functionDeclaration,
  373. arguments: args,
  374. returnByValue: true,
  375. awaitPromise: true,
  376. });
  377. if (result.exceptionDetails) {
  378. throw new Error(result.exceptionDetails.text || 'TARGET_SCRIPT_FAILED');
  379. }
  380. return result.result?.value as T;
  381. } finally {
  382. await cdp(session, 'Runtime.releaseObject', { objectId }).catch(() => undefined);
  383. }
  384. }
  385. }
  386. function sameStringSet(left: readonly string[], right: readonly string[]): boolean {
  387. return (
  388. left.length === right.length &&
  389. left.every((value) => right.includes(value)) &&
  390. right.every((value) => left.includes(value))
  391. );
  392. }