dsh-builtin-browser 1.0.1 → 1.0.3

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 (360) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/assets/browser-panel-locales.mjs +37 -5
  4. package/assets/browser-policy.d.mts +29 -0
  5. package/assets/browser-policy.mjs +40 -0
  6. package/desktop-bridge/desktop-discovery.d.mts +1 -1
  7. package/desktop-bridge/desktop-discovery.mjs +59 -9
  8. package/desktop-bridge/desktop-identity.json +12 -0
  9. package/desktop-bridge/install.mjs +14 -7
  10. package/desktop-bridge/plugin-browser-bridge.js +19 -7
  11. package/docs/acceptance-2026-11-27.md +67 -0
  12. package/docs/architecture.md +1 -1
  13. package/docs/development.md +33 -4
  14. package/docs/dsh-0.2.3-host-patch-task.md +34 -0
  15. package/docs/hardcoding-audit.md +28 -8
  16. package/docs/known-issues.md +26 -0
  17. package/docs/limitations.md +6 -2
  18. package/docs/tool-reference.md +1 -1
  19. package/docs/v1.1.0-bu-data-batching-task.md +66 -0
  20. package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
  21. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  22. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  23. package/dsh-host-patch/README.md +4 -0
  24. package/dsh-host-patch/apply.mjs +61 -13
  25. package/dsh-host-patch/rc3-revision9.json.gz +0 -0
  26. package/dsh-host-patch/rc5-revision9.json.gz +0 -0
  27. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  28. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  29. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  30. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  31. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  32. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  33. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  34. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  35. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  36. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  37. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  38. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  39. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  40. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  41. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  42. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  43. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  44. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  45. package/dsh-host-patch/sources/manifest.json +218 -0
  46. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  47. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  48. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  49. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  50. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  51. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  52. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  53. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  54. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  55. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  56. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  57. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  58. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  59. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  60. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  61. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  62. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  63. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  64. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  65. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  66. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  67. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  68. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  69. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  70. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  71. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  72. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  73. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  74. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  75. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  76. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  77. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  78. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  79. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  80. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  81. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  82. package/dsh-host-patch/sources/series.json +260 -0
  83. package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
  84. package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
  85. package/dsh-host-patch/tauri-revision1.json +39 -0
  86. package/dsh-host-patch/tauri.json +43 -0
  87. package/dsh-host-patch/v023-alpha2.json +153 -0
  88. package/lib/browser/anti-bot.js +215 -0
  89. package/lib/browser/deep-dom.js +39 -0
  90. package/lib/browser/runtime.js +15 -0
  91. package/lib/browser/takeover-target.js +13 -6
  92. package/lib/browser/types.js +30 -1
  93. package/lib/browser-electron/authenticated-route.js +16 -2
  94. package/lib/browser-electron/automatic-maintenance.js +16 -10
  95. package/lib/browser-electron/bridge-connection.js +3 -8
  96. package/lib/browser-electron/bridge-install.js +2 -1
  97. package/lib/browser-electron/bridge-status.js +55 -26
  98. package/lib/browser-electron/desktop-bridge-host.js +7 -6
  99. package/lib/browser-electron/desktop-identity.js +28 -5
  100. package/lib/browser-electron/desktop-shell.js +64 -0
  101. package/lib/browser-electron/electron-provision.js +105 -18
  102. package/lib/browser-electron/entry.js +129 -44
  103. package/lib/browser-electron/extension-browser.js +4 -4
  104. package/lib/browser-electron/foreground-watch.js +134 -0
  105. package/lib/browser-electron/guest-cookie-jar.js +13 -13
  106. package/lib/browser-electron/guest-route.js +181 -32
  107. package/lib/browser-electron/guest-runtime.js +61 -10
  108. package/lib/browser-electron/guest-storage.js +2 -2
  109. package/lib/browser-electron/history-store.js +1 -5
  110. package/lib/browser-electron/host-main.js +8 -4
  111. package/lib/browser-electron/host-patch-maintenance.js +14 -8
  112. package/lib/browser-electron/maintenance-route.js +2 -1
  113. package/lib/browser-electron/missing-system-browser.js +5 -9
  114. package/lib/browser-electron/preferred-browser.js +7 -3
  115. package/lib/browser-electron/preview-route.js +9 -13
  116. package/lib/browser-electron/process-ownership.js +1 -1
  117. package/lib/browser-electron/profile-command.js +2 -1
  118. package/lib/browser-electron/profile-extension.js +5 -0
  119. package/lib/browser-electron/profile-lease.js +152 -47
  120. package/lib/browser-electron/provider-core.js +527 -0
  121. package/lib/browser-electron/provider-interaction.js +963 -0
  122. package/lib/browser-electron/provider-media.js +518 -0
  123. package/lib/browser-electron/provider-navigation.js +301 -0
  124. package/lib/browser-electron/provider-observation.js +623 -0
  125. package/lib/browser-electron/provider-tabs.js +372 -0
  126. package/lib/browser-electron/provider.js +150 -3301
  127. package/lib/browser-electron/reference-route.js +9 -18
  128. package/lib/browser-electron/remote-host.js +79 -34
  129. package/lib/browser-electron/runtime-status.js +56 -6
  130. package/lib/browser-electron/settings-store.js +3 -6
  131. package/lib/browser-electron/sidebar-only-host.js +1 -1
  132. package/lib/browser-electron/system-browser.js +539 -172
  133. package/lib/browser-electron/tauri-host.js +208 -0
  134. package/lib/browser-electron/virtual-cursor.js +23 -13
  135. package/lib/browser-reference/service.js +22 -4
  136. package/lib/browser-reference/web-sources.js +1 -1
  137. package/lib/client.js +43409 -0
  138. package/lib/compat/host-features.js +75 -0
  139. package/lib/reference-source.js +1 -1
  140. package/lib/reference-text.js +23 -1
  141. package/lib/takeover-protocol.js +1 -1
  142. package/lib/tool-browser/block-recovery.js +69 -0
  143. package/lib/tool-browser/code-tool.js +170 -19
  144. package/lib/tool-browser/code-worker.js +115 -20
  145. package/lib/tool-browser/errors.js +34 -0
  146. package/lib/tool-browser/index.js +66 -3593
  147. package/lib/tool-browser/page-probe.js +227 -28
  148. package/lib/tool-browser/panel-page.js +2 -1
  149. package/lib/tool-browser/probe-client.js +157 -0
  150. package/lib/tool-browser/screenshot-annotations.js +108 -0
  151. package/lib/tool-browser/state.js +337 -0
  152. package/lib/tool-browser/takeover.js +1 -1
  153. package/lib/tool-browser/tools-debug.js +862 -0
  154. package/lib/tool-browser/tools-interaction.js +993 -0
  155. package/lib/tool-browser/tools-navigation.js +807 -0
  156. package/lib/tool-browser/tools-observation.js +461 -0
  157. package/lib/tool-browser/tools-reference.js +293 -0
  158. package/lib/web-guest.js +1 -0
  159. package/package.json +15 -53
  160. package/README.en.md +0 -89
  161. package/browser-extension/constants.mjs +0 -20
  162. package/browser-extension/controller.mjs +0 -293
  163. package/browser-extension/locales.mjs +0 -15
  164. package/browser-extension/manifest.json +0 -12
  165. package/browser-extension/options.html +0 -14
  166. package/browser-extension/options.mjs +0 -9
  167. package/browser-extension/permission-guard.mjs +0 -13
  168. package/browser-extension/worker.mjs +0 -74
  169. package/dist/client.cjs +0 -43167
  170. package/lib/browser-reference/submission-receipts.js +0 -139
  171. package/scripts/build.mjs +0 -66
  172. package/scripts/bundle-host.mjs +0 -28
  173. package/scripts/fix-exports.mjs +0 -50
  174. package/scripts/install-electron.mjs +0 -51
  175. package/scripts/verify-exports.mjs +0 -47
  176. package/scripts/verify-preview-sdk.mjs +0 -93
  177. package/skills/dsh-builtin-browser/SKILL.md +0 -73
  178. package/skills/dsh-builtin-browser/references/batch.md +0 -53
  179. package/skills/dsh-builtin-browser/references/deliver.md +0 -31
  180. package/skills/dsh-builtin-browser/references/locate.md +0 -11
  181. package/skills/dsh-builtin-browser/references/recover.md +0 -11
  182. package/skills/dsh-builtin-browser/references/verify.md +0 -13
  183. package/skills/dsh-debug-host/SKILL.md +0 -56
  184. package/skills/dsh-debug-self/SKILL.md +0 -50
  185. package/src/bridge-compatibility.ts +0 -39
  186. package/src/browser/handles.ts +0 -89
  187. package/src/browser/runtime.ts +0 -560
  188. package/src/browser/takeover-target.ts +0 -36
  189. package/src/browser/types.ts +0 -817
  190. package/src/browser-electron/authenticated-route.ts +0 -84
  191. package/src/browser-electron/automatic-maintenance.ts +0 -726
  192. package/src/browser-electron/bridge-auto.ts +0 -159
  193. package/src/browser-electron/bridge-connection.ts +0 -385
  194. package/src/browser-electron/bridge-endpoint.ts +0 -129
  195. package/src/browser-electron/bridge-install.ts +0 -289
  196. package/src/browser-electron/bridge-maintenance.ts +0 -189
  197. package/src/browser-electron/bridge-status.ts +0 -347
  198. package/src/browser-electron/desktop-bridge-host.ts +0 -251
  199. package/src/browser-electron/desktop-identity.ts +0 -320
  200. package/src/browser-electron/document-readiness.ts +0 -45
  201. package/src/browser-electron/electron-provision.ts +0 -261
  202. package/src/browser-electron/entry.ts +0 -1299
  203. package/src/browser-electron/ephemeral-profile.ts +0 -189
  204. package/src/browser-electron/extension-browser.ts +0 -223
  205. package/src/browser-electron/extension-setup.ts +0 -67
  206. package/src/browser-electron/file-write.ts +0 -31
  207. package/src/browser-electron/guest-cookie-jar.ts +0 -176
  208. package/src/browser-electron/guest-cookie-store.ts +0 -59
  209. package/src/browser-electron/guest-css-runtime.ts +0 -76
  210. package/src/browser-electron/guest-css.ts +0 -68
  211. package/src/browser-electron/guest-route.ts +0 -568
  212. package/src/browser-electron/guest-runtime.ts +0 -357
  213. package/src/browser-electron/guest-storage-runtime.ts +0 -54
  214. package/src/browser-electron/guest-storage.ts +0 -117
  215. package/src/browser-electron/history-store.ts +0 -227
  216. package/src/browser-electron/host-main.ts +0 -1381
  217. package/src/browser-electron/host-patch-maintenance.ts +0 -112
  218. package/src/browser-electron/http-body.ts +0 -65
  219. package/src/browser-electron/json-reply.ts +0 -47
  220. package/src/browser-electron/maintenance-broker.ts +0 -166
  221. package/src/browser-electron/maintenance-lifecycle.ts +0 -91
  222. package/src/browser-electron/maintenance-route.ts +0 -67
  223. package/src/browser-electron/missing-system-browser.ts +0 -113
  224. package/src/browser-electron/open-slot.ts +0 -49
  225. package/src/browser-electron/paths.ts +0 -25
  226. package/src/browser-electron/preferred-browser.ts +0 -120
  227. package/src/browser-electron/preview-route.ts +0 -218
  228. package/src/browser-electron/process-ownership.ts +0 -168
  229. package/src/browser-electron/process.ts +0 -23
  230. package/src/browser-electron/profile-checkpoint.ts +0 -187
  231. package/src/browser-electron/profile-command.ts +0 -46
  232. package/src/browser-electron/profile-extension.ts +0 -124
  233. package/src/browser-electron/profile-lease.ts +0 -115
  234. package/src/browser-electron/profile-residue.ts +0 -49
  235. package/src/browser-electron/provider.ts +0 -4571
  236. package/src/browser-electron/reference-route.ts +0 -608
  237. package/src/browser-electron/remote-host.ts +0 -1462
  238. package/src/browser-electron/rpc-input.ts +0 -13
  239. package/src/browser-electron/rpc-ops.ts +0 -41
  240. package/src/browser-electron/runtime-diagnostics.ts +0 -38
  241. package/src/browser-electron/runtime-route.ts +0 -105
  242. package/src/browser-electron/runtime-status.ts +0 -242
  243. package/src/browser-electron/settings-route.ts +0 -64
  244. package/src/browser-electron/settings-store.ts +0 -589
  245. package/src/browser-electron/shortcuts-route.ts +0 -112
  246. package/src/browser-electron/sidebar-only-host.ts +0 -298
  247. package/src/browser-electron/startpage-shortcuts.ts +0 -213
  248. package/src/browser-electron/system-browser.ts +0 -1497
  249. package/src/browser-electron/timing.ts +0 -16
  250. package/src/browser-electron/virtual-cursor.ts +0 -152
  251. package/src/browser-electron/windows-system.ts +0 -24
  252. package/src/browser-reference/delivery.ts +0 -384
  253. package/src/browser-reference/entry.ts +0 -631
  254. package/src/browser-reference/export.ts +0 -339
  255. package/src/browser-reference/import.ts +0 -303
  256. package/src/browser-reference/page-script.ts +0 -1537
  257. package/src/browser-reference/service.ts +0 -1315
  258. package/src/browser-reference/store.ts +0 -172
  259. package/src/browser-reference/submission-receipts.ts +0 -122
  260. package/src/browser-reference/text-quote.ts +0 -219
  261. package/src/browser-reference/types.ts +0 -195
  262. package/src/browser-reference/visible.ts +0 -367
  263. package/src/browser-reference/web-sources.ts +0 -103
  264. package/src/client/browser/BrowserController.ts +0 -693
  265. package/src/client/browser/BrowserFrame.ts +0 -78
  266. package/src/client/browser/BrowserNavigation.ts +0 -169
  267. package/src/client/browser/BrowserPage.ts +0 -23
  268. package/src/client/browser/BrowserPersistence.ts +0 -44
  269. package/src/client/browser/IframeImpl.ts +0 -176
  270. package/src/client/browser/child-tabs.ts +0 -14
  271. package/src/client/browser/iframe-reference.ts +0 -67
  272. package/src/client/browser/initialization.ts +0 -262
  273. package/src/client/browser/omnibox.ts +0 -243
  274. package/src/client/browser/store.ts +0 -38
  275. package/src/client/browser/takeover-channel.ts +0 -72
  276. package/src/client/browser/url.ts +0 -46
  277. package/src/client/browser/web-reference-source.ts +0 -52
  278. package/src/client/css-modules.d.ts +0 -4
  279. package/src/client/definition.tsx +0 -30
  280. package/src/client/electron/ElectronWebViewImpl.ts +0 -364
  281. package/src/client/electron/ElectronWebviewPresentation.ts +0 -138
  282. package/src/client/electron/NativeChildPresentation.ts +0 -45
  283. package/src/client/electron/NativeViewPage.ts +0 -251
  284. package/src/client/electron/pages.ts +0 -23
  285. package/src/client/electron/reference-overlay.ts +0 -53
  286. package/src/client/electron/workspace.ts +0 -33
  287. package/src/client/index.ts +0 -293
  288. package/src/client/locales.ts +0 -857
  289. package/src/client/pages.ts +0 -28
  290. package/src/client/reference/client/BrowserRefLink.tsx +0 -142
  291. package/src/client/reference/client/draft-reference.ts +0 -167
  292. package/src/client/reference/client/index.ts +0 -7
  293. package/src/client/reference/client/ordered-submission.ts +0 -108
  294. package/src/client/reference/client/pending-delivery.ts +0 -216
  295. package/src/client/reference/client/plugin.ts +0 -189
  296. package/src/client/reference/client/production/ReferenceCapsules.tsx +0 -345
  297. package/src/client/reference/client/production/ReferenceDock.module.css +0 -193
  298. package/src/client/reference/client/production/ReferenceDock.tsx +0 -6
  299. package/src/client/reference/client/production/ReferenceFeedback.tsx +0 -15
  300. package/src/client/reference/client/production/ReferenceMath.tsx +0 -44
  301. package/src/client/reference/client/production/ReferenceText.tsx +0 -36
  302. package/src/client/reference/client/production/assembly.ts +0 -471
  303. package/src/client/reference/client/production/asset-store.ts +0 -144
  304. package/src/client/reference/client/production/availability.ts +0 -74
  305. package/src/client/reference/client/production/bytes.ts +0 -36
  306. package/src/client/reference/client/production/delivery-client.ts +0 -211
  307. package/src/client/reference/client/production/draft-adapter.ts +0 -508
  308. package/src/client/reference/client/production/http-transport.ts +0 -217
  309. package/src/client/reference/client/production/production-submission.ts +0 -310
  310. package/src/client/reference/client/production/protocol.ts +0 -231
  311. package/src/client/reference/client/production/reference-card.ts +0 -240
  312. package/src/client/reference/client/production/reference-labels.ts +0 -29
  313. package/src/client/reference/client/production/reply-link-bridge.ts +0 -222
  314. package/src/client/reference/client/production/reveal.ts +0 -215
  315. package/src/client/reference/client/production/runtime.ts +0 -1101
  316. package/src/client/reference/client/production/snapshot-adapter.ts +0 -154
  317. package/src/client/reference/client/production/source-marker.ts +0 -63
  318. package/src/client/reference/client/production/source-opener.ts +0 -55
  319. package/src/client/reference/client/production/styles.ts +0 -104
  320. package/src/client/reference/client/production/user-text-rule.ts +0 -58
  321. package/src/client/reference/client/reveal.ts +0 -107
  322. package/src/client/reference/client/scheme.ts +0 -114
  323. package/src/client/reference/client/types.ts +0 -168
  324. package/src/client/reference/css-modules.d.ts +0 -4
  325. package/src/client/reference/index.ts +0 -11
  326. package/src/client/reference-capture-owner.ts +0 -162
  327. package/src/client/reference-intents.ts +0 -36
  328. package/src/client/settings/index.ts +0 -34
  329. package/src/client/settings/panel.ts +0 -2657
  330. package/src/client/shortcut-open.ts +0 -30
  331. package/src/client/startpage/binding.ts +0 -99
  332. package/src/client/startpage/controller.ts +0 -303
  333. package/src/client/startpage/model.ts +0 -279
  334. package/src/client/view/Browser.module.css +0 -751
  335. package/src/client/view/BrowserBody.tsx +0 -314
  336. package/src/client/view/BrowserPresentation.ts +0 -9
  337. package/src/client/view/BrowserTitle.tsx +0 -17
  338. package/src/client/view/IframePresentation.ts +0 -344
  339. package/src/client/view/StartPage.tsx +0 -597
  340. package/src/client/view/TakeoverBanner.tsx +0 -21
  341. package/src/index.ts +0 -110
  342. package/src/reference-owner.ts +0 -5
  343. package/src/reference-page.ts +0 -9
  344. package/src/reference-source.ts +0 -3
  345. package/src/reference-text.ts +0 -197
  346. package/src/startpage-settings.ts +0 -103
  347. package/src/startpage.ts +0 -71
  348. package/src/takeover-protocol.ts +0 -19
  349. package/src/tool-browser/code-tool.ts +0 -401
  350. package/src/tool-browser/code-worker.ts +0 -639
  351. package/src/tool-browser/element-fields.ts +0 -167
  352. package/src/tool-browser/index.ts +0 -3733
  353. package/src/tool-browser/page-probe.ts +0 -474
  354. package/src/tool-browser/panel-page.ts +0 -124
  355. package/src/tool-browser/screenshot-image.ts +0 -49
  356. package/src/tool-browser/takeover.ts +0 -198
  357. package/src/types/electron-shim.d.ts +0 -144
  358. package/src/types.ts +0 -85
  359. package/src/web-guest.ts +0 -34
  360. package/tools/accept-desktop.mjs +0 -148
