dsh-builtin-browser 1.0.0 → 1.0.3

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