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,15 +9,22 @@
7
9
  * @module dsh-browser/browser-electron
8
10
  */
9
11
 
10
- import { pageOperationScript } from '../tool-browser/page-probe.js'
12
+ import { pageOperationScript } from '../tool-browser/page-probe.ts'
13
+ import { dispatchReferenceCaptureAction } from '../browser-reference/service.ts'
14
+ import {
15
+ MAX_REFERENCE_COMMENT, REFERENCE_INTENT_CHANNEL, overlayScript, standaloneScript,
16
+ } from '../browser-reference/entry.ts'
17
+ import { noticeScript, validateFrozenCapture, type RawCaptureResult } from '../browser-reference/page-script.ts'
11
18
  import { randomUUID } from 'node:crypto'
19
+ import { setLastOpen } from './open-slot.ts'
12
20
  import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs'
13
- import { writeFileNoReplace } from './file-write.js'
21
+ import { writeFileNoReplace } from './file-write.ts'
14
22
  import { homedir } from 'node:os'
15
23
  import { dirname, isAbsolute, join, resolve, sep } from 'node:path'
16
- import { HistoryStore, type VisitedPage } from './history-store.js'
17
- import type { BrowserSettings } from './settings-store.js'
18
- import { forgetCursor, paintCursor, type CursorAction } from './virtual-cursor.js'
24
+ import { HistoryStore, type VisitedPage } from './history-store.ts'
25
+ import type { BrowserSettings } from './settings-store.ts'
26
+ import { forgetCursor, paintCursor, type CursorAction } from './virtual-cursor.ts'
27
+ import { documentReady, mainDocument, type DocumentIdentity } from './document-readiness.ts'
19
28
  import type {
20
29
  BrowserA11yRequest,
21
30
  BrowserA11yResult,
@@ -54,9 +63,28 @@ import type {
54
63
  BrowserScrollRequest,
55
64
  BrowserKeyRequest,
56
65
  ExportedCookie,
57
- } from '../browser/types.js'
58
- import { BrowserError } from '../browser/types.js'
59
- import type { CarrierPage, CarrierLossReason } from '../browser/types.js'
66
+ } from '../browser/types.ts'
67
+ import { BrowserError } from '../browser/types.ts'
68
+ import { browserSessionHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId, type BrowserTabWireId } from '../browser/handles.ts'
69
+ import type { CarrierPage, CarrierLossReason } from '../browser/types.ts'
70
+ import type { BrowserReferenceTarget } from '../browser-reference/types.ts'
71
+
72
+ /**
73
+ * Consecutive failed evaluations after which the reference pump forgets an
74
+ * adopted sidebar tab. One or two misses are a navigation; five (≈6 s at the
75
+ * pump's 1.2 s tick) mean the page the human had is gone.
76
+ */
77
+ const DEAD_REFERENCE_TAB_MISSES = 5
78
+ /** How long a tab that stopped answering waits before the pump tries it again. */
79
+ const DEAD_REFERENCE_TAB_RETRY_MS = 15_000
80
+ const PROVIDER_TIMEOUTS = Object.freeze({
81
+ evaluation: 3_000,
82
+ interaction: 5_000,
83
+ lookup: 10_000,
84
+ action: 15_000,
85
+ prepare: DEFAULT_OPERATION_TIMEOUT_MS + 1_000,
86
+ download: 60_000,
87
+ })
60
88
 
61
89
  /**
62
90
  * Page-context human-verification (CAPTCHA / bot-detection) detection. Runs
@@ -120,6 +148,10 @@ export const ELECTRON_BROWSER_PROVIDER_ID = 'electron'
120
148
  * desktop shell with a real `WebContentsView`; a fake implements it in tests.
121
149
  */
122
150
  export interface ElectronBrowserViewHost {
151
+ prepare?(scope?: BrowserSessionId): Promise<void>
152
+ readonly referenceOverlayOwner?: 'client'
153
+ referenceOverlayOwnerFor?(scope: BrowserSessionId): 'client' | undefined
154
+ retireSession?(scope: BrowserSessionId): Promise<void>
123
155
  /**
124
156
  * Create a new browser view and return a handle to its webContents-like
125
157
  * surface. The host owns windowing (adding the view to the window, sizing,
@@ -130,13 +162,13 @@ export interface ElectronBrowserViewHost {
130
162
  * single instance that every conversation runs through, so an owner held there would be one
131
163
  * conversation's id applied to all of them.
132
164
  */
133
- createView(owner?: string): ElectronViewHandle
165
+ createView(identity: BrowserTabWireId): ElectronViewHandle
134
166
  /**
135
167
  * Destroy a view created by this host. Called on session close; idempotent
136
168
  * for an already-destroyed view.
137
169
  * @param handle - the handle returned by {@link createView}.
138
170
  */
139
- destroyView(handle: ElectronViewHandle): void
171
+ destroyView(handle: ElectronViewHandle, options?: { readonly keepPage?: boolean }): void
140
172
  /**
141
173
  * Show one view as the session's visible surface. The host keeps exactly
142
174
  * one visible; switching tabs reorders visibility without losing state.
@@ -183,9 +215,13 @@ export interface ElectronBrowserViewHost {
183
215
  * `dsh_browser_list_tabs` reported one tab; on the installed-browser carrier the window held four
184
216
  * pages and the tool reported one.
185
217
  * @param owner - the calling task/conversation; shared sidebar hosts must scope to it.
218
+ * @param options - `requireRunning` lists only from a carrier that is already
219
+ * running. A background scan (the reference-bar pump) must use it: opening
220
+ * the human's installed browser just to look for a page is a side effect
221
+ * nobody asked for.
186
222
  * @returns every page this conversation's carrier holds that this host did not open.
187
223
  */
188
- listPages?(owner?: string): Promise<readonly CarrierPage[]>
224
+ listPages?(scope: BrowserSessionId, options?: { readonly requireRunning?: boolean }): Promise<readonly CarrierPage[]>
189
225
  /**
190
226
  * Optional: take over one page reported by {@link listPages}, so it becomes a page this provider
191
227
  * drives rather than one it can only see.
@@ -199,7 +235,7 @@ export interface ElectronBrowserViewHost {
199
235
  * @param id - the carrier's own page id, as {@link listPages} reported it.
200
236
  * @returns a handle for that page, usable for commands like any other view's.
201
237
  */
202
- adoptPage?(id: string): Promise<ElectronViewHandle>
238
+ adoptPage?(id: BrowserTabWireId, scope?: BrowserSessionId): Promise<ElectronViewHandle>
203
239
  /**
204
240
  * Optional: close one page reported by {@link listPages}.
205
241
  *
@@ -209,7 +245,7 @@ export interface ElectronBrowserViewHost {
209
245
  * @param id - the carrier's own page id, as {@link listPages} reported it.
210
246
  * @param owner - the same task/conversation used for listing; never a global fallback.
211
247
  */
212
- closePage?(id: string, owner?: string): Promise<void>
248
+ closePage?(id: BrowserTabWireId, scope?: BrowserSessionId): Promise<void>
213
249
  /**
214
250
  * Optional cheap usability probe (no network): whether the host can back
215
251
  * views at all right now. The self-hosted host checks for a usable Electron
@@ -270,7 +306,7 @@ export interface ElectronBrowserViewHost {
270
306
  * @param owner - the conversation whose pages to close. Omit to close every conversation's,
271
307
  * which is only correct from a teardown that is itself global.
272
308
  */
273
- releasePage?(owner?: string): Promise<void>
309
+ releasePage?(scope?: BrowserSessionId): Promise<void>
274
310
  /**
275
311
  * Report that this carrier can no longer serve anything, so its owner may replace it.
276
312
  *
@@ -317,6 +353,26 @@ export type BrowserUserAction =
317
353
  | { readonly type: 'back'; readonly windowId: string }
318
354
  | { readonly type: 'forward'; readonly windowId: string }
319
355
  | { readonly type: 'reload'; readonly windowId: string }
356
+ | {
357
+ readonly type: 'capture-reference'
358
+ readonly windowId: string
359
+ readonly entry: 'native-menu' | 'page-overlay'
360
+ readonly frameSelector?: string
361
+ /** The exact image/table the human right-clicked, if any. */
362
+ readonly target?: BrowserReferenceTarget
363
+ /** The note typed in the selection bar. */
364
+ readonly comment?: string
365
+ /**
366
+ * The selection text the bar froze before its comment field took focus.
367
+ * Used to locate the capture again when the live selection is gone.
368
+ */
369
+ readonly selectionText?: string
370
+ /**
371
+ * The complete ordered capture the bar froze at that same moment (text
372
+ * runs, assets, table ranges, anchors). Preferred over `selectionText`.
373
+ */
374
+ readonly capture?: RawCaptureResult
375
+ }
320
376
 
321
377
  /**
322
378
  * A CDP-capable view handle. This is the subset of Electron's
@@ -390,13 +446,22 @@ export interface ElectronViewHandle {
390
446
  * probing a tab it already knows is blank, where a probe is a round trip on an uncommitted view
391
447
  * that can only answer nothing.
392
448
  *
393
- * `handle` is deliberately NOT readonly: a view that has wedged is replaced in place, and the tab
394
- * keeps its public id across that replacement (see `replaceTabWithBlank`).
449
+ * A failed guest stays attached to its tab until the caller explicitly closes or resets it.
395
450
  */
396
451
  interface Tab {
397
- readonly id: string
398
- handle: ElectronViewHandle
452
+ readonly id: BrowserTabWireId
453
+ readonly handle: ElectronViewHandle
399
454
  url: string
455
+ navigation?: symbol
456
+ navigationAbort?: AbortController
457
+ failure?: BrowserError
458
+ /**
459
+ * Consecutive failed page evaluations, used only by the reference pump to tell
460
+ * "mid-navigation" (retried) from "this page is gone for now" (backed off).
461
+ */
462
+ misses?: number
463
+ /** Earliest time the reference pump may try this page again. */
464
+ retryAt?: number
400
465
  }
401
466
 
402
467
  /** One live browser session: an ordered list of tabs, one active. */
@@ -459,6 +524,16 @@ export interface ElectronBrowserProviderConfig {
459
524
  * a production deployment should set an explicit, verified path.
460
525
  */
461
526
  readonly downloadDir?: string
527
+ /**
528
+ * The conversation this process serves, when the composition knows it.
529
+ *
530
+ * The reference entry needs it to find the page the human has open in THIS
531
+ * conversation's sidebar: the shell exposes a panel's pages by conversation id,
532
+ * and a page bound under the wrong id would either be refused or wired into
533
+ * another conversation's draft. Absent on hosts that do not name it (a plain
534
+ * `dsh web`), where the sidebar entry simply does not apply.
535
+ */
536
+ readonly referenceLabel?: string | (() => string | undefined)
462
537
  }
463
538
 
464
539
  /**
@@ -645,6 +720,8 @@ export interface PresentOptions {
645
720
  * to fix.
646
721
  */
