dsh-builtin-browser 1.0.3 → 1.0.4

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 (293) hide show
  1. package/README.en.md +89 -0
  2. package/browser-extension/constants.mjs +20 -0
  3. package/browser-extension/controller.mjs +293 -0
  4. package/browser-extension/locales.mjs +15 -0
  5. package/browser-extension/manifest.json +12 -0
  6. package/browser-extension/options.html +14 -0
  7. package/browser-extension/options.mjs +9 -0
  8. package/browser-extension/permission-guard.mjs +13 -0
  9. package/browser-extension/worker.mjs +74 -0
  10. package/package.json +20 -2
  11. package/scripts/build-client.mjs +305 -0
  12. package/scripts/build.mjs +69 -0
  13. package/scripts/bundle-host.mjs +28 -0
  14. package/scripts/fix-exports.mjs +40 -0
  15. package/scripts/install-electron.mjs +101 -0
  16. package/scripts/pack.mjs +99 -0
  17. package/scripts/publish-manifest.mjs +56 -0
  18. package/scripts/verify-exports.mjs +58 -0
  19. package/scripts/verify-preview-sdk.mjs +93 -0
  20. package/skills/dsh-builtin-browser/SKILL.md +98 -0
  21. package/skills/dsh-builtin-browser/references/batch.md +68 -0
  22. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  23. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  24. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  25. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  26. package/skills/dsh-debug-host/SKILL.md +56 -0
  27. package/skills/dsh-debug-self/SKILL.md +50 -0
  28. package/src/bridge-compatibility.ts +39 -0
  29. package/src/browser/anti-bot.ts +251 -0
  30. package/src/browser/deep-dom.ts +40 -0
  31. package/src/browser/handles.ts +89 -0
  32. package/src/browser/runtime.ts +578 -0
  33. package/src/browser/takeover-target.ts +45 -0
  34. package/src/browser/types.ts +870 -0
  35. package/src/browser-electron/authenticated-route.ts +109 -0
  36. package/src/browser-electron/automatic-maintenance.ts +736 -0
  37. package/src/browser-electron/bridge-auto.ts +159 -0
  38. package/src/browser-electron/bridge-connection.ts +386 -0
  39. package/src/browser-electron/bridge-endpoint.ts +129 -0
  40. package/src/browser-electron/bridge-install.ts +290 -0
  41. package/src/browser-electron/bridge-maintenance.ts +189 -0
  42. package/src/browser-electron/bridge-status.ts +386 -0
  43. package/src/browser-electron/desktop-bridge-host.ts +253 -0
  44. package/src/browser-electron/desktop-identity.ts +353 -0
  45. package/src/browser-electron/desktop-shell.ts +100 -0
  46. package/src/browser-electron/document-readiness.ts +45 -0
  47. package/src/browser-electron/electron-provision.ts +347 -0
  48. package/src/browser-electron/entry.ts +1378 -0
  49. package/src/browser-electron/ephemeral-profile.ts +189 -0
  50. package/src/browser-electron/extension-browser.ts +230 -0
  51. package/src/browser-electron/extension-setup.ts +67 -0
  52. package/src/browser-electron/file-write.ts +31 -0
  53. package/src/browser-electron/foreground-watch.ts +142 -0
  54. package/src/browser-electron/guest-cookie-jar.ts +177 -0
  55. package/src/browser-electron/guest-cookie-store.ts +59 -0
  56. package/src/browser-electron/guest-css-runtime.ts +76 -0
  57. package/src/browser-electron/guest-css.ts +68 -0
  58. package/src/browser-electron/guest-route.ts +716 -0
  59. package/src/browser-electron/guest-runtime.ts +408 -0
  60. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  61. package/src/browser-electron/guest-storage.ts +120 -0
  62. package/src/browser-electron/history-store.ts +224 -0
  63. package/src/browser-electron/host-main.ts +1385 -0
  64. package/src/browser-electron/host-patch-maintenance.ts +121 -0
  65. package/src/browser-electron/http-body.ts +65 -0
  66. package/src/browser-electron/json-reply.ts +47 -0
  67. package/src/browser-electron/maintenance-broker.ts +166 -0
  68. package/src/browser-electron/maintenance-lifecycle.ts +91 -0
  69. package/src/browser-electron/maintenance-route.ts +68 -0
  70. package/src/browser-electron/missing-system-browser.ts +114 -0
  71. package/src/browser-electron/open-slot.ts +49 -0
  72. package/src/browser-electron/paths.ts +25 -0
  73. package/src/browser-electron/preferred-browser.ts +130 -0
  74. package/src/browser-electron/preview-route.ts +215 -0
  75. package/src/browser-electron/process-ownership.ts +174 -0
  76. package/src/browser-electron/process.ts +23 -0
  77. package/src/browser-electron/profile-checkpoint.ts +187 -0
  78. package/src/browser-electron/profile-command.ts +47 -0
  79. package/src/browser-electron/profile-extension.ts +129 -0
  80. package/src/browser-electron/profile-lease.ts +211 -0
  81. package/src/browser-electron/profile-residue.ts +49 -0
  82. package/src/browser-electron/provider-core.ts +1107 -0
  83. package/src/browser-electron/provider-interaction.ts +1034 -0
  84. package/src/browser-electron/provider-media.ts +589 -0
  85. package/src/browser-electron/provider-navigation.ts +323 -0
  86. package/src/browser-electron/provider-observation.ts +664 -0
  87. package/src/browser-electron/provider-tabs.ts +372 -0
  88. package/src/browser-electron/provider.ts +666 -0
  89. package/src/browser-electron/reference-route.ts +598 -0
  90. package/src/browser-electron/remote-host.ts +1538 -0
  91. package/src/browser-electron/rpc-input.ts +13 -0
  92. package/src/browser-electron/rpc-ops.ts +41 -0
  93. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  94. package/src/browser-electron/runtime-route.ts +105 -0
  95. package/src/browser-electron/runtime-status.ts +309 -0
  96. package/src/browser-electron/settings-route.ts +64 -0
  97. package/src/browser-electron/settings-store.ts +593 -0
  98. package/src/browser-electron/shortcuts-route.ts +112 -0
  99. package/src/browser-electron/sidebar-only-host.ts +300 -0
  100. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  101. package/src/browser-electron/system-browser.ts +1850 -0
  102. package/src/browser-electron/tauri-host.ts +194 -0
  103. package/src/browser-electron/timing.ts +16 -0
  104. package/src/browser-electron/virtual-cursor.ts +162 -0
  105. package/src/browser-electron/windows-system.ts +24 -0
  106. package/src/browser-reference/delivery.ts +384 -0
  107. package/src/browser-reference/entry.ts +631 -0
  108. package/src/browser-reference/export.ts +339 -0
  109. package/src/browser-reference/import.ts +303 -0
  110. package/src/browser-reference/page-script.ts +1537 -0
  111. package/src/browser-reference/service.ts +1346 -0
  112. package/src/browser-reference/store.ts +172 -0
  113. package/src/browser-reference/text-quote.ts +219 -0
  114. package/src/browser-reference/types.ts +195 -0
  115. package/src/browser-reference/visible.ts +367 -0
  116. package/src/browser-reference/web-sources.ts +106 -0
  117. package/src/client/apply-guard.ts +22 -0
  118. package/src/client/browser/BrowserController.ts +693 -0
  119. package/src/client/browser/BrowserFrame.ts +78 -0
  120. package/src/client/browser/BrowserNavigation.ts +169 -0
  121. package/src/client/browser/BrowserPage.ts +23 -0
  122. package/src/client/browser/BrowserPersistence.ts +44 -0
  123. package/src/client/browser/IframeImpl.ts +182 -0
  124. package/src/client/browser/child-tabs.ts +14 -0
  125. package/src/client/browser/frame-history.ts +125 -0
  126. package/src/client/browser/frame-state.ts +27 -0
  127. package/src/client/browser/iframe-reference.ts +67 -0
  128. package/src/client/browser/initialization.ts +262 -0
  129. package/src/client/browser/omnibox.ts +243 -0
  130. package/src/client/browser/store.ts +38 -0
  131. package/src/client/browser/takeover-channel.ts +72 -0
  132. package/src/client/browser/url.ts +46 -0
  133. package/src/client/browser/web-reference-source.ts +56 -0
  134. package/src/client/css-modules.d.ts +4 -0
  135. package/src/client/definition.tsx +36 -0
  136. package/src/client/electron/ElectronWebViewImpl.ts +371 -0
  137. package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
  138. package/src/client/electron/NativeChildPresentation.ts +53 -0
  139. package/src/client/electron/NativeViewPage.ts +265 -0
  140. package/src/client/electron/pages.ts +23 -0
  141. package/src/client/electron/reference-overlay.ts +53 -0
  142. package/src/client/electron/workspace.ts +33 -0
  143. package/src/client/index.ts +333 -0
  144. package/src/client/locales.ts +860 -0
  145. package/src/client/pages.ts +28 -0
  146. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  147. package/src/client/reference/client/draft-reference.ts +167 -0
  148. package/src/client/reference/client/index.ts +7 -0
  149. package/src/client/reference/client/ordered-submission.ts +108 -0
  150. package/src/client/reference/client/pending-delivery.ts +216 -0
  151. package/src/client/reference/client/plugin.ts +208 -0
  152. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  153. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  154. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  155. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  156. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  157. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  158. package/src/client/reference/client/production/assembly.ts +447 -0
  159. package/src/client/reference/client/production/asset-store.ts +144 -0
  160. package/src/client/reference/client/production/availability.ts +72 -0
  161. package/src/client/reference/client/production/bytes.ts +36 -0
  162. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  163. package/src/client/reference/client/production/delivery-client.ts +211 -0
  164. package/src/client/reference/client/production/draft-adapter.ts +512 -0
  165. package/src/client/reference/client/production/http-transport.ts +212 -0
  166. package/src/client/reference/client/production/production-submission.ts +70 -0
  167. package/src/client/reference/client/production/protocol.ts +234 -0
  168. package/src/client/reference/client/production/reference-card.ts +240 -0
  169. package/src/client/reference/client/production/reference-labels.ts +29 -0
  170. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  171. package/src/client/reference/client/production/reveal.ts +215 -0
  172. package/src/client/reference/client/production/runtime.ts +1056 -0
  173. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  174. package/src/client/reference/client/production/source-marker.ts +99 -0
  175. package/src/client/reference/client/production/source-opener.ts +55 -0
  176. package/src/client/reference/client/production/styles.ts +104 -0
  177. package/src/client/reference/client/production/user-text-rule.ts +67 -0
  178. package/src/client/reference/client/reveal.ts +109 -0
  179. package/src/client/reference/client/scheme.ts +114 -0
  180. package/src/client/reference/client/session-schedule.ts +36 -0
  181. package/src/client/reference/client/types.ts +168 -0
  182. package/src/client/reference/css-modules.d.ts +4 -0
  183. package/src/client/reference/index.ts +11 -0
  184. package/src/client/reference-capture-owner.ts +162 -0
  185. package/src/client/reference-intents.ts +36 -0
  186. package/src/client/settings/index.ts +42 -0
  187. package/src/client/settings/mount-guard.ts +31 -0
  188. package/src/client/settings/panel.ts +2768 -0
  189. package/src/client/shortcut-open.ts +30 -0
  190. package/src/client/startpage/binding.ts +99 -0
  191. package/src/client/startpage/controller.ts +300 -0
  192. package/src/client/startpage/model.ts +279 -0
  193. package/src/client/view/Browser.module.css +751 -0
  194. package/src/client/view/BrowserBody.tsx +315 -0
  195. package/src/client/view/BrowserPresentation.ts +9 -0
  196. package/src/client/view/BrowserTitle.tsx +17 -0
  197. package/src/client/view/IframePresentation.ts +365 -0
  198. package/src/client/view/StartPage.tsx +598 -0
  199. package/src/client/view/TakeoverBanner.tsx +21 -0
  200. package/src/compat/host-features.ts +92 -0
  201. package/src/index.ts +110 -0
  202. package/src/reference-owner.ts +5 -0
  203. package/src/reference-page.ts +9 -0
  204. package/src/reference-source.ts +3 -0
  205. package/src/reference-text.ts +219 -0
  206. package/src/startpage-settings.ts +103 -0
  207. package/src/startpage.ts +71 -0
  208. package/src/takeover-protocol.ts +28 -0
  209. package/src/tool-browser/block-recovery.ts +85 -0
  210. package/src/tool-browser/code-tool.ts +555 -0
  211. package/src/tool-browser/code-worker.ts +725 -0
  212. package/src/tool-browser/element-fields.ts +167 -0
  213. package/src/tool-browser/errors.ts +40 -0
  214. package/src/tool-browser/index.ts +265 -0
  215. package/src/tool-browser/page-probe.ts +675 -0
  216. package/src/tool-browser/panel-page.ts +126 -0
  217. package/src/tool-browser/probe-client.ts +183 -0
  218. package/src/tool-browser/screenshot-annotations.ts +131 -0
  219. package/src/tool-browser/screenshot-image.ts +49 -0
  220. package/src/tool-browser/state.ts +375 -0
  221. package/src/tool-browser/takeover.ts +199 -0
  222. package/src/tool-browser/tools-debug.ts +806 -0
  223. package/src/tool-browser/tools-interaction.ts +956 -0
  224. package/src/tool-browser/tools-navigation.ts +786 -0
  225. package/src/tool-browser/tools-observation.ts +474 -0
  226. package/src/tool-browser/tools-reference.ts +294 -0
  227. package/src/types/electron-shim.d.ts +144 -0
  228. package/src/types.ts +85 -0
  229. package/src/web-guest.ts +35 -0
  230. package/tools/accept-desktop.mjs +148 -0
  231. package/dist/client.d.cts +0 -516
  232. package/dist/client.d.mts +0 -516
  233. package/dist/index.cjs +0 -92
  234. package/dist/index.d.mts +0 -2960
  235. package/dist/index.mjs +0 -24
  236. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  237. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  238. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  239. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  240. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  241. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  242. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  243. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  244. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  245. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  246. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  247. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  248. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  249. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  250. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  251. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  252. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  253. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  254. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  255. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  256. package/dsh-host-patch/sources/manifest.json +0 -218
  257. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  258. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  259. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  260. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  261. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  262. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  263. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  264. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  265. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  266. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  267. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  268. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  269. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  270. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  271. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  272. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  273. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  274. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  275. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  276. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  277. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  278. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  279. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  280. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  281. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  282. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  283. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  284. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  285. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  286. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  287. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  288. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  289. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  290. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  291. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  292. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  293. package/dsh-host-patch/sources/series.json +0 -260
