dsh-builtin-browser 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/README.en.md +89 -0
  3. package/browser-extension/constants.mjs +20 -0
  4. package/browser-extension/controller.mjs +293 -0
  5. package/browser-extension/locales.mjs +15 -0
  6. package/browser-extension/manifest.json +12 -0
  7. package/browser-extension/options.html +14 -0
  8. package/browser-extension/options.mjs +9 -0
  9. package/browser-extension/permission-guard.mjs +13 -0
  10. package/browser-extension/worker.mjs +74 -0
  11. package/desktop-bridge/desktop-identity.json +10 -2
  12. package/desktop-bridge/install.mjs +28 -2
  13. package/docs/issue-replies-2026-11-28.md +141 -0
  14. package/dsh-host-patch/apply.mjs +1 -1
  15. package/dsh-host-patch/rc3.json +4 -4
  16. package/dsh-host-patch/rc5.json +4 -4
  17. package/dsh-host-patch/v023-alpha2.json +2 -2
  18. package/lib/browser-electron/bridge-status.js +24 -1
  19. package/lib/browser-electron/desktop-identity.js +47 -8
  20. package/lib/client.js +2 -1
  21. package/native-host/install.mjs +5 -0
  22. package/package.json +20 -2
  23. package/scripts/build-client.mjs +305 -0
  24. package/scripts/build.mjs +69 -0
  25. package/scripts/bundle-host.mjs +28 -0
  26. package/scripts/fix-exports.mjs +40 -0
  27. package/scripts/install-electron.mjs +101 -0
  28. package/scripts/pack.mjs +99 -0
  29. package/scripts/publish-manifest.mjs +56 -0
  30. package/scripts/verify-exports.mjs +58 -0
  31. package/scripts/verify-preview-sdk.mjs +93 -0
  32. package/skills/dsh-builtin-browser/SKILL.md +98 -0
  33. package/skills/dsh-builtin-browser/references/batch.md +68 -0
  34. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  35. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  36. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  37. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  38. package/skills/dsh-debug-host/SKILL.md +56 -0
  39. package/skills/dsh-debug-self/SKILL.md +50 -0
  40. package/src/bridge-compatibility.ts +39 -0
  41. package/src/browser/anti-bot.ts +251 -0
  42. package/src/browser/deep-dom.ts +40 -0
  43. package/src/browser/handles.ts +89 -0
  44. package/src/browser/runtime.ts +578 -0
  45. package/src/browser/takeover-target.ts +45 -0
  46. package/src/browser/types.ts +870 -0
  47. package/src/browser-electron/authenticated-route.ts +109 -0
  48. package/src/browser-electron/automatic-maintenance.ts +736 -0
  49. package/src/browser-electron/bridge-auto.ts +159 -0
  50. package/src/browser-electron/bridge-connection.ts +386 -0
  51. package/src/browser-electron/bridge-endpoint.ts +129 -0
  52. package/src/browser-electron/bridge-install.ts +290 -0
  53. package/src/browser-electron/bridge-maintenance.ts +189 -0
  54. package/src/browser-electron/bridge-status.ts +412 -0
  55. package/src/browser-electron/desktop-bridge-host.ts +253 -0
  56. package/src/browser-electron/desktop-identity.ts +400 -0
  57. package/src/browser-electron/desktop-shell.ts +100 -0
  58. package/src/browser-electron/document-readiness.ts +45 -0
  59. package/src/browser-electron/electron-provision.ts +347 -0
  60. package/src/browser-electron/entry.ts +1378 -0
  61. package/src/browser-electron/ephemeral-profile.ts +189 -0
  62. package/src/browser-electron/extension-browser.ts +230 -0
  63. package/src/browser-electron/extension-setup.ts +67 -0
  64. package/src/browser-electron/file-write.ts +31 -0
  65. package/src/browser-electron/foreground-watch.ts +142 -0
  66. package/src/browser-electron/guest-cookie-jar.ts +177 -0
  67. package/src/browser-electron/guest-cookie-store.ts +59 -0
  68. package/src/browser-electron/guest-css-runtime.ts +76 -0
  69. package/src/browser-electron/guest-css.ts +68 -0
  70. package/src/browser-electron/guest-route.ts +716 -0
  71. package/src/browser-electron/guest-runtime.ts +408 -0
  72. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  73. package/src/browser-electron/guest-storage.ts +120 -0
  74. package/src/browser-electron/history-store.ts +224 -0
  75. package/src/browser-electron/host-main.ts +1385 -0
  76. package/src/browser-electron/host-patch-maintenance.ts +121 -0
  77. package/src/browser-electron/http-body.ts +65 -0
  78. package/src/browser-electron/json-reply.ts +47 -0
  79. package/src/browser-electron/maintenance-broker.ts +166 -0
  80. package/src/browser-electron/maintenance-lifecycle.ts +91 -0
  81. package/src/browser-electron/maintenance-route.ts +68 -0
  82. package/src/browser-electron/missing-system-browser.ts +114 -0
  83. package/src/browser-electron/open-slot.ts +49 -0
  84. package/src/browser-electron/paths.ts +25 -0
  85. package/src/browser-electron/preferred-browser.ts +130 -0
  86. package/src/browser-electron/preview-route.ts +215 -0
  87. package/src/browser-electron/process-ownership.ts +174 -0
  88. package/src/browser-electron/process.ts +23 -0
  89. package/src/browser-electron/profile-checkpoint.ts +187 -0
  90. package/src/browser-electron/profile-command.ts +47 -0
  91. package/src/browser-electron/profile-extension.ts +129 -0
  92. package/src/browser-electron/profile-lease.ts +211 -0
  93. package/src/browser-electron/profile-residue.ts +49 -0
  94. package/src/browser-electron/provider-core.ts +1107 -0
  95. package/src/browser-electron/provider-interaction.ts +1034 -0
  96. package/src/browser-electron/provider-media.ts +589 -0
  97. package/src/browser-electron/provider-navigation.ts +323 -0
  98. package/src/browser-electron/provider-observation.ts +664 -0
  99. package/src/browser-electron/provider-tabs.ts +372 -0
  100. package/src/browser-electron/provider.ts +666 -0
  101. package/src/browser-electron/reference-route.ts +598 -0
  102. package/src/browser-electron/remote-host.ts +1538 -0
  103. package/src/browser-electron/rpc-input.ts +13 -0
  104. package/src/browser-electron/rpc-ops.ts +41 -0
  105. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  106. package/src/browser-electron/runtime-route.ts +105 -0
  107. package/src/browser-electron/runtime-status.ts +309 -0
  108. package/src/browser-electron/settings-route.ts +64 -0
  109. package/src/browser-electron/settings-store.ts +593 -0
  110. package/src/browser-electron/shortcuts-route.ts +112 -0
  111. package/src/browser-electron/sidebar-only-host.ts +300 -0
  112. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  113. package/src/browser-electron/system-browser.ts +1850 -0
  114. package/src/browser-electron/tauri-host.ts +194 -0
  115. package/src/browser-electron/timing.ts +16 -0
  116. package/src/browser-electron/virtual-cursor.ts +162 -0
  117. package/src/browser-electron/windows-system.ts +24 -0
  118. package/src/browser-reference/delivery.ts +384 -0
  119. package/src/browser-reference/entry.ts +631 -0
  120. package/src/browser-reference/export.ts +339 -0
  121. package/src/browser-reference/import.ts +303 -0
  122. package/src/browser-reference/page-script.ts +1537 -0
  123. package/src/browser-reference/service.ts +1346 -0
  124. package/src/browser-reference/store.ts +172 -0
  125. package/src/browser-reference/text-quote.ts +219 -0
  126. package/src/browser-reference/types.ts +195 -0
  127. package/src/browser-reference/visible.ts +367 -0
  128. package/src/browser-reference/web-sources.ts +106 -0
  129. package/src/client/apply-guard.ts +22 -0
  130. package/src/client/browser/BrowserController.ts +693 -0
  131. package/src/client/browser/BrowserFrame.ts +78 -0
  132. package/src/client/browser/BrowserNavigation.ts +169 -0
  133. package/src/client/browser/BrowserPage.ts +23 -0
  134. package/src/client/browser/BrowserPersistence.ts +44 -0
  135. package/src/client/browser/IframeImpl.ts +182 -0
  136. package/src/client/browser/child-tabs.ts +14 -0
  137. package/src/client/browser/frame-history.ts +125 -0
  138. package/src/client/browser/frame-state.ts +27 -0
  139. package/src/client/browser/iframe-reference.ts +67 -0
  140. package/src/client/browser/initialization.ts +262 -0
  141. package/src/client/browser/omnibox.ts +243 -0
  142. package/src/client/browser/store.ts +38 -0
  143. package/src/client/browser/takeover-channel.ts +72 -0
  144. package/src/client/browser/url.ts +46 -0
  145. package/src/client/browser/web-reference-source.ts +56 -0
  146. package/src/client/css-modules.d.ts +4 -0
  147. package/src/client/definition.tsx +36 -0
  148. package/src/client/electron/ElectronWebViewImpl.ts +371 -0
  149. package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
  150. package/src/client/electron/NativeChildPresentation.ts +53 -0
  151. package/src/client/electron/NativeViewPage.ts +265 -0
  152. package/src/client/electron/pages.ts +23 -0
  153. package/src/client/electron/reference-overlay.ts +53 -0
  154. package/src/client/electron/workspace.ts +33 -0
  155. package/src/client/index.ts +333 -0
  156. package/src/client/locales.ts +860 -0
  157. package/src/client/pages.ts +28 -0
  158. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  159. package/src/client/reference/client/draft-reference.ts +167 -0
  160. package/src/client/reference/client/index.ts +7 -0
  161. package/src/client/reference/client/ordered-submission.ts +108 -0
  162. package/src/client/reference/client/pending-delivery.ts +216 -0
  163. package/src/client/reference/client/plugin.ts +208 -0
  164. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  165. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  166. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  167. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  168. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  169. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  170. package/src/client/reference/client/production/assembly.ts +447 -0
  171. package/src/client/reference/client/production/asset-store.ts +144 -0
  172. package/src/client/reference/client/production/availability.ts +72 -0
  173. package/src/client/reference/client/production/bytes.ts +36 -0
  174. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  175. package/src/client/reference/client/production/delivery-client.ts +211 -0
  176. package/src/client/reference/client/production/draft-adapter.ts +512 -0
  177. package/src/client/reference/client/production/http-transport.ts +212 -0
  178. package/src/client/reference/client/production/production-submission.ts +70 -0
  179. package/src/client/reference/client/production/protocol.ts +234 -0
  180. package/src/client/reference/client/production/reference-card.ts +240 -0
  181. package/src/client/reference/client/production/reference-labels.ts +29 -0
  182. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  183. package/src/client/reference/client/production/reveal.ts +215 -0
  184. package/src/client/reference/client/production/runtime.ts +1056 -0
  185. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  186. package/src/client/reference/client/production/source-marker.ts +99 -0
  187. package/src/client/reference/client/production/source-opener.ts +55 -0
  188. package/src/client/reference/client/production/styles.ts +104 -0
  189. package/src/client/reference/client/production/user-text-rule.ts +67 -0
  190. package/src/client/reference/client/reveal.ts +109 -0
  191. package/src/client/reference/client/scheme.ts +114 -0
  192. package/src/client/reference/client/session-schedule.ts +36 -0
  193. package/src/client/reference/client/types.ts +168 -0
  194. package/src/client/reference/css-modules.d.ts +4 -0
  195. package/src/client/reference/index.ts +11 -0
  196. package/src/client/reference-capture-owner.ts +162 -0
  197. package/src/client/reference-intents.ts +36 -0
  198. package/src/client/settings/index.ts +42 -0
  199. package/src/client/settings/mount-guard.ts +31 -0
  200. package/src/client/settings/panel.ts +2773 -0
  201. package/src/client/shortcut-open.ts +30 -0
  202. package/src/client/startpage/binding.ts +99 -0
  203. package/src/client/startpage/controller.ts +300 -0
  204. package/src/client/startpage/model.ts +279 -0
  205. package/src/client/view/Browser.module.css +751 -0
  206. package/src/client/view/BrowserBody.tsx +315 -0
  207. package/src/client/view/BrowserPresentation.ts +9 -0
  208. package/src/client/view/BrowserTitle.tsx +17 -0
  209. package/src/client/view/IframePresentation.ts +365 -0
  210. package/src/client/view/StartPage.tsx +598 -0
  211. package/src/client/view/TakeoverBanner.tsx +21 -0
  212. package/src/compat/host-features.ts +92 -0
  213. package/src/index.ts +110 -0
  214. package/src/reference-owner.ts +5 -0
  215. package/src/reference-page.ts +9 -0
  216. package/src/reference-source.ts +3 -0
  217. package/src/reference-text.ts +219 -0
  218. package/src/startpage-settings.ts +103 -0
  219. package/src/startpage.ts +71 -0
  220. package/src/takeover-protocol.ts +28 -0
  221. package/src/tool-browser/block-recovery.ts +85 -0
  222. package/src/tool-browser/code-tool.ts +555 -0
  223. package/src/tool-browser/code-worker.ts +725 -0
  224. package/src/tool-browser/element-fields.ts +167 -0
  225. package/src/tool-browser/errors.ts +40 -0
  226. package/src/tool-browser/index.ts +265 -0
  227. package/src/tool-browser/page-probe.ts +675 -0
  228. package/src/tool-browser/panel-page.ts +126 -0
  229. package/src/tool-browser/probe-client.ts +183 -0
  230. package/src/tool-browser/screenshot-annotations.ts +131 -0
  231. package/src/tool-browser/screenshot-image.ts +49 -0
  232. package/src/tool-browser/state.ts +375 -0
  233. package/src/tool-browser/takeover.ts +199 -0
  234. package/src/tool-browser/tools-debug.ts +806 -0
  235. package/src/tool-browser/tools-interaction.ts +956 -0
  236. package/src/tool-browser/tools-navigation.ts +786 -0
  237. package/src/tool-browser/tools-observation.ts +474 -0
  238. package/src/tool-browser/tools-reference.ts +294 -0
  239. package/src/types/electron-shim.d.ts +144 -0
  240. package/src/types.ts +85 -0
  241. package/src/web-guest.ts +35 -0
  242. package/tools/accept-desktop.mjs +148 -0
  243. package/dist/client.d.cts +0 -516
  244. package/dist/client.d.mts +0 -516
  245. package/dist/index.cjs +0 -92
  246. package/dist/index.d.mts +0 -2960
  247. package/dist/index.mjs +0 -24
  248. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  249. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  250. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  251. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  252. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  253. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  254. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  255. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  256. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  257. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  258. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  259. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  260. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  261. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  262. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  263. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  264. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  265. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  266. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  267. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  268. package/dsh-host-patch/sources/manifest.json +0 -218
  269. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  270. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  271. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  272. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  273. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  274. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  275. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  276. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  277. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  278. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  279. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  280. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  281. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  282. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  283. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  284. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  285. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  286. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  287. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  288. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  289. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  290. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  291. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  292. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  293. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  294. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  295. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  296. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  297. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  298. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  299. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  300. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  301. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  302. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  303. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  304. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  305. package/dsh-host-patch/sources/series.json +0 -260
