dsh-builtin-browser 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/README.en.md +89 -0
  3. package/browser-extension/constants.mjs +20 -0
  4. package/browser-extension/controller.mjs +293 -0
  5. package/browser-extension/locales.mjs +15 -0
  6. package/browser-extension/manifest.json +12 -0
  7. package/browser-extension/options.html +14 -0
  8. package/browser-extension/options.mjs +9 -0
  9. package/browser-extension/permission-guard.mjs +13 -0
  10. package/browser-extension/worker.mjs +74 -0
  11. package/desktop-bridge/desktop-identity.json +10 -2
  12. package/desktop-bridge/install.mjs +28 -2
  13. package/docs/issue-replies-2026-11-28.md +141 -0
  14. package/dsh-host-patch/apply.mjs +1 -1
  15. package/dsh-host-patch/rc3.json +4 -4
  16. package/dsh-host-patch/rc5.json +4 -4
  17. package/dsh-host-patch/v023-alpha2.json +2 -2
  18. package/lib/browser-electron/bridge-status.js +24 -1
  19. package/lib/browser-electron/desktop-identity.js +47 -8
  20. package/lib/client.js +2 -1
  21. package/native-host/install.mjs +5 -0
  22. package/package.json +20 -2
  23. package/scripts/build-client.mjs +305 -0
  24. package/scripts/build.mjs +69 -0
  25. package/scripts/bundle-host.mjs +28 -0
  26. package/scripts/fix-exports.mjs +40 -0
  27. package/scripts/install-electron.mjs +101 -0
  28. package/scripts/pack.mjs +99 -0
  29. package/scripts/publish-manifest.mjs +56 -0
  30. package/scripts/verify-exports.mjs +58 -0
  31. package/scripts/verify-preview-sdk.mjs +93 -0
  32. package/skills/dsh-builtin-browser/SKILL.md +98 -0
  33. package/skills/dsh-builtin-browser/references/batch.md +68 -0
  34. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  35. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  36. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  37. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  38. package/skills/dsh-debug-host/SKILL.md +56 -0
  39. package/skills/dsh-debug-self/SKILL.md +50 -0
  40. package/src/bridge-compatibility.ts +39 -0
  41. package/src/browser/anti-bot.ts +251 -0
  42. package/src/browser/deep-dom.ts +40 -0
  43. package/src/browser/handles.ts +89 -0
  44. package/src/browser/runtime.ts +578 -0
  45. package/src/browser/takeover-target.ts +45 -0
  46. package/src/browser/types.ts +870 -0
  47. package/src/browser-electron/authenticated-route.ts +109 -0
  48. package/src/browser-electron/automatic-maintenance.ts +736 -0
  49. package/src/browser-electron/bridge-auto.ts +159 -0
  50. package/src/browser-electron/bridge-connection.ts +386 -0
  51. package/src/browser-electron/bridge-endpoint.ts +129 -0
  52. package/src/browser-electron/bridge-install.ts +290 -0
  53. package/src/browser-electron/bridge-maintenance.ts +189 -0
  54. package/src/browser-electron/bridge-status.ts +412 -0
  55. package/src/browser-electron/desktop-bridge-host.ts +253 -0
  56. package/src/browser-electron/desktop-identity.ts +400 -0
  57. package/src/browser-electron/desktop-shell.ts +100 -0
  58. package/src/browser-electron/document-readiness.ts +45 -0
  59. package/src/browser-electron/electron-provision.ts +347 -0
  60. package/src/browser-electron/entry.ts +1378 -0
  61. package/src/browser-electron/ephemeral-profile.ts +189 -0
  62. package/src/browser-electron/extension-browser.ts +230 -0
  63. package/src/browser-electron/extension-setup.ts +67 -0
  64. package/src/browser-electron/file-write.ts +31 -0
  65. package/src/browser-electron/foreground-watch.ts +142 -0
  66. package/src/browser-electron/guest-cookie-jar.ts +177 -0
  67. package/src/browser-electron/guest-cookie-store.ts +59 -0
  68. package/src/browser-electron/guest-css-runtime.ts +76 -0
  69. package/src/browser-electron/guest-css.ts +68 -0
  70. package/src/browser-electron/guest-route.ts +716 -0
  71. package/src/browser-electron/guest-runtime.ts +408 -0
  72. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  73. package/src/browser-electron/guest-storage.ts +120 -0
  74. package/src/browser-electron/history-store.ts +224 -0
  75. package/src/browser-electron/host-main.ts +1385 -0
  76. package/src/browser-electron/host-patch-maintenance.ts +121 -0
  77. package/src/browser-electron/http-body.ts +65 -0
  78. package/src/browser-electron/json-reply.ts +47 -0
  79. package/src/browser-electron/maintenance-broker.ts +166 -0
  80. package/src/browser-electron/maintenance-lifecycle.ts +91 -0
  81. package/src/browser-electron/maintenance-route.ts +68 -0
  82. package/src/browser-electron/missing-system-browser.ts +114 -0
  83. package/src/browser-electron/open-slot.ts +49 -0
  84. package/src/browser-electron/paths.ts +25 -0
  85. package/src/browser-electron/preferred-browser.ts +130 -0
  86. package/src/browser-electron/preview-route.ts +215 -0
  87. package/src/browser-electron/process-ownership.ts +174 -0
  88. package/src/browser-electron/process.ts +23 -0
  89. package/src/browser-electron/profile-checkpoint.ts +187 -0
  90. package/src/browser-electron/profile-command.ts +47 -0
  91. package/src/browser-electron/profile-extension.ts +129 -0
  92. package/src/browser-electron/profile-lease.ts +211 -0
  93. package/src/browser-electron/profile-residue.ts +49 -0
  94. package/src/browser-electron/provider-core.ts +1107 -0
  95. package/src/browser-electron/provider-interaction.ts +1034 -0
  96. package/src/browser-electron/provider-media.ts +589 -0
  97. package/src/browser-electron/provider-navigation.ts +323 -0
  98. package/src/browser-electron/provider-observation.ts +664 -0
  99. package/src/browser-electron/provider-tabs.ts +372 -0
  100. package/src/browser-electron/provider.ts +666 -0
  101. package/src/browser-electron/reference-route.ts +598 -0
  102. package/src/browser-electron/remote-host.ts +1538 -0
  103. package/src/browser-electron/rpc-input.ts +13 -0
  104. package/src/browser-electron/rpc-ops.ts +41 -0
  105. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  106. package/src/browser-electron/runtime-route.ts +105 -0
  107. package/src/browser-electron/runtime-status.ts +309 -0
  108. package/src/browser-electron/settings-route.ts +64 -0
  109. package/src/browser-electron/settings-store.ts +593 -0
  110. package/src/browser-electron/shortcuts-route.ts +112 -0
  111. package/src/browser-electron/sidebar-only-host.ts +300 -0
  112. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  113. package/src/browser-electron/system-browser.ts +1850 -0
  114. package/src/browser-electron/tauri-host.ts +194 -0
  115. package/src/browser-electron/timing.ts +16 -0
  116. package/src/browser-electron/virtual-cursor.ts +162 -0
  117. package/src/browser-electron/windows-system.ts +24 -0
  118. package/src/browser-reference/delivery.ts +384 -0
  119. package/src/browser-reference/entry.ts +631 -0
  120. package/src/browser-reference/export.ts +339 -0
  121. package/src/browser-reference/import.ts +303 -0
  122. package/src/browser-reference/page-script.ts +1537 -0
  123. package/src/browser-reference/service.ts +1346 -0
  124. package/src/browser-reference/store.ts +172 -0
  125. package/src/browser-reference/text-quote.ts +219 -0
  126. package/src/browser-reference/types.ts +195 -0
  127. package/src/browser-reference/visible.ts +367 -0
  128. package/src/browser-reference/web-sources.ts +106 -0
  129. package/src/client/apply-guard.ts +22 -0
  130. package/src/client/browser/BrowserController.ts +693 -0
  131. package/src/client/browser/BrowserFrame.ts +78 -0
  132. package/src/client/browser/BrowserNavigation.ts +169 -0
  133. package/src/client/browser/BrowserPage.ts +23 -0
  134. package/src/client/browser/BrowserPersistence.ts +44 -0
  135. package/src/client/browser/IframeImpl.ts +182 -0
  136. package/src/client/browser/child-tabs.ts +14 -0
  137. package/src/client/browser/frame-history.ts +125 -0
  138. package/src/client/browser/frame-state.ts +27 -0
  139. package/src/client/browser/iframe-reference.ts +67 -0
  140. package/src/client/browser/initialization.ts +262 -0
  141. package/src/client/browser/omnibox.ts +243 -0
  142. package/src/client/browser/store.ts +38 -0
  143. package/src/client/browser/takeover-channel.ts +72 -0
  144. package/src/client/browser/url.ts +46 -0
  145. package/src/client/browser/web-reference-source.ts +56 -0
  146. package/src/client/css-modules.d.ts +4 -0
  147. package/src/client/definition.tsx +36 -0
  148. package/src/client/electron/ElectronWebViewImpl.ts +371 -0
  149. package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
  150. package/src/client/electron/NativeChildPresentation.ts +53 -0
  151. package/src/client/electron/NativeViewPage.ts +265 -0
  152. package/src/client/electron/pages.ts +23 -0
  153. package/src/client/electron/reference-overlay.ts +53 -0
  154. package/src/client/electron/workspace.ts +33 -0
  155. package/src/client/index.ts +333 -0
  156. package/src/client/locales.ts +860 -0
  157. package/src/client/pages.ts +28 -0
  158. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  159. package/src/client/reference/client/draft-reference.ts +167 -0
  160. package/src/client/reference/client/index.ts +7 -0
  161. package/src/client/reference/client/ordered-submission.ts +108 -0
  162. package/src/client/reference/client/pending-delivery.ts +216 -0
  163. package/src/client/reference/client/plugin.ts +208 -0
  164. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  165. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  166. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  167. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  168. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  169. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  170. package/src/client/reference/client/production/assembly.ts +447 -0
  171. package/src/client/reference/client/production/asset-store.ts +144 -0
  172. package/src/client/reference/client/production/availability.ts +72 -0
  173. package/src/client/reference/client/production/bytes.ts +36 -0
  174. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  175. package/src/client/reference/client/production/delivery-client.ts +211 -0
  176. package/src/client/reference/client/production/draft-adapter.ts +512 -0
  177. package/src/client/reference/client/production/http-transport.ts +212 -0
  178. package/src/client/reference/client/production/production-submission.ts +70 -0
  179. package/src/client/reference/client/production/protocol.ts +234 -0
  180. package/src/client/reference/client/production/reference-card.ts +240 -0
  181. package/src/client/reference/client/production/reference-labels.ts +29 -0
  182. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  183. package/src/client/reference/client/production/reveal.ts +215 -0
  184. package/src/client/reference/client/production/runtime.ts +1056 -0
  185. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  186. package/src/client/reference/client/production/source-marker.ts +99 -0
  187. package/src/client/reference/client/production/source-opener.ts +55 -0
  188. package/src/client/reference/client/production/styles.ts +104 -0
  189. package/src/client/reference/client/production/user-text-rule.ts +67 -0
  190. package/src/client/reference/client/reveal.ts +109 -0
  191. package/src/client/reference/client/scheme.ts +114 -0
  192. package/src/client/reference/client/session-schedule.ts +36 -0
  193. package/src/client/reference/client/types.ts +168 -0
  194. package/src/client/reference/css-modules.d.ts +4 -0
  195. package/src/client/reference/index.ts +11 -0
  196. package/src/client/reference-capture-owner.ts +162 -0
  197. package/src/client/reference-intents.ts +36 -0
  198. package/src/client/settings/index.ts +42 -0
  199. package/src/client/settings/mount-guard.ts +31 -0
  200. package/src/client/settings/panel.ts +2773 -0
  201. package/src/client/shortcut-open.ts +30 -0
  202. package/src/client/startpage/binding.ts +99 -0
  203. package/src/client/startpage/controller.ts +300 -0
  204. package/src/client/startpage/model.ts +279 -0
  205. package/src/client/view/Browser.module.css +751 -0
  206. package/src/client/view/BrowserBody.tsx +315 -0
  207. package/src/client/view/BrowserPresentation.ts +9 -0
  208. package/src/client/view/BrowserTitle.tsx +17 -0
  209. package/src/client/view/IframePresentation.ts +365 -0
  210. package/src/client/view/StartPage.tsx +598 -0
  211. package/src/client/view/TakeoverBanner.tsx +21 -0
  212. package/src/compat/host-features.ts +92 -0
  213. package/src/index.ts +110 -0
  214. package/src/reference-owner.ts +5 -0
  215. package/src/reference-page.ts +9 -0
  216. package/src/reference-source.ts +3 -0
  217. package/src/reference-text.ts +219 -0
  218. package/src/startpage-settings.ts +103 -0
  219. package/src/startpage.ts +71 -0
  220. package/src/takeover-protocol.ts +28 -0
  221. package/src/tool-browser/block-recovery.ts +85 -0
  222. package/src/tool-browser/code-tool.ts +555 -0
  223. package/src/tool-browser/code-worker.ts +725 -0
  224. package/src/tool-browser/element-fields.ts +167 -0
  225. package/src/tool-browser/errors.ts +40 -0
  226. package/src/tool-browser/index.ts +265 -0
  227. package/src/tool-browser/page-probe.ts +675 -0
  228. package/src/tool-browser/panel-page.ts +126 -0
  229. package/src/tool-browser/probe-client.ts +183 -0
  230. package/src/tool-browser/screenshot-annotations.ts +131 -0
  231. package/src/tool-browser/screenshot-image.ts +49 -0
  232. package/src/tool-browser/state.ts +375 -0
  233. package/src/tool-browser/takeover.ts +199 -0
  234. package/src/tool-browser/tools-debug.ts +806 -0
  235. package/src/tool-browser/tools-interaction.ts +956 -0
  236. package/src/tool-browser/tools-navigation.ts +786 -0
  237. package/src/tool-browser/tools-observation.ts +474 -0
  238. package/src/tool-browser/tools-reference.ts +294 -0
  239. package/src/types/electron-shim.d.ts +144 -0
  240. package/src/types.ts +85 -0
  241. package/src/web-guest.ts +35 -0
  242. package/tools/accept-desktop.mjs +148 -0
  243. package/dist/client.d.cts +0 -516
  244. package/dist/client.d.mts +0 -516
  245. package/dist/index.cjs +0 -92
  246. package/dist/index.d.mts +0 -2960
  247. package/dist/index.mjs +0 -24
  248. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  249. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  250. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  251. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  252. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  253. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  254. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  255. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  256. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  257. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  258. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  259. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  260. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  261. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  262. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  263. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  264. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  265. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  266. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  267. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  268. package/dsh-host-patch/sources/manifest.json +0 -218
  269. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  270. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  271. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  272. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  273. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  274. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  275. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  276. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  277. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  278. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  279. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  280. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  281. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  282. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  283. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  284. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  285. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  286. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  287. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  288. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  289. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  290. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  291. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  292. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  293. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  294. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  295. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  296. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  297. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  298. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  299. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  300. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  301. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  302. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  303. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  304. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  305. package/dsh-host-patch/sources/series.json +0 -260
