dsh-builtin-browser 0.5.8 → 1.0.1

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 (401) hide show
  1. package/CHANGELOG.md +410 -1
  2. package/README.en.md +16 -64
  3. package/README.md +33 -64
  4. package/assets/browser-carriers.svg +20 -0
  5. package/assets/browser-extension-identity.d.mts +2 -0
  6. package/assets/browser-extension-identity.mjs +2 -0
  7. package/assets/browser-messages.d.mts +5 -0
  8. package/assets/browser-messages.mjs +64 -0
  9. package/assets/browser-panel-locales.d.mts +2 -0
  10. package/assets/browser-panel-locales.mjs +380 -0
  11. package/assets/browser-policy.d.mts +37 -0
  12. package/assets/browser-policy.mjs +37 -0
  13. package/assets/browser-products.d.mts +6 -0
  14. package/assets/browser-products.mjs +76 -0
  15. package/assets/screenshots/1-main.png +0 -0
  16. package/assets/screenshots/2-form-fill.png +0 -0
  17. package/assets/screenshots/3-challenge.png +0 -0
  18. package/browser-extension/constants.mjs +20 -0
  19. package/browser-extension/controller.mjs +293 -0
  20. package/browser-extension/locales.mjs +15 -0
  21. package/browser-extension/manifest.json +12 -0
  22. package/browser-extension/options.html +14 -0
  23. package/browser-extension/options.mjs +9 -0
  24. package/browser-extension/permission-guard.mjs +13 -0
  25. package/browser-extension/worker.mjs +74 -0
  26. package/cordis.patch.yml +23 -48
  27. package/desktop-bridge/desktop-discovery.d.mts +2 -0
  28. package/desktop-bridge/desktop-discovery.mjs +36 -0
  29. package/desktop-bridge/desktop-identity.json +17 -1
  30. package/desktop-bridge/desktop-processes.d.mts +1 -0
  31. package/desktop-bridge/desktop-processes.mjs +15 -0
  32. package/desktop-bridge/guest-proxy.mjs +109 -0
  33. package/desktop-bridge/install.mjs +197 -74
  34. package/desktop-bridge/main.mjs +11 -0
  35. package/desktop-bridge/maintenance-files.d.mts +8 -0
  36. package/desktop-bridge/maintenance-files.mjs +28 -0
  37. package/desktop-bridge/maintenance-progress.ps1 +2 -2
  38. package/desktop-bridge/native-guests.mjs +41 -0
  39. package/desktop-bridge/plugin-browser-bridge.js +618 -370
  40. package/desktop-bridge/profile-loader.mjs +26 -0
  41. package/dist/client.cjs +43167 -0
  42. package/dist/client.d.cts +516 -0
  43. package/dist/client.d.mts +516 -0
  44. package/dist/index.cjs +92 -0
  45. package/dist/index.d.mts +2960 -0
  46. package/dist/index.mjs +24 -0
  47. package/docs/HANDOVER-2026-11-15.md +178 -0
  48. package/docs/README.md +10 -19
  49. package/docs/architecture.md +17 -145
  50. package/docs/child-tabs.md +13 -0
  51. package/docs/desktop-acceptance.md +9 -0
  52. package/docs/development.md +88 -18
  53. package/docs/extension-browser.md +44 -0
  54. package/docs/hardcoding-audit.md +64 -0
  55. package/docs/limitations.md +23 -73
  56. package/docs/pr64-extension-status.md +46 -0
  57. package/docs/pr64-maintenance.md +25 -0
  58. package/docs/pr64-native-children.md +52 -0
  59. package/docs/pr64-native-views.md +60 -0
  60. package/docs/tool-reference.md +87 -11
  61. package/docs/user-guide.md +47 -255
  62. package/docs/why-browser.md +6 -39
  63. package/dsh-host-patch/README.md +60 -0
  64. package/dsh-host-patch/apply.mjs +194 -0
  65. package/dsh-host-patch/legacy-bridge.mjs +53 -0
  66. package/dsh-host-patch/rc3-revision1.json +90 -0
  67. package/dsh-host-patch/rc3-revision2.json +112 -0
  68. package/dsh-host-patch/rc3-revision3.json.gz +0 -0
  69. package/dsh-host-patch/rc3-revision4.json.gz +0 -0
  70. package/dsh-host-patch/rc3-revision5.json.gz +0 -0
  71. package/dsh-host-patch/rc3-revision6.json.gz +0 -0
  72. package/dsh-host-patch/rc3-revision7.json.gz +0 -0
  73. package/dsh-host-patch/rc3-revision8.json.gz +0 -0
  74. package/dsh-host-patch/rc3.json +148 -0
  75. package/dsh-host-patch/rc5-revision1.json +90 -0
  76. package/dsh-host-patch/rc5-revision2.json +112 -0
  77. package/dsh-host-patch/rc5-revision3.json.gz +0 -0
  78. package/dsh-host-patch/rc5-revision4.json.gz +0 -0
  79. package/dsh-host-patch/rc5-revision5.json.gz +0 -0
  80. package/dsh-host-patch/rc5-revision6.json.gz +0 -0
  81. package/dsh-host-patch/rc5-revision7.json.gz +0 -0
  82. package/dsh-host-patch/rc5-revision8.json.gz +0 -0
  83. package/dsh-host-patch/rc5.json +148 -0
  84. package/lib/bridge-compatibility.js +38 -0
  85. package/lib/browser/handles.js +78 -0
  86. package/lib/browser/runtime.js +155 -43
  87. package/lib/browser/takeover-target.js +24 -0
  88. package/lib/browser-electron/authenticated-route.js +23 -0
  89. package/lib/browser-electron/automatic-maintenance.js +394 -51
  90. package/lib/browser-electron/bridge-auto.js +2 -1
  91. package/lib/browser-electron/bridge-connection.js +8 -1
  92. package/lib/browser-electron/bridge-install.js +27 -2
  93. package/lib/browser-electron/bridge-maintenance.js +35 -10
  94. package/lib/browser-electron/bridge-status.js +98 -27
  95. package/lib/browser-electron/desktop-bridge-host.js +193 -560
  96. package/lib/browser-electron/desktop-identity.js +40 -2
  97. package/lib/browser-electron/document-readiness.js +34 -0
  98. package/lib/browser-electron/electron-provision.js +14 -44
  99. package/lib/browser-electron/entry.js +659 -252
  100. package/lib/browser-electron/extension-browser.js +234 -0
  101. package/lib/browser-electron/extension-setup.js +69 -0
  102. package/lib/browser-electron/guest-cookie-jar.LICENSE.txt +32 -0
  103. package/lib/browser-electron/guest-cookie-jar.js +10559 -0
  104. package/lib/browser-electron/guest-cookie-store.js +74 -0
  105. package/lib/browser-electron/guest-css-runtime.js +75 -0
  106. package/lib/browser-electron/guest-css.js +106 -0
  107. package/lib/browser-electron/guest-route.js +603 -0
  108. package/lib/browser-electron/guest-runtime.js +356 -0
  109. package/lib/browser-electron/guest-storage-runtime.js +52 -0
  110. package/lib/browser-electron/guest-storage.js +163 -0
  111. package/lib/browser-electron/history-store.js +2 -1
  112. package/lib/browser-electron/host-main.js +162 -7
  113. package/lib/browser-electron/host-patch-maintenance.js +141 -0
  114. package/lib/browser-electron/http-body.js +22 -0
  115. package/lib/browser-electron/maintenance-broker.js +35 -5
  116. package/lib/browser-electron/maintenance-lifecycle.js +7 -5
  117. package/lib/browser-electron/maintenance-route.js +9 -6
  118. package/lib/browser-electron/open-slot.js +47 -0
  119. package/lib/browser-electron/paths.js +4 -1
  120. package/lib/browser-electron/preferred-browser.js +144 -0
  121. package/lib/browser-electron/preview-route.js +11 -8
  122. package/lib/browser-electron/process-ownership.js +198 -0
  123. package/lib/browser-electron/profile-checkpoint.js +222 -0
  124. package/lib/browser-electron/profile-command.js +60 -0
  125. package/lib/browser-electron/profile-extension.js +126 -0
  126. package/lib/browser-electron/profile-lease.js +157 -0
  127. package/lib/browser-electron/profile-residue.js +61 -0
  128. package/lib/browser-electron/provider.js +719 -262
  129. package/lib/browser-electron/reference-route.js +635 -0
  130. package/lib/browser-electron/remote-host.js +12 -13
  131. package/lib/browser-electron/runtime-route.js +6 -5
  132. package/lib/browser-electron/runtime-status.js +30 -29
  133. package/lib/browser-electron/settings-store.js +10 -5
  134. package/lib/browser-electron/shortcuts-route.js +108 -0
  135. package/lib/browser-electron/sidebar-only-host.js +119 -18
  136. package/lib/browser-electron/startpage-shortcuts.js +172 -0
  137. package/lib/browser-electron/system-browser.js +352 -371
  138. package/lib/browser-electron/windows-system.js +2 -1
  139. package/lib/browser-reference/delivery.js +326 -0
  140. package/lib/browser-reference/entry.js +597 -0
  141. package/lib/browser-reference/export.js +298 -0
  142. package/lib/browser-reference/import.js +295 -0
  143. package/lib/browser-reference/page-script.js +1406 -0
  144. package/lib/browser-reference/service.js +1062 -0
  145. package/lib/browser-reference/store.js +177 -0
  146. package/lib/browser-reference/submission-receipts.js +139 -0
  147. package/lib/browser-reference/text-quote.js +167 -0
  148. package/lib/browser-reference/types.js +11 -0
  149. package/lib/browser-reference/visible.js +311 -0
  150. package/lib/browser-reference/web-sources.js +97 -0
  151. package/lib/index.js +10 -3
  152. package/lib/reference-owner.js +5 -0
  153. package/lib/reference-page.js +12 -0
  154. package/lib/reference-source.js +2 -0
  155. package/lib/reference-text.js +188 -0
  156. package/lib/startpage-settings.js +63 -0
  157. package/lib/startpage.js +44 -0
  158. package/lib/takeover-protocol.js +2 -0
  159. package/lib/tool-browser/code-tool.js +416 -0
  160. package/lib/tool-browser/code-worker.js +872 -0
  161. package/lib/tool-browser/index.js +940 -76
  162. package/lib/tool-browser/page-probe.js +3 -3
  163. package/lib/tool-browser/panel-page.js +95 -0
  164. package/lib/tool-browser/screenshot-image.js +51 -0
  165. package/lib/tool-browser/takeover.js +205 -0
  166. package/lib/types.js +1 -0
  167. package/lib/web-guest.js +26 -0
  168. package/native-host/client.d.mts +17 -0
  169. package/native-host/client.mjs +100 -0
  170. package/native-host/host.mjs +150 -0
  171. package/native-host/identity.d.mts +2 -0
  172. package/native-host/identity.mjs +1 -0
  173. package/native-host/install.mjs +168 -0
  174. package/native-host/protocol.mjs +75 -0
  175. package/package.json +80 -92
  176. package/scripts/build.mjs +66 -0
  177. package/scripts/bundle-host.mjs +28 -0
  178. package/scripts/fix-exports.mjs +50 -0
  179. package/scripts/install-electron.mjs +11 -26
  180. package/scripts/verify-exports.mjs +47 -0
  181. package/scripts/verify-preview-sdk.mjs +93 -0
  182. package/skills/dsh-builtin-browser/SKILL.md +56 -47
  183. package/skills/dsh-builtin-browser/references/batch.md +31 -1
  184. package/skills/dsh-debug-host/SKILL.md +56 -0
  185. package/skills/dsh-debug-self/SKILL.md +50 -0
  186. package/src/bridge-compatibility.ts +39 -0
  187. package/src/browser/handles.ts +89 -0
  188. package/src/browser/runtime.ts +146 -50
  189. package/src/browser/takeover-target.ts +36 -0
  190. package/src/browser/types.ts +19 -7
  191. package/src/browser-electron/authenticated-route.ts +29 -1
  192. package/src/browser-electron/automatic-maintenance.ts +368 -56
  193. package/src/browser-electron/bridge-auto.ts +5 -4
  194. package/src/browser-electron/bridge-connection.ts +20 -2
  195. package/src/browser-electron/bridge-endpoint.ts +3 -3
  196. package/src/browser-electron/bridge-install.ts +40 -4
  197. package/src/browser-electron/bridge-maintenance.ts +42 -14
  198. package/src/browser-electron/bridge-status.ts +94 -23
  199. package/src/browser-electron/desktop-bridge-host.ts +185 -585
  200. package/src/browser-electron/desktop-identity.ts +53 -2
  201. package/src/browser-electron/document-readiness.ts +45 -0
  202. package/src/browser-electron/electron-provision.ts +12 -45
  203. package/src/browser-electron/entry.ts +1299 -882
  204. package/src/browser-electron/ephemeral-profile.ts +1 -1
  205. package/src/browser-electron/extension-browser.ts +223 -0
  206. package/src/browser-electron/extension-setup.ts +67 -0
  207. package/src/browser-electron/guest-cookie-jar.ts +176 -0
  208. package/src/browser-electron/guest-cookie-store.ts +59 -0
  209. package/src/browser-electron/guest-css-runtime.ts +76 -0
  210. package/src/browser-electron/guest-css.ts +68 -0
  211. package/src/browser-electron/guest-route.ts +568 -0
  212. package/src/browser-electron/guest-runtime.ts +357 -0
  213. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  214. package/src/browser-electron/guest-storage.ts +117 -0
  215. package/src/browser-electron/history-store.ts +5 -4
  216. package/src/browser-electron/host-main.ts +156 -11
  217. package/src/browser-electron/host-patch-maintenance.ts +112 -0
  218. package/src/browser-electron/http-body.ts +23 -0
  219. package/src/browser-electron/maintenance-broker.ts +29 -5
  220. package/src/browser-electron/maintenance-lifecycle.ts +14 -9
  221. package/src/browser-electron/maintenance-route.ts +17 -14
  222. package/src/browser-electron/missing-system-browser.ts +2 -2
  223. package/src/browser-electron/open-slot.ts +49 -0
  224. package/src/browser-electron/paths.ts +5 -1
  225. package/src/browser-electron/preferred-browser.ts +120 -0
  226. package/src/browser-electron/preview-route.ts +18 -11
  227. package/src/browser-electron/process-ownership.ts +168 -0
  228. package/src/browser-electron/profile-checkpoint.ts +187 -0
  229. package/src/browser-electron/profile-command.ts +46 -0
  230. package/src/browser-electron/profile-extension.ts +124 -0
  231. package/src/browser-electron/profile-lease.ts +115 -0
  232. package/src/browser-electron/profile-residue.ts +49 -0
  233. package/src/browser-electron/provider.ts +771 -289
  234. package/src/browser-electron/reference-route.ts +608 -0
  235. package/src/browser-electron/remote-host.ts +15 -15
  236. package/src/browser-electron/runtime-route.ts +11 -10
  237. package/src/browser-electron/runtime-status.ts +51 -32
  238. package/src/browser-electron/settings-store.ts +27 -7
  239. package/src/browser-electron/shortcuts-route.ts +112 -0
  240. package/src/browser-electron/sidebar-only-host.ts +118 -19
  241. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  242. package/src/browser-electron/system-browser.ts +309 -338
  243. package/src/browser-electron/windows-system.ts +2 -1
  244. package/src/browser-reference/delivery.ts +384 -0
  245. package/src/browser-reference/entry.ts +631 -0
  246. package/src/browser-reference/export.ts +339 -0
  247. package/src/browser-reference/import.ts +303 -0
  248. package/src/browser-reference/page-script.ts +1537 -0
  249. package/src/browser-reference/service.ts +1315 -0
  250. package/src/browser-reference/store.ts +172 -0
  251. package/src/browser-reference/submission-receipts.ts +122 -0
  252. package/src/browser-reference/text-quote.ts +219 -0
  253. package/src/browser-reference/types.ts +195 -0
  254. package/src/browser-reference/visible.ts +367 -0
  255. package/src/browser-reference/web-sources.ts +103 -0
  256. package/src/client/browser/BrowserController.ts +693 -0
  257. package/src/client/browser/BrowserFrame.ts +78 -0
  258. package/src/client/browser/BrowserNavigation.ts +169 -0
  259. package/src/client/browser/BrowserPage.ts +23 -0
  260. package/src/client/browser/BrowserPersistence.ts +44 -0
  261. package/src/client/browser/IframeImpl.ts +176 -0
  262. package/src/client/browser/child-tabs.ts +14 -0
  263. package/src/client/browser/iframe-reference.ts +67 -0
  264. package/src/client/browser/initialization.ts +262 -0
  265. package/src/client/browser/omnibox.ts +243 -0
  266. package/src/client/browser/store.ts +38 -0
  267. package/src/client/browser/takeover-channel.ts +72 -0
  268. package/src/client/browser/url.ts +46 -0
  269. package/src/client/browser/web-reference-source.ts +52 -0
  270. package/src/client/css-modules.d.ts +4 -0
  271. package/src/client/definition.tsx +30 -0
  272. package/src/client/electron/ElectronWebViewImpl.ts +364 -0
  273. package/src/client/electron/ElectronWebviewPresentation.ts +138 -0
  274. package/src/client/electron/NativeChildPresentation.ts +45 -0
  275. package/src/client/electron/NativeViewPage.ts +251 -0
  276. package/src/client/electron/pages.ts +23 -0
  277. package/src/client/electron/reference-overlay.ts +53 -0
  278. package/src/client/electron/workspace.ts +33 -0
  279. package/src/client/index.ts +293 -0
  280. package/src/client/locales.ts +857 -0
  281. package/src/client/pages.ts +28 -0
  282. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  283. package/src/client/reference/client/draft-reference.ts +167 -0
  284. package/src/client/reference/client/index.ts +7 -0
  285. package/src/client/reference/client/ordered-submission.ts +108 -0
  286. package/src/client/reference/client/pending-delivery.ts +216 -0
  287. package/src/client/reference/client/plugin.ts +189 -0
  288. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  289. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  290. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  291. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  292. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  293. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  294. package/src/client/reference/client/production/assembly.ts +471 -0
  295. package/src/client/reference/client/production/asset-store.ts +144 -0
  296. package/src/client/reference/client/production/availability.ts +74 -0
  297. package/src/client/reference/client/production/bytes.ts +36 -0
  298. package/src/client/reference/client/production/delivery-client.ts +211 -0
  299. package/src/client/reference/client/production/draft-adapter.ts +508 -0
  300. package/src/client/reference/client/production/http-transport.ts +217 -0
  301. package/src/client/reference/client/production/production-submission.ts +310 -0
  302. package/src/client/reference/client/production/protocol.ts +231 -0
  303. package/src/client/reference/client/production/reference-card.ts +240 -0
  304. package/src/client/reference/client/production/reference-labels.ts +29 -0
  305. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  306. package/src/client/reference/client/production/reveal.ts +215 -0
  307. package/src/client/reference/client/production/runtime.ts +1101 -0
  308. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  309. package/src/client/reference/client/production/source-marker.ts +63 -0
  310. package/src/client/reference/client/production/source-opener.ts +55 -0
  311. package/src/client/reference/client/production/styles.ts +104 -0
  312. package/src/client/reference/client/production/user-text-rule.ts +58 -0
  313. package/src/client/reference/client/reveal.ts +107 -0
  314. package/src/client/reference/client/scheme.ts +114 -0
  315. package/src/client/reference/client/types.ts +168 -0
  316. package/src/client/reference/css-modules.d.ts +4 -0
  317. package/src/client/reference/index.ts +11 -0
  318. package/src/client/reference-capture-owner.ts +162 -0
  319. package/src/client/reference-intents.ts +36 -0
  320. package/src/client/settings/index.ts +34 -0
  321. package/{client.js → src/client/settings/panel.ts} +2657 -2231
  322. package/src/client/shortcut-open.ts +30 -0
  323. package/src/client/startpage/binding.ts +99 -0
  324. package/src/client/startpage/controller.ts +303 -0
  325. package/src/client/startpage/model.ts +279 -0
  326. package/src/client/view/Browser.module.css +751 -0
  327. package/src/client/view/BrowserBody.tsx +314 -0
  328. package/src/client/view/BrowserPresentation.ts +9 -0
  329. package/src/client/view/BrowserTitle.tsx +17 -0
  330. package/src/client/view/IframePresentation.ts +344 -0
  331. package/src/client/view/StartPage.tsx +597 -0
  332. package/src/client/view/TakeoverBanner.tsx +21 -0
  333. package/src/index.ts +110 -73
  334. package/src/reference-owner.ts +5 -0
  335. package/src/reference-page.ts +9 -0
  336. package/src/reference-source.ts +3 -0
  337. package/src/reference-text.ts +197 -0
  338. package/src/startpage-settings.ts +103 -0
  339. package/src/startpage.ts +71 -0
  340. package/src/takeover-protocol.ts +19 -0
  341. package/src/tool-browser/code-tool.ts +401 -0
  342. package/src/tool-browser/code-worker.ts +639 -0
  343. package/src/tool-browser/index.ts +908 -77
  344. package/src/tool-browser/page-probe.ts +4 -4
  345. package/src/tool-browser/panel-page.ts +124 -0
  346. package/src/tool-browser/screenshot-image.ts +49 -0
  347. package/src/tool-browser/takeover.ts +198 -0
  348. package/src/types/electron-shim.d.ts +20 -0
  349. package/src/types.ts +85 -0
  350. package/src/web-guest.ts +34 -0
  351. package/tools/accept-desktop.mjs +148 -0
  352. package/lib/browser/runtime.d.ts +0 -175
  353. package/lib/browser/types.d.ts +0 -797
  354. package/lib/browser-electron/authenticated-route.d.ts +0 -27
  355. package/lib/browser-electron/automatic-maintenance.d.ts +0 -41
  356. package/lib/browser-electron/bridge-auto.d.ts +0 -93
  357. package/lib/browser-electron/bridge-connection.d.ts +0 -93
  358. package/lib/browser-electron/bridge-endpoint.d.ts +0 -30
  359. package/lib/browser-electron/bridge-install.d.ts +0 -85
  360. package/lib/browser-electron/bridge-maintenance.d.ts +0 -24
  361. package/lib/browser-electron/bridge-status.d.ts +0 -50
  362. package/lib/browser-electron/desktop-bridge-host.d.ts +0 -248
  363. package/lib/browser-electron/desktop-identity.d.ts +0 -58
  364. package/lib/browser-electron/electron-provision.d.ts +0 -92
  365. package/lib/browser-electron/entry.d.ts +0 -64
  366. package/lib/browser-electron/ephemeral-profile.d.ts +0 -37
  367. package/lib/browser-electron/file-write.d.ts +0 -2
  368. package/lib/browser-electron/history-store.d.ts +0 -98
  369. package/lib/browser-electron/host-main.d.ts +0 -26
  370. package/lib/browser-electron/http-body.d.ts +0 -24
  371. package/lib/browser-electron/json-reply.d.ts +0 -33
  372. package/lib/browser-electron/maintenance-broker.d.ts +0 -35
  373. package/lib/browser-electron/maintenance-lifecycle.d.ts +0 -32
  374. package/lib/browser-electron/maintenance-route.d.ts +0 -18
  375. package/lib/browser-electron/missing-system-browser.d.ts +0 -54
  376. package/lib/browser-electron/paths.d.ts +0 -4
  377. package/lib/browser-electron/preview-route.d.ts +0 -89
  378. package/lib/browser-electron/process.d.ts +0 -14
  379. package/lib/browser-electron/provider.d.ts +0 -959
  380. package/lib/browser-electron/remote-host.d.ts +0 -256
  381. package/lib/browser-electron/rpc-input.d.ts +0 -4
  382. package/lib/browser-electron/rpc-ops.d.ts +0 -18
  383. package/lib/browser-electron/runtime-diagnostics.d.ts +0 -12
  384. package/lib/browser-electron/runtime-route.d.ts +0 -55
  385. package/lib/browser-electron/runtime-status.d.ts +0 -116
  386. package/lib/browser-electron/settings-route.d.ts +0 -15
  387. package/lib/browser-electron/settings-store.d.ts +0 -224
  388. package/lib/browser-electron/sidebar-only-host.d.ts +0 -36
  389. package/lib/browser-electron/system-browser.d.ts +0 -367
  390. package/lib/browser-electron/timing.d.ts +0 -8
  391. package/lib/browser-electron/virtual-cursor.d.ts +0 -67
  392. package/lib/browser-electron/windows-system.d.ts +0 -3
  393. package/lib/index.d.ts +0 -30
  394. package/lib/tool-browser/element-fields.d.ts +0 -145
  395. package/lib/tool-browser/index.d.ts +0 -53
  396. package/lib/tool-browser/page-probe.d.ts +0 -86
  397. package/scripts/consumer-install-check.mjs +0 -72
  398. package/scripts/run-tests.mjs +0 -32
  399. package/scripts/verify-host-compat.mjs +0 -195
  400. package/scripts/verify-preview-route.mjs +0 -168
  401. package/scripts/verify-runtime-status.mjs +0 -179
