dsh-builtin-browser 0.5.8 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (401) hide show
  1. package/CHANGELOG.md +410 -1
  2. package/README.en.md +16 -64
  3. package/README.md +33 -64
  4. package/assets/browser-carriers.svg +20 -0
  5. package/assets/browser-extension-identity.d.mts +2 -0
  6. package/assets/browser-extension-identity.mjs +2 -0
  7. package/assets/browser-messages.d.mts +5 -0
  8. package/assets/browser-messages.mjs +64 -0
  9. package/assets/browser-panel-locales.d.mts +2 -0
  10. package/assets/browser-panel-locales.mjs +380 -0
  11. package/assets/browser-policy.d.mts +37 -0
  12. package/assets/browser-policy.mjs +37 -0
  13. package/assets/browser-products.d.mts +6 -0
  14. package/assets/browser-products.mjs +76 -0
  15. package/assets/screenshots/1-main.png +0 -0
  16. package/assets/screenshots/2-form-fill.png +0 -0
  17. package/assets/screenshots/3-challenge.png +0 -0
  18. package/browser-extension/constants.mjs +20 -0
  19. package/browser-extension/controller.mjs +293 -0
  20. package/browser-extension/locales.mjs +15 -0
  21. package/browser-extension/manifest.json +12 -0
  22. package/browser-extension/options.html +14 -0
  23. package/browser-extension/options.mjs +9 -0
  24. package/browser-extension/permission-guard.mjs +13 -0
  25. package/browser-extension/worker.mjs +74 -0
  26. package/cordis.patch.yml +23 -48
  27. package/desktop-bridge/desktop-discovery.d.mts +2 -0
  28. package/desktop-bridge/desktop-discovery.mjs +36 -0
  29. package/desktop-bridge/desktop-identity.json +17 -1
  30. package/desktop-bridge/desktop-processes.d.mts +1 -0
  31. package/desktop-bridge/desktop-processes.mjs +15 -0
  32. package/desktop-bridge/guest-proxy.mjs +109 -0
  33. package/desktop-bridge/install.mjs +197 -74
  34. package/desktop-bridge/main.mjs +11 -0
  35. package/desktop-bridge/maintenance-files.d.mts +8 -0
  36. package/desktop-bridge/maintenance-files.mjs +28 -0
  37. package/desktop-bridge/maintenance-progress.ps1 +2 -2
  38. package/desktop-bridge/native-guests.mjs +41 -0
  39. package/desktop-bridge/plugin-browser-bridge.js +618 -370
  40. package/desktop-bridge/profile-loader.mjs +26 -0
  41. package/dist/client.cjs +43167 -0
  42. package/dist/client.d.cts +516 -0
  43. package/dist/client.d.mts +516 -0
  44. package/dist/index.cjs +92 -0
  45. package/dist/index.d.mts +2960 -0
  46. package/dist/index.mjs +24 -0
  47. package/docs/HANDOVER-2026-11-15.md +178 -0
  48. package/docs/README.md +10 -19
  49. package/docs/architecture.md +17 -145
  50. package/docs/child-tabs.md +13 -0
  51. package/docs/desktop-acceptance.md +9 -0
  52. package/docs/development.md +88 -18
  53. package/docs/extension-browser.md +44 -0
  54. package/docs/hardcoding-audit.md +64 -0
  55. package/docs/limitations.md +23 -73
  56. package/docs/pr64-extension-status.md +46 -0
  57. package/docs/pr64-maintenance.md +25 -0
  58. package/docs/pr64-native-children.md +52 -0
  59. package/docs/pr64-native-views.md +60 -0
  60. package/docs/tool-reference.md +87 -11
  61. package/docs/user-guide.md +47 -255
  62. package/docs/why-browser.md +6 -39
  63. package/dsh-host-patch/README.md +60 -0
  64. package/dsh-host-patch/apply.mjs +194 -0
  65. package/dsh-host-patch/legacy-bridge.mjs +53 -0
  66. package/dsh-host-patch/rc3-revision1.json +90 -0
  67. package/dsh-host-patch/rc3-revision2.json +112 -0
  68. package/dsh-host-patch/rc3-revision3.json.gz +0 -0
  69. package/dsh-host-patch/rc3-revision4.json.gz +0 -0
  70. package/dsh-host-patch/rc3-revision5.json.gz +0 -0
  71. package/dsh-host-patch/rc3-revision6.json.gz +0 -0
  72. package/dsh-host-patch/rc3-revision7.json.gz +0 -0
  73. package/dsh-host-patch/rc3-revision8.json.gz +0 -0
  74. package/dsh-host-patch/rc3.json +148 -0
  75. package/dsh-host-patch/rc5-revision1.json +90 -0
  76. package/dsh-host-patch/rc5-revision2.json +112 -0
  77. package/dsh-host-patch/rc5-revision3.json.gz +0 -0
  78. package/dsh-host-patch/rc5-revision4.json.gz +0 -0
  79. package/dsh-host-patch/rc5-revision5.json.gz +0 -0
  80. package/dsh-host-patch/rc5-revision6.json.gz +0 -0
  81. package/dsh-host-patch/rc5-revision7.json.gz +0 -0
  82. package/dsh-host-patch/rc5-revision8.json.gz +0 -0
  83. package/dsh-host-patch/rc5.json +148 -0
  84. package/lib/bridge-compatibility.js +38 -0
  85. package/lib/browser/handles.js +78 -0
  86. package/lib/browser/runtime.js +155 -43
  87. package/lib/browser/takeover-target.js +24 -0
  88. package/lib/browser-electron/authenticated-route.js +23 -0
  89. package/lib/browser-electron/automatic-maintenance.js +394 -51
  90. package/lib/browser-electron/bridge-auto.js +2 -1
  91. package/lib/browser-electron/bridge-connection.js +8 -1
  92. package/lib/browser-electron/bridge-install.js +27 -2
  93. package/lib/browser-electron/bridge-maintenance.js +35 -10
  94. package/lib/browser-electron/bridge-status.js +98 -27
  95. package/lib/browser-electron/desktop-bridge-host.js +193 -560
  96. package/lib/browser-electron/desktop-identity.js +40 -2
  97. package/lib/browser-electron/document-readiness.js +34 -0
  98. package/lib/browser-electron/electron-provision.js +14 -44
  99. package/lib/browser-electron/entry.js +659 -252
  100. package/lib/browser-electron/extension-browser.js +234 -0
  101. package/lib/browser-electron/extension-setup.js +69 -0
  102. package/lib/browser-electron/guest-cookie-jar.LICENSE.txt +32 -0
  103. package/lib/browser-electron/guest-cookie-jar.js +10559 -0
  104. package/lib/browser-electron/guest-cookie-store.js +74 -0
  105. package/lib/browser-electron/guest-css-runtime.js +75 -0
  106. package/lib/browser-electron/guest-css.js +106 -0
  107. package/lib/browser-electron/guest-route.js +603 -0
  108. package/lib/browser-electron/guest-runtime.js +356 -0
  109. package/lib/browser-electron/guest-storage-runtime.js +52 -0
  110. package/lib/browser-electron/guest-storage.js +163 -0
  111. package/lib/browser-electron/history-store.js +2 -1
  112. package/lib/browser-electron/host-main.js +162 -7
  113. package/lib/browser-electron/host-patch-maintenance.js +141 -0
  114. package/lib/browser-electron/http-body.js +22 -0
  115. package/lib/browser-electron/maintenance-broker.js +35 -5
  116. package/lib/browser-electron/maintenance-lifecycle.js +7 -5
  117. package/lib/browser-electron/maintenance-route.js +9 -6
  118. package/lib/browser-electron/open-slot.js +47 -0
  119. package/lib/browser-electron/paths.js +4 -1
  120. package/lib/browser-electron/preferred-browser.js +144 -0
  121. package/lib/browser-electron/preview-route.js +11 -8
  122. package/lib/browser-electron/process-ownership.js +198 -0
  123. package/lib/browser-electron/profile-checkpoint.js +222 -0
  124. package/lib/browser-electron/profile-command.js +60 -0
  125. package/lib/browser-electron/profile-extension.js +126 -0
  126. package/lib/browser-electron/profile-lease.js +157 -0
  127. package/lib/browser-electron/profile-residue.js +61 -0
  128. package/lib/browser-electron/provider.js +719 -262
  129. package/lib/browser-electron/reference-route.js +635 -0
  130. package/lib/browser-electron/remote-host.js +12 -13
  131. package/lib/browser-electron/runtime-route.js +6 -5
  132. package/lib/browser-electron/runtime-status.js +30 -29
  133. package/lib/browser-electron/settings-store.js +10 -5
  134. package/lib/browser-electron/shortcuts-route.js +108 -0
  135. package/lib/browser-electron/sidebar-only-host.js +119 -18
  136. package/lib/browser-electron/startpage-shortcuts.js +172 -0
  137. package/lib/browser-electron/system-browser.js +352 -371
  138. package/lib/browser-electron/windows-system.js +2 -1
  139. package/lib/browser-reference/delivery.js +326 -0
  140. package/lib/browser-reference/entry.js +597 -0
  141. package/lib/browser-reference/export.js +298 -0
  142. package/lib/browser-reference/import.js +295 -0
  143. package/lib/browser-reference/page-script.js +1406 -0
  144. package/lib/browser-reference/service.js +1062 -0
  145. package/lib/browser-reference/store.js +177 -0
  146. package/lib/browser-reference/submission-receipts.js +139 -0
  147. package/lib/browser-reference/text-quote.js +167 -0
  148. package/lib/browser-reference/types.js +11 -0
  149. package/lib/browser-reference/visible.js +311 -0
  150. package/lib/browser-reference/web-sources.js +97 -0
  151. package/lib/index.js +10 -3
  152. package/lib/reference-owner.js +5 -0
  153. package/lib/reference-page.js +12 -0
  154. package/lib/reference-source.js +2 -0
  155. package/lib/reference-text.js +188 -0
  156. package/lib/startpage-settings.js +63 -0
  157. package/lib/startpage.js +44 -0
  158. package/lib/takeover-protocol.js +2 -0
  159. package/lib/tool-browser/code-tool.js +416 -0
  160. package/lib/tool-browser/code-worker.js +872 -0
  161. package/lib/tool-browser/index.js +940 -76
  162. package/lib/tool-browser/page-probe.js +3 -3
  163. package/lib/tool-browser/panel-page.js +95 -0
  164. package/lib/tool-browser/screenshot-image.js +51 -0
  165. package/lib/tool-browser/takeover.js +205 -0
  166. package/lib/types.js +1 -0
  167. package/lib/web-guest.js +26 -0
  168. package/native-host/client.d.mts +17 -0
  169. package/native-host/client.mjs +100 -0
  170. package/native-host/host.mjs +150 -0
  171. package/native-host/identity.d.mts +2 -0
  172. package/native-host/identity.mjs +1 -0
  173. package/native-host/install.mjs +168 -0
  174. package/native-host/protocol.mjs +75 -0
  175. package/package.json +80 -92
  176. package/scripts/build.mjs +66 -0
  177. package/scripts/bundle-host.mjs +28 -0
  178. package/scripts/fix-exports.mjs +50 -0
  179. package/scripts/install-electron.mjs +11 -26
  180. package/scripts/verify-exports.mjs +47 -0
  181. package/scripts/verify-preview-sdk.mjs +93 -0
  182. package/skills/dsh-builtin-browser/SKILL.md +56 -47
  183. package/skills/dsh-builtin-browser/references/batch.md +31 -1
  184. package/skills/dsh-debug-host/SKILL.md +56 -0
  185. package/skills/dsh-debug-self/SKILL.md +50 -0
  186. package/src/bridge-compatibility.ts +39 -0
  187. package/src/browser/handles.ts +89 -0
  188. package/src/browser/runtime.ts +146 -50
  189. package/src/browser/takeover-target.ts +36 -0
  190. package/src/browser/types.ts +19 -7
  191. package/src/browser-electron/authenticated-route.ts +29 -1
  192. package/src/browser-electron/automatic-maintenance.ts +368 -56
  193. package/src/browser-electron/bridge-auto.ts +5 -4
  194. package/src/browser-electron/bridge-connection.ts +20 -2
  195. package/src/browser-electron/bridge-endpoint.ts +3 -3
  196. package/src/browser-electron/bridge-install.ts +40 -4
  197. package/src/browser-electron/bridge-maintenance.ts +42 -14
  198. package/src/browser-electron/bridge-status.ts +94 -23
  199. package/src/browser-electron/desktop-bridge-host.ts +185 -585
  200. package/src/browser-electron/desktop-identity.ts +53 -2
  201. package/src/browser-electron/document-readiness.ts +45 -0
  202. package/src/browser-electron/electron-provision.ts +12 -45
  203. package/src/browser-electron/entry.ts +1299 -882
  204. package/src/browser-electron/ephemeral-profile.ts +1 -1
  205. package/src/browser-electron/extension-browser.ts +223 -0
  206. package/src/browser-electron/extension-setup.ts +67 -0
  207. package/src/browser-electron/guest-cookie-jar.ts +176 -0
  208. package/src/browser-electron/guest-cookie-store.ts +59 -0
  209. package/src/browser-electron/guest-css-runtime.ts +76 -0
  210. package/src/browser-electron/guest-css.ts +68 -0
  211. package/src/browser-electron/guest-route.ts +568 -0
  212. package/src/browser-electron/guest-runtime.ts +357 -0
  213. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  214. package/src/browser-electron/guest-storage.ts +117 -0
  215. package/src/browser-electron/history-store.ts +5 -4
  216. package/src/browser-electron/host-main.ts +156 -11
  217. package/src/browser-electron/host-patch-maintenance.ts +112 -0
  218. package/src/browser-electron/http-body.ts +23 -0
  219. package/src/browser-electron/maintenance-broker.ts +29 -5
  220. package/src/browser-electron/maintenance-lifecycle.ts +14 -9
  221. package/src/browser-electron/maintenance-route.ts +17 -14
  222. package/src/browser-electron/missing-system-browser.ts +2 -2
  223. package/src/browser-electron/open-slot.ts +49 -0
  224. package/src/browser-electron/paths.ts +5 -1
  225. package/src/browser-electron/preferred-browser.ts +120 -0
  226. package/src/browser-electron/preview-route.ts +18 -11
  227. package/src/browser-electron/process-ownership.ts +168 -0
  228. package/src/browser-electron/profile-checkpoint.ts +187 -0
  229. package/src/browser-electron/profile-command.ts +46 -0
  230. package/src/browser-electron/profile-extension.ts +124 -0
  231. package/src/browser-electron/profile-lease.ts +115 -0
  232. package/src/browser-electron/profile-residue.ts +49 -0
  233. package/src/browser-electron/provider.ts +771 -289
  234. package/src/browser-electron/reference-route.ts +608 -0
  235. package/src/browser-electron/remote-host.ts +15 -15
  236. package/src/browser-electron/runtime-route.ts +11 -10
  237. package/src/browser-electron/runtime-status.ts +51 -32
  238. package/src/browser-electron/settings-store.ts +27 -7
  239. package/src/browser-electron/shortcuts-route.ts +112 -0
  240. package/src/browser-electron/sidebar-only-host.ts +118 -19
  241. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  242. package/src/browser-electron/system-browser.ts +309 -338
  243. package/src/browser-electron/windows-system.ts +2 -1
  244. package/src/browser-reference/delivery.ts +384 -0
  245. package/src/browser-reference/entry.ts +631 -0
  246. package/src/browser-reference/export.ts +339 -0
  247. package/src/browser-reference/import.ts +303 -0
  248. package/src/browser-reference/page-script.ts +1537 -0
  249. package/src/browser-reference/service.ts +1315 -0
  250. package/src/browser-reference/store.ts +172 -0
  251. package/src/browser-reference/submission-receipts.ts +122 -0
  252. package/src/browser-reference/text-quote.ts +219 -0
  253. package/src/browser-reference/types.ts +195 -0
  254. package/src/browser-reference/visible.ts +367 -0
  255. package/src/browser-reference/web-sources.ts +103 -0
  256. package/src/client/browser/BrowserController.ts +693 -0
  257. package/src/client/browser/BrowserFrame.ts +78 -0
  258. package/src/client/browser/BrowserNavigation.ts +169 -0
  259. package/src/client/browser/BrowserPage.ts +23 -0
  260. package/src/client/browser/BrowserPersistence.ts +44 -0
  261. package/src/client/browser/IframeImpl.ts +176 -0
  262. package/src/client/browser/child-tabs.ts +14 -0
  263. package/src/client/browser/iframe-reference.ts +67 -0
  264. package/src/client/browser/initialization.ts +262 -0
  265. package/src/client/browser/omnibox.ts +243 -0
  266. package/src/client/browser/store.ts +38 -0
  267. package/src/client/browser/takeover-channel.ts +72 -0
  268. package/src/client/browser/url.ts +46 -0
  269. package/src/client/browser/web-reference-source.ts +52 -0
  270. package/src/client/css-modules.d.ts +4 -0
  271. package/src/client/definition.tsx +30 -0
  272. package/src/client/electron/ElectronWebViewImpl.ts +364 -0
  273. package/src/client/electron/ElectronWebviewPresentation.ts +138 -0
  274. package/src/client/electron/NativeChildPresentation.ts +45 -0
  275. package/src/client/electron/NativeViewPage.ts +251 -0
  276. package/src/client/electron/pages.ts +23 -0
  277. package/src/client/electron/reference-overlay.ts +53 -0
  278. package/src/client/electron/workspace.ts +33 -0
  279. package/src/client/index.ts +293 -0
  280. package/src/client/locales.ts +857 -0
  281. package/src/client/pages.ts +28 -0
  282. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  283. package/src/client/reference/client/draft-reference.ts +167 -0
  284. package/src/client/reference/client/index.ts +7 -0
  285. package/src/client/reference/client/ordered-submission.ts +108 -0
  286. package/src/client/reference/client/pending-delivery.ts +216 -0
  287. package/src/client/reference/client/plugin.ts +189 -0
  288. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  289. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  290. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  291. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  292. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  293. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  294. package/src/client/reference/client/production/assembly.ts +471 -0
  295. package/src/client/reference/client/production/asset-store.ts +144 -0
  296. package/src/client/reference/client/production/availability.ts +74 -0
  297. package/src/client/reference/client/production/bytes.ts +36 -0
  298. package/src/client/reference/client/production/delivery-client.ts +211 -0
  299. package/src/client/reference/client/production/draft-adapter.ts +508 -0
  300. package/src/client/reference/client/production/http-transport.ts +217 -0
  301. package/src/client/reference/client/production/production-submission.ts +310 -0
  302. package/src/client/reference/client/production/protocol.ts +231 -0
  303. package/src/client/reference/client/production/reference-card.ts +240 -0
  304. package/src/client/reference/client/production/reference-labels.ts +29 -0
  305. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  306. package/src/client/reference/client/production/reveal.ts +215 -0
  307. package/src/client/reference/client/production/runtime.ts +1101 -0
  308. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  309. package/src/client/reference/client/production/source-marker.ts +63 -0
  310. package/src/client/reference/client/production/source-opener.ts +55 -0
  311. package/src/client/reference/client/production/styles.ts +104 -0
  312. package/src/client/reference/client/production/user-text-rule.ts +58 -0
  313. package/src/client/reference/client/reveal.ts +107 -0
  314. package/src/client/reference/client/scheme.ts +114 -0
  315. package/src/client/reference/client/types.ts +168 -0
  316. package/src/client/reference/css-modules.d.ts +4 -0
  317. package/src/client/reference/index.ts +11 -0
  318. package/src/client/reference-capture-owner.ts +162 -0
  319. package/src/client/reference-intents.ts +36 -0
  320. package/src/client/settings/index.ts +34 -0
  321. package/{client.js → src/client/settings/panel.ts} +2657 -2231
  322. package/src/client/shortcut-open.ts +30 -0
  323. package/src/client/startpage/binding.ts +99 -0
  324. package/src/client/startpage/controller.ts +303 -0
  325. package/src/client/startpage/model.ts +279 -0
  326. package/src/client/view/Browser.module.css +751 -0
  327. package/src/client/view/BrowserBody.tsx +314 -0
  328. package/src/client/view/BrowserPresentation.ts +9 -0
  329. package/src/client/view/BrowserTitle.tsx +17 -0
  330. package/src/client/view/IframePresentation.ts +344 -0
  331. package/src/client/view/StartPage.tsx +597 -0
  332. package/src/client/view/TakeoverBanner.tsx +21 -0
  333. package/src/index.ts +110 -73
  334. package/src/reference-owner.ts +5 -0
  335. package/src/reference-page.ts +9 -0
  336. package/src/reference-source.ts +3 -0
  337. package/src/reference-text.ts +197 -0
  338. package/src/startpage-settings.ts +103 -0
  339. package/src/startpage.ts +71 -0
  340. package/src/takeover-protocol.ts +19 -0
  341. package/src/tool-browser/code-tool.ts +401 -0
  342. package/src/tool-browser/code-worker.ts +639 -0
  343. package/src/tool-browser/index.ts +908 -77
  344. package/src/tool-browser/page-probe.ts +4 -4
  345. package/src/tool-browser/panel-page.ts +124 -0
  346. package/src/tool-browser/screenshot-image.ts +49 -0
  347. package/src/tool-browser/takeover.ts +198 -0
  348. package/src/types/electron-shim.d.ts +20 -0
  349. package/src/types.ts +85 -0
  350. package/src/web-guest.ts +34 -0
  351. package/tools/accept-desktop.mjs +148 -0
  352. package/lib/browser/runtime.d.ts +0 -175
  353. package/lib/browser/types.d.ts +0 -797
  354. package/lib/browser-electron/authenticated-route.d.ts +0 -27
  355. package/lib/browser-electron/automatic-maintenance.d.ts +0 -41
  356. package/lib/browser-electron/bridge-auto.d.ts +0 -93
  357. package/lib/browser-electron/bridge-connection.d.ts +0 -93
  358. package/lib/browser-electron/bridge-endpoint.d.ts +0 -30
  359. package/lib/browser-electron/bridge-install.d.ts +0 -85
  360. package/lib/browser-electron/bridge-maintenance.d.ts +0 -24
  361. package/lib/browser-electron/bridge-status.d.ts +0 -50
  362. package/lib/browser-electron/desktop-bridge-host.d.ts +0 -248
  363. package/lib/browser-electron/desktop-identity.d.ts +0 -58
  364. package/lib/browser-electron/electron-provision.d.ts +0 -92
  365. package/lib/browser-electron/entry.d.ts +0 -64
  366. package/lib/browser-electron/ephemeral-profile.d.ts +0 -37
  367. package/lib/browser-electron/file-write.d.ts +0 -2
  368. package/lib/browser-electron/history-store.d.ts +0 -98
  369. package/lib/browser-electron/host-main.d.ts +0 -26
  370. package/lib/browser-electron/http-body.d.ts +0 -24
  371. package/lib/browser-electron/json-reply.d.ts +0 -33
  372. package/lib/browser-electron/maintenance-broker.d.ts +0 -35
  373. package/lib/browser-electron/maintenance-lifecycle.d.ts +0 -32
  374. package/lib/browser-electron/maintenance-route.d.ts +0 -18
  375. package/lib/browser-electron/missing-system-browser.d.ts +0 -54
  376. package/lib/browser-electron/paths.d.ts +0 -4
  377. package/lib/browser-electron/preview-route.d.ts +0 -89
  378. package/lib/browser-electron/process.d.ts +0 -14
  379. package/lib/browser-electron/provider.d.ts +0 -959
  380. package/lib/browser-electron/remote-host.d.ts +0 -256
  381. package/lib/browser-electron/rpc-input.d.ts +0 -4
  382. package/lib/browser-electron/rpc-ops.d.ts +0 -18
  383. package/lib/browser-electron/runtime-diagnostics.d.ts +0 -12
  384. package/lib/browser-electron/runtime-route.d.ts +0 -55
  385. package/lib/browser-electron/runtime-status.d.ts +0 -116
  386. package/lib/browser-electron/settings-route.d.ts +0 -15
  387. package/lib/browser-electron/settings-store.d.ts +0 -224
  388. package/lib/browser-electron/sidebar-only-host.d.ts +0 -36
  389. package/lib/browser-electron/system-browser.d.ts +0 -367
  390. package/lib/browser-electron/timing.d.ts +0 -8
  391. package/lib/browser-electron/virtual-cursor.d.ts +0 -67
  392. package/lib/browser-electron/windows-system.d.ts +0 -3
  393. package/lib/index.d.ts +0 -30
  394. package/lib/tool-browser/element-fields.d.ts +0 -145
  395. package/lib/tool-browser/index.d.ts +0 -53
  396. package/lib/tool-browser/page-probe.d.ts +0 -86
  397. package/scripts/consumer-install-check.mjs +0 -72
  398. package/scripts/run-tests.mjs +0 -32
  399. package/scripts/verify-host-compat.mjs +0 -195
  400. package/scripts/verify-preview-route.mjs +0 -168
  401. package/scripts/verify-runtime-status.mjs +0 -179
