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 { PATH_NAMES, INSTALL_LOCATIONS } from '../../assets/browser-products.mjs'
2
+ import { cdpVersionUrl, CDP_DEFAULT_ATTACH_PORT, CDP_ATTACH_PROBE_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
1
3
  /**
2
4
  * Drive the browser the user already has (Chrome / Edge / any Chromium) instead of
3
5
  * the Electron we ship — the same approach Codex Browser Use takes.
@@ -28,9 +30,11 @@
28
30
  import { readFileSync, rmSync, statSync } from 'node:fs'
29
31
  import { existsSync } from 'node:fs'
30
32
  import { join } from 'node:path'
33
+ import { acquireProfileLease, type ProfileLease } from './profile-lease.ts'
34
+ import { BrowserProcessOwnership, type ProcessOwnershipOptions } from './process-ownership.ts'
31
35
  // Type-only: settings-store imports BrowserChannel from here, so a value import would be a cycle.
32
36
  // `hasDisplay` lives here instead of there for the same reason — it is a runtime function.
33
- import type { HeadlessMode } from './settings-store.js'
37
+ import type { HeadlessMode } from './settings-store.ts'
34
38
 
35
39
  /**
36
40
  * How long a killed browser is given to actually exit before the launch proceeds.
@@ -68,21 +72,6 @@ const CLOSE_GRACE_MS = 6_000
68
72
  */
69
73
  const PORT_PROBE_MS = 250
70
74
 
71
- /**
72
- * How long to keep trying to adopt a browser after a launcher reported a clean exit.
73
- *
74
- * Exit code 0 means the launcher handed the request to an instance already holding this profile —
75
- * but on Windows that stub exits BEFORE the real browser writes `DevToolsActivePort`. Measured on
76
- * Chrome 156: stub gone at 300 ms, port file present at 441 ms (issue #33). A single attempt read
77
- * too early and reported a launch failure for a browser that was starting normally, so this is a
78
- * retry rather than one shot.
79
- *
80
- * 8 s is the reporter's measured-working bound and is generous against that ~150 ms gap: an honest
81
- * hand-off resolves in well under a second, and a launch that genuinely failed still reaches the
82
- * error within the same budget the CDP loop already allows.
83
- */
84
- const HANDOFF_ADOPT_MS = 8_000
85
-
86
75
  /**
87
76
  * Starts a browser process and returns a handle to it.
88
77
  *
@@ -94,13 +83,30 @@ const HANDOFF_ADOPT_MS = 8_000
94
83
  */
95
84
  export type BrowserLauncher = (path: string, args: readonly string[]) => ReturnType<typeof spawn>
96
85
 
97
- /** The real launcher: spawn a detached-free child with pipes closed. */
86
+ export interface SystemBrowserLaunchDiagnostic {
87
+ cleanup?: 'ownership-unverified'
88
+ stderrTail: string
89
+ exitCode: number | null
90
+ signal: string | null
91
+ devToolsActivePortPresent: boolean
92
+ }
93
+
94
+ function diagnosticTail(value: string): string {
95
+ return value.replace(/\b(?:https?|wss?):\/\/[^\s]+/giu, '[URL redacted]')
96
+ .replace(/\b(authorization|cookie|password|token|secret)(\s*[:=]\s*)[^\r\n]+/giu, '$1$2[redacted]')
97
+ .replace(/\bBearer\s+[^\s]+/giu, 'Bearer [redacted]')
98
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/gu, '')
99
+ .split('\n').slice(-12).join('\n').slice(-2048)
100
+ }
101
+
102
+ /** The real launcher: retain stderr for bounded launch diagnostics. */
98
103
  const defaultLauncher: BrowserLauncher = (path, args) =>
99
- spawn(path, [...args], { stdio: ['ignore', 'ignore', 'ignore'], windowsHide: false })
104
+ spawn(path, [...args], { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: false })
100
105
  import { spawn, type ChildProcess } from 'node:child_process'
101
106
  import { randomUUID } from 'node:crypto'
102
- import type { ElectronBrowserViewHost, ElectronViewHandle } from './provider.js'
103
- import type { CarrierPage } from '../browser/types.js'
107
+ import type { ElectronBrowserViewHost, ElectronViewHandle } from './provider.ts'
108
+ import type { CarrierPage } from '../browser/types.ts'
109
+ import { readTabHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId, type BrowserSessionWireId, type BrowserTabWireId } from '../browser/handles.ts'
104
110
 
105
111
  /** Which browser the user asked for. */
106
112
  export type BrowserChannel = 'bundled' | 'chrome' | 'edge' | 'auto' | 'sidebar'
@@ -113,99 +119,6 @@ export interface DetectedBrowser {
113
119
  readonly path: string
114
120
  }
115
121
 
