dsh-builtin-browser 0.5.8 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (401) hide show
  1. package/CHANGELOG.md +410 -1
  2. package/README.en.md +16 -64
  3. package/README.md +33 -64
  4. package/assets/browser-carriers.svg +20 -0
  5. package/assets/browser-extension-identity.d.mts +2 -0
  6. package/assets/browser-extension-identity.mjs +2 -0
  7. package/assets/browser-messages.d.mts +5 -0
  8. package/assets/browser-messages.mjs +64 -0
  9. package/assets/browser-panel-locales.d.mts +2 -0
  10. package/assets/browser-panel-locales.mjs +380 -0
  11. package/assets/browser-policy.d.mts +37 -0
  12. package/assets/browser-policy.mjs +37 -0
  13. package/assets/browser-products.d.mts +6 -0
  14. package/assets/browser-products.mjs +76 -0
  15. package/assets/screenshots/1-main.png +0 -0
  16. package/assets/screenshots/2-form-fill.png +0 -0
  17. package/assets/screenshots/3-challenge.png +0 -0
  18. package/browser-extension/constants.mjs +20 -0
  19. package/browser-extension/controller.mjs +293 -0
  20. package/browser-extension/locales.mjs +15 -0
  21. package/browser-extension/manifest.json +12 -0
  22. package/browser-extension/options.html +14 -0
  23. package/browser-extension/options.mjs +9 -0
  24. package/browser-extension/permission-guard.mjs +13 -0
  25. package/browser-extension/worker.mjs +74 -0
  26. package/cordis.patch.yml +23 -48
  27. package/desktop-bridge/desktop-discovery.d.mts +2 -0
  28. package/desktop-bridge/desktop-discovery.mjs +36 -0
  29. package/desktop-bridge/desktop-identity.json +17 -1
  30. package/desktop-bridge/desktop-processes.d.mts +1 -0
  31. package/desktop-bridge/desktop-processes.mjs +15 -0
  32. package/desktop-bridge/guest-proxy.mjs +109 -0
  33. package/desktop-bridge/install.mjs +197 -74
  34. package/desktop-bridge/main.mjs +11 -0
  35. package/desktop-bridge/maintenance-files.d.mts +8 -0
  36. package/desktop-bridge/maintenance-files.mjs +28 -0
  37. package/desktop-bridge/maintenance-progress.ps1 +2 -2
  38. package/desktop-bridge/native-guests.mjs +41 -0
  39. package/desktop-bridge/plugin-browser-bridge.js +618 -370
  40. package/desktop-bridge/profile-loader.mjs +26 -0
  41. package/dist/client.cjs +43167 -0
  42. package/dist/client.d.cts +516 -0
  43. package/dist/client.d.mts +516 -0
  44. package/dist/index.cjs +92 -0
  45. package/dist/index.d.mts +2960 -0
  46. package/dist/index.mjs +24 -0
  47. package/docs/HANDOVER-2026-11-15.md +178 -0
  48. package/docs/README.md +10 -19
  49. package/docs/architecture.md +17 -145
  50. package/docs/child-tabs.md +13 -0
  51. package/docs/desktop-acceptance.md +9 -0
  52. package/docs/development.md +88 -18
  53. package/docs/extension-browser.md +44 -0
  54. package/docs/hardcoding-audit.md +64 -0
  55. package/docs/limitations.md +23 -73
  56. package/docs/pr64-extension-status.md +46 -0
  57. package/docs/pr64-maintenance.md +25 -0
  58. package/docs/pr64-native-children.md +52 -0
  59. package/docs/pr64-native-views.md +60 -0
  60. package/docs/tool-reference.md +87 -11
  61. package/docs/user-guide.md +47 -255
  62. package/docs/why-browser.md +6 -39
  63. package/dsh-host-patch/README.md +60 -0
  64. package/dsh-host-patch/apply.mjs +194 -0
  65. package/dsh-host-patch/legacy-bridge.mjs +53 -0
  66. package/dsh-host-patch/rc3-revision1.json +90 -0
  67. package/dsh-host-patch/rc3-revision2.json +112 -0
  68. package/dsh-host-patch/rc3-revision3.json.gz +0 -0
  69. package/dsh-host-patch/rc3-revision4.json.gz +0 -0
  70. package/dsh-host-patch/rc3-revision5.json.gz +0 -0
  71. package/dsh-host-patch/rc3-revision6.json.gz +0 -0
  72. package/dsh-host-patch/rc3-revision7.json.gz +0 -0
  73. package/dsh-host-patch/rc3-revision8.json.gz +0 -0
  74. package/dsh-host-patch/rc3.json +148 -0
  75. package/dsh-host-patch/rc5-revision1.json +90 -0
  76. package/dsh-host-patch/rc5-revision2.json +112 -0
  77. package/dsh-host-patch/rc5-revision3.json.gz +0 -0
  78. package/dsh-host-patch/rc5-revision4.json.gz +0 -0
  79. package/dsh-host-patch/rc5-revision5.json.gz +0 -0
  80. package/dsh-host-patch/rc5-revision6.json.gz +0 -0
  81. package/dsh-host-patch/rc5-revision7.json.gz +0 -0
  82. package/dsh-host-patch/rc5-revision8.json.gz +0 -0
  83. package/dsh-host-patch/rc5.json +148 -0
  84. package/lib/bridge-compatibility.js +38 -0
  85. package/lib/browser/handles.js +78 -0
  86. package/lib/browser/runtime.js +155 -43
  87. package/lib/browser/takeover-target.js +24 -0
  88. package/lib/browser-electron/authenticated-route.js +23 -0
  89. package/lib/browser-electron/automatic-maintenance.js +394 -51
  90. package/lib/browser-electron/bridge-auto.js +2 -1
  91. package/lib/browser-electron/bridge-connection.js +8 -1
  92. package/lib/browser-electron/bridge-install.js +27 -2
  93. package/lib/browser-electron/bridge-maintenance.js +35 -10
  94. package/lib/browser-electron/bridge-status.js +98 -27
  95. package/lib/browser-electron/desktop-bridge-host.js +193 -560
  96. package/lib/browser-electron/desktop-identity.js +40 -2
  97. package/lib/browser-electron/document-readiness.js +34 -0
  98. package/lib/browser-electron/electron-provision.js +14 -44
  99. package/lib/browser-electron/entry.js +659 -252
  100. package/lib/browser-electron/extension-browser.js +234 -0
  101. package/lib/browser-electron/extension-setup.js +69 -0
  102. package/lib/browser-electron/guest-cookie-jar.LICENSE.txt +32 -0
  103. package/lib/browser-electron/guest-cookie-jar.js +10559 -0
  104. package/lib/browser-electron/guest-cookie-store.js +74 -0
  105. package/lib/browser-electron/guest-css-runtime.js +75 -0
  106. package/lib/browser-electron/guest-css.js +106 -0
  107. package/lib/browser-electron/guest-route.js +603 -0
  108. package/lib/browser-electron/guest-runtime.js +356 -0
  109. package/lib/browser-electron/guest-storage-runtime.js +52 -0
  110. package/lib/browser-electron/guest-storage.js +163 -0
  111. package/lib/browser-electron/history-store.js +2 -1
  112. package/lib/browser-electron/host-main.js +162 -7
  113. package/lib/browser-electron/host-patch-maintenance.js +141 -0
  114. package/lib/browser-electron/http-body.js +22 -0
  115. package/lib/browser-electron/maintenance-broker.js +35 -5
  116. package/lib/browser-electron/maintenance-lifecycle.js +7 -5
  117. package/lib/browser-electron/maintenance-route.js +9 -6
  118. package/lib/browser-electron/open-slot.js +47 -0
  119. package/lib/browser-electron/paths.js +4 -1
  120. package/lib/browser-electron/preferred-browser.js +144 -0
  121. package/lib/browser-electron/preview-route.js +11 -8
  122. package/lib/browser-electron/process-ownership.js +198 -0
  123. package/lib/browser-electron/profile-checkpoint.js +222 -0
  124. package/lib/browser-electron/profile-command.js +60 -0
  125. package/lib/browser-electron/profile-extension.js +126 -0
  126. package/lib/browser-electron/profile-lease.js +157 -0
  127. package/lib/browser-electron/profile-residue.js +61 -0
  128. package/lib/browser-electron/provider.js +719 -262
  129. package/lib/browser-electron/reference-route.js +635 -0
  130. package/lib/browser-electron/remote-host.js +12 -13
  131. package/lib/browser-electron/runtime-route.js +6 -5
  132. package/lib/browser-electron/runtime-status.js +30 -29
  133. package/lib/browser-electron/settings-store.js +10 -5
  134. package/lib/browser-electron/shortcuts-route.js +108 -0
  135. package/lib/browser-electron/sidebar-only-host.js +119 -18
  136. package/lib/browser-electron/startpage-shortcuts.js +172 -0
  137. package/lib/browser-electron/system-browser.js +352 -371
  138. package/lib/browser-electron/windows-system.js +2 -1
  139. package/lib/browser-reference/delivery.js +326 -0
  140. package/lib/browser-reference/entry.js +597 -0
  141. package/lib/browser-reference/export.js +298 -0
  142. package/lib/browser-reference/import.js +295 -0
  143. package/lib/browser-reference/page-script.js +1406 -0
  144. package/lib/browser-reference/service.js +1062 -0
  145. package/lib/browser-reference/store.js +177 -0
  146. package/lib/browser-reference/submission-receipts.js +139 -0
  147. package/lib/browser-reference/text-quote.js +167 -0
  148. package/lib/browser-reference/types.js +11 -0
  149. package/lib/browser-reference/visible.js +311 -0
  150. package/lib/browser-reference/web-sources.js +97 -0
  151. package/lib/index.js +10 -3
  152. package/lib/reference-owner.js +5 -0
  153. package/lib/reference-page.js +12 -0
  154. package/lib/reference-source.js +2 -0
  155. package/lib/reference-text.js +188 -0
  156. package/lib/startpage-settings.js +63 -0
  157. package/lib/startpage.js +44 -0
  158. package/lib/takeover-protocol.js +2 -0
  159. package/lib/tool-browser/code-tool.js +416 -0
  160. package/lib/tool-browser/code-worker.js +872 -0
  161. package/lib/tool-browser/index.js +940 -76
  162. package/lib/tool-browser/page-probe.js +3 -3
  163. package/lib/tool-browser/panel-page.js +95 -0
  164. package/lib/tool-browser/screenshot-image.js +51 -0
  165. package/lib/tool-browser/takeover.js +205 -0
  166. package/lib/types.js +1 -0
  167. package/lib/web-guest.js +26 -0
  168. package/native-host/client.d.mts +17 -0
  169. package/native-host/client.mjs +100 -0
  170. package/native-host/host.mjs +150 -0
  171. package/native-host/identity.d.mts +2 -0
  172. package/native-host/identity.mjs +1 -0
  173. package/native-host/install.mjs +168 -0
  174. package/native-host/protocol.mjs +75 -0
  175. package/package.json +80 -92
  176. package/scripts/build.mjs +66 -0
  177. package/scripts/bundle-host.mjs +28 -0
  178. package/scripts/fix-exports.mjs +50 -0
  179. package/scripts/install-electron.mjs +11 -26
  180. package/scripts/verify-exports.mjs +47 -0
  181. package/scripts/verify-preview-sdk.mjs +93 -0
  182. package/skills/dsh-builtin-browser/SKILL.md +56 -47
  183. package/skills/dsh-builtin-browser/references/batch.md +31 -1
  184. package/skills/dsh-debug-host/SKILL.md +56 -0
  185. package/skills/dsh-debug-self/SKILL.md +50 -0
  186. package/src/bridge-compatibility.ts +39 -0
  187. package/src/browser/handles.ts +89 -0
  188. package/src/browser/runtime.ts +146 -50
  189. package/src/browser/takeover-target.ts +36 -0
  190. package/src/browser/types.ts +19 -7
  191. package/src/browser-electron/authenticated-route.ts +29 -1
  192. package/src/browser-electron/automatic-maintenance.ts +368 -56
  193. package/src/browser-electron/bridge-auto.ts +5 -4
  194. package/src/browser-electron/bridge-connection.ts +20 -2
  195. package/src/browser-electron/bridge-endpoint.ts +3 -3
  196. package/src/browser-electron/bridge-install.ts +40 -4
  197. package/src/browser-electron/bridge-maintenance.ts +42 -14
  198. package/src/browser-electron/bridge-status.ts +94 -23
  199. package/src/browser-electron/desktop-bridge-host.ts +185 -585
  200. package/src/browser-electron/desktop-identity.ts +53 -2
  201. package/src/browser-electron/document-readiness.ts +45 -0
  202. package/src/browser-electron/electron-provision.ts +12 -45
  203. package/src/browser-electron/entry.ts +1299 -882
  204. package/src/browser-electron/ephemeral-profile.ts +1 -1
  205. package/src/browser-electron/extension-browser.ts +223 -0
  206. package/src/browser-electron/extension-setup.ts +67 -0
  207. package/src/browser-electron/guest-cookie-jar.ts +176 -0
  208. package/src/browser-electron/guest-cookie-store.ts +59 -0
  209. package/src/browser-electron/guest-css-runtime.ts +76 -0
  210. package/src/browser-electron/guest-css.ts +68 -0
  211. package/src/browser-electron/guest-route.ts +568 -0
  212. package/src/browser-electron/guest-runtime.ts +357 -0
  213. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  214. package/src/browser-electron/guest-storage.ts +117 -0
  215. package/src/browser-electron/history-store.ts +5 -4
  216. package/src/browser-electron/host-main.ts +156 -11
  217. package/src/browser-electron/host-patch-maintenance.ts +112 -0
  218. package/src/browser-electron/http-body.ts +23 -0
  219. package/src/browser-electron/maintenance-broker.ts +29 -5
  220. package/src/browser-electron/maintenance-lifecycle.ts +14 -9
  221. package/src/browser-electron/maintenance-route.ts +17 -14
  222. package/src/browser-electron/missing-system-browser.ts +2 -2
  223. package/src/browser-electron/open-slot.ts +49 -0
  224. package/src/browser-electron/paths.ts +5 -1
  225. package/src/browser-electron/preferred-browser.ts +120 -0
  226. package/src/browser-electron/preview-route.ts +18 -11
  227. package/src/browser-electron/process-ownership.ts +168 -0
  228. package/src/browser-electron/profile-checkpoint.ts +187 -0
  229. package/src/browser-electron/profile-command.ts +46 -0
  230. package/src/browser-electron/profile-extension.ts +124 -0
  231. package/src/browser-electron/profile-lease.ts +115 -0
  232. package/src/browser-electron/profile-residue.ts +49 -0
  233. package/src/browser-electron/provider.ts +771 -289
  234. package/src/browser-electron/reference-route.ts +608 -0
  235. package/src/browser-electron/remote-host.ts +15 -15
  236. package/src/browser-electron/runtime-route.ts +11 -10
  237. package/src/browser-electron/runtime-status.ts +51 -32
  238. package/src/browser-electron/settings-store.ts +27 -7
  239. package/src/browser-electron/shortcuts-route.ts +112 -0
  240. package/src/browser-electron/sidebar-only-host.ts +118 -19
  241. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  242. package/src/browser-electron/system-browser.ts +309 -338
  243. package/src/browser-electron/windows-system.ts +2 -1
  244. package/src/browser-reference/delivery.ts +384 -0
  245. package/src/browser-reference/entry.ts +631 -0
  246. package/src/browser-reference/export.ts +339 -0
  247. package/src/browser-reference/import.ts +303 -0
  248. package/src/browser-reference/page-script.ts +1537 -0
  249. package/src/browser-reference/service.ts +1315 -0
  250. package/src/browser-reference/store.ts +172 -0
  251. package/src/browser-reference/submission-receipts.ts +122 -0
  252. package/src/browser-reference/text-quote.ts +219 -0
  253. package/src/browser-reference/types.ts +195 -0
  254. package/src/browser-reference/visible.ts +367 -0
  255. package/src/browser-reference/web-sources.ts +103 -0
  256. package/src/client/browser/BrowserController.ts +693 -0
  257. package/src/client/browser/BrowserFrame.ts +78 -0
  258. package/src/client/browser/BrowserNavigation.ts +169 -0
  259. package/src/client/browser/BrowserPage.ts +23 -0
  260. package/src/client/browser/BrowserPersistence.ts +44 -0
  261. package/src/client/browser/IframeImpl.ts +176 -0
  262. package/src/client/browser/child-tabs.ts +14 -0
  263. package/src/client/browser/iframe-reference.ts +67 -0
  264. package/src/client/browser/initialization.ts +262 -0
  265. package/src/client/browser/omnibox.ts +243 -0
  266. package/src/client/browser/store.ts +38 -0
  267. package/src/client/browser/takeover-channel.ts +72 -0
  268. package/src/client/browser/url.ts +46 -0
  269. package/src/client/browser/web-reference-source.ts +52 -0
  270. package/src/client/css-modules.d.ts +4 -0
  271. package/src/client/definition.tsx +30 -0
  272. package/src/client/electron/ElectronWebViewImpl.ts +364 -0
  273. package/src/client/electron/ElectronWebviewPresentation.ts +138 -0
  274. package/src/client/electron/NativeChildPresentation.ts +45 -0
  275. package/src/client/electron/NativeViewPage.ts +251 -0
  276. package/src/client/electron/pages.ts +23 -0
  277. package/src/client/electron/reference-overlay.ts +53 -0
  278. package/src/client/electron/workspace.ts +33 -0
  279. package/src/client/index.ts +293 -0
  280. package/src/client/locales.ts +857 -0
  281. package/src/client/pages.ts +28 -0
  282. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  283. package/src/client/reference/client/draft-reference.ts +167 -0
  284. package/src/client/reference/client/index.ts +7 -0
  285. package/src/client/reference/client/ordered-submission.ts +108 -0
  286. package/src/client/reference/client/pending-delivery.ts +216 -0
  287. package/src/client/reference/client/plugin.ts +189 -0
  288. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  289. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  290. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  291. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  292. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  293. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  294. package/src/client/reference/client/production/assembly.ts +471 -0
  295. package/src/client/reference/client/production/asset-store.ts +144 -0
  296. package/src/client/reference/client/production/availability.ts +74 -0
  297. package/src/client/reference/client/production/bytes.ts +36 -0
  298. package/src/client/reference/client/production/delivery-client.ts +211 -0
  299. package/src/client/reference/client/production/draft-adapter.ts +508 -0
  300. package/src/client/reference/client/production/http-transport.ts +217 -0
  301. package/src/client/reference/client/production/production-submission.ts +310 -0
  302. package/src/client/reference/client/production/protocol.ts +231 -0
  303. package/src/client/reference/client/production/reference-card.ts +240 -0
  304. package/src/client/reference/client/production/reference-labels.ts +29 -0
  305. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  306. package/src/client/reference/client/production/reveal.ts +215 -0
  307. package/src/client/reference/client/production/runtime.ts +1101 -0
  308. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  309. package/src/client/reference/client/production/source-marker.ts +63 -0
  310. package/src/client/reference/client/production/source-opener.ts +55 -0
  311. package/src/client/reference/client/production/styles.ts +104 -0
  312. package/src/client/reference/client/production/user-text-rule.ts +58 -0
  313. package/src/client/reference/client/reveal.ts +107 -0
  314. package/src/client/reference/client/scheme.ts +114 -0
  315. package/src/client/reference/client/types.ts +168 -0
  316. package/src/client/reference/css-modules.d.ts +4 -0
  317. package/src/client/reference/index.ts +11 -0
  318. package/src/client/reference-capture-owner.ts +162 -0
  319. package/src/client/reference-intents.ts +36 -0
  320. package/src/client/settings/index.ts +34 -0
  321. package/{client.js → src/client/settings/panel.ts} +2657 -2231
  322. package/src/client/shortcut-open.ts +30 -0
  323. package/src/client/startpage/binding.ts +99 -0
  324. package/src/client/startpage/controller.ts +303 -0
  325. package/src/client/startpage/model.ts +279 -0
  326. package/src/client/view/Browser.module.css +751 -0
  327. package/src/client/view/BrowserBody.tsx +314 -0
  328. package/src/client/view/BrowserPresentation.ts +9 -0
  329. package/src/client/view/BrowserTitle.tsx +17 -0
  330. package/src/client/view/IframePresentation.ts +344 -0
  331. package/src/client/view/StartPage.tsx +597 -0
  332. package/src/client/view/TakeoverBanner.tsx +21 -0
  333. package/src/index.ts +110 -73
  334. package/src/reference-owner.ts +5 -0
  335. package/src/reference-page.ts +9 -0
  336. package/src/reference-source.ts +3 -0
  337. package/src/reference-text.ts +197 -0
  338. package/src/startpage-settings.ts +103 -0
  339. package/src/startpage.ts +71 -0
  340. package/src/takeover-protocol.ts +19 -0
  341. package/src/tool-browser/code-tool.ts +401 -0
  342. package/src/tool-browser/code-worker.ts +639 -0
  343. package/src/tool-browser/index.ts +908 -77
  344. package/src/tool-browser/page-probe.ts +4 -4
  345. package/src/tool-browser/panel-page.ts +124 -0
  346. package/src/tool-browser/screenshot-image.ts +49 -0
  347. package/src/tool-browser/takeover.ts +198 -0
  348. package/src/types/electron-shim.d.ts +20 -0
  349. package/src/types.ts +85 -0
  350. package/src/web-guest.ts +34 -0
  351. package/tools/accept-desktop.mjs +148 -0
  352. package/lib/browser/runtime.d.ts +0 -175
  353. package/lib/browser/types.d.ts +0 -797
  354. package/lib/browser-electron/authenticated-route.d.ts +0 -27
  355. package/lib/browser-electron/automatic-maintenance.d.ts +0 -41
  356. package/lib/browser-electron/bridge-auto.d.ts +0 -93
  357. package/lib/browser-electron/bridge-connection.d.ts +0 -93
  358. package/lib/browser-electron/bridge-endpoint.d.ts +0 -30
  359. package/lib/browser-electron/bridge-install.d.ts +0 -85
  360. package/lib/browser-electron/bridge-maintenance.d.ts +0 -24
  361. package/lib/browser-electron/bridge-status.d.ts +0 -50
  362. package/lib/browser-electron/desktop-bridge-host.d.ts +0 -248
  363. package/lib/browser-electron/desktop-identity.d.ts +0 -58
  364. package/lib/browser-electron/electron-provision.d.ts +0 -92
  365. package/lib/browser-electron/entry.d.ts +0 -64
  366. package/lib/browser-electron/ephemeral-profile.d.ts +0 -37
  367. package/lib/browser-electron/file-write.d.ts +0 -2
  368. package/lib/browser-electron/history-store.d.ts +0 -98
  369. package/lib/browser-electron/host-main.d.ts +0 -26
  370. package/lib/browser-electron/http-body.d.ts +0 -24
  371. package/lib/browser-electron/json-reply.d.ts +0 -33
  372. package/lib/browser-electron/maintenance-broker.d.ts +0 -35
  373. package/lib/browser-electron/maintenance-lifecycle.d.ts +0 -32
  374. package/lib/browser-electron/maintenance-route.d.ts +0 -18
  375. package/lib/browser-electron/missing-system-browser.d.ts +0 -54
  376. package/lib/browser-electron/paths.d.ts +0 -4
  377. package/lib/browser-electron/preview-route.d.ts +0 -89
  378. package/lib/browser-electron/process.d.ts +0 -14
  379. package/lib/browser-electron/provider.d.ts +0 -959
  380. package/lib/browser-electron/remote-host.d.ts +0 -256
  381. package/lib/browser-electron/rpc-input.d.ts +0 -4
  382. package/lib/browser-electron/rpc-ops.d.ts +0 -18
  383. package/lib/browser-electron/runtime-diagnostics.d.ts +0 -12
  384. package/lib/browser-electron/runtime-route.d.ts +0 -55
  385. package/lib/browser-electron/runtime-status.d.ts +0 -116
  386. package/lib/browser-electron/settings-route.d.ts +0 -15
  387. package/lib/browser-electron/settings-store.d.ts +0 -224
  388. package/lib/browser-electron/sidebar-only-host.d.ts +0 -36
  389. package/lib/browser-electron/system-browser.d.ts +0 -367
  390. package/lib/browser-electron/timing.d.ts +0 -8
  391. package/lib/browser-electron/virtual-cursor.d.ts +0 -67
  392. package/lib/browser-electron/windows-system.d.ts +0 -3
  393. package/lib/index.d.ts +0 -30
  394. package/lib/tool-browser/element-fields.d.ts +0 -145
  395. package/lib/tool-browser/index.d.ts +0 -53
  396. package/lib/tool-browser/page-probe.d.ts +0 -86
  397. package/scripts/consumer-install-check.mjs +0 -72
  398. package/scripts/run-tests.mjs +0 -32
  399. package/scripts/verify-host-compat.mjs +0 -195
  400. package/scripts/verify-preview-route.mjs +0 -168
  401. package/scripts/verify-runtime-status.mjs +0 -179
