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,1462 +0,0 @@
1
- import { LOOPBACK_IPV4 } from '../../assets/browser-policy.mjs'
2
- /**
3
- * Legacy standalone Electron browser host (not a supported package export): an
4
- * {@link ElectronBrowserViewHost} implementation that spawns the plugin's own
5
- * Electron child process (host-main.js) and drives it over line-delimited
6
- * JSON-RPC on a loopback TCP socket.
7
- *
8
- * Protocol (one JSON object per line, both directions):
9
- * -> { id, op: 'createView' } | { id, op: 'destroyView', viewId } |
10
- * { id, op: 'showView', viewId } | { id, op: 'command', viewId, method, params }
11
- * <- { id, op: 'hello', token } (the child's FIRST message — authenticates it)
12
- * <- { id, ok: true, result? } | { id, ok: false, err }
13
- *
14
- * The child is Electron's main process; host-main.js owns the BrowserWindow,
15
- * WebContentsViews, and webContents.debugger (CDP).
16
- *
17
- * Security: the RPC server accepts exactly ONE connection, and only after
18
- * that connection proves knowledge of the random per-spawn token (passed to
19
- * the child via its stdin (first line, never in argv). A local process that
20
- * connects to the loopback port without the token can neither impersonate the
21
- * child nor inject replies — it is disconnected as soon as its first line
22
- * arrives. Commands are only written after the hello authenticates, and every
23
- * other inbound op (including the fire-and-forget `userAction` / `viewClosed`
24
- * notifications) is dispatched only once that check has passed, so an
25
- * unauthenticated peer can neither read traffic nor drive a session.
26
- * @module dsh-browser/browser-electron/remote-host
27
- */
28
-
29
- import { execFileSync, spawn } from 'node:child_process'
30
- import { appendFileSync, mkdirSync, statSync, writeFileSync } from 'node:fs'
31
- import { randomBytes, randomUUID } from 'node:crypto'
32
- import { createRequire } from 'node:module'
33
- import { existsSync, readFileSync, readdirSync, readlinkSync } from 'node:fs'
34
- import { basename, dirname, isAbsolute, join } from 'node:path'
35
- import { createServer, type Server, type Socket } from 'node:net'
36
- import { withTimeoutShared } from './timing.ts'
37
- import { browserHostLogPath } from './paths.ts'
38
- import { fileURLToPath } from 'node:url'
39
- import type { BrowserUserAction, ElectronBrowserViewHost, ElectronViewHandle, PresentOptions, ScreenshotOptions } from './provider.ts'
40
- import type { ExportedCookie } from '../browser/types.ts'
41
- import { readTabHandle, tabWireId, type BrowserTabWireId } from '../browser/handles.ts'
42
-
43
- /** How long to wait for the child to signal readiness before failing. */
44
- const READY_TIMEOUT_MS = 20_000
45
-
46
- /** Budget for the present/barrier round-trips (see presentView). */
47
- const PRESENT_TIMEOUT_MS = 10_000
48
-
49
- /** Safety cap on a single RPC reply line (base64 downloads are the big ones). */
50
- const MAX_RPC_BUFFER_BYTES = 512 * 1024 * 1024
51
-
52
- /**
53
- * Locate a SPAWNABLE Electron binary — one that runs a script given as an
54
- * argument, i.e. a BARE electron, never a packaged app executable:
55
- * 0. ELECTRON_PATH (explicit override — user intent beats auto-discovery),
56
- * 1. the plugin's own electron package (a real dependency since 0.1.18),
57
- * found by a pure filesystem walk — never require(), whose semantics
58
- * differ inside an Electron main process (there it is the built-in API
59
- * module, not the npm package) and which would trigger electron 44+'s
60
- * lazy binary download;
61
- * 2. every DSH install anchor (electron installed separately, e.g.
62
- * `dsh plugin add electron` into the profile or a global prefix),
63
- * choosing the NEWEST version found. Older Electron releases (e.g.
64
- * 33.x) have a compositor defect that intermittently breaks page
65
- * capture, so prefer the newest binary available in the environment,
66
- * 3. the current process, when it IS a bare Electron (dev hosts, e.g.
67
- * `electron .`): reuse the host binary. Packaged app executables
68
- * (resources/app.asar beside the exe) are never reused — they ignore
69
- * the script argument and launch the app itself, typically exiting
70
- * immediately via the single-instance lock, which is exactly the
71
- * "browser host exited (code=0)" failure on DSH Desktop;
72
- * 4. last resort: the process ancestry, for hosts that run this plugin in a
73
- * child Node process of their own bare-Electron main process.
74
- * @returns the path to the Electron executable.
75
- */
76
- /** The discovery inputs {@link resolveElectronPathImpl} selects over, injectable for tests. */
77
- interface ElectronPathInputs {
78
- /** ELECTRON_PATH (may be unset, empty, or pointing at a missing file). */
79
- readonly override: string | undefined
80
- /** True when running inside an Electron main process. */
81
- readonly inElectron: boolean
82
- /** process.execPath (candidate for in-process host reuse). */
83
- readonly execPath: string
84
- /** The plugin's own electron package probe (bundled). */
85
- readonly bundled: () => string | undefined
86
- /** The DSH install-anchor probe. */
87
- readonly anchored: () => string | undefined
88
- /** The process-ancestry probe (last resort). */
89
- readonly ancestry: () => string | undefined
90
- }
91
-
92
- function resolveElectronPath(): string {
93
- return resolveElectronPathImpl({
94
- override: process.env.ELECTRON_PATH,
95
- inElectron: typeof process.versions.electron === 'string',
96
- execPath: process.execPath,
97
- bundled: bundledElectronBinary,
98
- anchored: anchoredElectronBinary,
99
- ancestry: hostElectronViaProcessTree,
100
- })
101
- }
102
-
103
- /**
104
- * Pure selection over the discovery probes, in order:
105
- * 0. override (user intent) → 1. bundled package → 2. anchors (newest) →
106
- * 3. in-process BARE host → 4. process ancestry → throw.
107
- * Packaged app executables are never reused (steps 3/4 skip them).
108
- */
109
- function resolveElectronPathImpl(inputs: ElectronPathInputs): string {
110
- // 0. Explicit override first: a user-set ELECTRON_PATH is a deliberate
111
- // choice and must beat every auto-discovery (including the bundled
112
- // package) — auto-discovery is a fallback, not an override.
113
- const override = inputs.override
114
- if (typeof override === 'string' && override.length > 0 && existsSync(override)) return override
115
- // 1. The plugin's own electron package (filesystem probe). Never require():
116
- // inside an Electron main process require('electron') is the built-in
117
- // API module, not the npm package, and electron 44+ downloads its binary
118
- // on first require — probing must stay side-effect free (available()
119
- // would otherwise block DSH startup on the download).
120
- const bundled = inputs.bundled()
121
- if (bundled !== undefined) return bundled
122
- // 2. DSH install anchors, newest wins. (The plugin's own tree — plain and
123
- // pnpm store layouts — was already scanned in step 1; the anchors cover
124
- // electron installed separately, e.g. `dsh plugin add electron` into the
125
- // profile or a global prefix.)
126
- const anchored = inputs.anchored()
127
- if (anchored !== undefined) return anchored
128
- // 3. The current process IS a bare Electron (dev hosts, e.g. `electron .`):
129
- // reuse the host binary — it cannot be missing because we are running on
130
- // it. A PACKAGED app executable (resources/app.asar beside it, e.g. DSH
131
- // Desktop.exe) is NOT spawnable as bare electron: it ignores the script
132
- // argument, launches the app itself, and typically exits immediately
133
- // (single-instance lock) — so it is never reused.
134
- if (inputs.inElectron) {
135
- const exe = inputs.execPath
136
- if (typeof exe === 'string' && exe.length > 0 && existsSync(exe) && isBareElectron(exe)) return exe
137
- }
138
- // 4. Last resort for bare-Electron hosts: walk the process ancestry (the
139
- // plugin may run in a child Node process of an Electron main process).
140
- const hostExe = inputs.ancestry()
141
- if (hostExe !== undefined) return hostExe
142
- throw new Error(
143
- 'dsh-builtin-browser: cannot locate a spawnable Electron binary. ' +
144
- 'The electron package ships with the plugin and its binary is downloaded on first use, not at install time ' +
145
- '(issue #41: an install-time download made default profiles refuse the plugin). The plugin prepares it ' +
146
- 'automatically when the bundled carrier is selected, so right after an install this can mean the ' +
147
- 'download is still running: Settings → Browser → Readiness shows that state and can retry it. To do it ' +
148
- 'by hand instead, run `npx --no dsh-browser-install-electron` in the profile that installed the ' +
149
- 'plugin, then retry. Alternatively set ELECTRON_PATH to an electron executable. Note: the host\'s own ' +
150
- 'executable cannot be reused when it is a packaged Electron app (e.g. DSH Desktop.exe) — only a real ' +
151
- 'electron binary can be spawned.',
152
- )
153
- }
154
-
155
- /** DSH install anchors: electron installed separately (profile / global prefix), newest wins. */
156
- function anchoredElectronBinary(): string | undefined {
157
- const require = createRequire(import.meta.url)
158
- const candidates: Array<{ version: string; path: string }> = []
159
- const add = (version: string, path: string | undefined): void => {
160
- if (path !== undefined) candidates.push({ version, path })
161
- }
162
- const anchors: string[] = []
163
- const globalPrefix = process.env.npm_config_prefix ?? process.env.PREFIX
164
- if (globalPrefix !== undefined) {
165
- anchors.push(join(globalPrefix, 'node_modules'))
166
- anchors.push(join(globalPrefix, 'node_modules', '@deepseek-ai', 'dsh', 'node_modules'))
167
- }
168
- if (process.env.DSH_HOME !== undefined) {
169
- anchors.push(join(process.env.DSH_HOME, 'profiles', 'node_modules'))
170
- }
171
- for (const anchor of anchors) {
172
- try {
173
- const resolved: unknown = require.resolve('electron', { paths: [anchor] })
174
- // Inside an Electron main process resolve('electron') yields the
175
- // built-in module NAME (not a path) — requiring an absolute path keeps
176
- // electronExeBeside from probing cwd-relative garbage like ./dist/.
177
- if (typeof resolved === 'string' && resolved.length > 0 && isAbsolute(resolved)) {
178
- add(versionOf(resolved), electronExeBeside(resolved))
179
- }
180
- } catch {
181
- // continue probing
182
- }
183
- }
184
- return pickNewest(candidates)
185
- }
186
-
187
- /**
188
- * The plugin's own electron package binary, found by a pure filesystem walk
189
- * (never require(), whose semantics differ inside an Electron main process —
190
- * there `require('electron')` is the built-in API module, not the npm package
191
- * — and which would trigger electron 44+'s lazy binary download when the dist
192
- * is missing). Checks every `node_modules/electron` above this module,
193
- * including pnpm virtual-store layouts, and returns the NEWEST ready binary.
194
- * Scan ONLY the plugin's own install tree: never cwd or the executable's
195
- * directory, which can sit inside an unrelated project whose node_modules may
196
- * hold a different electron (executing the newest random binary in the
197
- * filesystem is a supply-chain hazard with no benefit).
198
- */
199
- function bundledElectronBinary(): string | undefined {
200
- const candidates: Array<{ version: string; path: string }> = []
201
- const consider = (pkgRoot: string, versionHint: string): void => {
202
- const exe = electronDistExe(pkgRoot)
203
- if (exe !== undefined) candidates.push({ version: versionHint || pkgVersion(pkgRoot), path: exe })
204
- }
205
- let dir = fileURLToPath(new URL('.', import.meta.url))
206
- for (let depth = 0; depth < 8; depth++) {
207
- // Plain (npm/yarn, hoisted) layout: <ancestor>/node_modules/electron.
208
- const plain = join(dir, 'node_modules', 'electron')
209
- if (existsSync(join(plain, 'package.json'))) consider(plain, '')
210
- // pnpm layout: <ancestor>/node_modules/.pnpm or <ancestor>/.pnpm, with
211
- // electron@<version>/node_modules/electron entries.
212
- for (const storeRoot of [join(dir, 'node_modules', '.pnpm'), join(dir, '.pnpm')]) {
213
- if (!existsSync(storeRoot)) continue
214
- for (const entry of readdirSync(storeRoot)) {
215
- if (!entry.startsWith('electron@')) continue
216
- const pkg = join(storeRoot, entry, 'node_modules', 'electron')
217
- // Strip pnpm's peer-dependency suffix (electron@44.0.0_@types+node@22).
218
- if (existsSync(join(pkg, 'package.json'))) consider(pkg, entry.slice('electron@'.length).split('_')[0])
219
- }
220
- }
221
- const parent = join(dir, '..')
222
- if (parent === dir) break
223
- dir = parent
224
- }
225
- return pickNewest(candidates)
226
- }
227
-
228
- /** The electron version from a package root's package.json, or '0.0.0'. */
229
- function pkgVersion(pkgRoot: string): string {
230
- try {
231
- const pkg = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')) as { version?: unknown }
232
- return typeof pkg.version === 'string' && pkg.version.length > 0 ? pkg.version : '0.0.0'
233
- } catch {
234
- return '0.0.0'
235
- }
236
- }
237
-
238
- /** The highest-versioned candidate's path, or undefined when none. */
239
- function pickNewest(candidates: Array<{ version: string; path: string }>): string | undefined {
240
- let best: { version: string; path: string } | undefined
241
- for (const c of candidates) {
242
- if (best === undefined || compareVersions(c.version, best.version) > 0) best = c
243
- }
244
- return best?.path
245
- }
246
-
247
- /**
248
- * Last-resort Electron discovery: walk this process's ancestry looking for a
249
- * parent process whose executable is a BARE Electron binary (only bare
250
- * electron can be spawned with a script argument). Covers hosts that run the
251
- * plugin in a child Node process of their own Electron main process: the host
252
- * binary is already on disk and running, so reusing it needs no extra
253
- * install. Filesystem-only on POSIX (/proc); on Windows a best-effort
254
- * PowerShell CIM query is used — this path only runs when every other lookup
255
- * failed, so its latency never touches the happy path, and a
256
- * missing/blocked powershell simply yields nothing.
257
- */
258
- function hostElectronViaProcessTree(): string | undefined {
259
- let pid: number | undefined = process.ppid
260
- for (let depth = 0; depth < 6 && pid !== undefined && pid > 1; depth++) {
261
- const exe = processExecutable(pid)
262
- if (exe !== undefined && isBareElectron(exe)) return exe
263
- pid = processParent(pid)
264
- }
265
- return undefined
266
- }
267
-
268
- /** One scalar property of a Windows process, read through CIM. */
269
- function cimQuery(pid: number, property: 'ExecutablePath' | 'ParentProcessId'): string {
270
- const out = execFileSync('powershell.exe', [
271
- '-NoProfile', '-NonInteractive', '-Command',
272
- `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").${property}`,
273
- ], { encoding: 'utf8', windowsHide: true, timeout: 3000 })
274
- return out.trim().split(/\r?\n/)[0] ?? ''
275
- }
276
-
277
- /** The executable path of a running process, or undefined when unknown. */
278
- function processExecutable(pid: number): string | undefined {
279
- try {
280
- if (process.platform === 'win32') {
281
- const line = cimQuery(pid, 'ExecutablePath')
282
- return line.length > 0 ? line : undefined
283
- }
284
- const exe = readlinkSync(`/proc/${pid}/exe`)
285
- return exe.length > 0 ? exe : undefined
286
- } catch {
287
- return undefined
288
- }
289
- }
290
-
291
- /** The parent pid of a running process, or undefined when unknown. */
292
- function processParent(pid: number): number | undefined {
293
- try {
294
- if (process.platform === 'win32') {
295
- const n = Number(cimQuery(pid, 'ParentProcessId'))
296
- return Number.isInteger(n) && n > 1 ? n : undefined
297
- }
298
- const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
299
- // Format: pid (comm) state ppid ... — comm is parenthesized and may
300
- // itself contain spaces/parens, so parse from the LAST ')'; ppid is the
301
- // second field after it.
302
- const fields = stat.slice(stat.lastIndexOf(')') + 1).trim().split(/\s+/)
303
- const n = Number(fields[1])
304
- return Number.isInteger(n) && n > 1 ? n : undefined
305
- } catch {
306
- return undefined
307
- }
308
- }
309
-
310
- /**
311
- * True when the given executable is an Electron binary. The name match
312
- * covers dev binaries (electron, electron.exe); the resources marker covers
313
- * packaged apps whose exe carries the product name (e.g. "DSH Desktop.exe") —
314
- * every Electron distribution ships `resources/electron.asar`,
315
- * `resources/app.asar`, or `resources/default_app.asar` beside the binary.
316
- */
317
- function isElectronBinary(exe: string): boolean {
318
- if (basename(exe).toLowerCase().includes('electron')) return true
319
- const resources = join(dirname(exe), 'resources')
320
- return existsSync(join(resources, 'electron.asar'))
321
- || existsSync(join(resources, 'app.asar'))
322
- || existsSync(join(resources, 'default_app.asar'))
323
- }
324
-
325
- /**
326
- * True when the executable is a BARE (unpackaged) Electron that can be
327
- * spawned with a script argument (`exe script.js --rpc-port N`). Packaged
328
- * apps carry their code inside a resources dir (`app.asar`, or an unpacked
329
- * `app` dir) and are NOT spawnable as bare electron: they ignore the script
330
- * argument and launch the app itself, typically exiting immediately via the
331
- * single-instance lock — spawning e.g. DSH Desktop.exe is exactly the
332
- * "browser host exited (code=0)" failure. A portable single-file build (no
333
- * resources dir at all) likewise cannot run a script argument.
334
- */
335
- function isBareElectron(exe: string): boolean {
336
- const dir = dirname(exe)
337
- // Windows/Linux keep resources beside the binary; macOS app bundles keep
338
- // them in Contents/Resources, one level above the binary's MacOS dir.
339
- const resourcesList = process.platform === 'darwin'
340
- ? [join(dir, '..', 'Resources'), join(dir, 'resources')]
341
- : [join(dir, 'resources')]
342
- for (const resources of resourcesList) {
343
- if (existsSync(join(resources, 'app.asar')) || existsSync(join(resources, 'app'))) return false
344
- }
345
- // A real electron always ships a resources dir somewhere; requiring one
346
- // keeps every not-actually-spawnable layout out.
347
- if (!resourcesList.some(p => existsSync(p))) return false
348
- return isElectronBinary(exe)
349
- }
350
-
351
- /** Extract an electron version like "43.4.0" from a path containing it. */
352
- function versionOf(path: string): string {
353
- const match = /electron@(\d+\.\d+\.\d+)/.exec(path)
354
- return match?.[1] ?? '0.0.0'
355
- }
356
-
357
- /** Compare dotted numeric versions; higher wins. */
358
- function compareVersions(a: string, b: string): number {
359
- const pa = a.split('.').map(n => Number(n) || 0)
360
- const pb = b.split('.').map(n => Number(n) || 0)
361
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
362
- const d = (pa[i] ?? 0) - (pb[i] ?? 0)
363
- if (d !== 0) return d
364
- }
365
- return 0
366
- }
367
-
368
- /** Candidate executable layouts used by the Electron npm package on one platform. */
369
- function electronDistCandidates(pkgRoot: string, platform: NodeJS.Platform = process.platform): string[] {
370
- // macOS keeps the runnable binary inside the Electron.app bundle; unlike
371
- // Windows/Linux there is no dist/electron(.exe) sibling to probe.
372
- if (platform === 'darwin') {
373
- return [join(pkgRoot, 'dist', 'Electron.app', 'Contents', 'MacOS', 'Electron')]
374
- }
375
- return [
376
- join(pkgRoot, 'dist', 'electron.exe'),
377
- join(pkgRoot, 'dist', 'electron'),
378
- ]
379
- }
380
-
381
- /** From an electron package entry file, find the dist executable beside it. */
382
- function electronExeBeside(entry: string, platform: NodeJS.Platform = process.platform): string | undefined {
383
- const packageRoots = [dirname(entry), join(dirname(entry), '..')]
384
- for (const packageRoot of packageRoots) {
385
- const candidate = electronDistExe(packageRoot, platform)
386
- if (candidate !== undefined) return candidate
387
- }
388
- return undefined
389
- }
390
-
391
- /** From an electron package root, find its dist executable. */
392
- function electronDistExe(pkgRoot: string, platform: NodeJS.Platform = process.platform): string | undefined {
393
- for (const candidate of electronDistCandidates(pkgRoot, platform)) {
394
- if (existsSync(candidate)) return candidate
395
- }
396
- return undefined
397
- }
398
-
399
- /** One RPC round-trip with the child. */
400
- interface Pending {
401
- resolve(result: unknown): void
402
- reject(err: Error): void
403
- }
404
-
405
- /**
406
- * Thrown whenever the browser host (the Electron child) is gone — it exited,
407
- * failed to start, or its RPC connection dropped. Operations against a dead
408
- * host can never succeed, so the view layer treats this as "rebuild against a
409
- * fresh host" instead of a page-level error. Kept module-private: callers
410
- * observe the behavior (auto-restart), not the class.
411
- */
412
- class HostGoneError extends Error {
413
- constructor(message: string) {
414
- super(message)
415
- this.name = 'HostGoneError'
416
- }
417
- }
418
-
419
- /**
420
- * Line-delimited JSON-RPC client over a local TCP socket. Electron's main
421
- * process on Windows does not receive piped stdin, so the parent listens on a
422
- * loopback port and passes it to the child via `--rpc-port`; the child
423
- * connects back and speaks the same one-JSON-per-line protocol.
424
- */
425
- class ElectronChildClient {
426
- private readonly child: import('node:child_process').ChildProcessWithoutNullStreams
427
- private readonly pending = new Map<number, Pending>()
428
- private nextId = 1
429
- private buffer = ''
430
- private socket: import('node:net').Socket | undefined
431
- private connected = false
432
- private outbox: string[] = []
433
- /** Set once the child has exited; further calls fail fast instead of queueing. */
434
- private dead = false
435
- /**
436
- * True until the first message proves the child knows the spawn token.
437
- * Commands are queued (not written) until then, so a spoofed socket never
438
- * sees any traffic.
439
- */
440
- private awaitingHello = true
441
- private helloTimer: ReturnType<typeof setTimeout> | undefined
442
-
443
- constructor(
444
- private readonly hostMainPath: string,
445
- private readonly port: number,
446
- private readonly token: string,
447
- private readonly onExit?: () => void,
448
- private readonly onUserAction?: (action: BrowserUserAction) => void,
449
- /**
450
- * Called when the human closes a browser window. The session it showed is
451
- * over: the provider releases it, while history and login state stay on disk
452
- * so the next open is a clean session rather than a resurrected one.
453
- */
454
- private readonly onViewClosed?: (windowId: string) => void,
455
- /** Test seam: the executable to spawn instead of the resolved Electron
456
- * binary. Absent -> resolveElectronPath() (production behavior). */
457
- private readonly executable?: string,
458
- ) {
459
- const electron = this.executable ?? resolveElectronPath()
460
- const source = this.executable !== undefined
461
- ? 'provided'
462
- : electron === process.env.ELECTRON_PATH ? 'ELECTRON_PATH' : 'auto'
463
- // Record what is about to be spawned — with existence checks — BEFORE the
464
- // attempt. When Electron cannot load the app entry it exits 1 with EMPTY
465
- // stderr, and that signature is otherwise indistinguishable from a missing
466
- // binary: writing both paths (and whether they exist) in advance is what
467
- // turns the next occurrence into a named cause instead of a guess.
468
- process.stderr.write(`[dsh-browser host] spawning electron: ${electron} source=${source}\n`)
469
- appendHostLog(
470
- `${hostStamp()} spawning: electron=${electron} (exists=${String(existsSync(electron))})`
471
- + ` source=${source}`
472
- + ` hostMain=${this.hostMainPath} (exists=${String(existsSync(this.hostMainPath))})`
473
- + ` port=${String(this.port)}\n`,
474
- )
475
- // ELECTRON_RUN_AS_NODE (even an empty string) makes Electron run as plain
476
- // Node, breaking require('electron'); NODE_OPTIONS can inject flags that
477
- // break the child. Rebuild the env without either.
478
- const env: Record<string, string | undefined> = { ...process.env }
479
- delete env.ELECTRON_RUN_AS_NODE
480
- delete env.NODE_OPTIONS
481
- // Windows GUI-subsystem processes (Electron included) never receive piped
482
- // stdin, so the token written below is silently lost there. Pass it as an
483
- // environment variable too (hidden from the process-listing tools that
484
- // expose argv, and preferred over stdin only when stdin cannot deliver):
485
- // the child reads env only as a fallback after stdin yields nothing.
486
- env.DSH_BROWSER_RPC_TOKEN = token
487
- this.child = spawn(electron, [hostMainPath, '--rpc-port', String(port)], {
488
- stdio: ['pipe', 'pipe', 'pipe'],
489
- windowsHide: false,
490
- env,
491
- })
492
- this.child.stderr.setEncoding('utf8')
493
- this.child.stderr.on('data', chunk => {
494
- // Diagnostics only; never parse stderr as protocol. Mirror to a log file
495
- // as well: under a plain `dsh web` self-host these lines only ever reach
496
- // the DSH process's stderr, so a host that crashes in a restart loop left
497
- // the user with a string of timeouts and no stack to act on.
498
- const text = String(chunk)
499
- process.stderr.write(`[dsh-browser host] ${text}`)
500
- appendHostLog(text)
501
- })
502
- // Send the spawn token over stdin (first line). The child reads it from
503
- // stdin instead of argv so the token is never visible in the process
504
- // listing (WMI / Process Explorer / /proc/*). After writing, close stdin
505
- // so the child knows the token has been fully delivered.
506
- this.child.stdin?.write(token + '\n')
507
- this.child.stdin?.end()
508
- // A failed spawn (bad/corrupt binary) emits 'error' — without a listener
509
- // that would crash the whole DSH process.
510
- this.child.on('error', error => {
511
- const line = `${hostStamp()} spawn error: ${String(error)} electron=${electron} hostMain=${this.hostMainPath}`
512
- process.stderr.write(`[dsh-browser host] ${line}\n`)
513
- appendHostLog(`${line}\n`)
514
- // The cached availability answer is retired by `onExit` below, which this reaches
515
- // through fail(): the decision needs the host's view of what is on disk, not the
516
- // client's.
517
- this.fail(new Error(`dsh-builtin-browser: browser host failed to start: ${String(error)}`))
518
- })
519
- this.child.on('exit', (code, signal) => {
520
- // The exit code/signal is the other half of a crash report; without it a
521
- // restart loop is indistinguishable from a clean stop. The timestamp, pid
522
- // and both paths are what turn a bare `code=1` into a diagnosis: Electron
523
- // exits 1 with empty stderr precisely when it cannot load the app entry,
524
- // so the dated `exists=` line written at spawn is the other half.
525
- const entryExists = existsSync(this.hostMainPath)
526
- const line = `${hostStamp()} browser host exited (code=${String(code)} signal=${String(signal)})`
527
- + ` pid=${String(this.child?.pid)} electron=${electron} hostMain=${this.hostMainPath}`
528
- + ` entryExists=${String(entryExists)}`
529
- // Comparing this with the `exists=` recorded at spawn is the whole
530
- // diagnosis: present at spawn and absent now means the installation was
531
- // replaced underneath a running host, which is exactly how Electron ends
532
- // up unable to load the app entry and exits 1 with empty stderr.
533
- + (entryExists ? '' : ' [entry script missing at exit]')
534
- appendHostLog(`${line}\n`)
535
- this.fail(new Error(`dsh-builtin-browser: ${line}`))
536
- })
537
- }
538
-
539
- /**
540
- * Drop the escalation kill once there is nothing left for it to target.
541
- *
542
- * Called on the paths where the child is known to be gone — after an observed exit, and on
543
- * release. It is deliberately NOT called from `fail()`: a dead socket says nothing about the
544
- * process on the other end, and the timer exists for exactly the case where the child ignores
545
- * the socket closing. Clearing it there disarmed the only escalation there was, which is how
546
- * a child that ignored its socket could outlive dispose() and keep holding the profile.
547
- */
548
- private clearKillGrace(): void {
549
- if (this.killGraceTimer === undefined) return
550
- clearTimeout(this.killGraceTimer)
551
- this.killGraceTimer = undefined
552
- }
553
-
554
- /** Drop the "did not authenticate" deadline once it can no longer be meaningful. */
555
- private clearHelloTimer(): void {
556
- if (this.helloTimer === undefined) return
557
- clearTimeout(this.helloTimer)
558
- this.helloTimer = undefined
559
- }
560
-
561
- /** Reject everything in flight, mark the client dead, and notify the host. */
562
- private fail(err: Error): void {
563
- if (this.dead) return
564
- this.dead = true
565
- this.connected = false
566
- // The authentication deadline outlives the socket it was armed for otherwise: it is
567
- // keyed on `awaitingHello` alone, so a client that already failed on some other path
568
- // kept a live timer until it fired (harmless, but it is a dangling timer in a process
569
- // that may be shutting down).
570
- this.clearHelloTimer()
571
- // NOT clearKillGrace(): this path runs when the SOCKET died, which says nothing about
572
- // whether the process did. Clearing the escalation here disarmed it for exactly the case it
573
- // exists for — a child that ignores its socket closing — so dispose() could return with the
574
- // child still running and still holding the profile. The timer clears itself when the child
575
- // exits, and `kill()` replaces it on an explicit release.
576
- // Tag every failure as "host gone" so the view layer can tell a dead host
577
- // apart from a page-level error and rebuild against a fresh child.
578
- const wrapped = err instanceof HostGoneError ? err : new HostGoneError(err.message)
579
- for (const pending of this.pending.values()) pending.reject(wrapped)
580
- this.pending.clear()
581
- this.outbox = []
582
- this.onExit?.()
583
- }
584
-
585
- /** Whether a connection (authenticated or still authenticating) is held. */
586
- isAttached(): boolean {
587
- return this.socket !== undefined
588
- }
589
-
590
- /**
591
- * Accept the child's connection (called by the server). Exactly one socket
592
- * is ever attached; the server drops any further connection. Commands stay
593
- * queued until the child's first line authenticates with the spawn token.
594
- */
595
- attach(socket: import('node:net').Socket): void {
596
- if (this.socket !== undefined) {
597
- // Already attached: this is a second connection; reject it.
598
- socket.destroy()
599
- return
600
- }
601
- this.socket = socket
602
- socket.setEncoding('utf8')
603
- // Without an 'error' listener a remote reset (ECONNRESET/EPIPE) throws an
604
- // uncaught 'error' event and crashes the whole DSH process; 'close' below
605
- // does the cleanup.
606
- socket.on('error', error => {
607
- process.stderr.write(`[dsh-browser host] socket error: ${String(error)}\n`)
608
- })
609
- socket.on('data', chunk => this.onData(chunk))
610
- socket.on('close', () => {
611
- this.connected = false
612
- if (!this.dead) {
613
- this.fail(new Error('dsh-builtin-browser: browser host connection closed'))
614
- }
615
- })
616
- // The child must authenticate within the readiness budget; otherwise the
617
- // connection is treated as hostile and torn down.
618
- this.helloTimer = setTimeout(() => {
619
- if (this.awaitingHello) {
620
- socket.destroy()
621
- this.fail(new Error('dsh-builtin-browser: browser host did not authenticate'))
622
- }
623
- }, READY_TIMEOUT_MS)
624
- }
625
-
626
- private onData(chunk: string | Buffer): void {
627
- this.buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8')
628
- // Safety net: a pathological child (or a reply larger than expected)
629
- // must not grow the parent's memory without bound. The child caps
630
- // downloads at 256 MiB, so a healthy stream never approaches this.
631
- if (this.buffer.length > MAX_RPC_BUFFER_BYTES) {
632
- this.buffer = ''
633
- this.fail(new Error(`dsh-builtin-browser: RPC reply exceeded ${MAX_RPC_BUFFER_BYTES} bytes`))
634
- return
635
- }
636
- let nl: number
637
- while ((nl = this.buffer.indexOf('\n')) >= 0) {
638
- const line = this.buffer.slice(0, nl).trim()
639
- this.buffer = this.buffer.slice(nl + 1)
640
- if (line === '') continue
641
- let msg: { id?: number; op?: string; token?: string; ok?: boolean; result?: unknown; err?: string; action?: unknown; windowId?: unknown }
642
- try {
643
- msg = JSON.parse(line) as typeof msg
644
- } catch {
645
- // Non-protocol line; ignore.
646
- continue
647
- }
648
- if (msg.op === 'userAction' || msg.op === 'viewClosed') {
649
- // A fire-and-forget notification from the child's own UI (toolbar). These carry no
650
- // reply and no pending id, and they hand the provider a session-level verb — so they
651
- // are dispatched ONLY once the peer has proved it knows the spawn token.
652
- //
653
- // They used to be handled before the hello check, while the module comment claimed an
654
- // unauthenticated peer "is disconnected immediately … a spoofed socket never sees
655
- // traffic". Both were wrong: any loopback process that won the race for the single
656
- // accepted socket could inject `viewClosed` and end the human's browser session
657
- // before the token check rejected it. Only the loopback interface can connect, so
658
- // this is a same-machine race rather than a remote attack — which is exactly the
659
- // kind of thing the token exists to close.
660
- if (this.awaitingHello) {
661
- this.awaitingHello = false
662
- this.clearHelloTimer()
663
- this.socket?.destroy()
664
- this.fail(new Error('dsh-builtin-browser: browser host sent a notification before authenticating'))
665
- return
666
- }
667
- if (msg.op === 'userAction') {
668
- // Route it straight to the host's user-action handler (which the provider registered).
669
- this.onUserAction?.(msg.action as BrowserUserAction)
670
- } else {
671
- // The human closed the window, so the interface that session showed is gone. The
672
- // provider decides what that ends — browsing history and login state survive on
673
- // disk, only the session itself does not.
674
- this.onViewClosed?.(typeof msg.windowId === 'string' ? msg.windowId : '')
675
- }
676
- continue
677
- }
678
- if (this.awaitingHello) {
679
- // The FIRST line must be the child's hello carrying the spawn token.
680
- // Anything else (or a wrong token) means a spoofed connection: drop
681
- // it and fail every pending call rather than trust the line.
682
- this.awaitingHello = false
683
- this.clearHelloTimer()
684
- if (msg.op !== 'hello' || msg.token !== this.token) {
685
- this.socket?.destroy()
686
- this.fail(new Error('dsh-builtin-browser: browser host authentication failed'))
687
- return
688
- }
689
- this.connected = true
690
- // Flush anything queued while disconnected — now that the peer is
691
- // authenticated, it is safe to send commands.
692
- if (this.outbox.length > 0) {
693
- for (const line of this.outbox) this.socket?.write(line + '\n')
694
- this.outbox = []
695
- }
696
- continue
697
- }
698
- if (typeof msg.id !== 'number') continue
699
- const pending = this.pending.get(msg.id)
700
- if (pending === undefined) continue
701
- this.pending.delete(msg.id)
702
- if (msg.ok === true) pending.resolve(msg.result)
703
- else pending.reject(new Error(msg.err ?? 'browser host command failed'))
704
- }
705
- }
706
-
707
- /** Send one command and await the reply. */
708
- call<T = unknown>(op: string, payload: Record<string, unknown> = {}): Promise<T> {
709
- if (this.dead) {
710
- return Promise.reject(new HostGoneError('dsh-builtin-browser: browser host is not running'))
711
- }
712
- const id = this.nextId++
713
- const line = JSON.stringify({ id, op, ...payload })
714
- return new Promise<T>((resolve, reject) => {
715
- this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject })
716
- if (this.connected && this.socket !== undefined) {
717
- try {
718
- this.socket.write(line + '\n')
719
- } catch {
720
- // The socket died between the dead check and the write; the 'close'
721
- // handler fails the rest. Reject THIS call as host-gone so the
722
- // caller can recover immediately instead of hanging.
723
- this.pending.delete(id)
724
- reject(new HostGoneError('dsh-builtin-browser: browser host connection closed'))
725
- }
726
- } else {
727
- // Not connected yet: queue; attach() flushes on the child's arrival.
728
- this.outbox.push(line)
729
- }
730
- })
731
- }
732
-
733
- /**
734
- * How long the child gets to exit by itself after the socket closes, before it is killed.
735
- * The child quits on that signal, so in practice this is a few dozen milliseconds; the timer
736
- * exists for the case where it does not, and it is deliberately NOT unref'd — the parent must
737
- * stay alive long enough to enforce it, or the escalation would be dropped with the process.
738
- */
739
- private static readonly KILL_GRACE_MS = 500
740
- private killGraceTimer: NodeJS.Timeout | undefined
741
-
742
- /**
743
- * Terminate the child, after giving it the chance to shut down properly.
744
- *
745
- * The socket goes first, because that is the signal the child actually handles: its `close`
746
- * listener quits the app, and a normal quit is what lets Chromium write its profile out. Only
747
- * a child still alive after the grace period is killed outright.
748
- *
749
- * This order used to be the other way round, justified by a comment claiming the child's own
750
- * path "closes its window and flushes the profile", which made killing first the safer order.
751
- * Both halves of that were wrong: the path ran `app.exit(0)`, which skips before-quit/will-quit
752
- * and does not flush Chromium's profile writers at all; and on Windows `child.kill()` is
753
- * TerminateProcess, which lands before the child can run any handler whatsoever. So the
754
- * graceful path that comment was protecting never got to start, and the profile went
755
- * unflushed on every single dispose.
756
- */
757
- kill(): void {
758
- this.clearHelloTimer()
759
- try { this.socket?.destroy() } catch { /* already closed */ }
760
- const child = this.child
761
- this.clearKillGrace()
762
- this.killGraceTimer = setTimeout(() => {
763
- try { child.kill() } catch { /* already gone */ }
764
- }, ElectronChildClient.KILL_GRACE_MS)
765
- }
766
- }
767
-
768
- /** One view in the child: its id, used for every command. */
769
- class RemoteView implements ElectronViewHandle {
770
- constructor(readonly id: string, private readonly client: ElectronChildClient) {}
771
-
772
- sendCommand(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>> {
773
- return this.client.call<Record<string, unknown>>('command', {
774
- viewId: this.id,
775
- method,
776
- params: params ?? {},
777
- })
778
- }
779
-
780
- /** Give this view web focus in the child, so keyboard input reaches the page. */
781
- focus(options?: PresentOptions): Promise<void> {
782
- return this.client.call<void>('focus', { viewId: this.id, ...options?.quiet ? { quiet: true } : {} })
783
- }
784
-
785
- /** Ask the child to download a URL to a local file (keeps cookies/login). */
786
- async download(url: string, savePath: string): Promise<void> {
787
- // The child writes the file itself (temp + rename); only a small
788
- // confirmation crosses the RPC, so large downloads never balloon the
789
- // parent's memory or hit the single-line cap.
790
- await this.client.call<{ path: string }>('download', { viewId: this.id, url, savePath })
791
- }
792
-
793
- /** Native capturePage snapshot of the view (base64 + mime). */
794
- capture(opts?: ScreenshotOptions): Promise<{ base64: string; mime: string }> {
795
- return this.client.call<{ base64: string; mime: string }>('capture', { viewId: this.id, ...opts ?? {} })
796
- }
797
-
798
- /** Export the session's cookies (login state). */
799
- flushAuth(): Promise<ExportedCookie[]> {
800
- return this.client.call<{ cookies: ExportedCookie[] }>('flushAuth', { viewId: this.id }).then(r => r.cookies)
801
- }
802
-
803
- /** Import cookies into the session (restore login state). */
804
- restoreAuth(cookies: ExportedCookie[]): Promise<number> {
805
- return this.client.call<{ restored: number }>('restoreAuth', { viewId: this.id, cookies }).then(r => r.restored)
806
- }
807
- }
808
-
809
- /**
810
- * How long a FAILED Electron-binary probe is remembered before the binary
811
- * search runs again (`available()`). A success is kept for the host's lifetime.
812
- */
813
- const PROBE_RETRY_MS = (() => {
814
- const raw = Number(process.env.DSH_BROWSER_PROBE_RETRY_MS)
815
- return Number.isFinite(raw) && raw >= 0 ? raw : 30000
816
- })()
817
-
818
- /**
819
- * Retry schedule for a browser host that will not stay up, in milliseconds, indexed by the
820
- * number of consecutive failed starts (see {@link RemoteElectronViewHost.noteStartFailure}).
821
- *
822
- * The first entry is 0 on purpose: an ordinary one-off death must still heal on the very
823
- * next call, which is the behaviour remote-host-recovery.test.mjs pins. From the second
824
- * failure on, each attempt is spaced. `available()` can only answer "is there a binary",
825
- * so a binary that exists and crashes on every launch (`code=1` with empty stderr) would
826
- * otherwise produce an endless crash loop, one window per tool call, with nothing to make
827
- * it stop.
828
- */
829
- const START_RETRY_SCHEDULE_MS: readonly number[] = [0, 500, 2_000, 8_000, 30_000]
830
-
831
- /** Attempts after which the host stops retrying immediately and keeps the longest delay. */
832
- const START_FAILURES_MAX = START_RETRY_SCHEDULE_MS.length
833
-
834
- /** Two reports within this window describe the same dying child, not two attempts. */
835
- const START_FAILURE_DEDUPE_MS = 1_000
836
-
837
- /** Render a delay for a human-readable log line. */
838
- function formatDelay(ms: number): string {
839
- return ms >= 1_000 ? `${(ms / 1_000).toFixed(1)}s` : `${String(ms)}ms`
840
- }
841
-
842
- /**
843
- * Self-hosted view host: spawns the plugin's Electron child on first use and
844
- * keeps it alive until dispose(). Fallback when no desktop shell provides
845
- * ctx.electronViewHost.
846
- */
847
- export class RemoteElectronViewHost implements ElectronBrowserViewHost {
848
- private client: ElectronChildClient | undefined
849
- private server: Server | undefined
850
- private pendingSocket: Socket | undefined
851
- private readonly views = new Map<string, ElectronViewHandle>()
852
- private readyPromise: Promise<void> | undefined
853
- private disposed = false
854
- /** Last probe result. A success is kept for the host's lifetime; a failure
855
- * is retried after `PROBE_RETRY_MS` (see `available()`). */
856
- private electronAvailable: boolean | undefined
857
- /** Earliest time the next probe may run after a negative one. */
858
- private nextProbeAt = 0
859
- /** Consecutive child starts that did not survive; drives {@link startRetryAt}. */
860
- private startFailures = 0
861
- /** Earliest time `ready()` may spawn another child after a failed start. */
862
- private startRetryAt: number | undefined
863
- /** When the last start failure was reported, used to keep one death to one log line. */
864
- private lastStartFailureAt = 0
865
- /** Window groups (windowId per view), re-sent on every materialization so
866
- * a restarted child still places views in the right windows. */
867
- private readonly groups = new Map<string, { windowId: string; label?: string }>()
868
- /** The provider's user-action handler; routes toolbar actions into sessions. */
869
- private userActionHandler: ((action: BrowserUserAction) => void) | undefined
870
- /**
871
- * The provider's handler for a window the human closed. Closing the interface
872
- * ends the session it showed: history and login state stay on disk, so the
873
- * next open starts clean instead of resuming a window nobody can see.
874
- */
875
- private viewClosedHandler: ((windowId: string) => void) | undefined
876
-
877
- constructor(
878
- private readonly hostMainPath: string,
879
- /** Test seam: the executable to spawn instead of the resolved Electron
880
- * binary. Absent -> resolveElectronPath() (production behavior). */
881
- private readonly spawnExecutable?: string,
882
- /** Test seam: the binary probe behind `available()`. Absent ->
883
- * resolveElectronPath(). */
884
- private readonly probe: () => void = resolveElectronPath,
885
- ) {}
886
-
887
- /**
888
- * Cheap usability probe: can we find an Electron binary to spawn? The scan
889
- * is filesystem-only (no network), per the seam's contract, so a missing
890
- * binary surfaces as `BROWSER_PROVIDER_UNAVAILABLE` at provider selection
891
- * instead of a confusing spawn failure on first use.
892
- *
893
- * A success is cached for the host's lifetime. A failure is NOT: an install
894
- * (`npm i electron`, or the postinstall that fetches the binary) can land
895
- * long after DSH started, and provider selection happens once per process —
896
- * caching "no" permanently reported "no usable browser provider is
897
- * registered" until DSH restarted, with no way back short of that. Retrying
898
- * on a cooldown heals it by itself while keeping the scan off the hot path.
899
- */
900
- available(): boolean {
901
- if (this.electronAvailable === true) return true
902
- if (Date.now() < this.nextProbeAt) return false
903
- this.nextProbeAt = Date.now() + PROBE_RETRY_MS
904
- try {
905
- this.probe()
906
- this.electronAvailable = true
907
- } catch (error) {
908
- this.electronAvailable = false
909
- // The provider will be reported unavailable, so the detailed
910
- // resolution error (install-electron / ELECTRON_PATH guidance) would
911
- // otherwise never reach the user — surface it on stderr.
912
- process.stderr.write(`[dsh-browser host] electron unavailable: ${error instanceof Error ? error.message : String(error)}\n`)
913
- }
914
- return this.electronAvailable
915
- }
916
-
917
- /**
918
- * Retire the cached "an Electron binary is here" answer.
919
- *
920
- * A success is cached for the host's lifetime because rescanning on every tool call was
921
- * the original bug — but the probe reads the FILESYSTEM, so it cannot see a binary that
922
- * stops being usable afterwards. Only a real spawn attempt can observe that, which is why
923
- * the two failure paths in {@link RemoteElectronViewHost.start} call this: the next
924
- * `available()` rescans and reports what is actually on disk, instead of advertising a
925
- * provider that cannot start.
926
- */
927
- private forgetBinary(): void {
928
- this.electronAvailable = undefined
929
- this.nextProbeAt = 0
930
- }
931
-
932
- /**
933
- * Whether the binary the host would spawn — or the entry it needs — is no longer there.
934
- *
935
- * Only asked after a launch actually failed, so a healthy path never pays for it. The
936
- * entry script counts because Electron exits 1 with empty stderr when it cannot load it,
937
- * and resolution itself throws exactly when it can find nothing, which is the same answer.
938
- * @returns true when the next `available()` must rescan instead of reusing its cache.
939
- */
940
- private binaryIsGone(): boolean {
941
- if (!existsSync(this.hostMainPath)) return true
942
- try {
943
- return !existsSync(this.spawnExecutable ?? resolveElectronPath())
944
- } catch {
945
- return true
946
- }
947
- }
948
-
949
- /**
950
- * Ensure the child is up and ready (lazy on first use; restarts after a crash).
951
- *
952
- * Never throws synchronously. Callers are fire-and-forget
953
- * (`void this.ready().then(…).catch(…)`), and a synchronous throw escapes their
954
- * `.catch` entirely — the shape that let a failed toolbar report take the whole
955
- * DSH host down (issue #16). A disposed host is reported as a rejected promise
956
- * instead, which those callers already handle.
957
- */
958
- private ready(): Promise<void> {
959
- // Fail fast on a disposed host: a recovery path can re-enter ready() after
960
- // dispose() cleared its state, and starting fresh here would spawn a child
961
- // nobody will ever kill.
962
- if (this.disposed) {
963
- const gone = Promise.reject(new HostGoneError('browser host disposed'))
964
- // Keep the rejection observable to callers while marking it handled here:
965
- // a fire-and-forget caller that forgot to attach a handler must not turn
966
- // this into an unhandled rejection either.
967
- gone.catch(() => undefined)
968
- return gone
969
- }
970
- if (this.readyPromise !== undefined) return this.readyPromise
971
- // Backoff gate for a host that keeps failing to START (see START_RETRY_SCHEDULE_MS).
972
- // The client is undefined exactly when the previous child is gone — a start failure, or
973
- // a child that died after it came up — so this only delays restarts, never first use.
974
- const retryAt = this.startRetryAt
975
- if (retryAt !== undefined && Date.now() < retryAt && this.client === undefined) {
976
- const waitMs = retryAt - Date.now()
977
- const waiting = Promise.reject(new HostGoneError(
978
- `browser host did not start; retrying in ${formatDelay(waitMs)} `
979
- + `(attempt ${String(this.startFailures)}${this.startFailures >= START_FAILURES_MAX ? ', start attempts are now spaced out rather than immediate' : ''})`,
980
- ))
981
- // Keep the rejection observable to callers while marking it handled here: the
982
- // fire-and-forget callers that drive this path attach their own handler, but one that
983
- // forgets must not turn the recovery gate into an unhandled rejection.
984
- waiting.catch(() => undefined)
985
- return waiting
986
- }
987
- const started = this.start()
988
- const wrapped = started.then(
989
- () => {
990
- // A child that came up clears the record: the next death is a new failure, not
991
- // another entry in this run of them.
992
- this.startFailures = 0
993
- this.startRetryAt = undefined
994
- },
995
- error => {
996
- // Record the failure BEFORE tearing anything down, and gate the teardown on the
997
- // retry state being gone rather than on readyPromise alone. Ordering matters: a
998
- // child that exits while the readiness call is still in flight fires the client's
999
- // 'exit' handler first (onChildExit invalidates this promise and starts the retry
1000
- // clock), and the rejection then lands here — at which point clearing startRetryAt
1001
- // would erase the very backoff that was just armed, so every tool call spawned
1002
- // another dying child. noteStartFailure's dedupe window counts that pair once.
1003
- this.noteStartFailure(error)
1004
- // A failed startup must not poison the host forever: tear down whatever
1005
- // was half-created and let the next call retry from scratch.
1006
- if (this.readyPromise === wrapped) {
1007
- this.readyPromise = undefined
1008
- this.client?.kill()
1009
- this.client = undefined
1010
- this.server?.close()
1011
- this.server = undefined
1012
- this.pendingSocket?.destroy()
1013
- this.pendingSocket = undefined
1014
- }
1015
- throw error
1016
- },
1017
- )
1018
- this.readyPromise = wrapped
1019
- return wrapped
1020
- }
1021
-
1022
- /**
1023
- * Record one child that did not survive, and set the earliest retry time.
1024
- *
1025
- * `available()` answers "is there a binary to spawn" from the FILESYSTEM, and a success
1026
- * there is cached for the host's lifetime (correctly — rescanning on every tool call was
1027
- * the bug). That probe therefore cannot see the failure mode where the binary exists and
1028
- * crashes on every launch: the signature `code=1` with empty stderr that host-log.test.mjs
1029
- * asserts. Each browser call then spawned a child that died within milliseconds, with no
1030
- * backoff and nothing that ever gives up — an endless crash loop, each iteration a window
1031
- * flashing on screen.
1032
- *
1033
- * The first retry is immediate, so the ordinary transient death (the DSH restart in
1034
- * remote-host-recovery.test.mjs) still heals on the very next call. After that the delay
1035
- * grows: once {@link START_FAILURES_MAX} attempts have failed, every later attempt is
1036
- * spaced by the table's last entry — the host keeps trying, but a permanently broken
1037
- * install now costs one spawn per 30s instead of one per tool call. Nothing is marked
1038
- * dead for good: a repaired installation heals on the next attempt, and `dispose()`
1039
- * still stops everything immediately.
1040
- * @param error - what the failed attempt reported.
1041
- */
1042
- private noteStartFailure(error: unknown): void {
1043
- // The same death arrives twice: the child's exit reports it, and ready() rejecting
1044
- // reports it again. Counting both pushed the first retry to the 500ms step and made
1045
- // the log say "attempt 2" for a first failure, while START_RETRY_SCHEDULE_MS[0] = 0
1046
- // exists precisely so an ordinary death heals on the next call. So a report inside the
1047
- // window is dropped ENTIRELY — the count and the log line alike.
1048
- //
1049
- // That last part used to be split in two: the guard below, and a second dedupe that only
1050
- // suppressed the LOG. The second one read `now - this.lastStartFailureAt` after the line
1051
- // above had already stored `failureAt` into that same field, so its window was 0-1ms wide
1052
- // and the comparison was unconditionally true — the log line was never written at all.
1053
- // Nothing noticed, because this function exists to make a silent failure visible and its
1054
- // only output was the thing being dropped: a child that exists and dies instantly (code=1,
1055
- // empty stderr) left no trace anywhere.
1056
- const failureAt = Date.now()
1057
- if (this.lastStartFailureAt !== undefined && failureAt - this.lastStartFailureAt < START_FAILURE_DEDUPE_MS) return
1058
- this.lastStartFailureAt = failureAt
1059
- this.startFailures += 1
1060
- const index = Math.min(this.startFailures, START_RETRY_SCHEDULE_MS.length) - 1
1061
- const delayMs = START_RETRY_SCHEDULE_MS[index] ?? 0
1062
- this.startRetryAt = delayMs > 0 ? failureAt + delayMs : undefined
1063
- const line = `${hostStamp()} browser host start failed (attempt ${String(this.startFailures)}`
1064
- + `${this.startFailures >= START_FAILURES_MAX ? ', giving up on immediate retries' : ''}): ${String(error)}`
1065
- + `${delayMs > 0 ? ` — next attempt in ${formatDelay(delayMs)}` : ''}`
1066
- process.stderr.write(`[dsh-browser host] ${line}\n`)
1067
- appendHostLog(`${line}\n`)
1068
- }
1069
-
1070
- private async start(): Promise<void> {
1071
- // Listen on an ephemeral loopback port; the child connects back. The
1072
- // server accepts exactly one connection: the child's. Any further
1073
- // connection (a local process probing the port) is destroyed at once.
1074
- const server = createServer(socket => {
1075
- if (this.client !== undefined && this.client.isAttached()) {
1076
- // A live child connection already exists — reject the extra one.
1077
- socket.destroy()
1078
- return
1079
- }
1080
- if (this.client !== undefined) {
1081
- // The child's first connection arrived after the client was created.
1082
- this.client.attach(socket)
1083
- return
1084
- }
1085
- if (this.pendingSocket !== undefined) {
1086
- // Only one connection may wait for the client; drop the older one.
1087
- this.pendingSocket.destroy()
1088
- }
1089
- this.pendingSocket = socket
1090
- })
1091
- await new Promise<void>((resolve, reject) => {
1092
- server.once('error', reject)
1093
- server.listen(0, LOOPBACK_IPV4, () => resolve())
1094
- })
1095
- // A later server error (rare on a loopback ephemeral port) must not crash
1096
- // the process; the client's fail path handles the actual recovery.
1097
- server.on('error', error => {
1098
- process.stderr.write(`[dsh-browser host] rpc server error: ${String(error)}\n`)
1099
- })
1100
- const address = server.address()
1101
- const port = typeof address === 'object' && address !== null ? address.port : 0
1102
- this.server = server
1103
- // Random per-spawn token: the child must prove knowledge of it (via
1104
- // stdin hello) before any command is written to the socket.
1105
- const token = randomBytes(24).toString('hex')
1106
- this.client = new ElectronChildClient(
1107
- this.hostMainPath,
1108
- port,
1109
- token,
1110
- () => this.onChildExit(),
1111
- action => this.userActionHandler?.(action),
1112
- windowId => this.viewClosedHandler?.(windowId),
1113
- this.spawnExecutable,
1114
- )
1115
- if (this.pendingSocket !== undefined) {
1116
- this.client.attach(this.pendingSocket)
1117
- this.pendingSocket = undefined
1118
- }
1119
- // dispose() can race this spawn (it may run while start() is suspended
1120
- // between the listen and the client creation): re-check here so a host
1121
- // that was torn down mid-start does not leak a child nobody will kill.
1122
- if (this.disposed) {
1123
- this.client.kill()
1124
- this.client = undefined
1125
- try { server.close() } catch { /* already closed */ }
1126
- if (this.server === server) this.server = undefined
1127
- throw new HostGoneError('browser host disposed')
1128
- }
1129
- // Wait for the child's connection + authentication + readiness ping. The
1130
- // ping is queued until the hello authenticates, so a spoofed socket
1131
- // never observes it.
1132
- await withTimeout(this.client.call('ping'), READY_TIMEOUT_MS, 'browser host did not become ready')
1133
- }
1134
-
1135
- /** The child died: tear down so the next use starts a fresh child. */
1136
- private onChildExit(): void {
1137
- // A disposed host still has to drop these: returning here left a child that had
1138
- // already been replaced during a dispose race in no map at all, so nothing would
1139
- // ever kill it. Only the restart is suppressed, not the cleanup.
1140
- const wasDisposed = this.disposed
1141
- if (!wasDisposed) process.stderr.write('[dsh-browser host] browser host gone; will restart on next use\n')
1142
- // A child that started and then died is also a failed start, and it is the shape a crash
1143
- // loop takes (the child comes up far enough to be pending on `ping`, then exits): count
1144
- // it so the restart is spaced instead of attempted on every single tool call.
1145
- if (!wasDisposed) this.noteStartFailure('the browser host process exited')
1146
- // The cached `available()` answer came from the FILESYSTEM, so only a real attempt can
1147
- // contradict it. A binary that stops being usable after the probe said yes — an
1148
- // interrupted reinstall, a removed mount, a wiped cache — kept the provider advertised
1149
- // as available for the rest of the process's life, because provider selection reads
1150
- // that same cached yes; every later call then paid a doomed spawn. Both failure routes
1151
- // (a spawn error, and a child that exits) arrive here, so this is the one place that
1152
- // observes the loss, and it costs two stats on a path that is already failing.
1153
- if (this.binaryIsGone()) this.forgetBinary()
1154
- this.client = undefined
1155
- this.server?.close()
1156
- this.server = undefined
1157
- this.pendingSocket?.destroy()
1158
- this.pendingSocket = undefined
1159
- this.readyPromise = undefined
1160
- // Keep the views map: handles still resolve to ids, and
1161
- // DeferredRemoteView re-materializes them against the fresh child on
1162
- // their next use — sessions opened before the crash stay usable instead
1163
- // of going stale (only the page state is lost).
1164
- }
1165
-
1166
- createView(identity?: BrowserTabWireId): ElectronViewHandle {
1167
- // The seam is synchronous; the provider uses the handle immediately, so
1168
- // commands are deferred until the child is up and the view materialized.
1169
- const id = identity ?? tabWireId({ owner: 'standalone', session: randomUUID(), tab: randomUUID() })
1170
- readTabHandle(id)
1171
- const view = new DeferredRemoteView(id, () => this.ensureView(id))
1172
- this.views.set(id, view)
1173
- return view
1174
- }
1175
-
1176
- private async ensureView(id: string): Promise<RemoteView> {
1177
- // A rebuild in flight during dispose() must not spawn a fresh child that
1178
- // would then outlive the host (a zombie window nobody disposes).
1179
- if (this.disposed) throw new HostGoneError('browser host disposed')
1180
- await this.ready()
1181
- // dispose() may have landed while the host was starting (ready() resolved
1182
- // after dispose cleared its state): never materialize into a dead host.
1183
- if (this.disposed) throw new HostGoneError('browser host disposed')
1184
- const client = this.client
1185
- if (client === undefined) throw new HostGoneError('browser host unavailable')
1186
- // Re-send the window group before creating the view: the child routes the
1187
- // view into its session's own window. Re-sending every materialization
1188
- // also covers a child restart (the new child has no assignments yet).
1189
- const group = this.groups.get(id)
1190
- if (group !== undefined) {
1191
- await client.call('groupView', { viewId: id, windowId: group.windowId, ...group.label !== undefined ? { label: group.label } : {} })
1192
- }
1193
- await client.call('createView', { viewId: id })
1194
- // If the view was destroyed while the createView RPC was in flight, do
1195
- // not re-insert a stale entry that would resurrect a dead child view.
1196
- if (this.views.get(id) === undefined) {
1197
- throw new Error('browser: view destroyed while starting')
1198
- }
1199
- const view = new RemoteView(id, client)
1200
- this.views.set(id, view)
1201
- return view
1202
- }
1203
-
1204
- showView(handle: ElectronViewHandle, label?: string, options?: PresentOptions): void {
1205
- // Fire-and-forget by design (visibility is best-effort), but a rejected
1206
- // promise must not become an unhandled rejection (crash on Node >= 15).
1207
- // The label (session/task id) rides along so the child can show it in the
1208
- // window title — a human can then tell which task's page is visible.
1209
- // `quiet` is only sent when it is on: the child's default is the documented
1210
- // "present and raise" behaviour, so an old child keeps working either way.
1211
- void this.ready()
1212
- .then(() => this.client?.call('showView', {
1213
- viewId: handle.id,
1214
- ...label !== undefined ? { label } : {},
1215
- ...options?.quiet === true ? { quiet: true } : {},
1216
- }))
1217
- .catch(() => { /* host unavailable */ })
1218
- }
1219
-
1220
- /**
1221
- * (Re)present a view and WAIT for the child to confirm it, so the provider
1222
- * can dispatch CDP `Input.*` knowing the view has a display surface.
1223
- *
1224
- * Two things this fixes, both silent before:
1225
- * - showing a view that does not exist yet is a no-op in the child, so the
1226
- * view must be materialized first (a fresh tab's createView races the
1227
- * provider's showActive);
1228
- * - a view whose renderer was replaced by a navigation is \"already\n * visible\" and therefore skipped by the child's flicker-avoidance fast
1229
- * path, leaving the new renderer without a surface.
1230
- *
1231
- * The barrier ping is meaningful because the child handles messages strictly
1232
- * in order: its reply is queued behind the showView and so only arrives once
1233
- * the visibility change has been applied.
1234
- */
1235
- async presentView(handle: ElectronViewHandle, label?: string, options?: PresentOptions): Promise<void> {
1236
- await this.ready()
1237
- const client = this.client
1238
- if (client === undefined) throw new HostGoneError('browser host unavailable')
1239
- // A view created after the last createView does not exist in the child yet.
1240
- // ensureMaterialized also rebuilds it against a fresh child after a host
1241
- // death, which is the path that used to leave sessions timing out forever.
1242
- if (handle instanceof DeferredRemoteView) {
1243
- await withTimeout(handle.ensureMaterialized(), PRESENT_TIMEOUT_MS, 'browser host did not materialize the view')
1244
- }
1245
- await withTimeout(
1246
- client.call('showView', {
1247
- viewId: handle.id,
1248
- ...label !== undefined ? { label } : {},
1249
- // `needSurface` tells the child this is the pre-input barrier: under quiet mode this
1250
- // is the only presentation allowed to un-minimize a window, because Chromium drops
1251
- // `Input.*` without a display surface. One line below in the child, and only read
1252
- // there when `quiet` is set.
1253
- ...options?.quiet === true ? { quiet: true, needSurface: true } : {},
1254
- }),
1255
- PRESENT_TIMEOUT_MS,
1256
- 'browser host did not confirm the view presentation',
1257
- )
1258
- await withTimeout(client.call('ping'), PRESENT_TIMEOUT_MS, 'browser host stopped answering')
1259
- }
1260
-
1261
- /** Route a view into its session's own window (one window per session). */
1262
- groupView(handle: ElectronViewHandle, windowId: string, label?: string): void {
1263
- this.groups.set(handle.id, { windowId, ...label !== undefined ? { label } : {} })
1264
- // Fire-and-forget: the child may not exist yet; ensureView re-sends the
1265
- // group before every createView anyway.
1266
- void this.ready()
1267
- .then(() => this.client?.call('groupView', { viewId: handle.id, windowId, ...label !== undefined ? { label } : {} }))
1268
- .catch(() => { /* host unavailable */ })
1269
- }
1270
-
1271
- /** Register the provider's handler for user-initiated toolbar actions. */
1272
- onUserAction(handler: (action: BrowserUserAction) => void): void {
1273
- this.userActionHandler = handler
1274
- }
1275
-
1276
- /** Register the provider's handler for windows the human closed. */
1277
- onViewClosed(handler: (windowId: string) => void): void {
1278
- this.viewClosedHandler = handler
1279
- }
1280
-
1281
- /** Surface a failed user action to the child's toolbar (address bar etc.). */
1282
- notifyUserActionError(windowId: string, message: string): void {
1283
- void this.ready()
1284
- .then(() => this.client?.call('userActionError', { windowId, message }))
1285
- .catch(() => { /* host unavailable */ })
1286
- }
1287
-
1288
- destroyView(handle: ElectronViewHandle): void {
1289
- const view = this.views.get(handle.id)
1290
- if (view === undefined) return
1291
- this.views.delete(handle.id)
1292
- void this.ready()
1293
- .then(() => this.client?.call('destroyView', { viewId: handle.id }))
1294
- .catch(() => { /* child already gone */ })
1295
- }
1296
-
1297
- /** Shut the child and the RPC server down. */
1298
- dispose(): void {
1299
- this.disposed = true
1300
- this.client?.kill()
1301
- this.client = undefined
1302
- this.server?.close()
1303
- this.server = undefined
1304
- this.pendingSocket?.destroy()
1305
- this.pendingSocket = undefined
1306
- this.readyPromise = undefined
1307
- this.views.clear()
1308
- }
1309
- }
1310
-
1311
- /** A view handle that waits for child readiness before issuing commands. */
1312
- class DeferredRemoteView implements ElectronViewHandle {
1313
- private materialized: Promise<RemoteView> | undefined
1314
-
1315
- constructor(
1316
- readonly id: string,
1317
- private readonly materialize: () => Promise<RemoteView>,
1318
- ) {}
1319
-
1320
- /**
1321
- * Materialize once and cache: every operation on the same handle must
1322
- * target the SAME child view (re-materializing would re-run createView and
1323
- * duplicate the window). A FAILED materialization is reset so a later call
1324
- * (e.g. after the host restarted) can retry instead of being poisoned.
1325
- */
1326
- private materializeOnce(): Promise<RemoteView> {
1327
- if (this.materialized === undefined) {
1328
- const pending = this.materialize()
1329
- // Compare against the promise actually stored — the derived one — not against `pending`.
1330
- // Storing `pending.catch(...)` and comparing `this.materialized === pending` compared two
1331
- // different objects, so the test was never true and the reset never ran: a materialization
1332
- // that failed with anything other than a HostGoneError (the child alive but not answering
1333
- // a ping, say) poisoned the handle for good, and the retry the comment below promises was
1334
- // unreachable.
1335
- const guarded = pending.catch(error => {
1336
- if (this.materialized === guarded) this.materialized = undefined
1337
- throw error
1338
- })
1339
- this.materialized = guarded
1340
- }
1341
- return this.materialized
1342
- }
1343
-
1344
- /**
1345
- * Run one operation against this view's backing child, automatically
1346
- * recovering from a dead host. The cached materialization is bound to the
1347
- * child it was created on; once that child is gone (exited, crashed, or its
1348
- * connection dropped — e.g. the DSH process that spawned it was restarted),
1349
- * any further operation on the same handle would otherwise fail forever
1350
- * with "browser host is not running". Instead: drop the cache, rebuild the
1351
- * view against a freshly spawned child, and retry the operation exactly
1352
- * once — so sessions that survive a host death self-heal on their FIRST
1353
- * call after it, without a manual dsh_browser_reset_session. Page-level errors
1354
- * are never retried (the view itself is fine).
1355
- */
1356
- private async withRecovery<T>(op: (view: RemoteView) => Promise<T>): Promise<T> {
1357
- try {
1358
- const view = await this.materializeOnce()
1359
- return await op(view)
1360
- } catch (error) {
1361
- if (!(error instanceof HostGoneError)) throw error
1362
- // The backing child is gone: a retry on the same materialization can
1363
- // never succeed. Rebuild against a fresh child and retry once; a second
1364
- // failure (fresh host also failing to start) surfaces to the caller.
1365
- this.materialized = undefined
1366
- const fresh = await this.materializeOnce()
1367
- return op(fresh)
1368
- }
1369
- }
1370
-
1371
- async sendCommand(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>> {
1372
- return this.withRecovery(view => view.sendCommand(method, params))
1373
- }
1374
-
1375
- async download(url: string, savePath: string): Promise<void> {
1376
- return this.withRecovery(view => view.download(url, savePath))
1377
- }
1378
-
1379
- async capture(opts?: ScreenshotOptions): Promise<{ base64: string; mime: string }> {
1380
- return this.withRecovery(view => view.capture(opts))
1381
- }
1382
-
1383
- async focus(options?: PresentOptions): Promise<void> {
1384
- return this.withRecovery(view => view.focus(options))
1385
- }
1386
-
1387
- async flushAuth(): Promise<ExportedCookie[]> {
1388
- return this.withRecovery(view => view.flushAuth())
1389
- }
1390
-
1391
- async restoreAuth(cookies: ExportedCookie[]): Promise<number> {
1392
- return this.withRecovery(view => view.restoreAuth(cookies))
1393
- }
1394
-
1395
- /** Materialize this view in the child (no-op when already there). */
1396
- async ensureMaterialized(): Promise<void> {
1397
- await this.withRecovery(async () => undefined)
1398
- }
1399
- }
1400
-
1401
- /**
1402
- * Append one host-diagnostics chunk to `$DSH_HOME/logs/dsh-builtin-browser-host.log`.
1403
- * Best-effort and self-limiting: diagnostics must never break the host or grow
1404
- * without bound, so failures are swallowed and the file is truncated when it
1405
- * gets large (a crash loop writes quickly).
1406
- */
1407
- const HOST_LOG_MAX_BYTES = 2 * 1024 * 1024
1408
-
1409
- /**
1410
- * ISO timestamp prefix for host-log lines. This log is the only place a spawn
1411
- * failure is recorded, and an undated line cannot be lined up with anything else
1412
- * that happened on the machine — a plugin update replacing the entry script, for
1413
- * instance — which is precisely the question this log gets asked.
1414
- */
1415
- function hostStamp(): string {
1416
- return new Date().toISOString()
1417
- }
1418
-
1419
- function appendHostLog(text: string): void {
1420
- try {
1421
- const file = browserHostLogPath()
1422
- const dir = dirname(file)
1423
- try {
1424
- if (statSync(file).size > HOST_LOG_MAX_BYTES) {
1425
- // Discard the old bytes but leave a dated marker: truncating to empty
1426
- // makes a rotation look like "nothing ever happened", which is how the
1427
- // history of a crash loop gets silently swallowed.
1428
- writeFileSync(file, `${hostStamp()} log rotated: previous content exceeded ${String(HOST_LOG_MAX_BYTES)} bytes and was discarded\n`)
1429
- }
1430
- } catch {
1431
- // No readable file yet: the log directory may not exist. When statSync
1432
- // succeeded the file exists, so its directory does too and creating it
1433
- // again was a redundant syscall on every child stdout/stderr line.
1434
- mkdirSync(dir, { recursive: true })
1435
- }
1436
- appendFileSync(file, text)
1437
- } catch { /* diagnostics are best-effort only */ }
1438
- }
1439
-
1440
- /** Reject a promise if it does not settle within the budget. */
1441
- function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
1442
- return withTimeoutShared(promise, ms, () => new Error(`${message} (${ms}ms)`))
1443
- }
1444
-
1445
- /** Default host-main path relative to this module's build output. */
1446
- export function defaultHostMainPath(): string {
1447
- return fileURLToPath(new URL('./host-main.js', import.meta.url))
1448
- }
1449
-
1450
- /**
1451
- * Test/diagnostic hooks (mirrors tool-browser's `internals` convention).
1452
- * `isBareElectron` is the packaged-app discriminator behind the host-reuse
1453
- * steps; `resolveElectronPath` is the full resolution order.
1454
- */
1455
- export const internals = {
1456
- electronDistCandidates,
1457
- electronDistExe,
1458
- electronExeBeside,
1459
- isBareElectron,
1460
- resolveElectronPath,
1461
- resolveElectronPathImpl,
1462
- }