116
- /**
117
- * Launcher names to look for on PATH, per product and per platform.
118
- *
119
- * The names genuinely differ: Linux distributions package the launcher under a
120
- * versioned name (`microsoft-edge-stable`, `google-chrome-stable`), Windows puts
121
- * `chrome.exe` in an Application directory that may or may not be on PATH, and macOS
122
- * ships the executable inside the .app bundle. PATH is still consulted first on every
123
- * platform — it is what reflects how the user actually installed the browser.
124
- */
125
- const PATH_NAMES: Record<DetectedBrowser['kind'], Partial<Record<NodeJS.Platform, string[]>>> = {
126
- chrome: {
127
- win32: ['chrome'],
128
- darwin: ['Google Chrome', 'Chromium'],
129
- linux: ['google-chrome-stable', 'google-chrome', 'chromium', 'chromium-browser'],
130
- },
131
- edge: {
132
- win32: ['msedge'],
133
- darwin: ['Microsoft Edge'],
134
- linux: ['microsoft-edge-stable', 'microsoft-edge', 'microsoft-edge-dev'],
135
- },
136
- brave: {
137
- win32: ['brave'],
138
- darwin: ['Brave Browser'],
139
- linux: ['brave-browser', 'brave'],
140
- },
141
- }
142
-
143
- /**
144
- * Where each product installs when its launcher is not on PATH.
145
- *
146
- * Windows keeps the executable inside a version-less Application directory; macOS
147
- * keeps it inside the .app bundle; Linux distributions that do not use a launcher
148
- * put it under /usr/bin or /opt. All are checked, and anything missed can be named
149
- * explicitly with DSH_BROWSER_<KIND>_PATH.
150
- */
151
- const INSTALL_LOCATIONS: Record<DetectedBrowser['kind'], Partial<Record<NodeJS.Platform, string[]>>> = {
152
- chrome: {
153
- win32: [
154
- String.raw`%ProgramFiles%\Google\Chrome\Application\chrome.exe`,
155
- String.raw`%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe`,
156
- // Where a per-user install lands, which is what Chrome's own installer chooses when it
157
- // cannot (or should not) write to Program Files. Missing this meant the plugin reported
158
- // "no browser found" on machines that plainly had one.
159
- String.raw`%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe`,
160
- String.raw`%LOCALAPPDATA%\Chromium\Application\chrome.exe`,
161
- ],
162
- darwin: [
163
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
164
- '/Applications/Chromium.app/Contents/MacOS/Chromium',
165
- ],
166
- linux: [
167
- '/usr/bin/google-chrome-stable',
168
- '/usr/bin/google-chrome',
169
- '/usr/bin/chromium',
170
- '/opt/google/chrome/chrome',
171
- '/snap/bin/chromium',
172
- ],
173
- },
174
- edge: {
175
- win32: [
176
- String.raw`%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe`,
177
- String.raw`%ProgramFiles%\Microsoft\Edge\Application\msedge.exe`,
178
- String.raw`%LOCALAPPDATA%\Microsoft\Edge\Application\msedge.exe`,
179
- ],
180
- darwin: ['/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'],
181
- linux: [
182
- '/usr/bin/microsoft-edge-stable',
183
- '/usr/bin/microsoft-edge',
184
- '/usr/bin/microsoft-edge-dev',
185
- ],
186
- },
187
- brave: {
188
- win32: [
189
- String.raw`%ProgramFiles%\BraveSoftware\Brave-Browser\Application\brave.exe`,
190
- String.raw`%ProgramFiles(x86)%\BraveSoftware\Brave-Browser\Application\brave.exe`,
191
- String.raw`%LOCALAPPDATA%\BraveSoftware\Brave-Browser\Application\brave.exe`,
192
- ],
193
- darwin: ['/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'],
194
- linux: ['/usr/bin/brave-browser', '/usr/bin/brave', '/snap/bin/brave'],
195
- },
196
- }
197
-
198
- /**
199
- * Resolve the environment references in one install location.
200
- *
201
- * The list is static strings, but a per-user install lands under %LOCALAPPDATA%, so the entry
202
- * has to be resolved against the environment detection was HANDED rather than process.env — a
203
- * caller that supplies a platform and an environment (which is what makes detection testable)
204
- * must not end up reading the developer's real machine.
205
- * @param location - one entry from the install-location table.
206
- * @param env - the environment to resolve against.
207
- * @returns the path with %NAME% references replaced, or the entry unchanged when unknown.
208
- */
209
122
  /**
210
123
  * Whether a browser's self-reported product name is one this carrier could have launched.
211
124
  *
@@ -235,32 +148,6 @@ function hasDisplay(env: NodeJS.ProcessEnv = process.env): boolean {
235
148
  return (env.DISPLAY ?? '') !== '' || (env.WAYLAND_DISPLAY ?? '') !== ''
236
149
  }
237
150
 
238
- /**
239
- * Whether Chromium's own sandbox cannot start here.
240
- *
241
- * Two cases, both of which make the browser exit at once rather than degrade: running as root
242
- * (the sandbox refuses), and running inside a container that lacks the namespaces it needs. The
243
- * check is deliberately conservative — when it is unsure it answers false, so the default is the
244
- * sandboxed launch and the weaker mode only happens where it is required.
245
- * @param env - the environment to inspect; defaults to the current process.
246
- * @returns true when `--no-sandbox` is required for the browser to start at all.
247
- */
248
- function needsNoSandbox(env: NodeJS.ProcessEnv = process.env): boolean {
249
- if (process.platform === 'win32') return false
250
- try {
251
- if (typeof process.getuid === 'function' && process.getuid() === 0) return true
252
- } catch {
253
- // No getuid: not a POSIX process; the container checks below still apply.
254
- }
255
- if ((env.container ?? '') !== '') return true
256
- try {
257
- if (existsSync('/.dockerenv')) return true
258
- } catch {
259
- // An unreadable root is not evidence of a container.
260
- }
261
- return false
262
- }
263
-
264
151
  /**
265
152
  * Resolve `auto` into a concrete decision, and say why.
266
153
  *
@@ -443,8 +330,8 @@ class CdpClient {
443
330
  return this.socket.readyState === WebSocket.OPEN
444
331
  }
445
332
 
446
- async whenReady(): Promise<void> {
447
- const timeoutMs = 30_000
333
+ async whenReady(deadline = Date.now() + 30_000): Promise<void> {
334
+ const timeoutMs = Math.max(1, deadline - Date.now())
448
335
  let timer: NodeJS.Timeout | undefined
449
336
  try {
450
337
  await Promise.race([
@@ -461,6 +348,11 @@ class CdpClient {
461
348
  }
462
349
  }
463
350
 
351
+ async whenClosed(): Promise<void> {
352
+ if (this.socket.readyState === WebSocket.CLOSED) return
353
+ await new Promise<void>(resolve => this.socket.addEventListener('close', () => resolve(), { once: true }))
354
+ }
355
+
464
356
  /**
465
357
  * Send one CDP command, optionally on an attached session.
466
358
  * @param method - the CDP method.
@@ -468,7 +360,7 @@ class CdpClient {
468
360
  * @param sessionId - the flattened session to target, when this is a page command.
469
361
  * @returns the CDP result.
470
362
  */
471
- async send(method: string, params?: Record<string, unknown>, sessionId?: string): Promise<unknown> {
363
+ async send(method: string, params?: Record<string, unknown>, sessionId?: string, timeoutMs = 30_000): Promise<unknown> {
472
364
  // Fail fast and say why. Waiting out the timeout on a closed socket produced
473
365
  // only "timed out", which reads as a slow page and hides the real cause.
474
366
  if (!this.isAlive()) {
@@ -482,7 +374,7 @@ class CdpClient {
482
374
  this.socket.send(JSON.stringify(message))
483
375
  setTimeout(() => {
484
376
  if (this.pending.delete(id)) reject(new Error(`dsh-builtin-browser: ${method} timed out`))
485
- }, 30_000).unref?.()
377
+ }, timeoutMs).unref?.()
486
378
  })
487
379
  }
488
380
 
@@ -546,9 +438,10 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
546
438
  */
547
439
  private clientSuspect = false
548
440
  private child: ChildProcess | undefined
549
- /** Whether this connection's surplus blank pages have been collapsed already. */
550
- private blanksNormalized = false
441
+ private profileLease: ProfileLease | undefined
551
442
  private starting: Promise<CdpClient> | undefined
443
+ private lastLaunchError: string | undefined
444
+ private launchDiagnostic: SystemBrowserLaunchDiagnostic | undefined
552
445
 
553
446
  /**
554
447
  * Browsers that ignored a kill.
@@ -557,7 +450,11 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
557
450
  * are still running, still holding the profile, and still something release must try to
558
451
  * stop. Forgetting them is what allowed a launch this host could not undo.
559
452
  */
560
- private readonly stubborn: { kill: () => void; exitCode: number | null; signalCode: NodeJS.Signals | null }[] = []
453
+ private readonly stubborn: ChildProcess[] = []
454
+ private readonly ownership: BrowserProcessOwnership
455
+ private readonly ownedClients = new WeakMap<CdpClient, ChildProcess>()
456
+ private readonly ownedChildren = new WeakSet<ChildProcess>()
457
+ private readonly createdTargets = new WeakMap<CdpClient, Map<string, BrowserTabWireId>>()
561
458
 
562
459
  /**
563
460
  * @param browser - the detected installation to launch on first use.
@@ -585,7 +482,43 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
585
482
  */
586
483
  private readonly headlessMode: HeadlessMode = 'auto',
587
484
  private readonly isQuiet: () => boolean = () => false,
