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,693 @@
1
+ /** Carrier-independent tab commands and renderer-facing state. */
2
+ import { createSnapshotStore, type BoundActions, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
3
+ import type { TabId } from '@deepseek-ai/dsh-client-ui-dockkit'
4
+ import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots'
5
+ import type { BrowserFrameState } from './BrowserFrame.ts'
6
+ import type { BrowserPage, BrowserPageFactory } from './BrowserPage.ts'
7
+ import { currentBrowserTarget, type BrowserTabState } from './BrowserPersistence.ts'
8
+ import { resolveOmniboxInput, type OmniboxPreferences, type OmniboxRefusal } from './omnibox.ts'
9
+ import type { BrowserStore } from './store.ts'
10
+ import { parseBrowserAddress, type BrowserTarget } from './url.ts'
11
+ import { StartPageBinding, type BrowserStartPageInjected } from '../startpage/binding.ts'
12
+ import type { ShortcutDraft } from '../startpage/model.ts'
13
+ import { createBrowserInitializationJournal } from './initialization.ts'
14
+ import type {
15
+ BrowserInitFailure,
16
+ BrowserInitReceipt,
17
+ BrowserInitializationJournal,
18
+ BrowserObservedPage,
19
+ } from './initialization.ts'
20
+
21
+ /** Live tab state; navigation comes from its provider and draft validation stays local. */
22
+ export interface BrowserControllerState {
23
+ readonly frame: BrowserFrameState
24
+ /** Saved address offered for explicit restoration before any page has been requested. */
25
+ readonly restoreTarget: BrowserTarget | undefined
26
+ readonly addressFailure: OmniboxRefusal | undefined
27
+ /** Counts explicit navigation commands; a page changing on its own leaves the address draft intact. */
28
+ readonly commandRevision: number
29
+ /** Prefilled new-shortcut form requested from the tab's actions menu. */
30
+ readonly shortcutDraft: ShortcutDraft | undefined
31
+ /** Last explicit initialization receipt for this occurrence; failed stages are visible. */
32
+ readonly initialization: BrowserInitReceipt | undefined
33
+ }
34
+
35
+ /** Construction inputs for one tab occurrence. */
36
+ export interface BrowserControllerOptions {
37
+ readonly tabId: TabId
38
+ readonly signal: AbortSignal
39
+ readonly applicationOrigin: string
40
+ readonly initial: BrowserTabState | undefined
41
+ readonly actions: BoundActions<BrowserStore>
42
+ readonly createPage: BrowserPageFactory
43
+ readonly openTab: (url: string) => void
44
+ /** Shared search selection read at submission time, never captured at mount. */
45
+ readonly omnibox?: () => OmniboxPreferences
46
+ /** DSH Session this occurrence belongs to; recorded in every receipt. */
47
+ readonly sessionId?: string
48
+ /** Distinguishes this mount from a reopened tab of the same id. */
49
+ readonly occurrenceId?: string
50
+ /** Shared lifecycle journal; one per Browser plugin, not per tab. */
51
+ readonly journal?: BrowserInitializationJournal
52
+ }
53
+
54
+ /** Owns input validation and page lifetime without inspecting the carrier type. */
55
+ export class BrowserController implements HostObservable<BrowserControllerState> {
56
+ private readonly page: BrowserPage
57
+ private readonly store: SnapshotStore<BrowserControllerState>
58
+ private readonly unsubscribe: () => void
59
+ private actions: BoundActions<BrowserStore>
60
+ private checkpoint: BrowserTabState | undefined
61
+ private disposed = false
62
+ private disposal: Promise<void> | undefined
63
+ private readonly abort = (): void => { void this.dispose() }
64
+ private unsubscribeCarrier: (() => void) | undefined
65
+ /** Last URL/revision this controller consumed, so a re-mount is not a reload. */
66
+ private applied: { readonly url: string; readonly revision: number } | undefined
67
+ /** The navigation record this occurrence is currently aimed at. */
68
+ private navigationRevision = 0
69
+ private readonly journal: BrowserInitializationJournal
70
+ private readonly sessionId: string
71
+ private readonly occurrenceId: string
72
+ private readonly options: BrowserControllerOptions
73
+ constructor(options: BrowserControllerOptions) {
74
+ this.options = options
75
+ this.actions = options.actions
76
+ this.journal = options.journal ?? createBrowserInitializationJournal()
77
+ this.sessionId = options.sessionId ?? ''
78
+ this.occurrenceId = options.occurrenceId ?? `${options.tabId}:0`
79
+ this.checkpoint = options.initial
80
+ this.page = options.createPage({
81
+ tabId: options.tabId,
82
+ initial: options.initial,
83
+ persist: (state) => {
84
+ if (this.disposed) return
85
+ this.checkpoint = state
86
+ this.actions.replace(options.tabId, state)
87
+ },
88
+ openRequested: (value) => {
89
+ if (this.disposed) return
90
+ const result = parseBrowserAddress(value, options.applicationOrigin)
91
+ if (!result.ok) { this.addressFailed(result.reason); return }
92
+ options.openTab(result.target.url)
93
+ },
94
+ })
95
+ this.store = createSnapshotStore({ frame: this.page.frame.getSnapshot(),
96
+ restoreTarget: currentBrowserTarget(this.checkpoint), addressFailure: undefined, commandRevision: 0,
97
+ shortcutDraft: undefined, initialization: undefined })
98
+ this.unsubscribe = this.page.frame.subscribe(() => {
99
+ if (this.disposed) return
100
+ const current = this.store.getSnapshot()
101
+ const frame = this.page.frame.getSnapshot()
102
+ const changed = frame.target?.url !== current.frame.target?.url
103
+ this.store.set({ frame, restoreTarget: frame.target === undefined ? currentBrowserTarget(this.checkpoint) : undefined,
104
+ addressFailure: changed ? undefined : current.addressFailure,
105
+ commandRevision: current.commandRevision,
106
+ shortcutDraft: current.shortcutDraft,
107
+ initialization: current.initialization })
108
+ this.advanceFromFrame(frame)
109
+ })
110
+ const lifecycle = this.page.frame.lifecycle
111
+ if (lifecycle !== undefined) {
112
+ this.unsubscribeCarrier = lifecycle.subscribe(() => {
113
+ if (this.disposed) return
114
+ const carrier = lifecycle.getSnapshot()
115
+ // `latest` is indexed only by tab, so a late carrier event from one
116
+ // occurrence must never write another occurrence's receipt.
117
+ const current = this.ownReceipt()
118
+ if (carrier.stage === 'guest') {
119
+ // A replacement guest for THIS occurrence (a physical unmount/remount
120
+ // recreates the guest under the same Controller) must not be blocked
121
+ // by a `failed` receipt left by a superseded mount. Begin a fresh
122
+ // receipt so the later dom-ready can advance it to `attached`.
123
+ if (current !== undefined && current.stage === 'failed') {
124
+ this.journal.begin({
125
+ sessionId: this.sessionId, tabId: this.options.tabId,
126
+ occurrenceId: this.occurrenceId, navigationRevision: this.navigationRevision,
127
+ url: this.applied?.url ?? current.url,
128
+ })
129
+ }
130
+ } else if (carrier.stage === 'ready') {
131
+ this.advanceFromFrame(this.page.frame.getSnapshot())
132
+ } else if (carrier.stage === 'failed') {
133
+ // `ownReceipt` already scopes this to the current occurrence.
134
+ if (current !== undefined && current.stage !== 'failed') {
135
+ this.journal.fail(this.options.tabId, carrier.reason ?? 'guest-bootstrap-failed',
136
+ carrier.detail === undefined ? {} : { detail: carrier.detail })
137
+ }
138
+ }
139
+ this.publishInitialization()
140
+ })
141
+ }
142
+ options.signal.addEventListener('abort', this.abort, { once: true })
143
+ }
144
+
145
+ /** @returns immutable state for the common toolbar. */
146
+ getSnapshot = (): BrowserControllerState => this.store.getSnapshot()
147
+ /** @param listener - state invalidation. @returns unsubscribe callback. */
148
+ subscribe = (listener: () => void): (() => void) => this.store.subscribe(listener)
149
+
150
+ /**
151
+ * Attach the page without transferring ownership of its tab occurrence.
152
+ * @param viewportId - mounted content container.
153
+ * @returns physical attachment cleanup only.
154
+ */
155
+ mount(viewportId: string): () => void {
156
+ this.publishSaved()
157
+ return this.page.presentation.mount(viewportId)
158
+ }
159
+
160
+ /**
161
+ * Bind this controller to one committed tab occurrence and consume its target.
162
+ * Called on every mount: a re-mount with the same URL/revision is a no-op, a
163
+ * new revision is a real navigation, and an empty page can still be filled.
164
+ * @param initialUrl - the navigation record's URL at this mount, or absence.
165
+ * @param navigationRevision - the record revision this mount represents.
166
+ */
167
+ applyMount(initialUrl: string | undefined, navigationRevision: number): void {
168
+ if (this.disposed) return
169
+ this.navigationRevision = navigationRevision
170
+ const adoption = this.page.adoption
171
+ if (adoption !== undefined && this.applied === undefined) {
172
+ this.applied = { url: adoption.url, revision: navigationRevision }
173
+ const receipt = this.journal.begin({ sessionId: this.sessionId, tabId: this.options.tabId,
174
+ occurrenceId: this.occurrenceId, navigationRevision, url: adoption.url })
175
+ adoption.acknowledge(receipt.requestId)
176
+ this.journal.advance(this.options.tabId, 'mounted', { navigationRevision })
177
+ this.publishInitialization()
178
+ return
179
+ }
180
+ const navigates = initialUrl !== undefined && initialUrl !== ''
181
+ && (this.applied === undefined || navigationRevision > this.applied.revision)
182
+ // `latest` is keyed only by tab, so a rebuilt occurrence can inherit a
183
+ // stale (often failed) receipt from the previous one. A mount that keeps
184
+ // the start page has no navigation to call `begin`, so establish our own
185
+ // `accepted`/`mounted` receipt here. When a URL will be consumed,
186
+ // `navigateTo` begins the receipt instead: doing both would write two
187
+ // `accepted` records for the same occurrence.
188
+ if (!navigates && this.journal.get(this.options.tabId)?.occurrenceId !== this.occurrenceId) {
189
+ this.journal.begin({
190
+ sessionId: this.sessionId, tabId: this.options.tabId,
191
+ occurrenceId: this.occurrenceId, navigationRevision, url: initialUrl ?? '',
192
+ })
193
+ this.journal.advance(this.options.tabId, 'mounted', { navigationRevision })
194
+ }
195
+ this.publishInitialization()
196
+ // A re-mount must not replay the initial URL over a URL the user typed
197
+ // afterwards: only a brand-new controller, or a NEWER navigation record,
198
+ // consumes the mount target.
199
+ if (navigates) this.applyNavigation(initialUrl!, navigationRevision)
200
+ }
201
+
202
+ /** Backwards-compatible mount entry; a caller without a revision gets the last one. */
203
+ start(initialUrl: string | undefined): void {
204
+ this.applyMount(initialUrl, this.navigationRevision)
205
+ }
206
+
207
+ /** Load the saved address only after an explicit restore action. */
208
+ restore(): void {
209
+ // 卡片由视图从 `currentBrowserTarget(checkpoint)` 算出,而快照里的 `restoreTarget` 在
210
+ // 「本 occurrence 已经带 url」时是 undefined——两处各算一遍就会「卡片在、点了没反应」。
211
+ // 这里补上同一个来源,让按钮与卡片指向同一个目标。
212
+ const target = this.store.getSnapshot().restoreTarget ?? currentBrowserTarget(this.checkpoint)
213
+ if (target !== undefined) this.loadUrl(target.url)
214
+ }
215
+
216
+ /**
217
+ * Validate an address before navigation, publishing invalid input for correction.
218
+ * A repeated URL/revision is not reloaded; a newer revision always is.
219
+ * @param value - address-bar or typed-open input.
220
+ */
221
+ loadUrl(value: string): void {
222
+ if (this.disposed) return
223
+ this.navigateTo(value, this.navigationRevision)
224
+ }
225
+
226
+ /**
227
+ * Resolve manual address-bar input into a URL or keyword search before navigating.
228
+ * @param value - text submitted from the address bar.
229
+ */
230
+ submitInput(value: string): void {
231
+ if (this.disposed) return
232
+ const preferences = this.options.omnibox?.() ?? { defaultSearchEngineId: '', searchEngines: [] }
233
+ const resolution = resolveOmniboxInput(value, { ...preferences, applicationOrigin: this.options.applicationOrigin })
234
+ if (resolution.kind === 'refused') {
235
+ this.journal.begin({
236
+ sessionId: this.sessionId, tabId: this.options.tabId,
237
+ occurrenceId: this.occurrenceId, navigationRevision: this.navigationRevision, url: value,
238
+ })
239
+ this.journal.fail(this.options.tabId, 'navigation-rejected')
240
+ this.addressFailed(resolution.reason)
241
+ this.publishInitialization()
242
+ return
243
+ }
244
+ this.navigateTo(resolution.primary.target.url, this.navigationRevision)
245
+ }
246
+
247
+ /** Delegate Back to the page's navigation provider. */
248
+ goBack(): void { this.command(() => { this.page.frame.goBack() }) }
249
+ /** Delegate Forward to the page's navigation provider. */
250
+ goForward(): void { this.command(() => { this.page.frame.goForward() }) }
251
+ /** Restore a saved address, or reload the already requested page. */
252
+ reload(): void {
253
+ if (this.store.getSnapshot().restoreTarget !== undefined) this.restore()
254
+ else this.command(() => { this.page.frame.reload() })
255
+ }
256
+
257
+ /**
258
+ * Apply the optional embedding-sandbox control; unsupported providers remain unchanged.
259
+ * @param enabled - whether to enforce the provider's embedding sandbox.
260
+ */
261
+ setSandbox(enabled: boolean): void {
262
+ const sandbox = this.page.frame.sandbox
263
+ if (sandbox !== undefined) this.command(() => { sandbox.setEnabled(enabled) })
264
+ }
265
+
266
+ /** @returns the current confirmable page address and title, or undefined on a start page or unknown address. */
267
+ pageInfo(): { readonly url: string; readonly title: string } | undefined {
268
+ if (this.disposed) return undefined
269
+ const { frame, restoreTarget } = this.store.getSnapshot()
270
+ if (restoreTarget !== undefined || frame.target === undefined) return undefined
271
+ if (frame.address === 'empty' || frame.address === 'unknown') return undefined
272
+ return { url: frame.target.url, title: frame.target.title }
273
+ }
274
+
275
+ /** @param draft - current page address and title offered for confirmation. */
276
+ requestShortcut(draft: ShortcutDraft): void {
277
+ if (this.disposed) return
278
+ this.store.set({ ...this.store.getSnapshot(), shortcutDraft: draft })
279
+ }
280
+
281
+ /** Close the prefilled shortcut form without writing. */
282
+ dismissShortcut(): void {
283
+ if (this.disposed) return
284
+ this.store.set({ ...this.store.getSnapshot(), shortcutDraft: undefined })
285
+ }
286
+
287
+ /**
288
+ * Redirect future checkpoint writes to a replacement Session binding.
289
+ * @param actions - replacement persistence writer.
290
+ */
291
+ rebind(actions: BoundActions<BrowserStore>): void { this.actions = actions }
292
+
293
+ /**
294
+ * Release the page and detach occurrence and state listeners.
295
+ * @returns after page teardown; repeated callers join the same disposal.
296
+ */
297
+ dispose(): Promise<void> {
298
+ if (this.disposal !== undefined) return this.disposal
299
+ this.disposed = true
300
+ this.options.signal.removeEventListener('abort', this.abort)
301
+ this.unsubscribe()
302
+ this.unsubscribeCarrier?.()
303
+ // A controller that never reached `attached` is a real failure, but only
304
+ // for receipts that belong to THIS occurrence: `latest` is shared by tab.
305
+ const receipt = this.ownReceipt()
306
+ if (receipt !== undefined && receipt.stage !== 'attached' && receipt.stage !== 'failed') {
307
+ this.journal.fail(this.options.tabId,
308
+ this.options.signal.aborted ? 'occurrence-aborted' : 'controller-missing')
309
+ }
310
+ this.disposal = this.page.frame.dispose()
311
+ return this.disposal
312
+ }
313
+
314
+ /** @returns the last initialization receipt for this occurrence. */
315
+ initialization(): BrowserInitReceipt | undefined {
316
+ return this.journal.get(this.options.tabId)
317
+ }
318
+
319
+ currentPage(): BrowserObservedPage | undefined {
320
+ const frame = this.page.frame.getSnapshot()
321
+ const carrier = this.page.frame.lifecycle?.getSnapshot()
322
+ if (this.disposed || frame.address !== 'observed' || (frame.loading && frame.documentReady !== true) || frame.error !== undefined
323
+ || frame.target === undefined || (carrier !== undefined && carrier.stage !== 'ready')) return undefined
324
+ return { url: frame.target.url, ...carrier?.guestId === undefined ? {} : { guestId: carrier.guestId },
325
+ ...carrier?.generation === undefined ? {} : { generation: carrier.generation, frameId: carrier.frameId, loaderId: carrier.loaderId } }
326
+ }
327
+
328
+ /** Aim this occurrence at a new navigation record revision (plugin/sidebar action). */
329
+ navigate(url: string, navigationRevision: number, requestId?: string): void {
330
+ if (this.disposed) return
331
+ this.navigationRevision = navigationRevision
332
+ this.navigateTo(url, navigationRevision, requestId)
333
+ }
334
+
335
+ private applyNavigation(url: string, revision: number, requestId?: string): void {
336
+ if (this.disposed) return
337
+ if (requestId === undefined && this.applied?.url === url && this.applied.revision === revision) return
338
+ this.applied = { url, revision }
339
+ this.navigateTo(url, revision, requestId)
340
+ }
341
+
342
+ private navigateTo(value: string, revision: number, requestId?: string): void {
343
+ this.applied = { url: value, revision }
344
+ const parsed = parseBrowserAddress(value, this.options.applicationOrigin)
345
+ this.journal.begin({
346
+ ...requestId === undefined ? {} : { requestId },
347
+ sessionId: this.sessionId, tabId: this.options.tabId,
348
+ occurrenceId: this.occurrenceId, navigationRevision: revision, url: value,
349
+ })
350
+ if (!parsed.ok) {
351
+ this.journal.fail(this.options.tabId, 'navigation-rejected')
352
+ this.addressFailed(parsed.reason)
353
+ this.publishInitialization()
354
+ return
355
+ }
356
+ this.journal.advance(this.options.tabId, 'navigating',
357
+ { navigationRevision: revision, url: parsed.target.url })
358
+ const navigationId = this.ownReceipt()?.requestId
359
+ this.command(() => { this.page.frame.loadUrl(parsed.target, navigationId) })
360
+ this.publishInitialization()
361
+ }
362
+
363
+ /** The latest receipt only when it belongs to this exact tab occurrence. */
364
+ private ownReceipt(): BrowserInitReceipt | undefined {
365
+ const receipt = this.journal.get(this.options.tabId)
366
+ return receipt?.occurrenceId === this.occurrenceId ? receipt : undefined
367
+ }
368
+
369
+ /** Carrier state is the strongest proof; the frame's observed address is the fallback. */
370
+ private advanceFromFrame(frame: BrowserFrameState): void {
371
+ const receipt = this.ownReceipt()
372
+ if (receipt === undefined || receipt.stage === 'failed' || receipt.stage === 'attached'
373
+ || frame.navigationId !== receipt.requestId) return
374
+ if (frame.error !== undefined) {
375
+ this.journal.fail(this.options.tabId, 'navigation-failed')
376
+ } else if (frame.address === 'observed' && (!frame.loading || frame.documentReady === true) && frame.target !== undefined) {
377
+ const carrier = this.page.frame.lifecycle?.getSnapshot()
378
+ if (carrier !== undefined && carrier.stage !== 'ready') return
379
+ this.journal.advance(this.options.tabId, 'attached',
380
+ carrier?.guestId === undefined ? {} : { guestId: carrier.guestId,
381
+ ...carrier.generation === undefined ? {} : { generation: carrier.generation, frameId: carrier.frameId, loaderId: carrier.loaderId } })
382
+ }
383
+ this.publishInitialization()
384
+ }
385
+
386
+ private publishInitialization(): void {
387
+ if (this.disposed) return
388
+ const receipt = this.ownReceipt()
389
+ const current = this.store.getSnapshot()
390
+ if (current.initialization === receipt) return
391
+ this.store.set({ ...current, initialization: receipt })
392
+ }
393
+
394
+ private publishSaved(): void {
395
+ if (this.checkpoint !== undefined) this.actions.replace(this.options.tabId, this.checkpoint)
396
+ }
397
+
398
+ private addressFailed(reason: OmniboxRefusal): void {
399
+ this.store.set({ ...this.store.getSnapshot(), addressFailure: reason })
400
+ }
401
+
402
+ private command(run: () => void): void {
403
+ if (this.disposed) return
404
+ const current = this.store.getSnapshot()
405
+ this.store.set({ ...current, addressFailure: undefined, commandRevision: current.commandRevision + 1 })
406
+ run()
407
+ }
408
+ }
409
+
410
+ /** Values available once a Sidebar body has committed its content container. */
411
+ export interface BrowserMountRequest {
412
+ readonly tabId: TabId
413
+ /** DSH Session; recorded in every initialization receipt. */
414
+ readonly sessionId?: string
415
+ /** The navigation record revision this mount represents. */
416
+ readonly navigationRevision?: number
417
+ readonly signal: AbortSignal
418
+ readonly viewportId: string
419
+ readonly applicationOrigin: string
420
+ readonly initial: BrowserTabState | undefined
421
+ readonly initialUrl: string | undefined
422
+ readonly openTab: (url: string) => void
423
+ readonly omnibox?: () => OmniboxPreferences
424
+ }
425
+
426
+ /** Result of aiming a tab at a URL; `controller-missing` is the recoverable failure. */
427
+ export type BrowserNavigationOutcome =
428
+ | { readonly ok: true; readonly requestId: string }
429
+ | { readonly ok: false; readonly reason: BrowserInitFailure }
430
+
431
+ /** Plain Slot callbacks and a framework-bound state source, not a desktop protocol. */
432
+ export interface BrowserInjected extends BrowserStartPageInjected {
433
+ readonly keyedHooks: {
434
+ readonly browserState: (key: string) => HostObservable<BrowserControllerState> | undefined
435
+ }
436
+ /** @param request - committed tab and container. @returns ends physical attachment without closing the tab. */
437
+ mount(request: BrowserMountRequest): () => void
438
+ /** @returns after every page has been disposed. */
439
+ dispose(): Promise<void>
440
+ /** @param actions - writer from a recreated Session binding. */
441
+ rebind(actions: BoundActions<BrowserStore>): void
442
+ /** @param tabId - owning tab. @param value - address input. */
443
+ loadUrl(tabId: TabId, value: string): BrowserNavigationOutcome
444
+ /** @param tabId - owning tab. @param value - manual address-bar input resolved as URL or search. */
445
+ submitInput(tabId: TabId, value: string): BrowserNavigationOutcome
446
+ /**
447
+ * Aim an existing (or recoverable) tab at one navigation record revision.
448
+ * Used by the body's revision effect; it never creates a second tab.
449
+ */
450
+ navigate(tabId: TabId, request: {
451
+ readonly url: string
452
+ readonly navigationRevision: number
453
+ readonly requestId?: string
454
+ }): BrowserNavigationOutcome
455
+ /** @param tabId - owning tab. @returns the latest initialization receipt. */
456
+ initialization(tabId: TabId): BrowserInitReceipt | undefined
457
+ currentPage(tabId: TabId): BrowserObservedPage | undefined
458
+ /** Newest-first receipts for diagnostics; bounded by the shared journal. */
459
+ initializationLog(): readonly BrowserInitReceipt[]
460
+ /** Capability marker: a caller may rely on receipts only when this is true. */
461
+ readonly initializationReceipts: true
462
+ /** @param tabId - tab whose saved address the user requested to restore. */
463
+ restore(tabId: TabId): void
464
+ /** @param tabId - owning tab. */
465
+ goBack(tabId: TabId): void
466
+ /** @param tabId - owning tab. */
467
+ goForward(tabId: TabId): void
468
+ /** Restore a saved address or reload its page. @param tabId - owning tab. */
469
+ reload(tabId: TabId): void
470
+ /** @param tabId - owning tab. @param enabled - provider's optional sandbox control. */
471
+ setSandbox(tabId: TabId, enabled: boolean): void
472
+ /** @param tabId - owning tab. @param focus - focuses the mounted address bar. @returns unregister callback. */
473
+ bindAddressFocus(tabId: TabId, focus: () => void): () => void
474
+ /** @param tabId - owning tab. @returns whether a mounted address bar can take focus. */
475
+ canFocusAddress(tabId: TabId): boolean
476
+ /** @param tabId - owning tab. @returns whether a mounted address bar received focus. */
477
+ focusAddress(tabId: TabId): boolean
478
+ /** @param tabId - owning tab. @returns the current confirmable page address and title. */
479
+ pageInfo(tabId: TabId): { readonly url: string; readonly title: string } | undefined
480
+ /** @param tabId - owning tab. @param draft - current page address and title. @returns whether the form opened. */
481
+ requestShortcut(tabId: TabId, draft: ShortcutDraft): boolean
482
+ /** @param tabId - owning tab. */
483
+ dismissShortcut(tabId: TabId): void
484
+ }
485
+
486
+ /**
487
+ * Own tab-occurrence controllers behind Session-scoped callbacks.
488
+ * @param actions - persisted view-state writer.
489
+ * @param createPage - composition-selected provider.
490
+ * @param isTabOpen - authoritative layout membership, independent of mounted bodies and plugin lifetime.
491
+ * @param startPage - shared start-page state and actions; an unavailable facade when settings are not served.
492
+ * @param options - Session identity and an optional shared initialization journal.
493
+ * @returns tab callbacks.
494
+ */
495
+ export function createBrowserControllers(actions: BoundActions<BrowserStore>, createPage: BrowserPageFactory,
496
+ isTabOpen: (tabId: TabId) => boolean, startPage?: BrowserStartPageInjected,
497
+ options: { readonly sessionId?: string; readonly journal?: BrowserInitializationJournal; readonly onInitializationChange?: () => void } = {},
498
+ ): BrowserInjected {
499
+ const page = startPage ?? new StartPageBinding()
500
+ const sessionId = options.sessionId ?? ''
501
+ const ownsJournal = options.journal === undefined
502
+ const journal = options.journal ?? createBrowserInitializationJournal({ onChange: options.onInitializationChange })
503
+ let disposal: Promise<void> | undefined
504
+ const mountRequests = new Map<TabId, BrowserMountRequest>()
505
+ let occurrenceSerial = 0
506
+ let currentActions = actions
507
+ const addressFocus = new Map<TabId, () => void>()
508
+ const controllers = new Map<TabId, {
509
+ readonly signal: AbortSignal
510
+ readonly controller: BrowserController
511
+ readonly forget: () => void
512
+ }>()
513
+ const controller = (id: TabId): BrowserController | undefined => controllers.get(id)?.controller
514
+
515
+ // Diagnostics handle for the real Desktop: the integration test reads the
516
+ // exact request/stage/reason instead of guessing from the DOM.
517
+ const root = globalThis as typeof globalThis & { __DSH_BROWSER_INIT_JOURNALS__?: BrowserInitializationJournal[] }
518
+ root.__DSH_BROWSER_INIT_JOURNALS__ ??= []
519
+ root.__DSH_BROWSER_INIT_JOURNALS__.push(journal)
520
+
521
+ const create = (request: BrowserMountRequest): BrowserController => new BrowserController({
522
+ ...request, actions: currentActions, createPage,
523
+ sessionId: sessionId === '' ? (request.sessionId ?? '') : sessionId,
524
+ occurrenceId: `${request.tabId}:${++occurrenceSerial}`,
525
+ journal,
526
+ omnibox: request.omnibox ?? (() => page.omniboxPreferences()),
527
+ })
528
+
529
+ const forgetController = (tabId: TabId, controllerToForget: BrowserController): void => {
530
+ const held = controllers.get(tabId)
531
+ if (held?.controller !== controllerToForget) return
532
+ controllers.delete(tabId)
533
+ // Plugin unload also aborts occurrences; only layout removal deletes saved
534
+ // navigation and retires the committed mount, so a reopened tab cannot
535
+ // resurrect a controller from a stale request.
536
+ if (!isTabOpen(tabId)) {
537
+ currentActions.forget(tabId)
538
+ mountRequests.delete(tabId)
539
+ }
540
+ }
541
+
542
+ /** Rebuild a missing controller from the last committed mount, if its occurrence is alive. */
543
+ const ensure = (tabId: TabId): { readonly ok: true } | { readonly ok: false; readonly reason: BrowserInitFailure } => {
544
+ if (controllers.has(tabId)) return { ok: true }
545
+ const request = mountRequests.get(tabId)
546
+ if (request === undefined) return { ok: false, reason: 'controller-missing' }
547
+ if (request.signal.aborted) {
548
+ journal.begin({
549
+ sessionId, tabId, occurrenceId: `${tabId}:${occurrenceSerial}`, navigationRevision: request.navigationRevision ?? 0,
550
+ url: request.initialUrl ?? '',
551
+ }, { aborted: true })
552
+ return { ok: false, reason: 'occurrence-aborted' }
553
+ }
554
+ const created = create(request)
555
+ const forget = (): void => {
556
+ created.dispose().catch(() => {})
557
+ forgetController(tabId, created)
558
+ }
559
+ controllers.set(tabId, { signal: request.signal, controller: created, forget })
560
+ request.signal.addEventListener('abort', forget, { once: true })
561
+ created.mount(request.viewportId)
562
+ created.applyMount(undefined, request.navigationRevision ?? 0)
563
+ return { ok: true }
564
+ }
565
+
566
+ const navigate = (tabId: TabId, request: {
567
+ readonly url: string
568
+ readonly navigationRevision: number
569
+ readonly requestId?: string
570
+ }): BrowserNavigationOutcome => {
571
+ const ready = ensure(tabId)
572
+ if (!ready.ok) {
573
+ journal.fail(tabId, ready.reason)
574
+ return { ok: false, reason: ready.reason }
575
+ }
576
+ const target = controller(tabId)
577
+ if (target === undefined) {
578
+ journal.fail(tabId, 'controller-missing')
579
+ return { ok: false, reason: 'controller-missing' }
580
+ }
581
+ target.navigate(request.url, request.navigationRevision, request.requestId)
582
+ const receipt = journal.get(tabId)
583
+ // navigateTo rejects an invalid address by failing its receipt without
584
+ // navigating; surface that instead of reporting a successful navigation.
585
+ return receipt?.stage === 'failed'
586
+ ? { ok: false, reason: receipt.reason ?? 'navigation-rejected' }
587
+ : { ok: true, requestId: receipt?.requestId ?? request.requestId ?? '' }
588
+ }
589
+
590
+ return {
591
+ hooks: page.hooks,
592
+ shortcuts: page.shortcuts,
593
+ engines: page.engines,
594
+ omniboxPreferences: () => page.omniboxPreferences(),
595
+ selectedEngine: () => page.selectedEngine(),
596
+ keyedHooks: { browserState: key => controller(key as TabId) },
597
+ initializationReceipts: true,
598
+ initialization: tabId => journal.get(tabId),
599
+ currentPage: tabId => controller(tabId)?.currentPage(),
600
+ initializationLog: () => journal.all(),
601
+ mount(request) {
602
+ const { tabId, signal } = request
603
+ mountRequests.set(tabId, request)
604
+ if (signal.aborted) {
605
+ journal.begin({
606
+ sessionId, tabId, occurrenceId: `${tabId}:${occurrenceSerial}`, navigationRevision: request.navigationRevision ?? 0,
607
+ url: request.initialUrl ?? '',
608
+ }, { aborted: true })
609
+ return () => {}
610
+ }
611
+ let held = controllers.get(tabId)
612
+ if (held?.signal !== signal) {
613
+ if (held !== undefined) {
614
+ held.signal.removeEventListener('abort', held.forget)
615
+ void held.controller.dispose()
616
+ }
617
+ const created = create(request)
618
+ const forget = (): void => { forgetController(tabId, created) }
619
+ held = { signal, controller: created, forget }
620
+ controllers.set(tabId, held)
621
+ signal.addEventListener('abort', forget, { once: true })
622
+ }
623
+ const hide = held.controller.mount(request.viewportId)
624
+ held.controller.applyMount(request.initialUrl, request.navigationRevision ?? 0)
625
+ return hide
626
+ },
627
+ dispose: () => {
628
+ disposal ??= (async () => {
629
+ try {
630
+ const pending = [...controllers.values()].map(({ signal, controller: held, forget }) => {
631
+ signal.removeEventListener('abort', forget)
632
+ return held.dispose()
633
+ })
634
+ await Promise.all(pending)
635
+ } finally {
636
+ controllers.clear()
637
+ mountRequests.clear()
638
+ if (ownsJournal) journal.dispose()
639
+ const registered = root.__DSH_BROWSER_INIT_JOURNALS__ ?? []
640
+ const index = registered.indexOf(journal)
641
+ if (index !== -1) registered.splice(index, 1)
642
+ }
643
+ })()
644
+ return disposal
645
+ },
646
+ rebind: (next) => {
647
+ currentActions = next
648
+ for (const { controller: held } of controllers.values()) held.rebind(next)
649
+ },
650
+ loadUrl: (id, value) => navigate(id, {
651
+ url: value, navigationRevision: mountRequests.get(id)?.navigationRevision ?? 0,
652
+ }),
653
+ submitInput: (id, value) => {
654
+ const ready = ensure(id)
655
+ if (!ready.ok) {
656
+ journal.fail(id, ready.reason)
657
+ return { ok: false, reason: ready.reason }
658
+ }
659
+ const target = controller(id)
660
+ if (target === undefined) return { ok: false, reason: 'controller-missing' }
661
+ target.submitInput(value)
662
+ const receipt = journal.get(id)
663
+ return receipt?.stage === 'failed' && receipt.reason !== undefined
664
+ ? { ok: false, reason: receipt.reason }
665
+ : { ok: true, requestId: receipt?.requestId ?? '' }
666
+ },
667
+ navigate,
668
+ bindAddressFocus: (id, focus) => {
669
+ addressFocus.set(id, focus)
670
+ return () => { if (addressFocus.get(id) === focus) addressFocus.delete(id) }
671
+ },
672
+ canFocusAddress: id => addressFocus.has(id),
673
+ focusAddress: (id) => {
674
+ const focus = addressFocus.get(id)
675
+ if (focus === undefined) return false
676
+ focus()
677
+ return true
678
+ },
679
+ pageInfo: id => controller(id)?.pageInfo(),
680
+ requestShortcut: (id, draft) => {
681
+ const target = controller(id)
682
+ if (target === undefined) return false
683
+ target.requestShortcut(draft)
684
+ return true
685
+ },
686
+ dismissShortcut: (id) => { controller(id)?.dismissShortcut() },
687
+ restore: (id) => { controller(id)?.restore() },
688
+ goBack: (id) => { controller(id)?.goBack() },
689
+ goForward: (id) => { controller(id)?.goForward() },
690
+ reload: (id) => { controller(id)?.reload() },
691
+ setSandbox: (id, enabled) => { controller(id)?.setSandbox(enabled) },
692
+ }
693
+ }