647
722
  export interface CommandOptions {
723
+ readonly deadline?: number
724
+ readonly signal?: AbortSignal
648
725
  /** Present the view first (default), or only use a page that is already there. */
649
726
  readonly present?: boolean
650
727
  /** Only use a guest already attached to this handle, without sidebar initialization. */
@@ -792,6 +869,37 @@ export class ElectronBrowserProvider implements BrowserProvider {
792
869
  readonly id = ELECTRON_BROWSER_PROVIDER_ID
793
870
 
794
871
  private readonly sessions = new Map<BrowserSessionId, Session>()
872
+ private carrierLaunchError: unknown
873
+ /**
874
+ * Tick that installs the selection bar in every live tab and collects what the
875
+ * human confirmed. The Desktop sidebar carrier is the shell's own <webview>:
876
+ * the page has no preload bridge and the bridge protocol carries no user-action
877
+ * channel, so the bar leaves its intent in `window.__dshRefIntents` and this
878
+ * pump takes it over CDP. Without it the sidebar has no reference entry.
879
+ */
880
+ private referencePump: ReturnType<typeof setInterval> | undefined
881
+ /** Guards against overlapping pump runs (setInterval keeps firing while one is slow). */
882
+ private referencePumping = false
883
+ /**
884
+ * Set once the carrier swapped to a newer provider. `onUserAction` and
885
+ * `onViewClosed` return void and cannot be unsubscribed, so the callbacks
886
+ * themselves must go inert: otherwise one human click is handled by every
887
+ * old provider still retained by the view host, producing duplicate cards.
888
+ */
889
+ private disposed = false
890
+ /**
891
+ * The session bound to the page the human has open, created on first sight.
892
+ *
893
+ * A reference is captured from a browser SESSION, and a page the human opened from
894
+ * the sidebar's own address bar belongs to no session of ours. Adopting it into one
895
+ * is what makes the selection bar appear there at all — and it is done here, inside
896
+ * the pump, so it needs nothing from the human and nothing from the agent.
897
+ */
898
+ private referenceSession: BrowserSessionId | undefined
899
+ /** Ticks between sidebar page scans while nothing is adopted yet. */
900
+ private referenceScanCountdown = 0
901
+ /** Last scan's diagnosis, surfaced by {@link referenceStatus}. */
902
+ private readonly referenceScan: { label?: string; pages: number; lastError?: string } = { pages: 0 }
795
903
  private readonly httpOnly: boolean
796
904
  private readonly snapshotMaxElements: number
797
905
  private readonly contentMaxChars: number | undefined
@@ -806,7 +914,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
806
914
 
807
915
  constructor(
808
916
  private readonly host: ElectronBrowserViewHost,
809
- config: ElectronBrowserProviderConfig = {},
917
+ private readonly config: ElectronBrowserProviderConfig = {},
810
918
  ) {
811
919
  this.httpOnly = config.httpOnly ?? true
812
920
  this.snapshotMaxElements = config.snapshotMaxElements ?? 60
@@ -828,10 +936,252 @@ export class ElectronBrowserProvider implements BrowserProvider {
828
936
  })
829
937
  // Route toolbar (host UI) actions into the session model: the human and
830
938
  // the agent then always drive the same tabs, history, and navigation.
831
- this.host.onUserAction?.(action => { void this.handleUserAction(action) })
939
+ this.host.onUserAction?.(action => { if (!this.disposed) void this.handleUserAction(action) })
832
940
  // A window the human closed ends the session it showed: the next call opens a
833
941
  // clean one instead of driving a page nobody can see.
834
- this.host.onViewClosed?.(windowId => { void this.handleViewClosed(windowId) })
942
+ this.host.onViewClosed?.(windowId => { if (!this.disposed) void this.handleViewClosed(windowId) })
943
+ this.startReferenceEntryPump()
944
+ }
945
+
946
+ /** Retire a provider after a carrier swap; its listeners must not act again. */
947
+ dispose(): void {
948
+ this.disposed = true
949
+ this.stopReferenceEntryPump()
950
+ }
951
+
952
+ /** Start the page-bar pump; idempotent, unref'd so it never holds the process. */
953
+ private startReferenceEntryPump(): void {
954
+ if (this.host.referenceOverlayOwner === 'client' || this.referencePump !== undefined) return
955
+ this.referencePump = setInterval(() => { void this.pumpReferenceEntry() }, 1200)
956
+ this.referencePump.unref?.()
957
+ }
958
+
959
+ /** Stop the pump (session teardown / tests). */
960
+ stopReferenceEntryPump(): void {
961
+ if (this.referencePump === undefined) return
962
+ clearInterval(this.referencePump)
963
+ this.referencePump = undefined
964
+ }
965
+
966
+ /**
967
+ * Install the bar where it is missing and forward one confirmed intent.
968
+ *
969
+ * Re-injection is what makes this survive navigation: a new document has no
970
+ * `__dshRefOverlayInstalled`, so the next tick installs the bar again.
971
+ *
972
+ * One run at a time: `setInterval` fires again whether or not the previous
973
+ * run finished, and a page that stopped answering would otherwise stack CDP
974
+ * commands behind the wedged renderer on every tick.
975
+ */
976
+ private async pumpReferenceEntry(): Promise<void> {
977
+ if (this.referencePumping) return
978
+ this.referencePumping = true
979
+ try {
980
+ await this.adoptSidebarPageForReference().catch(() => undefined)
981
+ for (const session of [...this.sessions.values()]) {
982
+ if (this.host.referenceOverlayOwnerFor?.(session.id) === 'client') continue
983
+ for (const tab of [...session.tabs]) {
984
+ await this.pumpOneTab(session, tab)
985
+ // A tab is never dropped for being unreachable: the page is the
986
+ // person's own sidebar page, and the host excludes every page it
987
+ // adopted from later listings, so letting go of the handle would
988
+ // close our only route back to it.
989
+ }
990
+ }
991
+ } finally {
992
+ this.referencePumping = false
993
+ }
994
+ }
995
+
996
+ /**
997
+ * Install or collect on one tab.
998
+ * @returns false when the page failed enough consecutive times to be gone.
999
+ */
1000
+ private async pumpOneTab(session: Session, tab: Tab): Promise<boolean> {
1001
+ if (tab.failure !== undefined) return false
1002
+ // A page that stopped answering is retried on a slow timer instead of being
1003
+ // dropped: navigations and renderer swaps both look like death for a moment.
1004
+ if (tab.retryAt !== undefined && Date.now() < tab.retryAt) return true
1005
+ try {
1006
+ // One round-trip per tab: a missing bar answers "install"; otherwise the
1007
+ // same evaluation hands back a confirmed intent.
1008
+ const probe = await this.evaluateInTab(tab, [
1009
+ 'window.__dshRefOverlayInstalled !== true ? "install"',
1010
+ ': (window.__dshRefTake ? window.__dshRefTake() : null)',
1011
+ ].join(''), PROVIDER_TIMEOUTS.evaluation)
1012
+ tab.misses = 0
1013
+ tab.retryAt = undefined
1014
+ if (probe === 'install') {
1015
+ await this.evaluateInTab(tab, standaloneScript(overlayScript(), {}), PROVIDER_TIMEOUTS.interaction)
1016
+ return true
1017
+ }
1018
+ if (probe === null || probe === undefined) return true
1019
+ try {
1020
+ if (typeof probe !== 'object') throw new Error('reference intent is invalid')
1021
+ const record = probe as Record<string, unknown>
1022
+ if (record.type !== REFERENCE_INTENT_CHANNEL) throw new Error('reference intent channel is invalid')
1023
+ const rawComment = typeof record.comment === 'string' ? record.comment.trim() : ''
1024
+ const rawSelection = typeof record.selectionText === 'string' ? record.selectionText.trim() : ''
1025
+ const capture = validateFrozenCapture(record.capture)
1026
+ if (capture === undefined) throw new Error('reference intent has no captured content')
1027
+ await this.handleUserAction({
1028
+ type: 'capture-reference',
1029
+ windowId: session.id,
1030
+ entry: 'page-overlay',
1031
+ ...rawComment !== '' ? { comment: rawComment.slice(0, MAX_REFERENCE_COMMENT) } : {},
1032
+ ...rawSelection !== '' ? { selectionText: rawSelection } : {},
1033
+ capture,
1034
+ }, true)
1035
+ } catch (error) {
1036
+ this.referenceScan.lastError = 'capture refused: ' + (error instanceof Error ? error.message : String(error))
1037
+ process.stderr.write(`[dsh-browser] ${this.referenceScan.lastError}\n`)
1038
+ try {
1039
+ await this.evaluateInTab(tab, standaloneScript(noticeScript(hostMessages.zh.referenceFailed)), PROVIDER_TIMEOUTS.evaluation)
1040
+ } catch { /* The failure remains in host diagnostics when the guest disappears. */ }
1041
+ }
1042
+ return true
1043
+ } catch {
1044
+ // A tab mid-navigation has no execution context yet; the next tick retries.
1045
+ // A page that keeps failing backs off instead of being forgotten: the
1046
+ // handle is the only way back to a page this host adopted, and dropping it
1047
+ // made the bar stop delivering for the rest of the conversation.
1048
+ tab.misses = (tab.misses ?? 0) + 1
1049
+ if (tab.misses >= DEAD_REFERENCE_TAB_MISSES) {
1050
+ tab.misses = 0
1051
+ tab.retryAt = Date.now() + DEAD_REFERENCE_TAB_RETRY_MS
1052
+ }
1053
+ return true
1054
+ }
1055
+ }
1056
+
1057
+ /** Forget one dead adopted tab; the conversation's next page starts a fresh session. */
1058
+
1059
+ /**
1060
+ * Bind the page the human has open in this conversation's sidebar into a session.
1061
+ *
1062
+ * Why this is the whole entry: the sidebar page is the shell's, opened by a person
1063
+ * through the address bar, so no session of ours names it and nothing injects the
1064
+ * selection bar into it. The shell DOES expose the panel's pages by conversation id
1065
+ * (`listPages`), and can hand one over (`adoptPage`) — the same pair the tools use
1066
+ * for `dsh_browser_list_tabs`. Doing it on a timer means the bar appears on a page
1067
+ * the human opened themselves, which is the only entry they actually take.
1068
+ *
1069
+ * Rescans are spaced by one idle tick, not five: the listing crosses the
1070
+ * bridge, and a page the human just opened must get its entry within a
1071
+ * couple of seconds rather than five.
1072
+ */
1073
+ private async adoptSidebarPageForReference(): Promise<void> {
1074
+ const configured = this.config.referenceLabel
1075
+ const label = typeof configured === 'function' ? configured() : configured
1076
+ this.referenceScan.label = label
1077
+ if (label === undefined || label === '') return
1078
+ if (this.host.listPages === undefined || this.host.adoptPage === undefined) {
1079
+ this.referenceScan.lastError = 'this carrier cannot list or adopt a page it did not open'
1080
+ return
1081
+ }
1082
+ if (this.referenceScanCountdown > 0) { this.referenceScanCountdown -= 1; return }
1083
+ // One idle tick between scans: a page the human opens must get its entry
1084
+ // within a couple of seconds (measured: the shell creates the guest, then
1085
+ // the next scan adopts it). The listing is a local bridge call, not a
1086
+ // network request, so this is cheap.
1087
+ this.referenceScanCountdown = 1
1088
+ let session = this.referenceSession === undefined ? undefined : this.sessions.get(this.referenceSession)
1089
+ if (session?.label !== label) session = undefined
1090
+ const candidate: Session = session ?? {
1091
+ id: sessionWireId(browserSessionHandle(label, randomUUID())), label,
1092
+ tabs: [], activeIndex: 0, history: [], nextSeq: 1,
1093
+ }
1094
+ let pages: readonly CarrierPage[]
1095
+ try {
1096
+ // `requireRunning` is what keeps a scan from launching the human's
1097
+ // installed browser: only a carrier that is already up can have pages.
1098
+ pages = await this.host.listPages(this.carrierScope(candidate), { requireRunning: true })
1099
+ } catch (error) {
1100
+ this.referenceScan.lastError = error instanceof Error ? error.message : String(error)
1101
+ return
1102
+ }
1103
+ this.referenceScan.pages = pages.length
1104
+ const live = pages.filter(candidate => /^https?:\/\//iu.test(candidate.url))
1105
+ // NOT pruned. The host's listing already EXCLUDES the pages this process
1106
+ // adopted (that exclusion is what keeps `listTabs` from reporting one page
1107
+ // twice), so "absent from the listing" means "already adopted" as often as
1108
+ // it means "closed". Dropping those tabs would lose the bar on every page
1109
+ // the human switches away from and re-adopt it under a new handle on the
1110
+ // way back. A closed page's handle simply stops answering, and the pump
1111
+ // already skips a tab it cannot evaluate.
1112
+ if (live.length === 0) {
1113
+ this.referenceScan.lastError = 'no http page is open in this conversation\'s sidebar'
1114
+ return
1115
+ }
1116
+ let refused: string | undefined
1117
+ for (const page of live) {
1118
+ const tabId = this.carrierTab(candidate, page.id)
1119
+ const existing = session?.tabs.find(tab => tab.id === tabId)
1120
+ if (existing !== undefined) {
1121
+ // A navigation changes the URL of a page we already hold.
1122
+ if (existing.url !== page.url) existing.url = page.url
1123
+ continue
1124
+ }
1125
+ try {
1126
+ // The owner is passed so the adopted view is released with THIS
1127
+ // conversation and not swept up by, or lost to, another one.
1128
+ const handle = await this.host.adoptPage(this.carrierTab(candidate, page.id), this.carrierScope(candidate))
1129
+ if (session === undefined) {
1130
+ session = candidate
1131
+ this.sessions.set(session.id, session)
1132
+ this.referenceSession = session.id
1133
+ }
1134
+ // Append only: discovery must never switch the page the human is
1135
+ // looking at, nor open a tab they did not ask for.
1136
+ session.tabs.push({ id: tabId, handle, url: page.url })
1137
+ } catch (error) {
1138
+ refused = error instanceof Error ? error.message : String(error)
1139
+ }
1140
+ }
1141
+ if (session !== undefined) {
1142
+ session.activeIndex = Math.min(session.activeIndex, Math.max(0, session.tabs.length - 1))
1143
+ }
1144
+ this.referenceScan.lastError = session === undefined
1145
+ ? refused ?? 'no page could be adopted'
1146
+ : refused
1147
+ }
1148
+
1149
+ /**
1150
+ * What the sidebar reference entry is doing right now.
1151
+ *
1152
+ * Served on the reference route so "there is no selection bar on my page" has an
1153
+ * answer that is not a guess: which conversation this process thinks it serves,
1154
+ * whether a page was adopted, how many the shell reported, and the last refusal.
1155
+ */
1156
+ referenceStatus(): { readonly label?: string; readonly session?: string; readonly pages: number; readonly lastError?: string } {
1157
+ return {
1158
+ ...this.referenceScan.label === undefined ? {} : { label: this.referenceScan.label },
1159
+ ...this.referenceSession === undefined ? {} : { session: this.referenceSession },
1160
+ pages: this.referenceScan.pages,
1161
+ ...this.referenceScan.lastError === undefined ? {} : { lastError: this.referenceScan.lastError },
1162
+ }
1163
+ }
1164
+
1165
+ /**
1166
+ * Evaluate one expression in a tab and return its value.
1167
+ *
1168
+ * Bounded on purpose: the pump runs on a timer, and an unresponsive renderer
1169
+ * would otherwise hold the whole tick (and every later one) forever.
1170
+ * @param tab - the tab to evaluate in.
1171
+ * @param expression - the JS expression.
1172
+ * @param timeoutMs - how long to wait before treating the page as not answering.
1173
+ */
1174
+ private async evaluateInTab(tab: Tab, expression: string, timeoutMs: number = PROVIDER_TIMEOUTS.evaluation): Promise<unknown> {
1175
+ const raw = await withTimeout(
1176
+ tab.handle.sendCommand('Runtime.evaluate', {
1177
+ expression, returnByValue: true, awaitPromise: true,
1178
+ }),
1179
+ timeoutMs,
1180
+ undefined,
1181
+ `browser: reference probe timed out after ${timeoutMs}ms`,
1182
+ )
1183
+ const result = (raw as { result?: { value?: unknown } }).result
1184
+ return result?.value
835
1185
  }
836
1186
 
837
1187
  /**
@@ -855,19 +1205,61 @@ export class ElectronBrowserProvider implements BrowserProvider {
855
1205
  // The label is the calling DSH task, and it is handed to the view as its owner: a host shared
856
1206
  // by several conversations (the desktop's) keeps one conversation's page out of another's on
857
1207
  // the strength of it, so it is not decoration.
858
- const handle = this.host.createView(label)
859
- const id = `browser:${randomUUID()}`
1208
+ const id = sessionWireId(browserSessionHandle(label || 'default', randomUUID()))
1209
+ const tabId = tabWireId({ ...resolveSessionHandle(id), tab: randomUUID() })
1210
+ const handle = this.host.createView(tabId)
860
1211
  // Group the session's views under its own window (one window per
861
1212
  // session), carrying the label for the window title. Hosts without
862
1213
  // groupView keep the shared-window behavior.
863
1214
  this.host.groupView?.(handle, id, label)
864
- this.sessions.set(id, { id, label, tabs: [{ id: `tab:${randomUUID()}`, handle, url: '' }], activeIndex: 0, history: [], nextSeq: 1 })
1215
+ this.sessions.set(id, { id, label, tabs: [{ id: tabId, handle, url: '' }], activeIndex: 0, history: [], nextSeq: 1 })
865
1216
  return Promise.resolve(id)
866
1217
  }
867
1218
 
868
- /** Open a URL in the active tab (default) or a new tab. */
1219
+ private async prepareCarrier(signal?: AbortSignal, scope?: BrowserSessionId): Promise<void> {
1220
+ if (this.host.prepare === undefined) return
1221
+ signal?.throwIfAborted()
1222
+ try {
1223
+ await withTimeout(this.host.prepare(scope), PROVIDER_TIMEOUTS.prepare, signal, 'browser: carrier launch timed out before navigating a guest')
1224
+ this.carrierLaunchError = undefined
1225
+ } catch (error) {
1226
+ if (!signal?.aborted) this.carrierLaunchError = error
1227
+ throw error
1228
+ }
1229
+ }
1230
+
1231
+ async bindPage(session: BrowserSessionId, pageId: BrowserTabWireId): Promise<void> {
1232
+ const s = this.session(session)
1233
+ if (this.host.adoptPage === undefined || !s.label) throw new Error('sidebar page binding unsupported')
1234
+ if (s.tabs.some(tab => tab.url !== '')) throw new Error('source binding requires a fresh browser session')
1235
+ const id = tabWireId(resolveTabHandle(resolveSessionHandle(s.id), pageId))
1236
+ const handle = await this.host.adoptPage(id, this.carrierScope(s))
1237
+ const previous = [...s.tabs]
1238
+ s.tabs.splice(0, s.tabs.length, { id: this.carrierTab(s, id), handle, url: '' })
1239
+ s.activeIndex = 0
1240
+ for (const tab of previous) this.destroyTab(tab)
1241
+ }
1242
+
1243
+ /**
1244
+ * The most recent open request, for the Web sidebar.
1245
+ *
1246
+ * On the desktop shell the host half tells the shell to place a tab (`__dshBuiltinBrowser.openPanel`)
1247
+ * through the bridge. The Web shell has no such channel, so a tool-opened page lived only in the
1248
+ * plugin's own browser while the panel stayed empty — and "open it in the sidebar" took several manual
1249
+ * steps. The client polls this one slot and places the tab itself.
1250
+ * @returns the last request and when it arrived, or undefined when nothing was opened yet.
1251
+ */
1252
+ lastOpenRequest(): { readonly url: string; readonly at: number } | undefined {
1253
+ return this.lastOpen
1254
+ }
1255
+
1256
+ /** Set by {@link openUrl}; read by the client through the HTTP surface. */
1257
+ private lastOpen: { readonly url: string; readonly at: number } | undefined
1258
+
869
1259
  async openUrl(session: BrowserSessionId, request: BrowserOpenRequest, signal?: AbortSignal): Promise<void> {
1260
+ try { setLastOpen(request.url, Date.now()) } catch { /* best effort */ }
870
1261
  const s = this.session(session)
1262
+ await this.prepareCarrier(signal, s.id)
871
1263
  if (request.newTab === true) {
872
1264
  this.newTab(s)
873
1265
  }
@@ -880,8 +1272,12 @@ export class ElectronBrowserProvider implements BrowserProvider {
880
1272
  //
881
1273
  // Only an exact match after normalisation: a deliberate navigation to a different URL must not
882
1274
  // be redirected to whatever page happens to be open.
883
- if (request.newTab !== true && await this.adoptMatchingPage(s, request.url)) return
884
- await this.navigate(session, { url: request.url }, signal)
1275
+ const tab = this.activeTab(s)
1276
+ const transaction = this.beginNavigation(tab, signal)
1277
+ const { navigation } = transaction
1278
+ signal = transaction.signal
1279
+ if (request.newTab !== true && await this.adoptMatchingPage(s, request.url, tab, navigation, signal)) return
1280
+ await this.navigateTab(s, tab, request.url, navigation, signal)
885
1281
  }
886
1282
 
887
1283
  /**
@@ -893,30 +1289,40 @@ export class ElectronBrowserProvider implements BrowserProvider {
893
1289
  * @param url - the URL being opened.
894
1290
  * @returns whether an existing page was taken over.
895
1291
  */
896
- private async adoptMatchingPage(s: Session, url: string): Promise<boolean> {
1292
+ private async adoptMatchingPage(s: Session, url: string, target: Tab, navigation: symbol, signal?: AbortSignal): Promise<boolean> {
897
1293
  if (this.host.adoptPage === undefined || this.host.listPages === undefined) return false
898
1294
  const wanted = this.comparableUrl(url)
899
1295
  if (wanted === undefined) return false
900
1296
  let pages: readonly CarrierPage[]
901
1297
  try {
902
- pages = await this.host.listPages(s.label)
1298
+ pages = await this.host.listPages(this.carrierScope(s))
903
1299
  } catch {
904
1300
  // A listing must not turn "nothing to reuse" into "open failed".
905
1301
  return false
906
1302
  }
1303
+ this.checkNavigation(target, navigation)
907
1304
  const match = pages.find(page => this.comparableUrl(page.url) === wanted)
908
1305
  if (match === undefined) return false
1306
+ let handle: ElectronViewHandle
909
1307
  try {
910
- const handle = await this.host.adoptPage(match.id)
911
- const tab: Tab = { id: `page:${match.id}`, handle, url: match.url }
912
- s.tabs.push(tab)
913
- s.activeIndex = s.tabs.length - 1
914
- this.showActive(s, true)
915
- return true
1308
+ handle = await this.host.adoptPage(this.carrierTab(s, match.id), this.carrierScope(s))
916
1309
  } catch {
917
1310
  // The page went away between listing and adopting: fall through to an ordinary navigation.
918
1311
  return false
919
1312
  }
1313
+ if (target.navigation !== navigation) {
1314
+ this.host.destroyView(handle, { keepPage: true })
1315
+ this.checkNavigation(target, navigation)
1316
+ }
1317
+ const tab: Tab = { id: this.carrierTab(s, match.id), handle, url: match.url, navigation, navigationAbort: target.navigationAbort }
1318
+ delete target.navigationAbort
1319
+ s.tabs.push(tab)
1320
+ s.activeIndex = s.tabs.length - 1
1321
+ const document = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation) })
1322
+ await this.settleDocument(handle, document, signal, { frameId: document.id, loaderId: document.loaderId },
1323
+ () => { this.checkNavigation(tab, navigation) })
1324
+ this.showActive(s, true)
1325
+ return true
920
1326
  }
921
1327
 
922
1328
  /** The parts of a URL that decide identity, or undefined when it cannot be parsed. */
@@ -941,7 +1347,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
941
1347
  // the round trip can only answer nothing — and it is the round trip that costs. A tab that
942
1348
  // HAS navigated is re-read, because the page may have moved itself since; a read that fails
943
1349
  // keeps the last accepted URL rather than reporting the tab as blank.
944
- const liveUrl = tab.url === '' ? '' : await this.currentUrl(tab.handle).catch(() => tab.url)
1350
+ const liveUrl = tab.failure !== undefined ? tab.url : tab.url === '' ? '' : await this.currentUrl(tab.handle).catch(() => tab.url)
945
1351
  if (liveUrl !== '') tab.url = liveUrl
946
1352
  result.push({
947
1353
  id: tab.id,
@@ -957,30 +1363,33 @@ export class ElectronBrowserProvider implements BrowserProvider {
957
1363
  // `dsh_browser_close_tab`, so they accumulated for the life of the browser. Measured on the
958
1364
  // sidebar carrier: three clicks produced three webview guests while this listed one tab.
959
1365
  //
960
- // `listPages` already excludes the pages it opened the view for — that filtering cannot happen
961
- // here, because a tab is known by this provider's own id and a carrier page by the carrier's,
962
- // and the two never match. A first version compared them anyway and listed every page twice.
963
- //
964
- // They are appended under a `page:` prefix so a caller can tell the two kinds apart — the
965
- // prefix is also what `closeTab` uses to decide whether to close a view or a carrier page.
966
- const pages = await this.host.listPages?.(s.label) ?? []
1366
+ // Hosts exclude pages already attached to provider views.
1367
+ const pages = await this.host.listPages?.(this.carrierScope(s)) ?? []
967
1368
  for (const page of pages) {
968
1369
  // A page with no URL is a blank one the carrier opened for itself. Listing it would invite a
969
1370
  // caller to act on nothing, and the blank normalisation already closes those.
970
1371
  if (page.url === '' || page.url === 'about:blank') continue
971
- result.push({ id: `page:${page.id}`, url: page.url, active: false })
1372
+ result.push({ id: this.carrierTab(s, page.id), url: page.url, active: false })
972
1373
  }
973
1374
  return result
974
1375
  }
975
1376
 
976
1377
  /** Switch to a tab by id, making its view visible. */
977
- async switchTab(session: BrowserSessionId, tabId: string): Promise<void> {
1378
+ async switchTab(session: BrowserSessionId, tabId: BrowserTabWireId): Promise<void> {
978
1379
  const s = this.session(session)
979
1380
  // A page the carrier owns. Before this, switching to one threw "not open in this session" —
980
1381
  // while `dsh_browser_list_tabs` was happily listing it, so the two tools disagreed and the
981
1382
  // page the human was looking at could not be reached (reported as a defect).
982
- if (tabId.startsWith('page:')) {
983
- const id = tabId.slice('page:'.length)
1383
+ const carrierId = this.carrierId(s, tabId)
1384
+ if (carrierId !== undefined) {
1385
+ const existing = s.tabs.findIndex(tab => tab.id === tabId)
1386
+ if (existing !== -1) {
1387
+ await this.host.presentView?.(s.tabs[existing]!.handle, s.label, { quiet: this.isQuiet(), select: true })
1388
+ s.activeIndex = existing
1389
+ this.showActive(s, true)
1390
+ return
1391
+ }
1392
+ const id = carrierId
984
1393
  if (this.host.adoptPage === undefined) {
985
1394
  throw new BrowserError(
986
1395
  'browser: this carrier cannot hand over a page it opened itself, so that page cannot be driven. '
@@ -988,11 +1397,23 @@ export class ElectronBrowserProvider implements BrowserProvider {
988
1397
  'BROWSER_TAB_NOT_FOUND',
989
1398
  )
990
1399
  }
991
- const handle = await this.host.adoptPage(id)
992
- const tab: Tab = { id: tabId, handle, url: '' }
993
- s.tabs.push(tab)
994
- s.activeIndex = s.tabs.length - 1
995
- this.showActive(s)
1400
+ const pages = await this.host.listPages?.(this.carrierScope(s)).catch(() => []) ?? []
1401
+ const page = pages.find(candidate => candidate.id === id)
1402
+ const handle = await this.host.adoptPage(id, this.carrierScope(s))
1403
+ try {
1404
+ // An adopted guest already has a document. Marking it as our never-opened
1405
+ // blank view makes the first snapshot/a11y return without reading it.
1406
+ const url = page?.url || await this.currentUrl(handle)
1407
+ if (url === '') throw new BrowserError('browser: the adopted page did not report its document URL', 'BROWSER_TAB_NOT_FOUND')
1408
+ const tab: Tab = { id: tabId, handle, url }
1409
+ await this.host.presentView?.(handle, s.label, { quiet: this.isQuiet(), select: true })
1410
+ s.tabs.push(tab)
1411
+ s.activeIndex = s.tabs.length - 1
1412
+ this.showActive(s, true)
1413
+ } catch (error) {
1414
+ this.host.destroyView(handle, { keepPage: true })
1415
+ throw error
1416
+ }
996
1417
  return
997
1418
  }
998
1419
  const found = this.locateTab(session, tabId)
@@ -1001,20 +1422,22 @@ export class ElectronBrowserProvider implements BrowserProvider {
1001
1422
  }
1002
1423
 
1003
1424
  /** Close one tab; closing the active tab activates the next. */
1004
- closeTab(session: BrowserSessionId, tabId: string): Promise<void> {
1005
- const owner = this.session(session).label
1425
+ async closeTab(session: BrowserSessionId, tabId: BrowserTabWireId): Promise<void> {
1426
+ const current = this.session(session)
1427
+ const carrierId = this.carrierId(current, tabId)
1006
1428
  // A page the carrier owns rather than a view we created. It was reported by `listTabs` under
1007
1429
  // this prefix, so closing it here is what keeps the two tools consistent — a page that can be
1008
1430
  // listed must be closable, or the listing reads as a contradiction.
1009
- if (tabId.startsWith('page:')) {
1010
- const id = tabId.slice('page:'.length)
1431
+ if (carrierId !== undefined) {
1432
+ const id = carrierId
1011
1433
  if (this.host.closePage === undefined) {
1012
1434
  return Promise.reject(new BrowserError(
1013
1435
  'browser: this carrier does not expose the pages it opens on its own, so that page cannot be closed',
1014
1436
  'BROWSER_TAB_NOT_FOUND',
1015
1437
  ))
1016
1438
  }
1017
- return this.host.closePage(id, owner)
1439
+ await this.host.closePage(id, this.carrierScope(current))
1440
+ if (!this.session(session).tabs.some(tab => tab.id === tabId)) return
1018
1441
  }
1019
1442
  const found = this.locateTab(session, tabId)
1020
1443
  const s = found.s
@@ -1022,7 +1445,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1022
1445
  const removed = s.tabs[index]
1023
1446
  if (removed !== undefined) {
1024
1447
  s.tabs.splice(index, 1)
1025
- this.host.destroyView(removed.handle)
1448
+ this.destroyTab(removed, { keepPage: carrierId !== undefined })
1026
1449
  }
1027
1450
  if (s.tabs.length === 0) {
1028
1451
  // Session keeps one blank tab so it stays usable.
@@ -1042,28 +1465,13 @@ export class ElectronBrowserProvider implements BrowserProvider {
1042
1465
  }
1043
1466
 
1044
1467
  /**
1045
- * Find a tab by id, preferring the calling session. Tab ids are globally
1046
- * unique UUIDs, so when the calling session does not hold the tab (the tool
1047
- * layer's session resolution can drift from the session that opened it),
1048
- * fall back to locating it in any other session instead of failing — the
1049
- * caller explicitly named a tab, so acting on it is what they want. Throws
1050
- * BROWSER_TAB_UNKNOWN with the session's actual tabs when the id exists
1051
- * nowhere.
1468
+ * Find a canonical tab within the calling session.
1052
1469
  */
1053
1470
  private locateTab(session: BrowserSessionId, tabId: string): { s: Session; index: number } {
1054
1471
  const s = this.session(session)
1055
- // Accept the bare uuid as well as the "tab:<uuid>" form the tools print:
1056
- // ids are globally unique, so requiring the printed prefix only produced a
1057
- // misleading "is not open in this session" error that listed the very tab
1058
- // the caller had just named.
1059
- const wanted = stripTabPrefix(tabId)
1060
- const own = s.tabs.findIndex(tab => stripTabPrefix(tab.id) === wanted)
1472
+ resolveTabHandle(resolveSessionHandle(session), tabId)
1473
+ const own = s.tabs.findIndex(tab => tab.id === tabId)
1061
1474
  if (own >= 0) return { s, index: own }
1062
- // Deliberately NOT searched across other sessions. Accepting a bare uuid and
1063
- // searching elsewhere are different things: ids are globally unique, so the first is
1064
- // harmless convenience, but the second lets a stale id close or switch a tab that
1065
- // belongs to another task — or to the human — while reporting success, which
1066
- // contradicts the isolation the tools promise.
1067
1475
  const ownIds = s.tabs.map(t => t.id).join(', ') || '(none)'
1068
1476
  throw new BrowserError(
1069
1477
  `browser: tab "${tabId}" is not open in this session (session tabs: ${ownIds})`,
@@ -1074,7 +1482,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1074
1482
  /** Close every tab and reset to one blank tab. */
1075
1483
  reset(session: BrowserSessionId): Promise<void> {
1076
1484
  const s = this.session(session)
1077
- for (const tab of s.tabs) this.host.destroyView(tab.handle)
1485
+ for (const tab of s.tabs) this.destroyTab(tab)
1078
1486
  s.tabs.length = 0
1079
1487
  this.newTab(s)
1080
1488
  s.activeIndex = 0
@@ -1085,9 +1493,36 @@ export class ElectronBrowserProvider implements BrowserProvider {
1085
1493
  /** Navigate the active tab's view to a URL, honoring HTTP(S)-only admission. */
1086
1494
  async navigate(session: BrowserSessionId, request: { readonly url: string }, signal?: AbortSignal): Promise<void> {
1087
1495
  const s = this.session(session)
1496
+ await this.prepareCarrier(signal, s.id)
1088
1497
  const tab = this.activeTab(s)
1498
+ const transaction = this.beginNavigation(tab, signal)
1499
+ const { navigation } = transaction
1500
+ signal = transaction.signal
1501
+ await this.navigateTab(s, tab, request.url, navigation, signal)
1502
+ }
1503
+
1504
+ private beginNavigation(tab: Tab, signal?: AbortSignal): { navigation: symbol; signal: AbortSignal } {
1505
+ signal?.throwIfAborted()
1506
+ const previous = tab.navigationAbort
1507
+ tab.navigation = Symbol()
1508
+ tab.navigationAbort = new AbortController()
1509
+ previous?.abort(Object.assign(new Error('a newer navigation was requested for this browser tab'), { code: 'panel-navigation-superseded' }))
1510
+ return { navigation: tab.navigation, signal: signal === undefined ? tab.navigationAbort.signal : AbortSignal.any([signal, tab.navigationAbort.signal]) }
1511
+ }
1512
+
1513
+ private checkNavigation(tab: Tab, navigation: symbol): void {
1514
+ if (tab.failure !== undefined) throw tab.failure
1515
+ if (![...this.sessions.values()].some(session => session.tabs.includes(tab))) {
1516
+ throw new BrowserError('browser: the navigation guest was closed', 'BROWSER_GUEST_CLOSED')
1517
+ }
1518
+ if (tab.navigation !== navigation) {
1519
+ throw Object.assign(new Error('a newer navigation was requested for this browser tab'), { code: 'panel-navigation-superseded' })
1520
+ }
1521
+ }
1522
+
1523
+ private async navigateTab(s: Session, tab: Tab, url: string, navigation: symbol, signal?: AbortSignal): Promise<void> {
1089
1524
  const { handle } = tab
1090
- const url = request.url
1525
+ this.checkNavigation(tab, navigation)
1091
1526
  try {
1092
1527
  if (this.httpOnly) {
1093
1528
  let parsed: URL
@@ -1104,42 +1539,48 @@ export class ElectronBrowserProvider implements BrowserProvider {
1104
1539
  // Page.navigate can hang on an unreachable/slow host; bound it like the
1105
1540
  // evaluate paths so a wedged navigation surfaces as an error instead of
1106
1541
  // blocking the tool call forever.
1107
- const timeoutMs = 30_000
1542
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
1543
+ const deadline = Date.now() + timeoutMs
1108
1544
  // Document identity of the page we are leaving (see settleDocument).
1109
- const before = await this.documentStamp(handle)
1545
+ const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation) }, deadline).catch(() => undefined)
1546
+ this.checkNavigation(tab, navigation)
1547
+ signal?.throwIfAborted()
1110
1548
  const result = await withTimeout(
1111
- handle.sendCommand(CDP_PAGE_NAVIGATE, { url } satisfies CdpNavigateParams),
1112
- timeoutMs,
1549
+ handle.sendCommand(CDP_PAGE_NAVIGATE, { url } satisfies CdpNavigateParams, { deadline, signal }),
1550
+ Math.max(1, deadline - Date.now()),
1113
1551
  signal,
1114
1552
  `browser: navigation timed out after ${timeoutMs}ms`,
1115
1553
  // Best-effort: cancel the in-flight navigation so a wedged load does
1116
1554
  // not leave the debugger queue busy.
1117
- () => { void handle.sendCommand('Page.stopLoading').catch(() => {}) },
1555
+ timedOut => { if (tab.navigation === navigation) this.interrupt(handle, timedOut) },
1118
1556
  )
1119
1557
  // Page.navigate resolves even when the navigation fails; surface the
1120
1558
  // failure instead of leaving a silent white screen.
1121
- const errorText = (result as { errorText?: string }).errorText
1559
+ this.checkNavigation(tab, navigation)
1560
+ const errorText = (result as { errorText?: string } | undefined)?.errorText
1122
1561
  if (typeof errorText === 'string' && errorText !== '') {
1123
1562
  throw new BrowserError(`browser: navigation to "${url}" failed: ${errorText}`, 'BROWSER_NAVIGATION_FAILED')
1124
1563
  }
1125
- // Record as soon as the navigation has committed: history bookkeeping must
1126
- // not wait on the best-effort settle below (which only delays what the
1127
- // NEXT observation sees, not whether this action happened).
1128
- // The page has already moved by now, so a caller that aborted must be told that rather
1129
- // than handed a success: settleDocument returns quietly on abort by design, so without
1130
- // this the whole path completes exception-free — success reported, success recorded, and
1131
- // the visit written to the persistent history for a navigation nobody awaits any more.
1132
1564
  signal?.throwIfAborted()
1133
- this.record(s, 'navigate', { url }, true)
1134
- // The tab now holds a committed document, which is what the blank short-circuit in
1135
- // `snapshot`/`a11y` keys on. Recorded here rather than after the settle below: the
1136
- // navigation HAS committed, and a tab wrongly treated as blank would return empty results
1137
- // for a page that is really there.
1565
+ const acknowledgement = result as { frameId?: string; loaderId?: string } | undefined
1566
+ if (typeof acknowledgement?.frameId !== 'string' || acknowledgement.frameId === '') {
1567
+ throw new BrowserError('browser: navigation returned no frame acknowledgement', 'BROWSER_DOCUMENT_UNACKNOWLEDGED')
1568
+ }
1569
+ if (acknowledgement.loaderId === undefined ? before === undefined
1570
+ : typeof acknowledgement.loaderId !== 'string' || acknowledgement.loaderId === '') {
1571
+ throw new BrowserError('browser: navigation returned no document acknowledgement', 'BROWSER_DOCUMENT_UNACKNOWLEDGED')
1572
+ }
1138
1573
  tab.url = url
1139
- await this.settleDocument(handle, before, signal)
1574
+ await this.settleDocument(handle, before, signal, acknowledgement, () => { this.checkNavigation(tab, navigation) }, undefined, deadline)
1575
+ this.checkNavigation(tab, navigation)
1576
+ this.record(s, 'navigate', { url }, true)
1140
1577
  this.recordVisit(s, handle)
1141
1578
  this.showActive(s, true)
1142
1579
  } catch (error) {
1580
+ const code = (error as { code?: string })?.code
1581
+ if (tab.navigation === navigation && (code === 'BROWSER_DOCUMENT_TIMEOUT' || code === 'BROWSER_DOCUMENT_UNACKNOWLEDGED')) {
1582
+ this.quarantine(handle)
1583
+ }
1143
1584
  if (!(error instanceof BrowserError && (error as { code?: string }).code === 'BROWSER_NAVIGATION_BLOCKED')) {
1144
1585
  this.record(s, 'navigate', { url }, false, { error: String(error) })
1145
1586
  }
@@ -1147,41 +1588,17 @@ export class ElectronBrowserProvider implements BrowserProvider {
1147
1588
  }
1148
1589
  }
1149
1590
 
1150
- /**
1151
- * A per-document stamp: `performance.timeOrigin` is unique per document load,
1152
- * so it tells a same-URL reload and an A→B→A redirect apart from the document
1153
- * that was current before the navigation. Empty string when unreadable.
1154
- */
1155
- private async documentStamp(handle: ElectronViewHandle): Promise<string> {
1156
- const probe = await this.documentProbe(handle)
1157
- return probe?.stamp ?? ''
1158
- }
1159
-
1160
- /**
1161
- * One cheap in-page reading of the document's identity and parse state.
1162
- *
1163
- * Returns null when the page did NOT answer (mid-commit, execution context
1164
- * destroyed) — the caller keeps waiting. A page that answered with an
1165
- * unexpected shape (an override or a non-conforming host; the production
1166
- * expression always yields a string) is reported as `unknown` rather than as
1167
- * "no answer": blocking the navigation for the whole budget on a page that
1168
- * demonstrably responded has no upside.
1169
- */
1170
- private async documentProbe(handle: ElectronViewHandle): Promise<{ stamp: string; readyState: string } | null> {
1171
- try {
1172
- const result = await withTimeout(
1173
- handleSendEvaluate(handle, 'String(performance.timeOrigin) + "|" + document.readyState', undefined, { present: false, initialize: false }),
1174
- 3_000,
1175
- undefined,
1176
- 'browser: document probe timed out',
1177
- )
1178
- if (!result.ok) return null
1179
- if (typeof result.value !== 'string') return { stamp: '', readyState: 'unknown' }
1180
- const [stamp = '', readyState = ''] = result.value.split('|')
1181
- return { stamp, readyState }
1182
- } catch {
1183
- return null
1184
- }
1591
+ private async documentIdentity(handle: ElectronViewHandle, signal?: AbortSignal, checkCurrent?: () => void,
1592
+ deadline = Date.now() + PROVIDER_TIMEOUTS.evaluation, allowErrorDocument = false): Promise<DocumentIdentity> {
1593
+ signal?.throwIfAborted()
1594
+ checkCurrent?.()
1595
+ return mainDocument(await withTimeout(
1596
+ handle.sendCommand('Page.getFrameTree', undefined, { present: false, initialize: false }),
1597
+ Math.max(1, Math.min(PROVIDER_TIMEOUTS.evaluation, deadline - Date.now())), signal, 'browser: document identity timed out', timedOut => {
1598
+ try { checkCurrent?.() } catch { return }
1599
+ this.interrupt(handle, timedOut)
1600
+ },
1601
+ ), { allowErrorDocument })
1185
1602
  }
1186
1603
 
1187
1604
  /**
@@ -1192,38 +1609,56 @@ export class ElectronBrowserProvider implements BrowserProvider {
1192
1609
  * interactive elements — and why a separate dsh_browser_snapshot right after
1193
1610
  * always found them.
1194
1611
  *
1195
- * Wait — bounded, best-effort — for the new document to settle: readyState
1196
- * must reach interactive/complete AND the document identity must have
1197
- * changed. A page that never settles must not fail a navigation that already
1198
- * succeeded, so a timeout here is swallowed.
1199
- */
1200
- private async settleDocument(handle: ElectronViewHandle, before: string, signal?: AbortSignal): Promise<void> {
1201
- const started = Date.now()
1202
- const deadline = started + SETTLE_TIMEOUT_MS
1612
+ * The CDP frame/loader acknowledgement, not elapsed time or URL equality,
1613
+ * identifies the document whose parse readiness can complete the transaction.
1614
+ */
1615
+ private async settleDocument(handle: ElectronViewHandle, before: DocumentIdentity | undefined, signal?: AbortSignal,
1616
+ acknowledgement?: { readonly frameId?: string; readonly loaderId?: string }, checkCurrent?: () => void,
1617
+ historyEntry?: number, deadline = Date.now() + DEFAULT_OPERATION_TIMEOUT_MS, allowErrorDocument = false): Promise<void> {
1203
1618
  // The document is being replaced, so the synthetic pointer drawn into the old one
1204
1619
  // is gone. Dropping the remembered position is what lets it be painted again:
1205
1620
  // without this, a paint at coincidentally identical coordinates would be skipped
1206
1621
  // and the pointer would never come back after a navigation.
1207
1622
  forgetCursor(handle)
1208
1623
  for (;;) {
1209
- if (signal?.aborted === true) return
1210
- // A probe failure is expected while the navigation commits (the context is
1211
- // being destroyed) — keep polling rather than giving up.
1212
- const probe = await this.documentProbe(handle)
1213
- if (probe !== null) {
1214
- const settled = probe.readyState === 'interactive'
1215
- || probe.readyState === 'complete'
1216
- || probe.readyState === 'unknown'
1217
- const isNewDocument = before === '' || probe.stamp === '' || probe.stamp !== before
1218
- // The common case: the new document exists and is parsed — return now.
1219
- if (settled && isNewDocument) return
1220
- // Same document (hash navigation, cancelled/aborted load): there is no
1221
- // parse to wait for, so do not burn the budget. Outlast the brief
1222
- // window in which the OUTGOING document may still answer instead.
1223
- if (settled && Date.now() - started >= SETTLE_GRACE_MS) return
1624
+ signal?.throwIfAborted()
1625
+ checkCurrent?.()
1626
+ const remaining = deadline - Date.now()
1627
+ if (remaining <= 0) {
1628
+ this.quarantine(handle)
1629
+ throw new BrowserError('browser: the navigation document was not ready within its deadline', 'BROWSER_DOCUMENT_TIMEOUT')
1224
1630
  }
1225
- if (Date.now() >= deadline) return
1226
- await delay(SETTLE_POLL_MS, signal)
1631
+ const ready = await withTimeout((async () => {
1632
+ if (historyEntry !== undefined) {
1633
+ const history = await handle.sendCommand('Page.getNavigationHistory') as { entries?: Array<{ id?: number }>; currentIndex?: number }
1634
+ if (history.entries?.[history.currentIndex ?? -1]?.id !== historyEntry) return false
1635
+ }
1636
+ const current = await this.documentIdentity(handle, signal, checkCurrent, deadline, allowErrorDocument)
1637
+ if (acknowledgement?.frameId !== undefined && current.id !== acknowledgement.frameId) {
1638
+ throw new BrowserError('browser: navigation frame was superseded', 'BROWSER_NAVIGATION_SUPERSEDED')
1639
+ }
1640
+ const loader = acknowledgement?.loaderId ?? (acknowledgement === undefined ? undefined : before?.loaderId)
1641
+ if (loader !== undefined && current.loaderId !== loader) {
1642
+ if (current.loaderId === before?.loaderId) return false
1643
+ throw new BrowserError('browser: navigation document was superseded', 'BROWSER_NAVIGATION_SUPERSEDED')
1644
+ }
1645
+ if (acknowledgement === undefined && current.loaderId === before?.loaderId) return false
1646
+ return documentReady(handle, current, () => {
1647
+ signal?.throwIfAborted()
1648
+ checkCurrent?.()
1649
+ if (Date.now() >= deadline) {
1650
+ this.quarantine(handle)
1651
+ throw new BrowserError('browser: document readiness deadline expired', 'BROWSER_DOCUMENT_TIMEOUT')
1652
+ }
1653
+ })
1654
+ })(), remaining, signal, 'browser: document readiness timed out', timedOut => {
1655
+ try { checkCurrent?.() } catch { return }
1656
+ this.interrupt(handle, timedOut)
1657
+ })
1658
+ signal?.throwIfAborted()
1659
+ checkCurrent?.()
1660
+ if (ready) return
1661
+ await delay(Math.min(SETTLE_POLL_MS, Math.max(0, deadline - Date.now())), signal)
1227
1662
  }
1228
1663
  }
1229
1664
 
@@ -1244,7 +1679,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1244
1679
  return this.activeTab(s).handle
1245
1680
  }
1246
1681
  signal?.throwIfAborted()
1247
- const timeoutMs = 10_000
1682
+ const timeoutMs = PROVIDER_TIMEOUTS.lookup
1248
1683
  try {
1249
1684
  await withTimeout(
1250
1685
  present(handle, s.label, { quiet: this.isQuiet() }),
@@ -1322,7 +1757,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1322
1757
  // and this runs before typing, so an unresponsive child would hang dsh_browser_key for
1323
1758
  // good. A timeout is caught below exactly like any other focus failure, so the
1324
1759
  // best-effort contract is unchanged.
1325
- await withTimeout(handle.focus(quiet ? { quiet } : undefined), 5_000, undefined, 'browser: focusing the view timed out')
1760
+ await withTimeout(handle.focus(quiet ? { quiet } : undefined), PROVIDER_TIMEOUTS.interaction, undefined, 'browser: focusing the view timed out')
1326
1761
  } catch (error) {
1327
1762
  if (quiet) throw error
1328
1763
  // Best-effort: a view that refuses focus must not fail the caller's key
@@ -1368,7 +1803,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1368
1803
  const handle = await this.present(s, signal)
1369
1804
  const viewport = await withTimeout(
1370
1805
  handleSendEvaluate(handle, '({width:innerWidth,height:innerHeight})'),
1371
- 5_000, signal, 'browser: pointer viewport check timed out',
1806
+ PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer viewport check timed out',
1372
1807
  )
1373
1808
  if (!viewport.ok) throw new BrowserError('browser: could not read the pointer viewport', 'BROWSER_POINTER_INVALID')
1374
1809
  const size = viewport.value as { width: number; height: number }
@@ -1378,7 +1813,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1378
1813
  const send = async (params: CdpMouseParams): Promise<void> => {
1379
1814
  signal?.throwIfAborted()
1380
1815
  this.assertSameView(session, handle, this.activeTab(s).handle)
1381
- await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), 5_000, signal, 'browser: pointer input timed out')
1816
+ await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer input timed out')
1382
1817
  }
1383
1818
  await send({ type: 'mouseMoved', x: from.x, y: from.y, buttons: 0 })
1384
1819
  if (to === undefined) return { ok: true, value: 'true' }
@@ -1431,7 +1866,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1431
1866
  // (navigate returned but the renderer has not committed). Bound it so a
1432
1867
  // stuck call surfaces as BROWSER_EXECUTE_TIMEOUT instead of wedging the
1433
1868
  // whole tool call. The caller's signal wins when it fires first.
1434
- const timeoutMs = request.timeoutMs ?? 30_000
1869
+ const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
1435
1870
  const result = await withTimeout(
1436
1871
  handle.sendCommand(CDP_RUNTIME_EVALUATE, {
1437
1872
  expression,
@@ -1443,7 +1878,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1443
1878
  `browser: execute timed out after ${timeoutMs}ms`,
1444
1879
  // Best-effort: kill the wedged page script so the renderer (and the
1445
1880
  // debugger queue) is not stuck behind a busy loop forever.
1446
- () => terminatePage(handle),
1881
+ timedOut => { this.interrupt(handle, timedOut) },
1447
1882
  )
1448
1883
  if (result.exceptionDetails !== undefined) {
1449
1884
  const detail = result.exceptionDetails as { text?: string; exception?: { description?: string } }
@@ -1464,7 +1899,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1464
1899
  // that belongs to the caller rather than to this call.
1465
1900
  if (signal?.aborted) throw signal.reason
1466
1901
  if (error instanceof Error && error.name === 'TimeoutError') {
1467
- throw new BrowserError(`browser: execute timed out after ${request.timeoutMs ?? 30_000}ms`, 'BROWSER_EXECUTE_TIMEOUT', { cause: error })
1902
+ throw new BrowserError(`browser: execute timed out after ${request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS}ms`, 'BROWSER_EXECUTE_TIMEOUT', { cause: error })
1468
1903
  }
1469
1904
  throw new BrowserError(`browser: execute failed: ${String(error)}`, 'BROWSER_EXECUTE_FAILED', { cause: error })
1470
1905
  }
@@ -1480,7 +1915,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1480
1915
  async waitFor(session: BrowserSessionId, request: BrowserWaitRequest, signal?: AbortSignal): Promise<BrowserWaitResult> {
1481
1916
  const tab = this.activeTab(this.session(session))
1482
1917
  signal?.throwIfAborted()
1483
- const timeoutMs = request.timeoutMs ?? 30_000
1918
+ const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
1484
1919
  const deadline = Date.now() + timeoutMs
1485
1920
  const url = request.url ?? ''
1486
1921
  const selector = request.selector ?? ''
@@ -1514,10 +1949,10 @@ export class ElectronBrowserProvider implements BrowserProvider {
1514
1949
  for (;;) {
1515
1950
  const result = await withTimeout(
1516
1951
  handleSendEvaluate(tab.handle, expression),
1517
- Math.min(5_000, Math.max(250, deadline - Date.now())),
1952
+ Math.min(PROVIDER_TIMEOUTS.interaction, Math.max(250, deadline - Date.now())),
1518
1953
  signal,
1519
1954
  'browser: wait poll timed out',
1520
- () => terminatePage(tab.handle),
1955
+ timedOut => { this.interrupt(tab.handle, timedOut) },
1521
1956
  )
1522
1957
  if (!result.ok) {
1523
1958
  throw new BrowserError(`browser: wait failed: ${result.exception}`, 'BROWSER_WAIT_FAILED')
@@ -1691,7 +2126,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1691
2126
  })()`
1692
2127
  // Same hang guard as execute: a renderer that has not committed after
1693
2128
  // navigate would otherwise block snapshot forever.
1694
- const timeoutMs = 30_000
2129
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
1695
2130
  let result: { ok: true; value: unknown } | { ok: false; exception: string }
1696
2131
  try {
1697
2132
  result = await withTimeout(
@@ -1699,18 +2134,13 @@ export class ElectronBrowserProvider implements BrowserProvider {
1699
2134
  timeoutMs,
1700
2135
  signal,
1701
2136
  `browser: snapshot timed out after ${timeoutMs}ms`,
1702
- () => terminatePage(tab.handle),
2137
+ timedOut => { this.interrupt(tab.handle, timedOut) },
1703
2138
  ) as { ok: true; value: unknown } | { ok: false; exception: string }
1704
2139
  } catch (error) {
1705
- // A timeout leaves the wedged view in the session, so every later read would pay the same
1706
- // 30 seconds again — and `terminatePage` only interrupts the running script, it does not
1707
- // make the view readable. Replacing it is what turns a permanent loss into one bad call:
1708
- // the tab keeps the id the caller holds, and the next dsh_browser_open with the real URL
1709
- // repopulates it.
1710
2140
  if (error instanceof Error && error.name === 'TimeoutError') {
1711
- this.replaceTabWithBlank(s, tab)
2141
+ this.quarantine(tab.handle)
1712
2142
  throw new BrowserError(
1713
- 'browser: snapshot timed out; the stuck tab was reset to blank. Call dsh_browser_open with the real target URL before reading it again.',
2143
+ 'browser: snapshot timed out; the guest is quarantined. Close this tab or explicitly reset the session.',
1714
2144
  'BROWSER_SNAPSHOT_TIMEOUT',
1715
2145
  { cause: error },
1716
2146
  )
@@ -1897,7 +2327,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1897
2327
  walk(document, false, 0)
1898
2328
  return { url: location.href, title: document.title || undefined, count: out.length, nodes: out, truncated: out.length >= maxNodes }
1899
2329
  })()`
1900
- const timeoutMs = 30_000
2330
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
1901
2331
  let result: { ok: true; value: unknown } | { ok: false; exception: string }
1902
2332
  try {
1903
2333
  result = await withTimeout(
@@ -1905,15 +2335,13 @@ export class ElectronBrowserProvider implements BrowserProvider {
1905
2335
  timeoutMs,
1906
2336
  signal,
1907
2337
  `browser: a11y timed out after ${timeoutMs}ms`,
1908
- () => terminatePage(tab.handle),
2338
+ timedOut => { this.interrupt(tab.handle, timedOut) },
1909
2339
  ) as { ok: true; value: unknown } | { ok: false; exception: string }
1910
2340
  } catch (error) {
1911
- // As in `snapshot`: a timeout means the view is wedged, and leaving it in the session would
1912
- // charge every later read the same 30 seconds. Replaced in place, so the tab id survives.
1913
2341
  if (error instanceof Error && error.name === 'TimeoutError') {
1914
- this.replaceTabWithBlank(s, tab)
2342
+ this.quarantine(tab.handle)
1915
2343
  throw new BrowserError(
1916
- 'browser: a11y timed out; the stuck tab was reset to blank. Call dsh_browser_open with the real target URL before reading it again.',
2344
+ 'browser: a11y timed out; the guest is quarantined. Close this tab or explicitly reset the session.',
1917
2345
  'BROWSER_A11Y_TIMEOUT',
1918
2346
  { cause: error },
1919
2347
  )
@@ -1931,13 +2359,13 @@ export class ElectronBrowserProvider implements BrowserProvider {
1931
2359
  const s = this.session(session)
1932
2360
  const tab = this.activeTab(s)
1933
2361
  signal?.throwIfAborted()
1934
- const timeoutMs = 15_000
2362
+ const timeoutMs = PROVIDER_TIMEOUTS.action
1935
2363
  const result = await withTimeout(
1936
2364
  handleSendEvaluate(tab.handle, CHALLENGE_DETECT_EXPRESSION),
1937
2365
  timeoutMs,
1938
2366
  signal,
1939
2367
  `browser: challenge detection timed out after ${timeoutMs}ms`,
1940
- () => terminatePage(tab.handle),
2368
+ timedOut => { this.interrupt(tab.handle, timedOut) },
1941
2369
  )
1942
2370
  if (!result.ok) {
1943
2371
  throw new BrowserError(`browser: challenge detection failed: ${result.exception}`, 'BROWSER_CHALLENGE_DETECT_FAILED')
@@ -2041,13 +2469,13 @@ export class ElectronBrowserProvider implements BrowserProvider {
2041
2469
  // Honor a per-call timeout: content evaluation can hang on a heavy page,
2042
2470
  // so a caller-supplied budget bounds it. Unlike a bare signal entry check,
2043
2471
  // withTimeout also interrupts a call already in flight.
2044
- const timeoutMs = request.timeoutMs ?? 30_000
2472
+ const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
2045
2473
  const result = await withTimeout(
2046
2474
  handleSendEvaluate(tab.handle, script),
2047
2475
  timeoutMs,
2048
2476
  signal,
2049
2477
  `browser: content timed out after ${timeoutMs}ms`,
2050
- () => terminatePage(tab.handle),
2478
+ timedOut => { this.interrupt(tab.handle, timedOut) },
2051
2479
  )
2052
2480
  if (!result.ok) throw new BrowserError(`browser: content evaluation failed: ${result.exception}`, 'BROWSER_CONTENT_FAILED')
2053
2481
  const value = result.value as { ok: boolean; reason?: string; content?: string; truncated?: boolean }
@@ -2074,7 +2502,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2074
2502
  if ('target' in request) {
2075
2503
  // Semantic targeting (②): locate the element in-page, scroll it into
2076
2504
  // view, and click its center — no coordinate guessing needed.
2077
- const locateMs = 10_000
2505
+ const locateMs = PROVIDER_TIMEOUTS.lookup
2078
2506
  const body = `
2079
2507
  el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'center' })
2080
2508
  const r = el.getBoundingClientRect()
@@ -2108,7 +2536,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2108
2536
  // earlier; if the human switched tabs meanwhile, these coordinates belong to one page
2109
2537
  // and the dispatch would go to another — and Chromium answers success either way.
2110
2538
  if ('target' in request) this.assertSameView(session, locateHandle, handle)
2111
- const timeoutMs = 30_000
2539
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2112
2540
  const send = (params: Record<string, unknown>, label: string): Promise<unknown> =>
2113
2541
  withTimeout(
2114
2542
  handle.sendCommand('Input.dispatchMouseEvent', params),
@@ -2198,7 +2626,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2198
2626
  }
2199
2627
  // One barrier for the whole run: cheap, and it is the view that needs a surface, not each press.
2200
2628
  const handle = await this.present(s, signal)
2201
- const timeoutMs = 30_000
2629
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2202
2630
  // 40 ms is above one frame at 30 fps, which is what keeps the page from reading two presses as a
2203
2631
  // double click. Faster runs were measured dropping presses outright.
2204
2632
  const gap = typeof request.intervalMs === 'number' && request.intervalMs >= 0 ? request.intervalMs : 40
@@ -2254,7 +2682,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2254
2682
  signal?.throwIfAborted()
2255
2683
  const hasTarget = 'target' in request
2256
2684
  if (hasTarget) {
2257
- const locateMs = 10_000
2685
+ const locateMs = PROVIDER_TIMEOUTS.lookup
2258
2686
  const script = this.buildTargetScript(request.target, locateMs, `
2259
2687
  el.focus()
2260
2688
  return { ok: true }
@@ -2265,7 +2693,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2265
2693
  if (cursorPoint !== undefined) this.showCursor(locateTab.handle, cursorPoint.x, cursorPoint.y, 'click', 'type', true)
2266
2694
  }
2267
2695
  const text = 'text' in request ? request.text : ''
2268
- const timeoutMs = 30_000
2696
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2269
2697
  // Input.insertText goes through the Input domain: same display-surface
2270
2698
  // requirement as click/key. It also reports which view is active once the barrier has
2271
2699
  // settled, which is what makes the tab-switch check below meaningful.
@@ -2308,13 +2736,13 @@ export class ElectronBrowserProvider implements BrowserProvider {
2308
2736
  window.scrollBy({ top: ${request.deltaY ?? 0}, left: ${request.deltaX ?? 0} })
2309
2737
  return { ok: true }
2310
2738
  })()`
2311
- const timeoutMs = 15_000
2739
+ const timeoutMs = PROVIDER_TIMEOUTS.action
2312
2740
  const result = await withTimeout(
2313
2741
  handleSendEvaluate(tab.handle, script),
2314
2742
  timeoutMs,
2315
2743
  signal,
2316
2744
  `browser: scroll timed out after ${timeoutMs}ms`,
2317
- () => terminatePage(tab.handle),
2745
+ timedOut => { this.interrupt(tab.handle, timedOut) },
2318
2746
  )
2319
2747
  if (!result.ok) throw new BrowserError(`browser: scroll failed: ${result.exception}`, 'BROWSER_SCROLL_FAILED')
2320
2748
  const value = result.value as { ok?: boolean; reason?: string }
@@ -2325,15 +2753,21 @@ export class ElectronBrowserProvider implements BrowserProvider {
2325
2753
  /** Go back (-1) or forward (+1) in the active tab's navigation history. */
2326
2754
  private async historyStep(session: BrowserSessionId, direction: -1 | 1, signal?: AbortSignal): Promise<void> {
2327
2755
  const s = this.session(session)
2328
- const { handle } = this.activeTab(s)
2756
+ const tab = this.activeTab(s)
2757
+ const { handle } = tab
2758
+ const transaction = this.beginNavigation(tab, signal)
2759
+ const { navigation } = transaction
2760
+ signal = transaction.signal
2329
2761
  signal?.throwIfAborted()
2330
- const timeoutMs = 30_000
2762
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2763
+ const deadline = Date.now() + timeoutMs
2331
2764
  const hist = await withTimeout(
2332
2765
  handle.sendCommand('Page.getNavigationHistory'),
2333
2766
  timeoutMs,
2334
2767
  signal,
2335
2768
  `browser: history read timed out after ${timeoutMs}ms`,
2336
- ) as { entries?: Array<{ id?: number }>; currentIndex?: number }
2769
+ ) as { entries?: Array<{ id?: number; url?: string }>; currentIndex?: number }
2770
+ this.checkNavigation(tab, navigation)
2337
2771
  const entries = hist.entries ?? []
2338
2772
  const currentIndex = hist.currentIndex ?? -1
2339
2773
  const target = currentIndex + direction
@@ -2347,16 +2781,25 @@ export class ElectronBrowserProvider implements BrowserProvider {
2347
2781
  if (entry?.id === undefined) throw new BrowserError('browser: history entry missing id', 'BROWSER_HISTORY_INVALID')
2348
2782
  // A history step is a navigation too: the classic A→B→A redirect would
2349
2783
  // otherwise read the outgoing document's identity (see settleDocument).
2350
- const before = await this.documentStamp(handle)
2784
+ const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation) }, deadline, true)
2785
+ const inPage = await withTimeout(handleSendEvaluate(handle, `(() => {
2786
+ if (typeof navigation === 'undefined') return false;
2787
+ const entry = navigation.entries().find(entry => entry.index === navigation.currentEntry.index + ${direction});
2788
+ return entry?.url === ${JSON.stringify(entry.url)} && entry.sameDocument === true;
2789
+ })()`), Math.max(1, deadline - Date.now()), signal, 'browser: history document identity timed out', timedOut => { this.interrupt(handle, timedOut) })
2790
+ this.checkNavigation(tab, navigation)
2791
+ signal?.throwIfAborted()
2351
2792
  await withTimeout(
2352
2793
  handle.sendCommand('Page.navigateToHistoryEntry', { entryId: entry.id }),
2353
- timeoutMs,
2794
+ Math.max(1, deadline - Date.now()),
2354
2795
  signal,
2355
2796
  `browser: history navigation timed out after ${timeoutMs}ms`,
2356
- () => { void handle.sendCommand('Page.stopLoading').catch(() => {}) },
2797
+ () => { if (tab.navigation === navigation) void handle.sendCommand('Page.stopLoading').catch(() => {}) },
2357
2798
  )
2799
+ await this.settleDocument(handle, before, signal,
2800
+ inPage.ok && inPage.value === true ? { frameId: before.id, loaderId: before.loaderId } : undefined,
2801
+ () => { this.checkNavigation(tab, navigation) }, entry.id, deadline, true)
2358
2802
  this.record(s, direction === -1 ? 'back' : 'forward', {}, true)
2359
- await this.settleDocument(handle, before, signal)
2360
2803
  this.recordVisit(s, handle)
2361
2804
  this.showActive(s)
2362
2805
  }
@@ -2374,22 +2817,29 @@ export class ElectronBrowserProvider implements BrowserProvider {
2374
2817
  /** Reload the active tab. */
2375
2818
  async reload(session: BrowserSessionId, signal?: AbortSignal): Promise<void> {
2376
2819
  const s = this.session(session)
2377
- const { handle } = this.activeTab(s)
2820
+ const tab = this.activeTab(s)
2821
+ const { handle } = tab
2822
+ const transaction = this.beginNavigation(tab, signal)
2823
+ const { navigation } = transaction
2824
+ signal = transaction.signal
2378
2825
  signal?.throwIfAborted()
2379
- const timeoutMs = 30_000
2826
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2827
+ const deadline = Date.now() + timeoutMs
2380
2828
  // Same-URL reload: only the per-load document identity can tell the new
2381
2829
  // document from the old one, so capture it before reloading.
2382
- const before = await this.documentStamp(handle)
2830
+ const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation) }, deadline, true)
2831
+ this.checkNavigation(tab, navigation)
2832
+ signal?.throwIfAborted()
2383
2833
  await withTimeout(
2384
2834
  handle.sendCommand('Page.reload', { ignoreCache: false }),
2385
- timeoutMs,
2835
+ Math.max(1, deadline - Date.now()),
2386
2836
  signal,
2387
2837
  `browser: reload timed out after ${timeoutMs}ms`,
2388
2838
  // Best-effort: cancel the reload if it wedges the debugger queue.
2389
- () => { void handle.sendCommand('Page.stopLoading').catch(() => {}) },
2839
+ () => { if (tab.navigation === navigation) void handle.sendCommand('Page.stopLoading').catch(() => {}) },
2390
2840
  )
2841
+ await this.settleDocument(handle, before, signal, undefined, () => { this.checkNavigation(tab, navigation) }, undefined, deadline, true)
2391
2842
  this.record(s, 'reload', {}, true)
2392
- await this.settleDocument(handle, before, signal)
2393
2843
  this.recordVisit(s, handle)
2394
2844
  this.showActive(s)
2395
2845
  }
@@ -2403,7 +2853,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2403
2853
  throw new BrowserError(`browser: unsupported key "${request.key}" (supported: ${BROWSER_KEY_NAMES.join(', ')})`, 'BROWSER_KEY_UNSUPPORTED')
2404
2854
  }
2405
2855
  const params = { key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.vk, nativeVirtualKeyCode: spec.vk, ...spec.text !== undefined ? { text: spec.text } : {} }
2406
- const timeoutMs = 15_000
2856
+ const timeoutMs = PROVIDER_TIMEOUTS.action
2407
2857
  // Input.dispatchKeyEvent is subject to the same display-surface rule. The handle comes
2408
2858
  // back from the presentation barrier rather than from a capture taken before it: this
2409
2859
  // session is shared with the human, who may switch tabs while the barrier round-trips,
@@ -2627,13 +3077,13 @@ export class ElectronBrowserProvider implements BrowserProvider {
2627
3077
  }
2628
3078
  return { fields: out, submitted }
2629
3079
  })()`
2630
- const timeoutMs = request.timeoutMs ?? 30_000
3080
+ const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
2631
3081
  const result = await withTimeout(
2632
3082
  handleSendEvaluate(tab.handle, script),
2633
3083
  timeoutMs,
2634
3084
  signal,
2635
3085
  `browser: fillForm timed out after ${timeoutMs}ms`,
2636
- () => terminatePage(tab.handle),
3086
+ timedOut => { this.interrupt(tab.handle, timedOut) },
2637
3087
  )
2638
3088
  if (!result.ok) {
2639
3089
  throw new BrowserError(`browser: fillForm evaluation failed: ${result.exception}`, 'BROWSER_FILL_FAILED')
@@ -2789,7 +3239,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2789
3239
  timeoutMs + TARGET_SCRIPT_GRACE_MS,
2790
3240
  signal,
2791
3241
  `${errorLabel} timed out after ${timeoutMs}ms`,
2792
- () => terminatePage(tab.handle),
3242
+ timedOut => { this.interrupt(tab.handle, timedOut) },
2793
3243
  )
2794
3244
  if (!result.ok) throw new BrowserError(`${errorLabel} failed: ${result.exception}`, errorCode)
2795
3245
  const value = result.value as { ok?: boolean; error?: string } | undefined
@@ -2802,7 +3252,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2802
3252
  const s = this.session(session)
2803
3253
  const tab = this.activeTab(s)
2804
3254
  signal?.throwIfAborted()
2805
- const timeoutMs = request.timeoutMs ?? 5_000
3255
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
2806
3256
  const body = `
2807
3257
  const value = ${JSON.stringify(String(request.value))}
2808
3258
  const setNative = (el, proto, v) => {
@@ -2851,7 +3301,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2851
3301
  const s = this.session(session)
2852
3302
  const tab = this.activeTab(s)
2853
3303
  signal?.throwIfAborted()
2854
- const timeoutMs = request.timeoutMs ?? 5_000
3304
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
2855
3305
  const want = request.checked ?? true
2856
3306
  const body = `
2857
3307
  const want = ${String(want)}
@@ -2879,7 +3329,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2879
3329
  const s = this.session(session)
2880
3330
  const tab = this.activeTab(s)
2881
3331
  signal?.throwIfAborted()
2882
- const timeoutMs = request.timeoutMs ?? 5_000
3332
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
2883
3333
  const body = `
2884
3334
  if (el.tagName !== 'SELECT') return { ok: false, error: 'element is not a <select> (' + el.tagName + ')' }
2885
3335
  const optionValue = ${JSON.stringify(request.optionValue ?? null)}
@@ -2913,7 +3363,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2913
3363
  const s = this.session(session)
2914
3364
  const tab = this.activeTab(s)
2915
3365
  signal?.throwIfAborted()
2916
- const timeoutMs = request.timeoutMs ?? 5_000
3366
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
2917
3367
  const body = `
2918
3368
  const setNative = (el, proto) => {
2919
3369
  const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
@@ -2949,7 +3399,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2949
3399
  const s = this.session(session)
2950
3400
  const tab = this.activeTab(s)
2951
3401
  signal?.throwIfAborted()
2952
- const timeoutMs = request.timeoutMs ?? 5_000
3402
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
2953
3403
  const body = `
2954
3404
  const type = (el.type || '').toLowerCase()
2955
3405
  if (type === 'checkbox' || type === 'radio') return { ok: true, value: null, checked: el.checked }
@@ -2980,7 +3430,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
2980
3430
  const s = this.session(session)
2981
3431
  const tab = this.activeTab(s)
2982
3432
  signal?.throwIfAborted()
2983
- const timeoutMs = request.timeoutMs ?? 5_000
3433
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
2984
3434
  const script = `(async () => {
2985
3435
  const itemSel = ${JSON.stringify(request.item)}
2986
3436
  const fields = ${JSON.stringify(request.fields)}
@@ -3025,7 +3475,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
3025
3475
  timeoutMs + TARGET_SCRIPT_GRACE_MS,
3026
3476
  signal,
3027
3477
  `browser: scrape timed out after ${timeoutMs}ms`,
3028
- () => terminatePage(tab.handle),
3478
+ timedOut => { this.interrupt(tab.handle, timedOut) },
3029
3479
  )
3030
3480
  if (!result.ok) throw new BrowserError(`browser: scrape evaluation failed: ${result.exception}`, 'BROWSER_SCRAPE_FAILED')
3031
3481
  const value = result.value as { ok?: boolean; error?: string; count?: number; items?: Record<string, string | null>[] }
@@ -3181,7 +3631,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
3181
3631
  // parent's timeout fires the child continues writing. The parent's pending
3182
3632
  // entry is cleaned up (the promise settles) and the child's eventual
3183
3633
  // reply is harmlessly consumed by the RPC layer.
3184
- const timeoutMs = 60_000
3634
+ const timeoutMs = PROVIDER_TIMEOUTS.download
3185
3635
  await withTimeout(
3186
3636
  downloadable.download(request.url, savePath),
3187
3637
  timeoutMs,
@@ -3205,7 +3655,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
3205
3655
  }
3206
3656
  const s = this.session(session)
3207
3657
  const { handle } = this.activeTab(s)
3208
- const timeoutMs = 30_000
3658
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
3209
3659
  // The self-hosted carrier has a native path (the child reads its own session), which
3210
3660
  // is worth preferring: it reports exactly what the browser persisted.
3211
3661
  const native = handle
@@ -3259,7 +3709,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
3259
3709
  this.assertActionAllowed('credentialWrite')
3260
3710
  const s = this.session(session)
3261
3711
  const { handle } = this.activeTab(s)
3262
- const timeoutMs = 30_000
3712
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
3263
3713
  const native = handle
3264
3714
  if (typeof native.restoreAuth === 'function') {
3265
3715
  const restored = await withTimeout(native.restoreAuth(cookies), timeoutMs, undefined, `browser: auth restore timed out after ${timeoutMs}ms`)
@@ -3393,13 +3843,15 @@ export class ElectronBrowserProvider implements BrowserProvider {
3393
3843
  // in the child from the NativeImage, so this path is the only one that
3394
3844
  // can produce JPEG (CDP JPEG hangs on Electron 43).
3395
3845
  const capturable = handle
3396
- if (request?.fullPage !== true && typeof capturable.capture === 'function') {
3846
+ // A region capture must go through CDP: the native NativeImage path has no
3847
+ // clip and would present/activate the window (a quiet-mode violation).
3848
+ if (request?.clip === undefined && request?.fullPage !== true && typeof capturable.capture === 'function') {
3397
3849
  // Ensure the target view is the visible one before capturing — unless quiet mode is on.
3398
3850
  // There, presenting the view is exactly what the user asked to avoid (it restores and
3399
3851
  // raises the window); the host switches the visible tab inside the window and, if the
3400
3852
  // window has no surface to capture, falls through to CDP.
3401
3853
  if (!this.isQuiet()) this.showActive(s)
3402
- const timeoutMs = 30_000
3854
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
3403
3855
  const shot = await withTimeout(
3404
3856
  capturable.capture({
3405
3857
  ...format === 'jpeg' ? { format, quality: request?.quality } : {},
@@ -3433,9 +3885,19 @@ export class ElectronBrowserProvider implements BrowserProvider {
3433
3885
  // installed Chrome or Edge is the real browser and has no such defect, so it says so
3434
3886
  // through `supportsCdpJpeg` and gets the format it asked for, and the same for
3435
3887
  // downscaling, which CDP performs through a full-document clip.
3436
- const timeoutMs = 30_000
3888
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
3437
3889
  const params: Record<string, unknown> = {}
3438
- if (request?.fullPage === true) {
3890
+ const region = request?.clip
3891
+ if (region !== undefined) {
3892
+ const valid = [region.x, region.y, region.width, region.height].every(
3893
+ value => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 8192,
3894
+ ) && region.width > 0 && region.height > 0
3895
+ if (!valid) throw new BrowserError('browser: screenshot region is out of range', 'BROWSER_SCREENSHOT_FAILED')
3896
+ params.clip = { x: region.x, y: region.y, width: region.width, height: region.height, scale: 1 }
3897
+ params.fromSurface = true
3898
+ params.captureBeyondViewport = false
3899
+ }
3900
+ if (region === undefined && request?.fullPage === true) {
3439
3901
  // `captureBeyondViewport` captures the full scrollable content; without
3440
3902
  // a clip this yields the full-page image (CDP default is the viewport).
3441
3903
  params.captureBeyondViewport = true
@@ -3451,7 +3913,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
3451
3913
  // is read first; when that is unavailable the capture proceeds unscaled rather than
3452
3914
  // failing — an image the caller can shrink itself beats no image at all.
3453
3915
  let rendered: { width: number; height: number } | undefined
3454
- if (request?.maxWidth !== undefined || request?.maxHeight !== undefined) {
3916
+ if (region === undefined && (request?.maxWidth !== undefined || request?.maxHeight !== undefined)) {
3455
3917
  const metrics = await withTimeout(
3456
3918
  handle.sendCommand('Page.getLayoutMetrics', {}),
3457
3919
  timeoutMs,
@@ -3474,8 +3936,12 @@ export class ElectronBrowserProvider implements BrowserProvider {
3474
3936
  }
3475
3937
  }
3476
3938
  }
3939
+ // A region capture is a read: it must never present the conversation or
3940
+ // raise a window. Every other screenshot keeps the original call shape.
3477
3941
  const result = await withTimeout(
3478
- handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params),
3942
+ region === undefined
3943
+ ? handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params)
3944
+ : handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params, { present: false }),
3479
3945
  timeoutMs,
3480
3946
  signal,
3481
3947
  `browser: screenshot timed out after ${timeoutMs}ms`,
@@ -3682,22 +4148,24 @@ export class ElectronBrowserProvider implements BrowserProvider {
3682
4148
  }
3683
4149
 
3684
4150
  /** Close the session and destroy all its views. Idempotent. */
3685
- close(session: BrowserSessionId): Promise<void> {
4151
+ async close(session: BrowserSessionId): Promise<void> {
3686
4152
  const existing = this.sessions.get(session)
3687
4153
  if (existing !== undefined) {
3688
4154
  this.sessions.delete(session)
3689
- for (const tab of existing.tabs) this.host.destroyView(tab.handle)
4155
+ for (const tab of existing.tabs) this.destroyTab(tab)
3690
4156
  // Releasing the browser at session end is a setting, not fixed behaviour
3691
4157
  // (requirements §3). A self-hosted carrier already tore its window down with
3692
4158
  // the views above; the desktop's sidebar does not, so it is asked explicitly
3693
4159
  // — and its cookies plus the browsing history outlive the page either way.
3694
- if (this.settingsSource !== undefined && this.settingsSource().ui.closeWithSession) {
3695
- // Named, because one host serves every conversation: an unnamed release would end the
3696
- // pages of conversations that are still running.
3697
- void this.host.releasePage?.(existing.label).catch(() => undefined)
4160
+ try {
4161
+ if (this.settingsSource !== undefined && this.settingsSource().ui.closeWithSession) {
4162
+ // Never release another conversation's pages.
4163
+ await this.host.releasePage?.(this.carrierScope(existing))
4164
+ }
4165
+ } finally {
4166
+ await this.host.retireSession?.(session)
3698
4167
  }
3699
4168
  }
3700
- return Promise.resolve()
3701
4169
  }
3702
4170
 
3703
4171
  /** Look up a session or throw the unknown-session error. */
@@ -3711,49 +4179,56 @@ export class ElectronBrowserProvider implements BrowserProvider {
3711
4179
 
3712
4180
  /** The active tab of a session. */
3713
4181
  private activeTab(s: Session): Tab {
4182
+ if (this.carrierLaunchError !== undefined) throw this.carrierLaunchError
3714
4183
  const tab = s.tabs[s.activeIndex]
3715
4184
  if (tab === undefined) throw new BrowserError('browser: session has no active tab', 'BROWSER_TAB_UNKNOWN')
4185
+ if (tab.failure !== undefined) throw tab.failure
3716
4186
  return tab
3717
4187
  }
3718
4188
 
3719
4189
  /** Append a fresh tab and make it active. */
3720
4190
  private newTab(s: Session): void {
3721
- const handle = this.host.createView(s.label)
4191
+ const id = tabWireId({ ...resolveSessionHandle(s.id), tab: randomUUID() })
4192
+ const handle = this.host.createView(id)
3722
4193
  // Same window as the session's other tabs.
3723
4194
  this.host.groupView?.(handle, s.id, s.label)
3724
- s.tabs.push({ id: `tab:${randomUUID()}`, handle, url: '' })
4195
+ s.tabs.push({ id, handle, url: '' })
3725
4196
  s.activeIndex = s.tabs.length - 1
3726
4197
  this.showActive(s)
3727
4198
  }
3728
4199
 
3729
- /**
3730
- * Swap a wedged view for a fresh blank one, keeping the tab's public id.
3731
- *
3732
- * A view whose renderer never commits cannot be read again: every evaluate into it runs out its
3733
- * whole budget. Replacing it is what turns that from permanent into one bad call — the tab id
3734
- * callers hold stays valid, and the next `dsh_browser_open` with the real URL re-populates it.
3735
- *
3736
- * The old view is destroyed AFTER the new one is in place, so a failure here cannot leave the
3737
- * session holding a handle that is already gone.
3738
- * @param s - the session owning the tab.
3739
- * @param tab - the tab to reset.
3740
- */
3741
- private replaceTabWithBlank(s: Session, tab: Tab): void {
3742
- const index = s.tabs.indexOf(tab)
3743
- if (index < 0) return
3744
- let handle: ElectronViewHandle
3745
- try {
3746
- handle = this.host.createView(s.label)
3747
- this.host.groupView?.(handle, s.id, s.label)
3748
- } catch {
3749
- // Creating the replacement failed: leaving the wedged tab in place is worse than nothing
3750
- // only for the caller, who is about to be told the tab timed out either way.
3751
- return
4200
+ private carrierScope(s: Session): BrowserSessionId {
4201
+ return s.id
4202
+ }
4203
+
4204
+ private carrierTab(s: Session, id: string): BrowserTabWireId {
4205
+ const scope = resolveSessionHandle(s.id)
4206
+ return tabWireId(resolveTabHandle(scope, id))
4207
+ }
4208
+
4209
+ private carrierId(s: Session, id: BrowserTabWireId): BrowserTabWireId | undefined {
4210
+ const tab = resolveTabHandle(resolveSessionHandle(s.id), id).tab
4211
+ if (!tab.startsWith('page:') && this.host.closePage === undefined) return undefined
4212
+ return id
4213
+ }
4214
+
4215
+ private destroyTab(tab: Tab, options?: { readonly keepPage?: boolean }): void {
4216
+ tab.navigationAbort?.abort(new BrowserError('browser: the navigation guest was closed', 'BROWSER_GUEST_CLOSED'))
4217
+ this.host.destroyView(tab.handle, options)
4218
+ }
4219
+
4220
+ private interrupt(handle: ElectronViewHandle, timedOut: boolean): void {
4221
+ if (timedOut) this.quarantine(handle)
4222
+ else terminatePage(handle)
4223
+ }
4224
+
4225
+ private quarantine(handle: ElectronViewHandle): void {
4226
+ for (const session of this.sessions.values()) {
4227
+ const tab = session.tabs.find(tab => tab.handle === handle)
4228
+ if (tab === undefined || tab.failure !== undefined) continue
4229
+ 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')
4230
+ terminatePage(handle)
3752
4231
  }
3753
- const wedged = tab.handle
3754
- s.tabs[index] = { id: tab.id, handle, url: '' }
3755
- if (index === s.activeIndex) this.showActive(s)
3756
- this.host.destroyView(wedged)
3757
4232
  }
3758
4233
 
3759
4234
  /** Find a session's tab by its backing view id (toolbar actions carry view ids). */
@@ -3783,6 +4258,14 @@ export class ElectronBrowserProvider implements BrowserProvider {
3783
4258
  return [...this.sessions.keys()]
3784
4259
  }
3785
4260
 
4261
+ takeoverTargets(owner: string): readonly { session: BrowserSessionId; owner: string; tabId: string; pageId: string; url: string }[] {
4262
+ return [...this.sessions.values()].filter(s => (s.label ?? 'default').replace(/^session-/u, '') === owner).flatMap(s => {
4263
+ const tab = s.tabs[s.activeIndex]
4264
+ return tab && !tab.failure && /^https?:\/\//u.test(tab.url)
4265
+ ? [{ session: s.id, owner: s.label ?? 'default', tabId: tab.id, pageId: tab.id, url: tab.url }] : []
4266
+ })
4267
+ }
4268
+
3786
4269
  /**
3787
4270
  * The human closed a browser window: the session that window showed is over.
3788
4271
  * Ending it here is what makes the next call a clean start rather than a
@@ -3803,8 +4286,8 @@ export class ElectronBrowserProvider implements BrowserProvider {
3803
4286
  * URL typed into the address bar) must never crash the host UI loop — it
3804
4287
  * is reported to the host (toolbar) when the host supports it, else logged.
3805
4288
  */
3806
- private async handleUserAction(action: BrowserUserAction): Promise<void> {
3807
- const s = this.sessions.get(action.windowId)
4289
+ private async handleUserAction(action: BrowserUserAction, propagate = false): Promise<void> {
4290
+ const s = this.sessions.get(action.windowId as BrowserSessionId)
3808
4291
  if (s === undefined) {
3809
4292
  // The window the human clicked in has no live session here (session
3810
4293
  // closed, or a child restart changed identity). Never swallow the click
@@ -3812,10 +4295,25 @@ export class ElectronBrowserProvider implements BrowserProvider {
3812
4295
  const message = `action ${action.type} failed: no live browser session for window "${action.windowId}"`
3813
4296
  process.stderr.write(`[dsh-browser] ${message}\n`)
3814
4297
  this.notifyUserActionError(action, new Error('no live browser session'))
4298
+ if (propagate) throw new Error('no live browser session')
3815
4299
  return
3816
4300
  }
3817
4301
  try {
3818
4302
  switch (action.type) {
4303
+ case 'capture-reference':
4304
+ // The human clicked a native menu item or the page's floating entry.
4305
+ // Delivery is owned by the plugin entry, which holds the reference
4306
+ // service; the provider only routes the action to the right session.
4307
+ await dispatchReferenceCaptureAction({
4308
+ windowId: action.windowId,
4309
+ entry: action.entry,
4310
+ ...action.frameSelector !== undefined ? { frameSelector: action.frameSelector } : {},
4311
+ ...action.target !== undefined ? { target: action.target } : {},
4312
+ ...action.comment !== undefined ? { comment: action.comment } : {},
4313
+ ...action.selectionText !== undefined ? { selectionText: action.selectionText } : {},
4314
+ ...action.capture !== undefined ? { capture: action.capture } : {},
4315
+ })
4316
+ return
3819
4317
  case 'navigate':
3820
4318
  await this.openUrl(s.id, { url: action.url })
3821
4319
  return
@@ -3847,6 +4345,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
3847
4345
  }
3848
4346
  } catch (error) {
3849
4347
  this.notifyUserActionError(action, error)
4348
+ if (propagate) throw error
3850
4349
  }
3851
4350
  }
3852
4351
 
@@ -3903,7 +4402,8 @@ export class ElectronBrowserProvider implements BrowserProvider {
3903
4402
  */
3904
4403
  private showActive(s: Session, select = false): void {
3905
4404
  const quiet = this.isQuiet()
3906
- this.host.showView?.(this.activeTab(s).handle, s.label, { quiet, ...select ? { select: true } : {} })
4405
+ const active = s.tabs[s.activeIndex]
4406
+ if (active !== undefined) this.host.showView?.(active.handle, s.label, { quiet, ...select ? { select: true } : {} })
3907
4407
  if (quiet || select) return
3908
4408
  const autoExpand = this.settingsSource === undefined || this.settingsSource().ui.autoExpandOnce
3909
4409
  if (autoExpand) return
@@ -3914,24 +4414,18 @@ export class ElectronBrowserProvider implements BrowserProvider {
3914
4414
  /** Read the current URL of a view through CDP. */
3915
4415
  private async currentUrl(handle: ElectronViewHandle): Promise<string> {
3916
4416
  // Bound the read: a wedged renderer would otherwise hang listTabs.
3917
- const timeoutMs = 10_000
4417
+ const timeoutMs = PROVIDER_TIMEOUTS.lookup
3918
4418
  const result = await withTimeout(
3919
4419
  handleSendEvaluate(handle, 'location.href'),
3920
4420
  timeoutMs,
3921
4421
  undefined,
3922
4422
  `browser: url read timed out after ${timeoutMs}ms`,
3923
- () => terminatePage(handle),
4423
+ timedOut => { this.interrupt(handle, timedOut) },
3924
4424
  )
3925
4425
  return result.ok && typeof result.value === 'string' ? result.value : ''
3926
4426
  }
3927
4427
  }
3928
4428
 
3929
- /**
3930
- * Hard cap on waiting for a navigation's new document to be parsed. Bounded and
3931
- * best-effort: a page that never settles must not fail the navigation.
3932
- */
3933
- const SETTLE_TIMEOUT_MS = 5_000
3934
-
3935
4429
  /**
3936
4430
  * Bounds for one passive preview frame.
3937
4431
  *
@@ -3945,13 +4439,6 @@ const PREVIEW_QUALITY = 70
3945
4439
  const PREVIEW_MAX_WIDTH = 1280
3946
4440
  const PREVIEW_MAX_HEIGHT = 720
3947
4441
 
3948
- /**
3949
- * When the document already looks settled but its identity has NOT changed
3950
- * (same-document navigation, or the outgoing document still answering), wait
3951
- * only this long before returning — there is no parse in flight to wait for.
3952
- */
3953
- const SETTLE_GRACE_MS = 150
3954
-
3955
4442
  /** Poll interval for the document-settle loop. */
3956
4443
  const SETTLE_POLL_MS = 25
3957
4444
 
@@ -3962,10 +4449,6 @@ const SETTLE_POLL_MS = 25
3962
4449
  */
3963
4450
  const TARGET_SCRIPT_GRACE_MS = 2_000
3964
4451
 
3965
- /** `tab:<uuid>` ↔ `<uuid>`: ids accept either form (see locateTab). */
3966
- function stripTabPrefix(id: string): string {
3967
- return id.startsWith('tab:') ? id.slice(4) : id
3968
- }
3969
4452
 
3970
4453
  /** Abortable sleep used by the settle loop. */
3971
4454
  function delay(ms: number, signal?: AbortSignal): Promise<void> {
@@ -3994,7 +4477,7 @@ function withTimeout<T>(
3994
4477
  ms: number,
3995
4478
  signal: AbortSignal | undefined,
3996
4479
  message: string,
3997
- onCancel?: () => void,
4480
+ onCancel?: (timedOut: boolean) => void,
3998
4481
  ): Promise<T> {
3999
4482
  return new Promise<T>((resolve, reject) => {
4000
4483
  let done = false
@@ -4008,7 +4491,7 @@ function withTimeout<T>(
4008
4491
  error.name = 'TimeoutError'
4009
4492
  reject(error)
4010
4493
  // Best-effort interrupt of the underlying CDP call (see onCancel).
4011
- onCancel?.()
4494
+ onCancel?.(true)
4012
4495
  }, ms)
4013
4496
  const finish = (fn: () => void): void => {
4014
4497
  if (done) return
@@ -4022,7 +4505,7 @@ function withTimeout<T>(
4022
4505
  done = true
4023
4506
  clearTimeout(timer)
4024
4507
  reject(signal?.reason instanceof Error ? signal.reason : new Error('aborted'))
4025
- onCancel?.()
4508
+ onCancel?.(false)
4026
4509
  }
4027
4510
  if (signal !== undefined) signal.addEventListener('abort', onAbort, { once: true })
4028
4511
  promise.then(
@@ -4048,7 +4531,7 @@ function terminatePage(handle: ElectronViewHandle): void {
4048
4531
  const count = pendingTerminations.get(handle) ?? 0
4049
4532
  if (count >= MAX_PENDING_TERMINATIONS) return
4050
4533
  pendingTerminations.set(handle, count + 1)
4051
- void handle.sendCommand('Runtime.terminateExecution').finally(() => {
4534
+ void handle.sendCommand('Runtime.terminateExecution', undefined, { present: false, initialize: false }).finally(() => {
4052
4535
  pendingTerminations.set(handle, Math.max(0, (pendingTerminations.get(handle) ?? 1) - 1))
4053
4536
  }).catch(() => {})
4054
4537
  }
@@ -4086,4 +4569,3 @@ async function handleSendEvaluate(
4086
4569
  }
4087
4570
  return { ok: true, value: (result.result as { value?: unknown } | undefined)?.value ?? null }
4088
4571
  }
4089
-