588
- ) {}
485
+ private readonly profileError?: string,
486
+ ownership: ProcessOwnershipOptions = { managed: false },
487
+ ) {
488
+ this.ownership = new BrowserProcessOwnership(browser.path, profileDir, ownership)
489
+ }
490
+
491
+ private async stopChild(child: ChildProcess): Promise<boolean> {
492
+ if (child.exitCode !== null || child.signalCode !== null) return true
493
+ if (await this.ownership.terminate(child)) return true
494
+ this.lastLaunchError = 'Cleanup refused: process ownership could not be verified; browser left running.'
495
+ if (this.launchDiagnostic) this.launchDiagnostic.cleanup = 'ownership-unverified'
496
+ return false
497
+ }
498
+
499
+ async prepare(): Promise<void> {
500
+ try {
501
+ await this.ensureClient()
502
+ } catch (error) {
503
+ const launch = this.connectionStatus().launch
504
+ if (!(error instanceof Error) || launch === undefined) throw error
505
+ throw Object.assign(new Error(`${error.message} Launch diagnostic: ${JSON.stringify(launch)}`, { cause: error }),
506
+ 'code' in error ? { code: error.code } : {})
507
+ }
508
+ }
509
+
510
+ connectionStatus(): { connected: boolean; detail: string; launch?: SystemBrowserLaunchDiagnostic } {
511
+ const connected = !this.disposed && this.client?.isAlive() === true && !this.clientSuspect
512
+ return { connected, detail: connected ? 'Browser launched and connected over CDP.'
513
+ : this.profileError ?? this.lastLaunchError ?? (this.disposed ? 'Browser carrier was released.'
514
+ : this.starting ? 'Browser launch is in progress; no live CDP connection yet.'
515
+ : this.client ? 'Browser CDP connection was lost or is awaiting verification.'
516
+ : 'Browser has not launched; run a browser command to establish CDP. No live CDP connection.'),
517
+ ...this.launchDiagnostic === undefined ? {} : { launch: {
518
+ ...this.launchDiagnostic, devToolsActivePortPresent: existsSync(join(this.profileDir, 'DevToolsActivePort')),
519
+ } },
520
+ }
521
+ }
589
522
 
590
523
  /** Which product this host would drive (for diagnostics). */
591
524
  get kind(): DetectedBrowser['kind'] {
@@ -642,16 +575,13 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
642
575
  private forgetBrowserState(): void {
643
576
  this.views.clear()
644
577
  this.sessions.clear()
645
- // A new browser comes with its own surplus pages, so the tidy-up runs again for it. Without
646
- // this, a restart would inherit the previous connection's "already handled" and leave the new
647
- // browser's extra blank page in place for the rest of the session.
648
- this.blanksNormalized = false
649
578
  }
650
579
 
651
580
  private async ensureClient(): Promise<CdpClient> {
652
581
  // A disposed host must never start a browser: doing so would spawn a process
653
582
  // nobody owns and nobody will kill.
654
583
  if (this.disposed) throw new Error('dsh-builtin-browser: this browser host was released')
584
+ if (this.profileError !== undefined) throw new Error(this.profileError)
655
585
  // The exit listener clears this, but a socket can also die without the process doing so
656
586
  // (the browser closing its debugging endpoint, a dropped connection). Checking the
657
587
  // socket's own state costs nothing and turns a 30s hang into a restart.
@@ -677,15 +607,14 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
677
607
  this.forgetBrowserState()
678
608
  }
679
609
  // Concurrent first calls share one startup rather than racing two browsers.
680
- this.starting ??= this.start().finally(() => { this.starting = undefined })
681
- const client = await this.starting
682
- // Once per connection. A browser opens more than one page when it starts, and the surplus is
683
- // invisible to the plugin's tab model — see normalizeBlankPages for why that matters.
684
- if (!this.blanksNormalized) {
685
- this.blanksNormalized = true
686
- await this.normalizeBlankPages(client)
687
- }
688
- return client
610
+ this.starting ??= this.start().then(client => {
611
+ this.lastLaunchError = undefined
612
+ return client
613
+ }).catch(error => {
614
+ this.lastLaunchError = error instanceof Error ? error.message : String(error)
615
+ throw error
616
+ }).finally(() => { this.starting = undefined })
617
+ return await this.starting
689
618
  }
690
619
 
691
620
  /**
@@ -706,10 +635,12 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
706
635
  * @param _why - a short phrase for the log, naming which attempt this is.
707
636
  * @returns a connected client for the running browser, or undefined when there is none.
708
637
  */