@@ -0,0 +1,666 @@
1
+ /**
2
+ * Electron-backed browser provider: `WebContentsView` sessions driven over
3
+ * `webContents.debugger` (CDP). The provider itself does not import Electron — it operates through the {@link ElectronBrowserViewHost} seam, which the
4
+ * desktop shell implements with real Electron objects. That keeps this
5
+ * package testable under plain Node and leaves the Electron dependency to the
6
+ * shell that owns the `BrowserWindow`.
7
+ * @module dsh-browser/browser-electron
8
+ */
9
+
10
+ import { hostMessages } from '../../assets/browser-messages.mjs'
11
+ import { dispatchReferenceCaptureAction } from '../browser-reference/service.ts'
12
+ import { MAX_REFERENCE_COMMENT, REFERENCE_INTENT_CHANNEL, overlayScript, standaloneScript } from '../browser-reference/entry.ts'
13
+ import { noticeScript, validateFrozenCapture } from '../browser-reference/page-script.ts'
14
+ import { randomUUID } from 'node:crypto'
15
+ import type { VisitedPage } from './history-store.ts'
16
+ import type { BrowserElementTarget, BrowserHistoryEntry, BrowserProvider, BrowserSessionId, BrowserScrollRequest } from '../browser/types.ts'
17
+ import { BrowserError } from '../browser/types.ts'
18
+ import { browserSessionHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId, type BrowserTabWireId } from '../browser/handles.ts'
19
+ import { PROVIDER_TIMEOUTS, withTimeout, handleSendEvaluate, type BrowserUserAction, type ElectronViewHandle, type Tab, type Session, type ElectronBrowserProviderConfig } from './provider-core.ts'
20
+ import { ProviderMedia } from './provider-media.ts'
21
+
22
+ export { ELECTRON_BROWSER_PROVIDER_ID, CDP_PAGE_CAPTURE_SCREENSHOT, layoutSize, toExportedCookies, toCdpCookie, CDP_RUNTIME_EVALUATE, CDP_PAGE_NAVIGATE, BROWSER_KEY_NAMES } from './provider-core.ts'
23
+ export type { ElectronBrowserViewHost, QuietRevealOptions, BrowserUserAction, ElectronViewHandle, ElectronBrowserProviderConfig, CdpNavigateParams, CdpMouseParams, CdpInsertTextParams, CdpEvaluateParams, PresentOptions, CommandOptions, ScreenshotOptions } from './provider-core.ts'
24
+
25
+ /**
26
+ * Consecutive failed evaluations after which the reference pump forgets an
27
+ * adopted sidebar tab. One or two misses are a navigation; five (≈6 s at the
28
+ * pump's 1.2 s tick) mean the page the human had is gone.
29
+ */
30
+ const DEAD_REFERENCE_TAB_MISSES = 5
31
+
32
+ /** How long a tab that stopped answering waits before the pump tries it again. */
33
+ const DEAD_REFERENCE_TAB_RETRY_MS = 15_000
34
+
35
+ /**
36
+ * Best-effort interrupt of a wedged page-script evaluation. `Runtime.evaluate`
37
+ * with `awaitPromise` can hold the renderer (and the target's debugger queue)
38
+ * behind a busy loop or a never-settling promise; terminating kills the
39
+ * running script so subsequent commands are not stuck forever. Fire-and-forget:
40
+ * if the interrupt itself hangs, it is ignored. Capped at
41
+ * MAX_PENDING_TERMINATIONS per view to prevent unbounded pending entries
42
+ * when the child is truly stuck.
43
+ * @param handle - the view handle to terminate in.
44
+ */
45
+ const pendingTerminations = new WeakMap<ElectronViewHandle, number>()
46
+
47
+ const MAX_PENDING_TERMINATIONS = 3
48
+
49
+ function terminatePage(handle: ElectronViewHandle): void {
50
+ const count = pendingTerminations.get(handle) ?? 0
51
+ if (count >= MAX_PENDING_TERMINATIONS) return
52
+ pendingTerminations.set(handle, count + 1)
53
+ void handle.sendCommand('Runtime.terminateExecution', undefined, { present: false, initialize: false }).finally(() => {
54
+ pendingTerminations.set(handle, Math.max(0, (pendingTerminations.get(handle) ?? 1) - 1))
55
+ }).catch(() => {})
56
+ }
57
+
58
+ /**
59
+ * Browser provider over Electron views. Sessions hold an ordered list of
60
+ * tabs; each tab is one view created by the host. The active tab receives
61
+ * every operation; switching tabs calls the host's optional `showView` and
62
+ * never loses state. Navigation is admitted only for HTTP(S) targets unless
63
+ * {@link ElectronBrowserProviderConfig.httpOnly} is disabled.
64
+ */
65
+ export class ElectronBrowserProvider extends ProviderMedia implements BrowserProvider {
66
+ /** Retire a provider after a carrier swap; its listeners must not act again. */
67
+ dispose(): void {
68
+ this.disposed = true
69
+ this.stopReferenceEntryPump()
70
+ }
71
+
72
+ /** Start the page-bar pump; idempotent, unref'd so it never holds the process. */
73
+ protected startReferenceEntryPump(): void {
74
+ if (this.host.referenceOverlayOwner === 'client' || this.referencePump !== undefined) return
75
+ this.referencePump = setInterval(() => { void this.pumpReferenceEntry() }, 1200)
76
+ this.referencePump.unref?.()
77
+ }
78
+
79
+ /** Stop the pump (session teardown / tests). */
80
+ stopReferenceEntryPump(): void {
81
+ if (this.referencePump === undefined) return
82
+ clearInterval(this.referencePump)
83
+ this.referencePump = undefined
84
+ }
85
+
86
+ /**
87
+ * Install the bar where it is missing and forward one confirmed intent.
88
+ *
89
+ * Re-injection is what makes this survive navigation: a new document has no
90
+ * `__dshRefOverlayInstalled`, so the next tick installs the bar again.
91
+ *
92
+ * One run at a time: `setInterval` fires again whether or not the previous
93
+ * run finished, and a page that stopped answering would otherwise stack CDP
94
+ * commands behind the wedged renderer on every tick.
95
+ */
96
+ private async pumpReferenceEntry(): Promise<void> {
97
+ if (this.referencePumping) return
98
+ this.referencePumping = true
99
+ try {
100
+ await this.adoptSidebarPageForReference().catch(() => undefined)
101
+ for (const session of [...this.sessions.values()]) {
102
+ if (this.host.referenceOverlayOwnerFor?.(session.id) === 'client') continue
103
+ for (const tab of [...session.tabs]) {
104
+ await this.pumpOneTab(session, tab)
105
+ // A tab is never dropped for being unreachable: the page is the
106
+ // person's own sidebar page, and the host excludes every page it
107
+ // adopted from later listings, so letting go of the handle would
108
+ // close our only route back to it.
109
+ }
110
+ }
111
+ } finally {
112
+ this.referencePumping = false
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Install or collect on one tab.
118
+ * @returns false when the page failed enough consecutive times to be gone.
119
+ */
120
+ private async pumpOneTab(session: Session, tab: Tab): Promise<boolean> {
121
+ if (tab.failure !== undefined) return false
122
+ // A page that stopped answering is retried on a slow timer instead of being
123
+ // dropped: navigations and renderer swaps both look like death for a moment.
124
+ if (tab.retryAt !== undefined && Date.now() < tab.retryAt) return true
125
+ try {
126
+ // One round-trip per tab: a missing bar answers "install"; otherwise the
127
+ // same evaluation hands back a confirmed intent.
128
+ const probe = await this.evaluateInTab(tab, [
129
+ 'window.__dshRefOverlayInstalled !== true ? "install"',
130
+ ': (window.__dshRefTake ? window.__dshRefTake() : null)',
131
+ ].join(''), PROVIDER_TIMEOUTS.evaluation)
132
+ tab.misses = 0
133
+ tab.retryAt = undefined
134
+ if (probe === 'install') {
135
+ await this.evaluateInTab(tab, standaloneScript(overlayScript(), {}), PROVIDER_TIMEOUTS.interaction)
136
+ return true
137
+ }
138
+ if (probe === null || probe === undefined) return true
139
+ try {
140
+ if (typeof probe !== 'object') throw new Error('reference intent is invalid')
141
+ const record = probe as Record<string, unknown>
142
+ if (record.type !== REFERENCE_INTENT_CHANNEL) throw new Error('reference intent channel is invalid')
143
+ const rawComment = typeof record.comment === 'string' ? record.comment.trim() : ''
144
+ const rawSelection = typeof record.selectionText === 'string' ? record.selectionText.trim() : ''
145
+ const capture = validateFrozenCapture(record.capture)
146
+ if (capture === undefined) throw new Error('reference intent has no captured content')
147
+ await this.handleUserAction({
148
+ type: 'capture-reference',
149
+ windowId: session.id,
150
+ entry: 'page-overlay',
151
+ ...rawComment !== '' ? { comment: rawComment.slice(0, MAX_REFERENCE_COMMENT) } : {},
152
+ ...rawSelection !== '' ? { selectionText: rawSelection } : {},
153
+ capture,
154
+ }, true)
155
+ } catch (error) {
156
+ this.referenceScan.lastError = 'capture refused: ' + (error instanceof Error ? error.message : String(error))
157
+ process.stderr.write(`[dsh-browser] ${this.referenceScan.lastError}\n`)
158
+ try {
159
+ await this.evaluateInTab(tab, standaloneScript(noticeScript(hostMessages.zh.referenceFailed)), PROVIDER_TIMEOUTS.evaluation)
160
+ } catch { /* The failure remains in host diagnostics when the guest disappears. */ }
161
+ }
162
+ return true
163
+ } catch {
164
+ // A tab mid-navigation has no execution context yet; the next tick retries.
165
+ // A page that keeps failing backs off instead of being forgotten: the
166
+ // handle is the only way back to a page this host adopted, and dropping it
167
+ // made the bar stop delivering for the rest of the conversation.
168
+ tab.misses = (tab.misses ?? 0) + 1
169
+ if (tab.misses >= DEAD_REFERENCE_TAB_MISSES) {
170
+ tab.misses = 0
171
+ tab.retryAt = Date.now() + DEAD_REFERENCE_TAB_RETRY_MS
172
+ }
173
+ return true
174
+ }
175
+ }
176
+
177
+ /** Forget one dead adopted tab; the conversation's next page starts a fresh session. */
178
+
179
+ /**
180
+ * What the sidebar reference entry is doing right now.
181
+ *
182
+ * Served on the reference route so "there is no selection bar on my page" has an
183
+ * answer that is not a guess: which conversation this process thinks it serves,
184
+ * whether a page was adopted, how many the shell reported, and the last refusal.
185
+ */
186
+ referenceStatus(): { readonly label?: string; readonly session?: string; readonly pages: number; readonly lastError?: string } {
187
+ return {
188
+ ...this.referenceScan.label === undefined ? {} : { label: this.referenceScan.label },
189
+ ...this.referenceSession === undefined ? {} : { session: this.referenceSession },
190
+ pages: this.referenceScan.pages,
191
+ ...this.referenceScan.lastError === undefined ? {} : { lastError: this.referenceScan.lastError },
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Usable when the host says it can back views (the self-hosted host probes
197
+ * for a usable Electron binary; the desktop shell is assumed usable).
198
+ */
199
+ available(): boolean {
200
+ return this.host.available?.() ?? true
201
+ }
202
+
203
+ /**
204
+ * Open a NEW browser session with its own view. Every call mints a fresh
205
+ * session id and backing view; per-task reuse is owned by the caller (the
206
+ * tool layer caches one session per DSH task). Sessions are isolated from
207
+ * each other: each keeps its own tabs, active tab, and history, and only
208
+ * the active tab of a session is made visible.
209
+ * @param label - optional human-readable label (e.g. the DSH task id) shown
210
+ * in the window title so a human can tell which task's page is visible.
211
+ */
212
+ open(label?: string): Promise<BrowserSessionId> {
213
+ // The label is the calling DSH task, and it is handed to the view as its owner: a host shared
214
+ // by several conversations (the desktop's) keeps one conversation's page out of another's on
215
+ // the strength of it, so it is not decoration.
216
+ const id = sessionWireId(browserSessionHandle(label || 'default', randomUUID()))
217
+ const tabId = tabWireId({ ...resolveSessionHandle(id), tab: randomUUID() })
218
+ const handle = this.host.createView(tabId)
219
+ // Group the session's views under its own window (one window per
220
+ // session), carrying the label for the window title. Hosts without
221
+ // groupView keep the shared-window behavior.
222
+ this.host.groupView?.(handle, id, label)
223
+ this.sessions.set(id, { id, label, tabs: [{ id: tabId, handle, url: '' }], activeIndex: 0, history: [], nextSeq: 1 })
224
+ return Promise.resolve(id)
225
+ }
226
+
227
+ protected async prepareCarrier(signal?: AbortSignal, scope?: BrowserSessionId): Promise<void> {
228
+ if (this.host.prepare === undefined) return
229
+ signal?.throwIfAborted()
230
+ try {
231
+ await withTimeout(this.host.prepare(scope), PROVIDER_TIMEOUTS.prepare, signal, 'browser: carrier launch timed out before navigating a guest')
232
+ this.carrierLaunchError = undefined
233
+ } catch (error) {
234
+ if (!signal?.aborted) this.carrierLaunchError = error
235
+ throw error
236
+ }
237
+ }
238
+
239
+ async bindPage(session: BrowserSessionId, pageId: BrowserTabWireId): Promise<void> {
240
+ const s = this.session(session)
241
+ if (this.host.adoptPage === undefined || !s.label) throw new Error('sidebar page binding unsupported')
242
+ if (s.tabs.some(tab => tab.url !== '')) throw new Error('source binding requires a fresh browser session')
243
+ const id = tabWireId(resolveTabHandle(resolveSessionHandle(s.id), pageId))
244
+ const handle = await this.host.adoptPage(id, this.carrierScope(s))
245
+ const previous = [...s.tabs]
246
+ s.tabs.splice(0, s.tabs.length, { id: this.carrierTab(s, id), handle, url: '' })
247
+ s.activeIndex = 0
248
+ for (const tab of previous) this.destroyTab(tab)
249
+ }
250
+
251
+ /**
252
+ * The most recent open request, for the Web sidebar.
253
+ *
254
+ * On the desktop shell the host half tells the shell to place a tab (`__dshBuiltinBrowser.openPanel`)
255
+ * through the bridge. The Web shell has no such channel, so a tool-opened page lived only in the
256
+ * plugin's own browser while the panel stayed empty — and "open it in the sidebar" took several manual
257
+ * steps. The client polls this one slot and places the tab itself.
258
+ * @returns the last request and when it arrived, or undefined when nothing was opened yet.
259
+ */
260
+ lastOpenRequest(): { readonly url: string; readonly at: number } | undefined {
261
+ return this.lastOpen
262
+ }
263
+
264
+ /**
265
+ * Make sure the active tab's view can actually receive synthesized input.
266
+ * Chromium drops `Input.*` events for a view with no display surface, so this
267
+ * runs before click/type/key and fails loudly (BROWSER_VIEW_NOT_PRESENTED)
268
+ * rather than reporting a success the page never saw.
269
+ * @param s - the session whose active view must be presented.
270
+ * @param signal - optional cancellation.
271
+ * @returns the view the session's active tab has AFTER the presentation barrier.
272
+ */
273
+ protected async present(s: Session, signal?: AbortSignal): Promise<ElectronViewHandle> {
274
+ const { handle } = this.activeTab(s)
275
+ const present = this.host.presentView?.bind(this.host)
276
+ if (present === undefined) {
277
+ this.showActive(s)
278
+ return this.activeTab(s).handle
279
+ }
280
+ signal?.throwIfAborted()
281
+ const timeoutMs = PROVIDER_TIMEOUTS.lookup
282
+ try {
283
+ await withTimeout(
284
+ present(handle, s.label, { quiet: this.isQuiet() }),
285
+ timeoutMs,
286
+ signal,
287
+ `browser: presenting the page view timed out after ${timeoutMs}ms`,
288
+ )
289
+ this.showActive(s)
290
+ } catch (error) {
291
+ throw new BrowserError(
292
+ `browser: the page view is not presented, so synthesized input would be silently dropped (${String(error)})`,
293
+ 'BROWSER_VIEW_NOT_PRESENTED',
294
+ { cause: error },
295
+ )
296
+ }
297
+ // Read the active tab AGAIN. `present` is a round-trip that can take up to the budget
298
+ // above, and the human is invited to drive the same window (a toolbar tab switch, a
299
+ // closed window) while the agent waits. Chromium answers `Input.*` with success even
300
+ // for a view that has no display surface, so dispatching to a handle that is no longer
301
+ // the visible one does not fail — it silently lands nowhere, or on the wrong page.
302
+ //
303
+ // Returning the re-read handle was wrong, though: `handle` above is the one that was
304
+ // actually presented, and if the active tab changed during the round trip then the
305
+ // re-read one was never presented at all. Handing it back meant the caller dispatched
306
+ // to a view with no display surface — the exact failure this method exists to prevent,
307
+ // arrived at from the other side. Either the presented view is still the active one, or
308
+ // the caller must be told rather than given something else to aim at.
309
+ const live = this.activeTab(s).handle
310
+ if (live !== handle) {
311
+ throw new BrowserError(
312
+ 'browser: the active tab changed while the page view was being presented, so synthesized input would go to an unshown view — retry, and the new page will be presented instead',
313
+ 'BROWSER_VIEW_CHANGED',
314
+ )
315
+ }
316
+ return handle
317
+ }
318
+
319
+ /** Append one operation to the session's history. */
320
+ protected record(
321
+ s: Session,
322
+ action: string,
323
+ params: Record<string, unknown>,
324
+ ok: boolean,
325
+ detail?: { result?: string; error?: string },
326
+ ): void {
327
+ const entry: BrowserHistoryEntry = {
328
+ seq: s.nextSeq++,
329
+ action,
330
+ params,
331
+ ok,
332
+ ...detail?.result !== undefined ? { result: detail.result } : {},
333
+ ...detail?.error !== undefined ? { error: detail.error } : {},
334
+ at: Date.now(),
335
+ }
336
+ s.history.push(entry)
337
+ // Bound memory: keep the last 500 operations.
338
+ if (s.history.length > 500) s.history.splice(0, s.history.length - 500)
339
+ }
340
+
341
+ /** Return the session's chronological operation log (newest last). */
342
+ async history(session: BrowserSessionId): Promise<readonly BrowserHistoryEntry[]> {
343
+ return this.session(session).history
344
+ }
345
+
346
+ /**
347
+ * Record one page visit in the persistent browsing history. Fire-and-forget by
348
+ * design: a visit must never delay or fail the navigation that produced it,
349
+ * and the title is only worth reading once the document has settled.
350
+ * @param s - the session that drove the visit.
351
+ * @param handle - the view whose document just loaded.
352
+ */
353
+ protected recordVisit(s: Session, handle: ElectronViewHandle): void {
354
+ const store = this.historyStore
355
+ if (store === undefined) return
356
+ // The settings panel can switch recording off at runtime; the static config
357
+ // only supplies the startup default. The RETENTION limits are read here too: they were
358
+ // parsed and stored but never handed to the store, so editing maxEntries or maxAgeDays in
359
+ // the file changed nothing — the switch worked and the numbers beside it did not.
360
+ if (this.settingsSource !== undefined) {
361
+ const live = this.settingsSource().history
362
+ if (!live.enabled) return
363
+ store.updateLimits({ maxEntries: live.maxEntries, maxAgeDays: live.maxAgeDays })
364
+ }
365
+ void handleSendEvaluate(handle, 'location.href + "\\u0000" + (document.title || "")')
366
+ .then(result => {
367
+ if (!result.ok || typeof result.value !== 'string') return
368
+ const [url = '', title = ''] = result.value.split('\u0000')
369
+ // Internal documents are not visits: an untouched browser is not history.
370
+ if (url === '' || url.startsWith('about:') || url.startsWith('devtools:')) return
371
+ store.append({
372
+ at: Date.now(),
373
+ url,
374
+ ...title.trim() !== '' ? { title: title.trim() } : {},
375
+ ...s.label !== undefined ? { session: s.label } : {},
376
+ })
377
+ store.prune()
378
+ })
379
+ .catch(() => { /* best-effort: history is never worth surfacing an error */ })
380
+ }
381
+
382
+ /**
383
+ * List persisted visits, newest first — what `dsh_browser_visited` reads back.
384
+ * @param options - result cap and an optional hostname filter.
385
+ * @returns the matching visits, or an empty list when history is disabled.
386
+ */
387
+ visited(options: { readonly limit?: number; readonly domain?: string; readonly query?: string; readonly session?: string } = {}): readonly VisitedPage[] {
388
+ return this.historyStore?.list(options) ?? []
389
+ }
390
+
391
+ /**
392
+ * Replay one recorded operation by sequence number. Navigate/click/type are
393
+ * re-issued against the current page; execute re-runs its script. The
394
+ * replayed step is appended to history as a new entry.
395
+ * @param session - the session id.
396
+ * @param seq - the recorded entry's sequence number to replay.
397
+ */
398
+ async replay(session: BrowserSessionId, seq: number): Promise<void> {
399
+ const s = this.session(session)
400
+ const entry = s.history.find(e => e.seq === seq)
401
+ if (entry === undefined) {
402
+ throw new BrowserError(`browser: no history entry with seq ${seq}`, 'BROWSER_HISTORY_UNKNOWN')
403
+ }
404
+ switch (entry.action) {
405
+ case 'navigate': {
406
+ const url = entry.params.url
407
+ if (typeof url !== 'string') throw new BrowserError(`browser: history seq ${seq} navigate has no url`, 'BROWSER_HISTORY_INVALID')
408
+ await this.navigate(session, { url })
409
+ this.record(s, 'replay', { seq, of: entry.action, url }, true)
410
+ return
411
+ }
412
+ case 'click': {
413
+ const target = entry.params.target as BrowserElementTarget | undefined
414
+ if (target !== undefined) {
415
+ await this.click(session, { target })
416
+ this.record(s, 'replay', { seq, of: entry.action, target }, true)
417
+ return
418
+ }
419
+ const x = entry.params.x
420
+ const y = entry.params.y
421
+ if (typeof x !== 'number' || typeof y !== 'number') throw new BrowserError(`browser: history seq ${seq} click has no coordinates`, 'BROWSER_HISTORY_INVALID')
422
+ await this.click(session, { x, y })
423
+ this.record(s, 'replay', { seq, of: entry.action, x, y }, true)
424
+ return
425
+ }
426
+ case 'type': {
427
+ const text = entry.params.text
428
+ if (typeof text !== 'string') throw new BrowserError(`browser: history seq ${seq} type has no text`, 'BROWSER_HISTORY_INVALID')
429
+ const target = entry.params.target as BrowserElementTarget | undefined
430
+ await this.type(session, { text, ...target !== undefined ? { target } : {} })
431
+ this.record(s, 'replay', { seq, of: entry.action, text, ...target !== undefined ? { target } : {} }, true)
432
+ return
433
+ }
434
+ case 'scroll': {
435
+ await this.scroll(session, entry.params as BrowserScrollRequest)
436
+ this.record(s, 'replay', { seq, of: entry.action }, true)
437
+ return
438
+ }
439
+ case 'key': {
440
+ const key = entry.params.key
441
+ if (typeof key !== 'string') throw new BrowserError(`browser: history seq ${seq} key has no key`, 'BROWSER_HISTORY_INVALID')
442
+ await this.key(session, { key })
443
+ this.record(s, 'replay', { seq, of: entry.action, key }, true)
444
+ return
445
+ }
446
+ case 'execute': {
447
+ const script = entry.params.script
448
+ if (typeof script !== 'string') throw new BrowserError(`browser: history seq ${seq} execute has no script`, 'BROWSER_HISTORY_INVALID')
449
+ const recordedArgs = entry.params.args
450
+ const args = Array.isArray(recordedArgs)
451
+ ? recordedArgs.filter((a): a is string | number | boolean => typeof a === 'string' || typeof a === 'number' || typeof a === 'boolean')
452
+ : undefined
453
+ const result = await this.execute(session, { script, ...args !== undefined && args.length > 0 ? { args } : {} })
454
+ this.record(s, 'replay', { seq, of: entry.action, script, ...args !== undefined && args.length > 0 ? { args } : {} }, result.ok, result.ok ? { result: String(result.value) } : { error: result.exception })
455
+ return
456
+ }
457
+ default:
458
+ throw new BrowserError(`browser: history seq ${seq} action "${entry.action}" is not replayable`, 'BROWSER_HISTORY_NOT_REPLAYABLE')
459
+ }
460
+ }
461
+
462
+ /** Close the session and destroy all its views. Idempotent. */
463
+ async close(session: BrowserSessionId): Promise<void> {
464
+ const existing = this.sessions.get(session)
465
+ if (existing !== undefined) {
466
+ this.sessions.delete(session)
467
+ for (const tab of existing.tabs) this.destroyTab(tab)
468
+ // Releasing the browser at session end is a setting, not fixed behaviour
469
+ // (requirements §3). A self-hosted carrier already tore its window down with
470
+ // the views above; the desktop's sidebar does not, so it is asked explicitly
471
+ // — and its cookies plus the browsing history outlive the page either way.
472
+ try {
473
+ if (this.settingsSource !== undefined && this.settingsSource().ui.closeWithSession) {
474
+ // Never release another conversation's pages.
475
+ await this.host.releasePage?.(this.carrierScope(existing))
476
+ }
477
+ } finally {
478
+ await this.host.retireSession?.(session)
479
+ }
480
+ }
481
+ }
482
+
483
+ protected interrupt(handle: ElectronViewHandle, timedOut: boolean): void {
484
+ if (timedOut) this.quarantine(handle)
485
+ else terminatePage(handle)
486
+ }
487
+
488
+ protected quarantine(handle: ElectronViewHandle): void {
489
+ for (const session of this.sessions.values()) {
490
+ const tab = session.tabs.find(tab => tab.handle === handle)
491
+ if (tab === undefined || tab.failure !== undefined) continue
492
+ tab.failure = new BrowserError('browser: this guest stopped acknowledging operations and is quarantined; close this tab or explicitly reset the session before retrying', 'BROWSER_GUEST_QUARANTINED')
493
+ terminatePage(handle)
494
+ }
495
+ }
496
+
497
+ /**
498
+ * The sessions a viewer may watch, which is exactly the sessions that exist.
499
+ *
500
+ * Served so the browser page can build a frame URL without guessing: the provider names its
501
+ * sessions, and an id invented by a client is refused at the route. Ids only — no URL, no title,
502
+ * no target handle — because the point is to let the panel address a session, not to describe
503
+ * what is in it.
504
+ * @returns the live session ids.
505
+ */
506
+ watchableSessions(): readonly BrowserSessionId[] {
507
+ return [...this.sessions.keys()]
508
+ }
509
+
510
+ takeoverTargets(owner: string): readonly { session: BrowserSessionId; owner: string; tabId: string; pageId: string; url: string; reveal?: (until?: AbortSignal) => Promise<boolean> }[] {
511
+ const reveal = this.host.revealQuietWindow?.bind(this.host)
512
+ const targets = [...this.sessions.values()].filter(s => (s.label ?? 'default').replace(/^session-/u, '') === owner).flatMap(s => {
513
+ const tab = s.tabs[s.activeIndex]
514
+ return tab && !tab.failure && /^https?:\/\//u.test(tab.url)
515
+ ? [{ session: s.id, owner: s.label ?? 'default', tabId: tab.id, pageId: tab.id, url: tab.url,
516
+ ...reveal ? { reveal: (until?: AbortSignal) => reveal(tab.handle, until === undefined ? undefined : { until }) } : {} }] : []
517
+ })
518
+ const own = targets.filter(target => target.session !== this.referenceSession)
519
+ return own.length > 0 ? own : targets
520
+ }
521
+
522
+ /**
523
+ * The human closed a browser window: the session that window showed is over.
524
+ * Ending it here is what makes the next call a clean start rather than a
525
+ * resurrection of an invisible window. Browsing history and login state live
526
+ * on disk, so nothing the human cares about is lost with it.
527
+ * @param windowId - the group key the host reported, which is the session id.
528
+ */
529
+ protected async handleViewClosed(windowId: string): Promise<void> {
530
+ if (typeof windowId !== 'string' || windowId === '') return
531
+ const s = this.sessions.get(windowId as BrowserSessionId)
532
+ if (s === undefined) return
533
+ await this.close(s.id).catch(() => { /* the window is already gone */ })
534
+ }
535
+
536
+ /**
537
+ * Route a user-initiated action from the host's UI into the session model.
538
+ * Fire-and-forget by design: a user action failing (e.g. an unreachable
539
+ * URL typed into the address bar) must never crash the host UI loop — it
540
+ * is reported to the host (toolbar) when the host supports it, else logged.
541
+ */
542
+ protected async handleUserAction(action: BrowserUserAction, propagate = false): Promise<void> {
543
+ const s = this.sessions.get(action.windowId as BrowserSessionId)
544
+ if (s === undefined) {
545
+ // The window the human clicked in has no live session here (session
546
+ // closed, or a child restart changed identity). Never swallow the click
547
+ // silently — surface it so the toolbar can tell the human what happened.
548
+ const message = `action ${action.type} failed: no live browser session for window "${action.windowId}"`
549
+ process.stderr.write(`[dsh-browser] ${message}\n`)
550
+ this.notifyUserActionError(action, new Error('no live browser session'))
551
+ if (propagate) throw new Error('no live browser session')
552
+ return
553
+ }
554
+ try {
555
+ switch (action.type) {
556
+ case 'capture-reference':
557
+ // The human clicked a native menu item or the page's floating entry.
558
+ // Delivery is owned by the plugin entry, which holds the reference
559
+ // service; the provider only routes the action to the right session.
560
+ await dispatchReferenceCaptureAction({
561
+ windowId: action.windowId,
562
+ entry: action.entry,
563
+ ...action.frameSelector !== undefined ? { frameSelector: action.frameSelector } : {},
564
+ ...action.target !== undefined ? { target: action.target } : {},
565
+ ...action.comment !== undefined ? { comment: action.comment } : {},
566
+ ...action.selectionText !== undefined ? { selectionText: action.selectionText } : {},
567
+ ...action.capture !== undefined ? { capture: action.capture } : {},
568
+ })
569
+ return
570
+ case 'navigate':
571
+ await this.openUrl(s.id, { url: action.url })
572
+ return
573
+ case 'newTab':
574
+ this.newTab(s)
575
+ if (action.url !== undefined && action.url !== '') {
576
+ await this.navigate(s.id, { url: action.url })
577
+ }
578
+ return
579
+ case 'activateTab': {
580
+ const tab = this.tabByViewId(s, action.viewId)
581
+ if (tab !== undefined) await this.switchTab(s.id, tab.id, { user: true })
582
+ return
583
+ }
584
+ case 'closeTab': {
585
+ const tab = this.tabByViewId(s, action.viewId)
586
+ if (tab !== undefined) await this.closeTab(s.id, tab.id)
587
+ return
588
+ }
589
+ case 'back':
590
+ await this.back(s.id)
591
+ return
592
+ case 'forward':
593
+ await this.forward(s.id)
594
+ return
595
+ case 'reload':
596
+ await this.reload(s.id)
597
+ return
598
+ }
599
+ } catch (error) {
600
+ this.notifyUserActionError(action, error)
601
+ if (propagate) throw error
602
+ }
603
+ }
604
+
605
+ /**
606
+ * Report a failed user action to the host UI (toolbar), when supported.
607
+ *
608
+ * Two properties matter here, because this runs inside the catch of an async
609
+ * handler (issue #16):
610
+ * - the receiver must be preserved. Reading the method off the host and calling
611
+ * it unbound runs the host's implementation with `this === undefined`, so its
612
+ * very first statement (`void this.ready()`) throws, the throw escapes the
613
+ * async catch as an unhandled rejection, and the whole DSH host exits;
614
+ * - this method must be incapable of throwing. Reporting a failed action is
615
+ * diagnostics: it can never be allowed to become the failure.
616
+ */
617
+ private notifyUserActionError(action: BrowserUserAction, error: unknown): void {
618
+ const message = `action ${action.type} failed: ${String(error)}`
619
+ let reported = false
620
+ try {
621
+ const notify = this.host.notifyUserActionError?.bind(this.host)
622
+ if (notify !== undefined) {
623
+ // Bound at the call: an unbound call here kills the host process (issue #16).
624
+ notify(action.windowId, message)
625
+ reported = true
626
+ }
627
+ } catch (notifyError) {
628
+ // Contained on purpose; the log line below still carries the original cause.
629
+ process.stderr.write(`[dsh-browser] host notify failed: ${String(notifyError)}\n`)
630
+ }
631
+ if (!reported) process.stderr.write(`[dsh-browser] user action failed: ${message}\n`)
632
+ }
633
+
634
+ /**
635
+ * Whether the operator asked for quiet mode (`ui.quiet`).
636
+ *
637
+ * Read live on every call rather than captured at construction: the panel writes the document
638
+ * and the next operation is expected to honour it, without a restart.
639
+ * @returns true when the carrier must present views without taking the screen over.
640
+ */
641
+ protected isQuiet(): boolean {
642
+ return this.settingsSource?.().ui.quiet === true
643
+ }
644
+
645
+ /**
646
+ * Ask the host to show the active tab's view, carrying the session label.
647
+ *
648
+ * The two halves are sequential, not alternatives. `showView` makes the view the
649
+ * visible one — which is what keeps what the human sees in step with what the agent
650
+ * drives, and what lets `capturePage` return an image at all (a hidden view captures
651
+ * empty) — while `collapse` folds the carrier's own chrome away when the user asked
652
+ * for no auto-expand. Making them exclusive meant that with auto-expand off this
653
+ * method did nothing at all on carriers without `collapse` (the self-hosted one),
654
+ * silently desynchronising the two and failing every screenshot.
655
+ */
656
+ protected showActive(s: Session, select = false, user = false): void {
657
+ const quiet = this.isQuiet()
658
+ const active = s.tabs[s.activeIndex]
659
+ if (active !== undefined) this.host.showView?.(active.handle, s.label, { quiet, ...select ? { select: true } : {}, ...user ? { user: true } : {} })
660
+ if (quiet || select) return
661
+ const autoExpand = this.settingsSource === undefined || this.settingsSource().ui.autoExpandOnce
662
+ if (autoExpand) return
663
+ // Best effort: a carrier that owns no presentation (self-hosted) simply has none.
664
+ void this.host.collapse?.().catch(() => undefined)
665
+ }
666
+ }