@@ -1,882 +1,1299 @@
1
- /**
2
- * Electron browser provider plugin entry: registers the Electron-backed
3
- * `BrowserProvider` with `ctx.browser`. The provider needs a view host (real
4
- * Electron `WebContentsView` objects). When a desktop shell supplies
5
- * `ctx.electronViewHost`, that host is used (embedded, human-machine shared
6
- * view). Otherwise the plugin self-hosts: it spawns its own Electron child
7
- * (`host-main.js`) and drives it over a local TCP JSON-RPC socket, so
8
- * installing the plugin is enough for `dsh_browser_*` tools to work on any
9
- * surface.
10
- * @module dsh-browser/browser-electron
11
- */
12
-
13
- import type { Context } from '@deepseek-ai/cordis'
14
- import type { IncomingMessage, ServerResponse } from 'node:http'
15
- import z from '@deepseek-ai/schemastery'
16
- import type { BrowserRuntime } from '../browser/runtime.js'
17
- import { ElectronBrowserProvider } from './provider.js'
18
- import { provisionElectronInBackground, provisionSnapshot, hasElectronRuntime } from './electron-provision.js'
19
- import type { ElectronBrowserViewHost } from './provider.js'
20
- import type { CarrierLossReason } from '../browser/types.js'
21
- import { randomUUID } from 'node:crypto'
22
- import { existsSync, mkdirSync, renameSync, statSync } from 'node:fs'
23
- import { homedir } from 'node:os'
24
- import { dirname, join } from 'node:path'
25
- import { dshHome } from './paths.js'
26
- import { setTimeout as wait } from 'node:timers/promises'
27
- import { defaultHostMainPath, RemoteElectronViewHost } from './remote-host.js'
28
- import { DesktopBridgeViewHost } from './desktop-bridge-host.js'
29
- import { SidebarOnlyHost } from './sidebar-only-host.js'
30
- import { detectBrowser, searchSummary, SystemBrowserViewHost } from './system-browser.js'
31
- import { claimEphemeralProfile, ephemeralProfileName, sweepAbandonedEphemeralProfiles } from './ephemeral-profile.js'
32
- import { MissingSystemBrowserHost } from './missing-system-browser.js'
33
- import { SettingsStore, settingsPath } from './settings-store.js'
34
- import { sameOrigin } from './settings-route.js'
35
- import { authenticatedRoute, isDirectLoopback, type BrowserConnection, type BrowserHttpHandler } from './authenticated-route.js'
36
- import { handleBridgeStatus, handlePreviewFrame, handlePreviewSessions, BRIDGE_STATUS_ROUTE, PREVIEW_ROUTE, PREVIEW_SESSIONS_ROUTE } from './preview-route.js'
37
- import { findDesktopInstall, readBridgeStatus } from './bridge-status.js'
38
- import { readBridgeEndpoint } from './bridge-endpoint.js'
39
- import { runBridgeAction } from './bridge-install.js'
40
- import { prepareBridgeMaintenance } from './bridge-maintenance.js'
41
- import { commitAutomaticMaintenance, readAutomaticMaintenance, startAutomaticMaintenance } from './automatic-maintenance.js'
42
- import { AUTOMATIC_MAINTENANCE_ROUTE, createAutomaticMaintenanceHandler } from './maintenance-route.js'
43
- import { runWithManualBridgePreference } from './bridge-auto.js'
44
- import { replyJson, writeJsonText } from './json-reply.js'
45
- import { readJsonBody, readTextBody } from './http-body.js'
46
- import { readRuntimeStatus } from './runtime-status.js'
47
- import { handleRuntimeProvision, handleRuntimeStatus, RUNTIME_PROVISION_ROUTE, RUNTIME_STATUS_ROUTE } from './runtime-route.js'
48
-
49
- export {
50
- ELECTRON_BROWSER_PROVIDER_ID,
51
- ElectronBrowserProvider,
52
- } from './provider.js'
53
- export type { ElectronBrowserViewHost, ElectronViewHandle } from './provider.js'
54
- export { RemoteElectronViewHost, defaultHostMainPath } from './remote-host.js'
55
-
56
- /** Cordis plugin name used by loader diagnostics. */
57
- export const name = 'browser-electron'
58
-
59
- /** The browser seam this provider registers into. */
60
- export const inject = ['browser']
61
-
62
- /** Plugin config: an optional externally-supplied view host. */
63
- export interface Config {
64
- /** View host supplied by a desktop shell; absent -> self-host. */
65
- readonly viewHost?: ElectronBrowserViewHost
66
- /** Allow navigation only to HTTP(S) URLs. Default true. */
67
- readonly httpOnly?: boolean
68
- /**
69
- * Directory `dsh_browser_download` save paths must resolve inside (prevents a
70
- * prompt-injected agent from writing arbitrary machine paths). Default:
71
- * the user's Downloads folder; override to confine downloads elsewhere.
72
- */
73
- readonly downloadDir?: string
74
- /** Maximum snapshot elements before truncation. Default 60. */
75
- readonly snapshotMaxElements?: number
76
- /** Maximum content characters before truncation when no maxChars is given. No longer read: the cap is per format (html and json 50 000, otherwise 20 000). */
77
- readonly contentMaxChars?: number
78
- }
79
-
80
- export const Config: z<Config> = z.object({
81
- // Absent on surfaces without a desktop shell; the plugin self-hosts then.
82
- viewHost: z.any(),
83
- httpOnly: z.boolean().default(true),
84
- downloadDir: z.string(),
85
- snapshotMaxElements: z.number(),
86
- contentMaxChars: z.number(),
87
- })
88
-
89
- /**
90
- * This process's session id, read the way DSH's own desktop host reads it.
91
- *
92
- * `dsh-desktop-host/lib/index.js` does `ctx.get('agents')` then `agents.list()`, and uses
93
- * `agent.id` directly as a sessionId. One conversation per process, so the list holds this one.
94
- *
95
- * Returns undefined rather than throwing when the service is absent — an older host, or a
96
- * non-desktop composition. The caller falls back to a random id, which is what the bridge used
97
- * before and is safe: it only means "this process", not "this conversation".
98
- *
99
- * @param ctx - the plugin context.
100
- * @returns the session id, or undefined when it cannot be read.
101
- */
102
- function readSessionId(ctx: unknown): string | undefined {
103
- try {
104
- const surface = ctx as { get?: (name: string) => unknown }
105
- if (typeof surface.get !== 'function') return undefined
106
- const agents = surface.get('agents') as { list?: () => unknown } | undefined
107
- const list = typeof agents?.list === 'function' ? agents.list() : undefined
108
- if (!Array.isArray(list) || list.length === 0) return undefined
109
- const first = list[0] as { id?: unknown } | undefined
110
- return typeof first?.id === 'string' && first.id !== '' ? first.id : undefined
111
- } catch {
112
- return undefined
113
- }
114
- }
115
-
116
- /** Register the Electron browser provider with `ctx.browser`. */
117
- export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config): void {
118
- // Which session is this process serving?
119
- //
120
- // The desktop shell keeps ONE sidebar per conversation — measured: two `[class*=_tabStrip]`
121
- // containers sat in the DOM at once, each carrying its own session id on the React fiber, and
122
- // the invisible one's webview was unloaded. So the bridge CAN tell which sidebar belongs to
123
- // whom; what it lacked was the other half, this process's own identity. Without it, the bridge
124
- // drove "whatever sidebar is on screen" and — measured on the running shell — typed into another
125
- // conversation's address bar and navigated that page.
126
- //
127
- // The identity is available here, and DSH's own desktop host shows how
128
- // (`dsh-desktop-host/lib/index.js`: `ctx.get('agents').list()`, with `agent.id` used directly as
129
- // a sessionId). One conversation per process, so the list holds this one.
130
- const sessionId = readSessionId(ctx)
131
-
132
- // One settings document per plugin instance: the settings panel writes it, the
133
- // provider reads it live, and both ends agree on the same file. The logger is passed so a
134
- // discarded value (a mistyped channel, most of all) is reported instead of being silently
135
- // replaced by the default — "my setting did nothing" and "I misspelled it" must not look alike.
136
- const settings = new SettingsStore(undefined, message => ctx.logger?.warn?.(message))
137
-
138
- const providerConfig = {
139
- httpOnly: config.httpOnly,
140
- downloadDir: config.downloadDir,
141
- snapshotMaxElements: config.snapshotMaxElements,
142
- contentMaxChars: config.contentMaxChars,
143
- settings: () => settings.get(),
144
- }
145
-
146
- // A host supplied by the composition (the desktop shell's own seam) wins and is
147
- // synchronous, so registration stays synchronous on that path.
148
- if (config.viewHost !== undefined) {
149
- const external = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(config.viewHost as ElectronBrowserViewHost, providerConfig))
150
- ctx.effect(() => () => { external() })
151
- // The composition supplied the carrier, so `browser.channel` is not ours to honour on this
152
- // surface. Saying so is the difference between a setting that cannot apply and a setting that
153
- // appears not to have worked — the second is what sends people looking for a bug elsewhere.
154
- const asked = settings.get().browser.channel
155
- if (asked !== 'sidebar' && asked !== 'bundled') {
156
- ctx.logger?.warn?.(
157
- `dsh-builtin-browser: browser.channel is "${asked}", but this surface's carrier was `
158
- + 'supplied by its composition (the desktop shell), which outranks the setting. Set it to '
159
- + '"sidebar" to record the intent, or run on a surface that picks its own carrier.',
160
- )
161
- }
162
- return
163
- }
164
-
165
- // Explicit sidebar selection stays on the desktop's carrier, including while its bridge
166
- // reconnects. Other choices can use the independently hosted browser when appropriate.
167
- const selfHosted = new RemoteElectronViewHost(defaultHostMainPath())
168
- // The self-hosted carrier is the only one that needs Electron, and it is prepared HERE, lazily,
169
- // rather than during package installation (issue #41: a `postinstall` download made a default
170
- // pnpm 11 profile refuse the install outright, and a failed fetch failed the install too).
171
- //
172
- // Non-fatal by construction: this never rejects, never blocks a tool call, and its failure leaves
173
- // the sidebar / Chrome / Edge carriers untouched. Only the two channels that can use the bundled
174
- // runtime are worth the download; an explicit chrome/edge choice is not.
175
- const wantedChannel = settings.get().browser.channel
176
- if (wantedChannel === 'bundled' || wantedChannel === 'auto') {
177
- void provisionElectronInBackground(message => ctx.logger?.info?.(`dsh-builtin-browser: ${message}`))
178
- }
179
- const requiredSidebar = (): SidebarOnlyHost => new SidebarOnlyHost(async () => {
180
- for (const pause of [0, 1_000, 3_000, 8_000]) {
181
- if (pause > 0) await wait(pause)
182
- const sidebar = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet)
183
- if (sidebar !== undefined) return sidebar
184
- if (DesktopBridgeViewHost.refusedIframePanel()) break
185
- }
186
- throw new Error('dsh-builtin-browser: the selected DSH sidebar is not connected. Check or repair the desktop bridge in Browser settings, then retry the same operation.')
187
- })
188
- const initialHost = wantedChannel === 'sidebar' ? requiredSidebar() : selfHosted
189
- let unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(initialHost, providerConfig))
190
- let disposed = false
191
- let carrierChoice = 0
192
- let discovery: AbortController | undefined
193
- /** The carrier an `adopt` installed, so a later choice can release it. */
194
- let adoptedCarrier: ElectronBrowserViewHost | undefined = initialHost === selfHosted ? undefined : initialHost
195
-
196
- ctx.effect(() => () => {
197
- disposed = true
198
- carrierChoice += 1
199
- discovery?.abort()
200
- unregister()
201
- adoptedCarrier?.dispose?.()
202
- selfHosted.dispose()
203
- })
204
-
205
- /**
206
- * Put the self-hosted browser back after an adopted carrier reports that it is gone.
207
- *
208
- * This is the half the startup retries never covered: a bridge that was alive at apply time and
209
- * exited later left every subsequent call dialling a port nobody owns, because the swap happened
210
- * once and only in one direction. Reaching here means the carrier cannot serve anything more, so
211
- * the choice made at startup is no longer a choice — the alternative to falling back is a browser
212
- * surface that does nothing until DSH is restarted.
213
- *
214
- * Two failures arrive here and the message must distinguish them. The first draft announced an
215
- * exiting shell unconditionally, so a fallback caused by an undrivable sidebar panel told the
216
- * user their desktop shell had exited while it was running normally.
217
- * @param adopted - the carrier that reported the loss, disposed once its replacement is in place.
218
- * @param reason - which failure this was; see {@link CarrierLossReason}.
219
- */
220
- const restoreSelfHosted = (adopted: ElectronBrowserViewHost, reason: CarrierLossReason): void => {
221
- // A replaced carrier may finish an outstanding request after the new choice is installed.
222
- if (disposed || adoptedCarrier !== adopted) return
223
- try {
224
- const sidebarSelected = settings.get().browser.channel === 'sidebar'
225
- const restored = sidebarSelected ? requiredSidebar() : new RemoteElectronViewHost(defaultHostMainPath())
226
- unregister()
227
- unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(restored, providerConfig))
228
- adoptedCarrier = restored
229
- ctx.logger?.warn?.(
230
- sidebarSelected
231
- ? 'dsh-builtin-browser: the selected DSH sidebar connection was lost; the next operation will reconnect to the sidebar.'
232
- : reason === 'shell-exited'
233
- ? 'dsh-builtin-browser: the desktop shell backed the sidebar browser and has exited, so the '
234
- + 'browser this plugin hosts itself takes over. Pages from the sidebar are gone with it; '
235
- + 'open the page again.'
236
- : 'dsh-builtin-browser: this desktop shell renders the sidebar browser panel in a way that '
237
- + 'cannot be driven (no webContents, so no CDP endpoint), so the browser this plugin hosts '
238
- + 'itself takes over. The shell is still running and nothing else is affected; the page '
239
- + 'opens in this plugin\'s own window. Set browser.channel to another value to silence this.',
240
- )
241
- } catch (error) {
242
- // Nothing better is available: the adopted carrier is gone and a provider that throws is
243
- // worse than one that explains.
244
- ctx.logger?.warn?.(`dsh-builtin-browser: could not fall back to the self-hosted browser: ${String(error)}`)
245
- } finally {
246
- // Disposed on a LATER turn of the event loop, deliberately.
247
- //
248
- // Disposing synchronously here closes the bridge socket while the request that triggered this
249
- // fallback is still settling, and the close rejects every call still waiting on that socket —
250
- // so the caller received "bridge closed" instead of the reason it actually failed for. The
251
- // fallback is what the user is supposed to be able to understand; replacing its explanation
252
- // with one about the connection loses exactly the information this path exists to convey.
253
- setImmediate(() => {
254
- try {
255
- adopted.dispose?.()
256
- } catch {
257
- // A carrier that cannot be released is not the caller's problem; the swap already happened.
258
- }
259
- })
260
- }
261
- }
262
-
263
- /**
264
- * Swap the provider to another carrier, releasing the previous one.
265
- * @param host - the carrier to adopt.
266
- * @param note - a one-line description for the log.
267
- */
268
- const adopt = (host: ElectronBrowserViewHost, note: string, choice = carrierChoice): void => {
269
- if (disposed || choice !== carrierChoice) {
270
- try { host.dispose?.() } catch { /* a stale result must not escape its retry */ }
271
- return
272
- }
273
- // This guard used to make the FIRST choice final, disposing anything that arrived later. That
274
- // is right against two carriers racing in, and exactly wrong for a user changing the setting:
275
- // `chooseCarrier` runs again on purpose, and a refusal here is indistinguishable from the
276
- // write having done nothing. The previous carrier is now released by the replacement instead.
277
- const previous = adoptedCarrier
278
- try {
279
- unregister()
280
- unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(host, providerConfig))
281
- selfHosted.dispose()
282
- adoptedCarrier = host
283
- ctx.logger?.info?.(`dsh-builtin-browser: ${note}`)
284
- // A borrowed carrier can lose the process behind it, and this is the only notification that
285
- // will ever arrive. Registering AFTER the swap succeeded means a listener can never fire
286
- // against a provider that was never installed.
287
- if (!(host instanceof SidebarOnlyHost)) host.onLost?.(reason => { restoreSelfHosted(host, reason) })
288
- // Released AFTER the replacement is installed, so the surface is never without a provider.
289
- if (previous !== undefined && previous !== host) {
290
- try { previous.dispose?.() } catch { /* the replacement is already serving */ }
291
- }
292
- } catch (error) {
293
- // Never leave the surface without a provider. The half-built host is disposed FIRST: an
294
- // adopt that got as far as constructing it may already hold a socket, a listener or a child
295
- // process, and dropping it on the floor is how a failed upgrade becomes a leak that only
296
- // shows up as a stray Electron in the task manager.
297
- try { host.dispose?.() } catch { /* the fallback below matters more than this */ }
298
- // The fallback registration gets its own guard, because THIS is the path taken when the
299
- // context is already gone — and then `ctx.browser` throws `cannot get required service
300
- // "browser" in inactive context`. Unguarded, that second throw escaped the async retry
301
- // that calls `adopt`, became an unhandled rejection, and killed the host process with
302
- // exit code 1: a failed upgrade, which should only ever cost a warning, took the whole
303
- // session down instead. Observed 2026-10-05 (crash-…-host.log, phase: running).
304
- try {
305
- const fallback = settings.get().browser.channel === 'sidebar' ? requiredSidebar() : new RemoteElectronViewHost(defaultHostMainPath())
306
- unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(fallback, providerConfig))
307
- adoptedCarrier = fallback
308
- if (previous !== undefined && previous !== host) {
309
- try { previous.dispose?.() } catch { /* fallback is already serving */ }
310
- }
311
- ctx.logger?.warn?.(`dsh-builtin-browser: could not adopt ${note} (${String(error)})`)
312
- } catch (fallbackError) {
313
- ctx.logger?.warn?.(
314
- `dsh-builtin-browser: could not adopt ${note} (${String(error)}), and the fallback `
315
- + `registration also failed (${String(fallbackError)}) — no browser provider is `
316
- + 'registered for this context')
317
- }
318
- }
319
- }
320
-
321
- /**
322
- * Choose and install the carrier that `browser.channel` names RIGHT NOW.
323
- *
324
- * A function rather than straight-line code because the setting is read live everywhere else:
325
- * the settings route writes the file and the provider picks the change up on its next call, so a
326
- * channel that could only be honoured at apply time was the one setting whose write silently did
327
- * nothing. Re-entrant by design — changing the channel means replacing the carrier, which is
328
- * exactly what a second call does.
329
- */
330
- const chooseCarrier = (): void => {
331
- if (disposed) return
332
- const choice = ++carrierChoice
333
- discovery?.abort()
334
- const controller = new AbortController()
335
- discovery = controller
336
- const { signal } = controller
337
- // A browser the user explicitly asked for outranks every automatic choice: the
338
- // whole point of the setting is that they know which browser they want. It is
339
- // launched with a plugin-owned profile, so their own windows are untouched.
340
- //
341
- // Registration is INERT: constructing the host starts nothing. The browser only
342
- // launches when a command actually needs a page, so merely running DSH never
343
- // spawns a browser window. (An earlier version launched it here, which meant a
344
- // browser appeared the moment the plugin loaded — reported and fixed.)
345
- const channel = settings.get().browser.channel
346
- // Naming a browser is a decision about which one to use, so it also decides whether the
347
- // desktop sidebar may take over. Skipping discovery for an explicit choice is what makes
348
- // that choice real — otherwise a user who picked Chrome would silently get the sidebar,
349
- // and a user who picked a browser that is not installed would never see the explanation
350
- // written for exactly that case, because the sidebar would quietly replace it.
351
- const explicitChoice: boolean = channel !== 'bundled' && channel !== 'auto' && channel !== 'sidebar'
352
- if (channel === 'sidebar') {
353
- if (!(adoptedCarrier instanceof SidebarOnlyHost)) adopt(requiredSidebar(), 'using only the selected DSH sidebar', choice)
354
- return
355
- }
356
- if (channel !== 'bundled') {
357
- const detected = detectBrowser(channel)
358
- if (detected === undefined) {
359
- // `auto` promises to take whatever is available, so falling back is what it
360
- // asked for. Naming a browser is a specific request, and quietly satisfying it
361
- // with a different one turns the real problem ("no Chrome here") into a
362
- // confusing error about Electron later on. Report it instead.
363
- if (channel === 'auto') {
364
- ctx.logger?.warn?.('dsh-builtin-browser: no installed browser was found; using the bundled browser')
365
- if (adoptedCarrier !== undefined) {
366
- adopt(new RemoteElectronViewHost(defaultHostMainPath()), 'using the bundled browser', choice)
367
- }
368
- } else {
369
- adopt(new MissingSystemBrowserHost(channel, searchSummary(channel)),
370
- `the selected ${channel} is not installed — commands will explain how to fix it`)
371
- }
372
- } else {
373
- // Same profile root as settings-store, history-store and desktop-bridge-host: the
374
- // `?.dsh` component used to be missing HERE only, so a desktop launched from a
375
- // shortcut (no DSH_HOME in the environment) put its browser profile in
376
- // `C:\Users\<user>\dsh-builtin-browser-host\` while its settings and history lived in
377
- // `~/.dsh/dsh-builtin-browser-host/` — two half-profiles that never met, and a
378
- // settings panel whose switches appeared not to apply.
379
- const home = dshHome()
380
- // Login state lives in the browser profile, so the cookies setting decides where
381
- // that profile goes: a stable directory keeps the user signed in across restarts
382
- // (the point of using their own browser), while turning persistence off gets a
383
- // throwaway directory that is removed when the browser is released.
384
- const persist = settings.get().cookies.persist
385
- const profileRoot = join(home, BROWSER_PROFILE_DIR)
386
- adoptLegacyProfileRoot(profileRoot)
387
- const profileDir = persist
388
- ? join(profileRoot, `${detected.kind}-profile`)
389
- : join(profileRoot, ephemeralProfileName(detected.kind, randomUUID()))
390
- if (!persist) {
391
- // A process killed outright never runs its own cleanup (see ephemeral-profile.ts),
392
- // so the sweep happens HERE — at the only moment that can still act on a profile
393
- // whose owner is gone — and before this run claims a directory of its own.
394
- sweepAbandonedEphemeralProfiles(profileRoot, detected.kind)
395
- claimEphemeralProfile(profileDir)
396
- }
397
- // The headless mode rides along so a display-less host (systemd, container, SSH-only server)
398
- // still gets a working browser instead of "exited immediately after launch" — issue #32.
399
- adopt(new SystemBrowserViewHost(detected, profileDir, [], persist ? undefined : profileDir,
400
- undefined, settings.get().browser.headless, () => settings.get().ui.quiet),
401
- `will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`)
402
- }
403
- } else if (adoptedCarrier !== undefined) {
404
- // The original self-hosted carrier was disposed by the first adoption. Switching back
405
- // must install a new one, even when no sidebar is found during the discovery below.
406
- adopt(new RemoteElectronViewHost(defaultHostMainPath()), 'using the bundled browser', choice)
407
- }
408
-
409
- // An explicit choice was already adopted above; discovering the sidebar here would
410
- // replace it, which is exactly what this guard prevents.
411
- //
412
- // Explicit sidebar selection was handled above by its reconnectable sidebar-only host.
413
- if (explicitChoice) return
414
-
415
- // The shell may not be up yet. `dsh web` starts before — or entirely without — the desktop app
416
- // that hosts the bridge, and a one-shot discovery meant a bridge that appeared a second later
417
- // was never adopted for the rest of the process's life. Retry a handful of times over roughly
418
- // half a minute, then stop: this is a convenience, not a promise, and the session the user is
419
- // already driving in the self-hosted window is not worth replacing minutes into their work.
420
- // Each attempt belongs to this choice. A later settings write or teardown cancels its waits,
421
- // and an endpoint returned by an already-running discovery is disposed instead of installed.
422
- void (async () => {
423
- for (const delay of [0, 2_000, 5_000, 15_000]) {
424
- if (delay > 0) {
425
- try { await wait(delay, undefined, { signal }) } catch { return }
426
- }
427
- if (signal.aborted || disposed) return
428
- let sidebar: Awaited<ReturnType<typeof DesktopBridgeViewHost.discover>>
429
- try {
430
- sidebar = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet)
431
- } catch {
432
- sidebar = undefined // discovery is documented not to throw; never let it stop the retries
433
- }
434
- if (signal.aborted || disposed) {
435
- try { sidebar?.dispose?.() } catch { /* the choice no longer owns this result */ }
436
- return
437
- }
438
- if (sidebar === undefined) continue
439
- adopt(sidebar, 'driving the desktop sidebar browser', choice)
440
- return
441
- }
442
- // A bridge exists but its sidebar panel is an iframe. Saying nothing here would leave the user
443
- // with a second browser window on a machine where they just followed the instructions to
444
- // install the bridge, and no way to know the two facts are related. The carrier is not
445
- // unavailable by accident: an iframe has no CDP endpoint, so adopting it would fail every call
446
- // instead of falling back — see DesktopBridgeViewHost.discover.
447
- if (DesktopBridgeViewHost.refusedIframePanel()) {
448
- ctx.logger?.warn?.(
449
- 'dsh-builtin-browser: a desktop bridge is installed, but this shell renders the sidebar '
450
- + 'browser panel as an iframe rather than a webview, which exposes no CDP endpoint and '
451
- + 'cannot be driven. Using the browser this plugin hosts itself instead — that is the '
452
- + 'independent window, not the sidebar. A shell that exposes `dshDesktop.browser` and '
453
- + 'enables `webviewTag` would provide a drivable panel.',
454
- )
455
- return
456
- }
457
- })()
458
- }
459
-
460
- chooseCarrier()
461
-
462
- // Wired AFTER the chooser exists, because the handler re-runs it: a settings write that changes
463
- // `browser.channel` is a request to switch carriers, and answering `ok` without switching is the
464
- // one thing a caller cannot tell apart from a write that worked.
465
- /**
466
- * Expose the live-view frame endpoint on the host's web server (issue #34).
467
- *
468
- * Registered exactly like the settings route and skipped the same way when a surface has no web
469
- * server: a CLI session simply has no viewer, which is not a plugin-startup failure. The endpoint
470
- * is inert until the host turns `remoteView.enabled` on, and it refuses a request whose session the
471
- * plugin never handed out.
472
- * @param ctx - the plugin context.
473
- * @param settings - the settings document, for the share switch.
474
- */
475
- function installPreviewRoute(ctx: Context, settings: SettingsStore): void {
476
- const injectPreview = (ctx as unknown as {
477
- inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
478
- }).inject
479
- if (typeof injectPreview !== 'function') return
480
- try {
481
- injectPreview(['webServer', 'browser'], (host) => {
482
- const browser = (ctx as unknown as { browser?: PreviewBrowser }).browser
483
- if (browser === undefined) return
484
- host.effect(() => host.webServer.register({
485
- kind: 'exact',
486
- path: PREVIEW_ROUTE,
487
- handler: authenticated(ctx, (request, response) => handlePreviewFrame(request, response, settings, browser)),
488
- }, 'dsh-builtin-browser: live view frame'))
489
- // The list the panel needs before it can build a frame URL at all: session ids only.
490
- host.effect(() => host.webServer.register({
491
- kind: 'exact',
492
- path: PREVIEW_SESSIONS_ROUTE,
493
- handler: authenticated(ctx, (request, response) => handlePreviewSessions(request, response, settings, browser)),
494
- }, 'dsh-builtin-browser: live view sessions')) })
495
- } catch {
496
- // No web server on this surface: watching is simply unavailable, and nothing else changes.
497
- }
498
- }
499
-
500
- /**
501
- * Expose the bridge's install state on the host's web server, for the settings panel.
502
- *
503
- * Separate from the live-view routes because it needs no browser service: it reads the install
504
- * tree, which is on disk and independent of any carrier. A surface without a web server skips it,
505
- * exactly like the other two.
506
- * @param ctx - the plugin context.
507
- */
508
- /** Where the panel asks to install or remove the bridge. */
509
- const BRIDGE_ACTION_ROUTE = '/dsh-builtin-browser/bridge-action'
510
- let bridgeActionRunning = false
511
-
512
- /**
513
- * Prepare external maintenance while Desktop remains open, or execute file maintenance from
514
- * an independent local host after Desktop has exited.
515
- * @param request - the incoming request (POST, JSON body `{action, prepare?}`).
516
- * @param response - the response to write.
517
- */
518
- async function handleBridgeAction(request: IncomingMessage, response: ServerResponse): Promise<void> {
519
- if (request.method !== 'POST') { replyJson(response, 405, { error: 'method-not-allowed' }); return }
520
- // Both creating a local launcher and changing installation files require write admission.
521
- if (!sameOrigin(request, true)) { replyJson(response, 403, { error: 'not-same-origin' }); return }
522
- if (!isDirectLoopback(request)) { replyJson(response, 403, { error: 'local-request-required' }); return }
523
- let action: unknown
524
- let preparationOnly = false
525
- try {
526
- const input = await readJsonBody<{ action?: unknown; prepare?: unknown }>(request)
527
- action = input.action
528
- if (input.prepare !== undefined && typeof input.prepare !== 'boolean') throw new Error('prepare must be a boolean')
529
- preparationOnly = input.prepare === true
530
- } catch (error) {
531
- replyJson(response, 400, { ok: false, error: `unreadable body: ${String(error)}` })
532
- return
533
- }
534
- if (action !== 'install' && action !== 'uninstall') {
535
- replyJson(response, 400, { ok: false, error: 'action must be "install" or "uninstall"' })
536
- return
537
- }
538
- const root = findDesktopInstall()
539
- if (root === undefined) {
540
- // Nothing to patch: say so instead of running an installer against a guess.
541
- replyJson(response, 409, { ok: false, error: 'no DSH Desktop install was found on this machine' })
542
- return
543
- }
544
- if (bridgeActionRunning) {
545
- replyJson(response, 409, { ok: false, error: 'bridge-action-in-progress' })
546
- return
547
- }
548
- const active = readAutomaticMaintenance()
549
- if (!preparationOnly && active !== undefined && !['completed', 'failed', 'cancelled'].includes(active.phase)) {
550
- replyJson(response, 409, { ok: false, error: 'an automatic bridge maintenance job is in progress' })
551
- return
552
- }
553
- bridgeActionRunning = true
554
- try {
555
- if (preparationOnly) {
556
- const result = await prepareBridgeMaintenance(action, root)
557
- replyJson(response, 200, { ...result, action })
558
- return
559
- }
560
- const result = await runWithManualBridgePreference(action, patch => settings.update(patch), () => runBridgeAction(action, root))
561
- replyJson(response, 200, { ...result, action })
562
- } catch (error) {
563
- if (preparationOnly) {
564
- replyJson(response, 500, { ok: false, error: `could not prepare bridge maintenance: ${String(error)}` })
565
- return
566
- }
567
- replyJson(response, 500, { ok: false, error: String(error instanceof Error ? error.message : error) })
568
- } finally {
569
- bridgeActionRunning = false
570
- }
571
- }
572
-
573
- function installBridgeStatusRoute(ctx: Context): void {
574
- const injectStatus = (ctx as unknown as {
575
- inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
576
- }).inject
577
- if (typeof injectStatus !== 'function') return
578
- try {
579
- injectStatus(['webServer'], (host) => {
580
- const automaticMaintenance = createAutomaticMaintenanceHandler({
581
- supported: () => process.platform === 'win32',
582
- busy: () => bridgeActionRunning,
583
- read: () => readAutomaticMaintenance(),
584
- commit: async id => { await commitAutomaticMaintenance(id) },
585
- start: async (action, options) => {
586
- const root = findDesktopInstall()
587
- if (root === undefined) throw new Error('no verified DSH Desktop installation was found')
588
- return await runWithManualBridgePreference(action, patch => settings.update(patch),
589
- async () => await startAutomaticMaintenance(action, root, options))
590
- },
591
- })
592
- host.effect(() => host.webServer.register({
593
- kind: 'exact', path: AUTOMATIC_MAINTENANCE_ROUTE,
594
- handler: authenticated(ctx, automaticMaintenance),
595
- }, 'dsh-builtin-browser: explicit automatic bridge maintenance'))
596
- host.effect(() => host.webServer.register({
597
- kind: 'exact',
598
- path: BRIDGE_STATUS_ROUTE,
599
- handler: authenticated(ctx, (request, response) => handleBridgeStatus(request, response)),
600
- }, 'dsh-builtin-browser: bridge status'))
601
- // The panel prepares a launcher without changing the running Desktop. Direct local
602
- // maintenance remains available once Desktop has exited.
603
- host.effect(() => host.webServer.register({
604
- kind: 'exact',
605
- path: BRIDGE_ACTION_ROUTE,
606
- handler: authenticated(ctx, (request, response) => handleBridgeAction(request, response)),
607
- }, 'dsh-builtin-browser: bridge action'))
608
- })
609
- } catch {
610
- // No web server: the panel is unreachable, and the installer stays the interface.
611
- }
612
- }
613
-
614
- installSettingsRoute(ctx, settings, () => { chooseCarrier() })
615
-
616
- // Bridge maintenance is explicit and requires DSH Desktop to be closed. Loading a provider
617
- // never starts an installer, including with an older settings file's bridge.autoInstall=true.
618
-
619
- /**
620
- * Expose readiness — "can the browser serve a call right now" — for the settings panel.
621
- *
622
- * The panel had switches for every behaviour and no answer to the one question a new install
623
- * raises: the bundled runtime is downloaded on first need (issue #41 moved it out of `postinstall`
624
- * for good reasons), so for the first minute of a fresh install the honest state is "preparing",
625
- * and until this route existed that state was a log line no panel could read. Both readings are
626
- * cheap and side-effect free: a path probe for the runtime, an install-tree inspection for the
627
- * bridge — the same two the launch path and the bridge-status route already use.
628
- *
629
- * Skipped, like its siblings, on a surface with no web server: a CLI has no panel to show it to.
630
- * @param ctx - the plugin context.
631
- * @param settings - the settings document, for the channel being honoured.
632
- */
633
- function installRuntimeStatusRoute(ctx: Context, settings: SettingsStore): void {
634
- const injectRuntime = (ctx as unknown as {
635
- inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
636
- }).inject
637
- if (typeof injectRuntime !== 'function') return
638
- const deps = {
639
- report: () => readRuntimeStatus({
640
- channel: () => settings.get().browser.channel,
641
- selectedCarrier: () => adoptedCarrier instanceof DesktopBridgeViewHost || adoptedCarrier instanceof SidebarOnlyHost ? 'sidebar'
642
- : adoptedCarrier instanceof SystemBrowserViewHost ? 'system' : 'bundled',
643
- hasBinary: hasElectronRuntime,
644
- provision: provisionSnapshot,
645
- bridge: () => {
646
- const root = findDesktopInstall()
647
- return root === undefined ? undefined : readBridgeStatus(root)
648
- },
649
- // Installed is not running: the install tree survives a reboot, the endpoint does not. Both
650
- // readings are cheap and side-effect free — a file read and a signal-0 pid check.
651
- endpoint: () => readBridgeEndpoint(),
652
- }),
653
- // `force` is what makes the panel's retry button mean anything: without it the answer would be
654
- // the settled failure the user is trying to replace. An attempt still running is joined.
655
- provision: () => {
656
- void provisionElectronInBackground(
657
- message => ctx.logger?.info?.(`dsh-builtin-browser: ${message}`),
658
- undefined,
659
- { force: true },
660
- )
661
- return provisionSnapshot()
662
- },
663
- }
664
- try {
665
- injectRuntime(['webServer'], (host) => {
666
- host.effect(() => host.webServer.register({
667
- kind: 'exact',
668
- path: RUNTIME_STATUS_ROUTE,
669
- handler: authenticated(ctx, (request, response) => handleRuntimeStatus(request, response, deps)),
670
- }, 'dsh-builtin-browser: runtime status'))
671
- host.effect(() => host.webServer.register({
672
- kind: 'exact',
673
- path: RUNTIME_PROVISION_ROUTE,
674
- handler: authenticated(ctx, (request, response) => handleRuntimeProvision(request, response, deps)),
675
- }, 'dsh-builtin-browser: runtime provision'))
676
- })
677
- } catch {
678
- // No web server: the panel is unreachable, and the readiness report has no reader.
679
- }
680
- }
681
-
682
- /**
683
- * Re-run the carrier choice when the settings FILE changes on disk.
684
- *
685
- * The route above covers a write through the panel. It does not cover a person editing
686
- * `settings.json` by hand — and that is how `browser.channel` gets changed when the panel is
687
- * unreachable or the user prefers the file. Measured: the document said `sidebar` and the plugin
688
- * kept driving the self-hosted window built for the previous choice, because nothing re-read it.
689
- *
690
- * Change detection is on the channel alone, not the mtime: a poll that re-chose the carrier on
691
- * every unrelated save would tear down and rebuild a working browser session for a switch that
692
- * cannot affect it. mtime is only the cheap trigger to go and look.
693
- */
694
- const watchSettingsFile = (): void => {
695
- const file = settingsPath()
696
- let lastChannel = settings.get().browser.channel
697
- let lastMtime = 0
698
- try { lastMtime = statSync(file).mtimeMs } catch { /* not written yet */ }
699
- const timer = setInterval(() => {
700
- if (disposed) { clearInterval(timer); return }
701
- let mtime = 0
702
- try { mtime = statSync(file).mtimeMs } catch { return }
703
- if (mtime === lastMtime) return
704
- lastMtime = mtime
705
- const channel = settings.get().browser.channel
706
- if (channel === lastChannel) return
707
- lastChannel = channel
708
- ctx.logger?.info?.(`dsh-builtin-browser: settings changed on disk, re-choosing the carrier for channel "${channel}"`)
709
- chooseCarrier()
710
- }, 5_000)
711
- // Unref-ed so a poll never holds the process open.
712
- timer.unref?.()
713
- ctx.effect(() => () => { clearInterval(timer) }, "dsh-builtin-browser: settings file watch")
714
- }
715
- watchSettingsFile()
716
- installPreviewRoute(ctx, settings)
717
- installBridgeStatusRoute(ctx)
718
- installRuntimeStatusRoute(ctx, settings)
719
- }
720
-
721
- /** Route the settings panel reads and writes. */
722
- const SETTINGS_ROUTE = '/dsh-builtin-browser/settings'
723
-
724
- /**
725
- * The directory under the DSH home that holds this plugin's browser profile.
726
- *
727
- * Named once, because every consumer of it must agree: `settingsPath()` and the history
728
- * store resolve their own copy from `$DSH_HOME`, and a profile written under a different
729
- * root than the settings document is a pair that silently never meets.
730
- */
731
- const BROWSER_PROFILE_DIR = 'dsh-builtin-browser-host'
732
-
733
- /**
734
- * Move a browser profile left behind by the old layout into the directory the plugin uses now.
735
- *
736
- * Before the `?.dsh` component was added here, a desktop launched from a shortcut (no `DSH_HOME`
737
- * in the environment) put its browser profile in `<homedir>/dsh-builtin-browser-host/` while its
738
- * settings and history lived in `<homedir>/.dsh/dsh-builtin-browser-host/`. Login state lives
739
- * INSIDE the browser profile, so leaving the old directory behind silently signs the user out of
740
- * everything they had signed into — reported after the fix shipped, as a one-time cost of it.
741
- *
742
- * That cost does not have to be paid. The move happens only when the new location is absent, so a
743
- * profile in use is never overwritten, and every failure — a cross-device rename, a permission
744
- * problem, a profile another process holds — falls through to an empty profile, which is exactly
745
- * what would have happened without this function. The old directory is then left untouched rather
746
- * than deleted, because a half-moved profile is worse than a stale one.
747
- *
748
- * @param profileRoot - the root the plugin resolves today (`<DSH_HOME>/dsh-builtin-browser-host`).
749
- * @param legacyRoot - the pre-`DSH_HOME` layout's root. Injected so the move can be exercised
750
- * without touching the real home directory.
751
- */
752
- export function adoptLegacyProfileRoot(
753
- profileRoot: string,
754
- legacyRoot: string = join(homedir(), BROWSER_PROFILE_DIR),
755
- ): void {
756
- try {
757
- if (legacyRoot === profileRoot) return
758
- if (!existsSync(legacyRoot) || existsSync(profileRoot)) return
759
- // `renameSync` needs the destination's PARENT to exist, and on a fresh install it does not:
760
- // the old layout never created `.dsh` at all. Creating it is harmless if it is already there.
761
- mkdirSync(dirname(profileRoot), { recursive: true })
762
- renameSync(legacyRoot, profileRoot)
763
- } catch {
764
- // Nothing here is worth failing an apply over; the fallback is the pre-existing behaviour.
765
- }
766
- }
767
-
768
- /** What the frame route needs from the browser service. */
769
- interface PreviewBrowser {
770
- exists(session: string): boolean
771
- capturePassive(session: string, signal?: AbortSignal): Promise<{ readonly dataUrl: string }>
772
- watchableSessions?(): readonly string[]
773
- }
774
-
775
- /** Bind the host's signed browser-session authentication to a plugin route. */
776
- function authenticated(ctx: Context, handler: BrowserHttpHandler): BrowserHttpHandler {
777
- return authenticatedRoute(() => {
778
- const surface = ctx as unknown as { get(name: string): BrowserConnection | undefined }
779
- return surface.get('connection')
780
- }, handler)
781
- }
782
-
783
- /** The host web-server surface this plugin uses, described structurally. */
784
- interface WebServerHost {
785
- readonly webServer: {
786
- register(
787
- spec: {
788
- readonly kind: 'exact'
789
- readonly path: string
790
- readonly handler: (request: IncomingMessage, response: ServerResponse) => void | Promise<void>
791
- },
792
- label?: string,
793
- ): () => void
794
- }
795
- effect(callback: () => (() => void) | void): void
796
- }
797
-
798
- /**
799
- * Expose the settings document over the host's web server, which is how the
800
- * settings panel reads and writes it. A host without that service (headless /
801
- * CLI surfaces) simply skips this: the panel is then unreachable and the file
802
- * stays hand-editable — never a plugin-startup failure.
803
- * @param ctx - the plugin context.
804
- * @param settings - the settings document to expose.
805
- */
806
- function installSettingsRoute(
807
- ctx: Context,
808
- settings: SettingsStore,
809
- onChannelChange?: () => void,
810
- ): void {
811
- const inject = (ctx as unknown as {
812
- inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
813
- }).inject
814
- if (typeof inject !== 'function') return
815
- try {
816
- inject(['webServer'], (host) => {
817
- host.effect(() => host.webServer.register({
818
- kind: 'exact',
819
- path: SETTINGS_ROUTE,
820
- handler: authenticated(ctx, (request, response) => handleSettingsRequest(request, response, settings, onChannelChange)),
821
- }, 'dsh-builtin-browser: settings'))
822
- })
823
- } catch {
824
- // No web server on this surface: the settings file remains the interface.
825
- }
826
- }
827
-
828
- /**
829
- * One settings round-trip: `GET` reads the document, `PUT`/`POST` merges a
830
- * partial patch into it. Admission lives in `settings-route.ts` so it can be tested.
831
- * @param request - the incoming request.
832
- * @param response - the response to write.
833
- * @param settings - the settings document.
834
- * @param onChannelChange - re-runs the carrier choice when this write changed `browser.channel`.
835
- */
836
- async function handleSettingsRequest(
837
- request: IncomingMessage,
838
- response: ServerResponse,
839
- settings: SettingsStore,
840
- onChannelChange?: () => void,
841
- ): Promise<void> {
842
- const json = (status: number, body: unknown): void => {
843
- writeJsonText(response, status, JSON.stringify(body), {
844
- 'content-type': 'application/json; charset=utf-8',
845
- 'cache-control': 'no-store',
846
- })
847
- }
848
- const method = request.method ?? 'GET'
849
- if (!sameOrigin(request, method !== 'GET')) {
850
- json(403, { ok: false, error: 'cross-origin request refused' })
851
- return
852
- }
853
- if (method === 'GET') {
854
- json(200, { ok: true, settings: settings.get(), path: settings.path() })
855
- return
856
- }
857
- if (method !== 'PUT' && method !== 'POST') {
858
- response.writeHead(405, { allow: 'GET, PUT' })
859
- response.end()
860
- return
861
- }
862
- try {
863
- const text = await readTextBody(request)
864
- const patch: unknown = text.trim() === '' ? {} : JSON.parse(text)
865
- const before = settings.get().browser.channel
866
- const updated = settings.update(patch)
867
- // A changed `browser.channel` is a request to switch carriers, not just a value to store. The
868
- // choice is re-run here so the write takes effect now — and the response says so, because a
869
- // caller that cannot tell "applied" from "stored for later" has no way to know what it got,
870
- // which is exactly how a write that did nothing read as a success.
871
- const channelChanged = updated.browser.channel !== before
872
- if (channelChanged) onChannelChange?.()
873
- json(200, {
874
- ok: true,
875
- settings: updated,
876
- ...channelChanged ? { carrierRechosen: true } : {},
877
- })
878
- } catch (error) {
879
- json(400, { ok: false, error: `invalid settings patch: ${String(error)}` })
880
- }
881
- }
882
-
1
+ import { referenceCaptureMessages, referenceCaptureErrors } from '../../assets/browser-messages.mjs'
2
+ import { BROWSER_PROFILE_DIR, SETTINGS_ROUTE, EXTENSION_INSTALL_ROUTE } from '../../assets/browser-policy.mjs'
3
+ /**
4
+ * Electron browser provider plugin entry: registers the Electron-backed
5
+ * `BrowserProvider` with `ctx.browser`. The provider needs a view host (real
6
+ * Electron `WebContentsView` objects). When a desktop shell supplies
7
+ * `ctx.electronViewHost`, that host is used (embedded, human-machine shared
8
+ * view). Otherwise it requires a reconnectable sidebar carrier. Only explicitly
9
+ * selected Chrome or Edge may launch an external browser.
10
+ * @module dsh-browser/browser-electron
11
+ */
12
+
13
+ import type { Context } from '@deepseek-ai/cordis'
14
+ import type { IncomingMessage, ServerResponse } from 'node:http'
15
+ import { fileURLToPath } from 'node:url'
16
+ import { statSync } from 'node:fs'
17
+ import z from '@deepseek-ai/schemastery'
18
+ import type { BrowserRuntime } from '../browser/runtime.ts'
19
+ import { ElectronBrowserProvider } from './provider.ts'
20
+ import { provisionElectronInBackground, provisionSnapshot, hasElectronRuntime } from './electron-provision.ts'
21
+ import type { ElectronBrowserViewHost } from './provider.ts'
22
+ import type { CarrierLossReason } from '../browser/types.ts'
23
+ import { randomUUID } from 'node:crypto'
24
+ import { existsSync, mkdirSync, renameSync } from 'node:fs'
25
+ import { homedir } from 'node:os'
26
+ import { dirname, join } from 'node:path'
27
+ import { dshHome } from './paths.ts'
28
+ import { setTimeout as wait } from 'node:timers/promises'
29
+ import { DesktopBridgeViewHost } from './desktop-bridge-host.ts'
30
+ import { SidebarOnlyHost } from './sidebar-only-host.ts'
31
+ import { ExtensionBrowserViewHost, extensionInstallHelp } from './extension-browser.ts'
32
+ import { PreferredBrowserViewHost } from './preferred-browser.ts'
33
+ import { nativeRegistration, installExtension, registrationStatus, probeExtension } from './extension-setup.ts'
34
+ import { registerCarrierTakeover } from '../browser/takeover-target.ts'
35
+ import { detectBrowser, searchSummary, SystemBrowserViewHost } from './system-browser.ts'
36
+ import { claimEphemeralProfile, ephemeralProfileName, sweepAbandonedEphemeralProfiles } from './ephemeral-profile.ts'
37
+ import { MissingSystemBrowserHost } from './missing-system-browser.ts'
38
+ import { SettingsStore, settingsPath } from './settings-store.ts'
39
+ import { sameOrigin } from './settings-route.ts'
40
+ import { authenticatedRoute, pairedRoute, isDirectLoopback, type BrowserConnection, type BrowserPairingConnection, type BrowserHttpHandler } from './authenticated-route.ts'
41
+ import { overlayScript } from '../browser-reference/entry.ts'
42
+ import { getLastOpen } from './open-slot.ts'
43
+ import { GUEST_ROUTE, handleGuest } from './guest-route.ts'
44
+ import { resolveSessionHandle, sessionWireId } from '../browser/handles.ts'
45
+ import { handleBridgeStatus, handlePreviewFrame, handlePreviewSessions, BRIDGE_STATUS_ROUTE, PREVIEW_ROUTE, PREVIEW_SESSIONS_ROUTE } from './preview-route.ts'
46
+ import { findDesktopInstall, readBridgeStatus } from './bridge-status.ts'
47
+ import { readHostExtensionStatus } from './profile-extension.ts'
48
+ import { readBridgeEndpoint } from './bridge-endpoint.ts'
49
+ import { runBridgeAction } from './bridge-install.ts'
50
+ import { prepareBridgeMaintenance } from './bridge-maintenance.ts'
51
+ import { automaticMaintenanceSupported, commitAutomaticMaintenance, readAutomaticMaintenance, startAutomaticMaintenance } from './automatic-maintenance.ts'
52
+ import { AUTOMATIC_MAINTENANCE_ROUTE, createAutomaticMaintenanceHandler } from './maintenance-route.ts'
53
+ import { HOST_PATCH_ROUTE, createHostPatchMaintenance, servedClientModules } from './host-patch-maintenance.ts'
54
+ import { runWithManualBridgePreference } from './bridge-auto.ts'
55
+ import { replyJson, writeJsonText } from './json-reply.ts'
56
+ import { readJsonBody, readTextBody } from './http-body.ts'
57
+ import { readRuntimeStatus } from './runtime-status.ts'
58
+ import { handleRuntimeProvision, handleRuntimeStatus, RUNTIME_PROVISION_ROUTE, RUNTIME_STATUS_ROUTE } from './runtime-route.ts'
59
+ import { createShortcutRouteHandlers, SHORTCUT_ADD_ROUTE, SHORTCUT_REMOVE_ROUTE, SHORTCUTS_ROUTE } from './shortcuts-route.ts'
60
+ import { createShortcutStore, type ShortcutSettings } from './startpage-shortcuts.ts'
61
+ import { createReferenceService, setReferenceCaptureActionHandler } from '../browser-reference/service.ts'
62
+ import { WEB_SOURCE_ROUTE } from '../reference-source.ts'
63
+ import { createDeliveryQueue, resolveReferenceOwner, type DeliveryQueue } from '../browser-reference/delivery.ts'
64
+ import { createSubmissionReceipts, type ReceiptSession } from '../browser-reference/submission-receipts.ts'
65
+ import type { BrowserReference, BrowserReferenceCarrier } from '../browser-reference/types.ts'
66
+ import {
67
+ createReferenceRouteHandlers,
68
+ REFERENCE_CAPTURE_ROUTE,
69
+ REFERENCE_EXPORT_ROUTE,
70
+ REFERENCE_GET_ROUTE,
71
+ REFERENCE_IMPORT_ROUTE,
72
+ REFERENCE_INSERT_ROUTE,
73
+ REFERENCE_LIST_ROUTE,
74
+ REFERENCE_REVEAL_ROUTE,
75
+ REFERENCE_DELIVERIES_ROUTE,
76
+ REFERENCE_DELIVERY_ACK_ROUTE,
77
+ REFERENCE_DELIVERY_REMOVE_ROUTE,
78
+ REFERENCE_ASSET_ROUTE,
79
+ CLIENT_VERSION_ROUTE,
80
+ REFERENCE_STATUS_ROUTE,
81
+ } from './reference-route.ts'
82
+
83
+ function isPreferredCarrier(host: ElectronBrowserViewHost | undefined): host is ExtensionBrowserViewHost | PreferredBrowserViewHost {
84
+ return host instanceof ExtensionBrowserViewHost || host instanceof PreferredBrowserViewHost
85
+ }
86
+
87
+ /**
88
+ * The reference bar as a <script> element, for documents served through the Web guest proxy.
89
+ *
90
+ * The desktop shell evaluates the same source with `executeJavaScript`; a proxied document has no such
91
+ * handle, so it is injected inline. A literal `</script` inside the source would close the element, so
92
+ * it is escaped on the way in.
93
+ * @returns the inline script element.
94
+ */
95
+ function overlayTag(): string {
96
+ const source = overlayScript().replace(/<\/script/giu, '<\\/script')
97
+ return `<script data-dsh-ref-overlay-src="guest">(function(){\n${source}\n})()</script>`
98
+ }
99
+
100
+
101
+ /** Where the Web sidebar asks "what was just opened?". */
102
+
103
+ /**
104
+ * The surface this host would use for an open, echoed to the client.
105
+ *
106
+ * The client must not place a tab when the host is in "builtin" mode, or when it is an older build that
107
+ * always opens its own browser: that combination is the double-open.
108
+ * @returns "panel" or "builtin".
109
+ */
110
+ function readSurfaceForRoute(): 'panel' | 'builtin' {
111
+ try {
112
+ // `process.getBuiltinModule` avoids adding imports to this file, whose header order is load-bearing
113
+ // for the plugin's own module graph.
114
+ const fs = (process as unknown as { getBuiltinModule?: (id: string) => { readFileSync: (p: string, e: string) => string } }).getBuiltinModule?.('fs')
115
+ if (fs === undefined) return 'panel'
116
+ const parsed = JSON.parse(fs.readFileSync(settingsPath(), 'utf8')) as { browser?: { surface?: unknown } }
117
+ return parsed.browser?.surface === 'builtin' ? 'builtin' : 'panel'
118
+ } catch { return 'panel' }
119
+ }
120
+
121
+
122
+ export const OPEN_REQUEST_ROUTE = '/dsh-builtin-browser/browser/open-request'
123
+ /** open 记录的有效期:超过就不再重放。这是一次即时事件,客户端 2 秒轮询一次,10 秒足够送达;
124
+ * 留得越久,「关掉侧栏后刷新又被拉起来」的窗口越大(实测复现过)。 */
125
+ const OPEN_REQUEST_TTL_MS = 10_000
126
+ /** The client declares which surface it can host, so the host needs no file sniffing. */
127
+ export const SURFACE_DECL_ROUTE = '/dsh-builtin-browser/browser/declare-surface'
128
+
129
+ export {
130
+ ELECTRON_BROWSER_PROVIDER_ID,
131
+ ElectronBrowserProvider,
132
+ } from './provider.ts'
133
+ export type { ElectronBrowserViewHost, ElectronViewHandle } from './provider.ts'
134
+
135
+ /** Cordis plugin name used by loader diagnostics. */
136
+
137
+ function carrierSettingsKey(settings: ReturnType<SettingsStore['get']>): string {
138
+ return JSON.stringify([settings.browser.channel, settings.browser.systemProfile, settings.browser.headless,
139
+ settings.browser.systemProfile === 'plugin' ? settings.cookies.persist : undefined])
140
+ }
141
+
142
+ export const name = 'browser-electron'
143
+
144
+ /** The browser seam this provider registers into. */
145
+ export const inject = ['browser']
146
+
147
+ /** Plugin config: an optional externally-supplied view host. */
148
+ export interface Config {
149
+ /** View host supplied by a desktop shell; absent -> discover the sidebar. */
150
+ readonly viewHost?: ElectronBrowserViewHost
151
+ /** Allow navigation only to HTTP(S) URLs. Default true. */
152
+ readonly httpOnly?: boolean
153
+ /**
154
+ * Directory `dsh_browser_download` save paths must resolve inside (prevents a
155
+ * prompt-injected agent from writing arbitrary machine paths). Default:
156
+ * the user's Downloads folder; override to confine downloads elsewhere.
157
+ */
158
+ readonly downloadDir?: string
159
+ /** Maximum snapshot elements before truncation. Default 60. */
160
+ readonly snapshotMaxElements?: number
161
+ /** Maximum content characters before truncation when no maxChars is given. No longer read: the cap is per format (html and json 50 000, otherwise 20 000). */
162
+ readonly contentMaxChars?: number
163
+ }
164
+
165
+ export const Config: z<Config> = z.object({
166
+ // Absent on surfaces without a desktop shell; the plugin self-hosts then.
167
+ viewHost: z.any(),
168
+ httpOnly: z.boolean().default(true),
169
+ downloadDir: z.string(),
170
+ snapshotMaxElements: z.number(),
171
+ contentMaxChars: z.number(),
172
+ })
173
+
174
+ /**
175
+ * This process's session id, read the way DSH's own desktop host reads it.
176
+ *
177
+ * `dsh-desktop-host/lib/index.js` does `ctx.get('agents')` then `agents.list()`, and uses
178
+ * `agent.id` directly as a sessionId. One conversation per process, so the list holds this one.
179
+ *
180
+ * Returns undefined rather than throwing when the service is absent — an older host, or a
181
+ * non-desktop composition. The caller falls back to a random id, which is what the bridge used
182
+ * before and is safe: it only means "this process", not "this conversation".
183
+ *
184
+ * @param ctx - the plugin context.
185
+ * @returns the session id, or undefined when it cannot be read.
186
+ */
187
+ function readSessionId(ctx: unknown): string | undefined {
188
+ try {
189
+ const surface = ctx as { get?: (name: string) => unknown }
190
+ if (typeof surface.get !== 'function') return undefined
191
+ const agents = surface.get('agents') as { list?: () => unknown } | undefined
192
+ const list = typeof agents?.list === 'function' ? agents.list() : undefined
193
+ if (!Array.isArray(list) || list.length === 0) return undefined
194
+ const first = list[0] as { id?: unknown } | undefined
195
+ return typeof first?.id === 'string' && first.id !== '' ? first.id : undefined
196
+ } catch {
197
+ return undefined
198
+ }
199
+ }
200
+
201
+ /** Register the Electron browser provider with `ctx.browser`. */
202
+ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config): void {
203
+ // Which session is this process serving?
204
+ //
205
+ // The desktop shell keeps ONE sidebar per conversation — measured: two `[class*=_tabStrip]`
206
+ // containers sat in the DOM at once, each carrying its own session id on the React fiber, and
207
+ // the invisible one's webview was unloaded. So the bridge CAN tell which sidebar belongs to
208
+ // whom; what it lacked was the other half, this process's own identity. Without it, the bridge
209
+ // drove "whatever sidebar is on screen" and — measured on the running shell — typed into another
210
+ // conversation's address bar and navigated that page.
211
+ //
212
+ // The identity is available here, and DSH's own desktop host shows how
213
+ // (`dsh-desktop-host/lib/index.js`: `ctx.get('agents').list()`, with `agent.id` used directly as
214
+ // a sessionId). One conversation per process, so the list holds this one.
215
+ const sessionId = readSessionId(ctx)
216
+
217
+ // One settings document per plugin instance: the settings panel writes it, the
218
+ // provider reads it live, and both ends agree on the same file. The logger is passed so a
219
+ // discarded value (a mistyped channel, most of all) is reported instead of being silently
220
+ // replaced by the default — "my setting did nothing" and "I misspelled it" must not look alike.
221
+ const settings = new SettingsStore(undefined, message => ctx.logger?.warn?.(message))
222
+
223
+ /**
224
+ * The provider currently serving `ctx.browser`, kept for diagnostics only.
225
+ *
226
+ * `referenceStatus` answers "why is there no selection bar on this page" with the
227
+ * conversation id this process believes it serves and what its last sidebar scan
228
+ * saw. A stale entry after a carrier swap is harmless: the status route only reads.
229
+ */
230
+ let referenceProvider: ElectronBrowserProvider | undefined
231
+ const trackProvider = (provider: ElectronBrowserProvider): ElectronBrowserProvider => {
232
+ // A carrier swap builds a NEW provider; the previous one's pump would keep
233
+ // ticking against a view host that no longer serves anything, and its user
234
+ // action listeners would duplicate every capture. Retire it completely.
235
+ if (referenceProvider !== undefined && referenceProvider !== provider) referenceProvider.dispose()
236
+ referenceProvider = provider
237
+ return provider
238
+ }
239
+ const providerConfig = {
240
+ // The conversation this process serves: the sidebar reference entry finds its
241
+ // page through this id (see `adoptSidebarPageForReference`).
242
+ referenceLabel: () => readSessionId(ctx),
243
+ httpOnly: config.httpOnly,
244
+ downloadDir: config.downloadDir,
245
+ snapshotMaxElements: config.snapshotMaxElements,
246
+ contentMaxChars: config.contentMaxChars,
247
+ settings: () => settings.get(),
248
+ }
249
+
250
+ let panelOpening: Promise<{ host: DesktopBridgeViewHost; provider: ElectronBrowserProvider } | undefined> | undefined
251
+ let panelsDisposed = false
252
+ const retirePanel = (panel: { host: DesktopBridgeViewHost; provider: ElectronBrowserProvider }, lost = false): void => {
253
+ panel.provider.dispose()
254
+ void Promise.allSettled(panel.provider.watchableSessions().map(id => panel.provider.close(id)))
255
+ .finally(() => {
256
+ if (lost) setImmediate(() => { panel.host.dispose() })
257
+ else panel.host.dispose()
258
+ })
259
+ }
260
+ const unregisterPanel = ctx.browser.registerPanelProvider(async () => {
261
+ const selected = settings.get().browser
262
+ if ((selected.channel === 'edge' || selected.channel === 'chrome') && selected.systemProfile === 'user') {
263
+ if (!isPreferredCarrier(adoptedCarrier) || !referenceProvider) throw new Error('Selected personal-browser carrier is unavailable; no sidebar fallback.')
264
+ return referenceProvider
265
+ }
266
+ if (panelOpening === undefined) {
267
+ const opening = (async () => {
268
+ const host = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet)
269
+ if (host === undefined) return undefined
270
+ if (panelsDisposed) { host.dispose(); return undefined }
271
+ const provider = new ElectronBrowserProvider(host, providerConfig)
272
+ const panel = { host, provider }
273
+ host.onLost(() => {
274
+ if (panelOpening === opening) panelOpening = undefined
275
+ retirePanel(panel, true)
276
+ })
277
+ return panel
278
+ })()
279
+ panelOpening = opening
280
+ }
281
+ try {
282
+ const panel = await panelOpening
283
+ if (panel === undefined) panelOpening = undefined
284
+ return panel?.provider
285
+ } catch (error) {
286
+ panelOpening = undefined
287
+ throw error
288
+ }
289
+ })
290
+ ctx.effect(() => () => {
291
+ panelsDisposed = true
292
+ unregisterPanel()
293
+ void panelOpening?.then(panel => {
294
+ if (panel === undefined) return
295
+ retirePanel(panel)
296
+ }).catch(() => {})
297
+ })
298
+
299
+ const reportCarrierLoss = (reason: CarrierLossReason): void => {
300
+ const detail = reason === 'shell-exited'
301
+ ? 'the desktop shell backed the sidebar browser and has exited'
302
+ : 'the desktop shell is running, but its sidebar browser panel cannot be driven'
303
+ ctx.logger?.warn?.(`dsh-builtin-browser: ${detail} (${reason}); the next operation requires the DSH sidebar. No standalone fallback will be opened.`)
304
+ }
305
+ const requiredSidebar = (): SidebarOnlyHost => {
306
+ const host = new SidebarOnlyHost(async signal => {
307
+ for (const pause of [0, 1_000, 3_000, 8_000]) {
308
+ signal.throwIfAborted()
309
+ if (pause > 0) await wait(pause, undefined, { signal })
310
+ const sidebar = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet)
311
+ if (sidebar !== undefined) return sidebar
312
+ if (DesktopBridgeViewHost.refusedIframePanel()) break
313
+ }
314
+ const detail = DesktopBridgeViewHost.refusedIframePanel()
315
+ ? 'the DSH sidebar is an iframe and cannot support CDP tools'
316
+ : 'no controllable DSH sidebar is available'
317
+ throw Object.assign(new Error(`dsh-builtin-browser: ${detail}. Use a host-provided sidebar/webview carrier or install the DSH native-view host patch, then retry. The Web panel supports manual browsing, not CDP tools. No standalone browser will be opened.`), { code: 'BROWSER_NATIVE_SURFACE_UNAVAILABLE' })
318
+ })
319
+ host.onLost(reportCarrierLoss)
320
+ return host
321
+ }
322
+ const initialHost = requiredSidebar()
323
+ let unregister = ctx.browser.registerBrowserProvider(trackProvider(new ElectronBrowserProvider(initialHost, providerConfig)))
324
+ let disposed = false
325
+ let carrierChoice = 0
326
+ /** The carrier an `adopt` installed, so a later choice can release it. */
327
+ let adoptedCarrier: ElectronBrowserViewHost | undefined = initialHost
328
+ let unregisterTakeover = (): void => {}
329
+
330
+ ctx.effect(() => () => {
331
+ disposed = true
332
+ unregisterTakeover()
333
+ carrierChoice += 1
334
+ unregister()
335
+ // The reference pump is a real interval, not a one-shot: `unref` alone lets
336
+ // the process exit but leaves the tick running inside a live plugin, so it
337
+ // must stop with the provider it belongs to. Retiring also silences its
338
+ // user-action listeners, which the view host never unsubscribes.
339
+ referenceProvider?.dispose()
340
+ if (adoptedCarrier !== config.viewHost) adoptedCarrier?.dispose?.()
341
+ })
342
+
343
+ /**
344
+ * Require the sidebar after a borrowed carrier is lost; never launch a fallback window.
345
+ * @param adopted - the carrier that reported the loss, disposed once its replacement is in place.
346
+ * @param reason - which failure this was; see {@link CarrierLossReason}.
347
+ */
348
+ const restoreSidebar = (adopted: ElectronBrowserViewHost, reason: CarrierLossReason): void => {
349
+ // A replaced carrier may finish an outstanding request after the new choice is installed.
350
+ if (disposed || adoptedCarrier !== adopted) return
351
+ try {
352
+ const restored = requiredSidebar()
353
+ unregister()
354
+ unregister = ctx.browser.registerBrowserProvider(trackProvider(new ElectronBrowserProvider(restored, providerConfig)))
355
+ adoptedCarrier = restored
356
+ reportCarrierLoss(reason)
357
+ } catch (error) {
358
+ // Nothing better is available: the adopted carrier is gone and a provider that throws is
359
+ // worse than one that explains.
360
+ ctx.logger?.warn?.(`dsh-builtin-browser: could not restore the sidebar carrier: ${String(error)}`)
361
+ } finally {
362
+ // Disposed on a LATER turn of the event loop, deliberately.
363
+ //
364
+ // Disposing synchronously here closes the bridge socket while the request that triggered this
365
+ // fallback is still settling, and the close rejects every call still waiting on that socket —
366
+ // so the caller received "bridge closed" instead of the reason it actually failed for. The
367
+ // fallback is what the user is supposed to be able to understand; replacing its explanation
368
+ // with one about the connection loses exactly the information this path exists to convey.
369
+ setImmediate(() => {
370
+ try {
371
+ adopted.dispose?.()
372
+ } catch {
373
+ // A carrier that cannot be released is not the caller's problem; the swap already happened.
374
+ }
375
+ })
376
+ }
377
+ }
378
+
379
+ /**
380
+ * Swap the provider to another carrier, releasing the previous one.
381
+ * @param host - the carrier to adopt.
382
+ * @param note - a one-line description for the log.
383
+ */
384
+ const adopt = (host: ElectronBrowserViewHost, note: string, choice = carrierChoice): void => {
385
+ if (disposed || choice !== carrierChoice) {
386
+ try { host.dispose?.() } catch { /* a stale result must not escape its retry */ }
387
+ return
388
+ }
389
+ // This guard used to make the FIRST choice final, disposing anything that arrived later. That
390
+ // is right against two carriers racing in, and exactly wrong for a user changing the setting:
391
+ // `chooseCarrier` runs again on purpose, and a refusal here is indistinguishable from the
392
+ // write having done nothing. The previous carrier is now released by the replacement instead.
393
+ const previous = adoptedCarrier
394
+ try {
395
+ unregister()
396
+ unregister = ctx.browser.registerBrowserProvider(trackProvider(new ElectronBrowserProvider(host, providerConfig)))
397
+ adoptedCarrier = host
398
+ unregisterTakeover()
399
+ if (isPreferredCarrier(host)) {
400
+ const provider = referenceProvider!
401
+ unregisterTakeover = registerCarrierTakeover(ctx.browser, owner => provider.takeoverTargets(owner).map(target => ({
402
+ ...target, connected: () => adoptedCarrier === host && host.connectedView(target.tabId),
403
+ })))
404
+ void host.refreshStatus()
405
+ }
406
+ ctx.logger?.info?.(`dsh-builtin-browser: ${note}`)
407
+ // A borrowed carrier can lose the process behind it, and this is the only notification that
408
+ // will ever arrive. Registering AFTER the swap succeeded means a listener can never fire
409
+ // against a provider that was never installed.
410
+ if (!(host instanceof SidebarOnlyHost)) host.onLost?.(reason => { restoreSidebar(host, reason) })
411
+ // Released AFTER the replacement is installed, so the surface is never without a provider.
412
+ if (previous !== undefined && previous !== host && previous !== config.viewHost) {
413
+ try { previous.dispose?.() } catch { /* the replacement is already serving */ }
414
+ }
415
+ } catch (error) {
416
+ // Never leave the surface without a provider. The half-built host is disposed FIRST: an
417
+ // adopt that got as far as constructing it may already hold a socket, a listener or a child
418
+ // process, and dropping it on the floor is how a failed upgrade becomes a leak that only
419
+ // shows up as a stray Electron in the task manager.
420
+ try { host.dispose?.() } catch { /* the fallback below matters more than this */ }
421
+ if (isPreferredCarrier(host)) {
422
+ ctx.logger?.warn?.(`dsh-builtin-browser: could not adopt the selected personal-browser extension (${String(error)}); no profile fallback`)
423
+ return
424
+ }
425
+ // The fallback registration gets its own guard, because THIS is the path taken when the
426
+ // context is already gone — and then `ctx.browser` throws `cannot get required service
427
+ // "browser" in inactive context`. Unguarded, that second throw escaped the async retry
428
+ // that calls `adopt`, became an unhandled rejection, and killed the host process with
429
+ // exit code 1: a failed upgrade, which should only ever cost a warning, took the whole
430
+ // session down instead. Observed 2026-10-05 (crash-…-host.log, phase: running).
431
+ try {
432
+ const fallback = requiredSidebar()
433
+ unregister = ctx.browser.registerBrowserProvider(trackProvider(new ElectronBrowserProvider(fallback, providerConfig)))
434
+ adoptedCarrier = fallback
435
+ if (previous !== undefined && previous !== host) {
436
+ try { previous.dispose?.() } catch { /* fallback is already serving */ }
437
+ }
438
+ ctx.logger?.warn?.(`dsh-builtin-browser: could not adopt ${note} (${String(error)})`)
439
+ } catch (fallbackError) {
440
+ ctx.logger?.warn?.(
441
+ `dsh-builtin-browser: could not adopt ${note} (${String(error)}), and the fallback `
442
+ + `registration also failed (${String(fallbackError)}) — no browser provider is `
443
+ + 'registered for this context')
444
+ }
445
+ }
446
+ }
447
+
448
+ /**
449
+ * Choose and install the carrier that `browser.channel` names RIGHT NOW.
450
+ *
451
+ * A function rather than straight-line code because the setting is read live everywhere else:
452
+ * the settings route writes the file and the provider picks the change up on its next call, so a
453
+ * channel that could only be honoured at apply time was the one setting whose write silently did
454
+ * nothing. Re-entrant by design — changing the channel means replacing the carrier, which is
455
+ * exactly what a second call does.
456
+ */
457
+ let chosenSettingsKey = ''
458
+ const chooseCarrier = (): void => {
459
+ if (disposed) return
460
+ chosenSettingsKey = carrierSettingsKey(settings.get())
461
+ const choice = ++carrierChoice
462
+ // A browser the user explicitly asked for outranks every automatic choice: the
463
+ // whole point of the setting is that they know which browser they want. It is
464
+ // launched with a plugin-owned profile, so their own windows are untouched.
465
+ //
466
+ // Registration is INERT: constructing the host starts nothing. The browser only
467
+ // launches when a command actually needs a page, so merely running DSH never
468
+ // spawns a browser window. (An earlier version launched it here, which meant a
469
+ // browser appeared the moment the plugin loaded — reported and fixed.)
470
+ const channel = settings.get().browser.channel
471
+ // Naming a browser is a decision about which one to use, so it also decides whether the
472
+ // desktop sidebar may take over. Skipping discovery for an explicit choice is what makes
473
+ // that choice real — otherwise a user who picked Chrome would silently get the sidebar,
474
+ // and a user who picked a browser that is not installed would never see the explanation
475
+ // written for exactly that case, because the sidebar would quietly replace it.
476
+ if (channel !== 'chrome' && channel !== 'edge') {
477
+ if (config.viewHost !== undefined) {
478
+ if (adoptedCarrier !== config.viewHost) adopt(config.viewHost as ElectronBrowserViewHost, 'using the composition-provided sidebar carrier', choice)
479
+ } else if (!(adoptedCarrier instanceof SidebarOnlyHost)) adopt(requiredSidebar(), 'using only the selected DSH sidebar', choice)
480
+ return
481
+ }
482
+ const detected = detectBrowser(channel)
483
+ if (detected === undefined) {
484
+ const missing = new MissingSystemBrowserHost(channel, searchSummary(channel))
485
+ adopt(settings.get().browser.systemProfile === 'user' ? new PreferredBrowserViewHost(channel, missing) : missing,
486
+ `the selected ${channel} is not installed — commands will explain how to fix it`)
487
+ } else {
488
+ // Same profile root as settings-store, history-store and desktop-bridge-host: the
489
+ // `?.dsh` component used to be missing HERE only, so a desktop launched from a
490
+ // shortcut (no DSH_HOME in the environment) put its browser profile in
491
+ // `C:\Users\<user>\dsh-builtin-browser-host\` while its settings and history lived in
492
+ // `~/.dsh/dsh-builtin-browser-host/` — two half-profiles that never met, and a
493
+ // settings panel whose switches appeared not to apply.
494
+ const home = dshHome()
495
+ // Login state lives in the browser profile, so the cookies setting decides where
496
+ // that profile goes: a stable directory keeps the user signed in across restarts
497
+ // (the point of using their own browser), while turning persistence off gets a
498
+ // throwaway directory that is removed when the browser is released.
499
+ const persist = settings.get().cookies.persist
500
+ const profileRoot = join(home, BROWSER_PROFILE_DIR)
501
+ adoptLegacyProfileRoot(profileRoot)
502
+ const profileDir = persist
503
+ ? join(profileRoot, `${detected.kind}-profile`)
504
+ : join(profileRoot, ephemeralProfileName(detected.kind, randomUUID()))
505
+ if (!persist) {
506
+ // A process killed outright never runs its own cleanup (see ephemeral-profile.ts),
507
+ // so the sweep happens HERE — at the only moment that can still act on a profile
508
+ // whose owner is gone — and before this run claims a directory of its own.
509
+ sweepAbandonedEphemeralProfiles(profileRoot, detected.kind)
510
+ claimEphemeralProfile(profileDir)
511
+ }
512
+ // The headless mode rides along so a display-less host (systemd, container, SSH-only server)
513
+ // still gets a working browser instead of "exited immediately after launch" — issue #32.
514
+ ;(globalThis as unknown as Record<string, unknown>).__dshBrowserCarrier = 'launched-plugin-profile'
515
+ const managed = new SystemBrowserViewHost(detected, profileDir, [], !persist ? profileDir : undefined,
516
+ undefined, settings.get().browser.headless, () => settings.get().ui.quiet,
517
+ undefined, { managed: true })
518
+ adopt(settings.get().browser.systemProfile === 'user' ? new PreferredBrowserViewHost(channel, managed) : managed,
519
+ `will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`)
520
+ }
521
+ }
522
+
523
+ chooseCarrier()
524
+ void nativeRegistration.ensure().catch(() => {})
525
+
526
+ // Wired AFTER the chooser exists, because the handler re-runs it: a settings write that changes
527
+ // `browser.channel` is a request to switch carriers, and answering `ok` without switching is the
528
+ // one thing a caller cannot tell apart from a write that worked.
529
+ /**
530
+ * Expose the live-view frame endpoint on the host's web server (issue #34).
531
+ *
532
+ * Registered exactly like the settings route and skipped the same way when a surface has no web
533
+ * server: a CLI session simply has no viewer, which is not a plugin-startup failure. The endpoint
534
+ * is inert until the host turns `remoteView.enabled` on, and it refuses a request whose session the
535
+ * plugin never handed out.
536
+ * @param ctx - the plugin context.
537
+ * @param settings - the settings document, for the share switch.
538
+ */
539
+ function installPreviewRoute(ctx: Context, settings: SettingsStore): void {
540
+ const injectPreview = (ctx as unknown as {
541
+ inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
542
+ }).inject
543
+ if (typeof injectPreview !== 'function') return
544
+ try {
545
+ injectPreview(['webServer', 'browser'], (host) => {
546
+ const browser = (ctx as unknown as { browser?: PreviewBrowser }).browser
547
+ if (browser === undefined) return
548
+ host.effect(() => host.webServer.register({
549
+ kind: 'exact',
550
+ path: PREVIEW_ROUTE,
551
+ handler: paired(ctx, (request, response) => handlePreviewFrame(request, response, settings, browser)),
552
+ }, 'dsh-builtin-browser: live view frame'))
553
+ // The Web sidebar's iframe has no handle into a cross-origin guest, so the guest is served
554
+ // through this prefix instead: same origin, readable, injectable. See guest-route.ts.
555
+ // The client is the authority on which surface exists in THIS shell: it either has a sidebar or not.
556
+ // Reading settings.json from the host was unreliable (a module instance can hold a stale home), and it
557
+ // needed a restart to take effect. A declaration rides recomposition instead.
558
+ host.effect(() => host.webServer.register({
559
+ kind: 'exact',
560
+ path: SURFACE_DECL_ROUTE,
561
+ handler: authenticated(ctx, (request, response) => {
562
+ readJsonBody(request).then((body) => {
563
+ const surface = body !== null && typeof body === 'object' && (body as { surface?: unknown }).surface
564
+ if (surface === 'panel' || surface === 'builtin') {
565
+ (globalThis as unknown as Record<string, unknown>).__dshBrowserSurface = surface
566
+ }
567
+ replyJson(response, 200, { ok: true })
568
+ }).catch(() => { replyJson(response, 200, { ok: false }) })
569
+ }),
570
+ }, 'dsh-builtin-browser: surface declaration'))
571
+ // One slot the Web sidebar polls: it cannot be told through a bridge, so it asks.
572
+ host.effect(() => host.webServer.register({
573
+ kind: 'exact',
574
+ path: OPEN_REQUEST_ROUTE,
575
+ handler: authenticated(ctx, (request, response) => {
576
+ // 这条记录**不能被第一个轮询到的客户端消费掉**:同一进程里可能有多个 DSH 窗口/标签页
577
+ // (人手一个、自动化又一个),先问的那个把记录清空后,另一个窗口就再也看不到这次 open,
578
+ // 表现成「工具说打开了、我这边没打开」。所以这里不清空,只按时间过期:
579
+ // 每个客户端各自用 sessionStorage 记住「这条处理过了」,既不重放,也不互相抢。
580
+ if ((request.method ?? 'GET').toUpperCase() === 'POST') {
581
+ request.resume()
582
+ request.on('end', () => { replyJson(response, 200, { ok: true, cleared: false }) })
583
+ return
584
+ }
585
+ const last = getLastOpen()
586
+ const fresh = last !== undefined && Date.now() - last.at <= OPEN_REQUEST_TTL_MS ? last : undefined
587
+ replyJson(response, 200, { ok: true, surface: readSurfaceForRoute(), open: isPreferredCarrier(adoptedCarrier) ? null : fresh ?? null })
588
+ }),
589
+ }, 'dsh-builtin-browser: open request slot'))
590
+ // guest 代理由根行注册(见 src/web-guest.ts):web 上 Electron 行可能被关闭。
591
+ // The list the panel needs before it can build a frame URL at all: session ids only.
592
+ host.effect(() => host.webServer.register({
593
+ kind: 'exact',
594
+ path: PREVIEW_SESSIONS_ROUTE,
595
+ handler: paired(ctx, (request, response) => handlePreviewSessions(request, response, settings, browser)),
596
+ }, 'dsh-builtin-browser: live view sessions')) })
597
+ } catch {
598
+ // No web server on this surface: watching is simply unavailable, and nothing else changes.
599
+ }
600
+ }
601
+
602
+ /**
603
+ * Expose the bridge's install state on the host's web server, for the settings panel.
604
+ *
605
+ * Separate from the live-view routes because it needs no browser service: it reads the install
606
+ * tree, which is on disk and independent of any carrier. A surface without a web server skips it,
607
+ * exactly like the other two.
608
+ * @param ctx - the plugin context.
609
+ */
610
+ /** Where the panel asks to install or remove the bridge. */
611
+ const BRIDGE_ACTION_ROUTE = '/dsh-builtin-browser/bridge-action'
612
+ let bridgeActionRunning = false
613
+
614
+ /**
615
+ * Prepare external maintenance while Desktop remains open, or execute file maintenance from
616
+ * an independent local host after Desktop has exited.
617
+ * @param request - the incoming request (POST, JSON body `{action, prepare?}`).
618
+ * @param response - the response to write.
619
+ */
620
+ async function handleBridgeAction(request: IncomingMessage, response: ServerResponse): Promise<void> {
621
+ if (request.method !== 'POST') { replyJson(response, 405, { error: 'method-not-allowed' }); return }
622
+ // Both creating a local launcher and changing installation files require write admission.
623
+ if (!sameOrigin(request, true)) { replyJson(response, 403, { error: 'not-same-origin' }); return }
624
+ if (!isDirectLoopback(request)) { replyJson(response, 403, { error: 'local-request-required' }); return }
625
+ let action: unknown
626
+ let preparationOnly = false
627
+ try {
628
+ const input = await readJsonBody<{ action?: unknown; prepare?: unknown }>(request)
629
+ action = input.action
630
+ if (input.prepare !== undefined && typeof input.prepare !== 'boolean') throw new Error('prepare must be a boolean')
631
+ preparationOnly = input.prepare === true
632
+ } catch (error) {
633
+ replyJson(response, 400, { ok: false, error: `unreadable body: ${String(error)}` })
634
+ return
635
+ }
636
+ if (action !== 'install' && action !== 'uninstall') {
637
+ replyJson(response, 400, { ok: false, error: 'action must be "install" or "uninstall"' })
638
+ return
639
+ }
640
+ const root = findDesktopInstall()
641
+ if (root === undefined) {
642
+ // Nothing to patch: say so instead of running an installer against a guess.
643
+ replyJson(response, 409, { ok: false, error: 'no DSH Desktop install was found on this machine' })
644
+ return
645
+ }
646
+ if (bridgeActionRunning) {
647
+ replyJson(response, 409, { ok: false, error: 'bridge-action-in-progress' })
648
+ return
649
+ }
650
+ const active = readAutomaticMaintenance()
651
+ if (!preparationOnly && active !== undefined && !['completed', 'failed', 'cancelled'].includes(active.phase)) {
652
+ replyJson(response, 409, { ok: false, error: 'an automatic bridge maintenance job is in progress' })
653
+ return
654
+ }
655
+ bridgeActionRunning = true
656
+ try {
657
+ if (preparationOnly) {
658
+ const result = await prepareBridgeMaintenance(action, root)
659
+ replyJson(response, 200, { ...result, action })
660
+ return
661
+ }
662
+ const result = await runWithManualBridgePreference(action, patch => settings.update(patch), () => runBridgeAction(action, root))
663
+ replyJson(response, 200, { ...result, action })
664
+ } catch (error) {
665
+ if (preparationOnly) {
666
+ replyJson(response, 500, { ok: false, error: `could not prepare bridge maintenance: ${String(error)}` })
667
+ return
668
+ }
669
+ replyJson(response, 500, { ok: false, error: String(error instanceof Error ? error.message : error) })
670
+ } finally {
671
+ bridgeActionRunning = false
672
+ }
673
+ }
674
+
675
+ function installBridgeStatusRoute(ctx: Context): void {
676
+ const injectStatus = (ctx as unknown as {
677
+ inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
678
+ }).inject
679
+ if (typeof injectStatus !== 'function') return
680
+ try {
681
+ injectStatus(['webServer'], (host) => {
682
+ const hostPatchMaintenance = createHostPatchMaintenance({
683
+ modules: () => servedClientModules(ctx.get('clientModules')),
684
+ desktop: () => process.versions.electron !== undefined,
685
+ })
686
+ host.effect(() => host.webServer.register({
687
+ kind: 'exact', path: HOST_PATCH_ROUTE,
688
+ handler: authenticated(ctx, hostPatchMaintenance),
689
+ }, 'dsh-builtin-browser: Web host patch maintenance'))
690
+ const automaticMaintenance = createAutomaticMaintenanceHandler({
691
+ supported: () => automaticMaintenanceSupported(),
692
+ // Windows quits through the Desktop's own menu, opened by the panel; macOS through its Quit Apple event.
693
+ quit: () => process.platform === 'win32' ? 'menu' : 'self',
694
+ busy: () => bridgeActionRunning,
695
+ read: () => readAutomaticMaintenance(),
696
+ commit: async id => { await commitAutomaticMaintenance(id) },
697
+ start: async (action, options) => {
698
+ const root = findDesktopInstall()
699
+ if (root === undefined) throw new Error('no verified DSH Desktop installation was found')
700
+ return await runWithManualBridgePreference('install', patch => settings.update(patch),
701
+ async () => await startAutomaticMaintenance(action, root, options))
702
+ },
703
+ })
704
+ host.effect(() => host.webServer.register({
705
+ kind: 'exact', path: AUTOMATIC_MAINTENANCE_ROUTE,
706
+ handler: authenticated(ctx, automaticMaintenance),
707
+ }, 'dsh-builtin-browser: explicit automatic bridge maintenance'))
708
+ host.effect(() => host.webServer.register({
709
+ kind: 'exact',
710
+ path: BRIDGE_STATUS_ROUTE,
711
+ handler: authenticated(ctx, async (request, response) => handleBridgeStatus(request, response, undefined,
712
+ await readHostExtensionStatus(dshHome()))),
713
+ }, 'dsh-builtin-browser: bridge status'))
714
+ // The panel prepares a launcher without changing the running Desktop. Direct local
715
+ // maintenance remains available once Desktop has exited.
716
+ host.effect(() => host.webServer.register({
717
+ kind: 'exact',
718
+ path: BRIDGE_ACTION_ROUTE,
719
+ handler: authenticated(ctx, (request, response) => handleBridgeAction(request, response)),
720
+ }, 'dsh-builtin-browser: bridge action'))
721
+ })
722
+ } catch {
723
+ // No web server: the panel is unreachable, and the installer stays the interface.
724
+ }
725
+ }
726
+
727
+ installSettingsRoute(ctx, settings, () => { chooseCarrier() })
728
+
729
+ // Bridge maintenance is explicit and requires DSH Desktop to be closed. Loading a provider
730
+ // never starts an installer, including with an older settings file's bridge.autoInstall=true.
731
+
732
+ /**
733
+ * Expose readiness — "can the browser serve a call right now" — for the settings panel.
734
+ *
735
+ * The panel had switches for every behaviour and no answer to the one question a new install
736
+ * raises: the bundled runtime is downloaded on first need (issue #41 moved it out of `postinstall`
737
+ * for good reasons), so for the first minute of a fresh install the honest state is "preparing",
738
+ * and until this route existed that state was a log line no panel could read. Both readings are
739
+ * cheap and side-effect free: a path probe for the runtime, an install-tree inspection for the
740
+ * bridge — the same two the launch path and the bridge-status route already use.
741
+ *
742
+ * Skipped, like its siblings, on a surface with no web server: a CLI has no panel to show it to.
743
+ * @param ctx - the plugin context.
744
+ * @param settings - the settings document, for the channel being honoured.
745
+ */
746
+ function installRuntimeStatusRoute(ctx: Context, settings: SettingsStore): void {
747
+ const injectRuntime = (ctx as unknown as {
748
+ inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
749
+ }).inject
750
+ if (typeof injectRuntime !== 'function') return
751
+ const deps = {
752
+ report: async () => {
753
+ const mainExtension = await readHostExtensionStatus(dshHome())
754
+ return readRuntimeStatus({
755
+ nativeHostRegistration: () => Object.fromEntries(registrationStatus),
756
+ channel: () => settings.get().browser.channel,
757
+ systemProfile: () => settings.get().browser.systemProfile,
758
+ extensionConnection: () => isPreferredCarrier(adoptedCarrier) ? {
759
+ ...adoptedCarrier.connectionStatus(), install: extensionInstallHelp(adoptedCarrier.browser), registration: registrationStatus.get(adoptedCarrier.browser),
760
+ } : undefined,
761
+ selectedCarrier: () => adoptedCarrier instanceof DesktopBridgeViewHost || adoptedCarrier instanceof SidebarOnlyHost ? 'sidebar'
762
+ : adoptedCarrier instanceof PreferredBrowserViewHost ? adoptedCarrier.activeCarrier()
763
+ : adoptedCarrier instanceof ExtensionBrowserViewHost ? 'extension' : adoptedCarrier instanceof SystemBrowserViewHost ? 'system' : 'bundled',
764
+ fallbackReason: () => adoptedCarrier instanceof PreferredBrowserViewHost ? adoptedCarrier.fallbackReason : undefined,
765
+ systemConnection: () => adoptedCarrier instanceof PreferredBrowserViewHost ? adoptedCarrier.fallback.connectionStatus?.() : adoptedCarrier instanceof SystemBrowserViewHost ? adoptedCarrier.connectionStatus() : undefined,
766
+ hasBinary: hasElectronRuntime,
767
+ provision: provisionSnapshot,
768
+ bridgeError: () => DesktopBridgeViewHost.compatibilityError(),
769
+ bridge: () => {
770
+ const root = findDesktopInstall()
771
+ return root === undefined ? undefined : readBridgeStatus(root, mainExtension)
772
+ },
773
+ // Installed is not running: the install tree survives a reboot, the endpoint does not. Both
774
+ // readings are cheap and side-effect free — a file read and a signal-0 pid check.
775
+ endpoint: () => readBridgeEndpoint(),
776
+ })
777
+ },
778
+ // `force` is what makes the panel's retry button mean anything: without it the answer would be
779
+ // the settled failure the user is trying to replace. An attempt still running is joined.
780
+ provision: () => {
781
+ void provisionElectronInBackground(
782
+ message => ctx.logger?.info?.(`dsh-builtin-browser: ${message}`),
783
+ undefined,
784
+ { force: true },
785
+ )
786
+ return provisionSnapshot()
787
+ },
788
+ }
789
+ try {
790
+ injectRuntime(['webServer'], (host) => {
791
+ host.effect(() => host.webServer.register({ kind: 'exact', path: EXTENSION_INSTALL_ROUTE, handler: authenticated(ctx, async (request, response) => {
792
+ if (request.method !== 'POST') { response.writeHead(405); response.end(); return }
793
+ if (!sameOrigin(request, true)) { response.writeHead(403); response.end(); return }
794
+ try {
795
+ const browser = settings.get().browser.channel === 'chrome' ? 'chrome' : 'edge'
796
+ if (isPreferredCarrier(adoptedCarrier)) await adoptedCarrier.refreshStatus()
797
+ const connected = isPreferredCarrier(adoptedCarrier) ? adoptedCarrier.connectionStatus().connected : await probeExtension(browser)
798
+ const result = await installExtension(browser, connected)
799
+ response.writeHead(200, { 'content-type': 'application/json' }); response.end(JSON.stringify(result))
800
+ } catch (error) { response.writeHead(200, { 'content-type': 'application/json' }); response.end(JSON.stringify({ ok: false, detail: String(error) })) }
801
+ }) }, 'dsh-builtin-browser: install extension'))
802
+ host.effect(() => host.webServer.register({
803
+ kind: 'exact',
804
+ path: RUNTIME_STATUS_ROUTE,
805
+ handler: authenticated(ctx, async (request, response) => {
806
+ if (request.method === 'GET' && isPreferredCarrier(adoptedCarrier)) await adoptedCarrier.refreshStatus()
807
+ await handleRuntimeStatus(request, response, deps)
808
+ }),
809
+ }, 'dsh-builtin-browser: runtime status'))
810
+ host.effect(() => host.webServer.register({
811
+ kind: 'exact',
812
+ path: RUNTIME_PROVISION_ROUTE,
813
+ handler: authenticated(ctx, (request, response) => handleRuntimeProvision(request, response, deps)),
814
+ }, 'dsh-builtin-browser: runtime provision'))
815
+ })
816
+ } catch {
817
+ // No web server: the panel is unreachable, and the readiness report has no reader.
818
+ }
819
+ }
820
+
821
+ /**
822
+ * Expose the shared start-page shortcut list on the host's web server.
823
+ *
824
+ * The sidebar edits the section through the settings RPC; this face exists for a
825
+ * caller that has no sidebar — an agent, a script, or a verification run — and it
826
+ * writes the SAME section through `ctx.settings`, so both paths see one list.
827
+ * @param host - the plugin context.
828
+ */
829
+ function installShortcutRoutes(host: Context): void {
830
+ const injectRoutes = (host as unknown as {
831
+ inject?: (deps: readonly string[], callback: (scope: WebServerHost) => void) => void
832
+ }).inject
833
+ if (typeof injectRoutes !== 'function') return
834
+ const store = createShortcutStore(() => (host as unknown as {
835
+ get?: (name: string) => ShortcutSettings | undefined
836
+ }).get?.('settings'))
837
+ const handlers = createShortcutRouteHandlers(store)
838
+ try {
839
+ injectRoutes(['webServer'], (scope) => {
840
+ const routes: readonly (readonly [string, BrowserHttpHandler, string])[] = [
841
+ [SHORTCUTS_ROUTE, handlers.list, 'dsh-builtin-browser: start-page shortcuts'],
842
+ [SHORTCUT_ADD_ROUTE, handlers.add, 'dsh-builtin-browser: start-page shortcut add'],
843
+ [SHORTCUT_REMOVE_ROUTE, handlers.remove, 'dsh-builtin-browser: start-page shortcut remove'],
844
+ ]
845
+ for (const [path, handler, label] of routes) {
846
+ scope.effect(() => scope.webServer.register({
847
+ kind: 'exact',
848
+ path,
849
+ handler: authenticated(host, handler),
850
+ }, label))
851
+ }
852
+ })
853
+ } catch {
854
+ // No web server: the shortcut seam stays available to the agent tool.
855
+ }
856
+ }
857
+
858
+ /**
859
+ * Expose browser-reference capture, listing and reveal on the host's web server.
860
+ *
861
+ * The panel needs no browser session of its own: list and reveal act on the
862
+ * session recorded inside each reference, and capture takes the pair of ids
863
+ * from the caller. Skipped on a surface with no web server, exactly like the
864
+ * sibling routes.
865
+ * @param ctx - the plugin context.
866
+ * @param service - the shared reference service.
867
+ * @param carrier - the carrier recorded for captures that do not name one.
868
+ * @param queue - durable capture-to-draft hand-off.
869
+ */
870
+ function installReferenceRoutes(
871
+ ctx: Context,
872
+ service: ReturnType<typeof createReferenceService>,
873
+ carrier: () => BrowserReferenceCarrier,
874
+ queue: DeliveryQueue,
875
+ receipts: ReturnType<typeof createSubmissionReceipts>,
876
+ ): void {
877
+ const injectRoutes = (ctx as unknown as {
878
+ inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
879
+ }).inject
880
+ if (typeof injectRoutes !== 'function') return
881
+ try {
882
+ injectRoutes(['webServer'], (host) => {
883
+ const handlers = createReferenceRouteHandlers({ service, carrier, queue, receipts })
884
+ const routes: readonly (readonly [string, (request: IncomingMessage, response: ServerResponse) => void | Promise<void>, string])[] = [
885
+ [CLIENT_VERSION_ROUTE, (_request, response) => {
886
+ // 客户端产物的版本指纹:内容变了,浏览器就应换到新 bundle。
887
+ const clientPath = fileURLToPath(new URL('../../dist/client.cjs', import.meta.url))
888
+ let version = "unknown"
889
+ try {
890
+ const stat = statSync(clientPath)
891
+ version = `${Math.round(stat.mtimeMs)}-${stat.size}`
892
+ } catch { /* 读不到就返回 unknown:客户端不会重载 */ }
893
+ response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" })
894
+ response.end(JSON.stringify({ ok: true, version }))
895
+ }, 'dsh-builtin-browser: client version'],
896
+ [REFERENCE_LIST_ROUTE, handlers.list, 'dsh-builtin-browser: reference list'],
897
+ [REFERENCE_GET_ROUTE, handlers.get, 'dsh-builtin-browser: reference detail'],
898
+ [REFERENCE_CAPTURE_ROUTE, handlers.capture, 'dsh-builtin-browser: reference capture'],
899
+ [REFERENCE_REVEAL_ROUTE, handlers.reveal, 'dsh-builtin-browser: reference reveal'],
900
+ [WEB_SOURCE_ROUTE, handlers.source, 'dsh-builtin-browser: web reference source'],
901
+ [REFERENCE_INSERT_ROUTE, handlers.insert, 'dsh-builtin-browser: reference draft insert'],
902
+ [REFERENCE_EXPORT_ROUTE, handlers.export, 'dsh-builtin-browser: reference export'],
903
+ [REFERENCE_IMPORT_ROUTE, handlers.importBundle, 'dsh-builtin-browser: reference import'],
904
+ [REFERENCE_DELIVERIES_ROUTE, handlers.deliveries, 'dsh-builtin-browser: reference deliveries'],
905
+ [REFERENCE_DELIVERY_ACK_ROUTE, handlers.ack, 'dsh-builtin-browser: reference delivery ack'],
906
+ [REFERENCE_DELIVERY_REMOVE_ROUTE, handlers.removeDelivery, 'dsh-builtin-browser: reference delivery remove'],
907
+ [REFERENCE_ASSET_ROUTE, handlers.asset, 'dsh-builtin-browser: reference asset bytes'],
908
+ ]
909
+ for (const [path, handler, label] of routes) {
910
+ host.effect(() => host.webServer.register({
911
+ kind: 'exact',
912
+ path,
913
+ handler: authenticated(ctx, handler),
914
+ }, label))
915
+ }
916
+ host.effect(() => host.webServer.register({
917
+ kind: 'exact',
918
+ path: REFERENCE_STATUS_ROUTE,
919
+ handler: authenticated(ctx, (request, response) => {
920
+ if (request.method !== 'GET') { replyJson(response, 405, { ok: false, error: 'method-not-allowed' }); return }
921
+ replyJson(response, 200, { ok: true, entry: referenceProvider?.referenceStatus() ?? null })
922
+ }),
923
+ }, 'dsh-builtin-browser: reference entry status'))
924
+ })
925
+ } catch {
926
+ // No web server: capture stays available through the agent tools.
927
+ }
928
+ }
929
+
930
+ /**
931
+ * Re-run the carrier choice when the settings FILE changes on disk.
932
+ *
933
+ * The route above covers a write through the panel. It does not cover a person editing
934
+ * `settings.json` by hand — and that is how `browser.channel` gets changed when the panel is
935
+ * unreachable or the user prefers the file. Measured: the document said `sidebar` and the plugin
936
+ * kept driving the self-hosted window built for the previous choice, because nothing re-read it.
937
+ *
938
+ * Change detection is on carrier settings, not the mtime: a poll that re-chose the carrier on
939
+ * every unrelated save would tear down and rebuild a working browser session for a switch that
940
+ * cannot affect it. mtime is only the cheap trigger to go and look.
941
+ */
942
+ const watchSettingsFile = (): void => {
943
+ const file = settingsPath()
944
+ let lastMtime = 0
945
+ try { lastMtime = statSync(file).mtimeMs } catch { /* not written yet */ }
946
+ const timer = setInterval(() => {
947
+ if (disposed) { clearInterval(timer); return }
948
+ let mtime = 0
949
+ try { mtime = statSync(file).mtimeMs } catch { return }
950
+ if (mtime === lastMtime) return
951
+ lastMtime = mtime
952
+ if (carrierSettingsKey(settings.get()) === chosenSettingsKey) return
953
+ ctx.logger?.info?.('dsh-builtin-browser: carrier settings changed on disk, re-choosing the carrier')
954
+ chooseCarrier()
955
+ }, 5_000)
956
+ // Unref-ed so a poll never holds the process open.
957
+ timer.unref?.()
958
+ ctx.effect(() => () => { clearInterval(timer) }, "dsh-builtin-browser: settings file watch")
959
+ }
960
+ watchSettingsFile()
961
+ installPreviewRoute(ctx, settings)
962
+ installBridgeStatusRoute(ctx)
963
+ installRuntimeStatusRoute(ctx, settings)
964
+ // One service for the panel's routes; the tool layer builds its own over the same store file.
965
+ const referenceService = createReferenceService(ctx.browser, {
966
+ sourceReady: async owner => { (await DesktopBridgeViewHost.discover(`session-${owner}`))?.dispose() },
967
+ sourceSession: (owner, pageId) => ctx.browser.bindPanelPage(`session-${owner}`, pageId),
968
+ // A visible-region snapshot is a read: the clipped CDP path never presents
969
+ // the conversation, raises a window or moves the pointer.
970
+ visibleCapture: async (sessionId, clip, signal) => {
971
+ const shot = await ctx.browser.screenshot(sessionWireId(resolveSessionHandle(sessionId)), { clip, format: 'png' }, signal)
972
+ return { dataUrl: shot.dataUrl, mime: 'image/png' }
973
+ },
974
+ })
975
+ const referenceCarrier = (): BrowserReferenceCarrier => {
976
+ const channel = settings.get().browser.channel
977
+ return channel === 'chrome' || channel === 'edge' ? channel : 'sidebar'
978
+ }
979
+
980
+ /**
981
+ * The durable hand-off. A capture is frozen into the queue with the FULL
982
+ * snapshot, so the client can restore a draft after the page closed or DSH
983
+ * restarted without asking the browser for anything (§12.2).
984
+ */
985
+ const deliveryQueue = createDeliveryQueue()
986
+ const receipts = createSubmissionReceipts(deliveryQueue, id => {
987
+ const sessions = ctx.get('sessions') as { get(sessionId: string): ReceiptSession | undefined } | undefined
988
+ return sessions?.get(id)
989
+ })
990
+ ctx.on?.('session/event', (session, event) => {
991
+ try { receipts.observe(session.id, event as Parameters<typeof receipts.observe>[1]) }
992
+ catch (error) { ctx.logger?.warn?.(`dsh-builtin-browser: reference receipt pending: ${String(error)}`) }
993
+ }, { global: true })
994
+ installReferenceRoutes(ctx, referenceService, referenceCarrier, deliveryQueue, receipts)
995
+ installShortcutRoutes(ctx)
996
+
997
+ /** Short, stable, non-sensitive codes for the page notice when an enqueue fails. */
998
+ type PrepareFailure = 'browser-session-id-required' | 'delivery-enqueue-failed'
999
+
1000
+ /** Freeze a captured reference for its owning conversation. */
1001
+ const prepareCaptured = (
1002
+ reference: BrowserReference | undefined,
1003
+ failures: readonly { readonly kind: string; readonly reason: string }[],
1004
+ onFailure?: (code: PrepareFailure) => void,
1005
+ ): boolean => {
1006
+ if (reference === undefined) return false
1007
+ // `resolveReferenceOwner` falls back to `browser:<uuid>` when no real DSH
1008
+ // conversation id can be read. queue.prepare would "succeed" under that
1009
+ // id, but the client polls with the REAL session id and can never match it,
1010
+ // so the card silently never appears. Refuse the enqueue instead of
1011
+ // reporting a success that cannot be delivered, and let the page ask the
1012
+ // human to retry once the session is ready.
1013
+ if ((reference.owner.sessionId ?? '').startsWith('browser:')) {
1014
+ process.stderr.write('[dsh-browser] reference delivery refused: browser-session-id-required\n')
1015
+ onFailure?.('browser-session-id-required')
1016
+ return false
1017
+ }
1018
+ try {
1019
+ deliveryQueue.prepare(reference, {
1020
+ failures: failures.map(failure => ({
1021
+ kind: (failure.kind === 'text' || failure.kind === 'image' || failure.kind === 'table'
1022
+ ? failure.kind : 'reference') as 'text' | 'image' | 'table' | 'reference',
1023
+ reason: failure.reason,
1024
+ })),
1025
+ })
1026
+ return true
1027
+ } catch (error) {
1028
+ process.stderr.write(`[dsh-browser] reference delivery prepare failed: ${String(error)}\n`)
1029
+ onFailure?.('delivery-enqueue-failed')
1030
+ return false
1031
+ }
1032
+ }
1033
+
1034
+ // The production draft adapter. `insertIntoDraft` used to answer
1035
+ // `draft-adapter-unavailable` because nothing ever registered one; now it
1036
+ // freezes the reference into the durable queue. The CLIENT decides when the
1037
+ // draft and assets are actually saved — only its ACK marks the delivery
1038
+ // acknowledged, never this enqueue (§12.1).
1039
+ //
1040
+ // NOTE: installReferenceRoutes always receives the queue, so `/reference/insert`
1041
+ // takes the `queue.prepare` branch and `insertIntoDraft` (hence this adapter)
1042
+ // is not reached in production. It is kept as the fallback for a caller that
1043
+ // constructs the routes WITHOUT a queue; removing it would make that path
1044
+ // silently lose the capture.
1045
+ referenceService.setDraftAdapter({
1046
+ insertReference: async (reference) => {
1047
+ const current = deliveryQueue.get(reference.referenceId)
1048
+ if (current?.state === 'removed') return { applied: false, reason: 'reference-was-removed' }
1049
+ // Only enqueue a capture that has no delivery yet, and HONOUR the result:
1050
+ // an unready session or a failed prepare must not report `applied: true`
1051
+ // for a card the client can never poll.
1052
+ if (current === undefined && !prepareCaptured(reference, [])) {
1053
+ return { applied: false, reason: 'delivery-enqueue-failed' }
1054
+ }
1055
+ return { applied: true }
1056
+ },
1057
+ })
1058
+
1059
+ /**
1060
+ * The one sentence the page shows when a capture produced no reference.
1061
+ *
1062
+ * Ordered from most actionable to least: the reader is told what to DO, not
1063
+ * which internal step failed.
1064
+ */
1065
+ const captureRefusalText = (failures: readonly { readonly reason: string }[]): string => {
1066
+ const copy = referenceCaptureMessages
1067
+ for (const failure of failures) {
1068
+ const reason = failure.reason
1069
+ const exact = copy[reason]
1070
+ if (exact !== undefined) return exact
1071
+ // Machine-coded reasons carry a detail suffix. A reader still deserves an
1072
+ // actionable sentence instead of the generic fallback.
1073
+ if (reason.startsWith('capture-failed:')) return referenceCaptureErrors.captureFailed
1074
+ if (reason.startsWith('store-refused:')) return referenceCaptureErrors.storeRefused
1075
+ if (reason.startsWith('frame-capture-refused:')) return copy['frame-capture-refused']
1076
+ if (reason.startsWith('cell-image:')) return referenceCaptureErrors.imageUnreadable
1077
+ if (reason.startsWith('image-')) return referenceCaptureErrors.imageFailed
1078
+ }
1079
+ return copy['capture-refused']
1080
+ }
1081
+
1082
+ // The self-hosted Electron host reports a right-click or a floating-button
1083
+ // press as a user action. Register the one handler that turns it into a
1084
+ // capture; the disposer keeps a plugin reload from leaving a stale closure.
1085
+ //
1086
+ // R01: `action.windowId` is `browser:<uuid>` — a BROWSER session / view, not a
1087
+ // DSH conversation. The real conversation id comes from `readSessionId(ctx)`
1088
+ // above (the same `ctx.get('agents').list()` the desktop host uses). Both are
1089
+ // recorded separately, and the owner is fixed at capture time, so switching
1090
+ // to another conversation later cannot move this reference.
1091
+ const disposeReferenceAction = setReferenceCaptureActionHandler(async action => {
1092
+ // Re-read: the agent list is empty while the plugin applies, so the id captured
1093
+ // at apply time can be missing exactly when the first capture arrives.
1094
+ const owner = resolveReferenceOwner(readSessionId(ctx) ?? sessionId, action.windowId)
1095
+ const outcome = await referenceService.capture({
1096
+ sessionId: owner.sessionId,
1097
+ browserSessionId: owner.browserSessionId,
1098
+ origin: 'user-selection',
1099
+ entry: action.entry,
1100
+ carrier: referenceCarrier(),
1101
+ ...action.frameSelector !== undefined ? { frameSelector: action.frameSelector } : {},
1102
+ ...action.target !== undefined ? { target: action.target } : {},
1103
+ ...action.comment !== undefined ? { comment: action.comment } : {},
1104
+ // The bar froze the WHOLE capture before its comment field took focus.
1105
+ // Only when that is missing (an older page script, a context-menu entry)
1106
+ // do we fall back to locating the frozen wording.
1107
+ ...action.capture !== undefined
1108
+ ? { frozenCapture: action.capture }
1109
+ : action.selectionText !== undefined && action.selectionText !== ''
1110
+ ? { excerptText: action.selectionText }
1111
+ : {},
1112
+ })
1113
+ if (outcome.reference === undefined) {
1114
+ process.stderr.write(`[dsh-browser] reference capture refused: ${outcome.failures.map(item => item.reason).join(', ')}\n`)
1115
+ // A refusal that is only logged looks like a dead button. Say it in the
1116
+ // page, where the click happened. `notify` MUST NOT be allowed to reject:
1117
+ // the provider's pump treats a thrown notification as an unreachable page
1118
+ // and retires the sidebar the human is still looking at after 5 strikes.
1119
+ try {
1120
+ await referenceService.notify(owner.browserSessionId, captureRefusalText(outcome.failures))
1121
+ } catch {
1122
+ // Best effort: the capture is already decided; a page that cannot be
1123
+ // notified must never escalate into tearing down the live sidebar.
1124
+ }
1125
+ return
1126
+ }
1127
+ let prepareFailure: PrepareFailure = 'delivery-enqueue-failed'
1128
+ if (!prepareCaptured(outcome.reference, outcome.failures, code => { prepareFailure = code })) {
1129
+ // The reference was saved but never entered the delivery queue. Without
1130
+ // this notice the button looks successful and no card EVER appears. The
1131
+ // code is short, stable and non-sensitive (no stack trace, no path).
1132
+ try {
1133
+ await referenceService.notify(owner.browserSessionId,
1134
+ `当前会话还没准备好,请稍后重新添加这条引用。(错误码:${prepareFailure})`)
1135
+ } catch {
1136
+ // Same as above: a failing notice must not reach the provider's pump.
1137
+ }
1138
+ }
1139
+ })
1140
+ ctx.effect(() => disposeReferenceAction, 'dsh-builtin-browser: reference action handler')
1141
+ ctx.effect(() => () => deliveryQueue.dispose(), 'dsh-builtin-browser: reference delivery queue')
1142
+ }
1143
+
1144
+ /**
1145
+ * Move a browser profile left behind by the old layout into the directory the plugin uses now.
1146
+ *
1147
+ * Before the `?.dsh` component was added here, a desktop launched from a shortcut (no `DSH_HOME`
1148
+ * in the environment) put its browser profile in `<homedir>/dsh-builtin-browser-host/` while its
1149
+ * settings and history lived in `<homedir>/.dsh/dsh-builtin-browser-host/`. Login state lives
1150
+ * INSIDE the browser profile, so leaving the old directory behind silently signs the user out of
1151
+ * everything they had signed into — reported after the fix shipped, as a one-time cost of it.
1152
+ *
1153
+ * That cost does not have to be paid. The move happens only when the new location is absent, so a
1154
+ * profile in use is never overwritten, and every failure — a cross-device rename, a permission
1155
+ * problem, a profile another process holds — falls through to an empty profile, which is exactly
1156
+ * what would have happened without this function. The old directory is then left untouched rather
1157
+ * than deleted, because a half-moved profile is worse than a stale one.
1158
+ *
1159
+ * @param profileRoot - the root the plugin resolves today (`<DSH_HOME>/dsh-builtin-browser-host`).
1160
+ * @param legacyRoot - the pre-`DSH_HOME` layout's root. Injected so the move can be exercised
1161
+ * without touching the real home directory.
1162
+ */
1163
+ export function adoptLegacyProfileRoot(
1164
+ profileRoot: string,
1165
+ legacyRoot: string = join(homedir(), BROWSER_PROFILE_DIR),
1166
+ ): void {
1167
+ try {
1168
+ if (legacyRoot === profileRoot) return
1169
+ if (!existsSync(legacyRoot) || existsSync(profileRoot)) return
1170
+ // `renameSync` needs the destination's PARENT to exist, and on a fresh install it does not:
1171
+ // the old layout never created `.dsh` at all. Creating it is harmless if it is already there.
1172
+ mkdirSync(dirname(profileRoot), { recursive: true })
1173
+ renameSync(legacyRoot, profileRoot)
1174
+ } catch {
1175
+ // Nothing here is worth failing an apply over; the fallback is the pre-existing behaviour.
1176
+ }
1177
+ }
1178
+
1179
+ /** What the frame route needs from the browser service. */
1180
+ interface PreviewBrowser {
1181
+ exists(session: string): boolean
1182
+ capturePassive(session: string, signal?: AbortSignal): Promise<{ readonly dataUrl: string }>
1183
+ watchableSessions?(): readonly string[]
1184
+ }
1185
+
1186
+ /** Bind the host's signed browser-session authentication to a plugin route. */
1187
+ function authenticated(ctx: Context, handler: BrowserHttpHandler): BrowserHttpHandler {
1188
+ return authenticatedRoute(() => {
1189
+ const surface = ctx as unknown as { get(name: string): BrowserConnection | undefined }
1190
+ return surface.get('connection')
1191
+ }, handler)
1192
+ }
1193
+
1194
+ function paired(ctx: Context, handler: BrowserHttpHandler): BrowserHttpHandler {
1195
+ return pairedRoute(() => {
1196
+ const surface = ctx as unknown as { get(name: string): BrowserPairingConnection | undefined }
1197
+ return surface.get('connection')
1198
+ }, handler)
1199
+ }
1200
+
1201
+ /** The host web-server surface this plugin uses, described structurally. */
1202
+ interface WebServerHost {
1203
+ readonly webServer: {
1204
+ register(
1205
+ spec: {
1206
+ readonly kind: 'exact'
1207
+ readonly path: string
1208
+ readonly handler: (request: IncomingMessage, response: ServerResponse) => void | Promise<void>
1209
+ },
1210
+ label?: string,
1211
+ ): () => void
1212
+ }
1213
+ effect(callback: () => (() => void) | void): void
1214
+ }
1215
+
1216
+ /**
1217
+ * Expose the settings document over the host's web server, which is how the
1218
+ * settings panel reads and writes it. A host without that service (headless /
1219
+ * CLI surfaces) simply skips this: the panel is then unreachable and the file
1220
+ * stays hand-editable — never a plugin-startup failure.
1221
+ * @param ctx - the plugin context.
1222
+ * @param settings - the settings document to expose.
1223
+ */
1224
+ function installSettingsRoute(
1225
+ ctx: Context,
1226
+ settings: SettingsStore,
1227
+ onChannelChange?: () => void,
1228
+ ): void {
1229
+ const inject = (ctx as unknown as {
1230
+ inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
1231
+ }).inject
1232
+ if (typeof inject !== 'function') return
1233
+ try {
1234
+ inject(['webServer'], (host) => {
1235
+ host.effect(() => host.webServer.register({
1236
+ kind: 'exact',
1237
+ path: SETTINGS_ROUTE,
1238
+ handler: authenticated(ctx, (request, response) => handleSettingsRequest(request, response, settings, onChannelChange)),
1239
+ }, 'dsh-builtin-browser: settings'))
1240
+ })
1241
+ } catch {
1242
+ // No web server on this surface: the settings file remains the interface.
1243
+ }
1244
+ }
1245
+
1246
+ /**
1247
+ * One settings round-trip: `GET` reads the document, `PUT`/`POST` merges a
1248
+ * partial patch into it. Admission lives in `settings-route.ts` so it can be tested.
1249
+ * @param request - the incoming request.
1250
+ * @param response - the response to write.
1251
+ * @param settings - the settings document.
1252
+ * @param onChannelChange - re-runs the carrier choice when this write changed carrier settings.
1253
+ */
1254
+ async function handleSettingsRequest(
1255
+ request: IncomingMessage,
1256
+ response: ServerResponse,
1257
+ settings: SettingsStore,
1258
+ onChannelChange?: () => void,
1259
+ ): Promise<void> {
1260
+ const json = (status: number, body: unknown): void => {
1261
+ writeJsonText(response, status, JSON.stringify(body), {
1262
+ 'content-type': 'application/json; charset=utf-8',
1263
+ 'cache-control': 'no-store',
1264
+ })
1265
+ }
1266
+ const method = request.method ?? 'GET'
1267
+ if (!sameOrigin(request, method !== 'GET')) {
1268
+ json(403, { ok: false, error: 'cross-origin request refused' })
1269
+ return
1270
+ }
1271
+ if (method === 'GET') {
1272
+ json(200, { ok: true, settings: settings.get(), path: settings.path() })
1273
+ return
1274
+ }
1275
+ if (method !== 'PUT' && method !== 'POST') {
1276
+ response.writeHead(405, { allow: 'GET, PUT' })
1277
+ response.end()
1278
+ return
1279
+ }
1280
+ try {
1281
+ const text = await readTextBody(request)
1282
+ const patch: unknown = text.trim() === '' ? {} : JSON.parse(text)
1283
+ const before = carrierSettingsKey(settings.get())
1284
+ const updated = settings.update(patch)
1285
+ // Changed carrier settings are a request to switch carriers, not just values to store. The
1286
+ // choice is re-run here so the write takes effect now — and the response says so, because a
1287
+ // caller that cannot tell "applied" from "stored for later" has no way to know what it got,
1288
+ // which is exactly how a write that did nothing read as a success.
1289
+ const carrierChanged = carrierSettingsKey(updated) !== before
1290
+ if (carrierChanged) onChannelChange?.()
1291
+ json(200, {
1292
+ ok: true,
1293
+ settings: updated,
1294
+ ...carrierChanged ? { carrierRechosen: true } : {},
1295
+ })
1296
+ } catch (error) {
1297
+ json(400, { ok: false, error: `invalid settings patch: ${String(error)}` })
1298
+ }
1299
+ }