@@ -1,1497 +0,0 @@
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'
3
- /**
4
- * Drive the browser the user already has (Chrome / Edge / any Chromium) instead of
5
- * the Electron we ship — the same approach Codex Browser Use takes.
6
- *
7
- * WHY
8
- * The bundled Electron is a private copy with its own profile, so it can never see
9
- * the logins the user already has in Chrome, and on a managed machine the user may
10
- * simply prefer their own browser. Launching their browser with a *separate*
11
- * `--user-data-dir` gives us a real Chromium we can drive over CDP without touching
12
- * their everyday profile, bookmarks or windows: nothing of theirs is opened, locked
13
- * or modified, and closing us never closes them.
14
- *
15
- * HOW
16
- * Chromium exposes CDP on `--remote-debugging-port=0`, and writes the port it chose
17
- * into `<profile>/DevToolsActivePort`. That file is the discovery mechanism — no
18
- * port guessing, no collisions. From there everything is CDP over one WebSocket:
19
- * `Target.createTarget` makes a page, `Target.attachToTarget` (flattened) gives a
20
- * session for it, and the plugin's commands ride that session. Node 22 ships a global
21
- * `WebSocket`, so this needs no dependency at all.
22
- *
23
- * WHAT IT IMPLEMENTS
24
- * The same `ElectronBrowserViewHost` seam as the self-hosted and sidebar hosts, so
25
- * the provider, the tools, history, the cursor and teardown rules are unchanged —
26
- * only the carrier differs.
27
- * @module dsh-browser/browser-electron/system-browser
28
- */
29
-
30
- import { readFileSync, rmSync, statSync } from 'node:fs'
31
- import { existsSync } from 'node:fs'
32
- import { join } from 'node:path'
33
- import { acquireProfileLease, type ProfileLease } from './profile-lease.ts'
34
- import { BrowserProcessOwnership, type ProcessOwnershipOptions } from './process-ownership.ts'
35
- // Type-only: settings-store imports BrowserChannel from here, so a value import would be a cycle.
36
- // `hasDisplay` lives here instead of there for the same reason — it is a runtime function.
37
- import type { HeadlessMode } from './settings-store.ts'
38
-
39
- /**
40
- * How long a killed browser is given to actually exit before the launch proceeds.
41
- *
42
- * `kill()` only sends the signal — on Windows it is TerminateProcess, which is asynchronous —
43
- * and the browser may hold this profile's singleton lock for a while afterwards. Spawning
44
- * immediately meant the replacement saw a live instance, handed its command line over and
45
- * exited, and that exit was reported as a bad browser path.
46
- */
47
- const EXIT_GRACE_MS = 3_000
48
- /**
49
- * How long a browser is given to close itself after being asked, before it is killed.
50
- *
51
- * Long enough for Chrome to flush its profile, which is what keeps the next launch from reading
52
- * the profile as crashed and offering a session restore. Deliberately not the same knob as
53
- * {@link EXIT_GRACE_MS}: that one waits for a browser to die because a NEW one cannot start until
54
- * it does, this one merely prefers a graceful exit to a kill.
55
- */
56
- const CLOSE_GRACE_MS = 6_000
57
-
58
- /**
59
- * Ceiling on one attempt to ask a discovered CDP port who it is.
60
- *
61
- * The launch loop below polls: it reads `DevToolsActivePort`, tries `/json/version` on the port
62
- * inside it, and waits 250 ms between attempts under a 30 s deadline. An unbounded fetch can
63
- * park inside one iteration for the whole budget, so a bound is needed — but it has to be
64
- * small enough that the loop still behaves like a loop.
65
- *
66
- * The usual case is NOT a slow answer, it is NO answer: a browser that has written the file but
67
- * is not listening yet refuses the connection instantly, and that immediacy is what lets the
68
- * loop spin. Any timeout added here is paid on every iteration in which the port is not ready,
69
- * so an earlier attempt at this used 2000 ms — eight times the poll interval — and cut the
70
- * attempts available in the budget from roughly 120 to 15. This value is the same size as the
71
- * interval, so a worst-case iteration costs 500 ms and the budget still affords ~60 attempts.
72
- */
73
- const PORT_PROBE_MS = 250
74
-
75
- /**
76
- * Starts a browser process and returns a handle to it.
77
- *
78
- * Injectable so tests can supply something that speaks CDP — the seam a recovery test needs
79
- * and could not have while the launch was hardcoded to a stub that rejects Chromium's args.
80
- * @param path - the executable to run.
81
- * @param args - its arguments.
82
- * @returns the child process.
83
- */
84
- export type BrowserLauncher = (path: string, args: readonly string[]) => ReturnType<typeof spawn>
85
-
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. */
103
- const defaultLauncher: BrowserLauncher = (path, args) =>
104
- spawn(path, [...args], { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: false })
105
- import { spawn, type ChildProcess } from 'node:child_process'
106
- import { randomUUID } from 'node:crypto'
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'
110
-
111
- /** Which browser the user asked for. */
112
- export type BrowserChannel = 'bundled' | 'chrome' | 'edge' | 'auto' | 'sidebar'
113
-
114
- /** A resolved browser installation. */
115
- export interface DetectedBrowser {
116
- /** Which product this is. */
117
- readonly kind: 'chrome' | 'edge' | 'brave'
118
- /** Absolute path to the executable. */
119
- readonly path: string
120
- }
121
-
122
- /**
123
- * Whether a browser's self-reported product name is one this carrier could have launched.
124
- *
125
- * `edg`, not `edge`: Edge reports itself as `Edg/155.0.4283.45`, both over HTTP and over the
126
- * protocol. Testing for the full word rejected a live Edge that had just been started, so the
127
- * call failed with the hand-off error this check was added to prevent — while the browser was
128
- * running the whole time, answering on its own port.
129
- * @param product - the product string a browser reports about itself.
130
- */
131
- function isBrowserProduct(product: unknown): boolean {
132
- return typeof product === 'string' && /chrome|chromium|edg/i.test(product)
133
- }
134
-
135
- /**
136
- * Whether this process has somewhere to draw a window.
137
- *
138
- * The same test Chromium makes: with neither `DISPLAY` nor `WAYLAND_DISPLAY` set it cannot open a
139
- * window and exits with "could not connect to display". Declared here rather than in
140
- * settings-store because that module imports from this one, and a value import back would be a
141
- * cycle; the equivalent export there delegates to this.
142
- * @param env - the environment to inspect; defaults to the current process.
143
- * @returns true when a display is advertised.
144
- */
145
- function hasDisplay(env: NodeJS.ProcessEnv = process.env): boolean {
146
- // Windows and macOS use neither variable, and always have a window server.
147
- if (process.platform === 'win32' || process.platform === 'darwin') return true
148
- return (env.DISPLAY ?? '') !== '' || (env.WAYLAND_DISPLAY ?? '') !== ''
149
- }
150
-
151
- /**
152
- * Resolve `auto` into a concrete decision, and say why.
153
- *
154
- * Chromium refuses to start without a display: with neither `DISPLAY` nor `WAYLAND_DISPLAY` set it
155
- * exits at once with "could not connect to display", and the caller sees only "exited immediately
156
- * after launch (exit code 1)". That is the ordinary state of a systemd service, a container, and an
157
- * SSH-only server — the deployment where a server-side browser is most useful, and the one reported
158
- * as issue #32: every `dsh_browser_*` call failed, with nothing in the message pointing at the
159
- * display.
160
- *
161
- * `auto` therefore launches headless exactly when there is no display, which leaves desktop and
162
- * sidebar users with the visible window they expect. An environment override wins over the setting
163
- * so an operator can fix a running deployment without editing settings: `DSH_BROWSER_HEADLESS=1`
164
- * forces headless, `=0` forces a window.
165
- * @param mode - the configured mode.
166
- * @param env - the environment to inspect; defaults to the current process.
167
- * @returns whether to launch headless, and a one-line reason for the log.
168
- */
169
- function resolveLaunchMode(
170
- mode: HeadlessMode,
171
- env: NodeJS.ProcessEnv = process.env,
172
- ): { readonly headless: boolean; readonly why: string } {
173
- const override = env.DSH_BROWSER_HEADLESS
174
- if (override === '1' || override === 'true') return { headless: true, why: 'DSH_BROWSER_HEADLESS' }
175
- if (override === '0' || override === 'false') return { headless: false, why: 'DSH_BROWSER_HEADLESS' }
176
- if (mode === 'headless') return { headless: true, why: 'browser.headless = headless' }
177
- if (mode === 'windowed') return { headless: false, why: 'browser.headless = windowed' }
178
- const display = hasDisplay(env)
179
- return display
180
- ? { headless: false, why: 'a display is available' }
181
- : { headless: true, why: 'no DISPLAY or WAYLAND_DISPLAY' }
182
- }
183
-
184
- /**
185
- * Whether a target URL is one of the blanks a browser opens by itself.
186
- *
187
- * Deliberately narrow: `about:blank` and Chrome's own new-tab pages, and nothing else. A wider
188
- * test ("has no path", "starts with chrome://") would sooner or later match a page the user is
189
- * reading, and the caller closes what this returns.
190
- * @param url - the target's reported URL.
191
- */
192
- function isBlankUrl(url: unknown): boolean {
193
- if (typeof url !== 'string') return false
194
- return url === 'about:blank'
195
- || url.startsWith('chrome://newtab')
196
- || url.startsWith('chrome://new-tab-page')
197
- }
198
-
199
- function expandLocation(location: string, env: NodeJS.ProcessEnv): string {
200
- return location.replace(/%([^%]+)%/g, (whole, name: string) =>
201
- env[name] ?? env[name.toUpperCase()] ?? env[name.toLowerCase()] ?? whole)
202
- }
203
-
204
- /**
205
- * Find an executable by name on PATH.
206
- *
207
- * PATH is read from the supplied environment rather than the process's own, so the
208
- * detection stays testable. On Windows a bare name needs its extension; elsewhere
209
- * the launcher is the file itself.
210
- * @param names - candidate launcher names, in preference order.
211
- * @param env - the environment to read PATH from.
212
- * @param platform - the platform whose PATH and extension conventions apply.
213
- * @returns the first existing absolute path, or undefined.
214
- */
215
- function findOnPath(names: readonly string[], env: NodeJS.ProcessEnv, platform: NodeJS.Platform): string | undefined {
216
- // Windows spells it Path as often as PATH; the separator differs too.
217
- const raw = env.PATH ?? env.Path ?? env.path ?? ''
218
- const separator = platform === 'win32' ? ';' : ':'
219
- const directories = raw.split(separator).map(entry => entry.trim()).filter(entry => entry !== '')
220
- const suffixes = platform === 'win32' ? ['.exe', '.cmd', ''] : ['']
221
- for (const name of names) {
222
- for (const directory of directories) {
223
- for (const suffix of suffixes) {
224
- const candidate = join(directory, `${name}${suffix}`)
225
- if (existsSync(candidate)) return candidate
226
- }
227
- }
228
- }
229
- return undefined
230
- }
231
-
232
- /**
233
- * Find an installed Chromium browser.
234
- *
235
- * `auto` prefers Chrome, then Edge, then Brave — the order reflects how likely each
236
- * is to be the browser a user actually chose rather than one the system shipped.
237
- * Each candidate is looked up in three places, most specific first: an explicit
238
- * environment override, then PATH, then the platform's conventional install
239
- * locations. PATH comes before the fixed paths because it is what actually reflects
240
- * how the browser was installed.
241
- * @param channel - the configured choice; `bundled` never resolves to a system browser.
242
- * @param env - environment lookup, injected so tests need no real machine.
243
- * @param platform - the platform to use conventions for; injected for the same reason.
244
- * @returns the detected browser, or undefined when the choice is unavailable.
245
- */
246
- export function detectBrowser(
247
- channel: BrowserChannel,
248
- env: NodeJS.ProcessEnv = process.env,
249
- platform: NodeJS.Platform = process.platform,
250
- ): DetectedBrowser | undefined {
251
- if (channel === 'bundled') return undefined
252
- const order: DetectedBrowser['kind'][] = channel === 'auto' ? ['chrome', 'edge', 'brave'] : [channel as DetectedBrowser['kind']]
253
- for (const kind of order) {
254
- const fromEnv = (kind === 'chrome' ? env.DSH_BROWSER_CHROME_PATH : kind === 'edge' ? env.DSH_BROWSER_EDGE_PATH : undefined)
255
- if (fromEnv !== undefined && fromEnv !== '' && existsSync(fromEnv)) return { kind, path: fromEnv }
256
- const onPath = findOnPath(PATH_NAMES[kind]?.[platform] ?? [], env, platform)
257
- if (onPath !== undefined) return { kind, path: onPath }
258
- for (const raw of INSTALL_LOCATIONS[kind]?.[platform] ?? []) {
259
- const candidate = expandLocation(raw, env)
260
- if (existsSync(candidate)) return { kind, path: candidate }
261
- }
262
- }
263
- return undefined
264
- }
265
-
266
- /**
267
- * Everything that was checked for one product, for reporting a miss.
268
- *
269
- * Detection returns undefined with no explanation, which left the caller able to say
270
- * only "not found". This gives the user the actual list so they can see whether the
271
- * plugin looked somewhere their browser is not.
272
- * @param kind - the product to describe.
273
- * @param platform - the platform whose names and locations apply.
274
- * @returns the launcher names (as PATH lookups) and the fixed locations checked.
275
- */
276
- export function searchSummary(
277
- kind: DetectedBrowser['kind'],
278
- platform: NodeJS.Platform = process.platform,
279
- env: NodeJS.ProcessEnv = process.env,
280
- ): string[] {
281
- const onPath = (PATH_NAMES[kind]?.[platform] ?? []).map(name => `${name} (on PATH)`)
282
- // Expanded, so the report names the location that was actually tested rather than a template
283
- // the user cannot paste into a file manager.
284
- const located = (INSTALL_LOCATIONS[kind]?.[platform] ?? []).map(entry => expandLocation(entry, env))
285
- return [...onPath, ...located]
286
- }
287
-
288
- /** One CDP connection to a browser-level WebSocket, with flattened sessions. */
289
- class CdpClient {
290
- private nextId = 1
291
- private readonly pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>()
292
- private readonly ready: Promise<void>
293
-
294
- /**
295
- * @param url - the browser's `webSocketDebuggerUrl`.
296
- */
297
- constructor(url: string) {
298
- // Node 22 provides WebSocket globally; no dependency is added for this.
299
- const socket = new WebSocket(url)
300
- this.socket = socket
301
- this.ready = new Promise<void>((resolve, reject) => {
302
- socket.addEventListener('open', () => resolve())
303
- socket.addEventListener('error', () => reject(new Error('dsh-builtin-browser: could not reach the browser over CDP')))
304
- })
305
- socket.addEventListener('message', event => this.onMessage(String((event as MessageEvent).data)))
306
- socket.addEventListener('close', () => this.fail(new Error('dsh-builtin-browser: the browser closed the CDP connection')))
307
- }
308
-
309
- private readonly socket: WebSocket
310
-
311
- /**
312
- * Resolve once the socket is open.
313
- *
314
- * Bounded on purpose. `ready` settles on the socket's own `open` or `error` events, and
315
- * a connection that is dropped by something in between may deliver neither — in which
316
- * case an unbounded await here would hang the tool call forever, because the caller's
317
- * own deadline is only checked between polls and this await happens inside one of them.
318
- * @returns when the handshake completed.
319
- */
320
- /**
321
- * Whether the socket is still usable.
322
- *
323
- * A dropped connection is not reported to the caller of send(); the pending command
324
- * would simply never complete. Asking the socket directly is what lets a cached client
325
- * be discarded instead of reused, which is the difference between a restart and a 30s
326
- * hang on every subsequent call.
327
- * @returns true while the socket is open.
328
- */
329
- isAlive(): boolean {
330
- return this.socket.readyState === WebSocket.OPEN
331
- }
332
-
333
- async whenReady(deadline = Date.now() + 30_000): Promise<void> {
334
- const timeoutMs = Math.max(1, deadline - Date.now())
335
- let timer: NodeJS.Timeout | undefined
336
- try {
337
- await Promise.race([
338
- this.ready,
339
- new Promise<never>((_resolve, reject) => {
340
- timer = setTimeout(
341
- () => reject(new Error(`dsh-builtin-browser: the browser did not complete the CDP handshake within ${timeoutMs / 1000}s`)),
342
- timeoutMs,
343
- )
344
- }),
345
- ])
346
- } finally {
347
- if (timer !== undefined) clearTimeout(timer)
348
- }
349
- }
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
-
356
- /**
357
- * Send one CDP command, optionally on an attached session.
358
- * @param method - the CDP method.
359
- * @param params - its parameters.
360
- * @param sessionId - the flattened session to target, when this is a page command.
361
- * @returns the CDP result.
362
- */
363
- async send(method: string, params?: Record<string, unknown>, sessionId?: string, timeoutMs = 30_000): Promise<unknown> {
364
- // Fail fast and say why. Waiting out the timeout on a closed socket produced
365
- // only "timed out", which reads as a slow page and hides the real cause.
366
- if (!this.isAlive()) {
367
- throw new Error('dsh-builtin-browser: the browser connection is closed (the browser window was probably closed); the next command will start it again')
368
- }
369
- await this.ready
370
- const id = this.nextId++
371
- const message = { id, method, ...params !== undefined ? { params } : {}, ...sessionId !== undefined ? { sessionId } : {} }
372
- return await new Promise<unknown>((resolve, reject) => {
373
- this.pending.set(id, { resolve, reject })
374
- this.socket.send(JSON.stringify(message))
375
- setTimeout(() => {
376
- if (this.pending.delete(id)) reject(new Error(`dsh-builtin-browser: ${method} timed out`))
377
- }, timeoutMs).unref?.()
378
- })
379
- }
380
-
381
- /** Close the socket. */
382
- close(): void {
383
- try { this.socket.close() } catch { /* already closed */ }
384
- }
385
-
386
- /** Route one CDP message to its waiter. */
387
- private onMessage(raw: string): void {
388
- let message: { id?: number; result?: unknown; error?: { message?: string } }
389
- try { message = JSON.parse(raw) } catch { return }
390
- if (message.id === undefined) return
391
- const entry = this.pending.get(message.id)
392
- if (entry === undefined) return
393
- this.pending.delete(message.id)
394
- if (message.error !== undefined) entry.reject(new Error(`dsh-builtin-browser: CDP error: ${message.error.message ?? 'unknown'}`))
395
- else entry.resolve(message.result)
396
- }
397
-
398
- /** Fail everything in flight. */
399
- private fail(error: Error): void {
400
- const pending = [...this.pending.values()]
401
- this.pending.clear()
402
- for (const entry of pending) entry.reject(error)
403
- }
404
- }
405
-
406
- /** A system browser driven over CDP, presented as a browser view host. */
407
- export class SystemBrowserViewHost implements ElectronBrowserViewHost {
408
- /**
409
- * viewId -> the session that view rides, and the client that issued it.
410
- *
411
- * The client is part of the value on purpose. A session id means nothing to a browser other
412
- * than the one that handed it out, and this host replaces browsers routinely: the process
413
- * dies, or its debugging socket closes while the process lives on. Keeping only the id meant
414
- * the host could start a NEW browser successfully and then send every command to it carrying
415
- * a session the old one had issued — `Session with given id not found`, on every call, with a
416
- * browser that answers /json/version perfectly well and nothing the user can do short of
417
- * restarting DSH. Comparing identity catches it with no round trip; validating each cached
418
- * session against the browser would put one on every page command.
419
- */
420
- private readonly views = new Map<string, { session: string; client: CdpClient }>()
421
- private disposed = false
422
- /**
423
- * The browser is started on FIRST USE, never on construction.
424
- *
425
- * A plugin that launches Chrome the moment its host loads is a plugin that takes
426
- * over the machine before anyone asked it to: simply starting DSH would spawn a
427
- * browser window. Registration must therefore be inert, and the process is only
428
- * spawned when a view is actually needed.
429
- */
430
- private client: CdpClient | undefined
431
- /**
432
- * Set when a command went unanswered rather than being refused.
433
- *
434
- * A timeout says nothing about the connection: the page may simply be slow. It marks the
435
- * client for a cheap check before the next command trusts it, which keeps a slow page
436
- * from being mistaken for a dead browser while still catching one that has truly stopped
437
- * answering.
438
- */
439
- private clientSuspect = false
440
- private child: ChildProcess | undefined
441
- private profileLease: ProfileLease | undefined
442
- private starting: Promise<CdpClient> | undefined
443
- private lastLaunchError: string | undefined
444
- private launchDiagnostic: SystemBrowserLaunchDiagnostic | undefined
445
-
446
- /**
447
- * Browsers that ignored a kill.
448
- *
449
- * They are no longer this host's child — a replacement has taken that slot — but they
450
- * are still running, still holding the profile, and still something release must try to
451
- * stop. Forgetting them is what allowed a launch this host could not undo.
452
- */
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>>()
458
-
459
- /**
460
- * @param browser - the detected installation to launch on first use.
461
- * @param profileDir - a plugin-owned directory; the user's own profile is never touched.
462
- * @param extraArgs - additional Chromium switches.
463
- * @param ephemeralDir - a directory to delete on release, when the user has turned
464
- * persistence off so no login state outlives the session.
465
- * @param launcher - how to start the browser, for tests.
466
- *
467
- * Recovery after the browser dies was untestable without this: the suite spawns a stub
468
- * with Chromium's arguments, and a stub that is not a browser rejects them and exits, so
469
- * no CDP endpoint ever appears and no session is ever created. Verified by mutation —
470
- * removing every sessions.clear() left the recovery tests green. A launcher lets a test
471
- * provide something that actually speaks CDP, so the state those tests describe exists.
472
- */
473
- constructor(
474
- private readonly browser: DetectedBrowser,
475
- private readonly profileDir: string,
476
- private readonly extraArgs: readonly string[] = [],
477
- private readonly ephemeralDir?: string,
478
- private readonly launcher: BrowserLauncher = defaultLauncher,
479
- /**
480
- * Whether this launch should get a window. See {@link resolveLaunchMode} for how `auto` decides
481
- * and why a display-less host needs headless at all (issue #32).
482
- */
483
- private readonly headlessMode: HeadlessMode = 'auto',
484
- private readonly isQuiet: () => boolean = () => false,
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
- }
522
-
523
- /** Which product this host would drive (for diagnostics). */
524
- get kind(): DetectedBrowser['kind'] {
525
- return this.browser.kind
526
- }
527
-
528
- /** Whether the browser has actually been started yet (diagnostics and tests). */
529
- get started(): boolean {
530
- return this.child !== undefined
531
- }
532
-
533
- /**
534
- * The CDP client, starting the browser on first use.
535
- * @returns the connected client.
536
- */
537
- /**
538
- * Whether a client that reports itself open is actually answering.
539
- *
540
- * An open socket proves nothing: a browser can hold the connection and never reply, and
541
- * that state must not be cached, or every later command waits out its own timeout. Asking
542
- * the browser something cheap is a fact; reading the failure text is a guess, and the
543
- * guess was wrong in both directions (it killed healthy browsers on a slow page, and it
544
- * mistook the browser's own free text for a verdict).
545
- *
546
- * This is only reached when the socket is open, so the common path costs nothing.
547
- * @param client - the client to question.
548
- * @returns true when it answered.
549
- */
550
- private async probeClient(client: CdpClient): Promise<boolean> {
551
- try {
552
- // The command budget (30s) on purpose, not a shorter "probe" value, because of what the
553
- // answer is used for: a false verdict discards the client and replaces the browser,
554
- // which KILLS the window the human is looking at. A page that is merely slow must not
555
- // lose its browser, so this errs toward waiting. The price is that a truly wedged
556
- // browser takes the full budget to be declared dead — the tool call that triggered the
557
- // probe answers first, and its timeout is the error the caller sees. Trading a later
558
- // error for a window that is not destroyed is the right way round.
559
- await client.send('Browser.getVersion', {})
560
- return true
561
- } catch {
562
- // No answer within the budget, or the socket failed while asking: unusable either way.
563
- return false
564
- }
565
- }
566
-
567
- /**
568
- * Forget which browser issued what, after that browser is gone.
569
- *
570
- * The two maps must move together: `views` maps a view id to a session id and `sessions`
571
- * maps a session id to a target id, so clearing one alone leaves a mapping the next command
572
- * will act on. Every path that abandons a browser calls this rather than spelling the pair
573
- * out — four separate copies is how the third one came to be missing.
574
- */
575
- private forgetBrowserState(): void {
576
- this.views.clear()
577
- this.sessions.clear()
578
- }
579
-
580
- private async ensureClient(): Promise<CdpClient> {
581
- // A disposed host must never start a browser: doing so would spawn a process
582
- // nobody owns and nobody will kill.
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)
585
- // The exit listener clears this, but a socket can also die without the process doing so
586
- // (the browser closing its debugging endpoint, a dropped connection). Checking the
587
- // socket's own state costs nothing and turns a 30s hang into a restart.
588
- if (this.client !== undefined) {
589
- // A closed socket means the browser is gone; an OPEN socket proves nothing, because
590
- // a browser can hold the connection and never answer. Only probe when the socket is
591
- // closed or a previous command went unanswered without being refused — probing every
592
- // call would add a round trip to the common path for nothing.
593
- const current = this.client
594
- if (current.isAlive() && !this.clientSuspect) return current
595
- if (current.isAlive() && await this.probeClient(current)) {
596
- this.clientSuspect = false
597
- return current
598
- }
599
- current.close()
600
- this.client = undefined
601
- this.clientSuspect = false
602
- // Everything this client issued dies with it. `start()` clears these too, but only
603
- // inside its "kill the old child" branch — and the shape of this failure usually has no
604
- // child left to kill: the process already exited, its exit listener already set
605
- // `this.child` to undefined, so start() skips that branch and publishes a new browser
606
- // while the views still point at the dead one. That is the state that never recovers.
607
- this.forgetBrowserState()
608
- }
609
- // Concurrent first calls share one startup rather than racing two browsers.
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
618
- }
619
-
620
- /**
621
- * Take over a browser already serving this profile, instead of racing it.
622
- *
623
- * A previous DSH process leaves its browser running: the child handle died with that process, so
624
- * nothing here knows about it, and `start()`'s cleanup branch is skipped because it keys on
625
- * `this.child`. Launching then does something worse than fail — on Windows Chrome hands the
626
- * request to the instance already holding the profile and exits 0, and that exit is read as a
627
- * launch failure. The user is told to go kill the leftovers by hand, on every restart, which is
628
- * exactly what was reported.
629
- *
630
- * The launch loop deliberately refuses to trust a `<profile>/DevToolsActivePort` left by a
631
- * previous launch, and it is right to: a stale port number can be reused by something that is
632
- * not a browser at all. What makes adoption safe HERE is that this runs BEFORE launching, on a
633
- * file that lives inside this plugin's own profile directory — only a browser started with this
634
- * `--user-data-dir` writes it — and the endpoint is then asked to identify itself.
635
- * @param _why - a short phrase for the log, naming which attempt this is.
636
- * @returns a connected client for the running browser, or undefined when there is none.
637
- */
638
- private async adoptRunningBrowser(_why: string, explicitPort?: number, deadline = Date.now() + 30_000): Promise<CdpClient | undefined> {
639
- const portFile = join(this.profileDir, 'DevToolsActivePort')
640
- let port: number
641
- if (typeof explicitPort === 'number' && explicitPort > 0) {
642
- port = explicitPort
643
- } else try {
644
- if (!existsSync(portFile)) return undefined
645
- const value = Number(readFileSync(portFile, 'utf8').split('\n')[0]?.trim() ?? '')
646
- if (!Number.isInteger(value) || value <= 0) return undefined
647
- port = value
648
- } catch {
649
- return undefined
650
- }
651
- let client: CdpClient | undefined
652
- let identified = false
653
- try {
654
- const version = await (await fetch(cdpVersionUrl(port), {
655
- signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())),
656
- })).json() as { webSocketDebuggerUrl?: string; Browser?: string }
657
- if (typeof version.webSocketDebuggerUrl !== 'string') return undefined
658
- // The port number alone proves nothing — it can be reused once the browser that owned it
659
- // exits. The endpoint's own answer is the evidence, and it has to name a browser.
660
- if (!isBrowserProduct(version.Browser)) return undefined
661
- identified = true
662
- client = new CdpClient(version.webSocketDebuggerUrl)
663
- await client.whenReady(deadline)
664
- // Asked through the protocol too, so a websocket that merely accepts connections is not
665
- // mistaken for a browser that answers.
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')
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 }
671
- this.client = client
672
- return client
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
- }
679
- // No endpoint, nothing listening, or not a browser: all of them mean "launch one".
680
- return undefined
681
- }
682
- }
683
-
684
- /**
685
- * Launch the browser with a private profile and connect over CDP.
686
- *
687
- * `--remote-debugging-port=0` plus the `DevToolsActivePort` file is the only
688
- * reliable way to learn the port: a fixed port collides with whatever else the
689
- * machine is running, and parsing stderr is fragile across versions.
690
- * @returns the connected client.
691
- */
692
- private async start(): Promise<CdpClient> {
693
- const deadline = Date.now() + 30_000
694
- this.profileLease ??= acquireProfileLease(this.profileDir)
695
- // Before spawning anything: is a browser for THIS profile already running? A DSH restart
696
- // leaves one behind, and launching into it is the failure reported as "exited immediately
697
- // after launch (exit code 0)" that required killing seven processes by hand.
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)
709
- if (adopted !== undefined) return adopted
710
- // Whether a window exists is decided by `browser.headless` ALONE (plus the operator's
711
- // DSH_BROWSER_HEADLESS override inside resolveLaunchMode). `ui.quiet` must not force
712
- // headless: it describes how the agent presents its work — no activation, no raising,
713
- // background targets — not whether the human is allowed to see a browser at all.
714
- // Overriding the setting here made an explicit `headless: windowed`/`headed` invisible on
715
- // Chrome/Edge, so the human could not take over a login or a challenge, and an already
716
- // headless process cannot become visible by toggling quiet later. Quiet still governs
717
- // presentView() and createTarget() below, which is where activation belongs.
718
- const launch = resolveLaunchMode(this.headlessMode)
719
- const args = [
720
- '--remote-debugging-port=0',
721
- `--user-data-dir=${this.profileDir}`,
722
- // Behave like a fresh, unattended browser: no first-run UI, no default-browser
723
- // prompt, no restore bubble, and no "Chrome is being controlled" infobar.
724
- '--no-first-run',
725
- '--no-default-browser-check',
726
- '--disable-features=Translate,MediaRouter',
727
- '--disable-session-crashed-bubble',
728
- '--hide-crash-restore-bubble',
729
- // Headless only where there is nothing to draw on. `--headless=new` rather than the legacy
730
- // flag: the new mode behaves like a windowed browser, which matters because every command
731
- // here was written and measured against one — including CDP input, which Chromium silently
732
- // drops for a view it believes has no display surface. `--disable-gpu` and
733
- // `--disable-dev-shm-usage` are what make that mode usable on a server: no GPU, and a
734
- // /dev/shm far smaller than a desktop. See resolveLaunchMode for why this is conditional.
735
- ...launch.headless ? ['--headless=new', '--disable-gpu', '--disable-dev-shm-usage'] : [],
736
- ...this.extraArgs,
737
- // NOT `about:blank`. Every page this plugin drives is created by `Target.createTarget` when a
738
- // session first needs one (`buildSession`, which adopts a blank if the browser opened one and
739
- // creates one otherwise), so a startup page is a tab nobody asked for and nobody closes: the
740
- // tab strip showed `about:blank` next to the real page while `dsh_browser_list_tabs` reported
741
- // only the real one. Reported as issue #33, banner and all.
742
- //
743
- // `--no-startup-window` keeps the browser alive with no window and no initial page; measured
744
- // by the reporter on Chrome 156 as writing DevToolsActivePort in 599 ms, answering
745
- // `/json/version`, listing two extension targets and no page, and then creating windows
746
- // normally through `Target.createTarget`.
747
- '--no-startup-window',
748
- ]
749
- if (launch.headless) {
750
- process.stderr.write(`[dsh-browser] launching headless (${launch.why}); `
751
- + 'the browser has no window but every tool works the same\n')
752
- }
753
- // A browser from a previous attempt may still be running with this same
754
- // --user-data-dir. On Windows the new one would merely hand off to it and exit, and that
755
- // exit would then be treated as the launch failing.
756
- if (this.child !== undefined) {
757
- const dying = this.child
758
- if (!await this.stopChild(dying)) throw new Error(this.lastLaunchError)
759
- this.child = undefined
760
-
761
- // Whatever the old browser issued is worthless now, and its exit listener cannot clean
762
- // up after itself: this.child is reassigned below, so the old child's exit event returns
763
- // early and the session ids it handed out would be reused against a browser that never
764
- // heard of them — the "Session with given id not found" loop, which never clears.
765
- this.client?.close()
766
- this.client = undefined
767
- this.forgetBrowserState()
768
-
769
- // Wait for it to actually die. kill() only sends the signal: on Windows it is
770
- // TerminateProcess, which is asynchronous, and the browser may still hold this profile's
771
- // singleton lock for a while. Spawning immediately meant the replacement saw an existing
772
- // instance, handed its command line over and exited — and that exit was then reported as
773
- // "check that the path is a runnable browser", blaming the user's install for a race this
774
- // code created. Bounded, because a process that refuses to die must not hang the call.
775
- await new Promise<void>(resolve => {
776
- if (dying.exitCode !== null || dying.signalCode !== null) { resolve(); return }
777
- const done = (): void => { clearTimeout(timer); resolve() }
778
- const timer = setTimeout(done, EXIT_GRACE_MS)
779
- dying.once('exit', done)
780
- // It did not exit in time. Dropping the reference here was how this host could
781
- // launch a browser it could never kill again: dispose() only knows about this.child,
782
- // and this process still holds the profile's singleton lock. Remember it so release
783
- // still reaches it.
784
- if (dying.exitCode === null && dying.signalCode === null) this.stubborn.push(dying)
785
- dying.once('exit', () => {
786
- const at2 = this.stubborn.indexOf(dying)
787
- if (at2 !== -1) this.stubborn.splice(at2, 1)
788
- })
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')
791
- }
792
- // The port file is deliberately NOT deleted here, and that is a reversal.
793
- //
794
- // It used to be removed so the launch loop below could not read a previous browser's port. But
795
- // the loop judges freshness against a snapshot taken below, so the deletion never protected it
796
- // — while it DID destroy the only record of a browser that may still be running for this
797
- // profile. That record is what `adoptRunningBrowser` needs when the launch comes back as a
798
- // hand-off: the browser was alive the whole time, and without the file there is no way to find
799
- // it again.
800
- const portFile = join(this.profileDir, 'DevToolsActivePort')
801
- /**
802
- * What the port file was like BEFORE this launch, so "fresh" is judged against a snapshot
803
- * rather than against a clock.
804
- *
805
- * The test used to be `mtimeMs < spawnedAt` — a filesystem timestamp compared to `Date.now()`.
806
- * Those are different clocks with different resolutions, and CI is where it showed: a file the
807
- * fake browser had just written was rejected as stale, so the loop waited out its full 30s
808
- * against a browser that was already listening, because the file's mtime had rounded down
809
- * below the spawn time. That is not a test-only problem: on any filesystem whose mtime
810
- * resolution is coarser than a millisecond, the plugin would fail to see the browser it had
811
- * just launched, and report a CDP timeout for a browser that was up the whole time.
812
- *
813
- * `undefined` means there was no file, so any file that appears afterwards is fresh. When one
814
- * existed, a later mtime OR different contents makes the new one fresh. Byte-identical contents
815
- * with an unchanged mtime is the PREVIOUS browser's port, and adopting it is what this whole
816
- * check exists to prevent: it may name a port that now belongs to something else entirely.
817
- */
818
- const portFileBefore = ((): { mtimeMs: number; contents: string } | undefined => {
819
- try {
820
- return { mtimeMs: statSync(portFile).mtimeMs, contents: readFileSync(portFile, 'utf8') }
821
- } catch {
822
- return undefined
823
- }
824
- })()
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
831
- try {
832
- child = this.launcher(this.browser.path, args)
833
- } catch (error) {
834
- // spawn throws synchronously for some targets (a .cmd on Windows, a path that cannot
835
- // be executed). Without this the exception escaped start() and skipped every
836
- // diagnostic below it.
837
- throw new Error(`dsh-builtin-browser: could not launch ${this.browser.path}: ${error instanceof Error ? error.message : String(error)}`)
838
- }
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
- })
846
- /**
847
- * A launch that fails (ENOENT, no permission, a broken binary) is reported by an
848
- * asynchronous 'error' event on the child, NOT by a throw here and NOT by exitCode.
849
- * Without this listener Node treats it as unhandled and takes the whole host process
850
- * down — one bad browser path would kill DSH, not just fail a tool call.
851
- */
852
- let launchError: Error | undefined
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
- })
866
- // A browser that exits later is as unusable as one that never started, and the failure
867
- // has to reach the NEXT call rather than being swallowed: clearing the client here is
868
- // what makes ensureClient() start a fresh browser instead of returning a socket to a
869
- // dead process and letting every command time out.
870
- child.on('exit', () => {
871
- if (this.child !== child) return
872
- this.client?.close()
873
- this.client = undefined
874
- this.child = undefined
875
- this.lastLaunchError = 'Browser exited; the CDP connection is no longer live.'
876
- // The pages this client opened belong to the process that just died; keeping their
877
- // session ids means every later command is sent to a browser that never issued them.
878
- // Clearing these is what makes the restart usable rather than merely alive.
879
- this.forgetBrowserState()
880
- })
881
- await this.ownership.capture(child)
882
- /**
883
- * The port this launch wrote, or undefined while it has not written one yet.
884
- *
885
- * A file left by the PREVIOUS browser is not evidence about this one. Its contents name a port
886
- * that may now belong to something else entirely — another Chromium, a `node --inspect` — and
887
- * connecting there publishes a client this host does not own and dispose() can never kill.
888
- * Only a file that CHANGED across this launch counts, which is what `portFileBefore` records.
889
- */
890
- const freshPort = (): number | undefined => {
891
- try {
892
- if (!existsSync(portFile)) return undefined
893
- const after = statSync(portFile)
894
- const contents = readFileSync(portFile, 'utf8')
895
- // Unchanged since before the launch: this is the previous browser's file, whatever its
896
- // mtime says. Comparing against the snapshot rather than a wall-clock instant is what
897
- // keeps this correct on a filesystem whose timestamps are coarser than a millisecond.
898
- if (portFileBefore !== undefined
899
- && after.mtimeMs <= portFileBefore.mtimeMs
900
- && contents === portFileBefore.contents && child.exitCode !== 0) return undefined
901
- const value = Number(contents.split('\n')[0]?.trim() ?? '')
902
- return Number.isInteger(value) && value > 0 ? value : undefined
903
- } catch {
904
- return undefined
905
- }
906
- }
907
- /**
908
- * Why the loop stopped, so the failure can say what actually happened. Reporting
909
- * every ending as "did not expose CDP within 30s" was wrong three ways: the cause,
910
- * the words, and the elapsed time — a browser that cannot be launched says so in
911
- * half a second, and the caller then looks for a CDP problem that does not exist.
912
- */
913
- let stopped: 'released' | 'timeout' | 'exited' | 'launch-failed' = 'timeout'
914
- for (;;) {
915
- // Released while we were starting: stop here rather than keep polling for a
916
- // browser that dispose() has already killed, which would leave a connection
917
- // to a dead process behind. The child is killed here too — dispose() may have
918
- // run before this child was recorded, leaving nobody else to do it.
919
- if (this.disposed) { await this.stopChild(child); if (this.child === child) this.child = undefined; stopped = 'released'; break }
920
- if (launchError !== undefined) { if (this.child === child) this.child = undefined; stopped = 'launch-failed'; break }
921
- if (Date.now() > deadline) { await this.stopChild(child); stopped = 'timeout'; break }
922
- // signalCode too: a browser killed by a signal never sets exitCode, so checking exitCode
923
- // alone made a killed browser look alive and the launch run out its full 30s deadline
924
- // before reporting "did not expose CDP" — a timeout for something that died at once.
925
- // The sibling check on the release path already looked at both.
926
- if (child.signalCode !== null || (child.exitCode !== null && child.exitCode !== 0)) { if (this.child === child) this.child = undefined; stopped = 'exited'; break }
927
- // Only a port THIS launch wrote: reading whatever file happened to be there is how a
928
- // restart could adopt the previous browser, or any process now holding that port.
929
- const port = freshPort()
930
- if (port !== undefined) {
931
- try {
932
- const version = await (await fetch(cdpVersionUrl(port), {
933
- // Bounded: an unanswered loopback request would otherwise park inside this
934
- // iteration for the rest of the budget, and the deadline above is only re-checked
935
- // between iterations. Deliberately no larger than the 250 ms sleep — see
936
- // PORT_PROBE_MS.
937
- signal: AbortSignal.timeout(Math.max(1, Math.min(PORT_PROBE_MS, deadline - Date.now()))),
938
- })).json() as { webSocketDebuggerUrl?: string; Browser?: string }
939
- if (typeof version.webSocketDebuggerUrl === 'string') {
940
- const client = new CdpClient(version.webSocketDebuggerUrl)
941
- // `whenReady` has its own 30 s ceiling, and it is reached only after the port
942
- // answered above — so the browser is listening and this is a handshake, not a
943
- // discovery. A handshake that outlives the launch is reported as the timeout it
944
- // is, by the same deadline that governs everything else here.
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 }
951
- // Still wanted? A dispose() during the handshake has already killed the
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
- }
964
- if (this.disposed) { client.close(); break }
965
- this.client = client
966
- return client
967
- }
968
- } catch (error) {
969
- if ((error as { code?: string })?.code === 'BROWSER_LAUNCH_UNACKNOWLEDGED') throw error
970
- // The file can exist a moment before the port answers; poll again.
971
- }
972
- }
973
- await new Promise(resolve => setTimeout(resolve, 250))
974
- }
975
- // Each ending gets its own message. The old single message blamed a CDP timeout for
976
- // all of them, which sent the reader looking for a port problem when the browser had
977
- // simply failed to launch.
978
- const target = `${this.browser.kind} (${this.browser.path})`
979
- if (stopped === 'launch-failed') {
980
- throw new Error(`dsh-builtin-browser: could not launch ${target}: ${launchError?.message ?? 'unknown error'}`)
981
- }
982
- if (stopped === 'exited') {
983
- // Only exit code 0 is the hand-off story. A non-zero code or a signal means the browser
984
- // died on its own — a crash, a missing library, a sandbox refusal — and asserting the
985
- // profile story for those sent people looking for a leftover process that was not there,
986
- // which is the same mistake this message was written to correct, pointing the other way.
987
- const code = child.exitCode
988
- const signal = child.signalCode
989
- throw new Error(
990
- `dsh-builtin-browser: ${target} exited immediately after launch `
991
- + `(${signal !== null ? `killed by ${signal}` : `exit code ${String(code)}`}), so it did not `
992
- + 'hand the request anywhere — the browser failed to start rather than deferring to another '
993
- + 'instance. Check that it can run at all: run it by hand, and look for a crash or a missing '
994
- + 'dependency rather than a leftover process.',
995
- )
996
- }
997
- if (stopped === 'released') {
998
- throw new Error(`dsh-builtin-browser: ${target} was released while it was starting`)
999
- }
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.')
1005
- }
1006
-
1007
- /**
1008
- * Whether this host can back views.
1009
- *
1010
- * True while the host is usable — including before the browser has been started,
1011
- * since the first command is what starts it. Reporting "unavailable" here would
1012
- * make the plugin fall back for no reason.
1013
- */
1014
- available(): boolean {
1015
- return !this.disposed
1016
- }
1017
-
1018
- /**
1019
- * Every page the browser currently holds, including ones this plugin did not create.
1020
- *
1021
- * Chrome and Edge own their own page creation. A click on a link that opens a new page — or any
1022
- * `window.open` — produces a page the provider never asked for, and nothing reports it back.
1023
- * Those pages are real: they hold memory and stay until something closes them. Measured on a real
1024
- * window: four pages present while `dsh_browser_list_tabs` reported one.
1025
- *
1026
- * Discovery is enabled before the connection is published, so
1027
- * `Target.getTargets` also lists pages that existed before this client connected.
1028
- * @returns the browser's pages, or an empty list when it cannot answer.
1029
- */
1030
- /**
1031
- * Every page the browser holds that THIS HOST did not open.
1032
- *
1033
- * Chrome and Edge own their own page creation. A click on a link that opens a new page — or any
1034
- * `window.open` — produces a page the provider never asked for, and nothing reports it back.
1035
- * Those pages are real: they hold memory and stay until something closes them. Measured on a real
1036
- * window: four pages present while `dsh_browser_list_tabs` reported one.
1037
- *
1038
- * Pages this host opened are EXCLUDED here rather than deduplicated by the caller, because the
1039
- * caller cannot do it: the provider knows a tab by its own id, the carrier knows a page by its
1040
- * CDP target id, and the two never match. The first version returned everything and relied on the
1041
- * caller to filter, which reported the same page twice.
1042
- *
1043
- * Discovery is enabled before the connection is published, so
1044
- * `Target.getTargets` also lists pages that existed before this client connected.
1045
- * @returns the browser's pages that are not ours, or an empty list when it cannot answer.
1046
- */
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 []
1058
- try {
1059
- const client = await this.ensureClient()
1060
- const listed = await client.send('Target.getTargets', {}) as {
1061
- targetInfos?: Array<{ targetId?: string; type?: string; url?: string; title?: string }>
1062
- }
1063
- const ours = new Set(this.sessions.values())
1064
- return (listed?.targetInfos ?? [])
1065
- .filter(entry => entry.type === 'page' && typeof entry.targetId === 'string')
1066
- .filter(entry => !/^edge:\/\/sync-confirmation-dialog(?:\/|$)/.test(entry.url ?? ''))
1067
- .filter(entry => !ours.has(entry.targetId as string))
1068
- .map(entry => ({
1069
- id: tabWireId({ ...resolveSessionHandle(scope), tab: `page:${entry.targetId as string}` }),
1070
- url: typeof entry.url === 'string' ? entry.url : '',
1071
- ...typeof entry.title === 'string' && entry.title !== '' ? { title: entry.title } : {},
1072
- }))
1073
- } catch {
1074
- // A listing must not fail harder than driving does; the next command reports a real problem.
1075
- return []
1076
- }
1077
- }
1078
-
1079
- /**
1080
- * Close one page by the target id {@link listPages} reported.
1081
- *
1082
- * Only targets created by this owner/session on this connection may be closed.
1083
- * @param id - the CDP target id.
1084
- */
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
1089
- const client = await this.ensureClient()
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)
1098
- }
1099
-
1100
- createView(identity?: BrowserTabWireId): ElectronViewHandle {
1101
- const viewId = identity ?? tabWireId({ owner: 'standalone', session: randomUUID(), tab: randomUUID() })
1102
- readTabHandle(viewId)
1103
- return {
1104
- id: viewId,
1105
- // This is the real browser, not Electron: CDP's JPEG encoder works here, so the
1106
- // provider may pass format and quality through instead of falling back to PNG.
1107
- supportsCdpJpeg: true,
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
- }
1112
- // A command that never answered is the only signal that a client has wedged — the
1113
- // socket can stay OPEN while nothing comes back, which is the form the reporter saw with
1114
- // a live, healthy-looking Edge. Dropping the client here means the next call starts a new
1115
- // browser rather than hanging again, and the error names the cause instead of a timeout.
1116
- const client = await this.ensureClient()
1117
- const cachedView = this.views.get(viewId)
1118
- // A session belongs to the browser that issued it. Clearing the cache whenever a client is
1119
- // dropped covers the ordinary case, but not this one: another call can be inside
1120
- // ensureSession() holding the OLD client while this one discards it and clears, and that
1121
- // call's `views.set` then lands afterwards — re-adding an entry naming a browser that is
1122
- // gone. The identity check is what refuses it, and it costs a comparison rather than the
1123
- // round trip that validating every cached session against the browser would cost.
1124
- //
1125
- // (Not covered by the tests: the race needs two interleaved commands, and the suite's fake
1126
- // browser is synchronous enough that they never interleave. Verified by mutation instead —
1127
- // removing this check alone leaves every case green, which is why the comment says what it
1128
- // protects rather than claiming a case proves it.)
1129
- const session = cachedView !== undefined && cachedView.client === client
1130
- ? cachedView.session
1131
- : await this.ensureSession(viewId)
1132
- /**
1133
- * Send one page command, rebuilding the attach once if the browser no longer knows the
1134
- * session.
1135
- *
1136
- * "Session with given id not found" means the session id is stale, and the causes differ:
1137
- * a replaced client (handled where the client is dropped), a target the browser destroyed,
1138
- * or a detach the page performed on itself. What they share is that the id is worthless and
1139
- * the VIEW is fine, so the right answer is one fresh attach — not an error to the caller and
1140
- * not a new page. Measured while solving a sudoku on a canvas page: after a tab switch every
1141
- * command failed with this text and nothing in the plugin ever recovered it.
1142
- *
1143
- * Retried exactly once: a failure that survives a fresh attach is not a stale id, and
1144
- * repeating it would turn an error into a loop.
1145
- */
1146
- const sendWithAttach = async (target: string): Promise<Record<string, unknown>> => {
1147
- try {
1148
- const result = await client.send(method, params, target)
1149
- return (result ?? {}) as Record<string, unknown>
1150
- } catch (error) {
1151
- const message = error instanceof Error ? error.message : String(error)
1152
- if (!/Session with given id not found|No session with given id/i.test(message)) throw error
1153
- // Drop the dead attach so `ensureSession` builds a new one instead of returning the same id.
1154
- const stale = this.views.get(viewId)
1155
- if (stale !== undefined) this.views.delete(viewId)
1156
- this.sessions.delete(target)
1157
- const rebuilt = await this.ensureSession(viewId)
1158
- const retried = await client.send(method, params, rebuilt)
1159
- return (retried ?? {}) as Record<string, unknown>
1160
- }
1161
- }
1162
- try {
1163
- return await sendWithAttach(session)
1164
- } catch (error) {
1165
- // A CDP protocol error means the browser ANSWERED and refused this one command, so the
1166
- // connection is healthy and must be kept. Deciding by the error TEXT misfires both
1167
- // ways: the inner timeout rejects with "… timed out", so a slow but healthy page read
1168
- // as a dead browser, the client was dropped, and the next call's start() killed the
1169
- // running child — the human's tabs and half-filled forms gone, which is worse than the
1170
- // bug that change was fixing. The browser's own free text is interpolated into
1171
- // protocol errors too, so any message containing those words misfired the same way.
1172
- // Unanswered versus refused. 'timed out' is the inner client's own budget expiring,
1173
- // which says the page was slow, not that the browser died — so it only marks the client
1174
- // for a probe. Being wrong here costs a two-second check; being wrong about the
1175
- // browser being dead cost the user their open tabs.
1176
- if (error instanceof Error && /timed out/.test(error.message)) this.clientSuspect = true
1177
- if (!client.isAlive()) {
1178
- // Only THIS call's client. Under concurrency the field may already hold a
1179
- // connection another call just published, and closing that would kill a healthy one.
1180
- if (this.client === client) {
1181
- this.client = undefined
1182
- // This is the third of the three paths that discard a client, and it was the one
1183
- // that did not retire what the client had issued. A view holding a session id
1184
- // from the dead browser kept handing it to the replacement, which had never heard
1185
- // of it: every page command then failed with "Session with given id not found"
1186
- // and no later call could clear it, because the cached session was returned
1187
- // unconditionally. Gated on the same identity check as the field itself, so a
1188
- // concurrent call that just published a healthy client does not lose its maps.
1189
- this.forgetBrowserState()
1190
- }
1191
- client.close()
1192
- }
1193
- throw error
1194
- }
1195
- },
1196
- }
1197
- }
1198
-
1199
- destroyView(handle: ElectronViewHandle, _options?: { readonly keepPage?: boolean }): void {
1200
- const cachedView = this.views.get(handle.id)
1201
- this.views.delete(handle.id)
1202
- if (cachedView === undefined) return
1203
- const session = cachedView.session
1204
- const targetId = this.sessions.get(session)
1205
- this.sessions.delete(session)
1206
- // Nothing to close if the browser was never started.
1207
- if (targetId !== undefined && this.client !== undefined) {
1208
- void cachedView.client.send('Target.detachFromTarget', { sessionId: session }).catch(() => undefined)
1209
- }
1210
- }
1211
-
1212
- /** Nothing to show: the browser owns its own windows. */
1213
- showView(): void {}
1214
-
1215
- /**
1216
- * Bring the target's page to the front, then report success.
1217
- *
1218
- * The comment on `focus` below used to say this was impossible — that raising the page needs
1219
- * `Page.bringToFront` on a target session, which is a view-level concern the host cannot
1220
- * reach. The handle this method is handed IS that view, and it can send commands, so the
1221
- * capability was here all along; it just was not used. Without it `presentView` was an empty
1222
- * async method, so the provider's whole presentation barrier — the one that stops
1223
- * `Input.*` from being silently dropped for a view with no display surface, and reports
1224
- * `BROWSER_VIEW_NOT_PRESENTED` when it cannot present — never ran on this carrier.
1225
- *
1226
- * A failure is swallowed rather than propagated: a real Chrome window that refuses to come
1227
- * forward is not a reason to refuse the click that follows. The barrier exists to order the
1228
- * two, and the order is honoured either way.
1229
- * @param handle - the view to present.
1230
- */
1231
- async presentView(handle: ElectronViewHandle, _label?: string, options?: { readonly quiet?: boolean }): Promise<void> {
1232
- if (options?.quiet === true || this.isQuiet()) return
1233
- try {
1234
- await handle.sendCommand('Page.bringToFront')
1235
- } catch {
1236
- // Backgrounded, minimised, or a target that went away between the snapshot and the
1237
- // click. The command that called this will report its own failure if the page is gone.
1238
- }
1239
- }
1240
-
1241
-
1242
-
1243
- /**
1244
- * Best effort at bringing the browser's window forward.
1245
- *
1246
- * The browser is a separate application, so there is no view to raise. What this can
1247
- * actually do is ask its process to continue from a stopped state — which is a no-op on
1248
- * Windows, where `SIGCONT` is not a supported signal and the call throws. It is kept
1249
- * because it costs nothing and does help on POSIX (a process stopped with SIGSTOP
1250
- * resumes), but it must not be read as a promise that the window comes to the front;
1251
- * importantly, it does NOT raise a window that is merely behind another. Raising the
1252
- * page properly would need `Page.bringToFront` on a specific target session, which is a
1253
- * view-level concern and not available to the host.
1254
- */
1255
- async focus(): Promise<void> {
1256
- if (this.child && await this.ownership.verify(this.child)) {
1257
- try { this.child.kill('SIGCONT') } catch { /* Windows has no SIGCONT. */ }
1258
- }
1259
- }
1260
-
1261
-
1262
-
1263
- /**
1264
- * Close the browser we launched, if we ever launched one.
1265
- *
1266
- * The user's own windows belong to a different process and are never touched. A
1267
- * host whose browser was never started (the common case when nobody used the
1268
- * browser) simply tears down its bookkeeping.
1269
- */
1270
- dispose(): void {
1271
- if (this.disposed) return
1272
- this.disposed = true
1273
- const client = this.client
1274
- this.forgetBrowserState()
1275
- this.client = undefined
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() }
1287
- }
1288
- void disconnect()
1289
- // Both the browser we launched and anything that ignored an earlier kill. They hold this
1290
- // profile, so leaving them running means the next launch contends with a browser nobody owns.
1291
- const doomed = [this.child, ...this.stubborn.splice(0)].filter(
1292
- (entry): entry is ChildProcess => entry !== undefined,
1293
- )
1294
- this.child = undefined
1295
- for (const dying of doomed) {
1296
- /**
1297
- * A bounded reprieve, then the kill we used to do immediately.
1298
- *
1299
- * The timer is unref'd so it never holds the process open: a DSH shutdown that is itself
1300
- * ending does not wait for this, and the browser — having been asked to close — generally
1301
- * gets there on its own. If it does not, the kill still lands while the process lives.
1302
- */
1303
- const force = (): void => { void this.stopChild(dying) }
1304
- const timer = setTimeout(force, CLOSE_GRACE_MS)
1305
- timer.unref?.()
1306
- dying.once('exit', () => { clearTimeout(timer) })
1307
- }
1308
- const ephemeral = this.ephemeralDir
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()
1332
- }
1333
- }
1334
-
1335
- /**
1336
- * The flattened session for a view, creating its page on first use.
1337
- *
1338
- * No cache check here: the only caller has already established that the cached session does
1339
- * not belong to the client it is about to use. Re-checking would mean either a round trip or
1340
- * a second copy of that rule.
1341
- */
1342
- private async ensureSession(viewId: string): Promise<string> {
1343
- // One target per view, even when two commands arrive together. The two CDP round trips
1344
- // below are awaits, so without this a second caller entering during the first's flight saw
1345
- // no session in `views` and created its own target — leaving an orphan page that nothing
1346
- // closes, because only the last id survives in the map.
1347
- const inFlight = this.sessionBuilding.get(viewId)
1348
- if (inFlight !== undefined) return await inFlight
1349
- const building = this.buildSession(viewId).finally(() => {
1350
- this.sessionBuilding.delete(viewId)
1351
- })
1352
- this.sessionBuilding.set(viewId, building)
1353
- return await building
1354
- }
1355
-
1356
- /** Create and attach the target for one view. Serialised by {@link ensureSession}. */
1357
- private async buildSession(viewId: string): Promise<string> {
1358
- const client = await this.ensureClient()
1359
- // Different views can initialise concurrently. Selecting an unclaimed page and attaching
1360
- // it must be one transaction, including when the page is created by a preceding view.
1361
- const previous = this.targetBuilds.get(client) ?? Promise.resolve()
1362
- let release!: () => void
1363
- const building = new Promise<void>(resolve => { release = resolve })
1364
- this.targetBuilds.set(client, building)
1365
- await previous
1366
- try {
1367
- // Adopt a blank page the browser opened on its own before creating another one.
1368
- //
1369
- // Chrome starts with more than one page when handed a URL on top of its own start page, so
1370
- // creating a target here discarded the original and left it behind as a tab that is not in
1371
- // the plugin's tab model — invisible to `dsh_browser_list_tabs`, and therefore unclosable
1372
- // through the tools. Taking the blank instead makes the page the browser already opened the
1373
- // one the caller gets.
1374
- const adopted = await this.adoptBlankTarget(client)
1375
- const targetId = adopted ?? await this.createTarget(client, viewId)
1376
- const attached = await client.send('Target.attachToTarget', { targetId, flatten: true }) as { sessionId?: string }
1377
- const sessionId = attached?.sessionId
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)
1380
- // The session id is what page commands ride; the target id is what closes it.
1381
- this.sessions.set(sessionId, targetId)
1382
- this.views.set(viewId, { session: sessionId, client })
1383
- return sessionId
1384
- } finally {
1385
- release()
1386
- if (this.targetBuilds.get(client) === building) this.targetBuilds.delete(client)
1387
- }
1388
- }
1389
-
1390
- /**
1391
- * Take over a page the browser already has, so a person's own tab becomes one this plugin drives.
1392
- *
1393
- * Reported as a defect: opening a window by hand, navigating it, and then asking a tool to read it
1394
- * produced a SECOND page, because the only tab the provider knew about was one it created itself.
1395
- * The page the human was looking at was listed by `dsh_browser_list_tabs` (under `page:`) and
1396
- * could be closed, but not read or driven — the opposite of what "the page you are looking at"
1397
- * means.
1398
- *
1399
- * Attaching is all it takes: a CDP session is not exclusive, so the browser's own tab becomes a
1400
- * target this plugin has a session on. The page is not moved, reloaded or focused, and its
1401
- * existing session (logins, scroll position, form state) is untouched.
1402
- * @param targetId - the carrier's page id, which for this carrier IS the CDP target id.
1403
- * @returns a handle for that page, in the same shape {@link createView} returns.
1404
- */
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)
1410
- const client = await this.ensureClient()
1411
- const attached = await client.send('Target.attachToTarget', { targetId, flatten: true }) as { sessionId?: string }
1412
- const sessionId = attached?.sessionId
1413
- if (typeof sessionId !== 'string') {
1414
- throw new Error(`dsh-builtin-browser: could not attach to the existing page ${targetId}`)
1415
- }
1416
- // Point the view `createView` just made at the page that already exists, instead of the one it
1417
- // would otherwise build on first use.
1418
- this.sessions.set(sessionId, targetId)
1419
- this.views.set(handle.id, { session: sessionId, client })
1420
- return handle
1421
- }
1422
-
1423
- /**
1424
- * Take an unclaimed blank page, if the browser has one to spare.
1425
- *
1426
- * "Unclaimed" is what matters: a blank page the plugin is already driving belongs to a view, and
1427
- * handing the same target to a second view would make two views share one page.
1428
- * @param client - the connected browser.
1429
- * @returns the target id to reuse, or undefined when a new page has to be created.
1430
- */
1431
- private async adoptBlankTarget(client: CdpClient): Promise<string | undefined> {
1432
- const listed = await client.send('Target.getTargets', {}) as {
1433
- targetInfos?: Array<{ targetId?: string; type?: string; url?: string }>
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
1444
- }
1445
-
1446
- /** Create one page, refusing to go on without an id. */
1447
- private async createTarget(client: CdpClient, viewId: string): Promise<string> {
1448
- const created = await client.send('Target.createTarget', {
1449
- url: 'about:blank',
1450
- ...this.isQuiet() ? { background: true } : {},
1451
- }) as { targetId?: string }
1452
- const targetId = created?.targetId
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)
1455
- return targetId
1456
- }
1457
-
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)
1462
- }
1463
-
1464
- /** Views whose session is being created right now, so a second caller waits for the first. */
1465
- private readonly sessionBuilding = new Map<string, Promise<string>>()
1466
-
1467
- /** Serialises page selection/creation and attachment for each browser connection. */
1468
- private readonly targetBuilds = new WeakMap<CdpClient, Promise<void>>()
1469
-
1470
- /** sessionId -> targetId, so a destroyed view can close the right page. */
1471
- private readonly sessions = new Map<string, string>()
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
- }