@@ -0,0 +1,1034 @@
1
+ import { DEFAULT_OPERATION_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
2
+ import { pageOperationScript } from '../tool-browser/page-probe.ts'
3
+ import { DEEP_DOM_SOURCE } from '../browser/deep-dom.ts'
4
+ import { paintCursor, type CursorAction } from './virtual-cursor.ts'
5
+ import type { BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserClickSequenceRequest, BrowserClickSequenceResult, BrowserElementTarget, BrowserPageOperationRequest, BrowserExecuteResult, BrowserFillRequest, BrowserFillResult, BrowserGetValueRequest, BrowserGetValueResult, BrowserSelectRequest, BrowserSelectResult, BrowserSessionId, BrowserSetValueRequest, BrowserSetValueResult, BrowserTypeRequest, BrowserScrollRequest, BrowserKeyRequest } from '../browser/types.ts'
6
+ import { BrowserError } from '../browser/types.ts'
7
+ import { PROVIDER_TIMEOUTS, KEY_SPECS, BROWSER_KEY_NAMES, TARGET_SCRIPT_GRACE_MS, pagePollSlice, withTimeout, scriptPoint, handleSendEvaluate, type ElectronViewHandle, type Tab, type CdpMouseParams, type CdpInsertTextParams } from './provider-core.ts'
8
+ import { ProviderObservation } from './provider-observation.ts'
9
+
10
+ const FOCUSED_EDITABLE_SCRIPT = `(() => {
11
+ const NON_TEXT_INPUTS = ['button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit']
12
+ let doc = document
13
+ let el = doc.activeElement
14
+ for (;;) {
15
+ if (el && el.shadowRoot && el.shadowRoot.activeElement) { el = el.shadowRoot.activeElement; continue }
16
+ if (el && (el.tagName === 'IFRAME' || el.tagName === 'FRAME')) {
17
+ let inner = null
18
+ try { inner = el.contentDocument } catch {}
19
+ if (!inner) return { editable: true, active: el.tagName }
20
+ doc = inner
21
+ el = inner.activeElement
22
+ continue
23
+ }
24
+ break
25
+ }
26
+ const active = el ? el.tagName : 'nothing'
27
+ if (doc.designMode === 'on' || (el && el.isContentEditable)) return { editable: true, active }
28
+ if (el && el.tagName === 'TEXTAREA') return { editable: !el.readOnly && !el.disabled, active }
29
+ if (el && el.tagName === 'INPUT') return { editable: !el.readOnly && !el.disabled && !NON_TEXT_INPUTS.includes(String(el.type || '').toLowerCase()), active }
30
+ if (el && el.tagName.includes('-') && !el.shadowRoot) return { editable: true, active }
31
+ return { editable: false, active }
32
+ })()`
33
+
34
+ /** An in-page locate for one poll slice: `last` reports a miss, earlier slices answer `{ pending: true }`. */
35
+ type TargetScript = (sliceMs: number, last: boolean) => string
36
+
37
+ export abstract class ProviderInteraction extends ProviderObservation {
38
+ /** Run a fixed browser operation; the request cannot contain a script. */
39
+ async pageOperation(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
40
+ const script = pageOperationScript(request)
41
+ if (request.operation === 'drag') {
42
+ return this.dispatchPointer(session, request.from, request.to, request.steps, signal)
43
+ }
44
+ if (request.operation === 'probe' && request.method === 'hoverAt') {
45
+ const point = { x: Number(request.args?.[0]), y: Number(request.args?.[1]) }
46
+ return this.dispatchPointer(session, point, undefined, 1, signal)
47
+ }
48
+ return this.evaluatePage(session, { script }, signal)
49
+ }
50
+
51
+ /** Send page pointer input through CDP while preserving presentation and cancellation policy. */
52
+ private async dispatchPointer(
53
+ session: BrowserSessionId,
54
+ from: { readonly x: number; readonly y: number },
55
+ to: { readonly x: number; readonly y: number } | undefined,
56
+ steps: number,
57
+ signal?: AbortSignal,
58
+ ): Promise<BrowserExecuteResult> {
59
+ const coordinates = [from.x, from.y, ...to === undefined ? [] : [to.x, to.y]]
60
+ if (coordinates.some(value => !Number.isFinite(value) || value < 0)) {
61
+ throw new BrowserError('browser: pointer coordinates must be finite nonnegative viewport pixels', 'BROWSER_POINTER_INVALID')
62
+ }
63
+ if (to !== undefined && this.settingsSource?.().vision.strategy === 'nonVisual') {
64
+ throw new BrowserError('browser: coordinate dragging requires the visual strategy', 'BROWSER_NON_VISUAL_COORDINATES')
65
+ }
66
+ const s = this.session(session)
67
+ const handle = await this.present(s, signal)
68
+ const viewport = await withTimeout(
69
+ handleSendEvaluate(handle, '({width:innerWidth,height:innerHeight})'),
70
+ PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer viewport check timed out',
71
+ )
72
+ if (!viewport.ok) throw new BrowserError('browser: could not read the pointer viewport', 'BROWSER_POINTER_INVALID')
73
+ const size = viewport.value as { width: number; height: number }
74
+ if (from.x >= size.width || from.y >= size.height || (to !== undefined && (to.x >= size.width || to.y >= size.height))) {
75
+ return { ok: true, value: JSON.stringify(to === undefined ? false : { ok: false, reason: 'drag points must be inside the current viewport' }) }
76
+ }
77
+ const send = async (params: CdpMouseParams): Promise<void> => {
78
+ signal?.throwIfAborted()
79
+ this.assertSameView(session, handle, this.activeTab(s).handle)
80
+ await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer input timed out')
81
+ }
82
+ await send({ type: 'mouseMoved', x: from.x, y: from.y, buttons: 0 })
83
+ if (to === undefined) return { ok: true, value: 'true' }
84
+ let at = from
85
+ let held = true
86
+ try {
87
+ await send({ type: 'mousePressed', x: from.x, y: from.y, button: 'left', buttons: 1, clickCount: 1 })
88
+ const count = Math.max(1, Math.min(Math.trunc(steps) || 12, 60))
89
+ for (let step = 1; step <= count; step += 1) {
90
+ const next = { x: from.x + (to.x - from.x) * step / count, y: from.y + (to.y - from.y) * step / count }
91
+ await send({ type: 'mouseMoved', ...next, button: 'left', buttons: 1 })
92
+ at = next
93
+ }
94
+ // Native HTML drag targets need a final drag-over before releasing at the destination.
95
+ await send({ type: 'mouseMoved', ...to, button: 'left', buttons: 1 })
96
+ await send({ type: 'mouseReleased', ...to, button: 'left', buttons: 0, clickCount: 1 })
97
+ held = false
98
+ return { ok: true, value: JSON.stringify({ ok: true, moved: count, at: to }) }
99
+ } finally {
100
+ if (held) {
101
+ await withTimeout(
102
+ handle.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, button: 'left', buttons: 0, clickCount: 1 }),
103
+ 1_000, undefined, 'browser: pointer release timed out',
104
+ ).catch(() => {})
105
+ }
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Click at viewport coordinates, or at a located element's center when a
111
+ * `target` (css/text/xpath) is given. CDP mousePressed + mouseReleased.
112
+ */
113
+ async click(
114
+ session: BrowserSessionId,
115
+ request: BrowserClickRequest | { readonly target: BrowserElementTarget },
116
+ signal?: AbortSignal,
117
+ ): Promise<void> {
118
+ const s = this.session(session)
119
+ // The view the locate runs against. It can stop being the session's active view while
120
+ // the locate waits (see prepareTarget), so every dispatch below re-reads the live one.
121
+ const locateHandle = this.activeTab(s).handle
122
+ signal?.throwIfAborted()
123
+ let x = 0
124
+ let y = 0
125
+ if ('target' in request) {
126
+ // Semantic targeting (②): locate the element in-page, scroll it into
127
+ // view, wait for the compositor to commit any scroll offset so CDP
128
+ // hit-testing matches the scrolled layout, and return top-viewport center.
129
+ const locateMs = PROVIDER_TIMEOUTS.lookup
130
+ const body = `
131
+ const absRect = node => {
132
+ const r = node.getBoundingClientRect()
133
+ let ax = r.x, ay = r.y
134
+ let d = node.ownerDocument
135
+ while (d && d.defaultView && d.defaultView.frameElement) {
136
+ const fr = d.defaultView.frameElement.getBoundingClientRect()
137
+ ax += fr.x; ay += fr.y
138
+ d = d.defaultView.frameElement.ownerDocument
139
+ }
140
+ return { x: ax, y: ay, width: r.width, height: r.height }
141
+ }
142
+ const before = absRect(el)
143
+ el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'center' })
144
+ const moved = absRect(el)
145
+ const needsFrame = Math.abs(moved.x - before.x) > 0.5 || Math.abs(moved.y - before.y) > 0.5
146
+ || before.y < 0 || before.y + before.height > innerHeight
147
+ || before.x < 0 || before.x + before.width > innerWidth
148
+ if (needsFrame) {
149
+ const nextFrame = () => new Promise(resolve => {
150
+ if (typeof requestAnimationFrame !== 'function') { setTimeout(resolve, 16); return }
151
+ let done = false
152
+ const finish = () => { if (!done) { done = true; resolve() } }
153
+ const timer = setTimeout(finish, 50)
154
+ requestAnimationFrame(() => { clearTimeout(timer); finish() })
155
+ })
156
+ await nextFrame()
157
+ await nextFrame()
158
+ }
159
+ const r = absRect(el)
160
+ return { ok: true, x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }
161
+ `
162
+ const script = this.buildTargetScript(request.target, locateMs, body)
163
+ const out = await this.runTargetScript(this.activeTab(s), script, locateMs, signal, 'BROWSER_CLICK_FAILED', 'browser: click')
164
+ x = Number(out.x)
165
+ y = Number(out.y)
166
+ } else {
167
+ // A coordinate only exists because somebody read a picture. Under the
168
+ // non-visual strategy the plugin must not accept one: a model that cannot
169
+ // see cannot have produced it, so the coordinates are either copied from an
170
+ // earlier vision pass or invented, and honouring them turns a silent
171
+ // mis-click into a mystery. Refusing here, with a message that says what to
172
+ // do instead, converts that into a usable instruction.
173
+ if (this.settingsSource !== undefined && this.settingsSource().vision.strategy === 'nonVisual') {
174
+ throw new BrowserError(
175
+ 'browser: the configured non-visual strategy refuses coordinate clicks — pass a semantic target instead, e.g. target { by: "text", value: "Sign in" }, which locates the element from the DOM and clicks its centre',
176
+ 'BROWSER_NON_VISUAL_COORDINATES',
177
+ )
178
+ }
179
+ x = request.x
180
+ y = request.y
181
+ }
182
+ // Input.* is only delivered to a view with a current display surface; the
183
+ // barrier also re-presents after a navigation replaced the renderer. It returns the
184
+ // handle that may still be receiving input when it settles.
185
+ const handle = await this.present(s, signal)
186
+ // The locate (up to 10s) and the present barrier both ran against the view captured
187
+ // earlier; if the human switched tabs meanwhile, these coordinates belong to one page
188
+ // and the dispatch would go to another — and Chromium answers success either way.
189
+ if ('target' in request) this.assertSameView(session, locateHandle, handle)
190
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
191
+ const send = (params: Record<string, unknown>, label: string): Promise<unknown> =>
192
+ withTimeout(
193
+ handle.sendCommand('Input.dispatchMouseEvent', params),
194
+ timeoutMs,
195
+ signal,
196
+ `browser: click ${label} timed out after ${timeoutMs}ms`,
197
+ )
198
+ // Paint the synthetic pointer before dispatching the mouse sequence so the
199
+ // overlay evaluation never interleaves between mouseMoved, mousePressed, and
200
+ // mouseReleased or races a form-submit navigation triggered by the click.
201
+ await this.showCursorSettled(handle, x, y, 'click', 'click', true)
202
+ // Chromium routes a synthesized `mousePressed` to the widget's *current*
203
+ // hover target rather than hit-testing the coordinates, and a real pointer
204
+ // click is always preceded by movement. A view that has never received a
205
+ // mouse event has no hover target yet, so the press of the FIRST click on a
206
+ // fresh tab went nowhere while CDP still answered success; the second click
207
+ // landed because the first had quietly established the target. Move the
208
+ // pointer first so a click is self-contained.
209
+ try {
210
+ await send({ type: 'mouseMoved', x, y, buttons: 0 } satisfies CdpMouseParams, 'move')
211
+ } catch (error) {
212
+ throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error })
213
+ }
214
+ const release = (): void => {
215
+ // Back to the handle the PRESS may have landed on, deliberately not to the currently
216
+ // active tab: this only runs after a failed press/release, and re-targeting a
217
+ // compensating half of a click to a view the human just switched to would press a
218
+ // button there. Best-effort either way.
219
+ void handle
220
+ .sendCommand('Input.dispatchMouseEvent', {
221
+ type: 'mouseReleased',
222
+ x,
223
+ y,
224
+ button: 'left',
225
+ buttons: 0,
226
+ clickCount: 1,
227
+ } satisfies CdpMouseParams)
228
+ .catch(() => {})
229
+ }
230
+ try {
231
+ await send({ type: 'mousePressed', x, y, button: 'left', buttons: 1, clickCount: 1 }, 'press')
232
+ } catch (error) {
233
+ // The press may still land late; release best-effort so the button is
234
+ // never left in a stuck pressed state.
235
+ release()
236
+ throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error })
237
+ }
238
+ try {
239
+ await send({ type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 }, 'release')
240
+ } catch (error) {
241
+ // The press already landed; retry the release so the button is not
242
+ // left pressed before surfacing the failure.
243
+ release()
244
+ throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error })
245
+ }
246
+ this.record(s, 'click', 'target' in request ? { target: request.target } : { x, y }, true)
247
+ }
248
+
249
+ /**
250
+ * Click many points in order, once.
251
+ *
252
+ * The same wire sequence as {@link click}, looped — only the round-trip count changes. Presenting
253
+ * happens ONCE: the display-surface barrier is per view, not per press, and paying it for every
254
+ * point is what made an 86-cell board expensive.
255
+ *
256
+ * Stops at the first point that fails and reports where: a run that pressed through a page which
257
+ * had navigated or lost its surface would fill the wrong cells and still answer success.
258
+ * @param session - the session to click in.
259
+ * @param request - the points and the interval between them.
260
+ * @param signal - cancellation between points.
261
+ * @returns how many points landed, and where it stopped if it did not finish.
262
+ */
263
+ async clickSequence(
264
+ session: BrowserSessionId,
265
+ request: BrowserClickSequenceRequest,
266
+ signal?: AbortSignal,
267
+ ): Promise<BrowserClickSequenceResult> {
268
+ const s = this.session(session)
269
+ const points = Array.isArray(request.points) ? request.points : []
270
+ if (points.length === 0) return { clicked: 0 }
271
+ if (this.settingsSource !== undefined && this.settingsSource().vision.strategy === 'nonVisual') {
272
+ throw new BrowserError(
273
+ 'browser: the configured non-visual strategy refuses coordinate clicks — pass a semantic target instead.',
274
+ 'BROWSER_NON_VISUAL_COORDINATES',
275
+ )
276
+ }
277
+ // One barrier for the whole run: cheap, and it is the view that needs a surface, not each press.
278
+ const handle = await this.present(s, signal)
279
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
280
+ // 40 ms is above one frame at 30 fps, which is what keeps the page from reading two presses as a
281
+ // double click. Faster runs were measured dropping presses outright.
282
+ const gap = typeof request.intervalMs === 'number' && request.intervalMs >= 0 ? request.intervalMs : 40
283
+ const send = (params: Record<string, unknown>, label: string): Promise<unknown> =>
284
+ withTimeout(
285
+ handle.sendCommand('Input.dispatchMouseEvent', params),
286
+ timeoutMs,
287
+ signal,
288
+ `browser: click sequence ${label} timed out after ${timeoutMs}ms`,
289
+ )
290
+ let clicked = 0
291
+ for (const [index, point] of points.entries()) {
292
+ signal?.throwIfAborted()
293
+ const x = Number(point?.x)
294
+ const y = Number(point?.y)
295
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
296
+ return { clicked, failedAt: index, error: `point ${index} has no finite x/y` }
297
+ }
298
+ try {
299
+ // The move is load-bearing: Chromium routes a synthesized press to the CURRENT hover target,
300
+ // and a view that has never received a mouse event has none — the first press would go nowhere
301
+ // while CDP still answered success.
302
+ await send({ type: 'mouseMoved', x, y, buttons: 0 } satisfies CdpMouseParams, 'move')
303
+ await send({ type: 'mousePressed', x, y, button: 'left', buttons: 1, clickCount: 1 } satisfies CdpMouseParams, 'press')
304
+ await send({ type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 } satisfies CdpMouseParams, 'release')
305
+ clicked += 1
306
+ } catch (error) {
307
+ // Best-effort release so a failed press cannot leave the button stuck down.
308
+ void handle
309
+ .sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 })
310
+ .catch(() => {})
311
+ return { clicked, failedAt: index, error: String(error instanceof Error ? error.message : error) }
312
+ }
313
+ if (index < points.length - 1 && gap > 0) await new Promise(resolve => setTimeout(resolve, gap))
314
+ }
315
+ return { clicked }
316
+ }
317
+
318
+ /**
319
+ * Type into the focused element, or focus a located element (css/text/xpath)
320
+ * first and then insert the text.
321
+ */
322
+ async type(
323
+ session: BrowserSessionId,
324
+ request: BrowserTypeRequest | { readonly target: BrowserElementTarget },
325
+ signal?: AbortSignal,
326
+ ): Promise<void> {
327
+ const s = this.session(session)
328
+ // The view the locate runs against. It can stop being the session's active view while
329
+ // the locate waits (the human is invited to drive the same window), so the input below
330
+ // goes to the handle `present` reports instead of this one.
331
+ const locateHandle = this.activeTab(s).handle
332
+ signal?.throwIfAborted()
333
+ const hasTarget = 'target' in request
334
+ if (hasTarget) {
335
+ const locateMs = PROVIDER_TIMEOUTS.lookup
336
+ const script = this.buildTargetScript(request.target, locateMs, `
337
+ el.focus()
338
+ return { ok: true }
339
+ `)
340
+ const locateTab = this.activeTab(s)
341
+ const out = await this.runTargetScript(locateTab, script, locateMs, signal, 'BROWSER_TYPE_FAILED', 'browser: type')
342
+ const cursorPoint = scriptPoint(out)
343
+ if (cursorPoint !== undefined) this.showCursor(locateTab.handle, cursorPoint.x, cursorPoint.y, 'click', 'type', true)
344
+ }
345
+ const text = 'text' in request ? request.text : ''
346
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
347
+ // Input.insertText goes through the Input domain: same display-surface
348
+ // requirement as click/key. It also reports which view is active once the barrier has
349
+ // settled, which is what makes the tab-switch check below meaningful.
350
+ const handle = await this.present(s, signal)
351
+ // Focusing one page and inserting into another is exactly the silent mis-target this
352
+ // refuses: the element was focused in the located view, and the text would have gone to
353
+ // whichever page is now visible — possibly a password field there.
354
+ if (hasTarget) this.assertSameView(session, locateHandle, handle)
355
+ // Electron guests (DSH Desktop and Tauri sidebar) crash their renderer when text is inserted
356
+ // with no editable element focused, and nothing would have been typed in any browser.
357
+ const focus = await withTimeout(
358
+ handleSendEvaluate(handle, FOCUSED_EDITABLE_SCRIPT, signal),
359
+ PROVIDER_TIMEOUTS.lookup,
360
+ signal,
361
+ `browser: type focus check timed out after ${PROVIDER_TIMEOUTS.lookup}ms`,
362
+ )
363
+ if (!focus.ok) throw new BrowserError(`browser: type failed: ${focus.exception}`, 'BROWSER_TYPE_FAILED')
364
+ const focused = focus.value as { editable?: unknown; active?: unknown } | null
365
+ if (focused?.editable !== true) {
366
+ const active = typeof focused?.active === 'string' ? `focus is on ${focused.active}` : 'nothing has focus'
367
+ throw new BrowserError(`browser: type needs a focused text field, and ${active}; pass a target, or tap the field first`, 'BROWSER_TYPE_NO_FOCUS')
368
+ }
369
+ try {
370
+ await withTimeout(
371
+ handle.sendCommand('Input.insertText', { text } satisfies CdpInsertTextParams),
372
+ timeoutMs,
373
+ signal,
374
+ `browser: type timed out after ${timeoutMs}ms`,
375
+ )
376
+ } catch (error) {
377
+ throw new BrowserError(`browser: type failed: ${String(error)}`, 'BROWSER_TYPE_FAILED', { cause: error })
378
+ }
379
+ // Store the full text so replay re-issues the same input; the history
380
+ // tool truncates long values when rendering.
381
+ this.record(s, 'type', { text, ...hasTarget ? { target: request.target } : {} }, true)
382
+ }
383
+
384
+ /** Scroll the page: by deltas, to a selector, or to top/bottom. */
385
+ async scroll(session: BrowserSessionId, request: BrowserScrollRequest, signal?: AbortSignal): Promise<void> {
386
+ const s = this.session(session)
387
+ const tab = this.activeTab(s)
388
+ signal?.throwIfAborted()
389
+ const selector = request.selector ?? ''
390
+ const script = `(() => {${DEEP_DOM_SOURCE}
391
+ const sel = ${JSON.stringify(selector)}
392
+ if (sel !== '') {
393
+ const el = __dshQuery(sel)
394
+ if (!el) return { ok: false, reason: 'selector not found' }
395
+ el.scrollIntoView({ behavior: 'instant', block: 'center' })
396
+ return { ok: true }
397
+ }
398
+ if (${request.toTop === true}) { window.scrollTo(0, 0); return { ok: true } }
399
+ if (${request.toBottom === true}) { window.scrollTo(0, document.body.scrollHeight); return { ok: true } }
400
+ window.scrollBy({ top: ${request.deltaY ?? 0}, left: ${request.deltaX ?? 0} })
401
+ return { ok: true }
402
+ })()`
403
+ const timeoutMs = PROVIDER_TIMEOUTS.action
404
+ const result = await withTimeout(
405
+ handleSendEvaluate(tab.handle, script),
406
+ timeoutMs,
407
+ signal,
408
+ `browser: scroll timed out after ${timeoutMs}ms`,
409
+ timedOut => { this.interrupt(tab.handle, timedOut) },
410
+ )
411
+ if (!result.ok) throw new BrowserError(`browser: scroll failed: ${result.exception}`, 'BROWSER_SCROLL_FAILED')
412
+ const value = result.value as { ok?: boolean; reason?: string }
413
+ if (value.ok !== true) throw new BrowserError(`browser: scroll failed: ${value.reason ?? 'unknown'}`, 'BROWSER_SCROLL_FAILED')
414
+ this.record(s, 'scroll', { ...request }, true)
415
+ }
416
+
417
+ /** Press one named key (Enter/Tab/arrows/…) via CDP key events. */
418
+ async key(session: BrowserSessionId, request: BrowserKeyRequest, signal?: AbortSignal): Promise<void> {
419
+ const s = this.session(session)
420
+ signal?.throwIfAborted()
421
+ const spec = KEY_SPECS[request.key]
422
+ if (spec === undefined) {
423
+ throw new BrowserError(`browser: unsupported key "${request.key}" (supported: ${BROWSER_KEY_NAMES.join(', ')})`, 'BROWSER_KEY_UNSUPPORTED')
424
+ }
425
+ const params = { key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.vk, nativeVirtualKeyCode: spec.vk, ...spec.text !== undefined ? { text: spec.text } : {} }
426
+ const timeoutMs = PROVIDER_TIMEOUTS.action
427
+ // Input.dispatchKeyEvent is subject to the same display-surface rule. The handle comes
428
+ // back from the presentation barrier rather than from a capture taken before it: this
429
+ // session is shared with the human, who may switch tabs while the barrier round-trips,
430
+ // and a key sent to the view they left is silently dropped (or lands on the new page).
431
+ const handle = await this.present(s, signal)
432
+ // Focus the SAME view the key is dispatched to; focusing the pre-switch handle would
433
+ // grant web focus to a page that then receives nothing.
434
+ await this.focusView(handle)
435
+ const release = (): Promise<Record<string, unknown>> =>
436
+ handle.sendCommand('Input.dispatchKeyEvent', { type: 'keyUp', ...params })
437
+ try {
438
+ await withTimeout(handle.sendCommand('Input.dispatchKeyEvent', { type: 'keyDown', ...params }), timeoutMs, signal, `browser: key press timed out after ${timeoutMs}ms`)
439
+ } catch (error) {
440
+ // The press may still land late; release best-effort so the key is
441
+ // never left in a stuck pressed state.
442
+ void release().catch(() => {})
443
+ throw new BrowserError(`browser: key "${request.key}" failed: ${String(error)}`, 'BROWSER_KEY_FAILED', { cause: error })
444
+ }
445
+ try {
446
+ await withTimeout(release(), timeoutMs, signal, `browser: key release timed out after ${timeoutMs}ms`)
447
+ } catch (error) {
448
+ // The press already landed; retry the release before surfacing.
449
+ void release().catch(() => {})
450
+ throw new BrowserError(`browser: key "${request.key}" failed: ${String(error)}`, 'BROWSER_KEY_FAILED', { cause: error })
451
+ }
452
+ this.record(s, 'key', { key: request.key }, true)
453
+ }
454
+
455
+ /**
456
+ * Fill a form's fields in one batch. Runs one page-context script that
457
+ * resolves each field (selector, or name/label/placeholder among visible
458
+ * controls), sets its value with the native prototype setter (React/Vue
459
+ * controlled inputs included) plus input/change events, handles
460
+ * select/checkbox/radio/contenteditable, and optionally submits the form.
461
+ */
462
+ async fillForm(session: BrowserSessionId, request: BrowserFillRequest, signal?: AbortSignal): Promise<BrowserFillResult> {
463
+ const s = this.session(session)
464
+ const tab = this.activeTab(s)
465
+ signal?.throwIfAborted()
466
+ const specs = JSON.stringify(request.fields.map(f => ({
467
+ selector: f.selector ?? null,
468
+ name: f.name ?? null,
469
+ label: f.label ?? null,
470
+ placeholder: f.placeholder ?? null,
471
+ // A field with NO kind is a field with no kind FILTER: absent, not 'text'. Defaulting
472
+ // it to 'text' here made `if (spec.kind)` above always true, so every unspecified
473
+ // field was narrowed to an <input> — dsh_browser_fill on a <textarea> reported
474
+ // `no "text" control matched`, and a contenteditable could not match any kind at all.
475
+ // The value stays a string or null (never undefined): the in-page check tests truthiness,
476
+ // and JSON drops an undefined member entirely, which is the same thing here.
477
+ kind: f.kind ?? null,
478
+ value: f.value,
479
+ })))
480
+ const submitFlag = request.submit === true
481
+ const script = `(() => {
482
+ const specs = ${specs}
483
+ const out = []
484
+ const setNative = (el, proto, value) => {
485
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
486
+ if (setter) setter.call(el, value)
487
+ else el.value = value
488
+ }
489
+ const visible = (el) => {
490
+ const r = el.getBoundingClientRect()
491
+ const cs = getComputedStyle(el)
492
+ return r.width >= 4 && r.height >= 4 && cs.visibility !== 'hidden' && cs.display !== 'none'
493
+ }
494
+ const describe = (spec) => spec.selector || spec.name || spec.label || spec.placeholder || '(unspecified)'
495
+ const matches = (el, spec) => {
496
+ if (spec.selector) { try { return el.matches(spec.selector) } catch { return false } }
497
+ if (spec.name && el.name === spec.name) return true
498
+ if (spec.placeholder && el.placeholder === spec.placeholder) return true
499
+ if (spec.label) {
500
+ if (el.getAttribute('aria-label') === spec.label) return true
501
+ if (el.id) {
502
+ const lbl = (el.getRootNode().querySelector ? el.getRootNode() : document).querySelector('label[for=' + JSON.stringify(el.id) + ']')
503
+ if (lbl && (lbl.textContent || '').trim() === spec.label) return true
504
+ }
505
+ const wrap = el.closest('label')
506
+ if (wrap && (wrap.textContent || '').trim() === spec.label) return true
507
+ }
508
+ return false
509
+ }
510
+ // Every root this page exposes: the top document plus its shadow trees (recursively)
511
+ // and same-origin iframes. The snapshot and waitFor already walk all of them, so an
512
+ // element inside one is shown to the model and can be waited for — resolving a click or
513
+ // a fill used to look at the top document alone and answer "not found" for something
514
+ // the model had just been handed a reference to. The two must agree about what exists.
515
+ // (Kept in step with the collector in the snapshot script above.)
516
+ const allRoots = () => {
517
+ const roots = []
518
+ const seen = new Set()
519
+ const visit = doc => {
520
+ if (seen.has(doc)) return
521
+ seen.add(doc)
522
+ roots.push(doc)
523
+ for (const el of doc.querySelectorAll('*')) {
524
+ if (el.shadowRoot) visit(el.shadowRoot)
525
+ if (el.tagName === 'IFRAME') {
526
+ try { const d = el.contentDocument; if (d) visit(d) } catch { /* cross-origin */ }
527
+ }
528
+ }
529
+ }
530
+ visit(document)
531
+ return roots
532
+ }
533
+ const roots = allRoots()
534
+ const candidates = (spec) => {
535
+ const all = spec.selector
536
+ ? roots.flatMap(root => [...root.querySelectorAll(spec.selector)])
537
+ : roots.flatMap(root => [...root.querySelectorAll('input, textarea, select, [contenteditable="true"]')]).filter(el => matches(el, spec))
538
+ const vis = all.filter(visible)
539
+ return vis.length > 0 ? vis : all
540
+ }
541
+ for (const spec of specs) {
542
+ let els
543
+ try {
544
+ els = candidates(spec)
545
+ } catch (e) {
546
+ // A malformed selector must not abort the whole batch; report the
547
+ // field as failed and continue with the rest.
548
+ out.push({ ok: false, error: String(e), target: describe(spec) })
549
+ continue
550
+ }
551
+ if (els.length === 0) { out.push({ ok: false, error: 'field not found', target: describe(spec) }); continue }
552
+ let el = els[0]
553
+ // The caller may name a kind. Honor it: the branches below read the element's own
554
+ // tag/type, so without this a selector matching two different controls acted on
555
+ // whichever came first — usually right, which is what hid the mistake. A field that
556
+ // names NO kind gets no filter at all: the element's own tag then decides the
557
+ // branch, which is what "kind defaults to text" was always trying to say.
558
+ if (spec.kind) {
559
+ const matchesKind = (node) => {
560
+ const nodeTag = node.tagName
561
+ const nodeType = (node.type || '').toLowerCase()
562
+ if (spec.kind === 'select') return nodeTag === 'SELECT'
563
+ if (spec.kind === 'textarea') return nodeTag === 'TEXTAREA'
564
+ if (spec.kind === 'checkbox' || spec.kind === 'radio') return nodeType === spec.kind
565
+ // 'text': the plain-value branch covers <input> AND <textarea>, and the batch
566
+ // already collects [contenteditable="true"] as a settable control — so all three
567
+ // must match. Requiring nodeTag === 'INPUT' here reported "no text control
568
+ // matched" for a textarea and left the contenteditable branch below unreachable.
569
+ if (nodeTag === 'TEXTAREA') return true
570
+ if (node.isContentEditable === true) return true
571
+ return nodeTag === 'INPUT' && nodeType !== 'checkbox' && nodeType !== 'radio' && nodeType !== 'file'
572
+ }
573
+ const wanted = els.find(matchesKind)
574
+ if (wanted === undefined) {
575
+ out.push({ ok: false, error: 'no "' + spec.kind + '" control matched', target: describe(spec) })
576
+ continue
577
+ }
578
+ els.length = 0
579
+ els.push(wanted)
580
+ // el was bound before the filter narrowed els, so the branches below would still
581
+ // read the first match — the very silent wrong-element behaviour this filter exists
582
+ // to remove.
583
+ el = els[0]
584
+ }
585
+ const tag = el.tagName
586
+ const type = (el.type || '').toLowerCase()
587
+ try {
588
+ if (tag === 'SELECT') {
589
+ const wanted = String(spec.value)
590
+ if (el.multiple) {
591
+ const wantedList = wanted.split(',').map(x => x.trim())
592
+ let hit = false
593
+ for (const o of [...el.options]) {
594
+ o.selected = wantedList.includes(o.value) || wantedList.includes((o.textContent || '').trim())
595
+ if (o.selected) hit = true
596
+ }
597
+ if (!hit) { out.push({ ok: false, error: 'option not found: ' + wanted, target: describe(spec) }); continue }
598
+ } else {
599
+ let opt = [...el.options].find(o => o.value === wanted)
600
+ if (!opt) opt = [...el.options].find(o => (o.textContent || '').trim() === wanted)
601
+ if (!opt) { out.push({ ok: false, error: 'option not found: ' + wanted, target: describe(spec) }); continue }
602
+ setNative(el, HTMLSelectElement.prototype, opt.value)
603
+ }
604
+ el.dispatchEvent(new Event('input', { bubbles: true }))
605
+ el.dispatchEvent(new Event('change', { bubbles: true }))
606
+ out.push({ ok: true, method: 'select', target: describe(spec) })
607
+ } else if (type === 'file') {
608
+ out.push({ ok: false, error: 'file inputs cannot be set from script; use dsh_browser_download or ask the human', target: describe(spec) })
609
+ } else if (type === 'checkbox') {
610
+ const want = spec.value === true || spec.value === 'true' || spec.value === 'on'
611
+ if (el.checked !== want) el.click()
612
+ out.push({ ok: true, method: 'checkbox', target: describe(spec) })
613
+ } else if (type === 'radio') {
614
+ const wanted = String(spec.value)
615
+ const radio = [...(el.getRootNode().querySelectorAll ? el.getRootNode() : document).querySelectorAll('input[type="radio"][name=' + JSON.stringify(el.name || '') + ']')]
616
+ .filter(r => r.form === el.form)
617
+ .find(r => r.value === wanted || (r === el && (spec.value === true || spec.value === 'true')))
618
+ if (!radio) { out.push({ ok: false, error: 'radio option not found: ' + wanted, target: describe(spec) }); continue }
619
+ if (!radio.checked) radio.click()
620
+ out.push({ ok: true, method: 'radio', target: describe(spec) })
621
+ } else if (el.isContentEditable) {
622
+ el.textContent = String(spec.value)
623
+ el.dispatchEvent(new Event('input', { bubbles: true }))
624
+ out.push({ ok: true, method: 'contenteditable', target: describe(spec) })
625
+ } else if (tag === 'TEXTAREA') {
626
+ setNative(el, HTMLTextAreaElement.prototype, String(spec.value))
627
+ el.dispatchEvent(new Event('input', { bubbles: true }))
628
+ el.dispatchEvent(new Event('change', { bubbles: true }))
629
+ out.push({ ok: true, method: 'textarea', target: describe(spec) })
630
+ } else {
631
+ setNative(el, HTMLInputElement.prototype, String(spec.value))
632
+ el.dispatchEvent(new Event('input', { bubbles: true }))
633
+ el.dispatchEvent(new Event('change', { bubbles: true }))
634
+ out.push({ ok: true, method: 'input', target: describe(spec) })
635
+ }
636
+ } catch (e) {
637
+ out.push({ ok: false, error: String(e), target: describe(spec) })
638
+ }
639
+ }
640
+ let submitted = false
641
+ if (${submitFlag}) {
642
+ let last = null
643
+ for (const spec of specs) {
644
+ try { const els = candidates(spec); if (els.length > 0) { last = els[0]; break } } catch { /* skip */ }
645
+ }
646
+ const form = last && (last.form || last.closest('form'))
647
+ if (form) { form.requestSubmit(); submitted = true }
648
+ }
649
+ return { fields: out, submitted }
650
+ })()`
651
+ const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
652
+ const result = await withTimeout(
653
+ handleSendEvaluate(tab.handle, script),
654
+ timeoutMs,
655
+ signal,
656
+ `browser: fillForm timed out after ${timeoutMs}ms`,
657
+ timedOut => { this.interrupt(tab.handle, timedOut) },
658
+ )
659
+ if (!result.ok) {
660
+ throw new BrowserError(`browser: fillForm evaluation failed: ${result.exception}`, 'BROWSER_FILL_FAILED')
661
+ }
662
+ const value = result.value as BrowserFillResult
663
+ const okCount = value.fields.filter(f => f.ok).length
664
+ this.record(s, 'fill', { fields: request.fields.length, submit: submitFlag }, okCount === value.fields.length, {
665
+ result: `${okCount}/${value.fields.length} fields filled${value.submitted ? ', form submitted' : ''}`,
666
+ })
667
+ return { fields: value.fields, submitted: value.submitted === true }
668
+ }
669
+
670
+ /**
671
+ * Build an in-page async IIFE that locates ONE element by css/text/xpath
672
+ * (polling until it appears or the budget runs out) and then runs `body`
673
+ * with `el` in scope. Shared by the target-based tools: click/type (②),
674
+ * setValue/check/select/clear/getValue (③), and the scrape item wait.
675
+ * A selector that fails to PARSE is reported immediately instead of being
676
+ * polled until the budget expires — see the comment in `match`.
677
+ */
678
+ private buildTargetScript(spec: BrowserElementTarget, timeoutMs: number, body: string): TargetScript {
679
+ // `by` defaults to css in-page; report the strategy that WAS used, or a
680
+ // miss says only `{"value":"Learn more"}` and the caller cannot tell that a
681
+ // plain label was queried as a CSS selector.
682
+ const resolvedSpec = { ...spec, by: spec.by ?? 'css' }
683
+ return (sliceMs, last) => `(async () => {
684
+ const spec = ${JSON.stringify(resolvedSpec)}
685
+ const timeoutMs = ${String(timeoutMs)}
686
+ const sliceMs = ${String(sliceMs)}
687
+ const last = ${String(last)}
688
+ const sleep = ms => new Promise(r => setTimeout(r, ms))
689
+ const isVisible = el => el instanceof HTMLElement && (el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0)
690
+ const ownText = el => Array.from(el.childNodes).filter(n => n.nodeType === Node.TEXT_NODE).map(n => n.textContent || '').join('').trim()
691
+ const depth = el => { let d = 0; let p = el.parentElement; while (p) { d++; p = p.parentElement } return d }
692
+ const match = () => {
693
+ const by = typeof spec.by === 'string' ? spec.by : 'css'
694
+ const value = String(spec.value ?? '')
695
+ // Named matchIndex rather than index: this whole function is one host-side template
696
+ // literal, so a bare name declared here can silently shadow a host binding of the
697
+ // same name and turn an inner reference into a type error.
698
+ const matchIndex = typeof spec.index === 'number' ? spec.index : 0
699
+ // An index that cannot address an element can never match on a later poll, exactly
700
+ // like a selector that fails to parse — so it must not look like a miss either. A
701
+ // negative index, the common "last one" shorthand, otherwise burned the caller's
702
+ // whole locate budget (10s) and then reported "element not found", which reads like a
703
+ // slow page rather than a bad argument.
704
+ // (No backticks in this comment: it lives inside a template literal.)
705
+ if (!Number.isInteger(matchIndex) || matchIndex < 0) {
706
+ throw new Error('target.index must be a non-negative integer, got ' + JSON.stringify(spec.index))
707
+ }
708
+ let els = []
709
+ // Every root this page exposes: the top document plus its shadow trees (recursively)
710
+ // and same-origin iframes. The snapshot and waitFor already walk all of them, so an
711
+ // element inside one is shown to the model and can be waited for — resolving a click or
712
+ // a fill used to look at the top document alone and answer "not found" for something
713
+ // the model had just been handed a reference to. The two must agree about what exists.
714
+ // (Kept in step with the collector in the snapshot script above.)
715
+ const allRoots = () => {
716
+ const roots = []
717
+ const seen = new Set()
718
+ const visit = doc => {
719
+ if (seen.has(doc)) return
720
+ seen.add(doc)
721
+ roots.push(doc)
722
+ for (const el of doc.querySelectorAll('*')) {
723
+ if (el.shadowRoot) visit(el.shadowRoot)
724
+ if (el.tagName === 'IFRAME') {
725
+ try { const d = el.contentDocument; if (d) visit(d) } catch { /* cross-origin */ }
726
+ }
727
+ }
728
+ }
729
+ visit(document)
730
+ return roots
731
+ }
732
+ const roots = allRoots()
733
+ if (by === 'css') {
734
+ // A selector that does not PARSE can never match on a later poll, so
735
+ // it must not look like a miss: the old "return null" kept the caller
736
+ // polling until the whole budget was gone, and "element not found
737
+ // after 10s" reads like a slow page while the real cause is a
738
+ // malformed selector (a label or plain text passed where one belongs).
739
+ // Parse on the top document first: a selector that does not PARSE must still be
740
+ // reported as a bad argument rather than as a miss, and that check is about syntax,
741
+ // not about which root holds the element.
742
+ try { document.querySelectorAll(value) }
743
+ catch (error) { throw new Error('invalid CSS selector ' + JSON.stringify(value) + ' (' + String((error && error.message) || error) + ')') }
744
+ for (const root of roots) els.push(...root.querySelectorAll(value))
745
+ } else if (by === 'xpath') {
746
+ try {
747
+ for (const root of roots) {
748
+ const snap = document.evaluate(value, root, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
749
+ for (let i = 0; i < snap.snapshotLength; i++) {
750
+ const n = snap.snapshotItem(i)
751
+ if (n instanceof Element) els.push(n)
752
+ }
753
+ }
754
+ } catch (error) { throw new Error('invalid XPath ' + JSON.stringify(value) + ' (' + String((error && error.message) || error) + ')') }
755
+ } else {
756
+ // '*' rather than 'body *': a shadow root and an iframe document have no body of
757
+ // their own to anchor to, and the visibility and own-text predicates below are what
758
+ // actually decide whether an element counts.
759
+ const all = roots.flatMap(root => [...root.querySelectorAll('*')])
760
+ const exact = all.filter(el => isVisible(el) && ownText(el) === value)
761
+ // Exact first, then contains; deepest element preferred (so a
762
+ // button inside a card wins over the card itself).
763
+ const pool = exact.length > 0 ? exact : all.filter(el => isVisible(el) && ownText(el).includes(value))
764
+ els = pool.sort((a, b) => depth(b) - depth(a))
765
+ }
766
+ return els[matchIndex] ?? null
767
+ }
768
+ const deadline = Date.now() + sliceMs
769
+ let el = null
770
+ for (;;) {
771
+ // Only a parse error escapes the poll: see the comment in match() above.
772
+ try { el = match() } catch (error) { return { ok: false, error: String((error && error.message) || error) } }
773
+ if (el !== null) break
774
+ if (Date.now() >= deadline && !last) return { pending: true }
775
+ if (Date.now() >= deadline) return { ok: false, error: 'element not found: ' + JSON.stringify(spec) + ' (looked for ' + timeoutMs + 'ms)' }
776
+ await sleep(100)
777
+ }
778
+ const __result = await (async () => {
779
+ ${body}
780
+ })()
781
+ // Report the operated element's viewport center next to the script's own
782
+ // verdict: the synthetic cursor (and any future feedback) needs the point,
783
+ // and no individual body should have to compute it a second time. Kept
784
+ // under a distinct key so a body that already returns x/y keeps them.
785
+ const __rect = el.getBoundingClientRect()
786
+ return {
787
+ ...(typeof __result === 'object' && __result !== null ? __result : { ok: true }),
788
+ __point: { x: Math.round(__rect.x + __rect.width / 2), y: Math.round(__rect.y + __rect.height / 2) },
789
+ }
790
+ })()`
791
+ }
792
+
793
+ /**
794
+ * Shared evaluate wrapper for the target-based tools. Runs the in-page
795
+ * script and returns its result object; throws a typed BrowserError on
796
+ * evaluation failure or an in-page `{ ok: false, error }` verdict.
797
+ */
798
+ private async runTargetScript(
799
+ tab: Tab,
800
+ script: TargetScript,
801
+ timeoutMs: number,
802
+ signal: AbortSignal | undefined,
803
+ errorCode: string,
804
+ errorLabel: string,
805
+ ): Promise<Record<string, unknown>> {
806
+ // Each slice polls in-page and answers only afterwards, so its outer budget must outlast it or
807
+ // the generic timeout hides the in-page reason (selector not found / malformed).
808
+ const deadline = Date.now() + timeoutMs
809
+ let value: { ok?: boolean; pending?: boolean; error?: string } | undefined
810
+ do {
811
+ const { sliceMs, last } = pagePollSlice(deadline)
812
+ const result = await withTimeout(
813
+ handleSendEvaluate(tab.handle, script(sliceMs, last)),
814
+ Math.max(sliceMs, deadline - Date.now()) + TARGET_SCRIPT_GRACE_MS,
815
+ signal,
816
+ `${errorLabel} timed out after ${timeoutMs}ms`,
817
+ timedOut => { this.interrupt(tab.handle, timedOut) },
818
+ )
819
+ if (!result.ok) throw new BrowserError(`${errorLabel} failed: ${result.exception}`, errorCode)
820
+ value = result.value as typeof value
821
+ } while (value?.pending === true)
822
+ if (value?.ok !== true) throw new BrowserError(`${errorLabel} failed: ${value?.error ?? 'unknown'}`, errorCode)
823
+ return value as Record<string, unknown>
824
+ }
825
+
826
+ /** Set one element's value (native setter + input/change, React-friendly). */
827
+ async setValue(session: BrowserSessionId, request: BrowserSetValueRequest, signal?: AbortSignal): Promise<BrowserSetValueResult> {
828
+ const s = this.session(session)
829
+ const tab = this.activeTab(s)
830
+ signal?.throwIfAborted()
831
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
832
+ const body = `
833
+ const value = ${JSON.stringify(String(request.value))}
834
+ const setNative = (el, proto, v) => {
835
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
836
+ if (setter) setter.call(el, v)
837
+ else el.value = v
838
+ }
839
+ const tag = el.tagName
840
+ const type = (el.type || '').toLowerCase()
841
+ if (tag === 'SELECT') {
842
+ const wanted = value
843
+ let opt = [...el.options].find(o => o.value === wanted)
844
+ if (!opt) opt = [...el.options].find(o => (o.textContent || '').trim() === wanted)
845
+ if (!opt) return { ok: false, error: 'option not found: ' + wanted }
846
+ setNative(el, HTMLSelectElement.prototype, opt.value)
847
+ el.dispatchEvent(new Event('input', { bubbles: true }))
848
+ el.dispatchEvent(new Event('change', { bubbles: true }))
849
+ return { ok: true, method: 'select', value: opt.value }
850
+ }
851
+ if (el.isContentEditable) {
852
+ el.textContent = value
853
+ el.dispatchEvent(new Event('input', { bubbles: true }))
854
+ return { ok: true, method: 'contenteditable', value }
855
+ }
856
+ if (tag === 'TEXTAREA') {
857
+ setNative(el, HTMLTextAreaElement.prototype, value)
858
+ el.dispatchEvent(new Event('input', { bubbles: true }))
859
+ el.dispatchEvent(new Event('change', { bubbles: true }))
860
+ return { ok: true, method: 'textarea', value }
861
+ }
862
+ setNative(el, HTMLInputElement.prototype, value)
863
+ el.dispatchEvent(new Event('input', { bubbles: true }))
864
+ el.dispatchEvent(new Event('change', { bubbles: true }))
865
+ return { ok: true, method: 'input', value }
866
+ `
867
+ const script = this.buildTargetScript(request.target, timeoutMs, body)
868
+ const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_SET_VALUE_FAILED', 'browser: setValue')
869
+ const cursorPoint = scriptPoint(out)
870
+ if (cursorPoint !== undefined) this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click')
871
+ this.record(s, 'setValue', { target: request.target, value: String(request.value) }, true, { result: out.method as string })
872
+ return { method: out.method as string, value: out.value as string }
873
+ }
874
+
875
+ /** Check or uncheck one checkbox/radio. */
876
+ async check(session: BrowserSessionId, request: BrowserCheckRequest, signal?: AbortSignal): Promise<{ readonly checked: boolean }> {
877
+ const s = this.session(session)
878
+ const tab = this.activeTab(s)
879
+ signal?.throwIfAborted()
880
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
881
+ const want = request.checked ?? true
882
+ const body = `
883
+ const want = ${String(want)}
884
+ const type = (el.type || '').toLowerCase()
885
+ if (type === 'checkbox') {
886
+ if (el.checked !== want) el.click()
887
+ return { ok: true, checked: el.checked }
888
+ }
889
+ if (type === 'radio') {
890
+ if (want && !el.checked) el.click()
891
+ return { ok: true, checked: el.checked }
892
+ }
893
+ return { ok: false, error: 'element is not a checkbox or radio (' + el.tagName + ')' }
894
+ `
895
+ const script = this.buildTargetScript(request.target, timeoutMs, body)
896
+ const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_CHECK_FAILED', 'browser: check')
897
+ const cursorPoint = scriptPoint(out)
898
+ if (cursorPoint !== undefined) this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click')
899
+ this.record(s, 'check', { target: request.target, checked: want }, true)
900
+ return { checked: out.checked === true }
901
+ }
902
+
903
+ /** Select one option of a <select>, by value, visible text, or index. */
904
+ async selectOption(session: BrowserSessionId, request: BrowserSelectRequest, signal?: AbortSignal): Promise<BrowserSelectResult> {
905
+ const s = this.session(session)
906
+ const tab = this.activeTab(s)
907
+ signal?.throwIfAborted()
908
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
909
+ const body = `
910
+ if (el.tagName !== 'SELECT') return { ok: false, error: 'element is not a <select> (' + el.tagName + ')' }
911
+ const optionValue = ${JSON.stringify(request.optionValue ?? null)}
912
+ const optionText = ${JSON.stringify(request.optionText ?? null)}
913
+ const optionIndex = ${String(request.optionIndex ?? -1)}
914
+ let opt = null
915
+ if (optionValue !== null) opt = [...el.options].find(o => o.value === optionValue)
916
+ if (!opt && optionText !== null) opt = [...el.options].find(o => (o.textContent || '').trim() === optionText)
917
+ if (!opt && optionIndex >= 0) opt = el.options[optionIndex] ?? null
918
+ if (!opt) return { ok: false, error: 'option not found' }
919
+ const setNative = (el, proto, v) => {
920
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
921
+ if (setter) setter.call(el, v)
922
+ else el.value = v
923
+ }
924
+ setNative(el, HTMLSelectElement.prototype, opt.value)
925
+ el.dispatchEvent(new Event('input', { bubbles: true }))
926
+ el.dispatchEvent(new Event('change', { bubbles: true }))
927
+ return { ok: true, value: opt.value, text: (opt.textContent || '').trim() }
928
+ `
929
+ const script = this.buildTargetScript(request.target, timeoutMs, body)
930
+ const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_SELECT_FAILED', 'browser: select')
931
+ const cursorPoint = scriptPoint(out)
932
+ if (cursorPoint !== undefined) this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click')
933
+ this.record(s, 'select', { target: request.target, optionValue: request.optionValue ?? null, optionText: request.optionText ?? null, optionIndex: request.optionIndex ?? null }, true)
934
+ return { value: out.value as string, text: out.text as string }
935
+ }
936
+
937
+ /** Clear one input/textarea/contenteditable (or uncheck a checkbox/radio). */
938
+ async clearField(session: BrowserSessionId, request: BrowserClearRequest, signal?: AbortSignal): Promise<{ readonly cleared: boolean }> {
939
+ const s = this.session(session)
940
+ const tab = this.activeTab(s)
941
+ signal?.throwIfAborted()
942
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
943
+ const body = `
944
+ const setNative = (el, proto) => {
945
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
946
+ if (setter) setter.call(el, '')
947
+ else el.value = ''
948
+ }
949
+ if (el.isContentEditable) {
950
+ el.textContent = ''
951
+ el.dispatchEvent(new Event('input', { bubbles: true }))
952
+ } else if (el.tagName === 'TEXTAREA') {
953
+ setNative(el, HTMLTextAreaElement.prototype)
954
+ el.dispatchEvent(new Event('input', { bubbles: true }))
955
+ el.dispatchEvent(new Event('change', { bubbles: true }))
956
+ } else if (el.tagName === 'INPUT' && (el.type === 'checkbox' || el.type === 'radio')) {
957
+ if (el.checked) el.click()
958
+ } else {
959
+ setNative(el, HTMLInputElement.prototype)
960
+ el.dispatchEvent(new Event('input', { bubbles: true }))
961
+ el.dispatchEvent(new Event('change', { bubbles: true }))
962
+ }
963
+ return { ok: true }
964
+ `
965
+ const script = this.buildTargetScript(request.target, timeoutMs, body)
966
+ const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_CLEAR_FAILED', 'browser: clear')
967
+ const cursorPoint = scriptPoint(out)
968
+ if (cursorPoint !== undefined) this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click')
969
+ this.record(s, 'clear', { target: request.target }, true)
970
+ return { cleared: true }
971
+ }
972
+
973
+ /** Read one element's current value (for verification). */
974
+ async getValue(session: BrowserSessionId, request: BrowserGetValueRequest, signal?: AbortSignal): Promise<BrowserGetValueResult> {
975
+ const s = this.session(session)
976
+ const tab = this.activeTab(s)
977
+ signal?.throwIfAborted()
978
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
979
+ const body = `
980
+ const type = (el.type || '').toLowerCase()
981
+ if (type === 'checkbox' || type === 'radio') return { ok: true, value: null, checked: el.checked }
982
+ if (el.tagName === 'SELECT') {
983
+ const o = el.options[el.selectedIndex]
984
+ return { ok: true, value: el.value, selectedText: o ? (o.textContent || '').trim() : null }
985
+ }
986
+ const v = el.value !== undefined ? el.value : el.textContent
987
+ return { ok: true, value: v === undefined || v === null ? null : String(v) }
988
+ `
989
+ const script = this.buildTargetScript(request.target, timeoutMs, body)
990
+ const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_GET_VALUE_FAILED', 'browser: getValue')
991
+ this.record(s, 'getValue', { target: request.target }, true)
992
+ return {
993
+ value: out.value === null || out.value === undefined ? null : String(out.value),
994
+ ...out.checked !== undefined ? { checked: out.checked === true } : {},
995
+ ...out.selectedText !== undefined && out.selectedText !== null ? { selectedText: String(out.selectedText) } : {},
996
+ }
997
+ }
998
+
999
+ /**
1000
+ * Show the synthetic pointer on a view, unless the user switched it off. The
1001
+ * cursor is the "the agent has taken over this tab" signal, so it is painted
1002
+ * for every operation that has a landing point — including DOM-level ones that
1003
+ * move no real pointer.
1004
+ * @param handle - the view to paint into.
1005
+ * @param x - viewport x in CSS pixels.
1006
+ * @param y - viewport y in CSS pixels.
1007
+ * @param action - click pulses a ripple; move only relocates.
1008
+ * @param label - short description of the operation, shown beside the pointer.
1009
+ * @param force - paint even when the pointer is already there (a click ripple must
1010
+ * always play; a bare move need not repeat).
1011
+ */
1012
+ private showCursor(handle: ElectronViewHandle, x: number, y: number, action: CursorAction, label?: string, force = false): Promise<void> {
1013
+ if (this.settingsSource !== undefined && !this.settingsSource().ui.virtualCursor) return Promise.resolve()
1014
+ return paintCursor(handle, x, y, action, (target, expression) => handleSendEvaluate(target, expression), label, force)
1015
+ }
1016
+
1017
+ /** Best-effort bounded wait for the click cursor paint before pointer dispatch. */
1018
+ private async showCursorSettled(handle: ElectronViewHandle, x: number, y: number, action: CursorAction, label?: string, force = false): Promise<void> {
1019
+ if (this.settingsSource !== undefined && !this.settingsSource().ui.virtualCursor) return
1020
+ const pending = this.showCursor(handle, x, y, action, label, force)
1021
+ let timer: ReturnType<typeof setTimeout> | undefined
1022
+ try {
1023
+ await Promise.race([
1024
+ pending,
1025
+ new Promise<void>(resolve => {
1026
+ timer = setTimeout(resolve, 250)
1027
+ timer.unref?.()
1028
+ }),
1029
+ ])
1030
+ } finally {
1031
+ if (timer !== undefined) clearTimeout(timer)
1032
+ }
1033
+ }
1034
+ }