@@ -21,13 +21,15 @@
21
21
  * `$DSH_HOME/dsh-builtin-browser-bridge.json` so the plugin can find it without
22
22
  * any user configuration.
23
23
  */
24
- import { createServer } from 'node:net'
25
- import { randomBytes } from 'node:crypto'
26
- import { writeFileSync, mkdirSync, constants } from 'node:fs'
24
+ import { createServer, connect as netConnect } from 'node:net'
25
+ import { randomBytes, randomUUID, createHash } from 'node:crypto'
26
+ import { writeFileSync, mkdirSync, readFileSync, unlinkSync, constants } from 'node:fs'
27
27
  import { open, mkdir, unlink, link, copyFile } from 'node:fs/promises'
28
28
  import { homedir } from 'node:os'
29
- import { join, dirname, isAbsolute } from 'node:path'
29
+ import { join, dirname, isAbsolute, resolve } from 'node:path'
30
30
  import { app, webContents } from 'electron'
31
+ import { sidebarProxyConfig, parseSystemProxy, normalizeGuestUserAgent, shouldFallbackToSystemProxy, DEFAULT_SIDEBAR_PROXY_BYPASS } from './guest-proxy.mjs'
32
+ import { nativeGuestRegistry } from './native-guests.mjs'
31
33
 