@@ -1,3 +1,5 @@
1
+ import { DEFAULT_OPERATION_TIMEOUT_MS } from '../../assets/browser-policy.mjs';
2
+ import { hostMessages } from '../../assets/browser-messages.mjs';
1
3
  /**
2
4
  * Electron-backed browser provider: `WebContentsView` sessions driven over
3
5
  * `webContents.debugger` (CDP). The provider itself does not import Electron — it operates through the {@link ElectronBrowserViewHost} seam, which the
@@ -7,14 +9,36 @@
7
9
  * @module dsh-browser/browser-electron
8
10
  */
9
11
  import { pageOperationScript } from '../tool-browser/page-probe.js';
12
+ import { dispatchReferenceCaptureAction } from '../browser-reference/service.js';
13
+ import { MAX_REFERENCE_COMMENT, REFERENCE_INTENT_CHANNEL, overlayScript, standaloneScript, } from '../browser-reference/entry.js';
14
+ import { noticeScript, validateFrozenCapture } from '../browser-reference/page-script.js';
10
15
  import { randomUUID } from 'node:crypto';
16
+ import { setLastOpen } from './open-slot.js';
11
17
  import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs';
12
18
  import { writeFileNoReplace } from './file-write.js';
13
19
  import { homedir } from 'node:os';
14
20
  import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
15
21
  import { HistoryStore } from './history-store.js';
16
22
  import { forgetCursor, paintCursor } from './virtual-cursor.js';
23
+ import { documentReady, mainDocument } from './document-readiness.js';
17
24
  import { BrowserError } from '../browser/types.js';
25
+ import { browserSessionHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId } from '../browser/handles.js';
26
+ /**
27
+ * Consecutive failed evaluations after which the reference pump forgets an
28
+ * adopted sidebar tab. One or two misses are a navigation; five (≈6 s at the
29
+ * pump's 1.2 s tick) mean the page the human had is gone.
30
+ */
31
+ const DEAD_REFERENCE_TAB_MISSES = 5;
32
+ /** How long a tab that stopped answering waits before the pump tries it again. */
33
+ const DEAD_REFERENCE_TAB_RETRY_MS = 15_000;
34
+ const PROVIDER_TIMEOUTS = Object.freeze({
35
+ evaluation: 3_000,
36
+ interaction: 5_000,
37
+ lookup: 10_000,
38
+ action: 15_000,
39
+ prepare: DEFAULT_OPERATION_TIMEOUT_MS + 1_000,
40
+ download: 60_000,
41
+ });
18
42
  /**
19
43
  * Page-context human-verification (CAPTCHA / bot-detection) detection. Runs
20
44
  * inside the page; returns `{ blocked, kind?, reason? }`. Marker-based and
@@ -296,8 +320,40 @@ function realAncestorOf(path) {
296
320
  */