@@ -0,0 +1,1385 @@
1
+ import { hostMessages } from '../../assets/browser-messages.mjs'
2
+ import { LOOPBACK_IPV4, BROWSER_PROFILE_DIR } from '../../assets/browser-policy.mjs'
3
+ /**
4
+ * Self-hosted Electron browser host (child side): the Electron main process
5
+ * spawned by {@link RemoteElectronViewHost}. Owns one `BrowserWindow` PER
6
+ * SESSION (each session's views live in their own window) plus a browser
7
+ * toolbar (address bar, back/forward/reload, tab strip) that makes the
8
+ * built-in browser usable as a real browser by the human — every window has
9
+ * its own toolbar. Views are `WebContentsView`s driven over
10
+ * `webContents.debugger` (CDP); user toolbar actions are routed back to the
11
+ * parent so the agent and the human always share one tab/navigation model.
12
+ *
13
+ * Protocol (one JSON object per line, both directions):
14
+ * <- { id, op: 'ping' } | { id, op: 'createView', viewId } |
15
+ * { id, op: 'destroyView', viewId } | { id, op: 'showView', viewId } |
16
+ * { id, op: 'groupView', viewId, windowId, label? } |
17
+ * { id, op: 'command', viewId, method, params } |
18
+ * { id, op: 'focus', viewId } |
19
+ * { id, op: 'userActionError', windowId, message }
20
+ * -> { id: 0, op: 'hello', token } (our FIRST message — proves we know the
21
+ * parent's stdin token; the parent refuses the connection otherwise)
22
+ * -> { id, ok: true, result? } | { id, ok: false, err }
23
+ * -> { id: 0, op: 'userAction', action } (fire-and-forget; no reply)
24
+ *
25
+ * The parent never parses stderr, so diagnostics may go there freely.
26
+ * @module dsh-browser/browser-electron/host-main
27
+ */
28
+
29
+ import { app, BrowserWindow, Menu, session, WebContentsView } from 'electron'
30
+ import {
31
+ overlayScript,
32
+ overlayDisposeScript,
33
+ referenceMenuTemplate,
34
+ standaloneScript,
35
+ REFERENCE_INTENT_CHANNEL,
36
+ MAX_REFERENCE_COMMENT,
37
+ MAX_REFERENCE_TEXT,
38
+ } from '../browser-reference/entry.ts'
39
+ import { validateFrozenCapture } from '../browser-reference/page-script.ts'
40
+ import { createInterface } from 'node:readline'
41
+ import { createConnection } from 'node:net'
42
+ import { mkdirSync, writeFileSync } from 'node:fs'
43
+ import { writeFileNoReplace } from './file-write.ts'
44
+ import { electronRuntimeDiagnosticLines } from './runtime-diagnostics.ts'
45
+ import { createRpcLineReader } from './rpc-input.ts'
46
+ import { tmpdir } from 'node:os'
47
+ import { isAbsolute, join } from 'node:path'
48
+ import { withTimeoutShared } from './timing.ts'
49
+ import { dshHome } from './paths.ts'
50
+
51
+ // Report the binary actually running this child, even when ELECTRON_PATH
52
+ // intentionally selects a different version from the plugin's dependency.
53
+ // The parent mirrors stderr to the host log; discovery stays filesystem-only.
54
+ for (const line of electronRuntimeDiagnosticLines(process.versions)) {
55
+ process.stderr.write(line + '\n')
56
+ }
57
+
58
+ /**
59
+ * The spawn token the parent sent via stdin (first line). Must be echoed in
60
+ * our hello. Read from stdin so the token never appears in argv (WMI /
61
+ * Process Explorer / /proc/*).
62
+ */
63
+
64
+ // Isolate this host's profile from the DSH app's default Electron userData:
65
+ // several Electron instances sharing Roaming\Electron fight over the GPU
66
+ // cache/session locks, which can leave the window without a display surface
67
+ // (capturePage then fails). A dedicated userData also persists cookies across
68
+ // host restarts (on top of dsh_browser_auth) unless an ephemeral userData dir
69
+ // is passed via DSH_BROWSER_USER_DATA_DIR. Must run before app is ready.
70
+ try {
71
+ const overrideUserData = process.env.DSH_BROWSER_USER_DATA_DIR
72
+ const userDataDir = typeof overrideUserData === 'string' && overrideUserData !== '' && isAbsolute(overrideUserData)
73
+ ? overrideUserData
74
+ : join(dshHome(), BROWSER_PROFILE_DIR)
75
+ app.setPath('userData', userDataDir)
76
+ } catch (error) {
77
+ process.stderr.write(`[dsh-browser host] userData setup failed: ${String(error)}\n`)
78
+ }
79
+
80
+ /**
81
+ * Read the spawn token. The parent sends it two ways:
82
+ * 1. stdin (first line) — the secure channel on Unix/macOS;
83
+ * 2. DSH_BROWSER_RPC_TOKEN env — the fallback on Windows, where Electron is
84
+ * a GUI-subsystem process and never receives piped stdin (the parent
85
+ * sets it in the spawn env for exactly this reason).
86
+ *
87
+ * stdin WINS over env, which is what the ordering here has to express. It used to read env
88
+ * first and only consult stdin when that came up empty, so the stdin branch never ran while
89
+ * env was set — every spawn was told both ways, so the documented preference was silently
90
+ * the other way round. The env value is kept as the default for the common case where stdin
91
+ * delivers nothing; the interface below overwrites it when a line arrives.
92
+ */
93
+ let RPC_TOKEN = process.env.DSH_BROWSER_RPC_TOKEN ?? ''
94
+ /** True once a line actually arrived on stdin (as opposed to env being present). */
95
+ let tokenFromStdin = false
96
+ /**
97
+ * The one and only stdin reader.
98
+ *
99
+ * It is created here and reused by the hello path inside `whenReady` below: two
100
+ * `createInterface` calls on the same stream both consume its lines, so the second one saw
101
+ * nothing at all. A single reader means whoever needs the token from stdin waits on it.
102
+ */
103
+ const stdinLines = process.stdin !== null && process.stdin.readable
104
+ ? createInterface({ input: process.stdin, terminal: false })
105
+ : undefined
106
+ if (stdinLines !== undefined) {
107
+ stdinLines.on('line', (line) => {
108
+ if (tokenFromStdin) return
109
+ tokenFromStdin = true
110
+ const token = line.trim()
111
+ if (token !== '') RPC_TOKEN = token
112
+ })
113
+ stdinLines.on('close', () => {
114
+ if (RPC_TOKEN === '') {
115
+ process.stderr.write('[dsh-browser host] warning: no token received on stdin or env\n')
116
+ }
117
+ })
118
+ }
119
+
120
+ /** CDP protocol version attached to every view's debugger. */
121
+ const CDP_VERSION = '1.3'
122
+
123
+ /** Download cap: the body is shipped base64 as one JSON line; bound the memory. */
124
+ const MAX_DOWNLOAD_BYTES = 256 * 1024 * 1024
125
+
126
+ /** Toolbar height in CSS px: nav row + tab strip. Page views sit below it. */
127
+ const TOOLBAR_HEIGHT = 64
128
+
129
+ /** One view: the Electron object plus its CDP-backed surface. */
130
+ interface HostView {
131
+ readonly webContentsView: WebContentsView
132
+ /**
133
+ * Set when the view's renderer process was replaced by a navigation. The
134
+ * fresh renderer has no display surface, and Chromium silently drops CDP
135
+ * synthesized input for a view without one — so the next show/input must
136
+ * force the visible-again dance even if this view is already the visible
137
+ * one. Cleared once the surface has been re-established.
138
+ */
139
+ needsRepresent: boolean
140
+ }
141
+
142
+ /** One window: a session's views + its toolbar. */
143
+ interface HostWindow {
144
+ /** The group key (session id), or the shared fallback. */
145
+ readonly windowId: string
146
+ readonly window: BrowserWindow
147
+ /** The toolbar view (address bar + tab strip); undefined when it failed. */
148
+ toolbarView: WebContentsView | undefined
149
+ /** Views by viewId, in creation order (the tab strip's order). */
150
+ readonly views: Map<string, HostView>
151
+ /** The visible (topmost) view id within this window. */
152
+ visibleViewId: string | undefined
153
+ /** The last view the human clicked (focus steering target on refocus). */
154
+ lastFocusedViewId: string | undefined
155
+ /** Deferred close: the last view may be re-created immediately (closeTab keeps one blank tab). */
156
+ closeTimer: ReturnType<typeof setTimeout> | undefined
157
+ }
158
+
159
+ /** Fallback group for views whose groupView never arrived (defensive only). */
160
+ const SHARED_WINDOW_ID = 'shared'
161
+
162
+ /** Focus key for the toolbar view (it is not in win.views). */
163
+ const TOOLBAR_FOCUS = '\u0000toolbar'
164
+
165
+ /** Windows by group key (session id). */
166
+ const windows = new Map<string, HostWindow>()
167
+
168
+ /**
169
+ * Window assignments received via groupView BEFORE the view's createView:
170
+ * the parent sends groupView right after createView (both deferred until the
171
+ * child is ready), so either order may arrive first.
172
+ */
173
+ const assignments = new Map<string, { windowId: string; label?: string }>()
174
+
175
+ /** The RPC socket to the parent; set when the connection is established. */
176
+ let rpcSocket: import('node:net').Socket | undefined
177
+
178
+ // ---------------------------------------------------------------------------
179
+ // Toolbar: a small HTML strip (address bar, back/forward/reload, tab strip)
180
+ // rendered in its own WebContentsView on top of every window. It talks to
181
+ // this main process over IPC; user actions go to the PARENT (which owns the
182
+ // session/tab model) as fire-and-forget `userAction` messages.
183
+ // ---------------------------------------------------------------------------
184
+
185
+ const TOOLBAR_PRELOAD = `const { contextBridge, ipcRenderer } = require('electron')
186
+ contextBridge.exposeInMainWorld('bridge', {
187
+ post: (action, payload) => ipcRenderer.send('toolbar-action', action, payload),
188
+ onTabs: cb => ipcRenderer.on('tabs', (_e, payload) => cb(payload)),
189
+ onError: cb => ipcRenderer.on('user-action-error', (_e, text) => cb(text)),
190
+ })
191
+ `
192
+
193
+ const TOOLBAR_HTML = `<!doctype html>
194
+ <html>
195
+ <head>
196
+ <meta charset="utf-8">
197
+ <style>
198
+ :root { color-scheme: light dark; }
199
+ * { box-sizing: border-box; margin: 0; padding: 0; }
200
+ html, body { height: 100%; overflow: hidden; font-family: system-ui, "Segoe UI", sans-serif; font-size: 12px; }
201
+ body { display: flex; flex-direction: column; background: #2b2d31; color: #e8e8e8; }
202
+ .nav { display: flex; align-items: center; gap: 4px; padding: 4px 6px; height: 32px; }
203
+ button.tool { background: transparent; border: none; color: inherit; width: 28px; height: 24px; border-radius: 4px; cursor: pointer; font-size: 13px; line-height: 1; flex: 0 0 auto; }
204
+ button.tool:hover { background: rgba(255,255,255,.12); }
205
+ #addr { flex: 1; min-width: 0; height: 24px; border: 1px solid rgba(255,255,255,.18); border-radius: 12px; background: rgba(255,255,255,.08); color: inherit; padding: 0 12px; font-size: 12px; outline: none; }
206
+ #addr:focus { border-color: #4a90d9; background: rgba(255,255,255,.14); }
207
+ #newtab { font-size: 15px; }
208
+ .strip { display: flex; align-items: stretch; gap: 2px; padding: 0 6px 4px; height: 30px; overflow-x: auto; }
209
+ .strip::-webkit-scrollbar { height: 4px; }
210
+ .tab { display: flex; align-items: center; gap: 6px; max-width: 180px; min-width: 90px; height: 24px; padding: 0 4px 0 10px; border-radius: 6px; background: rgba(255,255,255,.06); cursor: pointer; white-space: nowrap; flex: 0 0 auto; }
211
+ .tab:hover { background: rgba(255,255,255,.12); }
212
+ .tab.active { background: #3d4148; }
213
+ .tab .tt { overflow: hidden; text-overflow: ellipsis; flex: 1; }
214
+ .tab .x { width: 15px; height: 15px; border-radius: 3px; text-align: center; line-height: 15px; font-size: 10px; flex: 0 0 auto; }
215
+ .tab .x:hover { background: rgba(255,255,255,.25); }
216
+ #err { height: 0; overflow: hidden; font-size: 11px; color: #ff9090; padding: 0 8px; transition: height .15s; }
217
+ #err.show { height: 17px; }
218
+ </style>
219
+ </head>
220
+ <body>
221
+ <div class="nav">
222
+ <button class="tool" id="back" title="Back">&#9664;</button>
223
+ <button class="tool" id="fwd" title="Forward">&#9654;</button>
224
+ <button class="tool" id="reload" title="Reload">&#10227;</button>
225
+ <input id="addr" placeholder="Search or enter address" spellcheck="false">
226
+ <button class="tool" id="newtab" title="New tab">&#43;</button>
227
+ </div>
228
+ <div class="strip" id="strip"></div>
229
+ <div id="err"></div>
230
+ <script>
231
+ // The body runs inside an IIFE on purpose. The preload above exposes
232
+ // window.bridge via contextBridge.exposeInMainWorld(), which installs a
233
+ // NON-CONFIGURABLE global property. A top-level const/let named bridge here
234
+ // would hit HasRestrictedGlobalProperty and throw a SyntaxError at PARSE time
235
+ // — an early error, so the whole script is discarded: nothing gets bound, the
236
+ // address bar and nav buttons go silently dead, and the user sees no error.
237
+ // Function scope sidesteps that check (the tb name below stops the collision
238
+ // from returning by habit) and keeps these bindings off the page global.
239
+ // Keep this block free of backticks — it lives inside a TS template literal.
240
+ (() => {
241
+ const tb = window.bridge
242
+ const addr = document.getElementById('addr')
243
+ const strip = document.getElementById('strip')
244
+ const errBox = document.getElementById('err')
245
+ let showErrT = 0
246
+ function showErr(text) {
247
+ errBox.textContent = String(text)
248
+ errBox.classList.add('show')
249
+ clearTimeout(showErrT)
250
+ showErrT = setTimeout(() => errBox.classList.remove('show'), 5000)
251
+ }
252
+ function post(action, payload) { tb.post(action, payload || {}) }
253
+ document.getElementById('back').onclick = () => post('back')
254
+ document.getElementById('fwd').onclick = () => post('forward')
255
+ document.getElementById('reload').onclick = () => post('reload')
256
+ document.getElementById('newtab').onclick = () => {
257
+ const v = addr.value.trim()
258
+ post('new-tab', v !== '' ? { url: v } : {})
259
+ addr.value = ''
260
+ }
261
+ addr.addEventListener('keydown', e => {
262
+ if (e.key === 'Enter') {
263
+ const v = addr.value.trim()
264
+ if (v !== '') { post('navigate', { url: v }); addr.blur() }
265
+ }
266
+ })
267
+ tb.onTabs(payload => {
268
+ const tabs = (payload && payload.tabs) || []
269
+ strip.textContent = ''
270
+ for (const t of tabs) {
271
+ const el = document.createElement('div')
272
+ el.className = 'tab' + (t.active ? ' active' : '')
273
+ const tt = document.createElement('span')
274
+ tt.className = 'tt'
275
+ tt.textContent = (t.title && t.title !== '') ? t.title : ((t.url && t.url !== '' && t.url !== 'about:blank') ? t.url : 'New tab')
276
+ tt.title = t.url || ''
277
+ el.appendChild(tt)
278
+ const x = document.createElement('span')
279
+ x.className = 'x'
280
+ x.textContent = '\\u2715'
281
+ x.onclick = e => { e.stopPropagation(); post('close', { viewId: t.viewId }) }
282
+ el.appendChild(x)
283
+ el.onclick = () => post('activate', { viewId: t.viewId })
284
+ strip.appendChild(el)
285
+ }
286
+ const act = tabs.find(t => t.active)
287
+ if (act && document.activeElement !== addr) addr.value = act.url || ''
288
+ })
289
+ tb.onError(text => showErr(text))
290
+ })()
291
+ </script>
292
+ </body>
293
+ </html>
294
+ `
295
+
296
+ /** Temp dir for the toolbar files; written once per process. */
297
+ const TOOLBAR_DIR = join(tmpdir(), `dsh-browser-toolbar-${process.pid}`)
298
+ let toolbarFilesReady = false
299
+
300
+ /** Write the toolbar's html + preload to disk once. */
301
+ function ensureToolbarFiles(): void {
302
+ if (toolbarFilesReady) return
303
+ toolbarFilesReady = true
304
+ mkdirSync(TOOLBAR_DIR, { recursive: true })
305
+ writeFileSync(join(TOOLBAR_DIR, 'preload.js'), TOOLBAR_PRELOAD)
306
+ writeFileSync(join(TOOLBAR_DIR, 'toolbar.html'), TOOLBAR_HTML)
307
+ }
308
+
309
+ /**
310
+ * Bound an await with a timeout. Used so a wedged renderer surfaces as an
311
+ * explicit error instead of a command that never settles.
312
+ */
313
+ function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
314
+ return withTimeoutShared(promise, ms, () => new Error(`${label} timed out after ${ms}ms`))
315
+ }
316
+
317
+ /**
318
+ * CDP commands are bounded here as well as in the parent: a view whose
319
+ * renderer stopped responding must produce a clear error, not a hang that
320
+ * only the tool layer's 10–30s timeout eventually cuts off.
321
+ */
322
+ const COMMAND_TIMEOUT_MS = 20000
323
+
324
+ /**
325
+ * How long to let a `focus` request land before answering it. Focus moves
326
+ * asynchronously and a key dispatched in the same turn as the request is still
327
+ * dropped, so the caller needs this settle — but only on the call where focus
328
+ * actually had to move.
329
+ */
330
+ const FOCUS_SETTLE_MS = 80
331
+
332
+ /**
333
+ * A brand-new WebContentsView has no renderer process until something loads,
334
+ * and CDP commands (Runtime.evaluate …) sent to a renderer-less view never
335
+ * settle. That is what made a host restart unrecoverable: the provider
336
+ * rebuilds the session with a fresh blank view whose very first action is a
337
+ * location.href read, which hung until the tool timeout.
338
+ *
339
+ * Loading about:blank spawns the renderer, so the view answers the moment it
340
+ * exists; a real navigation replaces it right after. Bounded + best-effort —
341
+ * the caller still gets its reply if this fails.
342
+ */
343
+ const RENDERER_PRIME_TIMEOUT_MS = 3000
344
+
345
+ async function primeRenderer(view: WebContentsView): Promise<void> {
346
+ try {
347
+ await withTimeout(view.webContents.loadURL('about:blank'), RENDERER_PRIME_TIMEOUT_MS, 'renderer prime')
348
+ } catch { /* best effort: the first real navigation creates the renderer */ }
349
+ }
350
+
351
+ /** Reply to the parent over the RPC socket. */
352
+ function reply(id: number, payload: Record<string, unknown>): void {
353
+ if (rpcSocket === undefined) {
354
+ process.stderr.write(`[dsh-browser host] reply without socket (id=${id})\n`)
355
+ return
356
+ }
357
+ rpcSocket.write(JSON.stringify({ id, ...payload }) + '\n')
358
+ }
359
+
360
+ /** Send a fire-and-forget user action to the parent (no reply expected). */
361
+ function sendUserAction(action: Record<string, unknown>): void {
362
+ if (rpcSocket === undefined) return
363
+ try {
364
+ rpcSocket.write(JSON.stringify({ id: 0, op: 'userAction', action }) + '\n')
365
+ } catch { /* socket closed */ }
366
+ }
367
+
368
+ /** Turn a typed-in address into a URL (add https:// when no scheme is given). */
369
+ function normalizeUrl(raw: string): string {
370
+ const trimmed = raw.trim()
371
+ if (trimmed === '') return ''
372
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) return trimmed
373
+ return 'https://' + trimmed
374
+ }
375
+
376
+ /** Route one toolbar interaction to the parent (which owns the session model). */
377
+ function handleToolbarAction(win: HostWindow, action: string, payload: Record<string, unknown>): void {
378
+ const windowId = win.windowId
379
+ switch (action) {
380
+ case 'navigate': {
381
+ const url = normalizeUrl(String(payload.url ?? ''))
382
+ if (url === '') return
383
+ sendUserAction({ type: 'navigate', windowId, url })
384
+ return
385
+ }
386
+ case 'new-tab': {
387
+ const raw = String(payload.url ?? '').trim()
388
+ const url = raw !== '' ? normalizeUrl(raw) : undefined
389
+ sendUserAction({ type: 'newTab', windowId, ...url !== undefined ? { url } : {} })
390
+ return
391
+ }
392
+ case 'activate':
393
+ sendUserAction({ type: 'activateTab', windowId, viewId: String(payload.viewId ?? '') })
394
+ return
395
+ case 'close':
396
+ sendUserAction({ type: 'closeTab', windowId, viewId: String(payload.viewId ?? '') })
397
+ return
398
+ case 'back':
399
+ sendUserAction({ type: 'back', windowId })
400
+ return
401
+ case 'forward':
402
+ sendUserAction({ type: 'forward', windowId })
403
+ return
404
+ case 'reload':
405
+ sendUserAction({ type: 'reload', windowId })
406
+ return
407
+ default:
408
+ process.stderr.write(`[dsh-browser host] unknown toolbar action: ${action}\n`)
409
+ }
410
+ }
411
+
412
+ /** Find the window holding a view, if any. */
413
+ function windowOfView(viewId: string): HostWindow | undefined {
414
+ for (const win of windows.values()) {
415
+ if (win.views.has(viewId)) return win
416
+ }
417
+ return undefined
418
+ }
419
+
420
+ /** Get (or lazily create) the window for a group key. */
421
+ function windowFor(windowId: string | undefined): HostWindow {
422
+ const key = windowId === undefined || windowId === '' ? SHARED_WINDOW_ID : windowId
423
+ const existing = windows.get(key)
424
+ if (existing !== undefined) return existing
425
+ // `show: false` on purpose: creating a window must not be a presentation decision. With `show: true`
426
+ // the window appeared and took the screen the moment the first tool call created it — before any
427
+ // `showView` message could carry `ui.quiet`, so quiet mode had no effect at all on this carrier
428
+ // (measured: the setting was on and the window still popped up). The first presentation decides:
429
+ // quiet shows it inactive, a normal call shows it normally.
430
+ const w = new BrowserWindow({ width: 1400, height: 900, show: false, title: 'dsh-browser' })
431
+ w.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
432
+ w.on('closed', () => {
433
+ const closing = windows.get(key)
434
+ windows.delete(key)
435
+ // A BrowserWindow does not destroy its child views: their webContents (the
436
+ // renderer process, its timers and audio) outlive the window unless closed
437
+ // explicitly, so release them here instead of leaking a renderer per window.
438
+ if (closing !== undefined) {
439
+ for (const view of closing.views.values()) {
440
+ try {
441
+ view.webContentsView.webContents.close()
442
+ } catch {
443
+ // Already destroyed along with the window.
444
+ }
445
+ }
446
+ closing.views.clear()
447
+ }
448
+ // The interface is gone for good. Report it, so the plugin ends that session
449
+ // instead of holding one whose window the human already closed. Browsing
450
+ // history and login state live on disk, so the next open starts a clean
451
+ // session rather than resurrecting this one.
452
+ try {
453
+ rpcSocket?.write(JSON.stringify({ id: 0, op: 'viewClosed', windowId: key }) + '\n')
454
+ } catch {
455
+ // Socket already gone (parent shutting down): nothing left to report to.
456
+ }
457
+ })
458
+ const win: HostWindow = { windowId: key, window: w, toolbarView: undefined, views: new Map(), visibleViewId: undefined, lastFocusedViewId: undefined, closeTimer: undefined }
459
+ // Keep every view (and the toolbar) filling the window as the human
460
+ // resizes it; otherwise pages stay at their original size and break.
461
+ w.on('resize', () => layoutWindow(win))
462
+ // Windows: keyboard input goes only to the FOCUSED webContents, and a window
463
+ // regaining focus (alt-tab, click) does not automatically refocus any view
464
+ // (electron#28163) — the last addChildView keeps the focus. Restore the view
465
+ // the human was last using (click steering via wireFocusRouting), falling
466
+ // back to the visible page view. Windows-only: on macOS/Linux the OS routes
467
+ // keyboard input to the clicked view natively, and forcing focus() on window
468
+ // focus fights the platform — it can leave page inputs untypeable (issue #7).
469
+ w.on('focus', () => {
470
+ if (process.platform !== 'win32') return
471
+ const last = win.lastFocusedViewId
472
+ const wc = last === TOOLBAR_FOCUS ? win.toolbarView?.webContents
473
+ : last !== undefined ? win.views.get(last)?.webContentsView.webContents
474
+ : undefined
475
+ const fallback = win.visibleViewId !== undefined ? win.views.get(win.visibleViewId)?.webContentsView.webContents : undefined
476
+ try { (wc ?? fallback)?.focus() } catch { /* destroyed */ }
477
+ })
478
+ windows.set(key, win)
479
+ win.toolbarView = createToolbar(win)
480
+ layoutWindow(win)
481
+ return win
482
+ }
483
+
484
+ /** Position the toolbar and every page view within a window. */
485
+ function layoutWindow(win: HostWindow): void {
486
+ try {
487
+ const size = win.window.getContentSize() ?? [0, 0]
488
+ const width = size[0] ?? 0
489
+ const height = size[1] ?? 0
490
+ try { win.toolbarView?.setBounds({ x: 0, y: 0, width, height: TOOLBAR_HEIGHT }) } catch { /* destroyed */ }
491
+ for (const v of win.views.values()) {
492
+ try { v.webContentsView.setBounds({ x: 0, y: TOOLBAR_HEIGHT, width, height: Math.max(0, height - TOOLBAR_HEIGHT) }) } catch { /* destroyed */ }
493
+ }
494
+ } catch { /* window gone */ }
495
+ }
496
+
497
+ /**
498
+ * Route keyboard focus on Windows. Mouse clicks reach any view regardless of
499
+ * focus, but keyboard events go only to the FOCUSED webContents (and a window
500
+ * regaining focus does not refocus any view, electron#28163). Focusing the
501
+ * clicked view on mousedown makes the toolbar and pages behave like a real
502
+ * browser: click the URL bar and type, click the page and type/scroll.
503
+ *
504
+ * Windows-only by design (issue #7): macOS/Linux already route keyboard input
505
+ * to the clicked view natively; calling webContents.focus() from inside the
506
+ * mousedown input-event there interferes with native click-to-focus and can
507
+ * leave login/page inputs unable to receive typed characters.
508
+ */
509
+ function wireFocusRouting(win: HostWindow, view: WebContentsView, focusKey: string): void {
510
+ if (process.platform !== 'win32') return
511
+ view.webContents.on('input-event', (_event, input) => {
512
+ if (input.type !== 'mouseDown') return
513
+ win.lastFocusedViewId = focusKey
514
+ if (win.window.isFocused()) {
515
+ try { view.webContents.focus() } catch { /* destroyed */ }
516
+ }
517
+ })
518
+ }
519
+
520
+ /** Create the toolbar view for a window (best-effort; never fatal). */
521
+ function createToolbar(win: HostWindow): WebContentsView | undefined {
522
+ try {
523
+ ensureToolbarFiles()
524
+ const view = new WebContentsView({
525
+ webPreferences: {
526
+ preload: join(TOOLBAR_DIR, 'preload.js'),
527
+ sandbox: true,
528
+ contextIsolation: true,
529
+ nodeIntegration: false,
530
+ },
531
+ })
532
+ void view.webContents.loadFile(join(TOOLBAR_DIR, 'toolbar.html')).catch(() => { /* toolbar loads async */ })
533
+ view.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
534
+ view.webContents.on('ipc-message', (_event, channel, ...args) => {
535
+ if (channel !== 'toolbar-action') return
536
+ // Diagnostics only; the parent never parses stderr.
537
+ process.stderr.write(`[dsh-browser host] toolbar action: ${String(args[0] ?? '')}\n`)
538
+ handleToolbarAction(win, String(args[0] ?? ''), (args[1] ?? {}) as Record<string, unknown>)
539
+ })
540
+ // Once the toolbar page is up, push the current tab strip so it is not
541
+ // empty until the first navigation event.
542
+ view.webContents.on('dom-ready', () => syncToolbar(win))
543
+ wireFocusRouting(win, view, TOOLBAR_FOCUS)
544
+ win.window.contentView.addChildView(view)
545
+ return view
546
+ } catch (error) {
547
+ process.stderr.write(`[dsh-browser host] toolbar creation failed: ${String(error)}\n`)
548
+ return undefined
549
+ }
550
+ }
551
+
552
+ /** Push the window's tab strip state to its toolbar. */
553
+ function syncToolbar(win: HostWindow): void {
554
+ if (win.toolbarView === undefined) return
555
+ const tabs: Array<{ viewId: string; title: string; url: string; active: boolean }> = []
556
+ for (const [viewId, v] of win.views) {
557
+ let title = ''
558
+ let url = ''
559
+ try {
560
+ title = v.webContentsView.webContents.getTitle()
561
+ url = v.webContentsView.webContents.getURL()
562
+ } catch { /* destroyed */ }
563
+ tabs.push({ viewId, title, url, active: viewId === win.visibleViewId })
564
+ }
565
+ try {
566
+ win.toolbarView.webContents.send('tabs', { tabs })
567
+ } catch { /* toolbar not loaded yet */ }
568
+ }
569
+
570
+ /** Set a window's title: dsh-browser [label] — page title — url. */
571
+ function updateWindowTitle(win: HostWindow, viewId: string | undefined, label: string | undefined): void {
572
+ try {
573
+ let title = 'dsh-browser'
574
+ if (label !== undefined && label !== '') title += ` [${label.slice(0, 48)}]`
575
+ const entry = viewId !== undefined ? win.views.get(viewId) : undefined
576
+ if (entry !== undefined) {
577
+ const pageTitle = entry.webContentsView.webContents.getTitle()
578
+ const url = entry.webContentsView.webContents.getURL()
579
+ if (pageTitle !== '') title += ` — ${pageTitle}`
580
+ if (url !== '' && url !== 'about:blank') title += ` — ${url}`
581
+ }
582
+ win.window.setTitle(title)
583
+ } catch { /* destroyed */ }
584
+ }
585
+
586
+ /**
587
+ * Make one view the visible (topmost) one WITHIN its window, leaving the window itself alone.
588
+ *
589
+ * Split out of {@link showViewInWindow} for quiet-mode capture: a screenshot still has to look
590
+ * at the active tab rather than another tab of the same window, but it must not show, restore,
591
+ * raise or focus the window to do it. Everything here is contentView-local.
592
+ * @param win - the window holding the view.
593
+ * @param viewId - the view to reveal.
594
+ * @param label - session/task label, when known, for the window title.
595
+ */
596
+ function revealViewInWindow(win: HostWindow, viewId: string, label?: string): void {
597
+ const entry = win.views.get(viewId)
598
+ if (entry === undefined) return
599
+ // A navigation replaced this view's renderer, and the new one has no
600
+ // display surface yet. Chromium drops CDP synthesized input (Input.*) for a
601
+ // view without a surface, which silently swallowed the FIRST click/keystroke
602
+ // after every navigation — and because the view was already the visible one,
603
+ // the dance below used to be skipped entirely. Force it once.
604
+ const mustRepresent = entry.needsRepresent
605
+ if (mustRepresent) {
606
+ try { entry.webContentsView.setVisible(false) } catch { /* destroyed */ }
607
+ }
608
+ if (win.visibleViewId !== viewId || mustRepresent) {
609
+ // Hide every other view in THIS window, then show and RAISE the target
610
+ // (topmost child wins). When the target is already visible, skip the
611
+ // remove/re-add dance — doing it on every operation flickered.
612
+ for (const v of win.views.values()) {
613
+ if (v === entry) continue
614
+ try { v.webContentsView.setVisible(false) } catch { /* destroyed */ }
615
+ }
616
+ entry.webContentsView.setVisible(true)
617
+ try {
618
+ win.window.contentView.removeChildView(entry.webContentsView)
619
+ win.window.contentView.addChildView(entry.webContentsView)
620
+ } catch { /* window closing */ }
621
+ win.visibleViewId = viewId
622
+ entry.needsRepresent = false
623
+ syncToolbar(win)
624
+ }
625
+ // Always refresh the title: it reflects the CURRENT page of the visible
626
+ // view, which changes as the agent navigates.
627
+ updateWindowTitle(win, viewId, label)
628
+ }
629
+
630
+ /**
631
+ * Make one view the visible one within its window, and — outside quiet mode — raise the window.
632
+ * @param win - the window holding the view.
633
+ * @param viewId - the view to present.
634
+ * @param label - session/task label, when known, for the window title.
635
+ * @param quiet - `ui.quiet`: present without taking the screen over.
636
+ * @param _needSurface - pre-input barrier flag retained by the RPC protocol. Quiet presentation
637
+ * opens a new visible window without activation and preserves an existing foreground page.
638
+ */
639
+ function showViewInWindow(win: HostWindow, viewId: string, label?: string, quiet = false, _needSurface = false): void {
640
+ if (quiet) {
641
+ if (win.window.isMinimized()) return
642
+ // Preserve the page the operator is actively reading. Other views remain addressable by
643
+ // their own CDP session, without switching the foreground window's selected page.
644
+ if (win.window.isFocused() && win.visibleViewId !== viewId) return
645
+ revealViewInWindow(win, viewId, label)
646
+ // Quiet means a normal usable window without activation, including on the first open.
647
+ // An invisible surface made the browser look broken even after navigation succeeded.
648
+ if (win.window.getOpacity() === 0) {
649
+ win.window.setOpacity(1)
650
+ win.window.setSkipTaskbar(false)
651
+ win.window.setFocusable(true)
652
+ }
653
+ if (!win.window.isVisible()) win.window.showInactive()
654
+ return
655
+ }
656
+ revealViewInWindow(win, viewId, label)
657
+ try {
658
+ if (win.window.getOpacity() === 0) {
659
+ win.window.setFocusable(true)
660
+ win.window.setOpacity(1)
661
+ win.window.setSkipTaskbar(false)
662
+ }
663
+ if (!win.window.isVisible()) win.window.show()
664
+ win.window.moveTop()
665
+ } catch { /* closing */ }
666
+ }
667
+
668
+ /** Close a session window once its last view is gone (deferred, flicker-free). */
669
+ function scheduleWindowClose(win: HostWindow): void {
670
+ if (win.windowId === SHARED_WINDOW_ID) return // shared fallback persists
671
+ if (win.closeTimer !== undefined) clearTimeout(win.closeTimer)
672
+ win.closeTimer = setTimeout(() => {
673
+ win.closeTimer = undefined
674
+ if (win.views.size > 0) return // a new tab arrived; keep the window
675
+ try { win.toolbarView?.webContents.close() } catch { /* already gone */ }
676
+ try { win.window.close() } catch { /* already gone */ }
677
+ }, 250)
678
+ }
679
+
680
+ /** Handle one command. */
681
+ async function handle(op: string, msg: { id: number; viewId?: string; windowId?: string; method?: string; params?: Record<string, unknown>; url?: string; savePath?: string; cookies?: unknown[]; label?: string; format?: string; quality?: number; maxWidth?: number; maxHeight?: number; message?: string; quiet?: boolean; needSurface?: boolean }): Promise<void> {
682
+ try {
683
+ switch (op) {
684
+ case 'ping':
685
+ reply(msg.id, { ok: true })
686
+ return
687
+ case 'groupView': {
688
+ const viewId = msg.viewId
689
+ const windowId = msg.windowId
690
+ if (viewId === undefined || typeof windowId !== 'string') throw new Error('groupView missing viewId/windowId')
691
+ // May arrive before or after createView; createView consumes it.
692
+ assignments.set(viewId, { windowId, ...typeof msg.label === 'string' ? { label: msg.label } : {} })
693
+ reply(msg.id, { ok: true })
694
+ return
695
+ }
696
+ case 'createView': {
697
+ const viewId = msg.viewId
698
+ if (viewId === undefined) throw new Error('createView missing viewId')
699
+ // Idempotent against a duplicate createView for the same id (e.g. two
700
+ // concurrent parent-side recoveries after a host death): re-creating
701
+ // would stack a second WebContentsView in the window and leak the
702
+ // first — the duplicate call simply confirms the existing view.
703
+ if (windowOfView(viewId) !== undefined) {
704
+ reply(msg.id, { ok: true })
705
+ return
706
+ }
707
+ const assignment = assignments.get(viewId)
708
+ const win = windowFor(assignment?.windowId)
709
+ const view = new WebContentsView()
710
+ // Route popups (window.open / target=_blank) into the session/tab
711
+ // model instead of letting Electron open untracked native windows.
712
+ view.webContents.setWindowOpenHandler(({ url }) => {
713
+ // HTTP(S) popups open as a NEW TAB of this view's session: the
714
+ // parent (provider) owns the session model and its newTab action
715
+ // creates the tab in the same window, navigates it, and records it
716
+ // in the session history. Overriding THIS view with loadURL()
717
+ // destroyed the opener page — pages that need their opener context
718
+ // (portal dashboards carrying token/referer to the new window)
719
+ // lost it and the target page then 403'd (issue #8); the tab strip
720
+ // now keeps the original page alive like a real browser.
721
+ if (/^https?:/i.test(url)) {
722
+ if (win.windowId !== SHARED_WINDOW_ID) {
723
+ sendUserAction({ type: 'newTab', windowId: win.windowId, url })
724
+ } else {
725
+ // Ungrouped view (no live session to attach a tab to,
726
+ // defensive only): fall back to navigating this view.
727
+ void view.webContents.loadURL(url).catch(() => { /* navigation failures surface on the next snapshot */ })
728
+ }
729
+ return { action: 'deny' }
730
+ }
731
+ return { action: 'deny' }
732
+ })
733
+ // Attach the debugger BEFORE the view can be seen: an attach failure
734
+ // then leaves nothing in the window (no visible ghost view).
735
+ view.webContents.debugger.attach(CDP_VERSION)
736
+ // New views start hidden: only the shown one may be visible.
737
+ view.setVisible(false)
738
+ win.window.contentView.addChildView(view)
739
+ win.views.set(viewId, { webContentsView: view, needsRepresent: false })
740
+ // Keep the window title and the toolbar tab strip live as the page
741
+ // changes (navigations, title updates).
742
+ view.webContents.on('page-title-updated', () => { updateWindowTitle(win, viewId, undefined); syncToolbar(win) })
743
+ view.webContents.on('did-navigate', () => {
744
+ // The renderer process was just replaced: mark the view so the next
745
+ // show forces a fresh display surface (see showViewInWindow).
746
+ const current = win.views.get(viewId)
747
+ if (current !== undefined) current.needsRepresent = true
748
+ updateWindowTitle(win, viewId, undefined)
749
+ syncToolbar(win)
750
+ })
751
+ view.webContents.on('did-navigate-in-page', () => syncToolbar(win))
752
+ wireFocusRouting(win, view, viewId)
753
+ const first = win.views.size === 1
754
+ if (first) {
755
+ view.setVisible(true)
756
+ win.visibleViewId = viewId
757
+ }
758
+ layoutWindow(win)
759
+ if (first) updateWindowTitle(win, viewId, undefined)
760
+ syncToolbar(win)
761
+ // Prime the renderer BEFORE replying: the parent's next command
762
+ // (a location.href read) would otherwise hang on a view that has no
763
+ // renderer yet — the root of "host restarted and never recovers".
764
+ await primeRenderer(view)
765
+ reply(msg.id, { ok: true })
766
+ return
767
+ }
768
+ case 'destroyView': {
769
+ const viewId = msg.viewId
770
+ if (viewId === undefined) throw new Error('destroyView missing viewId')
771
+ const win = windowOfView(viewId)
772
+ if (win !== undefined) {
773
+ const entry = win.views.get(viewId)
774
+ win.views.delete(viewId)
775
+ if (win.visibleViewId === viewId) win.visibleViewId = undefined
776
+ try { entry?.webContentsView.webContents.debugger.detach() } catch { /* already detached */ }
777
+ try { entry?.webContentsView.webContents.close() } catch { /* destroyed */ }
778
+ try { if (entry !== undefined) win.window.contentView.removeChildView(entry.webContentsView) } catch { /* destroyed */ }
779
+ // The visible tab was destroyed: show the next one in this window.
780
+ if (win.visibleViewId === undefined && win.views.size > 0) {
781
+ const next = win.views.keys().next().value as string | undefined
782
+ if (next !== undefined) showViewInWindow(win, next)
783
+ } else if (win.visibleViewId === undefined) {
784
+ // No views left — reset the window title so it doesn't
785
+ // retain the old page's title.
786
+ updateWindowTitle(win, undefined, undefined)
787
+ }
788
+ syncToolbar(win)
789
+ // Close the window with its last view — deferred because the
790
+ // provider re-creates a blank tab right after closing the last one.
791
+ scheduleWindowClose(win)
792
+ }
793
+ assignments.delete(viewId)
794
+ reply(msg.id, { ok: true })
795
+ return
796
+ }
797
+ case 'showView': {
798
+ const viewId = msg.viewId
799
+ if (viewId === undefined) throw new Error('showView missing viewId')
800
+ const win = windowOfView(viewId)
801
+ if (win !== undefined) showViewInWindow(win, viewId, typeof msg.label === 'string' ? msg.label : undefined, msg.quiet === true, msg.needSurface === true)
802
+ reply(msg.id, { ok: true })
803
+ return
804
+ }
805
+ case 'userActionError': {
806
+ const windowId = msg.windowId
807
+ const message = msg.message
808
+ if (typeof windowId !== 'string' || typeof message !== 'string') throw new Error('userActionError missing windowId/message')
809
+ const win = windows.get(windowId)
810
+ if (win !== undefined) {
811
+ try { win.toolbarView?.webContents.send('user-action-error', message) } catch { /* toolbar not loaded */ }
812
+ }
813
+ reply(msg.id, { ok: true })
814
+ return
815
+ }
816
+ case 'command': {
817
+ const viewId = msg.viewId
818
+ if (viewId === undefined) throw new Error('command missing viewId')
819
+ const win = windowOfView(viewId)
820
+ const entry = win?.views.get(viewId)
821
+ if (win === undefined || entry === undefined) throw new Error(`command: unknown view ${viewId}`)
822
+ const method = msg.method
823
+ if (typeof method !== 'string') throw new Error('command missing method')
824
+ const result = await withTimeout(
825
+ entry.webContentsView.webContents.debugger.sendCommand(method, msg.params ?? {}),
826
+ COMMAND_TIMEOUT_MS,
827
+ `CDP ${method}`,
828
+ )
829
+ reply(msg.id, { ok: true, result })
830
+ return
831
+ }
832
+ case 'focus': {
833
+ const viewId = msg.viewId
834
+ if (viewId === undefined) throw new Error('focus missing viewId')
835
+ const win = windowOfView(viewId)
836
+ const entry = win?.views.get(viewId)
837
+ if (win === undefined || entry === undefined) throw new Error(`focus: unknown view ${viewId}`)
838
+ // Keys go to the view that holds web focus. A view that was never
839
+ // clicked holds none, so the FIRST dsh_browser_key of a session was dropped
840
+ // by the renderer while CDP still answered the dispatch with success —
841
+ // and `document.hasFocus()` inside the page even read true.
842
+ const contents = entry.webContentsView.webContents
843
+ const hadWebFocus = contents.isFocused()
844
+ // Electron webContents.focus() can activate its BrowserWindow. CDP input uses the
845
+ // target page's DOM focus and does not require that operating-system activation.
846
+ if (msg.quiet !== true) contents.focus()
847
+ // Focus lands asynchronously, and a key dispatched in the same turn as
848
+ // the request is still dropped, so hold the reply until the renderer can
849
+ // take input. Only on the call where focus actually had to move.
850
+ if (!hadWebFocus) await new Promise(resolve => setTimeout(resolve, FOCUS_SETTLE_MS))
851
+ reply(msg.id, { ok: true, focused: contents.isFocused() })
852
+ return
853
+ }
854
+ case 'capture': {
855
+ const viewId = msg.viewId
856
+ if (viewId === undefined) throw new Error('capture missing viewId')
857
+ const win = windowOfView(viewId)
858
+ const entry = win?.views.get(viewId)
859
+ if (win === undefined || entry === undefined) throw new Error(`capture: unknown view ${viewId}`)
860
+ // Two complementary paths, because each has a failure mode:
861
+ // - capturePage: fast and reliable with several WebContentsViews in
862
+ // the window, but needs a live display surface (fails when the
863
+ // window is minimized/occluded/unpainted).
864
+ // - CDP Page.captureScreenshot: works without a display surface, but
865
+ // can hang when another hidden WebContentsView exists in the window.
866
+ // Try capturePage first (show/focus/restore + one retry), then CDP.
867
+ // PNG/JPEG + downscale are applied on the NativeImage here, so the
868
+ // body never needs a second round-trip.
869
+ const wantFormat = msg.format === 'jpeg' ? 'jpeg' : 'png'
870
+ const wantQuality = typeof msg.quality === 'number' ? msg.quality : 80
871
+ const maxW = typeof msg.maxWidth === 'number' ? msg.maxWidth : 0
872
+ const maxH = typeof msg.maxHeight === 'number' ? msg.maxHeight : 0
873
+ // Quiet mode: a screenshot is not a reason to take the screen over. Skipping the
874
+ // raise below is what makes a minimized window survive a screenshot: capturePage on
875
+ // a hidden view returns an empty image, and the CDP fallback captures without needing
876
+ // a display surface. The default path keeps the raise, because there a screenshot is
877
+ // how the human follows what the agent is doing.
878
+ const quiet = msg.quiet === true
879
+ let mime = 'image/png'
880
+ if (quiet) {
881
+ // The active tab has to be the visible one INSIDE the window, or the capture may read
882
+ // another tab. Keep that switch contentView-local: show/restore/focus are precisely
883
+ // what quiet mode forbids.
884
+ if (!win.window.isVisible() || win.window.getOpacity() === 0) revealViewInWindow(win, viewId)
885
+ } else {
886
+ try {
887
+ if (!win.window.isVisible()) win.window.show()
888
+ } catch { /* closing */ }
889
+ try { win.window.restore() } catch { /* not minimized */ }
890
+ win.window.focus()
891
+ }
892
+ let base64 = ''
893
+ let renderedSize: { width: number; height: number } | undefined
894
+ try {
895
+ let image
896
+ try {
897
+ image = await withTimeout(
898
+ entry.webContentsView.webContents.capturePage(),
899
+ COMMAND_TIMEOUT_MS,
900
+ 'capturePage',
901
+ )
902
+ } catch (error) {
903
+ process.stderr.write(`[dsh-browser host] capturePage failed: ${String(error)}\n`)
904
+ await new Promise(resolve => setTimeout(resolve, 400))
905
+ image = await withTimeout(
906
+ entry.webContentsView.webContents.capturePage(),
907
+ COMMAND_TIMEOUT_MS,
908
+ 'capturePage',
909
+ )
910
+ }
911
+ // Downscale to fit the requested box, preserving aspect ratio.
912
+ const size = image.getSize()
913
+ let w = size.width ?? 0
914
+ let h = size.height ?? 0
915
+ if (maxW > 0 && w > maxW) { h = Math.round(h * maxW / w); w = maxW }
916
+ if (maxH > 0 && h > maxH) { w = Math.round(w * maxH / h); h = maxH }
917
+ if (w > 0 && h > 0 && (w !== size.width || h !== size.height)) image = image.resize({ width: w, height: h })
918
+ // What the caller actually receives: after the downscale, not the captured size.
919
+ // Recorded here because this is the last point that knows both.
920
+ if (w > 0 && h > 0) renderedSize = { width: w, height: h }
921
+ const buf = wantFormat === 'jpeg' ? image.toJPEG(wantQuality) : image.toPNG()
922
+ if (wantFormat === 'jpeg') mime = 'image/jpeg'
923
+ if (buf.length > 0) base64 = buf.toString('base64')
924
+ } catch (error) {
925
+ process.stderr.write(`[dsh-browser host] capturePage retry failed: ${String(error)}\n`)
926
+ base64 = ''
927
+ }
928
+ if (base64 === '') {
929
+ // CDP fallback. Page.captureScreenshot can hang when OTHER views
930
+ // (especially hidden attach-first ones) are in the window, so
931
+ // temporarily detach the siblings AND the toolbar, capture in
932
+ // single-view state, then restore them (target stays on top).
933
+ const siblings = [...win.views.values()].filter(v => v !== entry)
934
+ const toolbar = win.toolbarView
935
+ for (const v of siblings) {
936
+ try { win.window.contentView.removeChildView(v.webContentsView) } catch { /* already gone */ }
937
+ }
938
+ if (toolbar !== undefined) {
939
+ try { win.window.contentView.removeChildView(toolbar) } catch { /* already gone */ }
940
+ }
941
+ try {
942
+ const shot = await withTimeout(
943
+ entry.webContentsView.webContents.debugger.sendCommand('Page.captureScreenshot', {}),
944
+ COMMAND_TIMEOUT_MS,
945
+ 'Page.captureScreenshot',
946
+ )
947
+ const data = (shot as { data?: unknown }).data
948
+ if (typeof data === 'string' && data.length > 0) base64 = data
949
+ } finally {
950
+ if (toolbar !== undefined) {
951
+ try { win.window.contentView.addChildView(toolbar) } catch { /* destroyed */ }
952
+ }
953
+ for (const v of siblings) {
954
+ try { win.window.contentView.addChildView(v.webContentsView) } catch { /* destroyed */ }
955
+ }
956
+ try {
957
+ win.window.contentView.removeChildView(entry.webContentsView)
958
+ win.window.contentView.addChildView(entry.webContentsView)
959
+ } catch { /* closing */ }
960
+ }
961
+ }
962
+ if (base64 === '') {
963
+ throw new Error('capture produced no image (view not painted)')
964
+ }
965
+ // The measured size travels with the image. Without it the native path — which is the
966
+ // default self-hosted one — could never answer `dsh_browser_screenshot`'s width/height,
967
+ // because the seam's only channel was {base64, mime} and the provider had nothing to
968
+ // forward. The caller's `maxWidth`/`maxHeight` are applied here, so this is the only
969
+ // place that knows what came back.
970
+ reply(msg.id, { ok: true, result: { base64, mime, width: renderedSize?.width, height: renderedSize?.height } })
971
+ return
972
+ }
973
+ case 'download': {
974
+ const viewId = msg.viewId
975
+ const url = msg.url
976
+ const savePath = msg.savePath
977
+ if (viewId === undefined || typeof url !== 'string' || typeof savePath !== 'string') {
978
+ throw new Error('download missing viewId/url/savePath')
979
+ }
980
+ const win = windowOfView(viewId)
981
+ const entry = win?.views.get(viewId)
982
+ if (win === undefined || entry === undefined) throw new Error(`download: unknown view ${viewId}`)
983
+ // Fetch the URL inside the page context (keeps cookies/login), read
984
+ // the body as base64, and write the file HERE — the body never
985
+ // crosses the RPC line protocol, so large downloads cannot balloon
986
+ // the parent's memory or hit the single-line cap. This also avoids
987
+ // Electron's download pipeline entirely (CDP debugger attach can
988
+ // interfere with will-download).
989
+ // Bounded like every other op. The evaluate awaits a page-side fetch, so a slow or
990
+ // unresponsive server held the serial queue open forever: handle() never settled,
991
+ // every later op queued behind it, and the parent's plain timeout does not restart
992
+ // the host.
993
+ const result = await withTimeout(
994
+ entry.webContentsView.webContents.debugger.sendCommand('Runtime.evaluate', {
995
+ // Stream the body through a reader so the size cap is enforced as
996
+ // bytes arrive — never buffer an unbounded download into memory
997
+ // before checking the limit (a huge URL would otherwise OOM the
998
+ // renderer). The declared Content-Length short-circuits large files
999
+ // before any body is read.
1000
+ expression: `(async () => {
1001
+ const r = await fetch(${JSON.stringify(url)}, { credentials: 'include' })
1002
+ if (!r.ok) throw new Error('HTTP ' + r.status)
1003
+ const declared = Number(r.headers.get('content-length') || 0)
1004
+ if (declared > ${String(MAX_DOWNLOAD_BYTES)}) throw new Error('download too large (limit ' + ${String(MAX_DOWNLOAD_BYTES)} + ' bytes, declared ' + declared + ')')
1005
+ if (!r.body || typeof r.body.getReader !== 'function') {
1006
+ const b = await r.arrayBuffer()
1007
+ const bytes = new Uint8Array(b)
1008
+ if (bytes.length > ${String(MAX_DOWNLOAD_BYTES)}) throw new Error('download too large (limit ' + ${String(MAX_DOWNLOAD_BYTES)} + ' bytes, got ' + bytes.length + ')')
1009
+ let bin = ''
1010
+ for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000))
1011
+ return btoa(bin)
1012
+ }
1013
+ const reader = r.body.getReader()
1014
+ const chunks = []
1015
+ let total = 0
1016
+ for (;;) {
1017
+ const { done, value } = await reader.read()
1018
+ if (done) break
1019
+ total += value.length
1020
+ if (total > ${String(MAX_DOWNLOAD_BYTES)}) {
1021
+ await reader.cancel()
1022
+ throw new Error('download too large (limit ' + ${String(MAX_DOWNLOAD_BYTES)} + ' bytes, got ' + total + ')')
1023
+ }
1024
+ chunks.push(value)
1025
+ }
1026
+ const bytes = new Uint8Array(total)
1027
+ let off = 0
1028
+ for (const c of chunks) { bytes.set(c, off); off += c.length }
1029
+ let bin = ''
1030
+ for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000))
1031
+ return btoa(bin)
1032
+ })()`,
1033
+ awaitPromise: true,
1034
+ returnByValue: true,
1035
+ }) as Promise<{ result?: { value?: unknown }; exceptionDetails?: { exception?: { description?: string } } }>,
1036
+ COMMAND_TIMEOUT_MS,
1037
+ 'download evaluate',
1038
+ )
1039
+ const value = (result as { result?: { value?: unknown } }).result?.value
1040
+ if (typeof value !== 'string') {
1041
+ const detail = (result as { exceptionDetails?: { exception?: { description?: string } } }).exceptionDetails
1042
+ throw new Error(`download failed: ${detail?.exception?.description ?? 'no data'}`)
1043
+ }
1044
+ writeFileNoReplace(savePath, Buffer.from(value, 'base64'))
1045
+ reply(msg.id, { ok: true, result: { path: savePath } })
1046
+ return
1047
+ }
1048
+ case 'flushAuth': {
1049
+ const viewId = msg.viewId
1050
+ if (viewId === undefined) throw new Error('flushAuth missing viewId')
1051
+ const win = windowOfView(viewId)
1052
+ const entry = win?.views.get(viewId)
1053
+ if (win === undefined || entry === undefined) throw new Error(`flushAuth: unknown view ${viewId}`)
1054
+ // Export the session's cookies so login state can be saved/restored
1055
+ // across browser hosts (or shared with another machine).
1056
+ //
1057
+ // Scoped to this view's own page. The jar is SHARED on purpose: views here are built
1058
+ // without a partition and every window drives the same browser, so signing in once
1059
+ // works everywhere. What must not be shared is the HANDING OVER — an unfiltered read
1060
+ // would put every domain every task has visited, plus whatever the human is signed
1061
+ // into, in front of one task's caller. Least exposure, not isolation. An unknown page
1062
+ // refuses rather than widening.
1063
+ //
1064
+ // Bounded like every other op: a renderer that stops answering here would hold the
1065
+ // serial queue forever, and the parent's plain timeout does not restart the host.
1066
+ const pageUrl = entry.webContentsView.webContents.getURL()
1067
+ if (pageUrl === '' || pageUrl === 'about:blank') {
1068
+ throw new Error('flushAuth: this view has no page loaded, so the cookie scope is unknown — reading everything would expose other sessions')
1069
+ }
1070
+ const cookies = await withTimeout(
1071
+ entry.webContentsView.webContents.session.cookies.get({ url: pageUrl }),
1072
+ COMMAND_TIMEOUT_MS,
1073
+ 'cookies.get',
1074
+ )
1075
+ const exported = cookies.map(c => {
1076
+ // Electron types the cookie domain as optional; a missing domain
1077
+ // cannot be exported meaningfully, so default to '' (matches the
1078
+ // shim's string typing and keeps the export shape stable).
1079
+ const domain = c.domain ?? ''
1080
+ const host = domain.startsWith('.') ? domain.slice(1) : domain
1081
+ // IPv6 literal domains need brackets in a URL (e.g. http://[::1]/).
1082
+ const hostPart = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host
1083
+ return {
1084
+ url: `http${c.secure ? 's' : ''}://${hostPart}${c.path}`,
1085
+ name: c.name,
1086
+ value: c.value,
1087
+ domain,
1088
+ path: c.path,
1089
+ secure: c.secure,
1090
+ httpOnly: c.httpOnly,
1091
+ expirationDate: c.expirationDate,
1092
+ }
1093
+ })
1094
+ reply(msg.id, { ok: true, result: { cookies: exported } })
1095
+ return
1096
+ }
1097
+ case 'restoreAuth': {
1098
+ const viewId = msg.viewId
1099
+ const cookies = msg.cookies
1100
+ if (viewId === undefined) throw new Error('restoreAuth missing viewId')
1101
+ const win = windowOfView(viewId)
1102
+ const entry = win?.views.get(viewId)
1103
+ if (win === undefined || entry === undefined) throw new Error(`restoreAuth: unknown view ${viewId}`)
1104
+ if (!Array.isArray(cookies)) throw new Error('restoreAuth missing cookies array')
1105
+ let restored = 0
1106
+ for (const c of cookies as Array<{ url?: string; name?: string; value?: string; domain?: string; path?: string; secure?: boolean; httpOnly?: boolean; expirationDate?: number }>) {
1107
+ if (typeof c.url !== 'string' || typeof c.name !== 'string' || typeof c.value !== 'string') continue
1108
+ // Bounded per cookie: this runs once for every cookie, so a single hang held the
1109
+ // serial queue open forever with no path to recovery.
1110
+ await withTimeout(
1111
+ entry.webContentsView.webContents.session.cookies.set({
1112
+ url: c.url,
1113
+ name: c.name,
1114
+ value: c.value,
1115
+ ...typeof c.domain === 'string' ? { domain: c.domain } : {},
1116
+ ...typeof c.path === 'string' ? { path: c.path } : {},
1117
+ ...typeof c.secure === 'boolean' ? { secure: c.secure } : {},
1118
+ ...typeof c.httpOnly === 'boolean' ? { httpOnly: c.httpOnly } : {},
1119
+ ...typeof c.expirationDate === 'number' ? { expirationDate: c.expirationDate } : {},
1120
+ }),
1121
+ COMMAND_TIMEOUT_MS,
1122
+ 'cookies.set',
1123
+ )
1124
+ restored++
1125
+ }
1126
+ reply(msg.id, { ok: true, result: { restored } })
1127
+ return
1128
+ }
1129
+ default:
1130
+ throw new Error(`unknown op ${op}`)
1131
+ }
1132
+ } catch (error) {
1133
+ reply(msg.id, { ok: false, err: String(error) })
1134
+ }
1135
+ }
1136
+
1137
+ /**
1138
+ * Chromium's native-window occlusion tracker (Windows only) asks DWM whether a
1139
+ * window is covered by another window and, when it is, moves the WebContents to
1140
+ * `Visibility::HIDDEN`. That is the wrong model for this host: the shared
1141
+ * browser window normally sits *behind* whatever the human is working in, and
1142
+ * that is exactly the state the agent drives it from. A hidden WebContents
1143
+ * produces no frames at all (`requestAnimationFrame` never fires) and
1144
+ * `RenderWidgetHostImpl::CanReceiveInput()` returns false, so every
1145
+ * `Input.dispatchMouseEvent`/`dispatchKeyEvent` sent over CDP is dropped on the
1146
+ * floor while the CDP call itself still answers `{}` — clicks and keys that
1147
+ * silently do nothing, with no error anywhere. Keep the window's visibility
1148
+ * state application-controlled instead; the parent already shows/raises views
1149
+ * explicitly, and `webContentsView.setVisible()` remains the single source of
1150
+ * truth for whether a view renders.
1151
+ */
1152
+ function keepWindowsNonOccluding(): void {
1153
+ if (process.platform !== 'win32') return
1154
+ const DISABLED = 'CalculateNativeWinOcclusion'
1155
+ const current = app.commandLine.getSwitchValue('disable-features') ?? ''
1156
+ const features = current
1157
+ .split(',')
1158
+ .map(part => part.trim())
1159
+ .filter(part => part !== '')
1160
+ if (!features.includes(DISABLED)) features.push(DISABLED)
1161
+ app.commandLine.appendSwitch('disable-features', features.join(','))
1162
+ }
1163
+ keepWindowsNonOccluding()
1164
+
1165
+
1166
+ // ---------------------------------------------------------------------------
1167
+ // Human reference entries (design §3.1 / §11.3): ONE owner per page.
1168
+ // A typed preload gives the page a narrow intent channel; the page-side
1169
+ // overlay is low-trust and never receives activeTab/screenshot authority.
1170
+ // ---------------------------------------------------------------------------
1171
+ const REFERENCE_PRELOAD = `const { contextBridge, ipcRenderer } = require('electron')
1172
+ try {
1173
+ contextBridge.exposeInMainWorld('__dshRef', {
1174
+ intent: payload => ipcRenderer.send('dsh-reference-intent', payload),
1175
+ })
1176
+ } catch (error) { /* another preload already owns this name */ }
1177
+ `
1178
+ const REFERENCE_PRELOAD_PATH = join(TOOLBAR_DIR, 'reference-preload.js')
1179
+
1180
+ function isToolbarContents(contents: import('electron').WebContents): boolean {
1181
+ try { return contents.getURL().endsWith('/toolbar.html') } catch { return false }
1182
+ }
1183
+
1184
+ /** Find the session/window id whose view owns these webContents. */
1185
+ function windowIdForContents(contents: import('electron').WebContents): string | undefined {
1186
+ for (const [key, win] of windows) {
1187
+ for (const entry of win.views.values()) {
1188
+ try {
1189
+ if (entry.webContentsView.webContents === contents) return key
1190
+ } catch { /* view was destroyed mid-iteration */ }
1191
+ }
1192
+ }
1193
+ return undefined
1194
+ }
1195
+
1196
+ /** Install the single merged context menu and the resident selection entry. */
1197
+ function attachReferenceEntry(contents: import('electron').WebContents): void {
1198
+ if (isToolbarContents(contents)) return
1199
+ contents.on('context-menu', (_event, params) => {
1200
+ const windowId = windowIdForContents(contents)
1201
+ if (windowId === undefined) return
1202
+ // The browser's ordinary edit items are kept in the SAME menu, so no second
1203
+ // adapter can pop another one over it (design §3.1:59). The real params
1204
+ // decide which reference actions exist, and the target travels with the
1205
+ // action so a collapsed selection cannot change what was clicked (§3.2/§3.3).
1206
+ const hasSelection = typeof params.selectionText === 'string' && params.selectionText.trim() !== ''
1207
+ const mediaType = typeof params.mediaType === 'string' ? params.mediaType : undefined
1208
+ const template = referenceMenuTemplate({
1209
+ hasSelection,
1210
+ ...mediaType !== undefined ? { mediaType } : {},
1211
+ }).map(item => {
1212
+ if (item.kind === 'separator') return { type: 'separator' as const }
1213
+ if (item.kind === 'role') {
1214
+ if (item.role === undefined) return { type: 'separator' as const }
1215
+ return { role: item.role, label: item.label }
1216
+ }
1217
+ const target = item.target === undefined ? undefined : {
1218
+ kind: item.target,
1219
+ ...item.target === 'image' && typeof params.srcURL === 'string' && params.srcURL !== ''
1220
+ ? { srcUrl: params.srcURL } : {},
1221
+ ...Number.isFinite(params.x) ? { x: params.x } : {},
1222
+ ...Number.isFinite(params.y) ? { y: params.y } : {},
1223
+ }
1224
+ return {
1225
+ id: item.id,
1226
+ label: item.label,
1227
+ click: () => sendUserAction({
1228
+ type: 'capture-reference', windowId, entry: 'native-menu',
1229
+ ...target !== undefined ? { target } : {},
1230
+ }),
1231
+ }
1232
+ })
1233
+ try { Menu.buildFromTemplate(template).popup() } catch (error) {
1234
+ process.stderr.write(`[dsh-browser host] reference menu failed: ${String(error)}\n`)
1235
+ }
1236
+ })
1237
+ contents.on('ipc-message', (_event, channel, ...args) => {
1238
+ if (channel !== 'dsh-reference-intent') return
1239
+ const intent = args[0] as Record<string, unknown> | undefined
1240
+ if (intent === undefined || intent.type !== REFERENCE_INTENT_CHANNEL) return
1241
+ // isTrusted is deliberately NOT read: a page overlay is a low-trust entry.
1242
+ const windowId = windowIdForContents(contents)
1243
+ if (windowId === undefined) return
1244
+ // The page trims its own note; the host re-bounds it because a page is
1245
+ // low-trust, and ignores anything that is not a string.
1246
+ const rawComment = typeof intent.comment === 'string' ? intent.comment.trim() : ''
1247
+ const comment = rawComment.slice(0, MAX_REFERENCE_COMMENT)
1248
+ // The bar freezes the selection text before the comment field takes focus
1249
+ // (focusing it collapses the page selection). Re-bound here: a page is
1250
+ // low-trust, and this string becomes the locator when the live selection is
1251
+ // already gone.
1252
+ const rawSelection = typeof intent.selectionText === 'string' ? intent.selectionText : ''
1253
+ const selectionText = rawSelection.trim().slice(0, MAX_REFERENCE_TEXT)
1254
+ // The bar freezes the complete ordered capture before its comment field
1255
+ // takes focus. Bound and shape-check it here: a page is low-trust.
1256
+ const capture = validateFrozenCapture(intent.capture)
1257
+ sendUserAction({
1258
+ type: 'capture-reference', windowId, entry: 'page-overlay',
1259
+ ...comment !== '' ? { comment } : {},
1260
+ ...selectionText !== '' ? { selectionText } : {},
1261
+ ...capture !== undefined ? { capture } : {},
1262
+ })
1263
+ })
1264
+ contents.on('dom-ready', () => {
1265
+ if (isToolbarContents(contents)) return
1266
+ void contents.executeJavaScript(standaloneScript(overlayScript(), { label: hostMessages.zh.referenceLabel }))
1267
+ .catch(() => { /* an extension-managed page owns its own entry */ })
1268
+ })
1269
+ }
1270
+
1271
+ app.on('web-contents-created', (_event, contents) => {
1272
+ try { attachReferenceEntry(contents) } catch (error) {
1273
+ process.stderr.write(`[dsh-browser host] reference entry failed: ${String(error)}\n`)
1274
+ }
1275
+ })
1276
+
1277
+ /** Remove the overlay on plugin shutdown; the disposer clears every listener. */
1278
+ export function disposeReferenceEntries(views: Iterable<import('electron').WebContents>): void {
1279
+ for (const contents of views) {
1280
+ try { void contents.executeJavaScript(standaloneScript(overlayDisposeScript())) } catch { /* gone */ }
1281
+ }
1282
+ }
1283
+
1284
+ /**
1285
+ * Electron entry: connect back to the parent's RPC server (port from
1286
+ * `--rpc-port`) and serve line-delimited JSON-RPC. `ELECTRON_RUN_AS_NODE` is
1287
+ * cleared by the parent so `require('electron')` works; this file is loaded as
1288
+ * the app entry so `app` is available immediately.
1289
+ */
1290
+ void app.whenReady().then(() => {
1291
+ // One narrow preload for every webContents in this session. It only exposes
1292
+ // an intent sender; no file, command or CDP capability crosses the boundary.
1293
+ try {
1294
+ mkdirSync(TOOLBAR_DIR, { recursive: true })
1295
+ writeFileSync(REFERENCE_PRELOAD_PATH, REFERENCE_PRELOAD)
1296
+ // APPEND, never replace: another part of the shell may already own a
1297
+ // preload, and `setPreloads` takes the whole list.
1298
+ const existing = session.defaultSession.getPreloads()
1299
+ if (!existing.includes(REFERENCE_PRELOAD_PATH)) {
1300
+ session.defaultSession.setPreloads([...existing, REFERENCE_PRELOAD_PATH])
1301
+ }
1302
+ } catch (error) {
1303
+ process.stderr.write(`[dsh-browser host] reference preload unavailable: ${String(error)}\n`)
1304
+ }
1305
+ const portArg = process.argv.indexOf('--rpc-port')
1306
+ const port = portArg >= 0 ? Number(process.argv[portArg + 1]) : NaN
1307
+ if (!Number.isFinite(port)) {
1308
+ process.stderr.write('[dsh-browser host] missing --rpc-port\n')
1309
+ app.exit(1)
1310
+ return
1311
+ }
1312
+ const socket = createConnection({ host: LOOPBACK_IPV4, port })
1313
+ rpcSocket = socket
1314
+ socket.setEncoding('utf8')
1315
+ // Prove we know the parent's spawn token before anything else; the parent
1316
+ // refuses a connection whose first line is not this hello. The token is
1317
+ // written to stdin at spawn (moments after process start, long before
1318
+ // Electron's whenReady resolves), but guard the ordering anyway: sending an
1319
+ // empty hello would read as a spoofed connection and tear the session down.
1320
+ const writeHello = (): void => {
1321
+ socket.write(JSON.stringify({ id: 0, op: 'hello', token: RPC_TOKEN }) + '\n')
1322
+ }
1323
+ if (RPC_TOKEN !== '') {
1324
+ // Either stdin already delivered a line (it wins) or env supplied the fallback.
1325
+ writeHello()
1326
+ } else {
1327
+ // Neither yet: wait for stdin's first line with a bounded fallback, then send whatever
1328
+ // we have — an empty hello is refused by the parent, which then fails cleanly. The
1329
+ // reader is the module-level one, NOT a second createInterface on the same stream: two
1330
+ // readers of one stdin both consume its lines, so the second one never saw the token.
1331
+ const fallback = setTimeout(() => writeHello(), 2_000)
1332
+ if (stdinLines !== undefined) {
1333
+ const send = (): void => { clearTimeout(fallback); writeHello() }
1334
+ stdinLines.once('line', send)
1335
+ stdinLines.once('close', send)
1336
+ }
1337
+ }
1338
+ const rl = createRpcLineReader(socket, error => {
1339
+ process.stderr.write(`[dsh-browser host] socket error: ${String(error)}\n`)
1340
+ })
1341
+ // Handle messages STRICTLY in order. Ops depend on each other completing:
1342
+ // a `command` for a view must not overtake the `createView` that makes it,
1343
+ // and the parent's present-barrier (`showView` then `ping`) is only
1344
+ // meaningful if the child cannot answer the ping mid-show. The previous
1345
+ // fire-and-forget loop let all of them race, which is how a fresh tab's
1346
+ // first click could be dispatched before its view was ever on screen.
1347
+ let queue: Promise<void> = Promise.resolve()
1348
+ rl.on('line', line => {
1349
+ const text = line.trim()
1350
+ if (text === '') return
1351
+ let msg: { id: number; op?: string; viewId?: string; windowId?: string; method?: string; params?: Record<string, unknown>; url?: string; savePath?: string; cookies?: unknown[]; label?: string; format?: string; quality?: number; maxWidth?: number; maxHeight?: number; message?: string; quiet?: boolean; needSurface?: boolean }
1352
+ try {
1353
+ msg = JSON.parse(text) as typeof msg
1354
+ } catch {
1355
+ return // non-protocol noise
1356
+ }
1357
+ if (typeof msg.id !== 'number' || typeof msg.op !== 'string') return
1358
+ // Bind the narrowed op now: the check above does not survive into the
1359
+ // deferred callback (msg is a mutable binding).
1360
+ const op = msg.op
1361
+ queue = queue.then(() => handle(op, msg)).catch(() => { /* reply already sent inside handle */ })
1362
+ })
1363
+ // The parent owns our lifetime: when it closes the socket (dispose) or dies
1364
+ // without cleanup, exit so no zombie Electron window is left behind.
1365
+ socket.on('close', () => {
1366
+ process.stderr.write('[dsh-browser host] parent connection closed, exiting\n')
1367
+ // A normal quit, not `app.exit(0)`. exit() skips before-quit/will-quit and does not wait
1368
+ // for Chromium to finish writing the profile — the leveldb files holding cookies and site
1369
+ // data. This path runs on every dispose, and a session that has just logged in is exactly
1370
+ // when the profile holds unwritten state, so a hard exit could leave a half-written leveldb
1371
+ // behind, which is what makes a browser profile fail to open on the next launch.
1372
+ app.quit()
1373
+ // Belt and braces: the parent is already gone, so there is nothing left to serve. If a
1374
+ // listener or a window blocks the quit, forcing the exit after a grace period is still
1375
+ // strictly better than an orphaned Electron window the user has to close by hand.
1376
+ const force = setTimeout(() => app.exit(0), 5000)
1377
+ force.unref()
1378
+ })
1379
+ // Keep the process alive until the parent closes the socket or kills us.
1380
+ })
1381
+
1382
+ // Diagnostics go to stderr, which the parent never parses as protocol.
1383
+ process.on('uncaughtException', error => {
1384
+ process.stderr.write(`[dsh-browser host] uncaught: ${String(error)}\n`)
1385
+ })