32
34
  /**
33
35
  * The conversation's sidebar panel exists but the shell is not displaying that conversation, so no
@@ -40,6 +42,8 @@ import { app, webContents } from 'electron'
40
42
  */
41
43
  const PANEL_NOT_DISPLAYED = 'panel-not-displayed'
42
44
  const PANEL_INITIALIZING = 'panel-initializing'
45
+ const RENDERING_RELEASE_TIMEOUT_MS = 2000
46
+ const RENDERING_HOLD_MS = 30_000
43
47
 
44
48
  /**
45
49
  * An Error carrying a stable code, so the code survives the socket as a field rather than as text a
@@ -66,8 +70,8 @@ function codedError(code, message) {
66
70
  * Measured on DSH Desktop 0.2.0-rc.2, launched from a shortcut (no DSH_HOME in
67
71
  * its environment).
68
72
  */
69
- function endpointFile() {
70
- const home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
73
+ function endpointFile(dshHome) {
74
+ const home = dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh')
71
75
  return join(home, 'dsh-builtin-browser-bridge.json')
72
76
  }
73
77
 
@@ -87,7 +91,12 @@ const queues = new Map()
87
91
  * place where "who holds what" can be a single shared fact. Owners are per-process ids supplied
88
92
  * by the plugin; an entry is dropped when its guest disappears so a closed tab can be reused.
89
93
  */
90
- const claims = new Map()
94
+ const handles = new Map()
95
+ const retiredHandles = new Set()
96
+ const retiredSessions = new Set()
97
+ // Only pending URL opens participate. A passive guest lookup never cancels a navigation.
98
+ const pendingSidebarOpens = new Map()
99
+ const activeRequests = new Set()
91
100
 
92
101
  /**
93
102
  * When this module was loaded, and the protocol generation it speaks.
@@ -98,7 +107,7 @@ const claims = new Map()
98
107
  * acceptance script compares this against the file's mtime and says so before testing anything.
99
108
  */
100
109
  const LOADED_AT = new Date().toISOString()
101
- const PROTOCOL = 3
110
+ const PROTOCOL = 4
102
111
 
103
112
  /**
104
113
  * The DOM root of THIS conversation's sidebar, as JavaScript to embed in a page script.
@@ -202,33 +211,18 @@ async function evaluateInPanel(shellId, sessionId, method, params) {
202
211
  return { result: { value: text } }
203
212
  }
204
213
 
205
- /** Forget claims whose guest no longer exists, so a closed tab's id is not held forever. */
206
- function pruneClaims() {
207
- const live = new Set(webContents.getAllWebContents().filter(c => c.getType() === 'webview').map(c => c.id))
208
- for (const id of [...claims.keys()]) if (!live.has(id)) claims.delete(id)
209
- }
210
-
211
- /** The single ownership gate for every op that drives a guest: the ledger is the only proof. */
212
- async function assertGuestOwner(id, owner) {
213
- pruneClaims()
214
- if (claims.get(id) === owner) return
215
- // A bridge restart, or a host that cached a guest id before the ledger existed, can leave a
216
- // legitimate guest unclaimed. Ask the renderer once on this cold path and re-register it.
217
- const shell = webContents.getAllWebContents().find(contents => contents.getType() === 'window')
218
- if (shell !== undefined && /^session-/.test(owner)) {
219
- const ids = await panelGuestIds(shell, owner).catch(() => [])
220
- if (ids.includes(id)) { claims.set(id, owner); return }
221
- }
222
- throw new Error(`guest ${id} is not held by this conversation`)
223
- }
224
214
 
225
215
  function guestById(id) {
216
+ if (typeof id === 'string') return nativeGuests.get(id)
226
217
  for (const contents of webContents.getAllWebContents()) {
227
218
  if (contents.id === id) return contents
228
219
  }
229
220
  return undefined
230
221
  }
231
222
 
223
+ const nativeCapability = () => globalThis[ACTIVE]?.api?.browserGuests?.protocolVersion === 1 ? globalThis[ACTIVE].api.browserGuests : undefined
224
+ const nativeGuests = nativeGuestRegistry(nativeCapability)
225
+
232
226
  /** Describe one candidate guest. */
233
227
  function describe(contents) {
234
228
  let url = ''
@@ -249,36 +243,60 @@ function describe(contents) {
249
243
  * Attaching is per-webContents and idempotent; a destroyed guest drops the
250
244
  * attachment so a later guest with a recycled id is not mistaken for this one.
251
245
  */
252
- async function sendCdp(id, method, params) {
246
+ const CDP_COMMAND_TIMEOUT_MS = 15_000
247
+ const timedOutGuests = new WeakSet()
248
+
249
+ async function sendCdp(id, method, params, checkCurrent) {
253
250
  const guest = guestById(id)
254
251
  if (guest === undefined || guest.isDestroyed()) throw new Error(`guest ${id} is not available`)
255
252
  const previous = queues.get(id) ?? Promise.resolve()
256
- const next = previous.then(async () => {
253
+ const guarded = previous.then(async () => {
254
+ checkCurrent?.()
257
255
  const current = guestById(id)
258
- if (current === undefined || current.isDestroyed()) throw new Error(`guest ${id} is not available`)
259
- // Chromium's CDP keyboard handler can redirect a webview command to the embedder's
260
- // focused guest. Send text and keys to this exact guest instead, preserving OS focus.
261
- if (current.getType() === 'webview') {
262
- if (method === 'Input.insertText') {
263
- if (typeof params?.text !== 'string') throw new Error('Input.insertText requires text')
264
- await current.insertText(params.text)
265
- return {}
266
- }
267
- if (method === 'Input.dispatchKeyEvent') {
268
- const event = nativeKeyEvent(params)
269
- current.sendInputEvent(event)
270
- if (params.type === 'keyDown' && typeof params.text === 'string' && params.text !== '') {
271
- current.sendInputEvent({ ...event, type: 'char', keyCode: params.text })
256
+ if (current !== guest || current.isDestroyed()) throw new Error(`guest ${id} is not available`)
257
+ if (timedOutGuests.has(current)) throw new Error(`guest ${id} has a timed-out command; close and reopen its page before sending more commands`)
258
+ let timer
259
+ try {
260
+ return await Promise.race([
261
+ new Promise((_, reject) => {
262
+ timer = setTimeout(() => {
263
+ // A renderer command cannot be cancelled reliably, even by detaching its debugger.
264
+ // Never send another command to this page while its effects remain uncertain.
265
+ timedOutGuests.add(current)
266
+ reject(new Error(`cdp command ${method} on guest ${id} did not answer within ${CDP_COMMAND_TIMEOUT_MS}ms; close and reopen its page before sending more commands`))
267
+ }, CDP_COMMAND_TIMEOUT_MS)
268
+ timer.unref?.()
269
+ }),
270
+ execute(),
271
+ ])
272
+ } finally {
273
+ clearTimeout(timer)
274
+ }
275
+ async function execute() {
276
+ // Chromium's CDP keyboard handler can redirect a webview command to the embedder's
277
+ // focused guest. Send text and keys to this exact guest instead, preserving OS focus.
278
+ if (current.getType() === 'webview') {
279
+ if (method === 'Input.insertText') {
280
+ if (typeof params?.text !== 'string') throw new Error('Input.insertText requires text')
281
+ await current.insertText(params.text)
282
+ return {}
283
+ }
284
+ if (method === 'Input.dispatchKeyEvent') {
285
+ const event = nativeKeyEvent(params)
286
+ current.sendInputEvent(event)
287
+ if (params.type === 'keyDown' && typeof params.text === 'string' && params.text !== '') {
288
+ current.sendInputEvent({ ...event, type: 'char', keyCode: params.text })
289
+ }
290
+ return {}
272
291
  }
273
- return {}
274
292
  }
293
+ if (!current.debugger.isAttached()) current.debugger.attach('1.3')
294
+ return await current.debugger.sendCommand(method, params ?? {})
275
295
  }
276
- if (!current.debugger.isAttached()) current.debugger.attach('1.3')
277
- return await current.debugger.sendCommand(method, params ?? {})
278
296
  })
279
297
  // Keep the chain alive on failure so one bad command does not wedge the guest.
280
- queues.set(id, next.catch(() => undefined))
281
- return await next
298
+ queues.set(id, guarded.catch(() => undefined))
299
+ return await guarded
282
300
  }
283
301
 
284
302
  /** Convert CDP key data for Electron's per-webContents input channel. */
@@ -366,42 +384,33 @@ async function downloadGuest(guest, url, savePath) {
366
384
  *
367
385
  * @param shellId - the shell window's webContents id.
368
386
  * @param sessionId - the conversation that asked (the request's `owner`).
369
- * @param url - address to load when a panel has to be opened; `null` to only READ.
387
+ * @param url - address to load when a panel has to be opened.
370
388
  * @returns the renderer's verdict, normalized so a malformed answer is a named failure.
371
389
  */
372
- async function evaluatePanelService(shellId, sessionId, url, tabId, viewId, guestId) {
373
- // `null` means read-only. This distinction is not cosmetic: `openPanel` CREATES a tab when the
374
- // conversation has none, so polling with it turned a 20-second wait into one empty tab every
375
- // 250ms — the "it opens a pile of blank pages at once" report. A wait must never be a write.
376
- const reading = url === null
390
+ async function evaluatePanelService(shellId, sessionId, url, viewId, guestId, deadline = Date.now() + 30_000, transactionId) {
377
391
  const target = JSON.stringify({
378
- ...typeof viewId === 'string' && viewId !== '' ? { viewId } : {},
379
- ...Number.isSafeInteger(guestId) && guestId > 0 ? { guestId } : {},
392
+ viewId, deadline, transactionId,
393
+ ...(Number.isSafeInteger(guestId) && guestId > 0) || typeof guestId === 'string' ? { guestId } : {},
380
394
  })
381
- const call = reading
382
- // `panelGuest` reports state, not success, so the read form supplies the verdict itself: a
383
- // conversation with no panel yet is a legitimate answer to "what do you have", not a failure.
384
- ? `JSON.stringify({ ok: true, ...api.panelGuest(${JSON.stringify(String(sessionId))}, ${JSON.stringify(tabId ?? null)}, ${target}) })`
385
- : `JSON.stringify(api.openPanel(${JSON.stringify(String(sessionId))}, ${JSON.stringify(String(url ?? ''))}, ${target}))`
386
- const expression = `(() => {
395
+ const expression = `(async () => {
387
396
  const api = globalThis.__dshBuiltinBrowser;
388
- if (api === undefined || api === null || typeof api.openPanel !== 'function') {
389
- return JSON.stringify({ ok: false, reason: 'the plugin client half is not loaded in this window' });
390
- }
391
- if (${typeof viewId === 'string' && viewId !== ''} && Number(api.panelProtocol || 0) < 3) {
392
- return JSON.stringify({ ok: false, reason: 'the browser plugin client needs to reload for separate sidebar tabs; reopen DSH Desktop and retry' });
397
+ if (!api || api.panelProtocol < 5 || typeof api.initializePanel !== 'function') {
398
+ return JSON.stringify({ ok: false, code: 'panel-initialization-failed', reason: 'reload the browser plugin client for transactional sidebar initialization' });
393
399
  }
394
400
  try {
395
- return ${call};
401
+ const answer = await api.initializePanel(${JSON.stringify(String(sessionId))}, ${JSON.stringify(String(url ?? ''))}, ${target});
402
+ answer.backgroundRendering = typeof api.isBackgroundRendering === 'function'
403
+ && api.isBackgroundRendering(${JSON.stringify(String(sessionId))}) === true;
404
+ return JSON.stringify(answer);
396
405
  } catch (error) {
397
- return JSON.stringify({ ok: false, reason: String((error && error.message) || error) });
406
+ return JSON.stringify({ ok: false, code: error?.code, reason: String(error?.message ?? error) });
398
407
  }
399
408
  })()`
400
409
  // `executeJavaScript`, NOT the debugger/CDP path.
401
410
  //
402
411
  // Measured on the running shell: the debugger attachment to the shell WINDOW is unreliable — its
403
412
  // commands hang, repeatedly and for minutes, while the same channel to a guest page answers at
404
- // once. Nothing here needs the protocol: it is one synchronous call on a global the plugin itself
413
+ // once. Nothing here needs the protocol: it is one transaction on a global the plugin itself
405
414
  // published. `executeJavaScript` reaches the page's main world directly, with no attachment to go
406
415
  // stale and no reply to be lost. The guest path keeps CDP, because driving a PAGE genuinely needs
407
416
  // it (`Runtime.evaluate`, `Page.*`, `Input.*`).
@@ -428,15 +437,22 @@ async function evaluatePanelService(shellId, sessionId, url, tabId, viewId, gues
428
437
  const parsed = JSON.parse(value)
429
438
  return {
430
439
  ok: parsed?.ok === true,
440
+ ...typeof parsed?.code === 'string' ? { code: parsed.code } : {},
441
+ rendererNavigation: parsed?.rendererNavigation === true,
431
442
  reason: parsed?.reason === undefined ? undefined : String(parsed.reason),
432
443
  panel: parsed?.panel === true,
433
444
  created: parsed?.created === true,
445
+ navigating: parsed?.navigating === true,
446
+ backgroundRendering: parsed?.backgroundRendering === true,
434
447
  ...typeof parsed?.displayed === 'boolean' ? { displayed: parsed.displayed } : {},
435
- guestId: typeof parsed?.guestId === 'number' && Number.isFinite(parsed.guestId) ? parsed.guestId : null,
448
+ guestId: (typeof parsed?.guestId === 'number' && Number.isFinite(parsed.guestId)) || typeof parsed?.guestId === 'string' ? parsed.guestId : null,
436
449
  ...typeof parsed?.tabId === 'string' ? { tabId: parsed.tabId } : {},
437
450
  url: typeof parsed?.url === 'string' ? parsed.url : '',
438
451
  // A refusal carries what the renderer found, so the reason is actionable rather than a guess.
439
452
  found: parsed?.found === undefined ? undefined : parsed.found,
453
+ ...parsed?.initialization !== null && typeof parsed?.initialization === 'object'
454
+ ? { initialization: parsed.initialization } : {},
455
+ ...parsed?.nativeState !== null && typeof parsed?.nativeState === 'object' ? { nativeState: parsed.nativeState } : {},
440
456
  }
441
457
  } catch (error) {
442
458
  return { ok: false, reason: 'the shell answered a shape this bridge does not understand', panel: false, guestId: null, url: '' }
@@ -457,6 +473,23 @@ function guestShows(id, url) {
457
473
  }
458
474
  }
459
475
 
476
+ // A new native sidebar tab starts its own loadURL before it exposes a guest. Confirm the
477
+ // committed main frame (including HTTP redirects) without interrupting that load with CDP.
478
+ async function committedSidebarNavigation(id, url) {
479
+ const history = await sendCdp(id, 'Page.getNavigationHistory', {})
480
+ const entry = history.entries?.[history.currentIndex]
481
+ if (!entry) return undefined
482
+ const wanted = new URL(url).href
483
+ if (entry.userTypedURL !== wanted && entry.url !== wanted) return undefined
484
+ const { frameTree } = await sendCdp(id, 'Page.getFrameTree', {})
485
+ const frame = frameTree?.frame
486
+ if (!frame || typeof frame.id !== 'string' || frame.id === '' || typeof frame.loaderId !== 'string' || frame.loaderId === '') return undefined
487
+ if (frame.unreachableUrl) throw codedError('panel-navigation-failed', 'the sidebar could not load ' + frame.unreachableUrl)
488
+ // The main frame and history must acknowledge the same committed document.
489
+ if (frame.url + (frame.urlFragment ?? '') !== entry.url) return undefined
490
+ return { frameId: frame.id, loaderId: frame.loaderId }
491
+ }
492
+
460
493
  /**
461
494
  * Which kind of frame the sidebar browser panel is built from, on this shell.
462
495
  *
@@ -479,6 +512,7 @@ function guestShows(id, url) {
479
512
  * @returns 'webview' | 'iframe' | 'none' (no panel yet) | 'unknown' (could not be read).
480
513
  */
481
514
  async function sidebarFrameKind(shellId) {
515
+ if (nativeCapability() !== undefined) return 'native'
482
516
  if (typeof shellId !== 'number') return 'unknown'
483
517
  try {
484
518
  // `executeJavaScript`, not the debugger: the same measured reason as every other shell-side
@@ -501,6 +535,7 @@ async function sidebarFrameKind(shellId) {
501
535
  /** Read the exact guest set from the named conversation's renderer, never from free globals. */
502
536
  async function panelGuestIds(shell, owner) {
503
537
  if (!/^session-/.test(owner)) return []
538
+ if (nativeCapability() !== undefined) return nativeGuests.ids(owner)
504
539
  const value = await shell.executeJavaScript(`(() => {
505
540
  const api = globalThis.__dshBuiltinBrowser;
506
541
  if (!api || typeof api.panelGuests !== 'function') {
@@ -517,315 +552,251 @@ async function panelGuestIds(shell, owner) {
517
552
  }
518
553
 
519
554
  /** Handle one JSON request line; every answer is a JSON line too. */
520
- async function handle(request) { const op = String(request?.op ?? '')
521
- // Who is asking. Declared once, for every op, because the first attempt at this put `owner` in
522
- // the allocation path only and the reuse path — which every later call takes — stayed blind,
523
- // so one session was handed another's page and counted another's tabs as its own.
524
- const owner = typeof request?.owner === 'string' && request.owner !== '' ? request.owner : 'anonymous'
525
- // Which build is answering. The acceptance script asks this first, because everything else it
526
- // measures is meaningless if the host is still running the previous bridge.
527
- if (op === 'version') {
528
- return { ok: true, loadedAt: LOADED_AT, protocol: PROTOCOL }
555
+ async function handle(request, signal) {
556
+ signal?.throwIfAborted()
557
+ if (['owner', 'id', 'viewId', 'logicalViewId'].some(key => Object.hasOwn(request, key))) {
558
+ throw codedError('BROWSER_HANDLE_REQUIRED', 'the bridge requires canonical handles, not local ids')
529
559
  }
530
- if (op === 'list') {
531
- pruneClaims()
532
- const all = webContents.getAllWebContents().map(describe)
533
- // A guest claimed by another owner is not this caller's to see or to drive. Its id, url and
534
- // title are that session's business; handing them over is how a session came to list pages it
535
- // never opened. The shell window is always reported: it is what every op drives.
536
- const shell = webContents.getAllWebContents().find(g => g.getType() === 'window')
537
- const panelIds = shell === undefined ? [] : await panelGuestIds(shell, owner)
538
- for (const id of panelIds) {
539
- if (!claims.has(id) || claims.get(id) === owner) claims.set(id, owner)
540
- }
541
- const mineOrFree = all.filter(g => g.type !== 'webview'
542
- || (claims.get(g.id) === owner && (!/^session-/.test(owner) || panelIds.includes(g.id))))
543
- return {
544
- ok: true,
545
- protocol: PROTOCOL,
546
- guests: mineOrFree,
547
- sidebar: mineOrFree.filter(g => g.type === 'webview'),
548
- frame: await sidebarFrameKind(shell?.id),
560
+ const owner = ['ensureSidebar', 'cdp', 'download'].includes(request?.op) ? wireHandle(request.handle, 'tab').owner : undefined
561
+ const controller = new AbortController()
562
+ const checkCurrent = () => controller.signal.throwIfAborted()
563
+ if (request?.op === 'ensureSidebar') request = { ...request,
564
+ transactionId: request.transactionId ?? randomBytes(16).toString('hex'),
565
+ deadline: Number.isFinite(request.deadline) ? request.deadline : Date.now() + 30_000,
566
+ }
567
+ checkCurrent()
568
+ const shell = /^session-/.test(owner)
569
+ ? webContents.getAllWebContents().find(contents => contents.getType() === 'window') : undefined
570
+ const token = randomBytes(16).toString('hex')
571
+ const holdDeadline = Number.isFinite(request.deadline) ? request.deadline : Date.now() + RENDERING_HOLD_MS
572
+ let held
573
+ let releasePromise
574
+ const release = () => {
575
+ if (held === false) return Promise.resolve()
576
+ const run = async () => {
577
+ let timer
578
+ try {
579
+ await Promise.race([
580
+ shell.executeJavaScript(`globalThis.__dshBuiltinBrowser?.releaseRendering?.(${JSON.stringify(token)})`, true),
581
+ new Promise(resolve => { timer = setTimeout(resolve, Math.max(0, Math.min(RENDERING_RELEASE_TIMEOUT_MS, holdDeadline - Date.now()))) }),
582
+ ])
583
+ } catch (error) { console.error('[dsh-browser-bridge] rendering hold release failed:', error) }
584
+ finally { clearTimeout(timer) }
549
585
  }
586
+ return held === undefined ? run() : releasePromise ??= run()
550
587
  }
551
- if (op === 'closePage') {
552
- const id = Number(request.id)
553
- if (!Number.isSafeInteger(id) || id <= 0) throw new Error('closePage requires a numeric guest id')
554
- const shell = webContents.getAllWebContents().find(g => g.getType() === 'window')
555
- if (shell === undefined) throw new Error('no shell window to drive')
556
- if (!(await panelGuestIds(shell, owner)).includes(id)) throw new Error('the page does not belong to this conversation panel')
557
- pruneClaims()
558
- if (claims.has(id) && claims.get(id) !== owner) throw new Error('the page belongs to another session')
559
- const value = await shell.executeJavaScript(`(() => {
560
- const api = globalThis.__dshBuiltinBrowser;
561
- if (!api || typeof api.closePanelGuest !== 'function') {
562
- throw new Error('sidebar close API is unavailable; refresh or upgrade the browser plugin client');
588
+ let rejectAborted
589
+ const aborted = new Promise((_resolve, reject) => { rejectAborted = reject })
590
+ const onAbort = () => {
591
+ rejectAborted(controller.signal.reason)
592
+ if (shell !== undefined) {
593
+ void release()
594
+ if (request.op === 'ensureSidebar') {
595
+ void shell.executeJavaScript(`globalThis.__dshBuiltinBrowser?.cancelPanelInitialization?.(${JSON.stringify(owner)}, ${JSON.stringify(request.handle)}, ${JSON.stringify(request.transactionId)})`)
596
+ .catch(error => console.error('[dsh-browser-bridge] initialization cancellation failed:', error))
563
597
  }
564
- return JSON.stringify(api.closePanelGuest(${JSON.stringify(owner)}, ${id}));
565
- })()`, true)
566
- let answer
567
- try { answer = JSON.parse(value) } catch { throw new Error('invalid sidebar close reply') }
568
- if (answer?.ok !== true || answer.closed !== 1) throw new Error(String(answer?.reason ?? 'the sidebar did not close the requested page'))
569
- const deadline = Date.now() + 2_000
570
- while (Date.now() < deadline) {
571
- const guest = guestById(id)
572
- if (guest === undefined || guest.isDestroyed()) {
573
- claims.delete(id)
574
- return { ok: true, closed: 1 }
575
- }
576
- await new Promise(resolve => setTimeout(resolve, 50))
577
598
  }
578
- throw new Error('the sidebar close action did not remove the requested page')
579
599
  }
580
- if (op === 'cdp') {
581
- const id = Number(request.id)
582
- if (!Number.isSafeInteger(id) || id <= 0) throw new Error('cdp requires a positive numeric guest id')
583
- await assertGuestOwner(id, owner)
584
- const result = await sendCdp(id, String(request.method ?? ''), request.params)
585
- return { ok: true, result, bridgeRequestId: request.bridgeRequestId }
600
+ const forwardAbort = () => controller.abort(signal.reason)
601
+ controller.signal.addEventListener('abort', onAbort, { once: true })
602
+ signal?.addEventListener('abort', forwardAbort, { once: true })
603
+ activeRequests.add(controller)
604
+ const timer = request?.op === 'ensureSidebar' ? setTimeout(() => controller.abort(
605
+ codedError('BROWSER_DOCUMENT_TIMEOUT', 'sidebar initialization deadline expired')), Math.max(0, request.deadline - Date.now())) : undefined
606
+ const run = async () => {
607
+ try {
608
+ checkCurrent()
609
+ if (shell !== undefined) {
610
+ held = await shell.executeJavaScript(`(async () => {
611
+ const api = globalThis.__dshBuiltinBrowser;
612
+ if (typeof api?.holdRendering !== 'function') return false;
613
+ return api.holdRendering(${JSON.stringify(owner)}, ${JSON.stringify(token)}, ${holdDeadline});
614
+ })()`, true) === true
615
+ }
616
+ checkCurrent()
617
+ return await handleRequest(request, checkCurrent, controller)
618
+ } finally {
619
+ if (shell !== undefined) await release()
620
+ }
586
621
  }
587
- if (op === 'download') {
588
- const id = Number(request.id)
589
- if (!Number.isSafeInteger(id) || id <= 0) throw new Error('download requires a positive numeric guest id')
590
- await assertGuestOwner(id, owner)
591
- const guest = guestById(id)
592
- if (guest === undefined || guest.isDestroyed() || guest.getType() !== 'webview') throw new Error('download guest is not available')
593
- await downloadGuest(guest, request.url, request.savePath)
594
- return { ok: true, path: request.savePath }
622
+ try {
623
+ return await Promise.race([run(), aborted])
624
+ } finally {
625
+ clearTimeout(timer)
626
+ activeRequests.delete(controller)
627
+ signal?.removeEventListener('abort', forwardAbort)
628
+ controller.signal.removeEventListener('abort', onAbort)
629
+ if (shell !== undefined) await release()
595
630
  }
596
- if (op === 'ensureSidebar') {
597
- // This conversation's OWN panel, opened through the shell's own navigation — never by
598
- // simulating input.
599
- //
600
- // Every earlier version of this op drove the sidebar the way a human does: Ctrl+T, then a
601
- // click on the 「浏览器」guide card, then typing into the address bar. All three land on the
602
- // conversation the shell is DISPLAYING, because the shell routes keys and clicks to what it
603
- // shows. So a page asked for while the human read another conversation was opened into THAT
604
- // one, waiting for the screen to come back cost ten seconds, and when it never came back the
605
- // retry loop left a tab per round. Three separate symptoms — "it opened in the wrong place",
606
- // "it says it failed", "it opened a dozen browsers" — are one property of that path.
607
- //
608
- // The renderer can name the conversation instead. `openTabIn(sessionId, …)` is the shell's
609
- // own navigation aimed at ONE conversation, and it does not read what is on screen at all —
610
- // so this op no longer has an opinion about which conversation is displayed, and there is no
611
- // path from here to somebody else's sidebar. DOM is not touched: the call is evaluated on the
612
- // global the plugin's own client half published.
613
- const url = request.url === undefined ? '' : String(request.url)
631
+ }
632
+
633
+ async function handleRequest(request, checkCancelled, controller) {
634
+ const op = String(request?.op ?? '')
635
+ if (op !== 'ensureSidebar' && op !== 'cancelSidebar') return dispatch(request, checkCancelled)
636
+ const scope = wireHandle(request.handle, 'tab')
637
+ const key = request.handle
638
+ if (op === 'cancelSidebar') {
639
+ const pending = pendingSidebarOpens.get(key)
640
+ if (typeof request.transactionId !== 'string' || pending?.transactionId !== request.transactionId) return { ok: true, cancelled: false }
641
+ pending.cancelled = true
642
+ pending.abort()
614
643
  const shell = webContents.getAllWebContents().find(contents => contents.getType() === 'window')
615
- if (shell === undefined) throw new Error('no shell window to drive')
616
- if (!/^session-/.test(owner)) {
617
- throw new Error('this host supplied no conversation id, so its own panel cannot be identified')
618
- }
644
+ if (shell) await shell.executeJavaScript(`globalThis.__dshBuiltinBrowser?.cancelPanelInitialization?.(${JSON.stringify(scope.owner)}, ${JSON.stringify(key)}, ${JSON.stringify(request.transactionId)})`)
645
+ return { ok: true, cancelled: true }
646
+ }
647
+ const token = { transactionId: request.transactionId, cancelled: false,
648
+ abort: () => controller.abort(codedError('BROWSER_NAVIGATION_CANCELLED', 'sidebar initialization was cancelled')) }
649
+ pendingSidebarOpens.set(key, token)
650
+ const checkCurrent = () => {
651
+ checkCancelled?.()
652
+ if (token.cancelled) throw codedError('BROWSER_NAVIGATION_CANCELLED', 'sidebar initialization was cancelled')
653
+ if (pendingSidebarOpens.get(key) !== token) throw codedError('panel-navigation-superseded', 'a newer navigation was requested for this sidebar view')
654
+ }
655
+ try { return await dispatch(request, checkCurrent) }
656
+ finally { if (pendingSidebarOpens.get(key) === token) pendingSidebarOpens.delete(key) }
657
+ }
619
658
 
620
- let tabId
621
- const ask = async (withUrl) => {
622
- // `null` reads, a string places or navigates. Every round of the wait below uses the READ
623
- // form, because a wait must never create anything.
624
- const answer = await evaluatePanelService(shell.id, owner, withUrl ? url : null, tabId,
625
- typeof request.viewId === 'string' ? request.viewId : undefined, request.guestId)
626
- if (answer.ok !== true) {
627
- // Carry the renderer's own findings into the failure: it is the side that can see why the
628
- // lookup missed, and a bare "not mounted" leaves the next reader guessing between a real
629
- // absence and a lookup that reads the wrong place.
630
- const detail = answer.found === undefined ? '' : ' — renderer found ' + JSON.stringify(answer.found)
631
- throw new Error(String(answer.reason) + detail)
632
- }
633
- return answer
634
- }
659
+ function wireHandle(wire, kind) {
660
+ const prefix = kind === 'tab' ? 'dsh-tab:v1:' : 'dsh-session:v1:'
661
+ let values
662
+ try {
663
+ if (typeof wire !== 'string' || !wire.startsWith(prefix)) throw new Error()
664
+ values = JSON.parse(decodeURIComponent(wire.slice(prefix.length)))
665
+ if (!Array.isArray(values) || values.length !== (kind === 'tab' ? 3 : 2)
666
+ || values.some(value => typeof value !== 'string' || value === '')) throw new Error()
667
+ if (prefix + encodeURIComponent(JSON.stringify(values)) !== wire) throw new Error()
668
+ } catch { throw codedError('BROWSER_HANDLE_INVALID', 'invalid or noncanonical browser handle') }
669
+ const [owner, session, tab] = values
670
+ const sessionKey = 'dsh-session:v1:' + encodeURIComponent(JSON.stringify([owner, session]))
671
+ if (retiredHandles.has(wire) || retiredSessions.has(sessionKey)) throw codedError('BROWSER_HANDLE_STALE', 'the browser handle was released')
672
+ return { owner, session, tab }
673
+ }
635
674
 
636
- // Already has a page: reuse it. This is the common case after the first open of a session.
637
- //
638
- // A read-only caller (the live preview, issue #46) does NOT come through here at all: it uses the
639
- // `list` op instead, because this one can drive the shell — that is the difference between "show
640
- // me the page" and "let me look at it", and keeping the preview off this path is what stops a
641
- // read-only action from moving the reader's layout.
642
- const first = await ask(true)
643
- tabId = first.tabId
644
- if (first.displayed === false) {
645
- throw codedError(PANEL_NOT_DISPLAYED, 'the requested conversation is still being displayed; its sidebar will attach after rendering')
646
- }
647
- if (first.guestId !== null) {
648
- claims.set(first.guestId, owner)
649
- if (!guestShows(first.guestId, url)) {
650
- await sendCdp(first.guestId, 'Page.navigate', { url }).catch(() => undefined)
651
- }
652
- return { ok: true, created: false, id: first.guestId, via: 'panel', owner }
653
- }
675
+ function retireHandle(handle) {
676
+ handles.delete(handle)
677
+ retiredHandles.add(handle)
678
+ }
654
679
 
655
- // A tab was placed, but this conversation is not the one the shell is displaying.
656
- //
657
- // The shell renders the sidebar of the conversation it SHOWS. A background conversation's panel
658
- // exists in its own surface store — which is exactly why the tab could be placed at all — but
659
- // it has no DOM, so no webview attaches and no amount of waiting would produce one. Waiting
660
- // would turn a true statement into a timeout, and the page is genuinely there: it appears the
661
- // moment the conversation is shown.
662
- if (first.panel === false) {
663
- // Reported as issue #37. This is NOT a lost carrier: the tab exists in this conversation's own
664
- // surface store, the conversation is simply not the one on screen, and the page appears the
665
- // moment it is. A machine-readable code is what keeps the plugin from concluding the carrier
666
- // died — a conclusion that swapped the surface to a separate window and took the open page with
667
- // it, because the new window starts blank.
668
- throw codedError(
669
- PANEL_NOT_DISPLAYED,
670
- 'a panel was placed in this conversation\'s sidebar, but its page can only attach while the '
671
- + 'conversation is the one displayed — show it and the page appears',
672
- )
673
- }
680
+ function boundGuest(handle) {
681
+ wireHandle(handle, 'tab')
682
+ const entry = handles.get(handle)
683
+ if (!entry || entry.guest.isDestroyed() || guestById(entry.guest.id) !== entry.guest) {
684
+ retireHandle(handle)
685
+ throw codedError('BROWSER_HANDLE_STALE', 'the browser tab handle is stale; list tabs again')
686
+ }
687
+ return entry.guest
688
+ }
674
689
 
675
- // A guest attaches asynchronously once the renderer creates the webview. Poll INSIDE this
676
- // conversation's panel, so a guest appearing in any other conversation cannot satisfy the wait
677
- // — the scoping is what makes the wait safe.
678
- const deadline = Date.now() + (url === '' ? 4_000 : 20_000)
679
- while (Date.now() < deadline) {
680
- await new Promise(resolve => setTimeout(resolve, 250))
681
- const polled = await ask(false)
682
- if (polled.guestId === null) continue
683
- claims.set(polled.guestId, owner)
684
- if (!guestShows(polled.guestId, url)) {
685
- await sendCdp(polled.guestId, 'Page.navigate', { url }).catch(() => undefined)
690
+ function bindGuest(handle, guest) {
691
+ const scope = wireHandle(handle, 'tab')
692
+ const held = handles.get(handle)
693
+ if (held && held.guest !== guest) throw codedError('BROWSER_HANDLE_STALE', 'the browser tab was rebound; list tabs again')
694
+ for (const [key, entry] of handles) {
695
+ if (entry.guest === guest && key !== handle
696
+ && (entry.owner !== scope.owner || entry.session === scope.session)) retireHandle(key)
697
+ }
698
+ handles.set(handle, { ...scope, guest })
699
+ }
700
+
701
+ async function dispatch(request, checkCurrent) {
702
+ checkCurrent?.()
703
+ const op = String(request?.op ?? '')
704
+ // Which build is answering. The acceptance script asks this first, because everything else it
705
+ // measures is meaningless if the host is still running the previous bridge.
706
+ if (op === 'version') {
707
+ const api = globalThis[ACTIVE]?.api
708
+ const home = resolve(api?.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'))
709
+ return { ok: true, loadedAt: LOADED_AT, protocol: PROTOCOL,
710
+ bridgeVersion: api?.bridgeVersion, bridgeBuild: api?.bridgeBuild,
711
+ homeId: createHash('sha256').update(process.platform === 'win32' ? home.toLowerCase() : home).digest('hex'),
712
+ mainExtension: typeof api?.mainExtensions?.status === 'function'
713
+ ? await api.mainExtensions.status('dsh-builtin-browser') : { code: 'DESKTOP_MAIN_EXTENSION_UNSUPPORTED' } }
714
+ }
715
+ const shell = webContents.getAllWebContents().find(contents => contents.getType() === 'window')
716
+ if (op === 'list') {
717
+ const frame = await sidebarFrameKind(shell?.id)
718
+ if (request.handle === undefined) return { ok: true, protocol: PROTOCOL, frame }
719
+ const scope = wireHandle(request.handle, 'session')
720
+ const ids = shell === undefined ? [] : await panelGuestIds(shell, scope.owner)
721
+ const sidebar = []
722
+ for (const id of ids) {
723
+ const guest = guestById(id)
724
+ if (!guest || guest.isDestroyed() || !['webview', 'native'].includes(guest.getType())) continue
725
+ let handle
726
+ for (const [key, entry] of handles) {
727
+ if (entry.owner === scope.owner && entry.session === scope.session && entry.guest === guest) { handle = key; break }
686
728
  }
687
- return { ok: true, created: true, id: polled.guestId, via: 'panel', owner }
729
+ if (handle === undefined) handle = 'dsh-tab:v1:' + encodeURIComponent(JSON.stringify([scope.owner, scope.session, 'page:' + randomUUID()]))
730
+ bindGuest(handle, guest)
731
+ sidebar.push({ ...describe(guest), id: handle })
688
732
  }
689
- throw codedError(
690
- PANEL_INITIALIZING,
691
- 'this conversation\'s browser panel produced no page within its budget '
692
- + '(the shell placed no guest in this conversation\'s own sidebar)',
693
- )
733
+ return { ok: true, protocol: PROTOCOL, sidebar, frame }
694
734
  }
695
- if (op === 'showTab') {
696
- // Bring one browser guest to the front — the "switch to this tab" half of opening a page.
697
- //
698
- // Without this the desktop bridge had no way to satisfy `showView`, so its host
699
- // implementation was an empty method and a newly opened page stayed behind whatever the
700
- // human was looking at. Reported as issue #23; the other two carriers already did this
701
- // (the self-hosted window re-adds the view, the system browser calls Page.bringToFront).
702
- //
703
- // The tab strip belongs to the renderer, so raising one means asking the sidebar to do it. A
704
- // tab is matched by the title it shows, which is what the sidebar renders from the guest —
705
- // the guest's id is not exposed in the DOM.
706
- const viewId = Number(request.viewId)
707
- if (!Number.isFinite(viewId)) throw new Error('showTab needs a viewId')
708
- const guest = webContents.fromId(viewId)
709
- if (guest === undefined) throw new Error(`showTab: no guest with id ${viewId}`)
710
- // Only a guest this caller holds may be brought forward. Without the check, one session could
711
- // switch the sidebar to another session's page — moving the human's view out from under it.
712
- await assertGuestOwner(Number(viewId), owner)
713
- const shell = webContents.getAllWebContents().find(contents => contents.getType() === 'window')
714
- if (shell === undefined) throw new Error('no shell window to drive')
715
- // Bind by the exact native guest rather than its title: several tabs can have the same title.
716
- if (typeof request.logicalViewId === 'string' && request.logicalViewId !== '') {
717
- const shown = await evaluatePanelService(shell.id, owner, '', undefined, request.logicalViewId, viewId)
718
- if (shown.ok !== true || shown.guestId !== viewId) {
719
- throw new Error('could not select the requested sidebar tab: ' + String(shown.reason ?? 'the requested guest is not displayed yet'))
720
- }
721
- return { ok: true, verdict: 'SELECTED' }
735
+ const scope = wireHandle(request.handle, op === 'collapseSidebar' || op === 'releaseSession' ? 'session' : 'tab')
736
+ const owner = scope.owner
737
+ if (op === 'releaseTab') {
738
+ retireHandle(request.handle)
739
+ return { ok: true }
740
+ }
741
+ if (op === 'releaseSession') {
742
+ retiredSessions.add(request.handle)
743
+ for (const [key, entry] of handles) {
744
+ if (entry.owner === owner && entry.session === scope.session) retireHandle(key)
722
745
  }
723
- const wantTitle = String(guest.getTitle() ?? '').trim()
724
- const clicked = await evaluateInPanel(shell.id, owner, 'Runtime.evaluate', {
725
- expression: `(() => {
726
- const scan = (root, out) => {
727
- for (const node of root.querySelectorAll('button,[role=button],[role=tab],a')) {
728
- out.push(node);
729
- if (node.shadowRoot) scan(node.shadowRoot, out);
730
- }
731
- return out;
732
- };
733
- const nodes = scan(document, []);
734
- for (const frame of Array.from(document.querySelectorAll('iframe'))) {
735
- try { if (frame.contentDocument) scan(frame.contentDocument, nodes) } catch { /* cross-origin */ }
736
- }
737
- const label = (n) => ((n.getAttribute('aria-label') || '') + ' ' + (n.textContent || '') + ' ' + (n.getAttribute('title') || '')).trim();
738
- const want = ${JSON.stringify(wantTitle)};
739
- // Exact title first, then the tab-like control whose label contains it: a strip may
740
- // decorate the label with a close button, and a prefix match would hit the wrong tab
741
- // when one title contains another.
742
- let hit = nodes.find(n => want !== '' && label(n) === want);
743
- if (hit === undefined) hit = nodes.find(n => want !== '' && label(n).includes(want) && /tab|page|标签/i.test(n.getAttribute('role') || n.className || ''));
744
- if (hit === undefined) hit = nodes.find(n => want !== '' && label(n).includes(want));
745
- if (hit === undefined) return 'NO_TAB_FOR_TITLE';
746
- hit.click();
747
- return 'CLICKED';
748
- })()`,
749
- returnByValue: true,
750
- })
751
- const verdict = String(clicked?.result?.value ?? '')
752
- if (verdict !== 'CLICKED') {
753
- throw new Error(`could not bring the page to the front (${verdict}; wanted "${wantTitle}")`)
746
+ for (const [key, token] of pendingSidebarOpens) {
747
+ const values = JSON.parse(decodeURIComponent(key.slice('dsh-tab:v1:'.length)))
748
+ if (values[0] === owner && values[1] === scope.session) token.cancelled = true
754
749
  }
755
- return { ok: true, verdict }
756
- }
757
- if (op === 'closeSidebarBrowser') {
758
- // Release the sidebar's browser pages by closing the tabs that host them.
759
- //
760
- // This is the desktop equivalent of "close the browser window": the guests are destroyed, so
761
- // that agent's session ends and its next use starts a fresh page. History survives — it is this
762
- // plugin's own file on disk.
763
- //
764
- // Cookies do NOT survive on the shells measured so far, and this comment used to claim they did
765
- // (reported as issue #36). The shell allocates the sidebar's partition as
766
- // `dsh-sidebar-browser-<uuid>` with no `persist:` prefix, i.e. an in-memory session, so anything
767
- // logged in inside the sidebar is logged out again at the next DSH start. That is the shell's
768
- // choice, not something this bridge can change; a carrier whose cookies do persist is the
769
- // installed Chrome/Edge one, which keeps its own profile.
770
- //
771
- // `titles` narrows the release to specific pages. It matters as soon as more
772
- // than one session is running: each one owns its own tab (requirements §4), and
773
- // ending one session must not tear down another's page. With no titles given the
774
- // call means "release everything", which is only appropriate when the caller
775
- // knows it owns them all.
776
- //
777
- // The comment above said that; the code below did not enforce it. It closed every webview
778
- // whose title matched — and with no filter, EVERY webview — regardless of which session held
779
- // it. So one session's `dsh_browser_reset_session` could destroy another session's page, which is
780
- // the worst version of the bleed: not merely seeing someone else's tab, but closing it.
781
- //
782
- // Ownership is now the outer bound: only guests this owner holds are candidates at all, and
783
- // the title filter narrows further within them.
784
- pruneClaims()
785
- const wanted = Array.isArray(request.titles) ? request.titles.map(title => String(title).slice(0, 24)).filter(title => title !== '') : undefined
786
- const guests = webContents.getAllWebContents()
787
- .filter(contents => contents.getType() === 'webview')
788
- .filter(contents => claims.get(contents.id) === owner)
789
- const titles = []
790
- for (const guest of guests) {
791
- try {
792
- if (guest.isDestroyed()) continue
793
- const title = guest.getTitle()
794
- // With a filter, only the guest we intend to close contributes its title —
795
- // otherwise a tab belonging to another session could match by accident.
796
- if (wanted !== undefined && !wanted.some(w => title.startsWith(w))) continue
797
- titles.push(title)
798
- } catch { /* gone mid-read */ }
750
+ return { ok: true }
751
+ }
752
+ if (op === 'ensureSidebar') {
753
+ if (!shell) throw new Error('no shell window to drive')
754
+ if (!/^session-/.test(owner)) throw new Error('this host supplied no conversation id, so its own panel cannot be identified')
755
+ if (handles.has(request.handle)) boundGuest(request.handle)
756
+ const url = request.url === undefined ? '' : String(request.url)
757
+ const deadline = Number.isFinite(request.deadline) ? request.deadline : Date.now() + 30_000
758
+ if (Date.now() >= deadline) throw codedError('BROWSER_INITIALIZATION_TIMEOUT', 'sidebar initialization deadline expired')
759
+ checkCurrent?.()
760
+ const first = await evaluatePanelService(shell.id, owner, url, request.handle, undefined, deadline, request.transactionId)
761
+ checkCurrent?.()
762
+ if (first.ok !== true) {
763
+ const error = codedError(first.code || (first.reason === 'panel-not-displayed' ? PANEL_NOT_DISPLAYED : 'panel-initialization-failed'), 'sidebar unavailable (' + String(first.reason ?? 'renderer refused initialization') + ')')
764
+ if (first.initialization) error.initialization = first.initialization
765
+ throw error
799
766
  }
800
- if (guests.length === 0) return { ok: true, closed: 0 }
801
- const shell = webContents.getAllWebContents().find(contents => contents.getType() === 'window')
802
- if (shell === undefined) throw new Error('no shell window to drive')
803
- if (titles.length === 0 && wanted !== undefined) return { ok: true, closed: 0 }
804
- const clicked = await evaluateInPanel(shell.id, owner, 'Runtime.evaluate', {
805
- expression: `(() => {
806
- const wanted = ${JSON.stringify(titles.map(title => title.slice(0, 24)))};
807
- let closed = 0;
808
- for (const tab of Array.from(document.querySelectorAll('[role=tab]'))) {
809
- const label = (tab.textContent || '').trim();
810
- if (!wanted.some(w => label.startsWith(w))) continue;
811
- const own = Array.from(tab.querySelectorAll('button')).find(b => /关闭|close/i.test((b.getAttribute('aria-label') || '') + (b.getAttribute('title') || '')));
812
- const sibling = Array.from(tab.parentElement ? tab.parentElement.querySelectorAll('button') : []).find(b => /关闭|close/i.test((b.getAttribute('aria-label') || '') + (b.getAttribute('title') || '')));
813
- const button = own ?? sibling;
814
- if (button !== undefined) { button.click(); closed += 1; }
815
- }
816
- return closed;
817
- })()`,
818
- returnByValue: true,
819
- })
820
- return { ok: true, closed: Number(clicked?.result?.value ?? 0) }
767
+ if (first.guestId === null) throw codedError('BROWSER_DOCUMENT_UNACKNOWLEDGED', 'sidebar initialization did not acknowledge a guest')
768
+ const guest = guestById(first.guestId)
769
+ if (!guest || guest.isDestroyed() || !['webview', 'native'].includes(guest.getType())) throw codedError('BROWSER_GUEST_CLOSED', 'the acknowledged sidebar guest is gone')
770
+ if (guest.getType() === 'native') {
771
+ const admission = wireHandle(guest.scope, 'tab')
772
+ const state = nativeGuests.state(guest.id)
773
+ if (admission.owner !== owner || state?.stage !== 'document' || first.nativeState?.guestId !== guest.id
774
+ || first.nativeState?.generation !== state.generation || first.nativeState?.frameId !== state.frameId
775
+ || first.nativeState?.loaderId !== state.loaderId) throw codedError('BROWSER_DOCUMENT_UNACKNOWLEDGED', 'native document generation was not acknowledged')
776
+ }
777
+ const existing = handles.get(request.handle)
778
+ if (existing && existing.guest !== guest) throw codedError('BROWSER_HANDLE_STALE', 'the sidebar returned a replacement guest')
779
+ let navigation
780
+ if (first.rendererNavigation || (url !== '' && (first.created || first.navigating))) {
781
+ if (first.initialization?.stage !== 'attached' || first.initialization.guestId !== String(first.guestId)) {
782
+ throw codedError('BROWSER_DOCUMENT_UNACKNOWLEDGED', 'the native guest does not match its initialization receipt')
783
+ }
784
+ navigation = await committedSidebarNavigation(first.guestId, url)
785
+ checkCurrent?.()
786
+ if (!navigation) throw codedError('BROWSER_DOCUMENT_UNACKNOWLEDGED', 'the native guest did not acknowledge the requested document')
787
+ }
788
+ if (Date.now() >= deadline) throw codedError('BROWSER_DOCUMENT_TIMEOUT', 'sidebar initialization deadline expired')
789
+ bindGuest(request.handle, guest)
790
+ if (!request.attachOnly && !guestShows(guest.id, url)) {
791
+ navigation = await sendCdp(guest.id, 'Page.navigate', { url }, checkCurrent)
792
+ checkCurrent?.()
793
+ if (navigation?.errorText) throw codedError('panel-navigation-failed', String(navigation.errorText))
794
+ }
795
+ return { ok: true, created: first.created, id: request.handle, via: 'panel', ...navigation ? { navigation } : {} }
821
796
  }
822
797
  if (op === 'collapseSidebar') {
823
- // An unscoped owner falls back to sendCdp(shell window), whose debugger attachment hangs.
798
+ if (!shell) throw new Error('no shell window to drive')
824
799
  if (!/^session-/.test(owner)) throw new Error('collapseSidebar requires a conversation id')
825
- // Fold the sidebar away so the agent works without occupying the screen. The
826
- // guest keeps running — collapsing is presentation, exactly as §3 asks.
827
- const shell = webContents.getAllWebContents().find(contents => contents.getType() === 'window')
828
- if (shell === undefined) throw new Error('no shell window to drive')
829
800
  const folded = await evaluateInPanel(shell.id, owner, 'Runtime.evaluate', {
830
801
  expression: `(() => {
831
802
  const button = Array.from(document.querySelectorAll('button')).find(b => /收起右侧边栏/.test((b.getAttribute('aria-label') || '') + (b.textContent || '')));
@@ -835,7 +806,50 @@ async function handle(request) { const op = String(request?.op ?? '')
835
806
  })()`,
836
807
  returnByValue: true,
837
808
  })
838
- return { ok: true, result: folded?.result?.value, bridgeRequestId: request.bridgeRequestId }
809
+ return { ok: true, result: folded?.result?.value ?? 'NOT_OPEN' }
810
+ }
811
+ if (op === 'adoptPage') {
812
+ if (!handles.has(request.handle)) {
813
+ const match = /^page:([1-9]\d*)$/.exec(scope.tab)
814
+ const ids = shell === undefined ? [] : await panelGuestIds(shell, owner)
815
+ const guest = match && ids.includes(Number(match[1])) ? guestById(Number(match[1])) : undefined
816
+ if (!guest || guest.isDestroyed() || guest.getType() !== 'webview') throw codedError('BROWSER_HANDLE_STALE', 'the source page is not in this conversation panel')
817
+ bindGuest(request.handle, guest)
818
+ }
819
+ boundGuest(request.handle)
820
+ return { ok: true, id: request.handle }
821
+ }
822
+ const guest = boundGuest(request.handle)
823
+ if (op === 'cdp') return { ok: true, result: await sendCdp(guest.id, String(request.method ?? ''), request.params, checkCurrent) }
824
+ if (op === 'download') {
825
+ await downloadGuest(guest, request.url, request.savePath)
826
+ return { ok: true, path: request.savePath }
827
+ }
828
+ if (op === 'showTab') {
829
+ if (!shell) throw new Error('no shell window to drive')
830
+ const shown = await evaluatePanelService(shell.id, owner, '', request.handle, guest.id)
831
+ if (shown.ok !== true || shown.guestId !== guest.id) throw new Error('could not select the requested sidebar tab: ' + String(shown.reason ?? 'the requested guest is not displayed yet'))
832
+ return { ok: true, verdict: 'SELECTED' }
833
+ }
834
+ if (op === 'closePage') {
835
+ if (!shell) throw new Error('no shell window to drive')
836
+ const value = await shell.executeJavaScript(`(() => {
837
+ const api = globalThis.__dshBuiltinBrowser;
838
+ if (!api || typeof api.closePanelGuest !== 'function') throw new Error('sidebar close API is unavailable; refresh or upgrade the browser plugin client');
839
+ return JSON.stringify(api.closePanelGuest(${JSON.stringify(owner)}, ${JSON.stringify(guest.id)}));
840
+ })()`, true)
841
+ let answer
842
+ try { answer = JSON.parse(value) } catch { throw new Error('invalid sidebar close reply') }
843
+ if (answer?.ok !== true || answer.closed !== 1) throw new Error(String(answer?.reason ?? 'the sidebar did not close the requested page'))
844
+ const deadline = Date.now() + 2_000
845
+ while (Date.now() < deadline) {
846
+ if (guestById(guest.id) !== guest || guest.isDestroyed()) {
847
+ for (const [key, entry] of handles) if (entry.guest === guest) retireHandle(key)
848
+ return { ok: true, closed: 1 }
849
+ }
850
+ await new Promise(resolve => setTimeout(resolve, 50))
851
+ }
852
+ throw new Error('the sidebar close action did not remove the requested page')
839
853
  }
840
854
  throw new Error(`unknown op ${JSON.stringify(op)}`)
841
855
  }
@@ -865,7 +879,7 @@ const instanceStartedAt = (() => {
865
879
  * by the process that actually owns the listener, and readers are told the pid
866
880
  * so they can verify liveness themselves.
867
881
  */
868
- function publishEndpoint(port, token) {
882
+ function publishEndpoint(port, token, dshHome) {
869
883
  const payload = {
870
884
  port,
871
885
  token,
@@ -874,7 +888,7 @@ function publishEndpoint(port, token) {
874
888
  updatedAt: new Date().toISOString(),
875
889
  }
876
890
  try {
877
- const file = endpointFile()
891
+ const file = endpointFile(dshHome)
878
892
  mkdirSync(join(file, '..'), { recursive: true })
879
893
  writeFileSync(file, JSON.stringify(payload, null, 2) + '\n')
880
894
  return true
@@ -900,18 +914,243 @@ const ACTIVE = Symbol.for("dsh-builtin-browser.bridge.active")
900
914
  * drops its quit hook. Idempotent and never throws, so the shell can call it
901
915
  * before re-importing an edited bridge.
902
916
  */
917
+ /** A webview caches its UA at WebContents creation, so each guest needs its own override. */
918
+ const uaConfiguredContents = new WeakSet()
919
+ /** `did-fail-load` handlers attached by start(), keyed by WebContents. */
920
+ const fallbackHandlers = new Map()
921
+ /** Guest session -> the exact proxy config we applied (absent = OS settings are in charge). */
922
+ const proxyApplied = new WeakMap()
923
+
924
+ /** Cheap liveness check so a stopped proxy daemon never stays pinned into the guest session. */
925
+ function proxyReachable(authority) {
926
+ const at = String(authority).lastIndexOf(':')
927
+ if (at <= 0) return Promise.resolve(false)
928
+ const host = String(authority).slice(0, at)
929
+ const port = Number(String(authority).slice(at + 1))
930
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) return Promise.resolve(false)
931
+ return new Promise(resolve => {
932
+ const socket = netConnect({ host, port })
933
+ let done = false
934
+ const finish = ok => { if (done) return; done = true; socket.destroy(); resolve(ok) }
935
+ socket.setTimeout(400, () => finish(false))
936
+ socket.once('connect', () => finish(true))
937
+ socket.once('error', () => finish(false))
938
+ })
939
+ }
940
+
941
+ /** Release a previously applied override and let Chromium follow the OS again. */
942
+ async function releaseGuestProxy(session) {
943
+ try { await session.setProxy({ mode: 'system' }) } catch { /* older Electron */ }
944
+ try { await session.closeAllConnections?.() } catch { /* older Electron */ }
945
+ proxyApplied.delete(session)
946
+ console.log('[dsh-browser-bridge] sidebar guest proxy released (no live proxy)')
947
+ }
948
+
949
+ /**
950
+ * Give a Sidebar guest a normal-browser identity and a proxy policy.
951
+ *
952
+ * Two independent site-side problems are solved here:
953
+ * - "使用环境异常" / security-check banners: Electron's default UA advertises
954
+ * the app name and Electron version, so many sites classify the embedded
955
+ * webview as an unofficial/automated client.
956
+ * - CloudFront/WAF "Request blocked" 403: first-party DeepSeek hosts must not
957
+ * be forced through a rules proxy's overseas exit node.
958
+ */
959
+ async function applySidebarGuestProxy(contents) {
960
+ try {
961
+ if (contents.getType() !== 'webview') return
962
+ const session = contents.session
963
+ if (!session) return
964
+
965
+ // UA is per WebContents: a second tab in an already-configured partition
966
+ // still caches the UA it was created with, so check each guest separately.
967
+ if (process.env.DSH_SIDEBAR_UA !== 'off' && !uaConfiguredContents.has(contents)) {
968
+ const sessionUa = typeof session.getUserAgent === 'function' ? session.getUserAgent() : ''
969
+ const contentsUa = typeof contents.getUserAgent === 'function' ? contents.getUserAgent() : ''
970
+ const clean = normalizeGuestUserAgent(sessionUa || contentsUa)
971
+ const raw = sessionUa || contentsUa
972
+ if (clean && raw !== clean) {
973
+ // Only a guest whose UA was actually replaced counts as configured: a
974
+ // rejected setUserAgent (older Electron, locked session) must stay
975
+ // retryable instead of being remembered as "done" while the site keeps
976
+ // seeing `Electron/…` and shows its "unsupported client" banner.
977
+ let applied = true
978
+ if (sessionUa && sessionUa !== clean) {
979
+ if (typeof session.setUserAgent === 'function') {
980
+ try { await session.setUserAgent(clean) } catch (error) {
981
+ applied = false
982
+ console.warn('[dsh-browser-bridge] sidebar guest UA (session) rejected:', error && error.message)
983
+ }
984
+ } else applied = false
985
+ }
986
+ if (contentsUa && contentsUa !== clean) {
987
+ if (typeof contents.setUserAgent === 'function') {
988
+ try { await contents.setUserAgent(clean) } catch (error) {
989
+ applied = false
990
+ console.warn('[dsh-browser-bridge] sidebar guest UA (contents) rejected:', error && error.message)
991
+ }
992
+ } else applied = false
993
+ }
994
+ if (applied) {
995
+ console.log('[dsh-browser-bridge] sidebar guest UA:', clean)
996
+ uaConfiguredContents.add(contents)
997
+ }
998
+ } else {
999
+ // Nothing to strip (already clean) or no UA to read: remember it so a
1000
+ // clean guest is not re-checked on every guest creation.
1001
+ uaConfiguredContents.add(contents)
1002
+ }
1003
+ }
1004
+
1005
+ // Proxy policy is partition-wide, but the OS setting can change while the
1006
+ // app is running (VPN / rules proxy switched on or off). Re-evaluate on
1007
+ // every new guest so a later tab picks up the current setting.
1008
+ // DEFAULT: direct. Forcing the OS rules proxy onto the guest measured
1009
+ // 15-20x slower page loads (baidu 21.6s vs 1.1s), and that proxy is also
1010
+ // what returned CloudFront 403 for first-party hosts.
1011
+ const mode = process.env.DSH_SIDEBAR_PROXY_MODE ?? 'direct'
1012
+ if (mode === 'system' || mode === 'off') {
1013
+ if (proxyApplied.has(session)) await releaseGuestProxy(session)
1014
+ return
1015
+ }
1016
+ // resolveProxy reports OUR config once fixed_servers is applied, so it is
1017
+ // only an OS reading while we have not overridden this session.
1018
+ let resolved = ''
1019
+ try { resolved = await session.resolveProxy('https://example.com/') } catch { /* no OS proxy */ }
1020
+ const explicitRules = process.env.DSH_SIDEBAR_PROXY_RULES
1021
+ const config = sidebarProxyConfig({
1022
+ mode,
1023
+ resolved,
1024
+ bypass: process.env.DSH_SIDEBAR_PROXY_BYPASS ?? DEFAULT_SIDEBAR_PROXY_BYPASS,
1025
+ rules: explicitRules,
1026
+ })
1027
+ const signature = config ? JSON.stringify(config) : ''
1028
+ const applied = proxyApplied.get(session)
1029
+
1030
+ // A proxy daemon that has stopped listening must not stay pinned: every
1031
+ // non-bypassed site would fail with ERR_PROXY_CONNECTION_FAILED until the
1032
+ // app restarts. Release it and fall back to the OS setting (DIRECT here).
1033
+ if (applied && !explicitRules && mode !== 'direct') {
1034
+ const parsed = parseSystemProxy(resolved)
1035
+ if (!parsed || !(await proxyReachable(parsed.authority))) {
1036
+ await releaseGuestProxy(session)
1037
+ return
1038
+ }
1039
+ }
1040
+ if (!config) {
1041
+ // No proxy right now: leave the session in system mode so a proxy
1042
+ // enabled later is picked up without an app restart.
1043
+ if (applied) await releaseGuestProxy(session)
1044
+ return
1045
+ }
1046
+ if (applied === signature) return
1047
+ if (!explicitRules && config.mode === 'fixed_servers') {
1048
+ const parsed = parseSystemProxy(resolved)
1049
+ if (!parsed || !(await proxyReachable(parsed.authority))) {
1050
+ if (applied) await releaseGuestProxy(session)
1051
+ return
1052
+ }
1053
+ }
1054
+ await session.setProxy(config)
1055
+ // Pooled sockets created under the previous proxy would keep using it.
1056
+ try { await session.closeAllConnections?.() } catch { /* older Electron */ }
1057
+ proxyApplied.set(session, signature)
1058
+ console.log('[dsh-browser-bridge] sidebar guest proxy:', JSON.stringify(config))
1059
+ } catch (error) {
1060
+ console.error('[dsh-browser-bridge] sidebar guest proxy failed:', error)
1061
+ }
1062
+ }
1063
+
903
1064
  export function stop() {
1065
+ for (const controller of activeRequests) controller.abort(codedError('bridge-request-abandoned', 'the bridge was disposed'))
904
1066
  const current = globalThis[ACTIVE]
1067
+ if (nativeCapability() !== undefined) void nativeGuests.releaseAll().catch(error => console.error('[dsh-browser-bridge] native release failed:', error))
905
1068
  globalThis[ACTIVE] = undefined
1069
+ // Detach BEFORE the early return: a reload replaces this module's `start()`,
1070
+ // and a listener left on a live webContents keeps a stale closure alive that
1071
+ // still calls setProxy()/loadURL() behind the new bridge's back.
1072
+ for (const [contents, handler] of fallbackHandlers) {
1073
+ try { contents.removeListener('did-fail-load', handler) } catch { /* destroyed */ }
1074
+ }
1075
+ fallbackHandlers.clear()
906
1076
  if (!current) return
907
1077
  try { clearInterval(current.keepalive) } catch { /* ignore */ }
1078
+ for (const socket of current.sockets ?? []) socket.destroy()
908
1079
  try { current.server.close() } catch { /* already closed */ }
909
- try { app.off('will-quit', current.onQuit) } catch { /* ignore */ }
1080
+ try { current.application.off('will-quit', current.onQuit) } catch { /* ignore */ }
1081
+ try { current.application.off('web-contents-created', current.onGuestCreated) } catch { /* ignore */ }
1082
+ try {
1083
+ const file = endpointFile(current.api?.dshHome)
1084
+ const endpoint = JSON.parse(readFileSync(file, 'utf8'))
1085
+ if (endpoint.token === current.token && endpoint.pid === process.pid) unlinkSync(file)
1086
+ } catch { /* absent, unreadable, or owned by a replacement instance */ }
910
1087
  }
911
1088
 
912
1089
  /** Start the bridge: loopback listener + published endpoint file + token. */
913
- export function start() {
914
- stop()
1090
+ export function start(api) {
1091
+ const current = globalThis[ACTIVE]
1092
+ if (current) {
1093
+ const mainOwned = current.api?.owner === 'desktop-main'
1094
+ if (mainOwned && api?.owner !== 'desktop-main') return current.server
1095
+ if (api?.reload !== true && (mainOwned || api?.owner !== 'desktop-main')) return current.server
1096
+ if (typeof current.stop === 'function') current.stop()
1097
+ else stop()
1098
+ }
1099
+ const application = api?.app ?? app
1100
+ // Sidebar guests are created by the shell at any time (including after a
1101
+ // bridge reload), so configure both the existing guests and every future one.
1102
+ // Default policy is direct, which is fast but useless on a machine whose
1103
+ // only route out is the local proxy. Retry such a session ONCE through the
1104
+ // OS proxy on a transport-level failure (DNS/connect/timeout), so "no proxy
1105
+ // configured" environments degrade to the old behaviour instead of a blank
1106
+ // page. HTTP errors (404/500) must not trigger this.
1107
+ const attachProxyFallback = (contents) => {
1108
+ if (contents.getType() !== 'webview' || fallbackHandlers.has(contents)) return
1109
+ const handler = (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
1110
+ if (!isMainFrame) return
1111
+ if ((process.env.DSH_SIDEBAR_PROXY_MODE ?? 'direct') !== 'direct') return
1112
+ if (!shouldFallbackToSystemProxy(errorCode)) return
1113
+ void (async () => {
1114
+ try {
1115
+ const session = contents.session
1116
+ if (!session) return
1117
+ const resolved = await session.resolveProxy('https://example.com/').catch(() => '')
1118
+ const parsed = parseSystemProxy(resolved)
1119
+ if (!parsed || !(await proxyReachable(parsed.authority))) return
1120
+ const config = {
1121
+ mode: 'fixed_servers',
1122
+ proxyRules: parsed.rules,
1123
+ proxyBypassRules: process.env.DSH_SIDEBAR_PROXY_BYPASS ?? DEFAULT_SIDEBAR_PROXY_BYPASS,
1124
+ }
1125
+ await session.setProxy(config)
1126
+ proxyApplied.set(session, JSON.stringify(config))
1127
+ try { await session.closeAllConnections?.() } catch { /* older Electron */ }
1128
+ console.log('[dsh-browser-bridge] direct failed (' + errorCode + ' ' + errorDescription + '), retrying via system proxy:', parsed.authority)
1129
+ // The probe above takes a few hundred milliseconds. If the guest is
1130
+ // gone, or the user already started another navigation, reloading the
1131
+ // failed URL would silently drag them back to the old page.
1132
+ if (typeof contents.isDestroyed === 'function' && contents.isDestroyed()) return
1133
+ const currentUrl = typeof contents.getURL === 'function' ? contents.getURL() : validatedURL
1134
+ if (currentUrl !== validatedURL) return
1135
+ contents.loadURL(validatedURL).catch(() => undefined)
1136
+ } catch (error) {
1137
+ console.error('[dsh-browser-bridge] proxy fallback failed:', error)
1138
+ }
1139
+ })()
1140
+ }
1141
+ fallbackHandlers.set(contents, handler)
1142
+ contents.on('did-fail-load', handler)
1143
+ }
1144
+
1145
+ const onGuestCreated = (_event, contents) => {
1146
+ if (contents.getType() === 'webview') contents.setWindowOpenHandler?.(() => ({ action: 'deny' }))
1147
+ void applySidebarGuestProxy(contents)
1148
+ attachProxyFallback(contents)
1149
+ }
1150
+ application.on('web-contents-created', onGuestCreated)
1151
+ for (const contents of webContents.getAllWebContents()) {
1152
+ onGuestCreated(undefined, contents)
1153
+ }
915
1154
  // Drop any debugger attachment this process is still holding.
916
1155
  //
917
1156
  // An attachment belongs to the webContents, not to this module, so it outlives both the listener
@@ -927,13 +1166,20 @@ export function start() {
927
1166
  }
928
1167
  } catch { /* no webContents at all; nothing to detach */ }
929
1168
  const token = randomBytes(24).toString('hex')
1169
+ const sockets = new Set()
930
1170
  const server = createServer(socket => {
1171
+ sockets.add(socket)
1172
+ const controller = new AbortController()
931
1173
  let buffer = ''
932
1174
  let authed = false
933
1175
  socket.setEncoding('utf8')
934
1176
  const authenticationDeadline = setTimeout(() => socket.destroy(), 5_000)
935
1177
  authenticationDeadline.unref?.()
936
- socket.on('close', () => clearTimeout(authenticationDeadline))
1178
+ socket.on('close', () => {
1179
+ sockets.delete(socket)
1180
+ clearTimeout(authenticationDeadline)
1181
+ controller.abort(codedError('bridge-request-abandoned', 'the bridge client disconnected'))
1182
+ })
937
1183
  socket.on('data', chunk => {
938
1184
  if (Buffer.byteLength(buffer, 'utf8') + Buffer.byteLength(chunk, 'utf8') > 32 * 1024 * 1024) {
939
1185
  socket.destroy()
@@ -970,7 +1216,7 @@ export function start() {
970
1216
  // (A client may also put the token on its first real request; both work.)
971
1217
  if (typeof request.op !== 'string' || request.op === '') continue
972
1218
  }
973
- void handle(request)
1219
+ void handle(request, controller.signal)
974
1220
  // The request id is stamped HERE, at the single point where every answer is written,
975
1221
  // rather than on the handful of returns that happened to remember it.
976
1222
  //
@@ -987,6 +1233,7 @@ export function start() {
987
1233
  // English sentence to know whether the carrier died or the conversation is just not on
988
1234
  // screen (issue #37).
989
1235
  ...error?.code === undefined ? {} : { code: String(error.code) },
1236
+ ...error?.initialization === undefined ? {} : { initialization: error.initialization },
990
1237
  bridgeRequestId: request.bridgeRequestId,
991
1238
  }) + '\n'))
992
1239
  }
@@ -1000,9 +1247,10 @@ export function start() {
1000
1247
  // Loopback only, port chosen by the OS: the endpoint file is the discovery
1001
1248
  // mechanism, so a fixed port would only add collisions.
1002
1249
  server.listen(0, '127.0.0.1', () => {
1250
+ if (globalThis[ACTIVE]?.server !== server) { server.close(); return }
1003
1251
  const address = server.address()
1004
1252
  const port = typeof address === 'object' && address !== null ? address.port : 0
1005
- if (publishEndpoint(port, token)) {
1253
+ if (publishEndpoint(port, token, api?.dshHome)) {
1006
1254
  console.log(`[dsh-browser-bridge] listening on 127.0.0.1:${port} (pid ${process.pid})`)
1007
1255
  }
1008
1256
  })
@@ -1010,11 +1258,11 @@ export function start() {
1010
1258
  const keepalive = setInterval(() => {
1011
1259
  const address = server.address()
1012
1260
  const port = typeof address === 'object' && address !== null ? address.port : 0
1013
- if (port !== 0) publishEndpoint(port, token)
1261
+ if (port !== 0) publishEndpoint(port, token, api?.dshHome)
1014
1262
  }, 15_000)
1015
1263
  keepalive.unref?.()
1016
1264
  const onQuit = () => stop()
1017
- app.on('will-quit', onQuit)
1018
- globalThis[ACTIVE] = { server, keepalive, onQuit }
1265
+ application.on('will-quit', onQuit)
1266
+ globalThis[ACTIVE] = { server, keepalive, onQuit, onGuestCreated, stop, api, application, token, sockets }
1019
1267
  return server
1020
1268
  }