dsh-builtin-browser 1.0.3 → 1.1.0

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