297
321
  export class ElectronBrowserProvider {
298
322
  host;
323
+ config;
299
324
  id = ELECTRON_BROWSER_PROVIDER_ID;
300
325
  sessions = new Map();
326
+ carrierLaunchError;
327
+ /**
328
+ * Tick that installs the selection bar in every live tab and collects what the
329
+ * human confirmed. The Desktop sidebar carrier is the shell's own <webview>:
330
+ * the page has no preload bridge and the bridge protocol carries no user-action
331
+ * channel, so the bar leaves its intent in `window.__dshRefIntents` and this
332
+ * pump takes it over CDP. Without it the sidebar has no reference entry.
333
+ */
334
+ referencePump;
335
+ /** Guards against overlapping pump runs (setInterval keeps firing while one is slow). */
336
+ referencePumping = false;
337
+ /**
338
+ * Set once the carrier swapped to a newer provider. `onUserAction` and
339
+ * `onViewClosed` return void and cannot be unsubscribed, so the callbacks
340
+ * themselves must go inert: otherwise one human click is handled by every
341
+ * old provider still retained by the view host, producing duplicate cards.
342
+ */
343
+ disposed = false;
344
+ /**
345
+ * The session bound to the page the human has open, created on first sight.
346
+ *
347
+ * A reference is captured from a browser SESSION, and a page the human opened from
348
+ * the sidebar's own address bar belongs to no session of ours. Adopting it into one
349
+ * is what makes the selection bar appear there at all — and it is done here, inside
350
+ * the pump, so it needs nothing from the human and nothing from the agent.
351
+ */
352
+ referenceSession;
353
+ /** Ticks between sidebar page scans while nothing is adopted yet. */
354
+ referenceScanCountdown = 0;
355
+ /** Last scan's diagnosis, surfaced by {@link referenceStatus}. */
356
+ referenceScan = { pages: 0 };
301
357
  httpOnly;
302
358
  snapshotMaxElements;
303
359
  contentMaxChars;
@@ -311,6 +367,7 @@ export class ElectronBrowserProvider {
311
367
  settingsSource;
312
368
  constructor(host, config = {}) {
313
369
  this.host = host;
370
+ this.config = config;
314
371
  this.httpOnly = config.httpOnly ?? true;
315
372
  this.snapshotMaxElements = config.snapshotMaxElements ?? 60;
316
373
  this.contentMaxChars = config.contentMaxChars;
@@ -331,10 +388,262 @@ export class ElectronBrowserProvider {
331
388
  });
332
389
  // Route toolbar (host UI) actions into the session model: the human and
333
390
  // the agent then always drive the same tabs, history, and navigation.
334
- this.host.onUserAction?.(action => { void this.handleUserAction(action); });
391
+ this.host.onUserAction?.(action => { if (!this.disposed)
392
+ void this.handleUserAction(action); });
335
393
  // A window the human closed ends the session it showed: the next call opens a
336
394
  // clean one instead of driving a page nobody can see.
337
- this.host.onViewClosed?.(windowId => { void this.handleViewClosed(windowId); });
395
+ this.host.onViewClosed?.(windowId => { if (!this.disposed)
396
+ void this.handleViewClosed(windowId); });
397
+ this.startReferenceEntryPump();
398
+ }
399
+ /** Retire a provider after a carrier swap; its listeners must not act again. */
400
+ dispose() {
401
+ this.disposed = true;
402
+ this.stopReferenceEntryPump();
403
+ }
404
+ /** Start the page-bar pump; idempotent, unref'd so it never holds the process. */
405
+ startReferenceEntryPump() {
406
+ if (this.host.referenceOverlayOwner === 'client' || this.referencePump !== undefined)
407
+ return;
408
+ this.referencePump = setInterval(() => { void this.pumpReferenceEntry(); }, 1200);
409
+ this.referencePump.unref?.();
410
+ }
411
+ /** Stop the pump (session teardown / tests). */
412
+ stopReferenceEntryPump() {
413
+ if (this.referencePump === undefined)
414
+ return;
415
+ clearInterval(this.referencePump);
416
+ this.referencePump = undefined;
417
+ }
418
+ /**
419
+ * Install the bar where it is missing and forward one confirmed intent.
420
+ *
421
+ * Re-injection is what makes this survive navigation: a new document has no
422
+ * `__dshRefOverlayInstalled`, so the next tick installs the bar again.
423
+ *
424
+ * One run at a time: `setInterval` fires again whether or not the previous
425
+ * run finished, and a page that stopped answering would otherwise stack CDP
426
+ * commands behind the wedged renderer on every tick.
427
+ */
428
+ async pumpReferenceEntry() {
429
+ if (this.referencePumping)
430
+ return;
431
+ this.referencePumping = true;
432
+ try {
433
+ await this.adoptSidebarPageForReference().catch(() => undefined);
434
+ for (const session of [...this.sessions.values()]) {
435
+ if (this.host.referenceOverlayOwnerFor?.(session.id) === 'client')
436
+ continue;
437
+ for (const tab of [...session.tabs]) {
438
+ await this.pumpOneTab(session, tab);
439
+ // A tab is never dropped for being unreachable: the page is the
440
+ // person's own sidebar page, and the host excludes every page it
441
+ // adopted from later listings, so letting go of the handle would
442
+ // close our only route back to it.
443
+ }
444
+ }
445
+ }
446
+ finally {
447
+ this.referencePumping = false;
448
+ }
449
+ }
450
+ /**
451
+ * Install or collect on one tab.
452
+ * @returns false when the page failed enough consecutive times to be gone.
453
+ */
454
+ async pumpOneTab(session, tab) {
455
+ if (tab.failure !== undefined)
456
+ return false;
457
+ // A page that stopped answering is retried on a slow timer instead of being
458
+ // dropped: navigations and renderer swaps both look like death for a moment.
459
+ if (tab.retryAt !== undefined && Date.now() < tab.retryAt)
460
+ return true;
461
+ try {
462
+ // One round-trip per tab: a missing bar answers "install"; otherwise the
463
+ // same evaluation hands back a confirmed intent.
464
+ const probe = await this.evaluateInTab(tab, [
465
+ 'window.__dshRefOverlayInstalled !== true ? "install"',
466
+ ': (window.__dshRefTake ? window.__dshRefTake() : null)',
467
+ ].join(''), PROVIDER_TIMEOUTS.evaluation);
468
+ tab.misses = 0;
469
+ tab.retryAt = undefined;
470
+ if (probe === 'install') {
471
+ await this.evaluateInTab(tab, standaloneScript(overlayScript(), {}), PROVIDER_TIMEOUTS.interaction);
472
+ return true;
473
+ }
474
+ if (probe === null || probe === undefined)
475
+ return true;
476
+ try {
477
+ if (typeof probe !== 'object')
478
+ throw new Error('reference intent is invalid');
479
+ const record = probe;
480
+ if (record.type !== REFERENCE_INTENT_CHANNEL)
481
+ throw new Error('reference intent channel is invalid');
482
+ const rawComment = typeof record.comment === 'string' ? record.comment.trim() : '';
483
+ const rawSelection = typeof record.selectionText === 'string' ? record.selectionText.trim() : '';
484
+ const capture = validateFrozenCapture(record.capture);
485
+ if (capture === undefined)
486
+ throw new Error('reference intent has no captured content');
487
+ await this.handleUserAction({
488
+ type: 'capture-reference',
489
+ windowId: session.id,
490
+ entry: 'page-overlay',
491
+ ...rawComment !== '' ? { comment: rawComment.slice(0, MAX_REFERENCE_COMMENT) } : {},
492
+ ...rawSelection !== '' ? { selectionText: rawSelection } : {},
493
+ capture,
494
+ }, true);
495
+ }
496
+ catch (error) {
497
+ this.referenceScan.lastError = 'capture refused: ' + (error instanceof Error ? error.message : String(error));
498
+ process.stderr.write(`[dsh-browser] ${this.referenceScan.lastError}\n`);
499
+ try {
500
+ await this.evaluateInTab(tab, standaloneScript(noticeScript(hostMessages.zh.referenceFailed)), PROVIDER_TIMEOUTS.evaluation);
501
+ }
502
+ catch { /* The failure remains in host diagnostics when the guest disappears. */ }
503
+ }
504
+ return true;
505
+ }
506
+ catch {
507
+ // A tab mid-navigation has no execution context yet; the next tick retries.
508
+ // A page that keeps failing backs off instead of being forgotten: the
509
+ // handle is the only way back to a page this host adopted, and dropping it
510
+ // made the bar stop delivering for the rest of the conversation.
511
+ tab.misses = (tab.misses ?? 0) + 1;
512
+ if (tab.misses >= DEAD_REFERENCE_TAB_MISSES) {
513
+ tab.misses = 0;
514
+ tab.retryAt = Date.now() + DEAD_REFERENCE_TAB_RETRY_MS;
515
+ }
516
+ return true;
517
+ }
518
+ }
519
+ /** Forget one dead adopted tab; the conversation's next page starts a fresh session. */
520
+ /**
521
+ * Bind the page the human has open in this conversation's sidebar into a session.
522
+ *
523
+ * Why this is the whole entry: the sidebar page is the shell's, opened by a person
524
+ * through the address bar, so no session of ours names it and nothing injects the
525
+ * selection bar into it. The shell DOES expose the panel's pages by conversation id
526
+ * (`listPages`), and can hand one over (`adoptPage`) — the same pair the tools use
527
+ * for `dsh_browser_list_tabs`. Doing it on a timer means the bar appears on a page
528
+ * the human opened themselves, which is the only entry they actually take.
529
+ *
530
+ * Rescans are spaced by one idle tick, not five: the listing crosses the
531
+ * bridge, and a page the human just opened must get its entry within a
532
+ * couple of seconds rather than five.
533
+ */
534
+ async adoptSidebarPageForReference() {
535
+ const configured = this.config.referenceLabel;
536
+ const label = typeof configured === 'function' ? configured() : configured;
537
+ this.referenceScan.label = label;
538
+ if (label === undefined || label === '')
539
+ return;
540
+ if (this.host.listPages === undefined || this.host.adoptPage === undefined) {
541
+ this.referenceScan.lastError = 'this carrier cannot list or adopt a page it did not open';
542
+ return;
543
+ }
544
+ if (this.referenceScanCountdown > 0) {
545
+ this.referenceScanCountdown -= 1;
546
+ return;
547
+ }
548
+ // One idle tick between scans: a page the human opens must get its entry
549
+ // within a couple of seconds (measured: the shell creates the guest, then
550
+ // the next scan adopts it). The listing is a local bridge call, not a
551
+ // network request, so this is cheap.
552
+ this.referenceScanCountdown = 1;
553
+ let session = this.referenceSession === undefined ? undefined : this.sessions.get(this.referenceSession);
554
+ if (session?.label !== label)
555
+ session = undefined;
556
+ const candidate = session ?? {
557
+ id: sessionWireId(browserSessionHandle(label, randomUUID())), label,
558
+ tabs: [], activeIndex: 0, history: [], nextSeq: 1,
559
+ };
560
+ let pages;
561
+ try {
562
+ // `requireRunning` is what keeps a scan from launching the human's
563
+ // installed browser: only a carrier that is already up can have pages.
564
+ pages = await this.host.listPages(this.carrierScope(candidate), { requireRunning: true });
565
+ }
566
+ catch (error) {
567
+ this.referenceScan.lastError = error instanceof Error ? error.message : String(error);
568
+ return;
569
+ }
570
+ this.referenceScan.pages = pages.length;
571
+ const live = pages.filter(candidate => /^https?:\/\//iu.test(candidate.url));
572
+ // NOT pruned. The host's listing already EXCLUDES the pages this process
573
+ // adopted (that exclusion is what keeps `listTabs` from reporting one page
574
+ // twice), so "absent from the listing" means "already adopted" as often as
575
+ // it means "closed". Dropping those tabs would lose the bar on every page
576
+ // the human switches away from and re-adopt it under a new handle on the
577
+ // way back. A closed page's handle simply stops answering, and the pump
578
+ // already skips a tab it cannot evaluate.
579
+ if (live.length === 0) {
580
+ this.referenceScan.lastError = 'no http page is open in this conversation\'s sidebar';
581
+ return;
582
+ }
583
+ let refused;
584
+ for (const page of live) {
585
+ const tabId = this.carrierTab(candidate, page.id);
586
+ const existing = session?.tabs.find(tab => tab.id === tabId);
587
+ if (existing !== undefined) {
588
+ // A navigation changes the URL of a page we already hold.
589
+ if (existing.url !== page.url)
590
+ existing.url = page.url;
591
+ continue;
592
+ }
593
+ try {
594
+ // The owner is passed so the adopted view is released with THIS
595
+ // conversation and not swept up by, or lost to, another one.
596
+ const handle = await this.host.adoptPage(this.carrierTab(candidate, page.id), this.carrierScope(candidate));
597
+ if (session === undefined) {
598
+ session = candidate;
599
+ this.sessions.set(session.id, session);
600
+ this.referenceSession = session.id;
601
+ }
602
+ // Append only: discovery must never switch the page the human is
603
+ // looking at, nor open a tab they did not ask for.
604
+ session.tabs.push({ id: tabId, handle, url: page.url });
605
+ }
606
+ catch (error) {
607
+ refused = error instanceof Error ? error.message : String(error);
608
+ }
609
+ }
610
+ if (session !== undefined) {
611
+ session.activeIndex = Math.min(session.activeIndex, Math.max(0, session.tabs.length - 1));
612
+ }
613
+ this.referenceScan.lastError = session === undefined
614
+ ? refused ?? 'no page could be adopted'
615
+ : refused;
616
+ }
617
+ /**
618
+ * What the sidebar reference entry is doing right now.
619
+ *
620
+ * Served on the reference route so "there is no selection bar on my page" has an
621
+ * answer that is not a guess: which conversation this process thinks it serves,
622
+ * whether a page was adopted, how many the shell reported, and the last refusal.
623
+ */
624
+ referenceStatus() {
625
+ return {
626
+ ...this.referenceScan.label === undefined ? {} : { label: this.referenceScan.label },
627
+ ...this.referenceSession === undefined ? {} : { session: this.referenceSession },
628
+ pages: this.referenceScan.pages,
629
+ ...this.referenceScan.lastError === undefined ? {} : { lastError: this.referenceScan.lastError },
630
+ };
631
+ }
632
+ /**
633
+ * Evaluate one expression in a tab and return its value.
634
+ *
635
+ * Bounded on purpose: the pump runs on a timer, and an unresponsive renderer
636
+ * would otherwise hold the whole tick (and every later one) forever.
637
+ * @param tab - the tab to evaluate in.
638
+ * @param expression - the JS expression.
639
+ * @param timeoutMs - how long to wait before treating the page as not answering.
640
+ */
641
+ async evaluateInTab(tab, expression, timeoutMs = PROVIDER_TIMEOUTS.evaluation) {
642
+ const raw = await withTimeout(tab.handle.sendCommand('Runtime.evaluate', {
643
+ expression, returnByValue: true, awaitPromise: true,
644
+ }), timeoutMs, undefined, `browser: reference probe timed out after ${timeoutMs}ms`);
645
+ const result = raw.result;
646
+ return result?.value;
338
647
  }
339
648
  /**
340
649
  * Usable when the host says it can back views (the self-hosted host probes
@@ -356,18 +665,65 @@ export class ElectronBrowserProvider {
356
665
  // The label is the calling DSH task, and it is handed to the view as its owner: a host shared
357
666
  // by several conversations (the desktop's) keeps one conversation's page out of another's on
358
667
  // the strength of it, so it is not decoration.
359
- const handle = this.host.createView(label);
360
- const id = `browser:${randomUUID()}`;
668
+ const id = sessionWireId(browserSessionHandle(label || 'default', randomUUID()));
669
+ const tabId = tabWireId({ ...resolveSessionHandle(id), tab: randomUUID() });
670
+ const handle = this.host.createView(tabId);
361
671
  // Group the session's views under its own window (one window per
362
672
  // session), carrying the label for the window title. Hosts without
363
673
  // groupView keep the shared-window behavior.
364
674
  this.host.groupView?.(handle, id, label);
365
- this.sessions.set(id, { id, label, tabs: [{ id: `tab:${randomUUID()}`, handle, url: '' }], activeIndex: 0, history: [], nextSeq: 1 });
675
+ this.sessions.set(id, { id, label, tabs: [{ id: tabId, handle, url: '' }], activeIndex: 0, history: [], nextSeq: 1 });
366
676
  return Promise.resolve(id);
367
677
  }
368
- /** Open a URL in the active tab (default) or a new tab. */
678
+ async prepareCarrier(signal, scope) {
679
+ if (this.host.prepare === undefined)
680
+ return;
681
+ signal?.throwIfAborted();
682
+ try {
683
+ await withTimeout(this.host.prepare(scope), PROVIDER_TIMEOUTS.prepare, signal, 'browser: carrier launch timed out before navigating a guest');
684
+ this.carrierLaunchError = undefined;
685
+ }
686
+ catch (error) {
687
+ if (!signal?.aborted)
688
+ this.carrierLaunchError = error;
689
+ throw error;
690
+ }
691
+ }
692
+ async bindPage(session, pageId) {
693
+ const s = this.session(session);
694
+ if (this.host.adoptPage === undefined || !s.label)
695
+ throw new Error('sidebar page binding unsupported');
696
+ if (s.tabs.some(tab => tab.url !== ''))
697
+ throw new Error('source binding requires a fresh browser session');
698
+ const id = tabWireId(resolveTabHandle(resolveSessionHandle(s.id), pageId));
699
+ const handle = await this.host.adoptPage(id, this.carrierScope(s));
700
+ const previous = [...s.tabs];
701
+ s.tabs.splice(0, s.tabs.length, { id: this.carrierTab(s, id), handle, url: '' });
702
+ s.activeIndex = 0;
703
+ for (const tab of previous)
704
+ this.destroyTab(tab);
705
+ }
706
+ /**
707
+ * The most recent open request, for the Web sidebar.
708
+ *
709
+ * On the desktop shell the host half tells the shell to place a tab (`__dshBuiltinBrowser.openPanel`)
710
+ * through the bridge. The Web shell has no such channel, so a tool-opened page lived only in the
711
+ * plugin's own browser while the panel stayed empty — and "open it in the sidebar" took several manual
712
+ * steps. The client polls this one slot and places the tab itself.
713
+ * @returns the last request and when it arrived, or undefined when nothing was opened yet.
714
+ */
715
+ lastOpenRequest() {
716
+ return this.lastOpen;
717
+ }
718
+ /** Set by {@link openUrl}; read by the client through the HTTP surface. */
719
+ lastOpen;
369
720
  async openUrl(session, request, signal) {
721
+ try {
722
+ setLastOpen(request.url, Date.now());
723
+ }
724
+ catch { /* best effort */ }
370
725
  const s = this.session(session);
726
+ await this.prepareCarrier(signal, s.id);
371
727
  if (request.newTab === true) {
372
728
  this.newTab(s);
373
729
  }
@@ -380,9 +736,13 @@ export class ElectronBrowserProvider {
380
736
  //
381
737
  // Only an exact match after normalisation: a deliberate navigation to a different URL must not
382
738
  // be redirected to whatever page happens to be open.
383
- if (request.newTab !== true && await this.adoptMatchingPage(s, request.url))
739
+ const tab = this.activeTab(s);
740
+ const transaction = this.beginNavigation(tab, signal);
741
+ const { navigation } = transaction;
742
+ signal = transaction.signal;
743
+ if (request.newTab !== true && await this.adoptMatchingPage(s, request.url, tab, navigation, signal))
384
744
  return;
385
- await this.navigate(session, { url: request.url }, signal);
745
+ await this.navigateTab(s, tab, request.url, navigation, signal);
386
746
  }
387
747
  /**
388
748
  * Bind the carrier page that already shows this URL, if there is one.
@@ -393,7 +753,7 @@ export class ElectronBrowserProvider {
393
753
  * @param url - the URL being opened.
394
754
  * @returns whether an existing page was taken over.
395
755
  */
396
- async adoptMatchingPage(s, url) {
756
+ async adoptMatchingPage(s, url, target, navigation, signal) {
397
757
  if (this.host.adoptPage === undefined || this.host.listPages === undefined)
398
758
  return false;
399
759
  const wanted = this.comparableUrl(url);
@@ -401,27 +761,36 @@ export class ElectronBrowserProvider {
401
761
  return false;
402
762
  let pages;
403
763
  try {
404
- pages = await this.host.listPages(s.label);
764
+ pages = await this.host.listPages(this.carrierScope(s));
405
765
  }
406
766
  catch {
407
767
  // A listing must not turn "nothing to reuse" into "open failed".
408
768
  return false;
409
769
  }
770
+ this.checkNavigation(target, navigation);
410
771
  const match = pages.find(page => this.comparableUrl(page.url) === wanted);
411
772
  if (match === undefined)
412
773
  return false;
774
+ let handle;
413
775
  try {
414
- const handle = await this.host.adoptPage(match.id);
415
- const tab = { id: `page:${match.id}`, handle, url: match.url };
416
- s.tabs.push(tab);
417
- s.activeIndex = s.tabs.length - 1;
418
- this.showActive(s, true);
419
- return true;
776
+ handle = await this.host.adoptPage(this.carrierTab(s, match.id), this.carrierScope(s));
420
777
  }
421
778
  catch {
422
779
  // The page went away between listing and adopting: fall through to an ordinary navigation.
423
780
  return false;
424
781
  }
782
+ if (target.navigation !== navigation) {
783
+ this.host.destroyView(handle, { keepPage: true });
784
+ this.checkNavigation(target, navigation);
785
+ }
786
+ const tab = { id: this.carrierTab(s, match.id), handle, url: match.url, navigation, navigationAbort: target.navigationAbort };
787
+ delete target.navigationAbort;
788
+ s.tabs.push(tab);
789
+ s.activeIndex = s.tabs.length - 1;
790
+ const document = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation); });
791
+ await this.settleDocument(handle, document, signal, { frameId: document.id, loaderId: document.loaderId }, () => { this.checkNavigation(tab, navigation); });
792
+ this.showActive(s, true);
793
+ return true;
425
794
  }
426
795
  /** The parts of a URL that decide identity, or undefined when it cannot be parsed. */
427
796
  comparableUrl(url) {
@@ -447,7 +816,7 @@ export class ElectronBrowserProvider {
447
816
  // the round trip can only answer nothing — and it is the round trip that costs. A tab that
448
817
  // HAS navigated is re-read, because the page may have moved itself since; a read that fails
449
818
  // keeps the last accepted URL rather than reporting the tab as blank.
450
- const liveUrl = tab.url === '' ? '' : await this.currentUrl(tab.handle).catch(() => tab.url);
819
+ const liveUrl = tab.failure !== undefined ? tab.url : tab.url === '' ? '' : await this.currentUrl(tab.handle).catch(() => tab.url);
451
820
  if (liveUrl !== '')
452
821
  tab.url = liveUrl;
453
822
  result.push({
@@ -464,19 +833,14 @@ export class ElectronBrowserProvider {
464
833
  // `dsh_browser_close_tab`, so they accumulated for the life of the browser. Measured on the
465
834
  // sidebar carrier: three clicks produced three webview guests while this listed one tab.
466
835
  //
467
- // `listPages` already excludes the pages it opened the view for — that filtering cannot happen
468
- // here, because a tab is known by this provider's own id and a carrier page by the carrier's,
469
- // and the two never match. A first version compared them anyway and listed every page twice.
470
- //
471
- // They are appended under a `page:` prefix so a caller can tell the two kinds apart — the
472
- // prefix is also what `closeTab` uses to decide whether to close a view or a carrier page.
473
- const pages = await this.host.listPages?.(s.label) ?? [];
836
+ // Hosts exclude pages already attached to provider views.
837
+ const pages = await this.host.listPages?.(this.carrierScope(s)) ?? [];
474
838
  for (const page of pages) {
475
839
  // A page with no URL is a blank one the carrier opened for itself. Listing it would invite a
476
840
  // caller to act on nothing, and the blank normalisation already closes those.
477
841
  if (page.url === '' || page.url === 'about:blank')
478
842
  continue;
479
- result.push({ id: `page:${page.id}`, url: page.url, active: false });
843
+ result.push({ id: this.carrierTab(s, page.id), url: page.url, active: false });
480
844
  }
481
845
  return result;
482
846
  }
@@ -486,17 +850,39 @@ export class ElectronBrowserProvider {
486
850
  // A page the carrier owns. Before this, switching to one threw "not open in this session" —
487
851
  // while `dsh_browser_list_tabs` was happily listing it, so the two tools disagreed and the
488
852
  // page the human was looking at could not be reached (reported as a defect).
489
- if (tabId.startsWith('page:')) {
490
- const id = tabId.slice('page:'.length);
853
+ const carrierId = this.carrierId(s, tabId);
854
+ if (carrierId !== undefined) {
855
+ const existing = s.tabs.findIndex(tab => tab.id === tabId);
856
+ if (existing !== -1) {
857
+ await this.host.presentView?.(s.tabs[existing].handle, s.label, { quiet: this.isQuiet(), select: true });
858
+ s.activeIndex = existing;
859
+ this.showActive(s, true);
860
+ return;
861
+ }
862
+ const id = carrierId;
491
863
  if (this.host.adoptPage === undefined) {
492
864
  throw new BrowserError('browser: this carrier cannot hand over a page it opened itself, so that page cannot be driven. '
493
865
  + 'Open the URL through dsh_browser_open instead — that creates a page this plugin owns.', 'BROWSER_TAB_NOT_FOUND');
494
866
  }
495
- const handle = await this.host.adoptPage(id);
496
- const tab = { id: tabId, handle, url: '' };
497
- s.tabs.push(tab);
498
- s.activeIndex = s.tabs.length - 1;
499
- this.showActive(s);
867
+ const pages = await this.host.listPages?.(this.carrierScope(s)).catch(() => []) ?? [];
868
+ const page = pages.find(candidate => candidate.id === id);
869
+ const handle = await this.host.adoptPage(id, this.carrierScope(s));
870
+ try {
871
+ // An adopted guest already has a document. Marking it as our never-opened
872
+ // blank view makes the first snapshot/a11y return without reading it.
873
+ const url = page?.url || await this.currentUrl(handle);
874
+ if (url === '')
875
+ throw new BrowserError('browser: the adopted page did not report its document URL', 'BROWSER_TAB_NOT_FOUND');
876
+ const tab = { id: tabId, handle, url };
877
+ await this.host.presentView?.(handle, s.label, { quiet: this.isQuiet(), select: true });
878
+ s.tabs.push(tab);
879
+ s.activeIndex = s.tabs.length - 1;
880
+ this.showActive(s, true);
881
+ }
882
+ catch (error) {
883
+ this.host.destroyView(handle, { keepPage: true });
884
+ throw error;
885
+ }
500
886
  return;
501
887
  }
502
888
  const found = this.locateTab(session, tabId);
@@ -504,17 +890,20 @@ export class ElectronBrowserProvider {
504
890
  this.showActive(found.s, true);
505
891
  }
506
892
  /** Close one tab; closing the active tab activates the next. */
507
- closeTab(session, tabId) {
508
- const owner = this.session(session).label;
893
+ async closeTab(session, tabId) {
894
+ const current = this.session(session);
895
+ const carrierId = this.carrierId(current, tabId);
509
896
  // A page the carrier owns rather than a view we created. It was reported by `listTabs` under
510
897
  // this prefix, so closing it here is what keeps the two tools consistent — a page that can be
511
898
  // listed must be closable, or the listing reads as a contradiction.
512
- if (tabId.startsWith('page:')) {
513
- const id = tabId.slice('page:'.length);
899
+ if (carrierId !== undefined) {
900
+ const id = carrierId;
514
901
  if (this.host.closePage === undefined) {
515
902
  return Promise.reject(new BrowserError('browser: this carrier does not expose the pages it opens on its own, so that page cannot be closed', 'BROWSER_TAB_NOT_FOUND'));
516
903
  }
517
- return this.host.closePage(id, owner);
904
+ await this.host.closePage(id, this.carrierScope(current));
905
+ if (!this.session(session).tabs.some(tab => tab.id === tabId))
906
+ return;
518
907
  }
519
908
  const found = this.locateTab(session, tabId);
520
909
  const s = found.s;
@@ -522,7 +911,7 @@ export class ElectronBrowserProvider {
522
911
  const removed = s.tabs[index];
523
912
  if (removed !== undefined) {
524
913
  s.tabs.splice(index, 1);
525
- this.host.destroyView(removed.handle);
914
+ this.destroyTab(removed, { keepPage: carrierId !== undefined });
526
915
  }
527
916
  if (s.tabs.length === 0) {
528
917
  // Session keeps one blank tab so it stays usable.
@@ -543,29 +932,14 @@ export class ElectronBrowserProvider {
543
932
  return Promise.resolve();
544
933
  }
545
934
  /**
546
- * Find a tab by id, preferring the calling session. Tab ids are globally
547
- * unique UUIDs, so when the calling session does not hold the tab (the tool
548
- * layer's session resolution can drift from the session that opened it),
549
- * fall back to locating it in any other session instead of failing — the
550
- * caller explicitly named a tab, so acting on it is what they want. Throws
551
- * BROWSER_TAB_UNKNOWN with the session's actual tabs when the id exists
552
- * nowhere.
935
+ * Find a canonical tab within the calling session.
553
936
  */
554
937
  locateTab(session, tabId) {
555
938
  const s = this.session(session);
556
- // Accept the bare uuid as well as the "tab:<uuid>" form the tools print:
557
- // ids are globally unique, so requiring the printed prefix only produced a
558
- // misleading "is not open in this session" error that listed the very tab
559
- // the caller had just named.
560
- const wanted = stripTabPrefix(tabId);
561
- const own = s.tabs.findIndex(tab => stripTabPrefix(tab.id) === wanted);
939
+ resolveTabHandle(resolveSessionHandle(session), tabId);
940
+ const own = s.tabs.findIndex(tab => tab.id === tabId);
562
941
  if (own >= 0)
563
942
  return { s, index: own };
564
- // Deliberately NOT searched across other sessions. Accepting a bare uuid and
565
- // searching elsewhere are different things: ids are globally unique, so the first is
566
- // harmless convenience, but the second lets a stale id close or switch a tab that
567
- // belongs to another task — or to the human — while reporting success, which
568
- // contradicts the isolation the tools promise.
569
943
  const ownIds = s.tabs.map(t => t.id).join(', ') || '(none)';
570
944
  throw new BrowserError(`browser: tab "${tabId}" is not open in this session (session tabs: ${ownIds})`, 'BROWSER_TAB_UNKNOWN');
571
945
  }
@@ -573,7 +947,7 @@ export class ElectronBrowserProvider {
573
947
  reset(session) {
574
948
  const s = this.session(session);
575
949
  for (const tab of s.tabs)
576
- this.host.destroyView(tab.handle);
950
+ this.destroyTab(tab);
577
951
  s.tabs.length = 0;
578
952
  this.newTab(s);
579
953
  s.activeIndex = 0;
@@ -583,9 +957,34 @@ export class ElectronBrowserProvider {
583
957
  /** Navigate the active tab's view to a URL, honoring HTTP(S)-only admission. */
584
958
  async navigate(session, request, signal) {
585
959
  const s = this.session(session);
960
+ await this.prepareCarrier(signal, s.id);
586
961
  const tab = this.activeTab(s);
962
+ const transaction = this.beginNavigation(tab, signal);
963
+ const { navigation } = transaction;
964
+ signal = transaction.signal;
965
+ await this.navigateTab(s, tab, request.url, navigation, signal);
966
+ }
967
+ beginNavigation(tab, signal) {
968
+ signal?.throwIfAborted();
969
+ const previous = tab.navigationAbort;
970
+ tab.navigation = Symbol();
971
+ tab.navigationAbort = new AbortController();
972
+ previous?.abort(Object.assign(new Error('a newer navigation was requested for this browser tab'), { code: 'panel-navigation-superseded' }));
973
+ return { navigation: tab.navigation, signal: signal === undefined ? tab.navigationAbort.signal : AbortSignal.any([signal, tab.navigationAbort.signal]) };
974
+ }
975
+ checkNavigation(tab, navigation) {
976
+ if (tab.failure !== undefined)
977
+ throw tab.failure;
978
+ if (![...this.sessions.values()].some(session => session.tabs.includes(tab))) {
979
+ throw new BrowserError('browser: the navigation guest was closed', 'BROWSER_GUEST_CLOSED');
980
+ }
981
+ if (tab.navigation !== navigation) {
982
+ throw Object.assign(new Error('a newer navigation was requested for this browser tab'), { code: 'panel-navigation-superseded' });
983
+ }
984
+ }
985
+ async navigateTab(s, tab, url, navigation, signal) {
587
986
  const { handle } = tab;
588
- const url = request.url;
987
+ this.checkNavigation(tab, navigation);
589
988
  try {
590
989
  if (this.httpOnly) {
591
990
  let parsed;
@@ -603,76 +1002,63 @@ export class ElectronBrowserProvider {
603
1002
  // Page.navigate can hang on an unreachable/slow host; bound it like the
604
1003
  // evaluate paths so a wedged navigation surfaces as an error instead of
605
1004
  // blocking the tool call forever.
606
- const timeoutMs = 30_000;
1005
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
1006
+ const deadline = Date.now() + timeoutMs;
607
1007
  // Document identity of the page we are leaving (see settleDocument).
608
- const before = await this.documentStamp(handle);
609
- const result = await withTimeout(handle.sendCommand(CDP_PAGE_NAVIGATE, { url }), timeoutMs, signal, `browser: navigation timed out after ${timeoutMs}ms`,
1008
+ const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation); }, deadline).catch(() => undefined);
1009
+ this.checkNavigation(tab, navigation);
1010
+ signal?.throwIfAborted();
1011
+ const result = await withTimeout(handle.sendCommand(CDP_PAGE_NAVIGATE, { url }, { deadline, signal }), Math.max(1, deadline - Date.now()), signal, `browser: navigation timed out after ${timeoutMs}ms`,
610
1012
  // Best-effort: cancel the in-flight navigation so a wedged load does
611
1013
  // not leave the debugger queue busy.
612
- () => { void handle.sendCommand('Page.stopLoading').catch(() => { }); });
1014
+ timedOut => { if (tab.navigation === navigation)
1015
+ this.interrupt(handle, timedOut); });
613
1016
  // Page.navigate resolves even when the navigation fails; surface the
614
1017
  // failure instead of leaving a silent white screen.
615
- const errorText = result.errorText;
1018
+ this.checkNavigation(tab, navigation);
1019
+ const errorText = result?.errorText;
616
1020
  if (typeof errorText === 'string' && errorText !== '') {
617
1021
  throw new BrowserError(`browser: navigation to "${url}" failed: ${errorText}`, 'BROWSER_NAVIGATION_FAILED');
618
1022
  }
619
- // Record as soon as the navigation has committed: history bookkeeping must
620
- // not wait on the best-effort settle below (which only delays what the
621
- // NEXT observation sees, not whether this action happened).
622
- // The page has already moved by now, so a caller that aborted must be told that rather
623
- // than handed a success: settleDocument returns quietly on abort by design, so without
624
- // this the whole path completes exception-free — success reported, success recorded, and
625
- // the visit written to the persistent history for a navigation nobody awaits any more.
626
1023
  signal?.throwIfAborted();
627
- this.record(s, 'navigate', { url }, true);
628
- // The tab now holds a committed document, which is what the blank short-circuit in
629
- // `snapshot`/`a11y` keys on. Recorded here rather than after the settle below: the
630
- // navigation HAS committed, and a tab wrongly treated as blank would return empty results
631
- // for a page that is really there.
1024
+ const acknowledgement = result;
1025
+ if (typeof acknowledgement?.frameId !== 'string' || acknowledgement.frameId === '') {
1026
+ throw new BrowserError('browser: navigation returned no frame acknowledgement', 'BROWSER_DOCUMENT_UNACKNOWLEDGED');
1027
+ }
1028
+ if (acknowledgement.loaderId === undefined ? before === undefined
1029
+ : typeof acknowledgement.loaderId !== 'string' || acknowledgement.loaderId === '') {
1030
+ throw new BrowserError('browser: navigation returned no document acknowledgement', 'BROWSER_DOCUMENT_UNACKNOWLEDGED');
1031
+ }
632
1032
  tab.url = url;
633
- await this.settleDocument(handle, before, signal);
1033
+ await this.settleDocument(handle, before, signal, acknowledgement, () => { this.checkNavigation(tab, navigation); }, undefined, deadline);
1034
+ this.checkNavigation(tab, navigation);
1035
+ this.record(s, 'navigate', { url }, true);
634
1036
  this.recordVisit(s, handle);
635
1037
  this.showActive(s, true);
636
1038
  }
637
1039
  catch (error) {
1040
+ const code = error?.code;
1041
+ if (tab.navigation === navigation && (code === 'BROWSER_DOCUMENT_TIMEOUT' || code === 'BROWSER_DOCUMENT_UNACKNOWLEDGED')) {
1042
+ this.quarantine(handle);
1043
+ }
638
1044
  if (!(error instanceof BrowserError && error.code === 'BROWSER_NAVIGATION_BLOCKED')) {
639
1045
  this.record(s, 'navigate', { url }, false, { error: String(error) });
640
1046
  }
641
1047
  throw error;
642
1048
  }
643
1049
  }
644
- /**
645
- * A per-document stamp: `performance.timeOrigin` is unique per document load,
646
- * so it tells a same-URL reload and an A→B→A redirect apart from the document
647
- * that was current before the navigation. Empty string when unreadable.
648
- */
649
- async documentStamp(handle) {
650
- const probe = await this.documentProbe(handle);
651
- return probe?.stamp ?? '';
652
- }
653
- /**
654
- * One cheap in-page reading of the document's identity and parse state.
655
- *
656
- * Returns null when the page did NOT answer (mid-commit, execution context
657
- * destroyed) — the caller keeps waiting. A page that answered with an
658
- * unexpected shape (an override or a non-conforming host; the production
659
- * expression always yields a string) is reported as `unknown` rather than as
660
- * "no answer": blocking the navigation for the whole budget on a page that
661
- * demonstrably responded has no upside.
662
- */
663
- async documentProbe(handle) {
664
- try {
665
- const result = await withTimeout(handleSendEvaluate(handle, 'String(performance.timeOrigin) + "|" + document.readyState', undefined, { present: false, initialize: false }), 3_000, undefined, 'browser: document probe timed out');
666
- if (!result.ok)
667
- return null;
668
- if (typeof result.value !== 'string')
669
- return { stamp: '', readyState: 'unknown' };
670
- const [stamp = '', readyState = ''] = result.value.split('|');
671
- return { stamp, readyState };
672
- }
673
- catch {
674
- return null;
675
- }
1050
+ async documentIdentity(handle, signal, checkCurrent, deadline = Date.now() + PROVIDER_TIMEOUTS.evaluation, allowErrorDocument = false) {
1051
+ signal?.throwIfAborted();
1052
+ checkCurrent?.();
1053
+ return mainDocument(await withTimeout(handle.sendCommand('Page.getFrameTree', undefined, { present: false, initialize: false }), Math.max(1, Math.min(PROVIDER_TIMEOUTS.evaluation, deadline - Date.now())), signal, 'browser: document identity timed out', timedOut => {
1054
+ try {
1055
+ checkCurrent?.();
1056
+ }
1057
+ catch {
1058
+ return;
1059
+ }
1060
+ this.interrupt(handle, timedOut);
1061
+ }), { allowErrorDocument });
676
1062
  }
677
1063
  /**
678
1064
  * Page.navigate resolves at navigation COMMIT, not at load: the new document
@@ -682,42 +1068,63 @@ export class ElectronBrowserProvider {
682
1068
  * interactive elements — and why a separate dsh_browser_snapshot right after
683
1069
  * always found them.
684
1070
  *
685
- * Wait — bounded, best-effort — for the new document to settle: readyState
686
- * must reach interactive/complete AND the document identity must have
687
- * changed. A page that never settles must not fail a navigation that already
688
- * succeeded, so a timeout here is swallowed.
1071
+ * The CDP frame/loader acknowledgement, not elapsed time or URL equality,
1072
+ * identifies the document whose parse readiness can complete the transaction.
689
1073
  */
690
- async settleDocument(handle, before, signal) {
691
- const started = Date.now();
692
- const deadline = started + SETTLE_TIMEOUT_MS;
1074
+ async settleDocument(handle, before, signal, acknowledgement, checkCurrent, historyEntry, deadline = Date.now() + DEFAULT_OPERATION_TIMEOUT_MS, allowErrorDocument = false) {
693
1075
  // The document is being replaced, so the synthetic pointer drawn into the old one
694
1076
  // is gone. Dropping the remembered position is what lets it be painted again:
695
1077
  // without this, a paint at coincidentally identical coordinates would be skipped
696
1078
  // and the pointer would never come back after a navigation.
697
1079
  forgetCursor(handle);
698
1080
  for (;;) {
699
- if (signal?.aborted === true)
700
- return;
701
- // A probe failure is expected while the navigation commits (the context is
702
- // being destroyed) — keep polling rather than giving up.
703
- const probe = await this.documentProbe(handle);
704
- if (probe !== null) {
705
- const settled = probe.readyState === 'interactive'
706
- || probe.readyState === 'complete'
707
- || probe.readyState === 'unknown';
708
- const isNewDocument = before === '' || probe.stamp === '' || probe.stamp !== before;
709
- // The common case: the new document exists and is parsed — return now.
710
- if (settled && isNewDocument)
711
- return;
712
- // Same document (hash navigation, cancelled/aborted load): there is no
713
- // parse to wait for, so do not burn the budget. Outlast the brief
714
- // window in which the OUTGOING document may still answer instead.
715
- if (settled && Date.now() - started >= SETTLE_GRACE_MS)
716
- return;
1081
+ signal?.throwIfAborted();
1082
+ checkCurrent?.();
1083
+ const remaining = deadline - Date.now();
1084
+ if (remaining <= 0) {
1085
+ this.quarantine(handle);
1086
+ throw new BrowserError('browser: the navigation document was not ready within its deadline', 'BROWSER_DOCUMENT_TIMEOUT');
717
1087
  }
718
- if (Date.now() >= deadline)
1088
+ const ready = await withTimeout((async () => {
1089
+ if (historyEntry !== undefined) {
1090
+ const history = await handle.sendCommand('Page.getNavigationHistory');
1091
+ if (history.entries?.[history.currentIndex ?? -1]?.id !== historyEntry)
1092
+ return false;
1093
+ }
1094
+ const current = await this.documentIdentity(handle, signal, checkCurrent, deadline, allowErrorDocument);
1095
+ if (acknowledgement?.frameId !== undefined && current.id !== acknowledgement.frameId) {
1096
+ throw new BrowserError('browser: navigation frame was superseded', 'BROWSER_NAVIGATION_SUPERSEDED');
1097
+ }
1098
+ const loader = acknowledgement?.loaderId ?? (acknowledgement === undefined ? undefined : before?.loaderId);
1099
+ if (loader !== undefined && current.loaderId !== loader) {
1100
+ if (current.loaderId === before?.loaderId)
1101
+ return false;
1102
+ throw new BrowserError('browser: navigation document was superseded', 'BROWSER_NAVIGATION_SUPERSEDED');
1103
+ }
1104
+ if (acknowledgement === undefined && current.loaderId === before?.loaderId)
1105
+ return false;
1106
+ return documentReady(handle, current, () => {
1107
+ signal?.throwIfAborted();
1108
+ checkCurrent?.();
1109
+ if (Date.now() >= deadline) {
1110
+ this.quarantine(handle);
1111
+ throw new BrowserError('browser: document readiness deadline expired', 'BROWSER_DOCUMENT_TIMEOUT');
1112
+ }
1113
+ });
1114
+ })(), remaining, signal, 'browser: document readiness timed out', timedOut => {
1115
+ try {
1116
+ checkCurrent?.();
1117
+ }
1118
+ catch {
1119
+ return;
1120
+ }
1121
+ this.interrupt(handle, timedOut);
1122
+ });
1123
+ signal?.throwIfAborted();
1124
+ checkCurrent?.();
1125
+ if (ready)
719
1126
  return;
720
- await delay(SETTLE_POLL_MS, signal);
1127
+ await delay(Math.min(SETTLE_POLL_MS, Math.max(0, deadline - Date.now())), signal);
721
1128
  }
722
1129
  }
723
1130
  /**
@@ -737,7 +1144,7 @@ export class ElectronBrowserProvider {
737
1144
  return this.activeTab(s).handle;
738
1145
  }
739
1146
  signal?.throwIfAborted();
740
- const timeoutMs = 10_000;
1147
+ const timeoutMs = PROVIDER_TIMEOUTS.lookup;
741
1148
  try {
742
1149
  await withTimeout(present(handle, s.label, { quiet: this.isQuiet() }), timeoutMs, signal, `browser: presenting the page view timed out after ${timeoutMs}ms`);
743
1150
  this.showActive(s);
@@ -801,7 +1208,7 @@ export class ElectronBrowserProvider {
801
1208
  // and this runs before typing, so an unresponsive child would hang dsh_browser_key for
802
1209
  // good. A timeout is caught below exactly like any other focus failure, so the
803
1210
  // best-effort contract is unchanged.
804
- await withTimeout(handle.focus(quiet ? { quiet } : undefined), 5_000, undefined, 'browser: focusing the view timed out');
1211
+ await withTimeout(handle.focus(quiet ? { quiet } : undefined), PROVIDER_TIMEOUTS.interaction, undefined, 'browser: focusing the view timed out');
805
1212
  }
806
1213
  catch (error) {
807
1214
  if (quiet)
@@ -838,7 +1245,7 @@ export class ElectronBrowserProvider {
838
1245
  }
839
1246
  const s = this.session(session);
840
1247
  const handle = await this.present(s, signal);
841
- const viewport = await withTimeout(handleSendEvaluate(handle, '({width:innerWidth,height:innerHeight})'), 5_000, signal, 'browser: pointer viewport check timed out');
1248
+ const viewport = await withTimeout(handleSendEvaluate(handle, '({width:innerWidth,height:innerHeight})'), PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer viewport check timed out');
842
1249
  if (!viewport.ok)
843
1250
  throw new BrowserError('browser: could not read the pointer viewport', 'BROWSER_POINTER_INVALID');
844
1251
  const size = viewport.value;
@@ -848,7 +1255,7 @@ export class ElectronBrowserProvider {
848
1255
  const send = async (params) => {
849
1256
  signal?.throwIfAborted();
850
1257
  this.assertSameView(session, handle, this.activeTab(s).handle);
851
- await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), 5_000, signal, 'browser: pointer input timed out');
1258
+ await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer input timed out');
852
1259
  };
853
1260
  await send({ type: 'mouseMoved', x: from.x, y: from.y, buttons: 0 });
854
1261
  if (to === undefined)
@@ -899,7 +1306,7 @@ export class ElectronBrowserProvider {
899
1306
  // (navigate returned but the renderer has not committed). Bound it so a
900
1307
  // stuck call surfaces as BROWSER_EXECUTE_TIMEOUT instead of wedging the
901
1308
  // whole tool call. The caller's signal wins when it fires first.
902
- const timeoutMs = request.timeoutMs ?? 30_000;
1309
+ const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
903
1310
  const result = await withTimeout(handle.sendCommand(CDP_RUNTIME_EVALUATE, {
904
1311
  expression,
905
1312
  returnByValue: true,
@@ -907,7 +1314,7 @@ export class ElectronBrowserProvider {
907
1314
  }), timeoutMs, signal, `browser: execute timed out after ${timeoutMs}ms`,
908
1315
  // Best-effort: kill the wedged page script so the renderer (and the
909
1316
  // debugger queue) is not stuck behind a busy loop forever.
910
- () => terminatePage(handle));
1317
+ timedOut => { this.interrupt(handle, timedOut); });
911
1318
  if (result.exceptionDetails !== undefined) {
912
1319
  const detail = result.exceptionDetails;
913
1320
  const exception = detail.exception?.description ?? detail.text ?? 'unknown exception';
@@ -929,7 +1336,7 @@ export class ElectronBrowserProvider {
929
1336
  if (signal?.aborted)
930
1337
  throw signal.reason;
931
1338
  if (error instanceof Error && error.name === 'TimeoutError') {
932
- throw new BrowserError(`browser: execute timed out after ${request.timeoutMs ?? 30_000}ms`, 'BROWSER_EXECUTE_TIMEOUT', { cause: error });
1339
+ throw new BrowserError(`browser: execute timed out after ${request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS}ms`, 'BROWSER_EXECUTE_TIMEOUT', { cause: error });
933
1340
  }
934
1341
  throw new BrowserError(`browser: execute failed: ${String(error)}`, 'BROWSER_EXECUTE_FAILED', { cause: error });
935
1342
  }
@@ -944,7 +1351,7 @@ export class ElectronBrowserProvider {
944
1351
  async waitFor(session, request, signal) {
945
1352
  const tab = this.activeTab(this.session(session));
946
1353
  signal?.throwIfAborted();
947
- const timeoutMs = request.timeoutMs ?? 30_000;
1354
+ const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
948
1355
  const deadline = Date.now() + timeoutMs;
949
1356
  const url = request.url ?? '';
950
1357
  const selector = request.selector ?? '';
@@ -976,7 +1383,7 @@ export class ElectronBrowserProvider {
976
1383
  return { urlOk, loadedOk, foundOk }
977
1384
  })()`;
978
1385
  for (;;) {
979
- const result = await withTimeout(handleSendEvaluate(tab.handle, expression), Math.min(5_000, Math.max(250, deadline - Date.now())), signal, 'browser: wait poll timed out', () => terminatePage(tab.handle));
1386
+ const result = await withTimeout(handleSendEvaluate(tab.handle, expression), Math.min(PROVIDER_TIMEOUTS.interaction, Math.max(250, deadline - Date.now())), signal, 'browser: wait poll timed out', timedOut => { this.interrupt(tab.handle, timedOut); });
980
1387
  if (!result.ok) {
981
1388
  throw new BrowserError(`browser: wait failed: ${result.exception}`, 'BROWSER_WAIT_FAILED');
982
1389
  }
@@ -1151,20 +1558,15 @@ export class ElectronBrowserProvider {
1151
1558
  })()`;
1152
1559
  // Same hang guard as execute: a renderer that has not committed after
1153
1560
  // navigate would otherwise block snapshot forever.
1154
- const timeoutMs = 30_000;
1561
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
1155
1562
  let result;
1156
1563
  try {
1157
- result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: snapshot timed out after ${timeoutMs}ms`, () => terminatePage(tab.handle));
1564
+ result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: snapshot timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
1158
1565
  }
1159
1566
  catch (error) {
1160
- // A timeout leaves the wedged view in the session, so every later read would pay the same
1161
- // 30 seconds again — and `terminatePage` only interrupts the running script, it does not
1162
- // make the view readable. Replacing it is what turns a permanent loss into one bad call:
1163
- // the tab keeps the id the caller holds, and the next dsh_browser_open with the real URL
1164
- // repopulates it.
1165
1567
  if (error instanceof Error && error.name === 'TimeoutError') {
1166
- this.replaceTabWithBlank(s, tab);
1167
- throw new BrowserError('browser: snapshot timed out; the stuck tab was reset to blank. Call dsh_browser_open with the real target URL before reading it again.', 'BROWSER_SNAPSHOT_TIMEOUT', { cause: error });
1568
+ this.quarantine(tab.handle);
1569
+ throw new BrowserError('browser: snapshot timed out; the guest is quarantined. Close this tab or explicitly reset the session.', 'BROWSER_SNAPSHOT_TIMEOUT', { cause: error });
1168
1570
  }
1169
1571
  throw error;
1170
1572
  }
@@ -1349,17 +1751,15 @@ export class ElectronBrowserProvider {
1349
1751
  walk(document, false, 0)
1350
1752
  return { url: location.href, title: document.title || undefined, count: out.length, nodes: out, truncated: out.length >= maxNodes }
1351
1753
  })()`;
1352
- const timeoutMs = 30_000;
1754
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
1353
1755
  let result;
1354
1756
  try {
1355
- result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: a11y timed out after ${timeoutMs}ms`, () => terminatePage(tab.handle));
1757
+ result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: a11y timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
1356
1758
  }
1357
1759
  catch (error) {
1358
- // As in `snapshot`: a timeout means the view is wedged, and leaving it in the session would
1359
- // charge every later read the same 30 seconds. Replaced in place, so the tab id survives.
1360
1760
  if (error instanceof Error && error.name === 'TimeoutError') {
1361
- this.replaceTabWithBlank(s, tab);
1362
- throw new BrowserError('browser: a11y timed out; the stuck tab was reset to blank. Call dsh_browser_open with the real target URL before reading it again.', 'BROWSER_A11Y_TIMEOUT', { cause: error });
1761
+ this.quarantine(tab.handle);
1762
+ throw new BrowserError('browser: a11y timed out; the guest is quarantined. Close this tab or explicitly reset the session.', 'BROWSER_A11Y_TIMEOUT', { cause: error });
1363
1763
  }
1364
1764
  throw error;
1365
1765
  }
@@ -1374,8 +1774,8 @@ export class ElectronBrowserProvider {
1374
1774
  const s = this.session(session);
1375
1775
  const tab = this.activeTab(s);
1376
1776
  signal?.throwIfAborted();
1377
- const timeoutMs = 15_000;
1378
- const result = await withTimeout(handleSendEvaluate(tab.handle, CHALLENGE_DETECT_EXPRESSION), timeoutMs, signal, `browser: challenge detection timed out after ${timeoutMs}ms`, () => terminatePage(tab.handle));
1777
+ const timeoutMs = PROVIDER_TIMEOUTS.action;
1778
+ const result = await withTimeout(handleSendEvaluate(tab.handle, CHALLENGE_DETECT_EXPRESSION), timeoutMs, signal, `browser: challenge detection timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
1379
1779
  if (!result.ok) {
1380
1780
  throw new BrowserError(`browser: challenge detection failed: ${result.exception}`, 'BROWSER_CHALLENGE_DETECT_FAILED');
1381
1781
  }
@@ -1477,8 +1877,8 @@ export class ElectronBrowserProvider {
1477
1877
  // Honor a per-call timeout: content evaluation can hang on a heavy page,
1478
1878
  // so a caller-supplied budget bounds it. Unlike a bare signal entry check,
1479
1879
  // withTimeout also interrupts a call already in flight.
1480
- const timeoutMs = request.timeoutMs ?? 30_000;
1481
- const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: content timed out after ${timeoutMs}ms`, () => terminatePage(tab.handle));
1880
+ const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
1881
+ const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: content timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
1482
1882
  if (!result.ok)
1483
1883
  throw new BrowserError(`browser: content evaluation failed: ${result.exception}`, 'BROWSER_CONTENT_FAILED');
1484
1884
  const value = result.value;
@@ -1501,7 +1901,7 @@ export class ElectronBrowserProvider {
1501
1901
  if ('target' in request) {
1502
1902
  // Semantic targeting (②): locate the element in-page, scroll it into
1503
1903
  // view, and click its center — no coordinate guessing needed.
1504
- const locateMs = 10_000;
1904
+ const locateMs = PROVIDER_TIMEOUTS.lookup;
1505
1905
  const body = `
1506
1906
  el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'center' })
1507
1907
  const r = el.getBoundingClientRect()
@@ -1534,7 +1934,7 @@ export class ElectronBrowserProvider {
1534
1934
  // and the dispatch would go to another — and Chromium answers success either way.
1535
1935
  if ('target' in request)
1536
1936
  this.assertSameView(session, locateHandle, handle);
1537
- const timeoutMs = 30_000;
1937
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
1538
1938
  const send = (params, label) => withTimeout(handle.sendCommand('Input.dispatchMouseEvent', params), timeoutMs, signal, `browser: click ${label} timed out after ${timeoutMs}ms`);
1539
1939
  // Chromium routes a synthesized `mousePressed` to the widget's *current*
1540
1940
  // hover target rather than hit-testing the coordinates, and a real pointer
@@ -1614,7 +2014,7 @@ export class ElectronBrowserProvider {
1614
2014
  }
1615
2015
  // One barrier for the whole run: cheap, and it is the view that needs a surface, not each press.
1616
2016
  const handle = await this.present(s, signal);
1617
- const timeoutMs = 30_000;
2017
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
1618
2018
  // 40 ms is above one frame at 30 fps, which is what keeps the page from reading two presses as a
1619
2019
  // double click. Faster runs were measured dropping presses outright.
1620
2020
  const gap = typeof request.intervalMs === 'number' && request.intervalMs >= 0 ? request.intervalMs : 40;
@@ -1661,7 +2061,7 @@ export class ElectronBrowserProvider {
1661
2061
  signal?.throwIfAborted();
1662
2062
  const hasTarget = 'target' in request;
1663
2063
  if (hasTarget) {
1664
- const locateMs = 10_000;
2064
+ const locateMs = PROVIDER_TIMEOUTS.lookup;
1665
2065
  const script = this.buildTargetScript(request.target, locateMs, `
1666
2066
  el.focus()
1667
2067
  return { ok: true }
@@ -1673,7 +2073,7 @@ export class ElectronBrowserProvider {
1673
2073
  this.showCursor(locateTab.handle, cursorPoint.x, cursorPoint.y, 'click', 'type', true);
1674
2074
  }
1675
2075
  const text = 'text' in request ? request.text : '';
1676
- const timeoutMs = 30_000;
2076
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
1677
2077
  // Input.insertText goes through the Input domain: same display-surface
1678
2078
  // requirement as click/key. It also reports which view is active once the barrier has
1679
2079
  // settled, which is what makes the tab-switch check below meaningful.
@@ -1712,8 +2112,8 @@ export class ElectronBrowserProvider {
1712
2112
  window.scrollBy({ top: ${request.deltaY ?? 0}, left: ${request.deltaX ?? 0} })
1713
2113
  return { ok: true }
1714
2114
  })()`;
1715
- const timeoutMs = 15_000;
1716
- const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: scroll timed out after ${timeoutMs}ms`, () => terminatePage(tab.handle));
2115
+ const timeoutMs = PROVIDER_TIMEOUTS.action;
2116
+ const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: scroll timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
1717
2117
  if (!result.ok)
1718
2118
  throw new BrowserError(`browser: scroll failed: ${result.exception}`, 'BROWSER_SCROLL_FAILED');
1719
2119
  const value = result.value;
@@ -1724,10 +2124,16 @@ export class ElectronBrowserProvider {
1724
2124
  /** Go back (-1) or forward (+1) in the active tab's navigation history. */
1725
2125
  async historyStep(session, direction, signal) {
1726
2126
  const s = this.session(session);
1727
- const { handle } = this.activeTab(s);
2127
+ const tab = this.activeTab(s);
2128
+ const { handle } = tab;
2129
+ const transaction = this.beginNavigation(tab, signal);
2130
+ const { navigation } = transaction;
2131
+ signal = transaction.signal;
1728
2132
  signal?.throwIfAborted();
1729
- const timeoutMs = 30_000;
2133
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
2134
+ const deadline = Date.now() + timeoutMs;
1730
2135
  const hist = await withTimeout(handle.sendCommand('Page.getNavigationHistory'), timeoutMs, signal, `browser: history read timed out after ${timeoutMs}ms`);
2136
+ this.checkNavigation(tab, navigation);
1731
2137
  const entries = hist.entries ?? [];
1732
2138
  const currentIndex = hist.currentIndex ?? -1;
1733
2139
  const target = currentIndex + direction;
@@ -1742,10 +2148,18 @@ export class ElectronBrowserProvider {
1742
2148
  throw new BrowserError('browser: history entry missing id', 'BROWSER_HISTORY_INVALID');
1743
2149
  // A history step is a navigation too: the classic A→B→A redirect would
1744
2150
  // otherwise read the outgoing document's identity (see settleDocument).
1745
- const before = await this.documentStamp(handle);
1746
- await withTimeout(handle.sendCommand('Page.navigateToHistoryEntry', { entryId: entry.id }), timeoutMs, signal, `browser: history navigation timed out after ${timeoutMs}ms`, () => { void handle.sendCommand('Page.stopLoading').catch(() => { }); });
2151
+ const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation); }, deadline, true);
2152
+ const inPage = await withTimeout(handleSendEvaluate(handle, `(() => {
2153
+ if (typeof navigation === 'undefined') return false;
2154
+ const entry = navigation.entries().find(entry => entry.index === navigation.currentEntry.index + ${direction});
2155
+ return entry?.url === ${JSON.stringify(entry.url)} && entry.sameDocument === true;
2156
+ })()`), Math.max(1, deadline - Date.now()), signal, 'browser: history document identity timed out', timedOut => { this.interrupt(handle, timedOut); });
2157
+ this.checkNavigation(tab, navigation);
2158
+ signal?.throwIfAborted();
2159
+ await withTimeout(handle.sendCommand('Page.navigateToHistoryEntry', { entryId: entry.id }), Math.max(1, deadline - Date.now()), signal, `browser: history navigation timed out after ${timeoutMs}ms`, () => { if (tab.navigation === navigation)
2160
+ void handle.sendCommand('Page.stopLoading').catch(() => { }); });
2161
+ await this.settleDocument(handle, before, signal, inPage.ok && inPage.value === true ? { frameId: before.id, loaderId: before.loaderId } : undefined, () => { this.checkNavigation(tab, navigation); }, entry.id, deadline, true);
1747
2162
  this.record(s, direction === -1 ? 'back' : 'forward', {}, true);
1748
- await this.settleDocument(handle, before, signal);
1749
2163
  this.recordVisit(s, handle);
1750
2164
  this.showActive(s);
1751
2165
  }
@@ -1760,17 +2174,25 @@ export class ElectronBrowserProvider {
1760
2174
  /** Reload the active tab. */
1761
2175
  async reload(session, signal) {
1762
2176
  const s = this.session(session);
1763
- const { handle } = this.activeTab(s);
2177
+ const tab = this.activeTab(s);
2178
+ const { handle } = tab;
2179
+ const transaction = this.beginNavigation(tab, signal);
2180
+ const { navigation } = transaction;
2181
+ signal = transaction.signal;
1764
2182
  signal?.throwIfAborted();
1765
- const timeoutMs = 30_000;
2183
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
2184
+ const deadline = Date.now() + timeoutMs;
1766
2185
  // Same-URL reload: only the per-load document identity can tell the new
1767
2186
  // document from the old one, so capture it before reloading.
1768
- const before = await this.documentStamp(handle);
1769
- await withTimeout(handle.sendCommand('Page.reload', { ignoreCache: false }), timeoutMs, signal, `browser: reload timed out after ${timeoutMs}ms`,
2187
+ const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation); }, deadline, true);
2188
+ this.checkNavigation(tab, navigation);
2189
+ signal?.throwIfAborted();
2190
+ await withTimeout(handle.sendCommand('Page.reload', { ignoreCache: false }), Math.max(1, deadline - Date.now()), signal, `browser: reload timed out after ${timeoutMs}ms`,
1770
2191
  // Best-effort: cancel the reload if it wedges the debugger queue.
1771
- () => { void handle.sendCommand('Page.stopLoading').catch(() => { }); });
2192
+ () => { if (tab.navigation === navigation)
2193
+ void handle.sendCommand('Page.stopLoading').catch(() => { }); });
2194
+ await this.settleDocument(handle, before, signal, undefined, () => { this.checkNavigation(tab, navigation); }, undefined, deadline, true);
1772
2195
  this.record(s, 'reload', {}, true);
1773
- await this.settleDocument(handle, before, signal);
1774
2196
  this.recordVisit(s, handle);
1775
2197
  this.showActive(s);
1776
2198
  }
@@ -1783,7 +2205,7 @@ export class ElectronBrowserProvider {
1783
2205
  throw new BrowserError(`browser: unsupported key "${request.key}" (supported: ${BROWSER_KEY_NAMES.join(', ')})`, 'BROWSER_KEY_UNSUPPORTED');
1784
2206
  }
1785
2207
  const params = { key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.vk, nativeVirtualKeyCode: spec.vk, ...spec.text !== undefined ? { text: spec.text } : {} };
1786
- const timeoutMs = 15_000;
2208
+ const timeoutMs = PROVIDER_TIMEOUTS.action;
1787
2209
  // Input.dispatchKeyEvent is subject to the same display-surface rule. The handle comes
1788
2210
  // back from the presentation barrier rather than from a capture taken before it: this
1789
2211
  // session is shared with the human, who may switch tabs while the barrier round-trips,
@@ -2007,8 +2429,8 @@ export class ElectronBrowserProvider {
2007
2429
  }
2008
2430
  return { fields: out, submitted }
2009
2431
  })()`;
2010
- const timeoutMs = request.timeoutMs ?? 30_000;
2011
- const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: fillForm timed out after ${timeoutMs}ms`, () => terminatePage(tab.handle));
2432
+ const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
2433
+ const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: fillForm timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
2012
2434
  if (!result.ok) {
2013
2435
  throw new BrowserError(`browser: fillForm evaluation failed: ${result.exception}`, 'BROWSER_FILL_FAILED');
2014
2436
  }
@@ -2149,7 +2571,7 @@ export class ElectronBrowserProvider {
2149
2571
  // caller saw `click timed out after 10000ms` while the page had already
2150
2572
  // decided WHY (selector not found / malformed). Give the answer a chance to
2151
2573
  // get back before the generic timeout replaces it.
2152
- const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs + TARGET_SCRIPT_GRACE_MS, signal, `${errorLabel} timed out after ${timeoutMs}ms`, () => terminatePage(tab.handle));
2574
+ const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs + TARGET_SCRIPT_GRACE_MS, signal, `${errorLabel} timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
2153
2575
  if (!result.ok)
2154
2576
  throw new BrowserError(`${errorLabel} failed: ${result.exception}`, errorCode);
2155
2577
  const value = result.value;
@@ -2162,7 +2584,7 @@ export class ElectronBrowserProvider {
2162
2584
  const s = this.session(session);
2163
2585
  const tab = this.activeTab(s);
2164
2586
  signal?.throwIfAborted();
2165
- const timeoutMs = request.timeoutMs ?? 5_000;
2587
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
2166
2588
  const body = `
2167
2589
  const value = ${JSON.stringify(String(request.value))}
2168
2590
  const setNative = (el, proto, v) => {
@@ -2211,7 +2633,7 @@ export class ElectronBrowserProvider {
2211
2633
  const s = this.session(session);
2212
2634
  const tab = this.activeTab(s);
2213
2635
  signal?.throwIfAborted();
2214
- const timeoutMs = request.timeoutMs ?? 5_000;
2636
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
2215
2637
  const want = request.checked ?? true;
2216
2638
  const body = `
2217
2639
  const want = ${String(want)}
@@ -2239,7 +2661,7 @@ export class ElectronBrowserProvider {
2239
2661
  const s = this.session(session);
2240
2662
  const tab = this.activeTab(s);
2241
2663
  signal?.throwIfAborted();
2242
- const timeoutMs = request.timeoutMs ?? 5_000;
2664
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
2243
2665
  const body = `
2244
2666
  if (el.tagName !== 'SELECT') return { ok: false, error: 'element is not a <select> (' + el.tagName + ')' }
2245
2667
  const optionValue = ${JSON.stringify(request.optionValue ?? null)}
@@ -2273,7 +2695,7 @@ export class ElectronBrowserProvider {
2273
2695
  const s = this.session(session);
2274
2696
  const tab = this.activeTab(s);
2275
2697
  signal?.throwIfAborted();
2276
- const timeoutMs = request.timeoutMs ?? 5_000;
2698
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
2277
2699
  const body = `
2278
2700
  const setNative = (el, proto) => {
2279
2701
  const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
@@ -2309,7 +2731,7 @@ export class ElectronBrowserProvider {
2309
2731
  const s = this.session(session);
2310
2732
  const tab = this.activeTab(s);
2311
2733
  signal?.throwIfAborted();
2312
- const timeoutMs = request.timeoutMs ?? 5_000;
2734
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
2313
2735
  const body = `
2314
2736
  const type = (el.type || '').toLowerCase()
2315
2737
  if (type === 'checkbox' || type === 'radio') return { ok: true, value: null, checked: el.checked }
@@ -2339,7 +2761,7 @@ export class ElectronBrowserProvider {
2339
2761
  const s = this.session(session);
2340
2762
  const tab = this.activeTab(s);
2341
2763
  signal?.throwIfAborted();
2342
- const timeoutMs = request.timeoutMs ?? 5_000;
2764
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
2343
2765
  const script = `(async () => {
2344
2766
  const itemSel = ${JSON.stringify(request.item)}
2345
2767
  const fields = ${JSON.stringify(request.fields)}
@@ -2379,7 +2801,7 @@ export class ElectronBrowserProvider {
2379
2801
  }
2380
2802
  return { ok: true, count: out.length, items: out }
2381
2803
  })()`;
2382
- const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs + TARGET_SCRIPT_GRACE_MS, signal, `browser: scrape timed out after ${timeoutMs}ms`, () => terminatePage(tab.handle));
2804
+ const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs + TARGET_SCRIPT_GRACE_MS, signal, `browser: scrape timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
2383
2805
  if (!result.ok)
2384
2806
  throw new BrowserError(`browser: scrape evaluation failed: ${result.exception}`, 'BROWSER_SCRAPE_FAILED');
2385
2807
  const value = result.value;
@@ -2536,7 +2958,7 @@ export class ElectronBrowserProvider {
2536
2958
  // parent's timeout fires the child continues writing. The parent's pending
2537
2959
  // entry is cleaned up (the promise settles) and the child's eventual
2538
2960
  // reply is harmlessly consumed by the RPC layer.
2539
- const timeoutMs = 60_000;
2961
+ const timeoutMs = PROVIDER_TIMEOUTS.download;
2540
2962
  await withTimeout(downloadable.download(request.url, savePath), timeoutMs, signal, `browser: download timed out after ${timeoutMs}ms`);
2541
2963
  this.record(s, 'download', { url: request.url, savePath }, true, { result: savePath });
2542
2964
  return { path: savePath };
@@ -2554,7 +2976,7 @@ export class ElectronBrowserProvider {
2554
2976
  }
2555
2977
  const s = this.session(session);
2556
2978
  const { handle } = this.activeTab(s);
2557
- const timeoutMs = 30_000;
2979
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
2558
2980
  // The self-hosted carrier has a native path (the child reads its own session), which
2559
2981
  // is worth preferring: it reports exactly what the browser persisted.
2560
2982
  const native = handle;
@@ -2599,7 +3021,7 @@ export class ElectronBrowserProvider {
2599
3021
  this.assertActionAllowed('credentialWrite');
2600
3022
  const s = this.session(session);
2601
3023
  const { handle } = this.activeTab(s);
2602
- const timeoutMs = 30_000;
3024
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
2603
3025
  const native = handle;
2604
3026
  if (typeof native.restoreAuth === 'function') {
2605
3027
  const restored = await withTimeout(native.restoreAuth(cookies), timeoutMs, undefined, `browser: auth restore timed out after ${timeoutMs}ms`);
@@ -2703,14 +3125,16 @@ export class ElectronBrowserProvider {
2703
3125
  // in the child from the NativeImage, so this path is the only one that
2704
3126
  // can produce JPEG (CDP JPEG hangs on Electron 43).
2705
3127
  const capturable = handle;
2706
- if (request?.fullPage !== true && typeof capturable.capture === 'function') {
3128
+ // A region capture must go through CDP: the native NativeImage path has no
3129
+ // clip and would present/activate the window (a quiet-mode violation).
3130
+ if (request?.clip === undefined && request?.fullPage !== true && typeof capturable.capture === 'function') {
2707
3131
  // Ensure the target view is the visible one before capturing — unless quiet mode is on.
2708
3132
  // There, presenting the view is exactly what the user asked to avoid (it restores and
2709
3133
  // raises the window); the host switches the visible tab inside the window and, if the
2710
3134
  // window has no surface to capture, falls through to CDP.
2711
3135
  if (!this.isQuiet())
2712
3136
  this.showActive(s);
2713
- const timeoutMs = 30_000;
3137
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
2714
3138
  const shot = await withTimeout(capturable.capture({
2715
3139
  ...format === 'jpeg' ? { format, quality: request?.quality } : {},
2716
3140
  ...request?.maxWidth !== undefined ? { maxWidth: request.maxWidth } : {},
@@ -2735,9 +3159,18 @@ export class ElectronBrowserProvider {
2735
3159
  // installed Chrome or Edge is the real browser and has no such defect, so it says so
2736
3160
  // through `supportsCdpJpeg` and gets the format it asked for, and the same for
2737
3161
  // downscaling, which CDP performs through a full-document clip.
2738
- const timeoutMs = 30_000;
3162
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
2739
3163
  const params = {};
2740
- if (request?.fullPage === true) {
3164
+ const region = request?.clip;
3165
+ if (region !== undefined) {
3166
+ const valid = [region.x, region.y, region.width, region.height].every(value => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 8192) && region.width > 0 && region.height > 0;
3167
+ if (!valid)
3168
+ throw new BrowserError('browser: screenshot region is out of range', 'BROWSER_SCREENSHOT_FAILED');
3169
+ params.clip = { x: region.x, y: region.y, width: region.width, height: region.height, scale: 1 };
3170
+ params.fromSurface = true;
3171
+ params.captureBeyondViewport = false;
3172
+ }
3173
+ if (region === undefined && request?.fullPage === true) {
2741
3174
  // `captureBeyondViewport` captures the full scrollable content; without
2742
3175
  // a clip this yields the full-page image (CDP default is the viewport).
2743
3176
  params.captureBeyondViewport = true;
@@ -2754,7 +3187,7 @@ export class ElectronBrowserProvider {
2754
3187
  // is read first; when that is unavailable the capture proceeds unscaled rather than
2755
3188
  // failing — an image the caller can shrink itself beats no image at all.
2756
3189
  let rendered;
2757
- if (request?.maxWidth !== undefined || request?.maxHeight !== undefined) {
3190
+ if (region === undefined && (request?.maxWidth !== undefined || request?.maxHeight !== undefined)) {
2758
3191
  const metrics = await withTimeout(handle.sendCommand('Page.getLayoutMetrics', {}), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`);
2759
3192
  const size = layoutSize(metrics);
2760
3193
  if (size !== undefined) {
@@ -2772,7 +3205,11 @@ export class ElectronBrowserProvider {
2772
3205
  }
2773
3206
  }
2774
3207
  }
2775
- const result = await withTimeout(handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`);
3208
+ // A region capture is a read: it must never present the conversation or
3209
+ // raise a window. Every other screenshot keeps the original call shape.
3210
+ const result = await withTimeout(region === undefined
3211
+ ? handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params)
3212
+ : handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params, { present: false }), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`);
2776
3213
  const data = result.data;
2777
3214
  if (typeof data !== 'string') {
2778
3215
  throw new BrowserError('browser: screenshot returned no image data', 'BROWSER_SCREENSHOT_FAILED');
@@ -2968,23 +3405,26 @@ export class ElectronBrowserProvider {
2968
3405
  }
2969
3406
  }
2970
3407
  /** Close the session and destroy all its views. Idempotent. */
2971
- close(session) {
3408
+ async close(session) {
2972
3409
  const existing = this.sessions.get(session);
2973
3410
  if (existing !== undefined) {
2974
3411
  this.sessions.delete(session);
2975
3412
  for (const tab of existing.tabs)
2976
- this.host.destroyView(tab.handle);
3413
+ this.destroyTab(tab);
2977
3414
  // Releasing the browser at session end is a setting, not fixed behaviour
2978
3415
  // (requirements §3). A self-hosted carrier already tore its window down with
2979
3416
  // the views above; the desktop's sidebar does not, so it is asked explicitly
2980
3417
  // — and its cookies plus the browsing history outlive the page either way.
2981
- if (this.settingsSource !== undefined && this.settingsSource().ui.closeWithSession) {
2982
- // Named, because one host serves every conversation: an unnamed release would end the
2983
- // pages of conversations that are still running.
2984
- void this.host.releasePage?.(existing.label).catch(() => undefined);
3418
+ try {
3419
+ if (this.settingsSource !== undefined && this.settingsSource().ui.closeWithSession) {
3420
+ // Never release another conversation's pages.
3421
+ await this.host.releasePage?.(this.carrierScope(existing));
3422
+ }
3423
+ }
3424
+ finally {
3425
+ await this.host.retireSession?.(session);
2985
3426
  }
2986
3427
  }
2987
- return Promise.resolve();
2988
3428
  }
2989
3429
  /** Look up a session or throw the unknown-session error. */
2990
3430
  session(session) {
@@ -2996,51 +3436,56 @@ export class ElectronBrowserProvider {
2996
3436
  }
2997
3437
  /** The active tab of a session. */
2998
3438
  activeTab(s) {
3439
+ if (this.carrierLaunchError !== undefined)
3440
+ throw this.carrierLaunchError;
2999
3441
  const tab = s.tabs[s.activeIndex];
3000
3442
  if (tab === undefined)
3001
3443
  throw new BrowserError('browser: session has no active tab', 'BROWSER_TAB_UNKNOWN');
3444
+ if (tab.failure !== undefined)
3445
+ throw tab.failure;
3002
3446
  return tab;
3003
3447
  }
3004
3448
  /** Append a fresh tab and make it active. */
3005
3449
  newTab(s) {
3006
- const handle = this.host.createView(s.label);
3450
+ const id = tabWireId({ ...resolveSessionHandle(s.id), tab: randomUUID() });
3451
+ const handle = this.host.createView(id);
3007
3452
  // Same window as the session's other tabs.
3008
3453
  this.host.groupView?.(handle, s.id, s.label);
3009
- s.tabs.push({ id: `tab:${randomUUID()}`, handle, url: '' });
3454
+ s.tabs.push({ id, handle, url: '' });
3010
3455
  s.activeIndex = s.tabs.length - 1;
3011
3456
  this.showActive(s);
3012
3457
  }
3013
- /**
3014
- * Swap a wedged view for a fresh blank one, keeping the tab's public id.
3015
- *
3016
- * A view whose renderer never commits cannot be read again: every evaluate into it runs out its
3017
- * whole budget. Replacing it is what turns that from permanent into one bad call — the tab id
3018
- * callers hold stays valid, and the next `dsh_browser_open` with the real URL re-populates it.
3019
- *
3020
- * The old view is destroyed AFTER the new one is in place, so a failure here cannot leave the
3021
- * session holding a handle that is already gone.
3022
- * @param s - the session owning the tab.
3023
- * @param tab - the tab to reset.
3024
- */
3025
- replaceTabWithBlank(s, tab) {
3026
- const index = s.tabs.indexOf(tab);
3027
- if (index < 0)
3028
- return;
3029
- let handle;
3030
- try {
3031
- handle = this.host.createView(s.label);
3032
- this.host.groupView?.(handle, s.id, s.label);
3033
- }
3034
- catch {
3035
- // Creating the replacement failed: leaving the wedged tab in place is worse than nothing
3036
- // only for the caller, who is about to be told the tab timed out either way.
3037
- return;
3458
+ carrierScope(s) {
3459
+ return s.id;
3460
+ }
3461
+ carrierTab(s, id) {
3462
+ const scope = resolveSessionHandle(s.id);
3463
+ return tabWireId(resolveTabHandle(scope, id));
3464
+ }
3465
+ carrierId(s, id) {
3466
+ const tab = resolveTabHandle(resolveSessionHandle(s.id), id).tab;
3467
+ if (!tab.startsWith('page:') && this.host.closePage === undefined)
3468
+ return undefined;
3469
+ return id;
3470
+ }
3471
+ destroyTab(tab, options) {
3472
+ tab.navigationAbort?.abort(new BrowserError('browser: the navigation guest was closed', 'BROWSER_GUEST_CLOSED'));
3473
+ this.host.destroyView(tab.handle, options);
3474
+ }
3475
+ interrupt(handle, timedOut) {
3476
+ if (timedOut)
3477
+ this.quarantine(handle);
3478
+ else
3479
+ terminatePage(handle);
3480
+ }
3481
+ quarantine(handle) {
3482
+ for (const session of this.sessions.values()) {
3483
+ const tab = session.tabs.find(tab => tab.handle === handle);
3484
+ if (tab === undefined || tab.failure !== undefined)
3485
+ continue;
3486
+ tab.failure = new BrowserError('browser: this guest stopped acknowledging operations and is quarantined; close this tab or explicitly reset the session before retrying', 'BROWSER_GUEST_QUARANTINED');
3487
+ terminatePage(handle);
3038
3488
  }
3039
- const wedged = tab.handle;
3040
- s.tabs[index] = { id: tab.id, handle, url: '' };
3041
- if (index === s.activeIndex)
3042
- this.showActive(s);
3043
- this.host.destroyView(wedged);
3044
3489
  }
3045
3490
  /** Find a session's tab by its backing view id (toolbar actions carry view ids). */
3046
3491
  tabByViewId(s, viewId) {
@@ -3066,6 +3511,13 @@ export class ElectronBrowserProvider {
3066
3511
  watchableSessions() {
3067
3512
  return [...this.sessions.keys()];
3068
3513
  }
3514
+ takeoverTargets(owner) {
3515
+ return [...this.sessions.values()].filter(s => (s.label ?? 'default').replace(/^session-/u, '') === owner).flatMap(s => {
3516
+ const tab = s.tabs[s.activeIndex];
3517
+ return tab && !tab.failure && /^https?:\/\//u.test(tab.url)
3518
+ ? [{ session: s.id, owner: s.label ?? 'default', tabId: tab.id, pageId: tab.id, url: tab.url }] : [];
3519
+ });
3520
+ }
3069
3521
  /**
3070
3522
  * The human closed a browser window: the session that window showed is over.
3071
3523
  * Ending it here is what makes the next call a clean start rather than a
@@ -3087,7 +3539,7 @@ export class ElectronBrowserProvider {
3087
3539
  * URL typed into the address bar) must never crash the host UI loop — it
3088
3540
  * is reported to the host (toolbar) when the host supports it, else logged.
3089
3541
  */
3090
- async handleUserAction(action) {
3542
+ async handleUserAction(action, propagate = false) {
3091
3543
  const s = this.sessions.get(action.windowId);
3092
3544
  if (s === undefined) {
3093
3545
  // The window the human clicked in has no live session here (session
@@ -3096,10 +3548,26 @@ export class ElectronBrowserProvider {
3096
3548
  const message = `action ${action.type} failed: no live browser session for window "${action.windowId}"`;
3097
3549
  process.stderr.write(`[dsh-browser] ${message}\n`);
3098
3550
  this.notifyUserActionError(action, new Error('no live browser session'));
3551
+ if (propagate)
3552
+ throw new Error('no live browser session');
3099
3553
  return;
3100
3554
  }
3101
3555
  try {
3102
3556
  switch (action.type) {
3557
+ case 'capture-reference':
3558
+ // The human clicked a native menu item or the page's floating entry.
3559
+ // Delivery is owned by the plugin entry, which holds the reference
3560
+ // service; the provider only routes the action to the right session.
3561
+ await dispatchReferenceCaptureAction({
3562
+ windowId: action.windowId,
3563
+ entry: action.entry,
3564
+ ...action.frameSelector !== undefined ? { frameSelector: action.frameSelector } : {},
3565
+ ...action.target !== undefined ? { target: action.target } : {},
3566
+ ...action.comment !== undefined ? { comment: action.comment } : {},
3567
+ ...action.selectionText !== undefined ? { selectionText: action.selectionText } : {},
3568
+ ...action.capture !== undefined ? { capture: action.capture } : {},
3569
+ });
3570
+ return;
3103
3571
  case 'navigate':
3104
3572
  await this.openUrl(s.id, { url: action.url });
3105
3573
  return;
@@ -3134,6 +3602,8 @@ export class ElectronBrowserProvider {
3134
3602
  }
3135
3603
  catch (error) {
3136
3604
  this.notifyUserActionError(action, error);
3605
+ if (propagate)
3606
+ throw error;
3137
3607
  }
3138
3608
  }
3139
3609
  /**
@@ -3189,7 +3659,9 @@ export class ElectronBrowserProvider {
3189
3659
  */
3190
3660
  showActive(s, select = false) {
3191
3661
  const quiet = this.isQuiet();
3192
- this.host.showView?.(this.activeTab(s).handle, s.label, { quiet, ...select ? { select: true } : {} });
3662
+ const active = s.tabs[s.activeIndex];
3663
+ if (active !== undefined)
3664
+ this.host.showView?.(active.handle, s.label, { quiet, ...select ? { select: true } : {} });
3193
3665
  if (quiet || select)
3194
3666
  return;
3195
3667
  const autoExpand = this.settingsSource === undefined || this.settingsSource().ui.autoExpandOnce;
@@ -3201,16 +3673,11 @@ export class ElectronBrowserProvider {
3201
3673
  /** Read the current URL of a view through CDP. */
3202
3674
  async currentUrl(handle) {
3203
3675
  // Bound the read: a wedged renderer would otherwise hang listTabs.
3204
- const timeoutMs = 10_000;
3205
- const result = await withTimeout(handleSendEvaluate(handle, 'location.href'), timeoutMs, undefined, `browser: url read timed out after ${timeoutMs}ms`, () => terminatePage(handle));
3676
+ const timeoutMs = PROVIDER_TIMEOUTS.lookup;
3677
+ const result = await withTimeout(handleSendEvaluate(handle, 'location.href'), timeoutMs, undefined, `browser: url read timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(handle, timedOut); });
3206
3678
  return result.ok && typeof result.value === 'string' ? result.value : '';
3207
3679
  }
3208
3680
  }
3209
- /**
3210
- * Hard cap on waiting for a navigation's new document to be parsed. Bounded and
3211
- * best-effort: a page that never settles must not fail the navigation.
3212
- */
3213
- const SETTLE_TIMEOUT_MS = 5_000;
3214
3681
  /**
3215
3682
  * Bounds for one passive preview frame.
3216
3683
  *
@@ -3223,12 +3690,6 @@ const PREVIEW_CAPTURE_MS = 2_000;
3223
3690
  const PREVIEW_QUALITY = 70;
3224
3691
  const PREVIEW_MAX_WIDTH = 1280;
3225
3692
  const PREVIEW_MAX_HEIGHT = 720;
3226
- /**
3227
- * When the document already looks settled but its identity has NOT changed
3228
- * (same-document navigation, or the outgoing document still answering), wait
3229
- * only this long before returning — there is no parse in flight to wait for.
3230
- */
3231
- const SETTLE_GRACE_MS = 150;
3232
3693
  /** Poll interval for the document-settle loop. */
3233
3694
  const SETTLE_POLL_MS = 25;
3234
3695
  /**
@@ -3237,10 +3698,6 @@ const SETTLE_POLL_MS = 25;
3237
3698
  * must outlast it or its generic timeout hides the in-page reason.
3238
3699
  */
3239
3700
  const TARGET_SCRIPT_GRACE_MS = 2_000;
3240
- /** `tab:<uuid>` ↔ `<uuid>`: ids accept either form (see locateTab). */
3241
- function stripTabPrefix(id) {
3242
- return id.startsWith('tab:') ? id.slice(4) : id;
3243
- }
3244
3701
  /** Abortable sleep used by the settle loop. */
3245
3702
  function delay(ms, signal) {
3246
3703
  return new Promise((resolve) => {
@@ -3279,7 +3736,7 @@ function withTimeout(promise, ms, signal, message, onCancel) {
3279
3736
  error.name = 'TimeoutError';
3280
3737
  reject(error);
3281
3738
  // Best-effort interrupt of the underlying CDP call (see onCancel).
3282
- onCancel?.();
3739
+ onCancel?.(true);
3283
3740
  }, ms);
3284
3741
  const finish = (fn) => {
3285
3742
  if (done)
@@ -3296,7 +3753,7 @@ function withTimeout(promise, ms, signal, message, onCancel) {
3296
3753
  done = true;
3297
3754
  clearTimeout(timer);
3298
3755
  reject(signal?.reason instanceof Error ? signal.reason : new Error('aborted'));
3299
- onCancel?.();
3756
+ onCancel?.(false);
3300
3757
  };
3301
3758
  if (signal !== undefined)
3302
3759
  signal.addEventListener('abort', onAbort, { once: true });
@@ -3320,7 +3777,7 @@ function terminatePage(handle) {
3320
3777
  if (count >= MAX_PENDING_TERMINATIONS)
3321
3778
  return;
3322
3779
  pendingTerminations.set(handle, count + 1);
3323
- void handle.sendCommand('Runtime.terminateExecution').finally(() => {
3780
+ void handle.sendCommand('Runtime.terminateExecution', undefined, { present: false, initialize: false }).finally(() => {
3324
3781
  pendingTerminations.set(handle, Math.max(0, (pendingTerminations.get(handle) ?? 1) - 1));
3325
3782
  }).catch(() => { });
3326
3783
  }