709
- private async adoptRunningBrowser(_why: string): Promise<CdpClient | undefined> {
638
+ private async adoptRunningBrowser(_why: string, explicitPort?: number, deadline = Date.now() + 30_000): Promise<CdpClient | undefined> {
710
639
  const portFile = join(this.profileDir, 'DevToolsActivePort')
711
640
  let port: number
712
- try {
641
+ if (typeof explicitPort === 'number' && explicitPort > 0) {
642
+ port = explicitPort
643
+ } else try {
713
644
  if (!existsSync(portFile)) return undefined
714
645
  const value = Number(readFileSync(portFile, 'utf8').split('\n')[0]?.trim() ?? '')
715
646
  if (!Number.isInteger(value) || value <= 0) return undefined
@@ -717,27 +648,34 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
717
648
  } catch {
718
649
  return undefined
719
650
  }
651
+ let client: CdpClient | undefined
652
+ let identified = false
720
653
  try {
721
- const version = await (await fetch(`http://127.0.0.1:${port}/json/version`, {
722
- signal: AbortSignal.timeout(PORT_PROBE_MS),
654
+ const version = await (await fetch(cdpVersionUrl(port), {
655
+ signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())),
723
656
  })).json() as { webSocketDebuggerUrl?: string; Browser?: string }
724
657
  if (typeof version.webSocketDebuggerUrl !== 'string') return undefined
725
658
  // The port number alone proves nothing — it can be reused once the browser that owned it
726
659
  // exits. The endpoint's own answer is the evidence, and it has to name a browser.
727
660
  if (!isBrowserProduct(version.Browser)) return undefined
728
- const client = new CdpClient(version.webSocketDebuggerUrl)
729
- await client.whenReady()
661
+ identified = true
662
+ client = new CdpClient(version.webSocketDebuggerUrl)
663
+ await client.whenReady(deadline)
730
664
  // Asked through the protocol too, so a websocket that merely accepts connections is not
731
665
  // mistaken for a browser that answers.
732
- const info = await client.send('Browser.getVersion', {}) as { product?: string }
733
- if (!isBrowserProduct(info?.product)) {
734
- client.close()
735
- return undefined
736
- }
666
+ const info = await client.send('Browser.getVersion', {}, undefined, Math.max(1, deadline - Date.now())) as { product?: string }
667
+ if (!isBrowserProduct(info?.product) || info.product !== version.Browser) throw new Error('browser did not acknowledge its identity')
737
668
  if (this.disposed) { client.close(); return undefined }
669
+ await client.send('Target.setDiscoverTargets', { discover: true }, undefined, Math.max(1, deadline - Date.now()))
670
+ if (this.disposed || Date.now() >= deadline) { client.close(); return undefined }
738
671
  this.client = client
739
672
  return client
740
- } catch {
673
+ } catch (error) {
674
+ client?.close()
675
+ if (identified) throw error
676
+ if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
677
+ throw new Error('browser did not acknowledge its discovery endpoint before the launch deadline', { cause: error })
678
+ }
741
679
  // No endpoint, nothing listening, or not a browser: all of them mean "launch one".
742
680
  return undefined
743
681
  }
@@ -752,10 +690,22 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
752
690
  * @returns the connected client.
753
691
  */
754
692
  private async start(): Promise<CdpClient> {
693
+ const deadline = Date.now() + 30_000
694
+ this.profileLease ??= acquireProfileLease(this.profileDir)
755
695
  // Before spawning anything: is a browser for THIS profile already running? A DSH restart
756
696
  // leaves one behind, and launching into it is the failure reported as "exited immediately
757
697
  // after launch (exit code 0)" that required killing seven processes by hand.
758
- const adopted = await this.adoptRunningBrowser('before launch')
698
+ // A browser the human started with an explicit debugging port. Port 0 makes Chromium write the chosen
699
+ // port into the profile, which the probe below already finds; an explicit port leaves no file, so this
700
+ // is the only way to reach it. Attaching means driving the window they already have open.
701
+ const explicitPort = Number(process.env.DSH_BROWSER_ATTACH_PORT ?? '')
702
+ const attached = Number.isSafeInteger(explicitPort) && explicitPort > 0
703
+ ? await this.adoptRunningBrowser('explicit attach port', explicitPort, deadline) : undefined
704
+ if (attached !== undefined) {
705
+ ;(globalThis as unknown as Record<string, unknown>).__dshBrowserCarrier = 'attached'
706
+ return attached
707
+ }
708
+ const adopted = await this.adoptRunningBrowser('before launch', undefined, deadline)
759
709
  if (adopted !== undefined) return adopted
760
710
  // Whether a window exists is decided by `browser.headless` ALONE (plus the operator's
761
711
  // DSH_BROWSER_HEADLESS override inside resolveLaunchMode). `ui.quiet` must not force
@@ -793,19 +743,9 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
793
743
  // `--no-startup-window` keeps the browser alive with no window and no initial page; measured
794
744
  // by the reporter on Chrome 156 as writing DevToolsActivePort in 599 ms, answering
795
745
  // `/json/version`, listing two extension targets and no page, and then creating windows
796
- // normally through `Target.createTarget`. A browser that does start a blank despite this is
797
- // still handled: `normalizeBlankPages` closes the surplus and `buildSession` adopts the rest.
746
+ // normally through `Target.createTarget`.
798
747
  '--no-startup-window',
799
748
  ]
800
- // Chromium's own sandbox cannot start in some of these environments — running as root, or
801
- // inside a container without the namespaces it needs — and it exits rather than degrading.
802
- // Only then is the sandbox dropped, and never silently: a setting that weakens process
803
- // isolation must be visible in the log, because whoever reads it has to be able to disagree.
804
- if (launch.headless && needsNoSandbox()) {
805
- args.splice(args.length - 2, 0, '--no-sandbox')
806
- process.stderr.write('[dsh-browser] launching with --no-sandbox: '
807
- + 'this process runs as root or in a container, where the Chromium sandbox cannot start\n')
808
- }
809
749
  if (launch.headless) {
810
750
  process.stderr.write(`[dsh-browser] launching headless (${launch.why}); `
811
751
  + 'the browser has no window but every tool works the same\n')
@@ -815,7 +755,7 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
815
755
  // exit would then be treated as the launch failing.
816
756
  if (this.child !== undefined) {
817
757
  const dying = this.child
818
- try { dying.kill() } catch { /* already gone */ }
758
+ if (!await this.stopChild(dying)) throw new Error(this.lastLaunchError)
819
759
  this.child = undefined
820
760
 
821
761
  // Whatever the old browser issued is worthless now, and its exit listener cannot clean
@@ -847,6 +787,7 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
847
787
  if (at2 !== -1) this.stubborn.splice(at2, 1)
848
788
  })
849
789
  })
790
+ if (dying.exitCode === null && dying.signalCode === null) throw new Error('dsh-builtin-browser: the previous browser still holds this profile; refusing another launch')
850
791
  }
851
792
  // The port file is deliberately NOT deleted here, and that is a reversal.
852
793
  //
@@ -882,6 +823,11 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
882
823
  }
883
824
  })()
884
825
  let child: ReturnType<typeof spawn>
826
+ if (this.disposed || Date.now() >= deadline) throw new Error('dsh-builtin-browser: launch was cancelled or its deadline expired')
827
+ const launchDiagnostic: SystemBrowserLaunchDiagnostic = {
828
+ stderrTail: '', exitCode: null, signal: null, devToolsActivePortPresent: existsSync(portFile),
829
+ }
830
+ this.launchDiagnostic = launchDiagnostic
885
831
  try {
886
832
  child = this.launcher(this.browser.path, args)
887
833
  } catch (error) {
@@ -891,6 +837,12 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
891
837
  throw new Error(`dsh-builtin-browser: could not launch ${this.browser.path}: ${error instanceof Error ? error.message : String(error)}`)
892
838
  }
893
839
  this.child = child
840
+ launchDiagnostic.exitCode = child.exitCode
841
+ launchDiagnostic.signal = child.signalCode
842
+ child.on('exit', (code, signal) => {
843
+ launchDiagnostic.exitCode = code ?? child.exitCode
844
+ launchDiagnostic.signal = signal ?? child.signalCode
845
+ })
894
846
  /**
895
847
  * A launch that fails (ENOENT, no permission, a broken binary) is reported by an
896
848
  * asynchronous 'error' event on the child, NOT by a throw here and NOT by exitCode.
@@ -898,7 +850,19 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
898
850
  * down — one bad browser path would kill DSH, not just fail a tool call.
899
851
  */
900
852
  let launchError: Error | undefined
901
- child.on('error', error => { launchError = error })
853
+ let diagnostic = ''
854
+ child.stderr?.on('data', chunk => {
855
+ diagnostic = (diagnostic + String(chunk)).slice(-4096)
856
+ launchDiagnostic.stderrTail = diagnosticTail(diagnostic)
857
+ if (/remote debugging requires a non-default data directory/iu.test(diagnostic)) {
858
+ launchError = new Error('The browser refused remote debugging on its default user profile. A live CDP connection is required; no alternative profile was substituted.')
859
+ }
860
+ })
861
+ child.on('error', error => {
862
+ launchError = error
863
+ launchDiagnostic.exitCode = child.exitCode
864
+ launchDiagnostic.signal = child.signalCode
865
+ })
902
866
  // A browser that exits later is as unusable as one that never started, and the failure
903
867
  // has to reach the NEXT call rather than being swallowed: clearing the client here is
904
868
  // what makes ensureClient() start a fresh browser instead of returning a socket to a
@@ -908,11 +872,13 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
908
872
  this.client?.close()
909
873
  this.client = undefined
910
874
  this.child = undefined
875
+ this.lastLaunchError = 'Browser exited; the CDP connection is no longer live.'
911
876
  // The pages this client opened belong to the process that just died; keeping their
912
877
  // session ids means every later command is sent to a browser that never issued them.
913
878
  // Clearing these is what makes the restart usable rather than merely alive.
914
879
  this.forgetBrowserState()
915
880
  })
