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,412 @@
1
+ /**
2
+ * Whether the desktop bridge is installed, and what state its files are in.
3
+ *
4
+ * Reported as issue #36: when the bridge is missing the plugin only logs a warning, so a user who
5
+ * chose `channel: sidebar` sees "another window opened again" and has no way to connect that with
6
+ * "the bridge is not installed". This module answers the question the panel needs to show, from the
7
+ * install tree on disk rather than from anything the plugin remembers.
8
+ *
9
+ * The states are the three that actually occur:
10
+ *
11
+ * - `installed` — the loaded main.js carries our marker and its bridge matches this plugin.
12
+ * - `missing` — no marker. Either never installed, or the shell was upgraded (which restores
13
+ * `app.asar` and replaces `lib/main.js`) and the bridge went with it.
14
+ * - `stale` — the archive is back, or the deployed bridge module is missing or outdated.
15
+ * @module dsh-browser/browser-electron/bridge-status
16
+ */
17
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'
18
+ import { homedir } from 'node:os'
19
+ import { isAbsolute, join, relative } from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
21
+ import { createRequire } from 'node:module'
22
+
23
+ import { desktopPaths, readDesktopIdentity } from './desktop-identity.ts'
24
+ import { classifyDesktopShell, noDesktopShell, tauriShell, type DesktopShellReport } from './desktop-shell.ts'
25
+ import { findTauriRuntime, runningTauriRuntime, tauriHostPatchStatus } from './tauri-host.ts'
26
+ import { MAIN_EXTENSION_UNSUPPORTED, type MainExtensionStatus } from './profile-extension.ts'
27
+ import { BRIDGE_VERSION_MESSAGE } from '../bridge-compatibility.ts'
28
+ import { conventionalInstallRoots, registeredInstallLocations } from '../../desktop-bridge/desktop-discovery.mjs'
29
+
30
+ // A normal Electron existsSync(app.asar) caches the archive and keeps it locked on Windows.
31
+ // Status inspection must leave maintenance free to rename it after Desktop exits.
32
+ const rawExistsSync: typeof existsSync = (() => {
33
+ try { return (createRequire(import.meta.url)('original-fs') as typeof import('node:fs')).existsSync }
34
+ catch { return existsSync }
35
+ })()
36
+
37
+ /**
38
+ * Find the desktop install to report on.
39
+ *
40
+ * Reported as issue #40: this used to probe for a *generic* Electron layout and return the first
41
+ * directory that had one. Any Electron app has that layout, so a stranger's app was reported as
42
+ * "DSH Desktop, bridge missing" — together with a ready-to-run installer command aimed at it. The
43
+ * probe now verifies the same identity the installer does (see `desktop-identity.js`), so the
44
+ * answer is about DSH Desktop and nothing else.
45
+ * @param localAppData - the base directory; defaults to the environment's.
46
+ * @returns the install directory, or undefined when nothing matches.
47
+ */
48
+ export function findDesktopInstall(
49
+ localAppData?: string,
50
+ registry: () => readonly string[] = registeredInstallLocations,
51
+ conventions: () => readonly string[] = conventionalInstallRoots,
52
+ ): string | undefined {
53
+ for (const candidate of desktopInstallCandidates(localAppData, registry, conventions)) {
54
+ if (readDesktopIdentity(candidate).ok) return candidate
55
+ }
56
+ return undefined
57
+ }
58
+
59
+ /**
60
+ * Classify the desktop shell on this machine.
61
+ *
62
+ * The DSH Tauri hosting this process wins; then a verified official install found by the same walk as
63
+ * {@link findDesktopInstall}; then an installed DSH Tauri; else the first recognised DSH-named shell
64
+ * (third-party or unsupported) is reported, so the settings page can say what it found instead of
65
+ * "no install" — and never offer to patch it.
66
+ * @param options - discovery overrides and the browser to recommend when the sidebar is unavailable.
67
+ * @returns the structured report.
68
+ */
69
+ export function detectDesktopShell(options: {
70
+ readonly localAppData?: string
71
+ readonly registry?: () => readonly string[]
72
+ readonly conventions?: () => readonly string[]
73
+ readonly preferredBrowser?: string
74
+ readonly platform?: NodeJS.Platform
75
+ readonly execPath?: string
76
+ readonly tauriRegistry?: () => readonly string[]
77
+ } = {}): DesktopShellReport {
78
+ const running = runningTauriRuntime(options.execPath)
79
+ if (running !== undefined) return tauriShell(running, tauriHostPatchStatus(running.runtime))
80
+ let recognised: DesktopShellReport | undefined
81
+ for (const candidate of desktopInstallCandidates(options.localAppData, options.registry, options.conventions)) {
82
+ const report = classifyDesktopShell(candidate, readDesktopIdentity(candidate), options)
83
+ if (report.kind === 'official-supported') return report
84
+ if (report.kind !== 'none' && recognised === undefined) recognised = report
85
+ }
86
+ const tauri = findTauriRuntime({ execPath: options.execPath, localAppData: options.localAppData, registry: options.tauriRegistry ?? options.registry })
87
+ if (tauri !== undefined) return tauriShell(tauri, tauriHostPatchStatus(tauri.runtime))
88
+ return recognised ?? noDesktopShell(options)
89
+ }
90
+
91
+ /**
92
+ * Every directory that might hold a desktop install, most specific first.
93
+ *
94
+ * Not every install lives in %LOCALAPPDATA%\\Programs: people put the app on another drive, under
95
+ * Program Files, or in their own folder. DSH_DESKTOP_PATH names one explicitly, and the usual roots
96
+ * are all probed. A test or a caller that passes a base directory gets exactly that base, so the
97
+ * behaviour stays pinnable. Candidates are unverified; callers check identity.
98
+ */
99
+ function* desktopInstallCandidates(
100
+ localAppData?: string,
101
+ registry: () => readonly string[] = registeredInstallLocations,
102
+ conventions: () => readonly string[] = conventionalInstallRoots,
103
+ ): Generator<string> {
104
+ for (const explicit of [process.env.DSH_DESKTOP_PATH, process.env.DSH_DESKTOP_APP]) {
105
+ if (explicit !== undefined && explicit !== '') {
106
+ yield explicit
107
+ // A parent directory is a reasonable thing to point at too: look one level down.
108
+ try {
109
+ for (const entry of readdirSync(explicit, { withFileTypes: true })) {
110
+ if (entry.isDirectory()) yield join(explicit, entry.name)
111
+ }
112
+ } catch {
113
+ // Not a directory: fall through to the usual roots.
114
+ }
115
+ }
116
+ }
117
+ const roots = localAppData === undefined ? desktopInstallRoots() : [join(localAppData, 'Programs')]
118
+ for (const base of roots) {
119
+ for (const named of DESKTOP_INSTALL_NAMES) yield join(base, named)
120
+ try {
121
+ for (const entry of readdirSync(base, { withFileTypes: true })) {
122
+ if (entry.isDirectory()) yield join(base, entry.name)
123
+ }
124
+ } catch {
125
+ // A root that does not exist is a state, not an error.
126
+ }
127
+ }
128
+ for (const source of [registry, conventions]) {
129
+ let found: readonly string[] = []
130
+ try { found = source() } catch {}
131
+ yield* found
132
+ }
133
+ }
134
+
135
+ /** Directory names an install is given: a plain directory on Windows, an `.app` bundle on macOS. */
136
+ const DESKTOP_INSTALL_NAMES = ['DSH Desktop', 'DeepSeek Harness', 'DSH Desktop.app', 'DeepSeek Harness.app']
137
+
138
+ /**
139
+ * Where this OS keeps installed applications, most specific first.
140
+ * @returns the existing-or-not base directories to probe.
141
+ */
142
+ function desktopInstallRoots(): string[] {
143
+ const windows = [process.env.LOCALAPPDATA ?? '', process.env['ProgramFiles'] ?? '', process.env['ProgramFiles(x86)'] ?? '', process.env.APPDATA ?? '', process.env.ProgramData ?? '']
144
+ .filter(base => base !== '')
145
+ .map(base => (base === process.env.LOCALAPPDATA ? join(base, 'Programs') : base))
146
+ // The machine-wide macOS roots cannot be redirected, so a test process never reads them.
147
+ const testing = process.env.DSH_BROWSER_TEST === '1' || process.env.NODE_TEST_CONTEXT !== undefined
148
+ return process.platform === 'darwin' && !testing ? [...windows, '/Applications', join(homedir(), 'Applications')] : windows
149
+ }
150
+
151
+ /** The marker the installer inserts into the shell's main.js. */
152
+ const MARKER = '// dsh-builtin-browser: hand the plugin a way to drive the sidebar'
153
+
154
+ /** One reading of the install tree. */
155
+ export interface BridgeStatus {
156
+ readonly mainExtension?: MainExtensionStatus
157
+ readonly code?: string
158
+ /** `installed`, `missing` or `stale`; see the module comment for what each means. */
159
+ readonly state: 'installed' | 'missing' | 'stale' | 'unsupported-layout'
160
+ /** Main entry the identity resolved, for an install this build has no patch spec for. */
161
+ readonly entry?: string
162
+ /** Whether the loaded application passed DSH Desktop identity verification. */
163
+ readonly present: boolean
164
+ /**
165
+ * The desktop build this reading belongs to, when the identity check could name one.
166
+ *
167
+ * The automatic install runs once per build: a desktop update is exactly when the bridge has to be
168
+ * installed again, so the guard needs to tell the two apart.
169
+ */
170
+ readonly version?: string
171
+ /** The directory that was inspected, when one was found. */
172
+ readonly installRoot?: string
173
+ /** Whether `resources/app.asar` exists — the archive the shell actually loads. */
174
+ readonly archivePresent: boolean
175
+ /** When the pre-bridge backup was written, if there is one. */
176
+ readonly backupAt?: string
177
+ /** A one-line explanation for the panel, in the plugin's own words. */
178
+ readonly detail: string
179
+ /**
180
+ * The command that installs or repairs the bridge.
181
+ *
182
+ * The panel can show this command for manual use. Its install button calls the same packaged
183
+ * installer through the separately authenticated local bridge-action route.
184
+ */
185
+ readonly command?: string
186
+ }
187
+
188
+ /**
189
+ * The installer script inside THIS plugin package.
190
+ *
191
+ * Reported as issue #40, fourth item: the panel told users to run
192
+ * `node desktop-bridge/install.mjs "<root>" --restart`, which assumes the reader is standing in a
193
+ * source checkout. Anyone who installed the plugin from npm or the market has no such relative path —
194
+ * the file lives inside the installed package, and there is nowhere sensible for them to run the
195
+ * command from. Resolving it from this module's own location is the difference between a hint and an
196
+ * instruction that works.
197
+ * @returns the absolute path, or undefined when the package layout is unexpected.
198
+ */
199
+ function installerScriptPath(): string | undefined {
200
+ try {
201
+ // lib/browser-electron/bridge-status.js → <package>/desktop-bridge/install.mjs
202
+ const url = new URL('../../desktop-bridge/install.mjs', import.meta.url)
203
+ const path = fileURLToPath(url)
204
+ return safeExists(path) ? path : undefined
205
+ } catch {
206
+ return undefined
207
+ }
208
+ }
209
+
210
+ /**
211
+ * The command a user should run for this state, quoted so it survives a path with spaces.
212
+ * @param installRoot - the install directory, or undefined when none was found.
213
+ * @returns the command line, or undefined when there is nothing useful to suggest.
214
+ */
215
+ function repairCommand(installRoot: string | undefined): string | undefined {
216
+ if (installRoot === undefined) return undefined
217
+ const script = installerScriptPath()
218
+ // No absolute path means the package is laid out in a way this module cannot navigate; the bare
219
+ // relative form is still better than nothing, but it is the fallback, not the default.
220
+ const runner = script === undefined ? 'desktop-bridge/install.mjs' : `"${script}"`
221
+ return `node ${runner} "${installRoot}"`
222
+ }
223
+
224
+ /**
225
+ * Read the bridge's state from an install directory.
226
+ *
227
+ * Never throws: a caller showing this in a settings panel must get an answer even when the directory
228
+ * is unreadable or the user pointed at something that is not an install.
229
+ * @param installRoot - the desktop install directory.
230
+ * @returns the current state.
231
+ */
232
+ export function readBridgeStatus(installRoot: string, mainExtension?: MainExtensionStatus): BridgeStatus {
233
+ const disk = readBridgeInstallStatus(installRoot)
234
+ if (mainExtension === undefined) return { ...disk, code: disk.code ?? MAIN_EXTENSION_UNSUPPORTED }
235
+ return { ...disk, mainExtension, command: undefined, detail: `desktop main extension: ${mainExtension.state}`,
236
+ state: mainExtension.state === 'loaded' ? 'installed' : mainExtension.state === 'not-installed' ? 'missing' : 'stale',
237
+ code: mainExtension.code }
238
+ }
239
+
240
+ /** The main entry the identity resolved for this install, when it can be read again cheaply. */
241
+ function identityEntry(installRoot: string): string | undefined {
242
+ const identity = readDesktopIdentity(installRoot)
243
+ return identity.ok ? identity.mainEntry : undefined
244
+ }
245
+
246
+ function readBridgeInstallStatus(installRoot: string): BridgeStatus {
247
+ let resources: string
248
+ try { resources = desktopPaths(installRoot).resources }
249
+ catch (error) {
250
+ return { state: 'missing', present: false, installRoot, archivePresent: false, detail: `not a DSH Desktop install: ${String(error)}` }
251
+ }
252
+ const appDir = join(resources, 'app')
253
+ // Follow the entry the identity actually resolved instead of assuming the legacy name. When it is
254
+ // not the entry our patch specs target, the install is recognized but cannot be patched yet — that
255
+ // is a distinct answer from "this is not DSH Desktop at all" (issue #112).
256
+ const mainPath = join(appDir, ...(identityEntry(installRoot) ?? 'lib/main.js').split('/'))
257
+ const archivePath = join(resources, 'app.asar')
258
+ const backupPath = `${mainPath}.before-bridge`
259
+
260
+ // Identity first, and before any other reading. Two reasons, both measured in issue #40: a
261
+ // stranger's app must not be reported as DSH Desktop, and this status also carries a *command* —
262
+ // pointing that command at a directory whose identity was never verified is how the installer got
263
+ // aimed at an application that merely looked like Electron.
264
+ const identity = readDesktopIdentity(installRoot)
265
+ if (!identity.ok) {
266
+ return {
267
+ state: 'missing',
268
+ present: false,
269
+ installRoot,
270
+ archivePresent: safeExists(archivePath),
271
+ detail: `not a DSH Desktop install: ${identity.reason}`,
272
+ }
273
+ }
274
+
275
+ const archivePresent = safeExists(archivePath)
276
+ const version = identity.version ?? 'unknown'
277
+ // A recognized DSH Desktop whose main entry we have no patch spec for. Reported as its own state so
278
+ // the panel can say "this desktop version has no patch yet, use the web sidebar" instead of either
279
+ // pretending the desktop is absent (#112) or offering an install that must fail.
280
+ const entry = identityEntry(installRoot) ?? 'lib/main.js'
281
+ if (entry !== 'lib/main.js') {
282
+ return {
283
+ state: 'unsupported-layout',
284
+ present: true,
285
+ installRoot,
286
+ archivePresent,
287
+ version,
288
+ entry,
289
+ detail: `DSH Desktop ${version} uses ${entry}, which this build has no host-patch spec for; the web sidebar works without it`,
290
+ }
291
+ }
292
+ const mainPresent = safeExists(mainPath)
293
+ if (!mainPresent && !archivePresent) {
294
+ // Unreachable once identity has passed (identity requires the loaded main entry), kept as the
295
+ // fail-closed branch for a tree that changed between the two reads.
296
+ return {
297
+ state: 'missing',
298
+ present: false,
299
+ installRoot,
300
+ archivePresent,
301
+ version,
302
+ detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
303
+ }
304
+ }
305
+ if (!rawExistsSync(archivePath)
306
+ && safeIncludes(mainPath, '//#region lib/types/main-extensions.js')
307
+ && safeExists(fileURLToPath(new URL('../../desktop-bridge/main.mjs', import.meta.url)))) {
308
+ return {
309
+ state: 'installed', present: true, installRoot, archivePresent: false,
310
+ detail: 'DSH Desktop main extension loads the bridge from the installed profile plugin',
311
+ ...identity.version === undefined ? {} : { version: identity.version },
312
+ command: repairCommand(installRoot),
313
+ }
314
+ }
315
+ let backupAt
316
+ try {
317
+ if (existsSync(backupPath)) backupAt = statSync(backupPath).mtime.toISOString()
318
+ } catch {
319
+ // A backup we cannot stat is simply not reported; it does not change the state.
320
+ }
321
+ if (archivePresent && !safeIncludes(mainPath, MARKER)) {
322
+ // The archive is what the shell loads, so an unpacked tree without our marker is not in effect
323
+ // even if it were patched.
324
+ return {
325
+ state: 'missing',
326
+ present: true,
327
+ installRoot,
328
+ archivePresent,
329
+ version,
330
+ ...backupAt === undefined ? {} : { backupAt },
331
+ command: repairCommand(installRoot),
332
+ detail: 'packed layout with no bridge in the loaded tree: the bridge is not installed',
333
+ }
334
+ }
335
+ if (archivePresent) {
336
+ return {
337
+ state: 'stale',
338
+ present: true,
339
+ installRoot,
340
+ archivePresent,
341
+ version,
342
+ ...backupAt === undefined ? {} : { backupAt },
343
+ command: repairCommand(installRoot),
344
+ detail: 'the archive is back alongside the patched tree, so the shell loads the archive: '
345
+ + 'a desktop update restored it. Re-run the installer to repair.',
346
+ }
347
+ }
348
+ if (!safeIncludes(mainPath, MARKER)) {
349
+ return {
350
+ state: 'missing',
351
+ present: true,
352
+ installRoot,
353
+ archivePresent,
354
+ version,
355
+ ...backupAt === undefined ? {} : { backupAt },
356
+ command: repairCommand(installRoot),
357
+ detail: 'unpacked layout without the bridge patch: the bridge is not installed',
358
+ }
359
+ }
360
+ const bridgePath = join(appDir, 'lib', 'plugin-browser-bridge.js')
361
+ let bridgeDetail: string | undefined
362
+ let bridgeCode: string | undefined
363
+ try {
364
+ const deployed = readFileSync(bridgePath)
365
+ const shipped = readFileSync(new URL('../../desktop-bridge/plugin-browser-bridge.js', import.meta.url))
366
+ const loader = readFileSync(new URL('../../desktop-bridge/profile-loader.mjs', import.meta.url))
367
+ if (deployed.equals(loader)) {
368
+ try {
369
+ const profile = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'profiles', 'desktop')
370
+ const manifest = JSON.parse(readFileSync(join(profile, 'package.json'), 'utf8'))
371
+ if (!Object.hasOwn(manifest.dependencies ?? {}, 'dsh-builtin-browser')) throw new Error('not a direct profile dependency')
372
+ const directory = realpathSync(join(profile, 'node_modules', 'dsh-builtin-browser'))
373
+ const entry = realpathSync(join(directory, 'desktop-bridge', 'plugin-browser-bridge.js'))
374
+ const child = relative(directory, entry)
375
+ if (!child || isAbsolute(child) || child === '..' || child.startsWith('../') || child.startsWith('..\\')) {
376
+ throw new Error('bridge entry resolves outside its package')
377
+ }
378
+ if (!readFileSync(entry).equals(shipped)) bridgeDetail = BRIDGE_VERSION_MESSAGE
379
+ } catch {
380
+ bridgeCode = 'DSH_BRIDGE_PACKAGE_UNAVAILABLE'
381
+ bridgeDetail = `${bridgeCode}: the profile loader's package bridge is missing, unreadable or outside its package`
382
+ }
383
+ } else if (!deployed.equals(shipped)) bridgeDetail = BRIDGE_VERSION_MESSAGE
384
+ } catch {
385
+ bridgeDetail = 'the bridge module is missing or cannot be verified; reinstall the bridge to restore it'
386
+ }
387
+ return {
388
+ state: bridgeDetail === undefined ? 'installed' : 'stale',
389
+ ...bridgeCode === undefined ? {} : { code: bridgeCode },
390
+ present: true,
391
+ installRoot,
392
+ archivePresent,
393
+ version,
394
+ ...backupAt === undefined ? {} : { backupAt },
395
+ command: repairCommand(installRoot),
396
+ detail: bridgeDetail ?? 'the shell loads the patched tree and its bridge module matches this plugin version',
397
+ }
398
+ }
399
+
400
+ /** Whether a path exists, treating any error as absence. */
401
+ function safeExists(path: string): boolean {
402
+ try { return rawExistsSync(path) } catch { return false }
403
+ }
404
+
405
+ /** Whether a file contains a string, treating any error as absence. */
406
+ function safeIncludes(path: string, needle: string): boolean {
407
+ try {
408
+ return existsSync(path) && statSync(path).isFile() && readFileSync(path, 'utf8').includes(needle)
409
+ } catch {
410
+ return false
411
+ }
412
+ }
@@ -0,0 +1,253 @@
1
+ import { CARRIER_CALL_TIMEOUT_MS, CARRIER_DOWNLOAD_TIMEOUT_MS, CARRIER_PROBE_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
2
+ /** Drive the visible sidebar guest through canonical, bridge-bound handles. */
3
+ import { BridgeConnection, type BridgeEndpoint } from './bridge-connection.ts'
4
+ import { readFileSync } from 'node:fs'
5
+ import { bridgeEndpointPath } from './paths.ts'
6
+ import { randomUUID } from 'node:crypto'
7
+ import { readTabHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId, type BrowserSessionWireId, type BrowserTabWireId } from '../browser/handles.ts'
8
+ import type { CommandOptions, ElectronBrowserViewHost, ElectronViewHandle, BrowserUserAction } from './provider.ts'
9
+ import type { CarrierPage, CarrierLossReason } from '../browser/types.ts'
10
+ import { BridgeVersionError, bridgePackageError, isBridgeVersionMismatch } from '../bridge-compatibility.ts'
11
+
12
+ export { bridgeEndpointPath }
13
+
14
+ const PANEL_NOT_DISPLAYED = 'panel-not-displayed'
15
+ const PANEL_INITIALIZING = 'panel-initializing'
16
+
17
+ export class BrowserPanelNotDisplayedError extends Error {
18
+ readonly code: string
19
+ constructor(detail: string, code = PANEL_NOT_DISPLAYED) {
20
+ super(`dsh-builtin-browser: this conversation's sidebar page did not attach (${detail})`)
21
+ this.name = 'BrowserPanelNotDisplayedError'
22
+ this.code = code
23
+ }
24
+ }
25
+
26
+ interface View {
27
+ readonly scope: BrowserSessionWireId
28
+ bound: boolean
29
+ adopted?: boolean
30
+ }
31
+
32
+ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
33
+ readonly referenceOverlayOwner = 'client' as const
34
+ private readonly connection: BridgeConnection
35
+ private readonly views = new Map<string, View>()
36
+ private readonly orphaned = new Map<BrowserTabWireId, BrowserSessionWireId>()
37
+ private activeScope: BrowserSessionWireId | undefined
38
+ private readonly retiredSessions = new Set<BrowserSessionWireId>()
39
+ private lostListener: ((reason: CarrierLossReason) => void) | undefined
40
+ private static refuseIframe = false
41
+ private static versionError: string | undefined
42
+ private readonly isQuiet: () => boolean
43
+ private constructor(endpoint: BridgeEndpoint, isQuiet: () => boolean = () => false) {
44
+ this.isQuiet = isQuiet
45
+ this.connection = new BridgeConnection(endpoint, bridgeEndpointPath(), () => this.lostListener?.('shell-exited'))
46
+ }
47
+
48
+ onLost(listener: (reason: CarrierLossReason) => void): void { this.lostListener = listener }
49
+ available(): boolean { return true }
50
+ static refusedIframePanel(): boolean { return this.refuseIframe }
51
+ static compatibilityError(): string | undefined { return this.versionError }
52
+
53
+ static async discover(_owner?: string, isQuiet?: () => boolean): Promise<DesktopBridgeViewHost | undefined> {
54
+ this.refuseIframe = false
55
+ this.versionError = undefined
56
+ let endpoint: BridgeEndpoint
57
+ try {
58
+ const raw = JSON.parse(readFileSync(bridgeEndpointPath(), 'utf8')) as Partial<BridgeEndpoint>
59
+ if (typeof raw.port !== 'number' || typeof raw.token !== 'string' || typeof raw.pid !== 'number') return undefined
60
+ endpoint = { port: raw.port, token: raw.token, pid: raw.pid, ...raw.updatedAt === undefined ? {} : { updatedAt: raw.updatedAt } }
61
+ } catch { return undefined }
62
+ const probe = new BridgeConnection(endpoint, bridgeEndpointPath())
63
+ try {
64
+ const answer = await probe.call({ op: 'list' }, CARRIER_PROBE_TIMEOUT_MS)
65
+ if (isBridgeVersionMismatch(answer)) throw new BridgeVersionError()
66
+ if (answer.ok !== true) return undefined
67
+ if (typeof answer.protocol !== 'number' || !Number.isInteger(answer.protocol)) throw new BridgeVersionError()
68
+ if (answer.frame === 'iframe') { this.refuseIframe = true; return undefined }
69
+ return new DesktopBridgeViewHost(endpoint, isQuiet)
70
+ } catch (error) {
71
+ const versionError = bridgePackageError(error) ?? (error instanceof BridgeVersionError ? error : undefined)
72
+ if (versionError !== undefined) {
73
+ this.versionError = versionError.message
74
+ throw versionError
75
+ }
76
+ return undefined
77
+ }
78
+ finally { probe.close() }
79
+ }
80
+
81
+ async listPages(scope: BrowserSessionWireId, _options: { readonly requireRunning?: boolean } = {}): Promise<readonly CarrierPage[]> {
82
+ resolveSessionHandle(scope)
83
+ const answer = await this.connection.call({ op: 'list', handle: scope }, CARRIER_PROBE_TIMEOUT_MS)
84
+ if (answer.ok !== true) throw new Error(String(answer.error ?? 'sidebar page listing failed'))
85
+ if (!Array.isArray(answer.sidebar)) throw new Error('invalid sidebar page listing')
86
+ const pages: CarrierPage[] = []
87
+ for (const page of answer.sidebar) {
88
+ if (typeof page?.id !== 'string') throw new Error('invalid sidebar page handle')
89
+ resolveTabHandle(resolveSessionHandle(scope), page.id)
90
+ if (!this.views.has(page.id)) pages.push({ id: page.id, url: String(page.url ?? ''), title: String(page.title ?? '') })
91
+ }
92
+ return pages
93
+ }
94
+
95
+ async adoptPage(id: BrowserTabWireId, scope = sessionWireId(readTabHandle(id))): Promise<ElectronViewHandle> {
96
+ const identity = tabWireId(resolveTabHandle(resolveSessionHandle(scope), id))
97
+ const answer = await this.connection.call({ op: 'adoptPage', handle: identity })
98
+ if (answer.ok !== true || answer.id !== id) throw new Error(String(answer.error ?? 'sidebar page adoption failed'))
99
+ const handle = this.createView(identity)
100
+ const entry = this.views.get(handle.id)!
101
+ entry.bound = true
102
+ entry.adopted = true
103
+ return handle
104
+ }
105
+
106
+ async closePage(id: BrowserTabWireId, scope = sessionWireId(readTabHandle(id))): Promise<void> {
107
+ const identity = tabWireId(resolveTabHandle(resolveSessionHandle(scope), id))
108
+ const blank = this.views.get(id)?.bound === false
109
+ const answer = await this.connection.call({ op: blank ? 'releaseTab' : 'closePage', handle: identity }, 10_000)
110
+ if (answer.ok !== true || (!blank && answer.closed !== 1)) throw new Error(`dsh-builtin-browser: could not close sidebar page: ${String(answer.error ?? 'close not acknowledged')}`)
111
+ this.views.delete(id)
112
+ this.orphaned.delete(id)
113
+ }
114
+
115
+ private async guestFor(id: BrowserTabWireId, url?: string, options?: CommandOptions, checkNavigation?: () => void): Promise<Record<string, unknown> | undefined> {
116
+ const entry = this.views.get(id)
117
+ if (entry === undefined) throw new Error('dsh-builtin-browser: sidebar view was released')
118
+ const check = (): void => {
119
+ options?.signal?.throwIfAborted()
120
+ checkNavigation?.()
121
+ if (this.views.get(id) !== entry) throw new Error('dsh-builtin-browser: sidebar view was released')
122
+ }
123
+ check()
124
+ if (entry.bound) return undefined
125
+ if (options?.initialize === false || options?.present === false) {
126
+ throw new BrowserPanelNotDisplayedError('this view has no attached guest yet', PANEL_INITIALIZING)
127
+ }
128
+ if (entry.adopted) throw new Error('dsh-builtin-browser: the sidebar page this view was adopted from is gone')
129
+ const deadline = options?.deadline ?? Date.now() + CARRIER_CALL_TIMEOUT_MS
130
+ const transactionId = randomUUID()
131
+ const cancel = (): void => { void this.connection.call({ op: 'cancelSidebar', handle: id, transactionId }, 2_000).catch(() => {}) }
132
+ options?.signal?.addEventListener('abort', cancel, { once: true })
133
+ let answer: Record<string, unknown>
134
+ try {
135
+ answer = await this.connection.call({ op: 'ensureSidebar', handle: id, deadline, transactionId,
136
+ ...url ? { url, attachOnly: true } : {} }, Math.max(1, deadline - Date.now()))
137
+ } finally { options?.signal?.removeEventListener('abort', cancel) }
138
+ check()
139
+ if (answer.ok !== true) {
140
+ const code = String(answer.code ?? 'panel-initialization-failed')
141
+ const detail = String(answer.error ?? 'sidebar unavailable')
142
+ if (code === PANEL_NOT_DISPLAYED || code === PANEL_INITIALIZING) throw new BrowserPanelNotDisplayedError(detail, code)
143
+ if (code === 'panel-unusable') this.lostListener?.('panel-unusable')
144
+ throw Object.assign(new Error(`dsh-builtin-browser: sidebar unavailable (${detail})`), { code, initialization: answer.initialization })
145
+ }
146
+ if (answer.id !== id) throw new Error('dsh-builtin-browser: sidebar returned a different tab handle')
147
+ entry.bound = true
148
+ return answer.navigation && typeof answer.navigation === 'object' ? answer.navigation as Record<string, unknown> : undefined
149
+ }
150
+
151
+ createView(identity: BrowserTabWireId): ElectronViewHandle {
152
+ const scope = sessionWireId(readTabHandle(identity))
153
+ if (this.retiredSessions.has(scope)) throw new Error('dsh-builtin-browser: sidebar session was released')
154
+ const id = identity
155
+ this.activeScope = scope
156
+ if (this.views.has(id)) throw new Error('dsh-builtin-browser: sidebar view is already bound')
157
+ this.views.set(id, { scope, bound: false })
158
+ let latestNavigation = 0
159
+ return {
160
+ id,
161
+ download: async (url, savePath) => {
162
+ await this.guestFor(id)
163
+ const answer = await this.connection.call({ op: 'download', handle: id, url, savePath }, CARRIER_DOWNLOAD_TIMEOUT_MS)
164
+ if (answer.ok !== true) throw new Error(`dsh-builtin-browser: sidebar download failed: ${String(answer.error)}`)
165
+ },
166
+ sendCommand: async (method, params, options) => {
167
+ const url = method === 'Page.navigate' ? String(params?.url ?? '') : undefined
168
+ const sequence = url === undefined ? latestNavigation : ++latestNavigation
169
+ const check = (): void => {
170
+ if (sequence !== latestNavigation) throw Object.assign(new Error('a newer navigation was requested for this sidebar view'), { code: 'panel-navigation-superseded' })
171
+ }
172
+ const navigation = await this.guestFor(id, url, options, check)
173
+ check()
174
+ if (navigation !== undefined) return navigation
175
+ const answer = await this.connection.call({ op: 'cdp', handle: id, method, params })
176
+ if (answer.ok !== true) throw Object.assign(new Error(`dsh-builtin-browser: sidebar command failed: ${String(answer.error)}`), { code: answer.code })
177
+ return (answer.result ?? {}) as Record<string, unknown>
178
+ },
179
+ }
180
+ }
181
+
182
+ destroyView(handle: ElectronViewHandle): void {
183
+ const entry = this.views.get(handle.id)
184
+ if (entry?.bound && !entry.adopted) this.orphaned.set(tabWireId(readTabHandle(handle.id)), entry.scope)
185
+ this.views.delete(handle.id)
186
+ }
187
+
188
+ showView(handle: ElectronViewHandle, _label?: string, options?: { readonly quiet?: boolean; readonly select?: boolean }): void {
189
+ if ((options?.quiet ?? this.isQuiet()) && options?.select !== true) return
190
+ if (!this.views.get(handle.id)?.bound) return
191
+ void this.connection.call({ op: 'showTab', handle: tabWireId(readTabHandle(handle.id)) }, CARRIER_PROBE_TIMEOUT_MS).catch(() => {})
192
+ }
193
+
194
+ onUserAction(_handler: (action: BrowserUserAction) => void): void {}
195
+
196
+ async presentView(handle: ElectronViewHandle, _label?: string, options?: { readonly quiet?: boolean; readonly select?: boolean }): Promise<void> {
197
+ if ((options?.quiet ?? this.isQuiet()) && options?.select !== true) return
198
+ const id = tabWireId(readTabHandle(handle.id))
199
+ await this.guestFor(id)
200
+ const answer = await this.connection.call({ op: 'showTab', handle: id })
201
+ if (answer.ok !== true) throw Object.assign(new Error(String(answer.error ?? 'sidebar selection failed')), { code: answer.code })
202
+ }
203
+
204
+ async retireSession(scope: BrowserSessionWireId): Promise<void> {
205
+ resolveSessionHandle(scope)
206
+ if (this.retiredSessions.has(scope)) return
207
+ this.retiredSessions.add(scope)
208
+ const answer = await this.connection.call({ op: 'releaseSession', handle: scope })
209
+ if (answer.ok !== true) throw new Error(String(answer.error ?? 'sidebar release failed'))
210
+ for (const [id, held] of this.orphaned) if (held === scope) this.orphaned.delete(id)
211
+ }
212
+
213
+ async releasePage(scope?: BrowserSessionWireId): Promise<void> {
214
+ if (scope !== undefined) resolveSessionHandle(scope)
215
+ const mine = new Set<BrowserTabWireId>()
216
+ const scopes = new Set<BrowserSessionWireId>()
217
+ for (const [id, entry] of this.views) {
218
+ if (scope !== undefined && entry.scope !== scope) continue
219
+ scopes.add(entry.scope)
220
+ if (entry.bound && !entry.adopted) mine.add(tabWireId(readTabHandle(id)))
221
+ this.views.delete(id)
222
+ }
223
+ for (const [id, held] of this.orphaned) {
224
+ if (scope !== undefined && held !== scope) continue
225
+ scopes.add(sessionWireId(readTabHandle(id)))
226
+ mine.add(tabWireId(readTabHandle(id)))
227
+ this.orphaned.delete(id)
228
+ }
229
+ if (scope !== undefined) scopes.add(scope)
230
+ try {
231
+ const results = await Promise.allSettled([...mine].map(async id => {
232
+ const answer = await this.connection.call({ op: 'closePage', handle: id }, 10_000)
233
+ if (answer.ok !== true || answer.closed !== 1) throw new Error(String(answer.error ?? 'sidebar close not acknowledged'))
234
+ }))
235
+ const failure = results.find(result => result.status === 'rejected')
236
+ if (failure?.status === 'rejected') throw failure.reason
237
+ } finally {
238
+ await Promise.all([...scopes].map(handle => this.retireSession(handle)))
239
+ }
240
+ }
241
+
242
+ async collapse(): Promise<void> {
243
+ if (this.activeScope === undefined) return
244
+ await this.connection.call({ op: 'collapseSidebar', handle: this.activeScope }, 10_000).catch(() => {})
245
+ }
246
+
247
+ dispose(): void {
248
+ this.connection.close()
249
+ this.views.clear()
250
+ this.orphaned.clear()
251
+ this.activeScope = undefined
252
+ }
253
+ }