881
+ await this.ownership.capture(child)
916
882
  /**
917
883
  * The port this launch wrote, or undefined while it has not written one yet.
918
884
  *
@@ -931,14 +897,13 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
931
897
  // keeps this correct on a filesystem whose timestamps are coarser than a millisecond.
932
898
  if (portFileBefore !== undefined
933
899
  && after.mtimeMs <= portFileBefore.mtimeMs
934
- && contents === portFileBefore.contents) return undefined
900
+ && contents === portFileBefore.contents && child.exitCode !== 0) return undefined
935
901
  const value = Number(contents.split('\n')[0]?.trim() ?? '')
936
902
  return Number.isInteger(value) && value > 0 ? value : undefined
937
903
  } catch {
938
904
  return undefined
939
905
  }
940
906
  }
941
- const deadline = Date.now() + 30_000
942
907
  /**
943
908
  * Why the loop stopped, so the failure can say what actually happened. Reporting
944
909
  * every ending as "did not expose CDP within 30s" was wrong three ways: the cause,
@@ -951,40 +916,57 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
951
916
  // browser that dispose() has already killed, which would leave a connection
952
917
  // to a dead process behind. The child is killed here too — dispose() may have
953
918
  // run before this child was recorded, leaving nobody else to do it.
954
- if (this.disposed) { child.kill(); if (this.child === child) this.child = undefined; stopped = 'released'; break }
919
+ if (this.disposed) { await this.stopChild(child); if (this.child === child) this.child = undefined; stopped = 'released'; break }
955
920
  if (launchError !== undefined) { if (this.child === child) this.child = undefined; stopped = 'launch-failed'; break }
956
- if (Date.now() > deadline) { child.kill(); if (this.child === child) this.child = undefined; stopped = 'timeout'; break }
921
+ if (Date.now() > deadline) { await this.stopChild(child); stopped = 'timeout'; break }
957
922
  // signalCode too: a browser killed by a signal never sets exitCode, so checking exitCode
958
923
  // alone made a killed browser look alive and the launch run out its full 30s deadline
959
924
  // before reporting "did not expose CDP" — a timeout for something that died at once.
960
925
  // The sibling check on the release path already looked at both.
961
- if (child.exitCode !== null || child.signalCode !== null) { if (this.child === child) this.child = undefined; stopped = 'exited'; break }
926
+ if (child.signalCode !== null || (child.exitCode !== null && child.exitCode !== 0)) { if (this.child === child) this.child = undefined; stopped = 'exited'; break }
962
927
  // Only a port THIS launch wrote: reading whatever file happened to be there is how a
963
928
  // restart could adopt the previous browser, or any process now holding that port.
964
929
  const port = freshPort()
965
930
  if (port !== undefined) {
966
931
  try {
967
- const version = await (await fetch(`http://127.0.0.1:${port}/json/version`, {
932
+ const version = await (await fetch(cdpVersionUrl(port), {
968
933
  // Bounded: an unanswered loopback request would otherwise park inside this
969
934
  // iteration for the rest of the budget, and the deadline above is only re-checked
970
935
  // between iterations. Deliberately no larger than the 250 ms sleep — see
971
936
  // PORT_PROBE_MS.
972
- signal: AbortSignal.timeout(PORT_PROBE_MS),
973
- })).json() as { webSocketDebuggerUrl?: string }
937
+ signal: AbortSignal.timeout(Math.max(1, Math.min(PORT_PROBE_MS, deadline - Date.now()))),
938
+ })).json() as { webSocketDebuggerUrl?: string; Browser?: string }
974
939
  if (typeof version.webSocketDebuggerUrl === 'string') {
975
940
  const client = new CdpClient(version.webSocketDebuggerUrl)
976
941
  // `whenReady` has its own 30 s ceiling, and it is reached only after the port
977
942
  // answered above — so the browser is listening and this is a handshake, not a
978
943
  // discovery. A handshake that outlives the launch is reported as the timeout it
979
944
  // is, by the same deadline that governs everything else here.
980
- await client.whenReady()
945
+ try {
946
+ await client.whenReady(deadline)
947
+ const info = await client.send('Browser.getVersion', {}, undefined, Math.max(1, deadline - Date.now())) as { product?: string }
948
+ if (typeof info.product !== 'string' || info.product === '' || info.product !== version.Browser) throw Object.assign(new Error('browser did not acknowledge its identity'), { code: 'BROWSER_LAUNCH_UNACKNOWLEDGED' })
949
+ await client.send('Target.setDiscoverTargets', { discover: true }, undefined, Math.max(1, deadline - Date.now()))
950
+ } catch (error) { client.close(); throw error }
981
951
  // Still wanted? A dispose() during the handshake has already killed the
982
952
  // process, so publishing the client would leave a dangling connection.
953
+ if (this.disposed || Date.now() >= deadline) { client.close(); break }
954
+ if (await this.ownership.verify(child)) {
955
+ try {
956
+ const processes = await client.send('SystemInfo.getProcessInfo', {}, undefined, 1000) as { processInfo?: { type: string; id: number }[] }
957
+ if (processes.processInfo?.some(entry => entry.type === 'browser' && entry.id === child.pid)
958
+ && await this.ownership.verify(child)) {
959
+ this.ownedClients.set(client, child)
960
+ this.ownedChildren.add(child)
961
+ }
962
+ } catch { /* An unidentified endpoint is borrowed, never owned. */ }
963
+ }
983
964
  if (this.disposed) { client.close(); break }
984
965
  this.client = client
985
966
  return client
986
967
  }
987
- } catch {
968
+ } catch (error) {
969
+ if ((error as { code?: string })?.code === 'BROWSER_LAUNCH_UNACKNOWLEDGED') throw error
988
970
  // The file can exist a moment before the port answers; poll again.
989
971
  }
990
972
  }
@@ -1004,32 +986,8 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1004
986
  // which is the same mistake this message was written to correct, pointing the other way.
1005
987
  const code = child.exitCode
1006
988
  const signal = child.signalCode
1007
- const clean = code === 0 && signal === null
1008
- // Exit code 0 IS the hand-off: the request went to an instance already holding this profile,
1009
- // so that instance is our browser and it is running right now. Adopting it turns the
1010
- // reported "kill the leftovers by hand, on every restart" into a call that just works.
1011
- //
1012
- // Adopted with a bounded RETRY, because on Windows the launcher stub exits before the browser
1013
- // has written its port file: measured 300 ms to exit against 441 ms for DevToolsActivePort.
1014
- // One attempt therefore read too early and reported "exited immediately after launch" for a
1015
- // browser that was starting normally — reported as issue #33, where the reporter's own
1016
- // retry loop fixed it. 8 s at 250 ms is their measured-working bound and is generous against
1017
- // the ~150 ms gap, without turning a genuinely failed launch into a slow failure.
1018
- if (clean) {
1019
- const deadline = Date.now() + HANDOFF_ADOPT_MS
1020
- for (;;) {
1021
- const recovered = await this.adoptRunningBrowser('after a hand-off')
1022
- if (recovered !== undefined) return recovered
1023
- if (this.disposed || Date.now() >= deadline) break
1024
- await new Promise(resolve => setTimeout(resolve, PORT_PROBE_MS))
1025
- }
1026
- }
1027
989
  throw new Error(
1028
- clean
1029
- ? `dsh-builtin-browser: ${target} exited immediately after launch (exit code 0). `
1030
- + 'That means it handed the request to an instance already using this profile '
1031
- + 'directory and quit — look for a leftover browser process from an earlier run, then retry.'
1032
- : `dsh-builtin-browser: ${target} exited immediately after launch `
990
+ `dsh-builtin-browser: ${target} exited immediately after launch `
1033
991
  + `(${signal !== null ? `killed by ${signal}` : `exit code ${String(code)}`}), so it did not `
1034
992
  + 'hand the request anywhere — the browser failed to start rather than deferring to another '
1035
993
  + 'instance. Check that it can run at all: run it by hand, and look for a crash or a missing '
@@ -1039,7 +997,11 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1039
997
  if (stopped === 'released') {
1040
998
  throw new Error(`dsh-builtin-browser: ${target} was released while it was starting`)
1041
999
  }
1042
- throw new Error(`dsh-builtin-browser: ${target} did not expose CDP within 30s`)
1000
+ throw new Error(`dsh-builtin-browser: ${target} did not expose CDP within 30s. `
1001
+ + (child.exitCode === 0 && !existsSync(portFile)
1002
+ ? 'The launcher exited successfully without DevToolsActivePort; it may have handed off to an already-running browser without debugging enabled. '
1003
+ : 'The selected profile did not provide a live debugging endpoint. ')
1004
+ + 'No alternative browser profile was substituted.')
1043
1005
  }
1044
1006
 
1045
1007
  /**
@@ -1061,7 +1023,7 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1061
1023
  * Those pages are real: they hold memory and stay until something closes them. Measured on a real
1062
1024
  * window: four pages present while `dsh_browser_list_tabs` reported one.
1063
1025
  *
1064
- * Discovery is already on at connection time (see the blank-page normalisation), so
1026
+ * Discovery is enabled before the connection is published, so
1065
1027
  * `Target.getTargets` also lists pages that existed before this client connected.
1066
1028
  * @returns the browser's pages, or an empty list when it cannot answer.
1067
1029
  */
@@ -1078,11 +1040,21 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1078
1040
  * CDP target id, and the two never match. The first version returned everything and relied on the
1079
1041
  * caller to filter, which reported the same page twice.
1080
1042
  *
1081
- * Discovery is already on at connection time (see the blank-page normalisation), so
1043
+ * Discovery is enabled before the connection is published, so
1082
1044
  * `Target.getTargets` also lists pages that existed before this client connected.
1083
1045
  * @returns the browser's pages that are not ours, or an empty list when it cannot answer.
1084
1046
  */
1085
- async listPages(): Promise<readonly CarrierPage[]> {
1047
+ async listPages(
1048
+ // The installed browser is one shared instance, not a per-conversation
1049
+ // panel, so ownership does not scope its listing.
1050
+ scope: BrowserSessionWireId,
1051
+ options: { readonly requireRunning?: boolean } = {},
1052
+ ): Promise<readonly CarrierPage[]> {
1053
+ // Looking for a page must never START the human's browser. Before this
1054
+ // check the reference-bar pump called listPages on every tick, whose
1055
+ // ensureClient() launched Edge on its own within seconds of the plugin
1056
+ // loading — measured with no open/navigate call at all.
1057
+ if (options.requireRunning === true && !this.started) return []
1086
1058
  try {
1087
1059
  const client = await this.ensureClient()
1088
1060
  const listed = await client.send('Target.getTargets', {}) as {
@@ -1094,7 +1066,7 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1094
1066
  .filter(entry => !/^edge:\/\/sync-confirmation-dialog(?:\/|$)/.test(entry.url ?? ''))
1095
1067
  .filter(entry => !ours.has(entry.targetId as string))
1096
1068
  .map(entry => ({
1097
- id: entry.targetId as string,
1069
+ id: tabWireId({ ...resolveSessionHandle(scope), tab: `page:${entry.targetId as string}` }),
1098
1070
  url: typeof entry.url === 'string' ? entry.url : '',
1099
1071
  ...typeof entry.title === 'string' && entry.title !== '' ? { title: entry.title } : {},
1100
1072
  }))
@@ -1107,24 +1079,36 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1107
1079
  /**
1108
1080
  * Close one page by the target id {@link listPages} reported.
1109
1081
  *
1110
- * `Target.closeTarget` is the browser's own close, so it works for pages this plugin never
1111
- * created. The page may already be gone if the human closed it in the meantime — the caller
1112
- * asked for it to be closed and it is, so that is not an error.
1082
+ * Only targets created by this owner/session on this connection may be closed.
1113
1083
  * @param id - the CDP target id.
1114
1084
  */
1115
- async closePage(id: string): Promise<void> {
1085
+ async closePage(id: BrowserTabWireId, scope = sessionWireId(readTabHandle(id))): Promise<void> {
1086
+ const identity = resolveTabHandle(resolveSessionHandle(scope), id)
1087
+ const view = this.views.get(id)
1088
+ if (view === undefined && !identity.tab.startsWith('page:')) return
1116
1089
  const client = await this.ensureClient()
1117
- await client.send('Target.closeTarget', { targetId: id }).catch(() => undefined)
1090
+ const targetId = view === undefined ? identity.tab.replace(/^page:/, '') : this.sessions.get(view.session)
1091
+ if (targetId === undefined) throw new Error('dsh-builtin-browser: browser page is stale')
1092
+ const creator = this.createdTargets.get(client)?.get(targetId)
1093
+ if (creator === undefined) throw new Error('dsh-builtin-browser: personal or adopted tabs are detach-only; close the tab in the browser')
1094
+ resolveTabHandle(resolveSessionHandle(scope), creator)
1095
+ const answer = await client.send('Target.closeTarget', { targetId }) as { success?: boolean }
1096
+ if (answer.success !== true) throw new Error('dsh-builtin-browser: browser close was not acknowledged')
1097
+ this.createdTargets.get(client)?.delete(targetId)
1118
1098
  }
1119
1099
 
1120
- createView(): ElectronViewHandle {
1121
- const viewId = randomUUID()
1100
+ createView(identity?: BrowserTabWireId): ElectronViewHandle {
1101
+ const viewId = identity ?? tabWireId({ owner: 'standalone', session: randomUUID(), tab: randomUUID() })
1102
+ readTabHandle(viewId)
1122
1103
  return {
1123
1104
  id: viewId,
1124
1105
  // This is the real browser, not Electron: CDP's JPEG encoder works here, so the
1125
1106
  // provider may pass format and quality through instead of falling back to PNG.
1126
1107
  supportsCdpJpeg: true,
1127
1108
  sendCommand: async (method: string, params?: Record<string, unknown>) => {
1109
+ if (method === 'Browser.close' || method === 'Target.closeTarget' || method === 'Page.close') {
1110
+ throw new Error('dsh-builtin-browser: use explicit tab close; browser-wide and unowned-tab closes are not allowed')
1111
+ }
1128
1112
  // A command that never answered is the only signal that a client has wedged — the
1129
1113
  // socket can stay OPEN while nothing comes back, which is the form the reporter saw with
1130
1114
  // a live, healthy-looking Edge. Dropping the client here means the next call starts a new
@@ -1212,19 +1196,16 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1212
1196
  }
1213
1197
  }
1214
1198
 
1215
- destroyView(handle: ElectronViewHandle): void {
1199
+ destroyView(handle: ElectronViewHandle, _options?: { readonly keepPage?: boolean }): void {
1216
1200
  const cachedView = this.views.get(handle.id)
1217
1201
  this.views.delete(handle.id)
1218
1202
  if (cachedView === undefined) return
1219
1203
  const session = cachedView.session
1220
- // A session id is not a target id: closing the page needs the target the session
1221
- // was attached to, which is why they are tracked separately.
1222
1204
  const targetId = this.sessions.get(session)
1223
1205
  this.sessions.delete(session)
1224
1206
  // Nothing to close if the browser was never started.
1225
1207
  if (targetId !== undefined && this.client !== undefined) {
1226
- // Best-effort: a page that is already gone is not an error.
1227
- void this.client.send('Target.closeTarget', { targetId }).catch(() => undefined)
1208
+ void cachedView.client.send('Target.detachFromTarget', { sessionId: session }).catch(() => undefined)
1228
1209
  }
1229
1210
  }
1230
1211
 
@@ -1272,7 +1253,9 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1272
1253
  * view-level concern and not available to the host.
1273
1254
  */
1274
1255
  async focus(): Promise<void> {
1275
- try { this.child?.kill('SIGCONT') } catch { /* Windows has no SIGCONT; nothing to do */ }
1256
+ if (this.child && await this.ownership.verify(this.child)) {
1257
+ try { this.child.kill('SIGCONT') } catch { /* Windows has no SIGCONT. */ }
1258
+ }
1276
1259
  }
1277
1260
 
1278
1261
 
@@ -1290,13 +1273,19 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1290
1273
  const client = this.client
1291
1274
  this.forgetBrowserState()
1292
1275
  this.client = undefined
1293
- // Ask before killing. `kill()` on Windows is TerminateProcess, which gives the browser no
1294
- // chance to flush its profile — and Chrome records how it ended in that profile, so a
1295
- // hard kill leaves it marked as a crash and the NEXT launch offers to restore a session.
1296
- // That is a visible symptom (an extra window) traced all the way back to this line.
1297
- if (client !== undefined) {
1298
- try { void client.send('Browser.close', {}).catch(() => { /* it is closing, not talking */ }) } catch { /* already gone */ }
1276
+ const disconnect = async (): Promise<void> => {
1277
+ if (!client) return
1278
+ const owner = this.ownedClients.get(client)
1279
+ try {
1280
+ if (owner && await this.ownership.verify(owner)) {
1281
+ const result = await client.send('SystemInfo.getProcessInfo', {}, undefined, 1000) as { processInfo?: { type: string; id: number }[] }
1282
+ if (result.processInfo?.some(entry => entry.type === 'browser' && entry.id === owner.pid)
1283
+ && await this.ownership.verify(owner)) await client.send('Browser.close', {}, undefined, 1000)
1284
+ }
1285
+ } catch { /* An unverified endpoint is detach-only. */ }
1286
+ finally { client.close() }
1299
1287
  }
1288
+ void disconnect()
1300
1289
  // Both the browser we launched and anything that ignored an earlier kill. They hold this
1301
1290
  // profile, so leaving them running means the next launch contends with a browser nobody owns.
1302
1291
  const doomed = [this.child, ...this.stubborn.splice(0)].filter(
@@ -1311,34 +1300,35 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1311
1300
  * ending does not wait for this, and the browser — having been asked to close — generally
1312
1301
  * gets there on its own. If it does not, the kill still lands while the process lives.
1313
1302
  */
1314
- const force = (): void => { try { dying.kill() } catch { /* already gone */ } }
1303
+ const force = (): void => { void this.stopChild(dying) }
1315
1304
  const timer = setTimeout(force, CLOSE_GRACE_MS)
1316
1305
  timer.unref?.()
1317
1306
  dying.once('exit', () => { clearTimeout(timer) })
1318
1307
  }
1319
1308
  const ephemeral = this.ephemeralDir
1320
- if (ephemeral !== undefined) {
1321
- const removeEphemeral = (): void => {
1322
- try { rmSync(ephemeral, { recursive: true, force: true }) } catch { /* best effort */ }
1323
- }
1324
- // `this.child` was cleared above; the saved processes still own the profile until
1325
- // their exit events arrive. Deleting it now races Chromium's final cookie flush.
1326
- const live = doomed.filter(child => child.exitCode === null && child.signalCode === null)
1327
- if (live.length > 0) {
1328
- const remaining = new Set(live)
1329
- for (const child of live) child.once('exit', () => {
1330
- remaining.delete(child)
1331
- if (remaining.size === 0) removeEphemeral()
1332
- })
1333
- } else if (client !== undefined) {
1334
- // A handed-off browser has no process handle. Give its graceful close time to
1335
- // finish; abandoned profiles remain eligible for the next startup's safe sweep.
1336
- setTimeout(() => {
1337
- if (!client.isAlive()) removeEphemeral()
1338
- }, CLOSE_GRACE_MS).unref?.()
1339
- } else {
1340
- removeEphemeral()
1341
- }
1309
+ const cleanup = (): void => {
1310
+ void (async () => {
1311
+ const removeProfile = (): void => {
1312
+ if (ephemeral !== undefined && doomed.length > 0 && doomed.every(child => this.ownership.ownsDirectory(child, ephemeral) && this.ownedChildren.has(child)
1313
+ && (child.exitCode !== null || child.signalCode !== null))) rmSync(ephemeral, { recursive: true, force: true })
1314
+ }
1315
+ if (this.profileLease !== undefined) await this.profileLease.release(removeProfile)
1316
+ else removeProfile()
1317
+ this.profileLease = undefined
1318
+ })().catch(error => process.stderr.write(`[dsh-browser] profile release failed: ${String(error)}\n`))
1319
+ }
1320
+ // Saved processes retain the profile until their exit events arrive.
1321
+ const live = doomed.filter(child => child.exitCode === null && child.signalCode === null)
1322
+ if (live.length > 0) {
1323
+ const remaining = new Set(live)
1324
+ for (const child of live) child.once('exit', () => {
1325
+ remaining.delete(child)
1326
+ if (remaining.size === 0) cleanup()
1327
+ })
1328
+ } else if (client !== undefined) {
1329
+ void client.whenClosed().then(cleanup)
1330
+ } else {
1331
+ cleanup()
1342
1332
  }
1343
1333
  }
1344
1334
 
@@ -1382,10 +1372,11 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1382
1372
  // through the tools. Taking the blank instead makes the page the browser already opened the
1383
1373
  // one the caller gets.
1384
1374
  const adopted = await this.adoptBlankTarget(client)
1385
- const targetId = adopted ?? await this.createTarget(client)
1375
+ const targetId = adopted ?? await this.createTarget(client, viewId)
1386
1376
  const attached = await client.send('Target.attachToTarget', { targetId, flatten: true }) as { sessionId?: string }
1387
1377
  const sessionId = attached?.sessionId
1388
1378
  if (typeof sessionId !== 'string') throw new Error('dsh-builtin-browser: the browser did not attach to the new page')
1379
+ if (adopted !== undefined) this.rememberTarget(client, targetId, viewId)
1389
1380
  // The session id is what page commands ride; the target id is what closes it.
1390
1381
  this.sessions.set(sessionId, targetId)
1391
1382
  this.views.set(viewId, { session: sessionId, client })
@@ -1411,8 +1402,11 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1411
1402
  * @param targetId - the carrier's page id, which for this carrier IS the CDP target id.
1412
1403
  * @returns a handle for that page, in the same shape {@link createView} returns.
1413
1404
  */
1414
- async adoptPage(targetId: string): Promise<ElectronViewHandle> {
1415
- const handle = this.createView()
1405
+ async adoptPage(identity: BrowserTabWireId, scope = sessionWireId(readTabHandle(identity))): Promise<ElectronViewHandle> {
1406
+ const tab = resolveTabHandle(resolveSessionHandle(scope), identity).tab
1407
+ if (!tab.startsWith('page:')) throw new Error('dsh-builtin-browser: invalid carrier page handle')
1408
+ const targetId = tab.slice('page:'.length)
1409
+ const handle = this.createView(identity)
1416
1410
  const client = await this.ensureClient()
1417
1411
  const attached = await client.send('Target.attachToTarget', { targetId, flatten: true }) as { sessionId?: string }
1418
1412
  const sessionId = attached?.sessionId
@@ -1430,89 +1424,41 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1430
1424
  * Take an unclaimed blank page, if the browser has one to spare.
1431
1425
  *
1432
1426
  * "Unclaimed" is what matters: a blank page the plugin is already driving belongs to a view, and
1433
- * handing the same target to a second view would make two views share one page. The page kept by
1434
- * {@link normalizeBlankPages} is exactly the unclaimed one this is looking for.
1427
+ * handing the same target to a second view would make two views share one page.
1435
1428
  * @param client - the connected browser.
1436
1429
  * @returns the target id to reuse, or undefined when a new page has to be created.
1437
1430
  */
1438
1431
  private async adoptBlankTarget(client: CdpClient): Promise<string | undefined> {
1439
- try {
1440
- const listed = await client.send('Target.getTargets', {}) as {
1441
- targetInfos?: Array<{ targetId?: string; type?: string; url?: string }>
1442
- }
1443
- const claimed = new Set(this.sessions.values())
1444
- for (const entry of listed?.targetInfos ?? []) {
1445
- if (entry.type !== 'page' || typeof entry.targetId !== 'string') continue
1446
- if (!isBlankUrl(entry.url)) continue
1447
- if (claimed.has(entry.targetId)) continue
1448
- return entry.targetId
1449
- }
1450
- return undefined
1451
- } catch {
1452
- // Discovery is best-effort; creating a page is the behaviour this replaced.
1453
- return undefined
1432
+ const listed = await client.send('Target.getTargets', {}) as {
1433
+ targetInfos?: Array<{ targetId?: string; type?: string; url?: string }>
1454
1434
  }
1435
+ if (!Array.isArray(listed?.targetInfos)) throw new Error('dsh-builtin-browser: the browser did not acknowledge its target inventory')
1436
+ const claimed = new Set(this.sessions.values())
1437
+ for (const entry of listed.targetInfos) {
1438
+ if (entry.type !== 'page' || typeof entry.targetId !== 'string') continue
1439
+ if (!isBlankUrl(entry.url)) continue
1440
+ if (claimed.has(entry.targetId)) continue
1441
+ return entry.targetId
1442
+ }
1443
+ return undefined
1455
1444
  }
1456
1445
 
1457
1446
  /** Create one page, refusing to go on without an id. */
1458
- private async createTarget(client: CdpClient): Promise<string> {
1447
+ private async createTarget(client: CdpClient, viewId: string): Promise<string> {
1459
1448
  const created = await client.send('Target.createTarget', {
1460
1449
  url: 'about:blank',
1461
1450
  ...this.isQuiet() ? { background: true } : {},
1462
1451
  }) as { targetId?: string }
1463
1452
  const targetId = created?.targetId
1464
- if (typeof targetId !== 'string') throw new Error('dsh-builtin-browser: the browser did not create a page')
1453
+ if (typeof targetId !== 'string' || targetId === '') throw new Error('dsh-builtin-browser: the browser did not create a page')
1454
+ this.rememberTarget(client, targetId, viewId)
1465
1455
  return targetId
1466
1456
  }
1467
1457
 
1468
- /**
1469
- * Collapse the blank pages a freshly started browser comes with down to one.
1470
- *
1471
- * Chrome opens more than one page when it is given a URL on top of its own start page, and this
1472
- * is the browser's behaviour rather than a session restore: measured on a cleanly exited profile
1473
- * as well as a crashed one, both pages appear within a second of launch. There is nothing to
1474
- * configure away — by the time a client can talk to the browser, both already exist.
1475
- *
1476
- * Left alone the surplus page is invisible to the plugin's tab model and therefore unclosable
1477
- * through the tools, so it survives every navigation and accumulates for as long as the window
1478
- * lives. One is kept deliberately: {@link buildSession} adopts it instead of creating a third.
1479
- *
1480
- * `Target.setDiscoverTargets` has to come first. Without it the browser may omit pages that
1481
- * existed before this client connected — which is precisely the page that needs closing, and the
1482
- * reason the first attempt at this fix failed silently.
1483
- * @param client - the connected browser.
1484
- * @returns how many surplus blank pages were closed.
1485
- */
1486
- private async normalizeBlankPages(client: CdpClient): Promise<number> {
1487
- try {
1488
- await client.send('Target.setDiscoverTargets', { discover: true })
1489
- const listed = await client.send('Target.getTargets', {}) as {
1490
- targetInfos?: Array<{ targetId?: string; type?: string; url?: string }>
1491
- }
1492
- const blanks = (listed?.targetInfos ?? []).filter(
1493
- entry => entry.type === 'page' && typeof entry.targetId === 'string' && isBlankUrl(entry.url),
1494
- )
1495
- const claimed = new Set(this.sessions.values())
1496
- let closed = 0
1497
- // Keep the first unclaimed blank (that is the one buildSession will adopt) and close the rest.
1498
- let kept = false
1499
- for (const entry of blanks) {
1500
- const targetId = entry.targetId as string
1501
- if (claimed.has(targetId)) continue
1502
- if (!kept) { kept = true; continue }
1503
- try {
1504
- await client.send('Target.closeTarget', { targetId })
1505
- closed += 1
1506
- } catch {
1507
- // It may already be gone; one failure must not stop the rest.
1508
- }
1509
- }
1510
- return closed
1511
- } catch {
1512
- // A browser that will not answer Target commands has a real problem, and the next command
1513
- // will report it. Turning a tidy-up into a functional error here would hide that.
1514
- return 0
1515
- }
1458
+ private rememberTarget(client: CdpClient, targetId: string, viewId: string): void {
1459
+ let targets = this.createdTargets.get(client)
1460
+ if (!targets) { targets = new Map(); this.createdTargets.set(client, targets) }
1461
+ targets.set(targetId, viewId as BrowserTabWireId)
1516
1462
  }
1517
1463
 
1518
1464
  /** Views whose session is being created right now, so a second caller waits for the first. */
@@ -1524,3 +1470,28 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1524
1470
  /** sessionId -> targetId, so a destroyed view can close the right page. */
1525
1471
  private readonly sessions = new Map<string, string>()
1526
1472
  }
1473
+
1474
+ /**
1475
+ * Probe for a browser the human already has open with a debugging port.
1476
+ *
1477
+ * Chromium exposes CDP only when it was STARTED with --remote-debugging-port, so an already-running Edge
1478
+ * cannot be attached unless it was launched that way. Attaching is therefore opt-in: this probe answers
1479
+ * "is there something to attach to right now", and the caller decides whether to use it.
1480
+ * @param port - the debugging port to try (default 9222).
1481
+ * @param timeoutMs - how long to wait for the endpoint.
1482
+ * @returns the browser banner when an endpoint answers, undefined otherwise.
1483
+ */
1484
+ export async function probeAttach(port: number = CDP_DEFAULT_ATTACH_PORT, timeoutMs: number = CDP_ATTACH_PROBE_TIMEOUT_MS): Promise<string | undefined> {
1485
+ const controller = new AbortController()
1486
+ const timer = setTimeout(() => { controller.abort() }, timeoutMs)
1487
+ try {
1488
+ const response = await fetch(cdpVersionUrl(port), { signal: controller.signal })
1489
+ if (!response.ok) return undefined
1490
+ const body = await response.json() as { Browser?: unknown }
1491
+ return typeof body.Browser === 'string' ? body.Browser : 'unknown'
1492
+ } catch {
1493
+ return undefined
1494
+ } finally {
1495
+ clearTimeout(timer)
1496
+ }
1497
+ }