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,2773 @@
1
+ import { zh, en } from '../../../assets/browser-panel-locales.mjs'
2
+ import { REFERENCE_REVEAL_ROUTE, REFERENCE_INSERT_ROUTE, REFERENCE_IMPORT_ROUTE, REFERENCE_DELIVERY_REMOVE_ROUTE, REFERENCE_LIST_ROUTE, REFERENCE_EXPORT_ROUTE, OPEN_REQUEST_ROUTE, HOST_PATCH_ROUTE, AUTOMATIC_MAINTENANCE_ROUTE, PREVIEW_ROUTE, PREVIEW_SESSIONS_ROUTE, BRIDGE_STATUS_ROUTE, RUNTIME_STATUS_ROUTE, RUNTIME_PROVISION_ROUTE } from '../../../assets/browser-policy.mjs'
3
+ import { SETTINGS_ROUTE, EXTENSION_INSTALL_ROUTE } from '../../../assets/browser-policy.mjs'
4
+ import { nativeViews } from '../../compat/host-features.ts'
5
+ /**
6
+ * 设置面板(客户端半):从旧插件的 ModuleLoader bundle 机械移植而来,内部实现未改一行。
7
+ *
8
+ * 它注册进设置页的 `settings.section` 插槽,渲染宿主 `/dsh-builtin-browser/settings` 返回的
9
+ * 设置文档并回写补丁;宿主那一份文件仍是唯一事实来源(面板不可用时也能手改)。
10
+ *
11
+ * 外壳由 `window.__ModuleLoader__.load({factory})` 换成普通导出函数:本仓库的客户端半由
12
+ * tsdown 打成 CJS 工厂,`require` 由模块加载器在运行期注入,语义与旧加载器一致。
13
+ */
14
+
15
+ export interface LegacyClientModule {
16
+ readonly name?: string
17
+ readonly inject?: readonly string[]
18
+ readonly apply: (ctx: never) => void
19
+ }
20
+
21
+ export async function requestExtensionSetup(fetcher = fetch) {
22
+ const response = await fetcher(EXTENSION_INSTALL_ROUTE, { method: 'POST', headers: { accept: 'application/json' } })
23
+ const result = await response.json()
24
+ if (!response.ok || !result.ok) throw new Error(result.detail ?? `HTTP ${response.status}`)
25
+ return result
26
+ }
27
+
28
+ /**
29
+ * 装配旧面板:调用一次返回它的 `{ name, inject, apply }`。
30
+ * @param require - 模块加载器注入的 require(与旧加载器同签名)。
31
+ * @returns 旧 bundle 导出的模块对象。
32
+ */
33
+ export function loadSettingsPanel(require: (id: string) => unknown): LegacyClientModule {
34
+ var module = { exports: {} }
35
+ var exports = module.exports
36
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" })
37
+
38
+ const react = require("react")
39
+ const h = react.createElement
40
+ const { useCallback, useEffect, useRef, useState } = react
41
+
42
+ const name = "dsh-builtin-browser"
43
+ const inject = ["slots", "locale"]
44
+ const NS = "settings.dsh-builtin-browser"
45
+ const ROUTE = SETTINGS_ROUTE
46
+ let translate = (key) => key
47
+ let currentLocale = "zh"
48
+ function updateCurrentLocale(locale) {
49
+ let active
50
+ try { active = locale.getSnapshot?.().active ?? locale.getLocale?.().active } catch { /* Older hosts may only expose bind. */ }
51
+ const language = typeof active === "string" ? active : typeof document === "undefined" ? "" : document.documentElement?.lang
52
+ currentLocale = typeof language === "string" && /^en(?:-|$)/i.test(language) ? "en" : "zh"
53
+ }
54
+ /**
55
+ * Re-evaluate the floating watch entry.
56
+ *
57
+ * Set by `installWatchPanel`, called by the settings writer after a `remoteView` change so the
58
+ * switch takes effect on the spot. A no-op until the panel is installed, and a no-op forever on a
59
+ * host without one.
60
+ */
61
+ let refreshWatchEntry = () => {}
62
+ /**
63
+ * Re-apply the locale to the watch panel's static labels.
64
+ *
65
+ * Set by `installWatchPanel`, called from the locale subscription in `apply()`. Separate from
66
+ * {@link refreshWatchEntry} because a language switch must not re-probe or re-mount anything.
67
+ */
68
+ let refreshWatchLabels = () => {}
69
+
70
+
71
+ /**
72
+ * Read or patch the host-owned settings document.
73
+ *
74
+ * A patch that touches remote viewing re-evaluates the floating entry right away. Without that,
75
+ * turning the switch on wrote the file and did nothing anyone could see until the page was
76
+ * reloaded — unusable from a phone, and reported as such on #46.
77
+ */
78
+ async function callSettings(patch) {
79
+ const response = await fetch(ROUTE, patch === undefined
80
+ ? { method: "GET", headers: { accept: "application/json" } }
81
+ : {
82
+ method: "PUT",
83
+ headers: { "content-type": "application/json" },
84
+ body: JSON.stringify(patch),
85
+ })
86
+ const data = await response.json().catch(() => undefined)
87
+ if (data === undefined || data.ok !== true) {
88
+ throw new Error((data && data.error) || `HTTP ${response.status}`)
89
+ }
90
+ if (patch !== undefined && patch !== null && typeof patch === "object" && patch.remoteView !== undefined) {
91
+ try { refreshWatchEntry() } catch { /* the entry is a convenience, not the setting */ }
92
+ }
93
+ return data
94
+ }
95
+
96
+ /**
97
+ * The panel's own stylesheet.
98
+ *
99
+ * Inline styles cannot express `:hover`, and the rows need one — an interactive row with no
100
+ * feedback reads as decoration. The colours come from DSH's own design tokens
101
+ * (`--dsw-alias-*`, the same ones the host's settings rows use) so this follows the active
102
+ * theme instead of guessing at it; each has a literal fallback because a token may be absent
103
+ * under a third-party theme, and an unstyled row is worse than a slightly-off one.
104
+ */
105
+ const CSS = `
106
+ .dsh-bb-settings .dsh-bb-row {
107
+ min-height: 36px;
108
+ align-items: center;
109
+ justify-content: space-between;
110
+ padding: 8px 0;
111
+ border-bottom: .5px solid var(--dsw-alias-border-l2, GrayText);
112
+ border-radius: 0;
113
+ background: transparent;
114
+ }
115
+ .dsh-bb-settings { font-size: 14px; line-height: 22px; }
116
+ .dsh-bb-references > summary { display: list-item; }
117
+ .dsh-bb-ref-count { margin-left: 8px; color: var(--dsw-alias-label-tertiary, GrayText); font-size: 12px; font-weight: 400; }
118
+ .dsh-bb-ref-toolbar, .dsh-bb-ref-transfer-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
119
+ .dsh-bb-ref-toolbar { justify-content: flex-end; margin: 4px 0; }
120
+ .dsh-bb-ref-list { list-style: none; padding: 0; margin: 0; }
121
+ .dsh-bb-ref-item { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-bottom: .5px solid var(--dsw-alias-border-l2, GrayText); }
122
+ .dsh-bb-ref-content { flex: 1; min-width: 0; display: grid; gap: 4px; }
123
+ .dsh-bb-ref-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 500; }
124
+ .dsh-bb-ref-preview { margin: 0; color: var(--dsw-alias-label-secondary, inherit); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; font-size: 13px; line-height: 1.5; }
125
+ .dsh-bb-ref-meta { display: flex; flex-wrap: wrap; gap: 4px 8px; color: var(--dsw-alias-label-tertiary, GrayText); font-size: 12px; line-height: 1.5; }
126
+ .dsh-bb-ref-source { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
127
+ .dsh-bb-ref-item > button { flex: none; white-space: nowrap; }
128
+ .dsh-bb-ref-transfer { margin-top: 10px; }
129
+ .dsh-bb-ref-transfer-actions { padding: 6px 0; }
130
+ .dsh-bb-ref-outcome { margin: 0; font-size: 12px; line-height: 1.5; overflow-wrap: anywhere; }
131
+ @media (pointer: coarse) { .dsh-bb-ref-item > button, .dsh-bb-ref-toolbar button, .dsh-bb-ref-transfer-actions button { min-height: 40px !important; } }
132
+ .dsh-bb-ref-menu { position: relative; display: inline-flex; align-items: center; }
133
+ .dsh-bb-ref-toggle { font: inherit; padding: 4px 10px; border: .5px solid var(--dsw-alias-border-l2, GrayText); border-radius: 6px; background: transparent; color: inherit; cursor: pointer; white-space: nowrap; }
134
+ .dsh-bb-ref-toggle:hover { background: var(--dsw-alias-fill-hover, rgba(127,127,127,.12)); }
135
+ .dsh-bb-ref-popover { position: fixed; right: 24px; bottom: 88px; z-index: 2147483000; width: min(460px, calc(100vw - 32px)); max-height: min(70vh, 640px); overflow: auto; padding: 14px 16px; border: .5px solid var(--dsw-alias-border-l2, GrayText); border-radius: 10px; background: var(--dsw-alias-bg-l1, Canvas); color: var(--dsw-alias-label-primary, CanvasText); box-shadow: 0 8px 28px rgba(0,0,0,.18); font-size: 13px; }
136
+ .dsh-bb-ref-actions { display: flex; flex-wrap: wrap; gap: 6px; flex: none; }
137
+ .dsh-bb-ref-actions button { font-size: 12px; }
138
+ @media (pointer: coarse) { .dsh-bb-ref-actions button, .dsh-bb-ref-toggle { min-height: 40px !important; } }
139
+ .dsh-bb-settings .dsh-bb-diagnostics { margin-top: 4px; }
140
+ .dsh-bb-diagnostics code { display: block; max-height: 160px; overflow: auto; }
141
+ .dsh-bb-toggle { justify-content: space-between; cursor: pointer; }
142
+ .dsh-bb-toggle:has(:disabled) { cursor: default; }
143
+ .dsh-bb-switch {
144
+ appearance: none;
145
+ position: relative;
146
+ flex: 0 0 36px;
147
+ width: 36px;
148
+ height: 20px;
149
+ margin: 0;
150
+ box-sizing: border-box;
151
+ border: 0;
152
+ border-radius: 999px;
153
+ corner-shape: round;
154
+ background: var(--dsw-alias-border-l3, GrayText);
155
+ color: var(--dsw-alias-switch-thumb, Canvas);
156
+ cursor: inherit;
157
+ }
158
+ .dsh-bb-switch::after {
159
+ content: "";
160
+ position: absolute;
161
+ inset: 2px auto auto 2px;
162
+ width: 16px;
163
+ height: 16px;
164
+ border-radius: 50%;
165
+ corner-shape: round;
166
+ background: currentColor;
167
+ }
168
+ .dsh-bb-switch:checked {
169
+ background: var(--dsw-alias-brand-primary, Highlight);
170
+ color: var(--dsw-alias-label-primary-foreground, HighlightText);
171
+ }
172
+ .dsh-bb-switch:checked::after { transform: translateX(16px); }
173
+ .dsh-bb-switch:disabled { opacity: .6; }
174
+ .dsh-bb-settings :is(button, input, textarea, select, summary):focus-visible {
175
+ outline: var(--dsw-focus-ring-width, 2px) solid var(--dsw-focus-ring-color, Highlight);
176
+ outline-offset: 2px;
177
+ }
178
+ .dsh-bb-settings summary { cursor: pointer; padding: 5px 0; }
179
+ .dsh-bb-settings .dsh-bb-dd { flex: 0 1 auto; margin: 0; }
180
+ .dsh-bb-settings .dsh-bb-dd-btn {
181
+ min-height: 36px;
182
+ padding: 0 14px;
183
+ border: 0;
184
+ border-radius: var(--dsw-radius-md, 8px);
185
+ background: var(--dsw-alias-bg-module-platform, ButtonFace);
186
+ }
187
+ .dsh-bb-settings .dsh-bb-dd-list { left: auto; right: 0; }
188
+ .dsh-bb-settings .dsh-bb-input {
189
+ box-sizing: border-box;
190
+ width: 100%;
191
+ min-height: 34px;
192
+ padding: 6px 8px;
193
+ border: 1px solid var(--dsw-alias-border, GrayText);
194
+ border-radius: 7px;
195
+ background: var(--dsw-alias-bg-layer-1, Canvas);
196
+ color: var(--dsw-alias-label-primary, CanvasText);
197
+ font: inherit;
198
+ }
199
+ .dsh-bb-settings fieldset { min-inline-size: 0; }
200
+ .dsh-bb-settings textarea { resize: vertical; }
201
+ .dsh-bb-row {
202
+ border-radius: 8px;
203
+ padding: 7px 9px;
204
+ color: var(--dsw-alias-label-primary, inherit);
205
+ transition: background-color .12s ease;
206
+ }
207
+ /* Only the switch rows act as a single control; status and selector rows are plain text. */
208
+ .dsh-bb-toggle:hover:not(:has(:disabled)) {
209
+ background: var(--dsw-alias-interactive-bg-hover, rgba(128,128,128,.15));
210
+ }
211
+ .dsh-bb-toggle:active:not(:has(:disabled)) {
212
+ background: var(--dsw-alias-interactive-bg-active, rgba(128,128,128,.22));
213
+ }
214
+ /* The dropdown is drawn here rather than by the OS.
215
+ A native <select> paints its popup with system colours on Windows: the highlight overrides
216
+ whatever the option sets (white text on a white bar), and the list carries a border no CSS
217
+ can remove. Only the collapsed control is styleable, so a panel that matches its theme
218
+ everywhere else ends up with one control that does not. Everything below is ours: the
219
+ surface, the highlight, and the absence of that line. */
220
+ .dsh-bb-dd {
221
+ position: relative;
222
+ display: inline-block;
223
+ max-width: min(100%, calc(100vw - 32px));
224
+ margin-top: 4px;
225
+ }
226
+ .dsh-bb-dd-btn {
227
+ display: flex;
228
+ align-items: center;
229
+ gap: 8px;
230
+ max-width: 100%;
231
+ padding: 4px 8px 4px 9px;
232
+ border: 1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.4));
233
+ border-radius: 6px;
234
+ background: var(--dsw-alias-bg-layer-2, rgba(128,128,128,.12));
235
+ color: var(--dsw-alias-label-primary, inherit);
236
+ font: inherit;
237
+ text-align: left;
238
+ cursor: pointer;
239
+ }
240
+ .dsh-bb-dd-btn:hover:not(:disabled) {
241
+ background: var(--dsw-alias-interactive-bg-hover, rgba(128,128,128,.18));
242
+ }
243
+ .dsh-bb-dd-btn:disabled { opacity: .55; cursor: default; }
244
+ .dsh-bb-dd-btn > span:first-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
245
+ .dsh-bb-dd-caret { flex-shrink: 0; opacity: .6; font-size: 10px; line-height: 1; }
246
+ .dsh-bb-dd-list {
247
+ position: absolute;
248
+ box-sizing: border-box;
249
+ z-index: 20;
250
+ top: calc(100% + 4px);
251
+ left: 0;
252
+ width: max-content;
253
+ min-width: 100%;
254
+ max-width: min(340px, calc(100vw - 32px));
255
+ padding: 4px;
256
+ border: 1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.4));
257
+ border-radius: 8px;
258
+ background: var(--dsw-alias-bg-layer-2, #2f2f2f);
259
+ box-shadow: 0 6px 20px rgba(0,0,0,.28);
260
+ }
261
+ .dsh-bb-dd-opt {
262
+ display: block;
263
+ box-sizing: border-box;
264
+ width: 100%;
265
+ padding: 6px 9px;
266
+ border: none;
267
+ border-radius: 6px;
268
+ background: transparent;
269
+ color: var(--dsw-alias-label-primary, inherit);
270
+ font: inherit;
271
+ text-align: left;
272
+ white-space: nowrap;
273
+ overflow: hidden;
274
+ text-overflow: ellipsis;
275
+ cursor: pointer;
276
+ }
277
+ /* The same ellipse the rows use, so the panel reads as one surface — and it is ours to draw,
278
+ which is the whole reason this control exists. */
279
+ .dsh-bb-dd-opt:hover,
280
+ .dsh-bb-dd-opt[data-active="true"] {
281
+ background: var(--dsw-alias-interactive-bg-hover, rgba(128,128,128,.18));
282
+ }
283
+ .dsh-bb-dd-opt[aria-selected="true"] { font-weight: 600; }
284
+
285
+ /* Live-view panel. Fixed layer rather than a slot: the host has no stable slot for an extra
286
+ surface over the conversation, and a layer works in every layout including a phone. */
287
+ .dsh-bw-watch {
288
+ position: fixed; right: 16px; bottom: 16px; font-family: inherit;
289
+ /* Below a modal or popover rather than above everything: the old 2147483000 sat on top of the page,
290
+ * its inputs and any dialog the host opened (issue #46). A floating helper is a guest here. */
291
+ z-index: 1000;
292
+ }
293
+ .dsh-bw-watch-open {
294
+ display: inline-flex; align-items: center; gap: 7px; cursor: pointer;
295
+ border: 1px solid var(--dsw-alias-border, rgba(128,128,128,.45)); border-radius: 999px;
296
+ padding: 7px 13px; font-size: 12px; color: inherit;
297
+ background: var(--dsw-alias-interactive-bg, rgba(128,128,128,.12));
298
+ }
299
+ .dsh-bw-watch-open:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(128,128,128,.2)); }
300
+ .dsh-bw-watch-dot { width: 7px; height: 7px; border-radius: 50%; background: #d9534f; }
301
+ .dsh-bw-watch-panel {
302
+ position: absolute; right: 0; bottom: calc(100% + 8px); width: min(560px, calc(100vw - 32px));
303
+ /* The panel used to sit at 40px from the bottom while the button it hangs off occupied 16-46px
304
+ * from the bottom edge of its own box: the two overlapped by 6px and, because the panel's
305
+ * background is opaque, it covered the only way back out (issue #46). 100% is the button's own
306
+ * height, so the gap survives a font-size or padding change instead of being a second magic
307
+ * number. */
308
+ border: 1px solid var(--dsw-alias-border, rgba(128,128,128,.35)); border-radius: 10px;
309
+ /* --dsw-alias-bg-elevated does not exist in the theme this ships against (measured on rc.5: 0
310
+ * occurrences, while --dsw-alias-bg-layer-2 has 5). With a token that is never defined, the
311
+ * fallback is what everyone sees — a dark card in a light theme. bg-layer-2 is the token the
312
+ * host's own elevated rows use. */
313
+ background: var(--dsw-alias-bg-layer-2, #1b1b1f); color: inherit; overflow: hidden;
314
+ box-shadow: 0 10px 30px rgba(0,0,0,.35);
315
+ }
316
+ .dsh-bw-watch-head { display: flex; align-items: center; gap: 8px; padding: 8px 10px; font-size: 12px; }
317
+ .dsh-bw-watch-title { font-weight: 600; }
318
+ .dsh-bw-watch-state { opacity: .7; margin-left: auto; }
319
+ .dsh-bw-watch-session {
320
+ max-width: 40%; font-size: 11px; color: inherit; background: transparent; cursor: pointer;
321
+ border: 1px solid var(--dsw-alias-border, rgba(128,128,128,.45)); border-radius: 5px; padding: 2px 4px;
322
+ }
323
+ .dsh-bw-watch-session[hidden] { display: none; }
324
+ .dsh-bw-watch-close {
325
+ /* A visible control, not a hinted one: the old close was a 16px glyph at 70% opacity with no border
326
+ * or background, in the same colour as the title — reported as 'no way out but a page refresh'
327
+ * (issue #46). */
328
+ border: 1px solid var(--dsw-alias-border, rgba(128,128,128,.45)); border-radius: 6px;
329
+ background: var(--dsw-alias-interactive-bg, rgba(128,128,128,.12));
330
+ color: inherit; cursor: pointer; font-size: 14px; line-height: 1; padding: 3px 7px;
331
+ }
332
+ .dsh-bw-watch-close:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(128,128,128,.2)); }
333
+ .dsh-bw-watch-stage { background: #000; min-height: 120px; display: flex; align-items: center; justify-content: center; }
334
+ .dsh-bw-watch-img { display: block; max-width: 100%; height: auto; }
335
+ /* The hidden ATTRIBUTE is styled by the UA sheet as [hidden]{display:none}, and an author rule
336
+ * defeats it whatever its specificity — so img.hidden = true in the script did nothing and the
337
+ * empty-state image kept taking space (issue #46). */
338
+ .dsh-bw-watch-img[hidden] { display: none; }
339
+ .dsh-bw-watch-note { margin: 0; padding: 24px 14px; font-size: 12px; opacity: .75; text-align: center; }
340
+ .dsh-bw-watch-foot {
341
+ display: flex; align-items: center; gap: 8px; padding: 7px 10px;
342
+ font-size: 11px; border-top: 1px solid var(--dsw-alias-border, rgba(128,128,128,.25));
343
+ }
344
+ .dsh-bw-watch-readonly { opacity: .6; }
345
+ .dsh-bw-watch-bridge { padding: 8px 10px; font-size: 11px; border-bottom: 1px solid var(--dsw-alias-border, rgba(128,128,128,.25)); background: rgba(217,83,79,.12); }
346
+ .dsh-bw-watch-bridge-line { line-height: 1.5; }
347
+ .dsh-bw-watch-bridge-cmd { display: block; margin-top: 5px; padding: 5px 7px; font-size: 11px; white-space: pre-wrap; word-break: break-all; background: rgba(0,0,0,.28); border-radius: 5px; }
348
+ .dsh-bw-watch-stop {
349
+ margin-left: auto; cursor: pointer; font-size: 11px; padding: 4px 10px;
350
+ border: 1px solid var(--dsw-alias-border, rgba(128,128,128,.45)); border-radius: 6px;
351
+ background: transparent; color: inherit;
352
+ }
353
+ `
354
+
355
+ /** Install the stylesheet once, however many times the panel is mounted. */
356
+ function installStyles() {
357
+ if (typeof document === "undefined") return
358
+ if (document.getElementById("dsh-builtin-browser-styles") !== null) return
359
+ const tag = document.createElement("style")
360
+ tag.id = "dsh-builtin-browser-styles"
361
+ tag.textContent = CSS
362
+ document.head.appendChild(tag)
363
+ }
364
+
365
+ const styles = {
366
+ wrap: { display: "flex", flexDirection: "column", gap: "12px" },
367
+ lead: { opacity: 0.75, lineHeight: 1.6, margin: 0 },
368
+ group: { minWidth: 0 },
369
+ groupTitle: { margin: "0 0 2px", fontSize: "14px", fontWeight: 600, color: "var(--dsw-alias-label-primary, inherit)" },
370
+ row: { display: "flex", gap: "10px", alignItems: "flex-start" },
371
+ label: { display: "flex", flexDirection: "column", gap: "2px", cursor: "pointer" },
372
+ hint: { color: "var(--dsw-alias-label-tertiary, inherit)", fontSize: "12px", lineHeight: 1.5 },
373
+ status: { opacity: 0.7, minHeight: "18px" },
374
+ error: { color: "var(--dsw-alias-label-error, #c9342c)" },
375
+ pathLine: { opacity: 0.6, wordBreak: "break-all", lineHeight: 1.5 },
376
+ button: { minHeight: "32px", padding: "5px 12px", borderRadius: "8px", border: "1px solid var(--dsw-alias-border, rgba(128,128,128,.4))", background: "transparent", color: "inherit", font: "inherit", cursor: "pointer" },
377
+ // Readiness: one headline state, three one-line facts, and at most two buttons. The colours are
378
+ // the only place this panel states an opinion, which is why they carry no text of their own —
379
+ // the label next to them is always a locale string.
380
+ badge: { display: "inline-block", padding: "1px 8px", marginRight: "8px", borderRadius: "10px", fontSize: "11px", lineHeight: 1.6, border: "1px solid transparent" },
381
+ badgeOk: { color: "#2f9e44", borderColor: "rgba(47,158,68,.5)", background: "rgba(47,158,68,.12)" },
382
+ // Amber is "recoverable, act if you want"; red is reserved for a real failure. A blocked
383
+ // readiness whose extension is simply not connected used to be red, which read as "your
384
+ // browser was found but it is broken".
385
+ badgeWarn: { color: "#b26a00", borderColor: "rgba(178,106,0,.5)", background: "rgba(178,106,0,.12)" },
386
+ badgeError: { color: "#e5534b", borderColor: "rgba(229,83,75,.5)", background: "rgba(229,83,75,.12)" },
387
+ badgeUnknown: { color: "#a0a0a8", borderColor: "rgba(160,160,168,.5)", background: "rgba(160,160,168,.12)" },
388
+ kv: { display: "grid", gridTemplateColumns: "auto 1fr", gap: "3px 12px", margin: "8px 0 0", fontSize: "12px" },
389
+ kvKey: { opacity: 0.68 },
390
+ kvVal: { lineHeight: 1.5 },
391
+ mono: { fontFamily: "ui-monospace, SFMono-Regular, Consolas, monospace", fontSize: "11px", whiteSpace: "pre-wrap", wordBreak: "break-all", background: "var(--dsw-alias-bg-layer-2, rgba(0,0,0,.22))", borderRadius: "5px", padding: "4px 6px", marginTop: "4px" },
392
+ buttons: { display: "flex", gap: "8px", alignItems: "center", marginTop: "10px", flexWrap: "wrap" },
393
+ }
394
+
395
+ /**
396
+ * A dropdown drawn by this panel rather than by the operating system.
397
+ *
398
+ * Replaces a native `<select>`, whose popup Windows paints with system colours: the hover
399
+ * highlight overrode the option's background (white text on a white bar) and the list carried
400
+ * a border no CSS could remove. Both are unfixable from outside the control, and this panel's
401
+ * two dropdowns were the only places it did not match its own theme.
402
+ *
403
+ * Keyboard and assistive-technology behaviour is reimplemented rather than inherited, which is
404
+ * the cost of owning the rendering: Up/Down move, Enter/Space commit, Escape closes and
405
+ * returns focus, Home/End jump, clicking outside closes.
406
+ */
407
+ function Dropdown(props) {
408
+ const [open, setOpen] = useState(false)
409
+ // Index the keyboard has moved to; -1 means "the selected value, unless the user moved".
410
+ const [active, setActive] = useState(-1)
411
+ const rootRef = useRef(null)
412
+ const buttonRef = useRef(null)
413
+
414
+ const selected = props.options.findIndex(option => option.value === props.value)
415
+ const current = props.options[selected] ?? props.options[0]
416
+
417
+ useEffect(() => {
418
+ if (!open) return undefined
419
+ const away = event => {
420
+ if (rootRef.current !== null && !rootRef.current.contains(event.target)) setOpen(false)
421
+ }
422
+ document.addEventListener("mousedown", away)
423
+ return () => document.removeEventListener("mousedown", away)
424
+ }, [open])
425
+
426
+ const commit = index => {
427
+ const option = props.options[index]
428
+ if (option === undefined) return
429
+ setOpen(false)
430
+ setActive(-1)
431
+ buttonRef.current?.focus()
432
+ if (option.value !== props.value) props.onChange(option.value)
433
+ }
434
+
435
+ const onKeyDown = event => {
436
+ if (event.key === "Escape") {
437
+ if (open) { event.preventDefault(); setOpen(false); buttonRef.current?.focus() }
438
+ return
439
+ }
440
+ if (!open && (event.key === "Enter" || event.key === " " || event.key === "ArrowDown")) {
441
+ event.preventDefault()
442
+ setOpen(true)
443
+ setActive(selected >= 0 ? selected : 0)
444
+ return
445
+ }
446
+ if (!open) return
447
+ const last = props.options.length - 1
448
+ if (event.key === "ArrowDown") { event.preventDefault(); setActive(a => Math.min(last, (a < 0 ? selected : a) + 1)) }
449
+ else if (event.key === "ArrowUp") { event.preventDefault(); setActive(a => Math.max(0, (a < 0 ? selected : a) - 1)) }
450
+ else if (event.key === "Home") { event.preventDefault(); setActive(0) }
451
+ else if (event.key === "End") { event.preventDefault(); setActive(last) }
452
+ else if (event.key === "Enter" || event.key === " ") { event.preventDefault(); commit(active < 0 ? selected : active) }
453
+ }
454
+
455
+ return h("div", { key: "s", className: "dsh-bb-dd", ref: rootRef }, [
456
+ h("button", {
457
+ key: "b",
458
+ type: "button",
459
+ ref: buttonRef,
460
+ className: "dsh-bb-dd-btn",
461
+ "aria-label": props.label + ": " + (current?.label ?? ""),
462
+ disabled: props.disabled,
463
+ "aria-haspopup": "listbox",
464
+ "aria-expanded": open ? "true" : "false",
465
+ onBlur: event => {
466
+ if (!rootRef.current?.contains(event.relatedTarget)) setOpen(false)
467
+ },
468
+ onClick: () => { setOpen(o => !o); setActive(-1) },
469
+ onKeyDown,
470
+ }, [
471
+ h("span", { key: "v" }, current === undefined ? "" : current.label),
472
+ h("span", { key: "c", className: "dsh-bb-dd-caret", "aria-hidden": "true" }, "\u25be"),
473
+ ]),
474
+ open ? h("div", {
475
+ key: "l",
476
+ className: "dsh-bb-dd-list",
477
+ role: "listbox",
478
+ "aria-label": props.label,
479
+ }, props.options.map((option, index) => h("button", {
480
+ key: option.value,
481
+ type: "button",
482
+ className: "dsh-bb-dd-opt",
483
+ role: "option",
484
+ tabIndex: -1,
485
+ "aria-selected": option.value === props.value ? "true" : "false",
486
+ onMouseDown: event => event.preventDefault(),
487
+ "data-active": index === active ? "true" : "false",
488
+ onMouseEnter: () => setActive(index),
489
+ onClick: () => commit(index),
490
+ }, option.label))) : null,
491
+ ])
492
+ }
493
+
494
+ /** One boolean switch bound to a settings path. */
495
+ function Toggle(props) {
496
+ const t = translate
497
+ return h("label", { style: styles.row, className: "dsh-bb-row dsh-bb-toggle" }, [
498
+ h("span", { key: "l", style: styles.label }, [
499
+ h("span", { key: "t" }, t(props.labelKey)),
500
+ props.hintKey ? h("span", { key: "h", style: styles.hint }, t(props.hintKey)) : null,
501
+ ]),
502
+ h("input", {
503
+ key: "i",
504
+ type: "checkbox",
505
+ className: "dsh-bb-switch",
506
+ role: "switch",
507
+ "aria-label": t(props.labelKey),
508
+ checked: props.checked,
509
+ disabled: props.busy,
510
+ onChange: event => props.onChange(event.target.checked),
511
+ }),
512
+ ])
513
+ }
514
+
515
+ /**
516
+ * Re-render this component when the interface language changes at run time.
517
+ *
518
+ * `translate` is a module-level binding that `apply()` re-binds on every locale snapshot, but
519
+ * React has no idea that happened: every label rendered so far keeps the language it was rendered
520
+ * in, which is exactly the defect the watch panel hit (#40) and the one commit `666cbff` fixed for
521
+ * that panel's DOM. The settings section is rendered by React, so it needs the notification rather
522
+ * than a text pass.
523
+ */
524
+ let localeVersion = 0
525
+ const localeWatchers = new Set()
526
+ function useLocaleVersion() {
527
+ const [, setVersion] = useState(localeVersion)
528
+ useEffect(() => {
529
+ const update = () => setVersion(localeVersion)
530
+ localeWatchers.add(update)
531
+ return () => { localeWatchers.delete(update) }
532
+ }, [])
533
+ }
534
+
535
+ /**
536
+ * Readiness: can the browser serve a call right now, and what is missing if not.
537
+ *
538
+ * This is the "it works once you install it" promise, made visible. The bundled runtime downloads
539
+ * on first need (issue #41 moved the download out of `postinstall`), so on a fresh install the
540
+ * honest answer for the first minute is "a download is running" — a state that used to exist only
541
+ * in a log line. Everything shown here comes from `GET /runtime-status`; the button starts the
542
+ * same one background attempt the plugin makes on its own, which is why pressing it is never
543
+ * harmful and never starts a second download.
544
+ */
545
+ const hostPatchNoticeEvent = "dsh-builtin-browser:host-patch-notice"
546
+ function readHostPatchNotice() {
547
+ try {
548
+ const saved = JSON.parse(sessionStorage.getItem(hostPatchNoticeEvent))
549
+ return saved?.page === performance.timeOrigin ? saved.key : ""
550
+ } catch { return "" /* Storage may be unavailable. */ }
551
+ }
552
+ function publishHostPatchNotice(key) {
553
+ try { sessionStorage.setItem(hostPatchNoticeEvent, JSON.stringify({ page: performance.timeOrigin, key })) }
554
+ catch { /* An open panel can still show the result without storage. */ }
555
+ if (typeof window !== "undefined") window.dispatchEvent(new CustomEvent(hostPatchNoticeEvent, { detail: key }))
556
+ }
557
+
558
+ function HostPatchControls() {
559
+ useLocaleVersion()
560
+ const t = translate
561
+ const [state, setState] = useState(null)
562
+ const [busy, setBusy] = useState(false)
563
+ const [error, setError] = useState("")
564
+ const [notice, setNotice] = useState(readHostPatchNotice)
565
+ const alive = useRef(true)
566
+ const pending = useRef(false)
567
+ useEffect(() => {
568
+ if (typeof window === "undefined") return
569
+ const target = window
570
+ const update = event => setNotice(event.detail)
571
+ target.addEventListener(hostPatchNoticeEvent, update)
572
+ return () => target.removeEventListener(hostPatchNoticeEvent, update)
573
+ }, [])
574
+ useEffect(() => {
575
+ alive.current = true
576
+ void fetch(HOST_PATCH_ROUTE, { headers: { accept: "application/json" } })
577
+ .then(async response => {
578
+ if (response.status === 404) return
579
+ const data = await response.json()
580
+ if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`)
581
+ if (alive.current && (data.hostPatch?.surface === "web" || data.hostPatch?.surface === "tauri")) setState(data.hostPatch)
582
+ }).catch(failure => { if (alive.current) setError(String(failure)) })
583
+ return () => { alive.current = false }
584
+ }, [])
585
+ const change = async action => {
586
+ if (pending.current) return
587
+ pending.current = true
588
+ setBusy(true); setError(""); setNotice(""); publishHostPatchNotice("")
589
+ try {
590
+ const response = await fetch(HOST_PATCH_ROUTE, {
591
+ method: "POST", headers: { accept: "application/json", "content-type": "application/json" },
592
+ body: JSON.stringify({ action }),
593
+ })
594
+ const data = await response.json()
595
+ if (alive.current && data.hostPatch) setState(data.hostPatch)
596
+ if (!response.ok || data.ok !== true) throw new Error(data.error || data.hostPatch?.reason || `HTTP ${response.status}`)
597
+ const noticeKey = data.hostPatch.surface === "tauri" ? "hostPatch.restartTauri" : data.hostPatch.restartRequired ? "hostPatch.restart" : "hostPatch.reload"
598
+ publishHostPatchNotice(noticeKey)
599
+ if (alive.current) setNotice(noticeKey)
600
+ } catch (failure) { if (alive.current) setError(String(failure)) }
601
+ finally { pending.current = false; if (alive.current) setBusy(false) }
602
+ }
603
+ if (state === null && error === "") return null
604
+ // The host says whether this line needs a patch at all (its spec carries `native`). A host that
605
+ // already supports the feature keeps the section out; older lines still get one action.
606
+ if (state?.needed === false) return null
607
+ // One row, one action. Nothing actionable and nothing wrong means this host needs no patch at
608
+ // all, so the whole section stays out of the panel instead of offering a no-op install.
609
+ const status = String(state?.status ?? "")
610
+ const applied = status === "applied"
611
+ const broken = /mismatch|unsupported|failed/u.test(status)
612
+ const actionable = applied ? state?.canRestore === true : state?.canInstall === true
613
+ const action = applied ? "restore" : "install"
614
+ const actionKey = applied ? "hostPatch.uninstall" : broken ? "hostPatch.reinstall" : "hostPatch.install"
615
+ return h("div", { key: "web-host-patch", style: styles.group }, [
616
+ h("div", { key: "row", className: "dsh-bb-row", style: styles.row }, [
617
+ h("span", { key: "title", role: "status" }, t(state?.surface === "tauri" ? "readiness.hostPatch.tauri" : "readiness.hostPatch") + (state ? ": " + t((state.surface === "tauri" && applied ? "readiness.hostPatch.tauri." : "readiness.hostPatch.") + status.replaceAll(" ", "-")) : "")),
618
+ h("button", { key: "action", type: "button", style: styles.button, disabled: busy || state === null || !actionable, onClick: () => change(action) }, t(busy ? "hostPatch.working" : actionKey)),
619
+ ]),
620
+ state?.reason ? h("p", { key: "reason", style: styles.hint }, state.reason) : null,
621
+ notice ? h("p", { key: "notice", role: "status", style: styles.hint }, t(notice)) : null,
622
+ error ? h("p", { key: "error", role: "alert", style: styles.error }, error) : null,
623
+ ])
624
+ }
625
+
626
+ function Readiness({ channel, experimental = false } = {}) {
627
+ useLocaleVersion()
628
+ const t = translate
629
+ const [runtime, setRuntime] = useState(null)
630
+ const [error, setError] = useState("")
631
+ const [unsupported, setUnsupported] = useState(false)
632
+ const [busy, setBusy] = useState(false)
633
+ const [bridgeBusy, setBridgeBusy] = useState(null)
634
+ const [bridgeJob, setBridgeJob] = useState(null)
635
+ const [bridgePollVersion, setBridgePollVersion] = useState(0)
636
+ const [bridgeError, setBridgeError] = useState(null)
637
+ const [extensionMessage, setExtensionMessage] = useState('')
638
+ const bridgePending = useRef(false)
639
+ const bridgeSubmitting = useRef(false)
640
+ const bridgeJobId = useRef(null)
641
+ const alive = useRef(true)
642
+
643
+ const read = useCallback(async () => {
644
+ try {
645
+ const response = await fetch(RUNTIME_STATUS_ROUTE, { headers: { accept: "application/json" } })
646
+ // A host that predates this route answers 404, and that is a version skew rather than a
647
+ // fault: after an update the client bundle is read at request time while the host's code is
648
+ // what started with the process. Rendering "could not read readiness: HTTP 404" at a user who
649
+ // simply has not restarted yet would be reporting the skew as their problem — so the section
650
+ // stays out of the way, exactly like a document with no `actions` section.
651
+ if (response.status === 404) {
652
+ if (alive.current) { setUnsupported(true); setRuntime(null); setError("") }
653
+ return null
654
+ }
655
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
656
+ const data = await response.json()
657
+ if (data.runtime?.bridge) {
658
+ const extensions = typeof window === "undefined" ? undefined : window.dshDesktop?.mainExtensions
659
+ if (typeof extensions?.status === "function") {
660
+ const status = await extensions.status("dsh-builtin-browser")
661
+ data.runtime.bridge = { ...data.runtime.bridge, mainExtension: status, code: status.code, command: undefined,
662
+ state: status.state === "loaded" ? "installed" : status.state === "not-installed" ? "missing" : "stale" }
663
+ } else if (!data.runtime.bridge.mainExtension) {
664
+ data.runtime.bridge = { ...data.runtime.bridge, code: "DESKTOP_MAIN_EXTENSION_UNSUPPORTED" }
665
+ }
666
+ }
667
+ if (!alive.current) return null
668
+ setUnsupported(false)
669
+ setRuntime(data && data.runtime ? data.runtime : null)
670
+ setError("")
671
+ return data && data.runtime ? data.runtime : null
672
+ } catch (failure) {
673
+ if (!alive.current) return null
674
+ setError(String(failure && failure.message ? failure.message : failure))
675
+ return null
676
+ }
677
+ }, [])
678
+
679
+ const bridgeActivePhases = ["armed", "closing", "installing", "restarting", "verifying"]
680
+ const bridgeActive = bridgeJob !== null && bridgeActivePhases.includes(bridgeJob.phase)
681
+ const readBridgeJob = useCallback(async () => {
682
+ try {
683
+ const response = await fetch(AUTOMATIC_MAINTENANCE_ROUTE, { headers: { accept: "application/json" } })
684
+ if (!response.ok) return
685
+ const data = await response.json()
686
+ if (!alive.current || bridgeSubmitting.current || data.ok !== true || data.protocol !== 1 || !data.job || typeof data.job.id !== "string") return
687
+ if (bridgePending.current && bridgeJobId.current !== null && bridgeJobId.current !== data.job.id) return
688
+ bridgeJobId.current = data.job.id
689
+ bridgePending.current = ["armed", "closing", "installing", "restarting", "verifying"].includes(data.job.phase)
690
+ setBridgeJob(data.job)
691
+ if (data.job.phase === "completed") void read()
692
+ } catch { /* The desktop is briefly offline while maintenance restarts it. Keep its job. */ }
693
+ finally { if (alive.current) setBridgePollVersion(version => version + 1) }
694
+ }, [read])
695
+
696
+ useEffect(() => {
697
+ alive.current = true
698
+ void read()
699
+ void readBridgeJob()
700
+ return () => { alive.current = false }
701
+ }, [read, readBridgeJob, channel])
702
+
703
+ useEffect(() => {
704
+ if (!bridgeActive) return undefined
705
+ const timer = setTimeout(() => { void readBridgeJob() }, 1000)
706
+ return () => clearTimeout(timer)
707
+ }, [bridgeActive, bridgeJob, bridgePollVersion, readBridgeJob])
708
+
709
+ // Poll only while a download is running: that is the one state that changes on its own, and a
710
+ // poll in any other state would be a background request per panel per two seconds forever.
711
+ const preparing = runtime !== null && runtime.electron.state === "preparing"
712
+ useEffect(() => {
713
+ if (!preparing) return undefined
714
+ const timer = setTimeout(() => { void read() }, 2000)
715
+ return () => clearTimeout(timer)
716
+ }, [preparing, runtime, read])
717
+
718
+ const prepare = async () => {
719
+ setBusy(true)
720
+ setError("")
721
+ try {
722
+ const response = await fetch(RUNTIME_PROVISION_ROUTE, {
723
+ method: "POST",
724
+ headers: { accept: "application/json" },
725
+ })
726
+ const data = await response.json().catch(() => ({}))
727
+ if (!response.ok) throw new Error((data && data.error) || `HTTP ${response.status}`)
728
+ if (alive.current && data && data.runtime) setRuntime(data.runtime)
729
+ } catch (failure) {
730
+ if (alive.current) setError(String(failure && failure.message ? failure.message : failure))
731
+ } finally {
732
+ if (alive.current) setBusy(false)
733
+ void read()
734
+ }
735
+ }
736
+
737
+ const bridgeAction = async (requested = "reinstall") => {
738
+ const action = requested
739
+ if (bridgePending.current || busy || bridgeActive) return
740
+ const desktopMenu = () => typeof document.querySelector === "function"
741
+ ? document.querySelector("[data-windows-menu]")?.shadowRoot?.querySelector("button") : null
742
+ // Windows Desktop draws its own menu; macOS uses the native menu bar, so its Desktop preload is the proof.
743
+ const inDesktop = typeof desktopMenu()?.click === "function" || (globalThis.dshDesktop !== null && typeof globalThis.dshDesktop === "object")
744
+ if (!inDesktop) {
745
+ setBridgeError({ key: "readiness.bridge.localOnly" })
746
+ return
747
+ }
748
+ bridgePending.current = true
749
+ bridgeSubmitting.current = true
750
+ setBridgeBusy(action)
751
+ setBridgeJob(null)
752
+ setBridgeError(null)
753
+ let accepted = false
754
+ try {
755
+ const response = await fetch(AUTOMATIC_MAINTENANCE_ROUTE, {
756
+ method: "POST",
757
+ headers: { accept: "application/json", "content-type": "application/json" },
758
+ body: JSON.stringify({ action, locale: currentLocale }),
759
+ })
760
+ const data = await response.json().catch(() => ({}))
761
+ if (response.status === 404) {
762
+ if (alive.current) setBridgeError({ key: "readiness.bridge.unsupported" })
763
+ return
764
+ }
765
+ if (!response.ok || data.ok !== true) throw new Error(data.error || data.output || `HTTP ${response.status}`)
766
+ if (data.protocol !== 1 || data.accepted !== true || typeof data.job?.id !== "string" || data.job.phase !== "armed" || data.job.action !== action) throw new Error("invalid bridge maintenance acknowledgement")
767
+ accepted = true
768
+ bridgeJobId.current = data.job.id
769
+ if (alive.current) setBridgeJob(data.job)
770
+ if (data.quit === "self") return
771
+ const menu = desktopMenu()
772
+ if (typeof menu?.click !== "function") throw new Error(t("readiness.bridge.localOnly"))
773
+ // The armed worker selects Exit in this official native menu. This opens that menu only
774
+ // after the new maintenance endpoint has acknowledged the handoff.
775
+ menu.click()
776
+ } catch (failure) {
777
+ if (alive.current) setBridgeError({ key: "readiness.bridge.actionFailed", detail: String(failure && failure.message ? failure.message : failure) })
778
+ } finally {
779
+ bridgeSubmitting.current = false
780
+ if (!accepted) bridgePending.current = false
781
+ if (alive.current) setBridgeBusy(null)
782
+ }
783
+ }
784
+
785
+ if (unsupported) return null
786
+ if (runtime === null) {
787
+ return h("div", { style: styles.wrap }, [
788
+ h("p", { key: "l", style: styles.lead }, error === "" ? t("readiness.loading") : `${t("readiness.failed")} ${error}`),
789
+ ])
790
+ }
791
+
792
+ // Usable is one colour. CDP readiness, a detected browser that has not been launched yet, and the
793
+ // Web sidebar all mean "this works"; amber stays for genuinely unusable states.
794
+ // `isDesktop`/`carrierIsSidebar` are declared below; inline those two facts here. Usable is one
795
+ // colour: CDP readiness, a detected-but-not-yet-launched browser, and the Web sidebar all mean
796
+ // "this works"; amber stays for genuinely unusable states.
797
+ const desktopNow = typeof globalThis.dshDesktop === "object" && globalThis.dshDesktop !== null
798
+ const sidebarNow = runtime.resolvedCarrier === "sidebar" || runtime.carrier === "sidebar" || runtime.carrier === "bundled"
799
+ const usable = runtime.readiness === "ready" || (!desktopNow && sidebarNow)
800
+ // A detected browser is usable: the plugin launches it over CDP on the first command, so
801
+ // "found but not connected yet" is not a warning — that was the amber badge the user kept seeing.
802
+ || runtime.systemBrowser?.present === true
803
+ const tone = usable ? styles.badgeOk
804
+ : runtime.readiness === "blocked" ? styles.badgeWarn : styles.badgeUnknown
805
+ const row = (key, label, value) => [
806
+ h("span", { key: `${key}-k`, style: styles.kvKey }, label),
807
+ h("span", { key: `${key}-v`, style: styles.kvVal }, value),
808
+ ]
809
+ // "Installed" and "running" are different facts, and the gap between them is the most common
810
+ // broken state there is (the desktop app is simply closed). The row says which one it means —
811
+ // and when the host does not report the running half at all, it says the plain truth rather
812
+ // than inferring "not running" from an absent field.
813
+ const bridgeLabel = runtime.bridge.state !== "installed"
814
+ ? t(`readiness.bridge.${runtime.bridge.state}`)
815
+ : runtime.bridge.running === true
816
+ ? t("readiness.bridge.installedRunning")
817
+ : runtime.bridge.running === false
818
+ ? t("readiness.bridge.installedNotRunning")
819
+ : t("readiness.bridge.installed")
820
+ const resolvedCarrier = runtime.resolvedCarrier ?? (runtime.carrier === "auto"
821
+ ? runtime.bridge.state === "installed" && runtime.bridge.running === true ? "sidebar"
822
+ : runtime.systemBrowser?.present === true ? "system" : "bundled"
823
+ : runtime.carrier)
824
+ const systemName = ({ chrome: "Chrome", edge: "Edge", brave: "Brave" })[runtime.systemBrowser?.kind ?? runtime.channel] ?? t("readiness.system")
825
+ const systemLabel = runtime.systemBrowser?.checked === true
826
+ ? t(runtime.systemBrowser.present ? "readiness.status.systemReady" : "readiness.status.systemMissing").replace("{browser}", systemName)
827
+ : t("readiness.status.checkPending")
828
+ // A third-party desktop shell is never patched (issue #62): no bridge controls, and the system
829
+ // browser is recommended first because it works from this page right now.
830
+ // Which rows and diagnostics belong to the selected carrier: bridge/patch are sidebar-only,
831
+ // native-host registration is the Installed Chrome/Edge path only. Showing every carrier's
832
+ // errors at once is what made all three modes look identically broken.
833
+ // `bundled` is the legacy name of the sidebar carrier, so it counts as sidebar here too.
834
+ const carrierIsSidebar = resolvedCarrier === "sidebar" || runtime.carrier === "sidebar" || runtime.carrier === "bundled"
835
+ const selectedSystemBrowser = runtime.channel === "edge" ? "edge" : runtime.channel === "chrome" ? "chrome" : undefined
836
+ const thirdPartyShell = runtime.shell?.kind === "third-party-shell"
837
+ const shellBrowserName = runtime.shell?.recommendedCarrier === "edge" ? "Edge" : "Chrome"
838
+ const extensionDisconnected = runtime.extension?.state === 'not-connected' || runtime.extension?.state === 'extension-missing'
839
+ // Desktop presence is the only honest signal for the bridge / host-patch / extension rows: a
840
+ // Desktop install on disk is not proof that THIS page is the Desktop shell, and the Web surface
841
+ // has none of those three things. Defined before `stateLabel`, which must not report a bridge
842
+ // state on the Web surface.
843
+ const isDesktop = typeof globalThis.dshDesktop === "object" && globalThis.dshDesktop !== null
844
+ const isSystemCarrier = runtime.channel === 'chrome' || runtime.channel === 'edge'
845
+ // A healthy bridge makes an older terminal failure stale: the record on disk is only replaced
846
+ // when the next maintenance starts, so it must not keep colouring the panel red (issue #142).
847
+ const bridgeHealthy = runtime.bridge.state === "installed" && runtime.bridge.running === true
848
+ // The patch row is about the sidebar carrier only, and only while this Desktop build cannot
849
+ // provide native views by itself: a host that already exposes them needs nothing from us, so
850
+ // the row is absent instead of offering a no-op install.
851
+ const channelIsSidebar = runtime.channel === 'sidebar' || runtime.channel === 'bundled'
852
+ const nativeViewsPresent = typeof globalThis.dshDesktop?.browser?.nativeViews === 'object'
853
+ const stateLabel = resolvedCarrier === "extension" ? extensionDisconnected ? t('extension.notConnected') : runtime.extension?.detail ?? t("readiness.state.blocked")
854
+ : resolvedCarrier === "system" || resolvedCarrier === "cdp" ? systemLabel
855
+ : resolvedCarrier === "sidebar"
856
+ ? !isDesktop ? t("readiness.status.webSidebar")
857
+ : thirdPartyShell ? t("readiness.status.thirdPartyShell")
858
+ : runtime.shell?.kind === "tauri" ? t(runtime.shell.hostPatch?.status === "applied" ? "readiness.status.tauriReady" : "readiness.status.tauriPatchMissing")
859
+ : t(runtime.bridge.state === "installed"
860
+ ? runtime.bridge.running === true ? "readiness.status.bridgeReady"
861
+ : runtime.bridge.running === false ? "readiness.status.bridgeStopped" : "readiness.status.bridgeInstalled"
862
+ : runtime.bridge.state === "stale" ? "readiness.status.bridgeStale"
863
+ : runtime.bridge.state === "missing" ? "readiness.status.bridgeMissing" : "readiness.status.desktopMissing")
864
+ : t(runtime.electron.state === "present" || runtime.electron.state === "ready" ? "readiness.status.bundledReady"
865
+ : runtime.electron.state === "preparing" ? "readiness.status.bundledPreparing"
866
+ : runtime.electron.state === "failed" ? "readiness.status.bundledFailed" : "readiness.status.bundledMissing")
867
+ const controlsBusy = busy || bridgeBusy !== null || bridgeActive
868
+ // (Desktop detection moved above `stateLabel`: the Web surface must not report bridge states.)
869
+ const extensionAction = async () => {
870
+ setBusy(true)
871
+ try {
872
+ const result = await requestExtensionSetup()
873
+ setExtensionMessage(t(result.connected ? 'extension.connected' : result.store ? 'extension.storeHint' : 'extension.loadHint'))
874
+ } catch (failure) { setExtensionMessage(String(failure.message ?? failure)) }
875
+ finally { setBusy(false); void read() }
876
+ }
877
+ const extensionButton = h("button", { key: "install-extension", type: "button", style: styles.button, disabled: controlsBusy, onClick: extensionAction }, t('extension.button'))
878
+ // `unsupported-layout`: the desktop is recognized, but this build has no host-patch spec for its
879
+ // main entry. Offering the install would only produce a failure, so the panel explains the state
880
+ // and points at the web sidebar instead (issue #112).
881
+ const canManageBridge = isDesktop && runtime.shell?.patchable !== false && runtime.bridge.present === true
882
+ && runtime.bridge.state !== "absent" && runtime.bridge.state !== "unsupported-layout"
883
+ const unsupportedLayout = runtime.bridge.state === "unsupported-layout"
884
+ const extensionUnsupported = runtime.bridge.code === "DESKTOP_MAIN_EXTENSION_UNSUPPORTED"
885
+ const bridgeButtonBusy = bridgeBusy !== null || bridgeActive
886
+ const bridgeButtonStyle = controlsBusy || preparing ? { ...styles.button, cursor: "default", opacity: .6 } : styles.button
887
+ const bridgeJobError = typeof bridgeJob?.error === "string" ? bridgeJob.error : ""
888
+ const bridgeJobOutput = typeof bridgeJob?.output === "string" ? bridgeJob.output : ""
889
+ const bridgeJobDiagnostic = bridgeJobOutput !== "" && bridgeJobError.includes(bridgeJobOutput)
890
+ ? bridgeJobError : [bridgeJobError, bridgeJobOutput].filter(Boolean).join("\n")
891
+
892
+ return h("div", { style: styles.group }, [
893
+ h("div", { key: "head", className: "dsh-bb-row", style: styles.row }, [
894
+ h("span", { key: "title" }, t("readiness.title")),
895
+ h("span", { key: "state", role: "status", style: { ...styles.badge, ...tone } }, stateLabel),
896
+ ]),
897
+ experimental && isDesktop && isSystemCarrier && runtime.extension ? h("div", { key: "extension" }, [
898
+ resolvedCarrier !== 'extension' && extensionDisconnected ? h('p', { key: 'fallback-hint', role: 'status', style: styles.hint }, t('extension.notConnected')) : null,
899
+ h("p", { key: "profile", role: "status", style: styles.hint }, [runtime.extension.browser, runtime.extension.profile, runtime.extension.connectionId, runtime.extension.state].filter(Boolean).join(" · ")),
900
+ h("p", { key: "quiet", style: styles.hint }, t("extension.quiet")),
901
+ h('p', { key: 'hint', style: styles.hint }, t('extension.loadHint')),
902
+ ]) : null,
903
+ canManageBridge ? h("div", { key: "bridge-controls" }, [
904
+ extensionUnsupported ? h("p", { key: "extension-unsupported", role: "status", style: styles.hint }, t("readiness.bridge.extensionUnsupported"))
905
+ : runtime.bridge.mainExtension ? h("p", { key: "extension-status", role: "status", style: styles.hint },
906
+ `${t("readiness.bridge.extension." + runtime.bridge.mainExtension.state)}${runtime.bridge.mainExtension.version ? " · " + runtime.bridge.mainExtension.version : ""}${runtime.bridge.mainExtension.code ? " · " + runtime.bridge.mainExtension.code : ""}`) : null,
907
+ h("div", { key: "row", className: "dsh-bb-row", style: styles.row }, [
908
+ h("span", { key: "title" }, t("readiness.bridge")),
909
+ h("button", { key: "reinstall", type: "button", style: bridgeButtonStyle, disabled: controlsBusy || preparing, "aria-busy": bridgeButtonBusy ? "true" : undefined, onClick: () => bridgeAction("reinstall") }, t("readiness.bridge.reinstall")),
910
+ // The only way out when the desktop integration itself is the problem: revert and stop,
911
+ // instead of reinstall-and-repatch (#126). Kept next to reinstall so the row stays honest.
912
+ h("button", { key: "uninstall", type: "button", style: bridgeButtonStyle, disabled: controlsBusy || preparing, onClick: () => bridgeAction("uninstall") }, t("readiness.bridge.uninstall")),
913
+ experimental ? extensionButton : null,
914
+ ]),
915
+ h("p", { key: "hint", role: bridgeBusy !== null || bridgeActive ? "status" : undefined, style: styles.hint }, t(bridgeBusy !== null ? "readiness.bridge.working" : bridgeActive ? "readiness.bridge.progressHint" : "readiness.bridge.maintenanceHint")),
916
+ ]) : null,
917
+ thirdPartyShell ? h("div", { key: "third-party-shell", role: "status" }, [
918
+ h("p", { key: "use-browser", style: styles.hint }, t("readiness.shell.thirdParty.useBrowser").replaceAll("{browser}", shellBrowserName)),
919
+ h("p", { key: "official", style: styles.hint }, t("readiness.shell.thirdParty.official")),
920
+ ]) : null,
921
+ experimental && isDesktop && isSystemCarrier && !canManageBridge ? extensionButton : null,
922
+ // Host patch gets its own row, and only when a patch spec matches this Desktop build. A
923
+ // third-party shell or an unsupported version has no patchable target, so the row is absent
924
+ // rather than a dead "unsupported" line.
925
+ isDesktop && channelIsSidebar && !nativeViewsPresent && runtime.shell?.patchable === true ? h("div", { key: "host-patch-row", className: "dsh-bb-row", style: styles.row }, [
926
+ h("span", { key: "title" }, t("readiness.hostPatch")),
927
+ h("span", { key: "state", role: "status", style: styles.hint }, t(runtime.shell?.hostPatch?.status === "applied" ? "readiness.hostPatch.applied" : "readiness.hostPatch.absent")),
928
+ ]) : null,
929
+ experimental && extensionMessage ? h('p', { key: 'extension-message', role: 'status', style: styles.hint }, extensionMessage) : null,
930
+ h('p', { key: 'active-carrier', role: 'status', style: styles.hint }, [runtime.resolvedCarrier, runtime.controlledProfile, runtime.fallbackReason, runtime.extension?.registration?.detail].filter(Boolean).join(' · ')),
931
+ // A failed native-host registration is not the user's fault and not a raw command dump: on
932
+ // Windows it is usually EPERM (the registry write needs elevation). Say what it means and
933
+ // keep the exact command in the diagnostics block below.
934
+ ...(selectedSystemBrowser === undefined ? [] : Object.entries(runtime.nativeHostRegistration ?? {})
935
+ .filter(([browser, status]) => experimental && isDesktop && !status.registered && browser === selectedSystemBrowser)
936
+ .map(([browser, status]) => {
937
+ const detail = String(status.detail ?? "")
938
+ const needsAdmin = /EPERM|EACCES|Access is denied/iu.test(detail)
939
+ return h("p", { key: "registration-" + browser, role: "status", style: needsAdmin ? styles.hint : styles.error },
940
+ needsAdmin ? t("readiness.registration.needsAdmin").replaceAll("{browser}", browser) : browser + ': ' + detail)
941
+ })),
942
+ bridgeActive ? h("p", { key: "bridge-progress", role: "status", style: styles.hint }, t(`readiness.bridge.phase.${bridgeJob.phase}`)) : null,
943
+ bridgeJob?.phase === "completed" ? h("p", { key: "bridge-result", role: "status", style: styles.hint }, t("readiness.bridge.installedDone")) : null,
944
+ bridgeJob?.hostPatch ? h("p", { key: "host-patch", role: "status", style: styles.hint },
945
+ `${t("readiness.hostPatch")}: ${t("readiness.hostPatch." + bridgeJob.hostPatch.status.replaceAll(" ", "-"))}`) : null,
946
+ isDesktop && carrierIsSidebar && !bridgeHealthy && (bridgeJob?.phase === "failed" || bridgeJob?.phase === "cancelled") ? h("p", { key: "bridge-job-error", role: "alert", style: styles.error }, t(`readiness.bridge.${bridgeJob.phase}`)) : null,
947
+ isDesktop && carrierIsSidebar && bridgeError !== null ? h("p", { key: "bridge-error", role: "alert", style: styles.error }, t(bridgeError.key)) : null,
948
+ isDesktop && carrierIsSidebar && runtime.bridge.state === "stale" ? h("p", { key: "bridge-compatibility-error", role: "alert", style: styles.error }, runtime.bridge.detail) : null,
949
+ h("details", { key: "diagnostics", className: "dsh-bb-diagnostics" }, [
950
+ h("summary", { key: "title", style: styles.hint }, t("readiness.details")),
951
+ h("div", { key: "kv", style: styles.kv }, [
952
+ ...row("carrier", t("readiness.channel"), t(`readiness.carrier.${runtime.carrier}`)),
953
+ runtime.resolvedCarrier ? row("resolved-carrier", t("readiness.resolvedCarrier"), t(`readiness.carrier.${runtime.resolvedCarrier}`)) : null,
954
+ runtime.systemBrowser?.checked === true ? row("system", t("readiness.system"), systemLabel) : null,
955
+ ...row("electron", t("readiness.electron"), t(`readiness.electron.${runtime.electron.state}`)),
956
+ ...(carrierIsSidebar ? row("bridge", t("readiness.bridge"), bridgeLabel) : []),
957
+ ]),
958
+ runtime.systemBrowser?.path ? h("code", { key: "system-path", style: styles.mono }, runtime.systemBrowser.path) : null,
959
+ bridgeError?.detail ? h("code", { key: "bridge-error-detail", style: styles.mono }, bridgeError.detail) : null,
960
+ carrierIsSidebar && bridgeJobDiagnostic !== "" ? h("code", { key: "bridge-job-detail", style: styles.mono }, bridgeJobDiagnostic) : null,
961
+ // A host peer that does not resolve is what makes four entries stay inactive on a Desktop
962
+ // install that shipped the plugin without its peers (issue #59): name it here so a reporter
963
+ // can paste one line instead of describing the symptom.
964
+ ...(runtime.peers ?? []).filter(peer => !peer.resolved).map(peer =>
965
+ h("code", { key: "peer-" + peer.name, style: styles.mono }, `${peer.name}: ${peer.error ?? "unresolved"}`)),
966
+ // The carrier decision trail (issue #106): which browser was adopted last, and why.
967
+ ...(runtime.carrierHistory ?? []).map((reason, index) => h("code", { key: "carrier-" + index, style: styles.mono }, reason)),
968
+ // The exact command a human needs when a registration failed (elevation, wrong browser).
969
+ ...Object.entries(runtime.nativeHostRegistration ?? {}).filter(([, status]) => !status.registered)
970
+ .map(([browser, status]) => h("code", { key: "registration-detail-" + browser, style: styles.mono }, String(status.detail ?? ""))),
971
+ runtime.electron.state === "failed" || runtime.electron.state === "skipped"
972
+ ? h("p", { key: "edetail", style: styles.hint }, runtime.electron.detail) : null,
973
+ runtime.bridge.state === "installed" && runtime.bridge.running === false
974
+ ? h("p", { key: "bdetail", style: styles.hint }, runtime.bridge.runningDetail ?? runtime.bridge.detail) : null,
975
+ runtime.bridge.command
976
+ ? h("p", { key: "command", style: styles.hint }, [
977
+ h("span", { key: "label" }, t("readiness.fix")),
978
+ h("code", { key: "value", style: styles.mono }, runtime.bridge.command),
979
+ ]) : null,
980
+ h("button", {
981
+ key: "recheck",
982
+ type: "button",
983
+ style: styles.button,
984
+ disabled: controlsBusy || preparing,
985
+ onClick: () => { void read() },
986
+ }, t("readiness.recheck")),
987
+ ]),
988
+ runtime.canProvision || preparing
989
+ ? h("div", { key: "buttons", style: styles.buttons }, [
990
+ preparing ? h("span", { key: "progress", role: "status", style: styles.hint }, t("readiness.preparing")) : null,
991
+ runtime.canProvision ? h("button", { key: "prepare", type: "button", style: styles.button, disabled: controlsBusy, onClick: () => { void prepare() } }, t("readiness.prepare")) : null,
992
+ ]) : null,
993
+ error !== "" ? h("p", { key: "error", role: "alert", style: styles.error }, t("readiness.failed") + " " + error) : null,
994
+ ])
995
+ }
996
+
997
+ /** Save the delivery fields together so moving focus never writes a partial template. */
998
+ function DeliverySettings({ delivery, busy, onSave }) {
999
+ const t = translate
1000
+ const [invalid, setInvalid] = useState(false)
1001
+ const toolPattern = /^[A-Za-z0-9_.-]+$/
1002
+ const submit = event => {
1003
+ event.preventDefault()
1004
+ const fields = event.currentTarget.elements
1005
+ const tool = fields.namedItem("tool").value.trim()
1006
+ const onFail = fields.namedItem("onFail").value
1007
+ const rules = fields.namedItem("sites").value.split("\n").filter(line => line.trim() !== "")
1008
+ const entries = rules.map(line => line.split("=").map(value => value.trim()))
1009
+ let args
1010
+ try {
1011
+ args = JSON.parse(fields.namedItem("args").value)
1012
+ } catch {
1013
+ setInvalid(true)
1014
+ return
1015
+ }
1016
+ if ((tool !== "" && !toolPattern.test(tool))
1017
+ || args === null || typeof args !== "object" || Array.isArray(args)
1018
+ || Object.values(args).some(value => typeof value !== "string")
1019
+ || entries.some(entry => entry.length !== 2 || !/^[A-Za-z0-9.-]+$/.test(entry[0]) || !toolPattern.test(entry[1]))) {
1020
+ setInvalid(true)
1021
+ return
1022
+ }
1023
+ const sites = Object.fromEntries(entries.map(([host, name]) => [host.toLowerCase(), name]))
1024
+ if (Object.keys(sites).length !== entries.length) {
1025
+ setInvalid(true)
1026
+ return
1027
+ }
1028
+ setInvalid(false)
1029
+ onSave({ tool, args, onFail, sites })
1030
+ }
1031
+ const field = (name, control) => h("label", { key: name, style: styles.label }, [
1032
+ h("span", { key: "label" }, t("delivery." + name)),
1033
+ control,
1034
+ name === "args" ? h("span", { key: "hint", style: styles.hint }, t("delivery.args.hint")) : null,
1035
+ ])
1036
+ return h("form", { onSubmit: submit }, [
1037
+ h("fieldset", { key: "fields", disabled: busy, style: { border: 0, margin: 0, padding: 0, display: "grid", gap: "10px" } }, [
1038
+ field("tool", h("input", { key: "control", name: "tool", className: "dsh-bb-input", defaultValue: delivery?.tool ?? "", placeholder: "lark_drive_upload" })),
1039
+ field("args", h("textarea", { key: "control", name: "args", className: "dsh-bb-input", rows: 3, defaultValue: JSON.stringify(delivery?.args ?? { file_path: "{path}" }, null, 2) })),
1040
+ field("onFail", h("select", { key: "control", name: "onFail", className: "dsh-bb-input", defaultValue: delivery?.onFail ?? "keep-local" }, [
1041
+ h("option", { key: "keep", value: "keep-local" }, t("delivery.onFail.keep")),
1042
+ h("option", { key: "stop", value: "stop" }, t("delivery.onFail.stop")),
1043
+ ])),
1044
+ field("sites", h("textarea", { key: "control", name: "sites", className: "dsh-bb-input", rows: 3, defaultValue: Object.entries(delivery?.sites ?? {}).map(([host, tool]) => host + "=" + tool).join("\n") })),
1045
+ h("div", { key: "actions" }, h("button", { type: "submit", style: styles.button }, t("delivery.save"))),
1046
+ ]),
1047
+ invalid ? h("p", { key: "error", role: "alert", style: styles.error }, t("delivery.invalid")) : null,
1048
+ ])
1049
+ }
1050
+
1051
+ /** The settings page section. */
1052
+ /**
1053
+ * The references section: what was selected in a page earlier, and the way back.
1054
+ *
1055
+ * It lists and reveals only. A capture starts from the page — the assistant's
1056
+ * tool, or a browser menu once one exists — because a selection lives in the
1057
+ * page, not in this panel. A host without the reference routes makes the list
1058
+ * request fail, and the section then renders nothing, exactly like a settings
1059
+ * row an older host does not serve.
1060
+ */
1061
+ function References(props) {
1062
+ useLocaleVersion()
1063
+ const t = translate
1064
+ const [rows, setRows] = useState([])
1065
+ const [status, setStatus] = useState("loading")
1066
+ const [pending, setPending] = useState("")
1067
+ const [outcome, setOutcome] = useState(null)
1068
+ const [exporting, setExporting] = useState("")
1069
+ const [importing, setImporting] = useState(false)
1070
+ const [importNote, setImportNote] = useState("")
1071
+ const fileInput = useRef(null)
1072
+ const alive = useRef(true)
1073
+ const loadRevision = useRef(0)
1074
+
1075
+ useEffect(() => {
1076
+ alive.current = true
1077
+ return () => { alive.current = false; loadRevision.current += 1 }
1078
+ }, [])
1079
+
1080
+ const load = useCallback(() => {
1081
+ const revision = ++loadRevision.current
1082
+ setStatus("loading")
1083
+ fetch(`${REFERENCE_LIST_ROUTE}?limit=10`, { headers: { accept: "application/json" } })
1084
+ .then(response => response.ok ? response.json() : Promise.reject(new Error(`HTTP ${response.status}`)))
1085
+ .then(data => {
1086
+ if (!alive.current || loadRevision.current !== revision) return
1087
+ setRows(Array.isArray(data.references) ? data.references : [])
1088
+ setStatus("ready")
1089
+ })
1090
+ .catch(() => { if (alive.current && loadRevision.current === revision) setStatus("failed") })
1091
+ }, [])
1092
+ useEffect(() => { load() }, [load])
1093
+
1094
+ const label = state => {
1095
+ if (state === "revealed") return t("refs.revealed")
1096
+ if (state === "ambiguous") return t("refs.ambiguous")
1097
+ if (state === "missing") return t("refs.missing")
1098
+ if (state === "page-mismatch") return t("refs.pageMismatch")
1099
+ if (state === "session-unavailable") return t("refs.sessionUnavailable")
1100
+ if (state === "not-found") return t("refs.notFound")
1101
+ if (state === "added") return t("refs.added")
1102
+ if (state === "addFailed") return t("refs.addFailed")
1103
+ if (state === "removed") return t("refs.removed")
1104
+ if (state === "removeFailed") return t("refs.removeFailed")
1105
+ return t("refs.failed")
1106
+ }
1107
+ const reveal = referenceId => {
1108
+ setPending(referenceId)
1109
+ setOutcome(null)
1110
+ fetch(REFERENCE_REVEAL_ROUTE, {
1111
+ method: "POST",
1112
+ headers: { "content-type": "application/json" },
1113
+ body: JSON.stringify({ referenceId }),
1114
+ }).then(async response => {
1115
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
1116
+ return response.json()
1117
+ })
1118
+ .then(data => { if (alive.current) setOutcome({ referenceId, status: data.status || "unavailable" }) })
1119
+ .catch(() => { if (alive.current) setOutcome({ referenceId, status: "failed" }) })
1120
+ .finally(() => { if (alive.current) setPending("") })
1121
+ }
1122
+ const exportAs = format => {
1123
+ setExporting(format)
1124
+ setOutcome(null)
1125
+ fetch(`${REFERENCE_EXPORT_ROUTE}?format=${encodeURIComponent(format)}`, { headers: { accept: "*/*" } })
1126
+ .then(async response => {
1127
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
1128
+ const blob = await response.blob()
1129
+ if (!alive.current) return
1130
+ const disposition = response.headers.get("content-disposition") || ""
1131
+ const named = /filename="([^"]+)"/.exec(disposition)
1132
+ const fallback = { jsonl: "browser-references.jsonl", markdown: "browser-references.md", zip: "browser-references.zip" }[format] || "browser-references.zip"
1133
+ const url = URL.createObjectURL(blob)
1134
+ const link = document.createElement("a")
1135
+ link.href = url
1136
+ link.download = named ? named[1] : fallback
1137
+ link.click()
1138
+ setTimeout(() => URL.revokeObjectURL(url), 0)
1139
+ })
1140
+ .catch(() => { if (alive.current) setOutcome({ referenceId: "", status: "failed" }) })
1141
+ .finally(() => { if (alive.current) setExporting("") })
1142
+ }
1143
+ /**
1144
+ * Restore a `format=zip` export. The route re-verifies every hash and reports per-record
1145
+ * rejections; a partial import is shown as such rather than as a clean success.
1146
+ * @param file - the user-picked archive.
1147
+ */
1148
+ const importFrom = file => {
1149
+ if (!file) return
1150
+ setImporting(true)
1151
+ setImportNote("")
1152
+ setOutcome(null)
1153
+ fetch(REFERENCE_IMPORT_ROUTE, {
1154
+ method: "POST",
1155
+ headers: { "content-type": "application/zip" },
1156
+ body: file,
1157
+ })
1158
+ .then(async response => {
1159
+ const data = await response.json().catch(() => ({}))
1160
+ if (!response.ok || data.ok !== true) throw new Error(String(data.error || `HTTP ${response.status}`))
1161
+ return data
1162
+ })
1163
+ .then(data => {
1164
+ if (!alive.current) return
1165
+ const rejected = Array.isArray(data.rejected) ? data.rejected.length : 0
1166
+ setImportNote(`${t("refs.importDone")} ${String(data.added)}/${String(data.references)}`
1167
+ + (rejected > 0 ? ` · ${String(rejected)} ${t("refs.importPartial")}` : ""))
1168
+ load()
1169
+ })
1170
+ .catch(() => { if (alive.current) setImportNote(t("refs.importFailed")) })
1171
+ .finally(() => {
1172
+ if (!alive.current) return
1173
+ setImporting(false)
1174
+ if (fileInput.current) fileInput.current.value = ""
1175
+ })
1176
+ }
1177
+
1178
+ /**
1179
+ * "Add to conversation" feeds the durable delivery queue; the DSH client
1180
+ * drains that queue into the real draft. The record itself is untouched, so
1181
+ * a failed add can be retried without re-capturing the page.
1182
+ */
1183
+ const postDelivery = (path, body, okStatus, failStatus, referenceId) => {
1184
+ setPending(referenceId)
1185
+ setOutcome(null)
1186
+ fetch(path, {
1187
+ method: "POST",
1188
+ headers: { "content-type": "application/json" },
1189
+ body: JSON.stringify(body),
1190
+ })
1191
+ .then(async response => ({ ok: response.ok, data: await response.json().catch(() => ({})) }))
1192
+ .then(({ ok, data }) => {
1193
+ if (alive.current) setOutcome({ referenceId, status: ok && data.ok !== false ? okStatus : failStatus })
1194
+ })
1195
+ .catch(() => { if (alive.current) setOutcome({ referenceId, status: failStatus }) })
1196
+ .finally(() => { if (alive.current) setPending("") })
1197
+ }
1198
+ const addToDraft = referenceId => postDelivery(
1199
+ REFERENCE_INSERT_ROUTE, { referenceId }, "added", "addFailed", referenceId,
1200
+ )
1201
+ const removeFromDraft = referenceId => postDelivery(
1202
+ REFERENCE_DELIVERY_REMOVE_ROUTE, { referenceId }, "removed", "removeFailed", referenceId,
1203
+ )
1204
+ const withActions = props && props.withActions === true
1205
+
1206
+ const transferring = exporting !== "" || importing
1207
+ const sourceLabel = url => {
1208
+ try { return new URL(url).host } catch { return "" }
1209
+ }
1210
+ const preview = item => (Array.isArray(item.parts) ? item.parts : []).map(part =>
1211
+ part.type === "image" ? `${t("refs.image")}${part.preview ? ` · ${part.preview}` : ""}`
1212
+ : part.type === "table" ? `${t("refs.table")}${part.preview ? ` · ${part.preview}` : ""}`
1213
+ : String(part.preview || "")).filter(Boolean).join(" · ")
1214
+
1215
+ return h("details", { style: styles.group, className: "dsh-bb-references" }, [
1216
+ h("summary", { key: "head", style: { ...styles.groupTitle, fontWeight: 500 } }, [
1217
+ t("refs.title"),
1218
+ rows.length > 0 ? h("span", { key: "count", className: "dsh-bb-ref-count" }, `${rows.length} ${t("refs.records")}`) : null,
1219
+ ]),
1220
+ h("div", { key: "toolbar", className: "dsh-bb-ref-toolbar" }, [
1221
+ h("button", { key: "refresh", type: "button", style: styles.button, disabled: status === "loading", onClick: load }, t("refs.refresh")),
1222
+ ]),
1223
+ status === "failed" ? h("p", { key: "error", role: "alert", style: styles.error }, t("refs.loadFailed")) : null,
1224
+ status === "loading" && rows.length === 0 ? h("p", { key: "loading", role: "status", style: styles.hint }, t("refs.reading")) : null,
1225
+ status === "ready" && rows.length === 0 ? h("p", { key: "empty", style: styles.hint }, t("refs.empty")) : null,
1226
+ h("ul", { key: "list", className: "dsh-bb-ref-list", "aria-busy": status === "loading" }, rows.map(item => h("li", {
1227
+ key: item.referenceId, className: "dsh-bb-ref-item",
1228
+ }, [
1229
+ h("div", { key: "text", className: "dsh-bb-ref-content" }, [
1230
+ h("span", { key: "title", className: "dsh-bb-ref-title", title: item.title || item.pageUrl }, item.title || sourceLabel(item.pageUrl) || t("refs.untitled")),
1231
+ preview(item) ? h("p", { key: "preview", className: "dsh-bb-ref-preview" }, preview(item)) : null,
1232
+ h("div", { key: "meta", className: "dsh-bb-ref-meta" }, [
1233
+ h("span", { key: "source", className: "dsh-bb-ref-source", title: item.pageUrl }, sourceLabel(item.pageUrl)),
1234
+ h("time", { key: "date", dateTime: item.capturedAt }, new Date(item.capturedAt).toLocaleDateString(currentLocale === "en" ? "en" : "zh-CN")),
1235
+ h("span", { key: "parts" }, `${item.partCount} ${t("refs.parts")}`),
1236
+ ]),
1237
+ outcome !== null && outcome.referenceId === item.referenceId
1238
+ ? h("p", { key: "outcome", role: "status", className: "dsh-bb-ref-outcome", style: outcome.status === "revealed" || outcome.status === "added" || outcome.status === "removed" ? styles.hint : styles.error }, label(outcome.status))
1239
+ : null,
1240
+ ]),
1241
+ h("div", { key: "actions", className: "dsh-bb-ref-actions" }, [
1242
+ withActions ? h("button", {
1243
+ key: "add", type: "button", style: styles.button,
1244
+ disabled: pending !== "", onClick: () => addToDraft(item.referenceId),
1245
+ }, t("refs.addToDraft")) : null,
1246
+ withActions ? h("button", {
1247
+ key: "remove", type: "button", style: styles.button,
1248
+ disabled: pending !== "", onClick: () => removeFromDraft(item.referenceId),
1249
+ }, t("refs.remove")) : null,
1250
+ h("button", {
1251
+ key: "reveal", type: "button", style: styles.button,
1252
+ disabled: pending !== "", onClick: () => reveal(item.referenceId),
1253
+ "aria-label": `${t("refs.reveal")} · ${item.title || sourceLabel(item.pageUrl)}`,
1254
+ }, pending === item.referenceId ? t("refs.loading") : t("refs.reveal")),
1255
+ ]),
1256
+ ]))),
1257
+ h("details", { key: "transfer", className: "dsh-bb-ref-transfer" }, [
1258
+ h("summary", { key: "label", style: styles.hint }, t("refs.transfer")),
1259
+ h("div", { key: "exports", className: "dsh-bb-ref-transfer-actions" }, [
1260
+ ...["jsonl", "markdown", "zip"].map(format => h("button", {
1261
+ key: format,
1262
+ type: "button",
1263
+ style: styles.button,
1264
+ disabled: transferring,
1265
+ onClick: () => exportAs(format),
1266
+ }, `${t("refs.export")} ${t(format === "jsonl" ? "refs.exportJsonl" : format === "markdown" ? "refs.exportMarkdown" : "refs.exportZip")}`)),
1267
+ ]),
1268
+ h("div", { key: "imports", className: "dsh-bb-ref-transfer-actions" }, [
1269
+ h("input", {
1270
+ key: "file",
1271
+ type: "file",
1272
+ accept: ".zip,application/zip",
1273
+ ref: fileInput,
1274
+ style: { display: "none" },
1275
+ onChange: event => importFrom(event.target.files && event.target.files[0]),
1276
+ }),
1277
+ h("button", {
1278
+ key: "importButton",
1279
+ type: "button",
1280
+ style: styles.button,
1281
+ disabled: transferring,
1282
+ onClick: () => { if (fileInput.current) fileInput.current.click() },
1283
+ }, importing ? t("refs.importBusy") : t("refs.import")),
1284
+ ]),
1285
+ ]),
1286
+ importNote !== "" ? h("p", { key: "importNote", role: "status", style: styles.hint }, importNote) : null,
1287
+ outcome !== null && outcome.referenceId === "" ? h("p", { key: "transfer-error", role: "alert", style: styles.error }, t("refs.failed")) : null,
1288
+ ])
1289
+ }
1290
+
1291
+ /**
1292
+ * The record list is kept for the test seam only. The user-facing entry was
1293
+ * removed: the conversation input now renders one card per reference, so a
1294
+ * separate aggregate history menu duplicated the same content.
1295
+ */
1296
+ function SettingsRoot() {
1297
+ useLocaleVersion()
1298
+ const t = translate
1299
+ const [rawSettings, setSettings] = useState(null)
1300
+ const [meta, setMeta] = useState({ path: "" })
1301
+ const [error, setError] = useState("")
1302
+ const [busy, setBusy] = useState(false)
1303
+ const [saved, setSaved] = useState(false)
1304
+ // The main panel is the carrier switch plus CDP readiness — CDP is the baseline that needs no
1305
+ // installation. The extension (drive the user's own browser) is an optional control that lives
1306
+ // in 高级设置 and only renders while that section is open.
1307
+ const [advancedOpen, setAdvancedOpen] = useState(false)
1308
+ const saving = useRef(false)
1309
+ const savedTimer = useRef(null)
1310
+ const alive = useRef(true)
1311
+
1312
+ const load = useCallback(() => {
1313
+ setError("")
1314
+ callSettings().then(data => {
1315
+ if (!alive.current) return
1316
+ setSettings(data.settings)
1317
+ setMeta({ path: data.path || "" })
1318
+ }).catch(failure => { if (alive.current) setError(String(failure && failure.message ? failure.message : failure)) })
1319
+ }, [])
1320
+
1321
+ useEffect(() => {
1322
+ alive.current = true
1323
+ load()
1324
+ return () => { alive.current = false }
1325
+ }, [load])
1326
+ useEffect(() => () => clearTimeout(savedTimer.current), [])
1327
+
1328
+ const patch = useCallback(next => {
1329
+ if (saving.current) return
1330
+ saving.current = true
1331
+ clearTimeout(savedTimer.current)
1332
+ setSaved(false)
1333
+ setBusy(true)
1334
+ setError("")
1335
+ callSettings(next).then(data => {
1336
+ if (!alive.current) return
1337
+ setSettings(data.settings)
1338
+ setSaved(true)
1339
+ savedTimer.current = setTimeout(() => setSaved(false), 1800)
1340
+ }).catch(failure => { if (alive.current) setError(String(failure && failure.message ? failure.message : failure)) })
1341
+ .finally(() => {
1342
+ saving.current = false
1343
+ if (alive.current) setBusy(false)
1344
+ })
1345
+ }, [])
1346
+
1347
+ if (rawSettings === null) {
1348
+ return h("div", { style: styles.wrap }, [
1349
+ error === "" ? h("p", { key: "l", role: "status", style: styles.lead }, t("loading")) : null,
1350
+ error !== "" ? h("p", { key: "e", style: styles.error }, `${t("failed")} ${error}`) : null,
1351
+ error !== "" ? h("button", { key: "retry", type: "button", style: styles.button, onClick: load }, t("retry")) : null,
1352
+ ])
1353
+ }
1354
+
1355
+ // A document served by an OLDER host has no `actions` section — which is exactly the state
1356
+ // an update leaves behind when the host has not been restarted yet (the client bundle is
1357
+ // read at request time, the host's code at startup). Rendering `settings.actions.allowExecute`
1358
+ // off that threw, and the throw took the whole panel with it: the section did not merely show
1359
+ // stale values, it refused to open. Fill the gap with the defaults an older host behaves by,
1360
+ // which is also the honest reading — it has no such switch, so "on" is what it does.
1361
+ const settings = rawSettings.actions === undefined
1362
+ ? { ...rawSettings, actions: { allowExecute: true, allowDownload: true, allowCredentialWrite: true } }
1363
+ : rawSettings
1364
+
1365
+ const toggle = (group, key, labelKey = group + "." + key, hintKey) => h(Toggle, {
1366
+ key,
1367
+ labelKey,
1368
+ hintKey,
1369
+ checked: settings[group]?.[key] ?? (group === "cookies" && key === "persist"),
1370
+ busy,
1371
+ onChange: value => patch({ [group]: { [key]: value } }),
1372
+ })
1373
+ const selector = (labelKey, value, options, onChange, hintKey) => h("div", {
1374
+ key: labelKey,
1375
+ className: "dsh-bb-row",
1376
+ style: styles.row,
1377
+ }, [
1378
+ h("span", { key: "text", style: styles.label }, [
1379
+ h("span", { key: "label" }, t(labelKey)),
1380
+ hintKey ? h("span", { key: "hint", style: styles.hint }, t(hintKey)) : null,
1381
+ ]),
1382
+ h(Dropdown, { key: "select", label: t(labelKey), value, options, disabled: busy, onChange }),
1383
+ ])
1384
+ const options = (prefix, values) => values.map(value => ({ value, label: t(prefix + value) }))
1385
+ const section = (titleKey, children) => h("section", { key: titleKey, style: styles.group }, [
1386
+ h("h3", { key: "title", style: styles.groupTitle }, t(titleKey)),
1387
+ ...children,
1388
+ ])
1389
+ const systemBrowser = ["chrome", "edge"].includes(settings.browser.channel)
1390
+ const pluginOwnedProfile = settings.browser.channel === "electron"
1391
+ || (systemBrowser && settings.browser.systemProfile !== "user")
1392
+
1393
+ return h("div", { style: styles.wrap, className: "dsh-bb-settings" }, [
1394
+ selector("browser.channel", settings.browser.channel === "bundled" || settings.browser.channel === "auto" ? "sidebar" : settings.browser.channel,
1395
+ options("browser.", ["sidebar", "electron", "chrome", "edge"]),
1396
+ channel => patch({ browser: { channel } })),
1397
+ h(Readiness, { key: "readiness-" + settings.browser.channel + "-" + settings.browser.systemProfile, channel: settings.browser.channel, experimental: advancedOpen }),
1398
+ section("ui.title", [
1399
+ toggle("ui", "quiet", "ui.quiet", "ui.quiet.hint"),
1400
+ toggle("ui", "autoExpandOnce"),
1401
+ toggle("ui", "closeWithSession"),
1402
+ toggle("ui", "virtualCursor"),
1403
+ toggle("remoteView", "enabled", "remoteView.enabled", "remoteView.enabled.hint"),
1404
+ ]),
1405
+ section("actions.title", [
1406
+ toggle("actions", "allowExecute"),
1407
+ toggle("actions", "allowDownload"),
1408
+ toggle("credentials", "allowRead"),
1409
+ toggle("actions", "allowCredentialWrite", "actions.allowCredentialWrite", "actions.allowCredentialWrite.hint"),
1410
+ ]),
1411
+ h("details", { key: "advanced", style: styles.group, onToggle: event => setAdvancedOpen(event.currentTarget.open) }, [
1412
+ h("summary", { key: "title", style: styles.groupTitle }, t("settings.advanced")),
1413
+ // The host patch is a maintenance surface, not a daily control: it lives here with the other
1414
+ // optional plumbing, and it renders nothing when there is nothing actionable.
1415
+ h(HostPatchControls, { key: "host-patch" }),
1416
+ advancedOpen && systemBrowser ? selector("browser.systemProfile", settings.browser.systemProfile ?? "plugin",
1417
+ options("browser.mode.", ["plugin", "user"]), systemProfile => patch({ browser: { systemProfile } })) : null,
1418
+ toggle("history", "enabled"),
1419
+ selector("vision.strategy", settings.vision.strategy, [
1420
+ { value: "auto", label: t("vision.auto") },
1421
+ { value: "nonVisual", label: t("vision.nonVisual") },
1422
+ ], strategy => patch({ vision: { strategy } })),
1423
+ pluginOwnedProfile ? toggle("cookies", "persist", "browser.profile", "browser.profile.hint") : null,
1424
+ systemBrowser && settings.browser.systemProfile !== "user" ? selector("browser.headless", settings.browser.headless ?? "auto",
1425
+ options("browser.headless.", ["auto", "windowed", "headless"]),
1426
+ headless => patch({ browser: { headless } }), "browser.headless.hint") : null,
1427
+ settings.delivery ? section("delivery.title", [
1428
+ h(DeliverySettings, {
1429
+ key: JSON.stringify(settings.delivery),
1430
+ delivery: settings.delivery,
1431
+ busy,
1432
+ onSave: delivery => patch({ delivery }),
1433
+ }),
1434
+ ]) : null,
1435
+ meta.path !== "" ? h("p", { key: "path", style: styles.pathLine }, t("settings.details") + " · " + meta.path) : null,
1436
+ ]),
1437
+ h("div", { key: "status", style: styles.status, role: "status" }, [
1438
+ busy || saved ? h("span", { key: "s" }, t(busy ? "settings.saving" : "saved")) : null,
1439
+ error !== "" ? h("span", { key: "e", style: styles.error }, ` ${t("failed")} ${error} `) : null,
1440
+ error !== "" ? h("button", { key: "r", type: "button", style: styles.button, onClick: load }, t("retry")) : null,
1441
+ ]),
1442
+ ])
1443
+ }
1444
+
1445
+ // ===========================================================================
1446
+ // Conversation panel service: the one place a sidebar panel is opened.
1447
+ //
1448
+ // The shell mounts one right sidebar per conversation, and DSH's own sidebar
1449
+ // browser keeps that conversation's tabs and its webview guest inside it.
1450
+ // `ctx.sidebarRight.openTab` acts on the conversation the shell is SHOWING
1451
+ // (`mounted`), so every path that simulated a shortcut or clicked a card put
1452
+ // the page into whichever conversation the human happened to be reading —
1453
+ // that is the cross-conversation bleed, and it is a property of the path, not
1454
+ // an accident of it.
1455
+ //
1456
+ // `openTabIn(sessionId, …)` is the same navigation aimed at a NAMED
1457
+ // conversation, and it works for one that is not on screen. This service is
1458
+ // the only caller; the plugin's host half reaches it by evaluating
1459
+ // `globalThis.__dshBuiltinBrowser.openPanel(...)` inside the shell window, so
1460
+ // no input event, no key dispatch and no element click is involved.
1461
+ //
1462
+ // Guest identity is read from the panel's own `<webview>` and only inside the
1463
+ // subtree found for THAT conversation — never from the first match in the
1464
+ // document, which belongs to somebody else's panel.
1465
+ // ===========================================================================
1466
+
1467
+ /** The conversation a sidebar element belongs to, read off its React fiber. */
1468
+ function sessionIdOfElement(element) {
1469
+ const key = Object.keys(element).find(
1470
+ name => name.startsWith("__reactFiber$") || name.startsWith("__reactInternalInstance$"),
1471
+ )
1472
+ if (key === undefined) return null
1473
+ let fiber = element[key]
1474
+ let depth = 0
1475
+ while (fiber !== null && fiber !== undefined && depth < 60) {
1476
+ const props = fiber.memoizedProps
1477
+ if (props !== null && typeof props === "object" && typeof props.sessionId === "string") return props.sessionId
1478
+ fiber = fiber.return
1479
+ depth += 1
1480
+ }
1481
+ return null
1482
+ }
1483
+
1484
+ /**
1485
+ * DSH 0.2.2-rc.3 has no `data-sidebar-right-session` markers, so its tab strip is found by its
1486
+ * CSS Modules class. This is the only class-name lookup: every shell with the markers takes
1487
+ * `panelRootsFor` instead.
1488
+ */
1489
+ const LEGACY_TAB_STRIP_SELECTOR = "[class*=_tabStrip]"
1490
+
1491
+ /**
1492
+ * This conversation's own sidebar strip, or null when the shell has not mounted it.
1493
+ *
1494
+ * Its presence is the precondition `openTabIn` needs: it is minted together with the
1495
+ * conversation's surface store, and a call for a conversation whose store was never
1496
+ * minted silently does nothing. Detecting it here turns that silence into a reason
1497
+ * the caller can report, instead of a page that never appears.
1498
+ */
1499
+ function tabStripFor(sessionId) {
1500
+ for (const strip of Array.from(document.querySelectorAll(LEGACY_TAB_STRIP_SELECTOR))) {
1501
+ if (sessionIdOfElement(strip) === sessionId) return strip
1502
+ }
1503
+ return null
1504
+ }
1505
+
1506
+ /** rc.5 marks both SessionView and its nested SidebarPanel, including floating panes. */
1507
+ function panelRootsFor(sessionId) {
1508
+ const roots = Array.from(document.querySelectorAll("[data-sidebar-right-session]"))
1509
+ // Only shells without DOM ownership markers may use the legacy React adapter.
1510
+ return roots.length === 0 ? undefined : roots.filter(root => root.getAttribute("data-sidebar-right-session") === sessionId)
1511
+ }
1512
+
1513
+ /**
1514
+ * Every live `<webview>` guest inside this conversation's panel subtree.
1515
+ *
1516
+ * The walk up stops the moment an ancestor carries ANOTHER conversation's sidebar, and that stop
1517
+ * condition is the whole point of this function. The shell mounts every conversation's panel in
1518
+ * the same document — hidden ones included — so one step too far lands on a subtree that holds
1519
+ * all of them, and the first guest found there belongs to whichever conversation the shell
1520
+ * happens to render first. Measured: a GitHub login page opened in a different conversation was
1521
+ * reported as this one's guest, which is the cross-conversation bleed this service exists to
1522
+ * prevent. A sibling strip is the exact, class-name-independent signature of having stepped
1523
+ * outside; a conversation may legitimately own more than one strip of its own, so the test is
1524
+ * "is there one that is NOT mine", never a count.
1525
+ */
1526
+ function guestsInPanel(sessionId) {
1527
+ const roots = panelRootsFor(sessionId)
1528
+ if (roots !== undefined) {
1529
+ // The nested markers can enumerate a guest twice. Its closest owner must still
1530
+ // name this session, so an embedded foreign session never enters the result.
1531
+ return Array.from(new Set(roots.flatMap(root => Array.from(root.querySelectorAll("webview"))))).filter(view => {
1532
+ try {
1533
+ return roots.includes(view.closest("[data-sidebar-right-session]"))
1534
+ && typeof view.getWebContentsId === "function" && view.getWebContentsId() > 0
1535
+ } catch { return false }
1536
+ })
1537
+ }
1538
+ const strip = tabStripFor(sessionId)
1539
+ if (strip === null) return []
1540
+ // Start at the strip itself: it is by construction this conversation's own, so the foreign test
1541
+ // below cannot trip on it, and a shell that renders the guest as a sibling of the strip is
1542
+ // still reached.
1543
+ let node = strip
1544
+ while (node !== null && node !== undefined && node !== document.body) {
1545
+ const foreign = Array.from(node.querySelectorAll(LEGACY_TAB_STRIP_SELECTOR))
1546
+ .some(el => sessionIdOfElement(el) !== sessionId)
1547
+ if (foreign) break
1548
+ const found = Array.from(node.querySelectorAll("webview")).filter(view => {
1549
+ try { return typeof view.getWebContentsId === "function" && view.getWebContentsId() > 0 }
1550
+ catch (error) { return false }
1551
+ })
1552
+ if (found.length > 0) return found
1553
+ node = node.parentElement
1554
+ }
1555
+ return []
1556
+ }
1557
+
1558
+ /** Read this conversation's current guest, preferring the one actually drawn. */
1559
+ function guestStateFor(sessionId, tabId, initializationReader) {
1560
+ const roots = panelRootsFor(sessionId)
1561
+ if (roots === undefined ? tabStripFor(sessionId) === null : roots.length === 0) return { panel: false, guestId: null, url: "" }
1562
+ if (nativeViews() !== undefined && typeof tabId === "string") {
1563
+ const page = initializationReader?.current({ sessionId, tabId })
1564
+ return { panel: true, guestId: page?.guestId ?? null, url: page?.url ?? "", ...page?.generation === undefined ? {} : { nativeState: page } }
1565
+ }
1566
+ const guests = guestsInPanel(sessionId).filter(view => tabId === undefined
1567
+ || tabIdOfElement(view, new Set([tabId]), roots) === tabId)
1568
+ if (guests.length === 0) return { panel: true, guestId: null, url: "" }
1569
+ // A sidebar keeps every tab mounted (`keepMounted`), so a background tab's guest is
1570
+ // in the tree too. Prefer the one with a drawn box; fall back to the newest.
1571
+ const drawn = guests.find(view => {
1572
+ const rect = view.getBoundingClientRect()
1573
+ return rect.width > 0 && rect.height > 0
1574
+ })
1575
+ const chosen = drawn === undefined ? guests[guests.length - 1] : drawn
1576
+ let url = ""
1577
+ try { url = String(chosen.getURL ? chosen.getURL() : "") } catch (error) { url = "" }
1578
+ try { return { panel: true, guestId: chosen.getWebContentsId(), url } }
1579
+ catch (error) { return { panel: true, guestId: null, url: "" } }
1580
+ }
1581
+
1582
+ /** Resolve a shell tab by its stable id, never by the page's displayed title. */
1583
+ function tabIdOfElement(element, allowed, roots) {
1584
+ if (roots !== undefined) {
1585
+ const owner = element.closest("[data-sidebar-right-session]")
1586
+ if (!roots.includes(owner)) return null
1587
+ let id = null
1588
+ for (let node = element; node && node !== owner; node = node.parentElement) {
1589
+ for (const value of [node.getAttribute("data-sidebar-right-tab"), node.getAttribute("data-dockkit-tab")]) {
1590
+ if (value === null) continue
1591
+ if (id !== null && id !== value) return null
1592
+ id = value
1593
+ }
1594
+ }
1595
+ return allowed.has(id) ? id : null
1596
+ }
1597
+ const key = Object.keys(element).find(name => name.startsWith("__reactFiber$") || name.startsWith("__reactInternalInstance$"))
1598
+ let fiber = key === undefined ? null : element[key]
1599
+ for (let depth = 0; fiber && depth < 60; depth += 1, fiber = fiber.return) {
1600
+ const props = fiber.memoizedProps
1601
+ if (!props || typeof props !== "object") continue
1602
+ for (const id of [props.tabId, props.tab && props.tab.id]) {
1603
+ if (typeof id === "string" && allowed.has(id)) return id
1604
+ }
1605
+ }
1606
+ return null
1607
+ }
1608
+
1609
+ /**
1610
+ * Publish the service every host-side panel request goes through.
1611
+ *
1612
+ * The binding is separate from the publication so the API exists from the first
1613
+ * apply — a request arriving before `sidebarRight` is ready gets a named reason
1614
+ * rather than a missing global, which is indistinguishable from a bridge that
1615
+ * never loaded.
1616
+ */
1617
+ function installPanelService(ctx) {
1618
+ let sidebarRight = null
1619
+ let initializationReader = null
1620
+ const pendingTabs = new Map()
1621
+ const renderingHolds = new Map()
1622
+ function releaseRendering(token) {
1623
+ const hold = renderingHolds.get(token)
1624
+ if (hold === undefined) return
1625
+ renderingHolds.delete(token)
1626
+ clearTimeout(hold.timer)
1627
+ hold.release()
1628
+ }
1629
+ function releaseAllRendering() {
1630
+ for (const token of renderingHolds.keys()) releaseRendering(token)
1631
+ }
1632
+ function hasRenderingHold(sessionId) {
1633
+ return Array.from(renderingHolds.values()).some(hold => hold.sessionId === sessionId)
1634
+ }
1635
+ const initializing = new Map()
1636
+ /** The shell's own navigation service: `openSession` is how it is asked to DISPLAY a conversation. */
1637
+ let uiWorkspace = null
1638
+ // `inject` is how a client plugin waits for a service to appear. A host that does not offer it
1639
+ // — an older composition, or a harness that mounted this bundle for its settings panel alone —
1640
+ // must still get the panel, so the wait is skipped and the published API names the missing
1641
+ // service when it is called. Failing the whole apply here would take the settings panel down
1642
+ // with it, which is exactly the shape of regression this file has been bitten by before.
1643
+ if (typeof ctx.inject === "function") {
1644
+ ctx.inject(["sidebarBrowserInitialization"], (scope) => {
1645
+ const reader = scope.sidebarBrowserInitialization
1646
+ if (reader?.protocolVersion !== 1 || typeof reader.read !== "function") return
1647
+ initializationReader = reader
1648
+ scope.effect(() => () => {
1649
+ if (initializationReader === reader) initializationReader = null
1650
+ }, "dsh-builtin-browser: initialization receipt reader")
1651
+ })
1652
+ ctx.inject(["sidebarRight"], (scope) => {
1653
+ if (sidebarRight !== scope.sidebarRight) {
1654
+ releaseAllRendering()
1655
+ pendingTabs.clear()
1656
+ }
1657
+ sidebarRight = scope.sidebarRight
1658
+ scope.effect(() => () => {
1659
+ if (sidebarRight === scope.sidebarRight) {
1660
+ releaseAllRendering()
1661
+ sidebarRight = null
1662
+ pendingTabs.clear()
1663
+ for (const transaction of initializing.values()) transaction.controller.abort(new Error("the sidebar service was released"))
1664
+ initializing.clear()
1665
+ }
1666
+ }, "dsh-builtin-browser: conversation panel binding")
1667
+ })
1668
+ // A separate inject, deliberately: waiting for both services in one call would take the
1669
+ // panel down on a host that has the sidebar but not the workspace service (an older
1670
+ // composition), and the panel is the part that must keep working.
1671
+ ctx.inject(["uiWorkspace"], (scope) => {
1672
+ uiWorkspace = scope.uiWorkspace
1673
+ scope.effect(() => () => {
1674
+ if (uiWorkspace === scope.uiWorkspace) uiWorkspace = null
1675
+ }, "dsh-builtin-browser: workspace binding")
1676
+ })
1677
+ }
1678
+ /**
1679
+ * Place a tool-opened page into the Web sidebar.
1680
+ *
1681
+ * The desktop shell is told to place a tab through the bridge; the Web shell has no such channel, so
1682
+ * a page opened by a tool stayed inside the plugin's own browser while the panel showed nothing.
1683
+ * The host keeps the last open request in one slot; this poll turns it into a sidebar tab, which is
1684
+ * what makes "open it" a single call again.
1685
+ */
1686
+ /**
1687
+ * Which surface this shell should drive.
1688
+ *
1689
+ * Default "panel": the sidebar is the browsing surface. Appending ?browser-surface=builtin to the DSH
1690
+ * URL switches this window to the built-in browser for debugging DSH itself — no restart, no settings
1691
+ * file, and it cannot affect another window.
1692
+ * @returns the surface to declare.
1693
+ */
1694
+ function declaredSurface() {
1695
+ try {
1696
+ const wanted = new URLSearchParams(location.search).get("browser-surface")
1697
+ return wanted === "builtin" ? "builtin" : "panel"
1698
+ } catch { return "panel" }
1699
+ }
1700
+ /**
1701
+ * 已经摆放过的 open 记录时间戳。
1702
+ *
1703
+ * 这份状态以前只在内存里,**刷新页面即归零**:宿主那边仍留着上一次 open 记录,于是页面一刷新就把
1704
+ * 用户已经关掉的侧栏与网页重新打开。写进 sessionStorage 后,同一次浏览会话内的刷新不会再重放;
1705
+ * 换新标签页也不会因为宿主里那条旧记录而凭空冒出侧栏。
1706
+ * @returns 已处理过的最晚 open 时间(毫秒)。
1707
+ */
1708
+ let lastOpenHandled = (() => {
1709
+ try {
1710
+ const raw = sessionStorage.getItem("dsh-builtin-browser:last-open-handled")
1711
+ const value = raw === null ? 0 : Number(raw)
1712
+ return Number.isFinite(value) ? value : 0
1713
+ } catch { return 0 }
1714
+ })()
1715
+
1716
+ /**
1717
+ * 记住已处理的 open,供刷新后继续沿用。
1718
+ * @param at - 该条 open 记录的时间戳(毫秒)。
1719
+ */
1720
+ function rememberOpenHandled(at) {
1721
+ lastOpenHandled = at
1722
+ try { sessionStorage.setItem("dsh-builtin-browser:last-open-handled", String(at)) } catch { /* 隐私模式忽略 */ }
1723
+ }
1724
+
1725
+ function drainOpenRequest() {
1726
+ const sessionId = guestSession()
1727
+ if (typeof sessionId !== "string" || sessionId === "") return
1728
+ fetch(OPEN_REQUEST_ROUTE, { headers: { accept: "application/json" } })
1729
+ .then(response => (response.ok ? response.json() : undefined))
1730
+ .then(body => {
1731
+ const open = body && body.open
1732
+ if (!open || typeof open.url !== "string" || typeof open.at !== "number") return
1733
+ if (typeof open.owner === "string" && open.owner.replace(/^session-/, "") !== sessionId) return
1734
+ // Only act when the HOST says it is in panel mode. A host that predates the single-surface
1735
+ // switch still opens its own browser for every call, so placing a tab here as well produced TWO
1736
+ // live views of one page (the reported double-open). No echo, no tab.
1737
+ if (body.surface !== "panel") return
1738
+ if (open.at <= lastOpenHandled) return
1739
+ const frame = document.querySelector('iframe[data-sidebar-browser-frame]')
1740
+ const already = frame !== null && decodeURIComponent(frame.getAttribute("src") || "").includes(encodeURIComponent(open.url).slice(0, 24))
1741
+ if (already) { rememberOpenHandled(open.at); return }
1742
+ rememberOpenHandled(open.at)
1743
+ const api = globalThis.__dshBuiltinBrowser
1744
+ if (api && typeof api.openPanel === "function") api.openPanel("session-" + sessionId, open.url)
1745
+ })
1746
+ .catch(() => {})
1747
+ }
1748
+ // 轮询节奏:页面不可见时完全不发请求,回来时立刻补一次。
1749
+ // Web 端没有宿主→客户端的推送通道(桌面端有 bridge),这条「工具打开了某页」的通知只能由客户端来问;
1750
+ // 但没必要在后台标签页里一直问:DSH 自身常驻,一个隐藏窗口每秒一次的请求纯属浪费。
1751
+ if (typeof setInterval === "function") setInterval(() => {
1752
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return
1753
+ drainOpenRequest()
1754
+ }, 2000)
1755
+ if (typeof document !== "undefined" && typeof document.addEventListener === "function") {
1756
+ document.addEventListener("visibilitychange", () => {
1757
+ if (document.visibilityState !== "hidden") drainOpenRequest()
1758
+ })
1759
+ }
1760
+ /**
1761
+ * The conversation a proxied guest should attribute its quote to.
1762
+ *
1763
+ * \`screen()\` is empty for a brand-new conversation, but the shell already stamps the Session on its
1764
+ * own DOM; without this fallback the FIRST reference of a fresh conversation was silently dropped.
1765
+ * @returns the session id, or null when the shell exposes none.
1766
+ */
1767
+ function guestSession() {
1768
+ const normalise = (value) => (value.startsWith("session-") ? value.slice(8) : value)
1769
+ const direct = onScreenSession()
1770
+ if (typeof direct === "string" && direct !== "") return normalise(direct)
1771
+ try {
1772
+ const node = document.querySelector("[data-sidebar-right-session], [data-conversation-session]")
1773
+ const stamped = node === null ? null
1774
+ : node.getAttribute("data-sidebar-right-session") ?? node.getAttribute("data-conversation-session")
1775
+ // The shell stamps its DOM with a "session-<uuid>" prefix; the host's own registry (and the
1776
+ // capture route) key on the bare id, and an un-stripped value is refused as session-unavailable.
1777
+ if (typeof stamped === "string" && stamped !== "") return normalise(stamped)
1778
+ } catch { /* no DOM */ }
1779
+ return null
1780
+ }
1781
+ function onScreenSession() {
1782
+ try {
1783
+ const screen = sidebarRight === null || typeof sidebarRight.screen !== "function" ? undefined : sidebarRight.screen()
1784
+ return screen !== undefined && screen !== null && typeof screen.sessionId === "string" ? screen.sessionId : null
1785
+ } catch (error) {
1786
+ return null
1787
+ }
1788
+ }
1789
+
1790
+ /** Display the owner of an explicit open request, including an already mounted hidden guest. */
1791
+ function claimConversation(sessionId) {
1792
+ if (hasRenderingHold(sessionId)) return false
1793
+ if (uiWorkspace === null || typeof uiWorkspace.openSession !== "function") return false
1794
+ // Already displayed? Then the shell needs no navigation: the panel simply has not been opened
1795
+ // yet, and `revealPlacedPanel` opens it. Re-opening the conversation a human is reading would
1796
+ // be a no-op at best and a view reset at worst.
1797
+ if (onScreenSession() === sessionId) return false
1798
+ try {
1799
+ uiWorkspace.openSession(sessionId)
1800
+ return true
1801
+ } catch (error) {
1802
+ return false
1803
+ }
1804
+ }
1805
+
1806
+ /**
1807
+ * Make a page that has been PLACED actually appear: expand the column, focus its tab.
1808
+ *
1809
+ * A placed tab is not a shown page. The shell renders the body of the ACTIVE tab, and only
1810
+ * while the column is expanded. A collapsed column keeps the strip — so the read side still
1811
+ * reports `panel: true` — while no `<webview>` is ever created, and every guest read comes
1812
+ * back empty. That is the state that used to sit here for 20 s and then get reported as an
1813
+ * unusable panel: measured on the running shell as `panel: true`, `guestId: null` in the
1814
+ * renderer and `sidebar: []` from the bridge, with no carrier-side step that could have
1815
+ * fixed it, because nobody had ever asked the column to open.
1816
+ *
1817
+ * Both calls are layout commands on a conversation's own surface store — no input event, no
1818
+ * key dispatch, no element click. Two guards keep them from touching a conversation the
1819
+ * human is not reading:
1820
+ * - only when `screen()` names THIS conversation. `screen()` is the shell's own answer to
1821
+ * "which conversation is displayed", and `toggleExpanded` acts on exactly that one, so
1822
+ * without this check an expand could fold the column a human is reading. A conversation
1823
+ * that is displayed but was never opened (a fresh window has no right sidebar at all until
1824
+ * something asks for it) passes this check — that case is why the DOM alone is not enough;
1825
+ * - `focus` is scoped by the shell itself (a tab outside the mounted surface is ignored),
1826
+ * so passing it a tab id from another conversation's list cannot move that view.
1827
+ *
1828
+ * @param sessionId - the conversation whose page was just placed.
1829
+ * A live guest may remain mounted while its column is folded, so it still needs this step.
1830
+ * @returns what was asked for, so a caller can tell "expanded" from "already visible", and
1831
+ * `displayed` so it can tell "the shell is showing this conversation" from "it is not".
1832
+ */
1833
+ function revealPlacedPanel(sessionId, tabId) {
1834
+ if (sidebarRight === null) return {}
1835
+ const done = {}
1836
+ // Which conversation is the shell DISPLAYING? `screen()` answers it, and it is the question
1837
+ // that decides whether an expand call is safe: `toggleExpanded()` acts on the on-screen
1838
+ // session, so calling it for any other conversation would fold the column a human is reading.
1839
+ //
1840
+ // It also separates two states that the DOM alone cannot:
1841
+ // - this conversation is displayed but its column has never been opened (a fresh window
1842
+ // starts with no right sidebar at all) — expand, and the panel mounts;
1843
+ // - another conversation is displayed — nothing here may touch the column; the claim step
1844
+ // is what moves the shell, and the caller retries one render later.
1845
+ let onScreen = null
1846
+ try {
1847
+ onScreen = onScreenSession()
1848
+ } catch (error) {
1849
+ onScreen = null
1850
+ }
1851
+ if (onScreen !== sessionId) {
1852
+ done.displayed = false
1853
+ return done
1854
+ }
1855
+ done.displayed = true
1856
+ // Expansion happens before any screen() verdict: a side panel that was never opened has no
1857
+ // column to match, and bailing early there is exactly what left the page in a floating window.
1858
+ try {
1859
+ if (typeof sidebarRight.isExpanded === "function" && typeof sidebarRight.toggleExpanded === "function") {
1860
+ // `isExpanded()` is false both for "folded" and for "never opened". Both want the same
1861
+ // thing here, and `screen()` above has already established that the column being toggled
1862
+ // is THIS conversation's, so expanding cannot touch anybody else's.
1863
+ if (sidebarRight.isExpanded() === false) {
1864
+ sidebarRight.toggleExpanded()
1865
+ done.expanded = true
1866
+ }
1867
+ }
1868
+ } catch (error) {
1869
+ done.expandError = String(error?.message ?? error)
1870
+ }
1871
+ try {
1872
+ const tabs = typeof sidebarRight.tabsIn === "function" ? sidebarRight.tabsIn(sessionId) : []
1873
+ const page = Array.isArray(tabs) ? tabs.find(entry => entry !== null && typeof entry === "object" && entry.kind === "browser" && entry.id === tabId) : undefined
1874
+ if (page !== undefined && typeof sidebarRight.focus === "function") {
1875
+ sidebarRight.focus(page.id)
1876
+ done.focused = String(page.id)
1877
+ }
1878
+ } catch (error) {
1879
+ done.focusError = String(error?.message ?? error)
1880
+ }
1881
+ return done
1882
+ }
1883
+
1884
+ function viewKey(sessionId, viewId) {
1885
+ return JSON.stringify([sessionId, viewId])
1886
+ }
1887
+
1888
+ /**
1889
+ * Aim an already placed tab at one address through the shell's own
1890
+ * navigation face. This is the only way a bound tab showing the start page
1891
+ * can acquire a guest: the tab exists, but its body has never navigated.
1892
+ * @returns true when the shell accepted the target.
1893
+ */
1894
+ function navigatePlacedTab(sessionId, tabId, address) {
1895
+ try {
1896
+ if (typeof sidebarRight.navigateTabIn === "function") {
1897
+ return sidebarRight.navigateTabIn(sessionId, tabId, { params: { url: address } }) === true
1898
+ }
1899
+ const tab = Array.from(sidebarRight.tabsIn(sessionId)).find(tab => tab.id === tabId && tab.kind === "browser")
1900
+ if (typeof tab?.contentId === "string" && typeof sidebarRight.tabDomain?.navigate === "function") {
1901
+ sidebarRight.tabDomain.navigate(sessionId, tabId, { address: tab.contentId, params: { url: address } })
1902
+ return true
1903
+ }
1904
+ } catch (error) {
1905
+ return false
1906
+ }
1907
+ return false
1908
+ }
1909
+
1910
+ /** Bind each logical view to one native tab; URLs can change without changing that identity. */
1911
+ function openViewPanel(sessionId, address, viewId, guestId) {
1912
+ const key = viewKey(sessionId, viewId)
1913
+ const switched = claimConversation(sessionId)
1914
+ let tabs
1915
+ try { tabs = Array.from(sidebarRight.tabsIn(sessionId)) }
1916
+ catch { return { ok: false, reason: "the shell cannot list this conversation's tabs", panel: false, guestId: null, ...switched ? { switched: true } : {} } }
1917
+ const browsers = tabs.filter(tab => tab !== null && typeof tab === "object" && tab.kind === "browser" && typeof tab.id === "string")
1918
+ const allowed = new Set(browsers.map(tab => tab.id))
1919
+ const roots = panelRootsFor(sessionId)
1920
+ const owned = new Set(Array.from(pendingTabs.entries())
1921
+ .filter(([otherKey, binding]) => otherKey !== key && binding.sessionId === sessionId)
1922
+ .map(([, binding]) => binding.id))
1923
+ let binding = pendingTabs.get(key)
1924
+ if (binding !== undefined && !allowed.has(binding.id)) {
1925
+ // A missing store while the conversation mounts is temporary. Keep its identity until the
1926
+ // store is readable again; a nonempty store proves that the original tab actually closed.
1927
+ if (tabs.length === 0 && onScreenSession() !== sessionId) {
1928
+ return { ok: false, reason: "this conversation's sidebar is not mounted", panel: false, guestId: null, ...switched ? { switched: true } : {} }
1929
+ }
1930
+ return { ok: false, code: "BROWSER_GUEST_CLOSED", reason: "the native tab for this browser view was closed; close or reset the view before retrying", panel: true, guestId: null }
1931
+ }
1932
+ const guests = guestsInPanel(sessionId)
1933
+ const hasNativeGuest = nativeViews() !== undefined && typeof guestId === "string"
1934
+ const hasCachedGuest = (Number.isInteger(guestId) && guestId > 0) || hasNativeGuest
1935
+ if (binding === undefined && hasNativeGuest) {
1936
+ const cached = browsers.find(tab => initializationReader?.current({ sessionId, tabId: tab.id })?.guestId === guestId)
1937
+ if (cached === undefined || owned.has(cached.id)) return { ok: false, code: "BROWSER_GUEST_CLOSED", reason: "the native guest is not in this conversation", panel: true, guestId: null }
1938
+ binding = { sessionId, id: cached.id, url: address, scoped: true }
1939
+ }
1940
+ if (binding === undefined && hasCachedGuest) {
1941
+ const cached = guests.find(view => view.getWebContentsId() === guestId)
1942
+ if (cached !== undefined) {
1943
+ const id = tabIdOfElement(cached, allowed, roots)
1944
+ if (id === null || owned.has(id)) {
1945
+ return { ok: false, reason: "the requested guest cannot be assigned to this browser view", panel: true, guestId: null }
1946
+ }
1947
+ binding = { sessionId, id, url: address, scoped: true }
1948
+ }
1949
+ if (binding === undefined) return { ok: false, code: "BROWSER_GUEST_CLOSED", reason: "the native guest for this browser view is gone", panel: true, guestId: null }
1950
+ }
1951
+ if (binding === undefined && !hasCachedGuest) {
1952
+ // Adopt only an unclaimed guest whose native tab can be proved. Multiple visible guests
1953
+ // are ambiguous (split panes); creating a tab is safer than choosing by list order.
1954
+ const candidates = guests.map(view => ({ view, id: tabIdOfElement(view, allowed, roots) }))
1955
+ .filter(candidate => candidate.id !== null && !owned.has(candidate.id))
1956
+ const drawn = candidates.filter(({ view }) => {
1957
+ const rect = view.getBoundingClientRect()
1958
+ return rect.width > 0 && rect.height > 0
1959
+ })
1960
+ const candidate = drawn.length === 1 ? drawn[0] : candidates.length === 1 ? candidates[0] : undefined
1961
+ if (candidate !== undefined) binding = { sessionId, id: candidate.id, url: address, scoped: true }
1962
+ }
1963
+ const placeTab = (url) => {
1964
+ // The Web panel serves pages through the same-origin guest proxy; it needs to know which
1965
+ // conversation the tab belongs to so a quote can be handed back to the right draft.
1966
+ try { globalThis.__dshSidebarSessionId = sessionId } catch { /* non-writable global */ }
1967
+ const before = new Set(tabs.map(tab => tab.id))
1968
+ try {
1969
+ if (nativeViews() !== undefined
1970
+ && typeof sidebarRight.openReservedTab === "function") {
1971
+ const id = globalThis.crypto.randomUUID()
1972
+ if (!sidebarRight.openReservedTab(sessionId, "browser", id)) return { ok: false, reason: "the shell refused this browser tab reservation" }
1973
+ if (url && !navigatePlacedTab(sessionId, id, url)) {
1974
+ sidebarRight.closeIn?.(sessionId, id)
1975
+ return { ok: false, reason: "the shell refused this browser tab navigation" }
1976
+ }
1977
+ } else sidebarRight.openTabIn(sessionId, "browser", url ? { params: { url } } : {})
1978
+ }
1979
+ catch (error) { return { ok: false, reason: String(error?.message ?? error) } }
1980
+ let placed
1981
+ try { placed = Array.from(sidebarRight.tabsIn(sessionId)) }
1982
+ catch { placed = [] }
1983
+ const added = placed.filter(tab => tab !== null && typeof tab === "object" && tab.kind === "browser"
1984
+ && typeof tab.id === "string" && !before.has(tab.id) && !owned.has(tab.id))
1985
+ if (added.length !== 1) {
1986
+ return { ok: false, reason: placed.length === 0 ? "this conversation's sidebar is not mounted" : "the shell did not identify a new browser tab for this view" }
1987
+ }
1988
+ return { ok: true, id: added[0].id }
1989
+ }
1990
+ let created = false
1991
+ if (binding === undefined) {
1992
+ const placed = placeTab(address)
1993
+ if (!placed.ok) {
1994
+ return { ok: false, reason: placed.reason, panel: roots === undefined ? tabStripFor(sessionId) !== null : roots.length > 0, guestId: null, ...switched ? { switched: true } : {} }
1995
+ }
1996
+ binding = { sessionId, id: placed.id, url: address, scoped: true }
1997
+ created = true
1998
+ }
1999
+ pendingTabs.set(key, binding)
2000
+ const state = guestStateFor(sessionId, binding.id, initializationReader)
2001
+ // A bound tab that still shows the start page has no guest to reveal.
2002
+ // Revealing it can never produce one, so ask the shell to aim that exact
2003
+ // tab at the requested address; the host body turns the new navigation
2004
+ // revision into the one real page load. Tabs created above already carry
2005
+ // the address as their initial URL and need no second navigation.
2006
+ let navigating = false
2007
+ if (!created && state.guestId === null && address !== "") {
2008
+ navigating = navigatePlacedTab(sessionId, binding.id, address)
2009
+ if (!navigating) {
2010
+ return {
2011
+ ok: false,
2012
+ reason: "this DSH shell cannot initialize a bound start-page tab; update DSH and retry",
2013
+ panel: state.panel,
2014
+ guestId: null,
2015
+ tabId: binding.id,
2016
+ ...switched ? { switched: true } : {},
2017
+ }
2018
+ }
2019
+ }
2020
+ return {
2021
+ ok: true,
2022
+ created,
2023
+ navigating,
2024
+ panel: state.panel,
2025
+ guestId: state.guestId,
2026
+ url: state.url,
2027
+ tabId: binding.id,
2028
+ ...switched ? { switched: true } : {},
2029
+ ...revealPlacedPanel(sessionId, binding.id),
2030
+ }
2031
+ }
2032
+
2033
+ const api = {
2034
+ holdRendering(sessionId, token, deadline = Date.now() + 30_000) {
2035
+ if (typeof sessionId !== "string" || !sessionId.startsWith("session-") || typeof token !== "string") return false
2036
+ if (!Number.isFinite(deadline) || deadline <= Date.now()) return false
2037
+ if (renderingHolds.has(token)) return true
2038
+ if (onScreenSession() === sessionId || typeof sidebarRight?.holdRendering !== "function") return false
2039
+ const release = sidebarRight.holdRendering(sessionId)
2040
+ const timer = setTimeout(() => releaseRendering(token), Math.min(30_000, deadline - Date.now()))
2041
+ renderingHolds.set(token, { sessionId, release, timer })
2042
+ return true
2043
+ },
2044
+ releaseRendering,
2045
+ isBackgroundRendering(sessionId) {
2046
+ return hasRenderingHold(sessionId) && Array.from(document.querySelectorAll("[data-sidebar-right-background-rendering]"))
2047
+ .some(element => element.getAttribute("data-sidebar-right-session") === sessionId)
2048
+ },
2049
+ panelProtocol: 5,
2050
+ cancelPanelInitialization(sessionId, viewId, transactionId) {
2051
+ const pending = initializing.get(viewKey(sessionId, viewId))
2052
+ if (!pending || pending.transactionId !== transactionId) return false
2053
+ pending.controller.abort(Object.assign(new Error("sidebar initialization was cancelled"), { code: "BROWSER_NAVIGATION_CANCELLED" }))
2054
+ return true
2055
+ },
2056
+ async initializePanel(sessionId, url, options) {
2057
+ const refuse = (code, reason) => ({ ok: false, code, reason, panel: false, guestId: null })
2058
+ if (onScreenSession() !== sessionId && !api.isBackgroundRendering(sessionId)) {
2059
+ // Opening the tab and binding the sidebar are two steps in the shell, and the binding lands a
2060
+ // frame or two later. Waiting for it is not the same as switching conversations — the contract
2061
+ // that a tool-driven initialization never changes what the user is looking at still holds; we
2062
+ // only give the shell time to catch up before refusing.
2063
+ for (let attempt = 0; attempt < 4 && onScreenSession() !== sessionId; attempt += 1)
2064
+ await new Promise(resolve => setTimeout(resolve, 250))
2065
+ if (onScreenSession() !== sessionId && !api.isBackgroundRendering(sessionId))
2066
+ return refuse("panel-not-displayed", `the requested conversation is not displayed (sidebar shows ${String(onScreenSession() ?? "nothing")}, asked for ${sessionId}); select it before opening its browser`)
2067
+ }
2068
+ const reader = initializationReader
2069
+ if (reader === null || typeof reader.wait !== "function") return refuse("panel-initialization-failed", "the browser initialization subscription is unavailable; reload the plugin client")
2070
+ const deadline = options.deadline
2071
+ if (!Number.isFinite(deadline) || deadline <= Date.now()) return refuse("BROWSER_DOCUMENT_TIMEOUT", "sidebar initialization deadline expired")
2072
+ const key = viewKey(sessionId, options.viewId)
2073
+ const previous = initializing.get(key)
2074
+ const controller = new AbortController()
2075
+ const transaction = { controller, transactionId: options.transactionId }
2076
+ let placed
2077
+ const closeNative = () => {
2078
+ if (nativeViews() === undefined || typeof placed?.tabId !== "string") return
2079
+ sidebarRight.closeIn?.(sessionId, placed.tabId)
2080
+ if (pendingTabs.get(key)?.id === placed.tabId) pendingTabs.delete(key)
2081
+ }
2082
+ controller.signal.addEventListener("abort", closeNative, { once: true })
2083
+ initializing.set(key, transaction)
2084
+ previous?.controller.abort(Object.assign(new Error("a newer sidebar initialization was requested"), { code: "panel-navigation-superseded" }))
2085
+ const timer = setTimeout(() => controller.abort(Object.assign(new Error("sidebar initialization deadline expired"), { code: "BROWSER_DOCUMENT_TIMEOUT" })), deadline - Date.now())
2086
+ try {
2087
+ const answer = api.openPanel(sessionId, url, options)
2088
+ placed = answer
2089
+ if (controller.signal.aborted) { closeNative(); controller.signal.throwIfAborted() }
2090
+ if (!answer.ok) return answer
2091
+ const rendererNavigation = url !== "" && (answer.created || answer.navigating)
2092
+ if (!rendererNavigation && answer.guestId !== null) return nativeViews() !== undefined
2093
+ ? { ...answer, nativeState: reader.current({ sessionId, tabId: answer.tabId }) } : answer
2094
+ if (typeof answer.tabId !== "string") return refuse("panel-initialization-failed", "the shell did not acknowledge its native tab identity")
2095
+ const receipt = await reader.wait({ sessionId, tabId: answer.tabId, url }, controller.signal)
2096
+ controller.signal.throwIfAborted()
2097
+ const state = api.panelGuest(sessionId, answer.tabId, options)
2098
+ const observed = reader.current({ sessionId, tabId: answer.tabId })
2099
+ if (state.guestId === null || String(state.guestId) !== receipt.guestId || observed?.guestId !== receipt.guestId) {
2100
+ return refuse("panel-initialization-failed", "the mounted native guest did not acknowledge its initialization identity")
2101
+ }
2102
+ return { ...answer, ...state, url: observed.url, initialization: receipt, rendererNavigation,
2103
+ ...observed.generation === undefined ? {} : { nativeState: observed } }
2104
+ } catch (error) {
2105
+ closeNative()
2106
+ return refuse(error?.code ?? "panel-initialization-failed", String(error?.message ?? error))
2107
+ } finally {
2108
+ clearTimeout(timer)
2109
+ controller.signal.removeEventListener("abort", closeNative)
2110
+ if (initializing.get(key) === transaction) initializing.delete(key)
2111
+ }
2112
+ },
2113
+ get initializationProtocol() { return initializationReader?.protocolVersion ?? 0 },
2114
+ panelInitialization(sessionId, tabId, url, requestId) {
2115
+ if (initializationReader === null || typeof sessionId !== "string" || !sessionId.startsWith("session-")
2116
+ || typeof tabId !== "string" || typeof url !== "string") return undefined
2117
+ const binding = Array.from(pendingTabs.values()).find(value => value.sessionId === sessionId && value.id === tabId)
2118
+ if (binding === undefined) return undefined
2119
+ return initializationReader.read({ sessionId, tabId, url,
2120
+ ...typeof requestId === "string" ? { requestId } : {} })
2121
+ },
2122
+ /** @returns what happened: an existing guest, a newly opened tab, or a named refusal. */
2123
+ openPanel(sessionId, url, options) {
2124
+ const wanted = typeof sessionId === "string" ? sessionId : ""
2125
+ if (!/^session-/.test(wanted)) {
2126
+ return { ok: false, reason: "not a conversation id: " + JSON.stringify(sessionId), panel: false, guestId: null }
2127
+ }
2128
+ if (sidebarRight === null || typeof sidebarRight.openTabIn !== "function") {
2129
+ return { ok: false, reason: "the shell's sidebar service is not available", panel: false, guestId: null }
2130
+ }
2131
+ const address = url ? String(url) : ""
2132
+ if (typeof options?.viewId === "string" && options.viewId !== "") {
2133
+ return openViewPanel(wanted, address, options.viewId, options.guestId)
2134
+ }
2135
+ const pending = pendingTabs.get(wanted)
2136
+ const state = guestStateFor(wanted, pending?.url === address && pending.scoped ? pending.id : undefined, initializationReader)
2137
+ // Explicit opening also reveals a guest kept mounted in a collapsed or hidden sidebar.
2138
+ // Passive panelGuest/panelGuests reads never call either presentation helper.
2139
+ const switched = claimConversation(wanted)
2140
+ if (state.guestId !== null) {
2141
+ const revealed = revealPlacedPanel(wanted, pending?.url === address ? pending.id : undefined)
2142
+ return {
2143
+ ok: true,
2144
+ created: false,
2145
+ panel: true,
2146
+ guestId: state.guestId,
2147
+ url: state.url,
2148
+ ...switched ? { switched: true } : {},
2149
+ ...revealed,
2150
+ }
2151
+ }
2152
+ // No panel DOM for this conversation means the shell is not DISPLAYING it, and no tab placed
2153
+ // here can ever grow a webview: the shell renders one sidebar, for the conversation it shows.
2154
+ // Asking the human to click over was the old answer, and it made a working carrier depend on
2155
+ // their timing. Ask the shell instead — `openSession` is its own navigation, one call on its
2156
+ // own workspace service, no input events — and report `switched` so the caller can retry one
2157
+ // render later instead of reporting a dead carrier.
2158
+ // A mounted panel is NOT required to place a tab.
2159
+ //
2160
+ // `openTabIn` acts on the conversation's own surface store, and the sidebar-right service
2161
+ // keeps one for every conversation the shell has shown — "reaches any session's store by
2162
+ // id … on screen or not". What a DISPLAYED conversation adds is the DOM to read the guest
2163
+ // back out of, which is a separate question. So the tab is placed either way, and `tabsIn`
2164
+ // (a public method) is what says whether it actually landed: `openTabIn` SILENTLY ignores a
2165
+ // conversation whose store was never minted, and a silent no-op must never be reported as
2166
+ // success.
2167
+ let beforeTabs = []
2168
+ try { beforeTabs = Array.from(sidebarRight.tabsIn(wanted)) } catch {}
2169
+ const before = beforeTabs.length
2170
+ const beforeIds = new Set(beforeTabs.map(tab => tab.id))
2171
+ const remembered = pending?.url === address
2172
+ ? beforeTabs.find(tab => tab.kind === "browser" && tab.id === pending.id)
2173
+ : undefined
2174
+ if (remembered === undefined) {
2175
+ try {
2176
+ sidebarRight.openTabIn(wanted, "browser", address ? { params: { url: address } } : {})
2177
+ } catch (error) {
2178
+ return { ok: false, reason: String((error && error.message) || error), panel: state.panel, guestId: null }
2179
+ }
2180
+ }
2181
+ let placedTabs = beforeTabs
2182
+ try { placedTabs = Array.from(sidebarRight.tabsIn(wanted)) } catch {}
2183
+ const placed = placedTabs.length
2184
+ const browserTabs = placedTabs.filter(tab => tab !== null && typeof tab === "object" && tab.kind === "browser")
2185
+ const added = browserTabs.filter(tab => !beforeIds.has(tab.id))
2186
+ const matching = browserTabs.filter(tab => address !== "" && (tab.params?.url === address || tab.url === address))
2187
+ // Multiple browser tabs use separate ids. Correlate this placement before revealing it.
2188
+ // Older shells deduplicate the browser kind, so their sole browser is unambiguous.
2189
+ const page = remembered
2190
+ ?? (added.length === 1 ? added[0] : undefined)
2191
+ ?? (matching.length === 1 ? matching[0] : undefined)
2192
+ ?? (browserTabs.length === 1 ? browserTabs[0] : undefined)
2193
+ const scoped = browserTabs.length > 1 || panelRootsFor(wanted) !== undefined
2194
+ if (page !== undefined) pendingTabs.set(wanted, { id: page.id, url: address, scoped })
2195
+ if (page === undefined && browserTabs.length > 1) {
2196
+ return { ok: false, reason: "the shell did not identify which browser tab was placed", panel: state.panel, guestId: null }
2197
+ }
2198
+ // `openTabIn` DEDUPLICATES, so "the count grew" is the wrong test for "is this
2199
+ // conversation's surface mounted".
2200
+ //
2201
+ // Placing a page kind the conversation already holds leaves the count unchanged — the shell
2202
+ // reveals the tab it has. Testing for growth therefore reported a conversation that already
2203
+ // held the page as UNMOUNTED, and refused to drive a page that was right there: that is the
2204
+ // "it will not reopen what it already opened" behaviour, and it bites hardest on the second
2205
+ // open of an address, which is exactly when a human expects a fast answer.
2206
+ //
2207
+ // A count that started at zero and stayed there is the real signature of a surface the
2208
+ // shell has never minted, because that is the only case where `openTabIn` is a silent no-op.
2209
+ if (placed <= before && before === 0) {
2210
+ // Name what was FOUND, not just what was missing: "no panel" has two very different
2211
+ // causes — the shell has mounted no sidebar for this conversation (nothing this side can
2212
+ // do), or it writes its session id somewhere this lookup does not read (fixable) — and a
2213
+ // refusal that says only "not mounted" cannot tell them apart.
2214
+ const strips = Array.from(document.querySelectorAll(LEGACY_TAB_STRIP_SELECTOR))
2215
+ return {
2216
+ ok: false,
2217
+ reason: "this conversation's sidebar is not mounted, so a panel cannot be opened in it",
2218
+ panel: state.panel,
2219
+ guestId: null,
2220
+ ...switched ? { switched: true } : {},
2221
+ found: {
2222
+ wanted: wanted,
2223
+ strips: strips.length,
2224
+ owners: strips.slice(0, 8).map(strip => sessionIdOfElement(strip)),
2225
+ reactKeys: strips.length === 0 ? [] : Object.keys(strips[0]).filter(key => key.startsWith("__react")).slice(0, 4),
2226
+ },
2227
+ }
2228
+ }
2229
+ // Placing is not showing: ask the shell to expand the column and focus that tab, so the
2230
+ // body (and with it the `<webview>`) actually gets created. Without this the caller polls
2231
+ // a panel that can never answer, which is exactly what "produced no page" used to mean.
2232
+ const revealed = revealPlacedPanel(wanted, page?.id)
2233
+ return {
2234
+ ok: true,
2235
+ created: placed > before,
2236
+ panel: state.panel,
2237
+ guestId: null,
2238
+ tabs: placed,
2239
+ ...page === undefined || !scoped ? {} : { tabId: String(page.id) },
2240
+ ...switched ? { switched: true } : {},
2241
+ ...revealed,
2242
+ }
2243
+ },
2244
+ /** Read-only: this conversation's current guest, if it has one. */
2245
+ panelGuest(sessionId, tabId, options) {
2246
+ if (typeof options?.viewId === "string" && options.viewId !== "") {
2247
+ const bound = pendingTabs.get(viewKey(sessionId, options.viewId))
2248
+ const intended = typeof tabId === "string" && tabId !== "" ? tabId : bound?.id
2249
+ if (intended === undefined || (bound !== undefined && bound.id !== intended)) {
2250
+ const roots = panelRootsFor(sessionId)
2251
+ return { panel: roots === undefined ? tabStripFor(sessionId) !== null : roots.length > 0, guestId: null, url: "" }
2252
+ }
2253
+ return guestStateFor(sessionId, intended, initializationReader)
2254
+ }
2255
+ return guestStateFor(
2256
+ typeof sessionId === "string" ? sessionId : "",
2257
+ typeof tabId === "string" && tabId !== "" ? tabId : undefined,
2258
+ initializationReader,
2259
+ )
2260
+ },
2261
+ /** All guest ids verified inside this conversation, including shell-created popup tabs. */
2262
+ panelGuests(sessionId) {
2263
+ if (typeof sessionId !== "string" || !/^session-/.test(sessionId)) return []
2264
+ return guestsInPanel(sessionId).map(view => view.getWebContentsId())
2265
+ },
2266
+ /** Close exactly the tab hosting this guest. An unknown shell shape must fail closed. */
2267
+ closePanelGuest(sessionId, guestId) {
2268
+ const refuse = reason => ({ ok: false, reason, closed: 0 })
2269
+ if (typeof sessionId !== "string" || !/^session-/.test(sessionId)) return refuse("a conversation id is required")
2270
+ if (typeof guestId === "string" && nativeViews() !== undefined) {
2271
+ const tabs = sidebarRight.tabsIn(sessionId)
2272
+ const tab = tabs.find(tab => tab.kind === "browser" && initializationReader?.current({ sessionId, tabId: tab.id })?.guestId === guestId)
2273
+ if (tab === undefined || typeof sidebarRight.closeIn !== "function") return refuse("the native guest does not belong to this conversation")
2274
+ sidebarRight.closeIn(sessionId, tab.id)
2275
+ return { ok: true, closed: 1 }
2276
+ }
2277
+ const view = guestsInPanel(sessionId).find(candidate => candidate.getWebContentsId() === guestId)
2278
+ if (view === undefined) return refuse("the guest does not belong to this conversation panel")
2279
+ const roots = panelRootsFor(sessionId)
2280
+ const containers = roots === undefined ? [tabStripFor(sessionId)].filter(Boolean) : roots
2281
+ if (containers.length === 0 || sidebarRight === null || typeof sidebarRight.tabsIn !== "function") {
2282
+ return refuse("the shell cannot identify its tabs; refresh or upgrade the browser plugin client")
2283
+ }
2284
+ let tabs
2285
+ try { tabs = sidebarRight.tabsIn(sessionId) } catch { return refuse("the conversation tabs are unavailable") }
2286
+ const allowed = new Set(tabs.map(tab => tab.id))
2287
+ const id = tabIdOfElement(view, allowed, roots)
2288
+ if (id === null) return refuse("the shell does not expose this guest's tab identity; refresh or upgrade the desktop")
2289
+ // rc.5's scoped controller runs registered cleanup and removes the shell tab as one action.
2290
+ if (typeof sidebarRight.closeIn === "function") {
2291
+ try {
2292
+ sidebarRight.closeIn(sessionId, id)
2293
+ if (sidebarRight.tabsIn(sessionId).some(tab => tab.id === id)) return refuse("the shell did not remove the requested conversation tab")
2294
+ return { ok: true, closed: 1 }
2295
+ } catch (error) { return refuse("the shell could not close the conversation tab: " + String(error?.message ?? error)) }
2296
+ }
2297
+ const headers = Array.from(new Set(containers.flatMap(container => Array.from(container.querySelectorAll("[role=tab]")))))
2298
+ .filter(tab => tabIdOfElement(tab, allowed, roots) === id)
2299
+ if (headers.length !== 1) return refuse("the shell does not expose one matching tab control; refresh or upgrade the desktop")
2300
+ const buttons = Array.from(headers[0].querySelectorAll("button"))
2301
+ .filter(button => /关闭|close/i.test((button.getAttribute("aria-label") || "") + " " + (button.getAttribute("title") || "")))
2302
+ if (buttons.length !== 1) return refuse("the shell does not expose one matching close control; refresh or upgrade the desktop")
2303
+ buttons[0].click()
2304
+ return { ok: true, closed: 1 }
2305
+ },
2306
+ }
2307
+ ctx.effect(() => {
2308
+ globalThis.__dshBuiltinBrowser = api
2309
+ return () => {
2310
+ for (const transaction of initializing.values()) transaction.controller.abort(new Error("the panel service was disposed"))
2311
+ initializing.clear()
2312
+ releaseAllRendering()
2313
+ if (globalThis.__dshBuiltinBrowser === api) delete globalThis.__dshBuiltinBrowser
2314
+ }
2315
+ }, "dsh-builtin-browser: conversation panel service")
2316
+ }
2317
+
2318
+ /**
2319
+ * The live-view panel: one frame at a time, for an operator who is not sitting at this machine.
2320
+ *
2321
+ * A plain floating layer rather than a slot registration, deliberately. The host's layout has no
2322
+ * stable slot for "an extra surface over the conversation", and inventing one would tie this
2323
+ * panel to a layout that changes; a fixed layer works in every layout including a phone. It is
2324
+ * also entirely inert until the host turns `remoteView.enabled` on, which the sessions probe
2325
+ * reports.
2326
+ *
2327
+ * Pulls one frame per request and waits for it to paint before asking for the next, so a slow
2328
+ * link shows fewer frames instead of queueing them. Nothing here retries in a tight loop: a
2329
+ * refusal or a 503 moves the panel to a paused state, and it resumes on the next user action.
2330
+ * @param ctx - the plugin context, for the disposal hook.
2331
+ */
2332
+ function installWatchPanel(ctx) {
2333
+ if (typeof document === "undefined") return
2334
+ const SESSIONS = PREVIEW_SESSIONS_ROUTE
2335
+ const FRAME = PREVIEW_ROUTE
2336
+ const MIN_INTERVAL_MS = 500
2337
+
2338
+ // Built element by element and referenced directly, never through innerHTML + querySelector.
2339
+ // Two reasons: the host's test sandbox provides a minimal `createElement`, and re-parsing markup
2340
+ // to find elements this code just made is work without a purpose.
2341
+ const make = (tag, className, text) => {
2342
+ const node = document.createElement(tag)
2343
+ if (className !== undefined) node.className = className
2344
+ if (text !== undefined) node.textContent = text
2345
+ return node
2346
+ }
2347
+
2348
+ const layer = make("div", "dsh-bw-watch")
2349
+ layer.setAttribute("data-dsh-bw-watch", "")
2350
+
2351
+ const openButton = make("button", "dsh-bw-watch-open")
2352
+ openButton.setAttribute("type", "button")
2353
+ const dot = make("span", "dsh-bw-watch-dot")
2354
+ const openLabel = make("span", "dsh-bw-watch-label")
2355
+ openButton.appendChild(dot)
2356
+ openButton.appendChild(openLabel)
2357
+
2358
+ const panel = make("section", "dsh-bw-watch-panel")
2359
+ panel.hidden = true
2360
+
2361
+ const head = make("header", "dsh-bw-watch-head")
2362
+ const title = make("span", "dsh-bw-watch-title")
2363
+ const state = make("span", "dsh-bw-watch-state")
2364
+ /** Only visible when the host reports more than one session to watch. */
2365
+ const sessionSelect = make("select", "dsh-bw-watch-session")
2366
+ sessionSelect.hidden = true
2367
+ const closeButton = make("button", "dsh-bw-watch-close", "×")
2368
+ closeButton.setAttribute("type", "button")
2369
+ head.appendChild(title)
2370
+ head.appendChild(sessionSelect)
2371
+ head.appendChild(state)
2372
+ head.appendChild(closeButton)
2373
+
2374
+ const stage = make("div", "dsh-bw-watch-stage")
2375
+ const img = make("img", "dsh-bw-watch-img")
2376
+ img.hidden = true
2377
+ const note = make("p", "dsh-bw-watch-note")
2378
+ stage.appendChild(img)
2379
+ stage.appendChild(note)
2380
+
2381
+ const foot = make("footer", "dsh-bw-watch-foot")
2382
+ const readonlyLabel = make("span", "dsh-bw-watch-readonly")
2383
+ const stopButton = make("button", "dsh-bw-watch-stop")
2384
+ stopButton.setAttribute("type", "button")
2385
+ foot.appendChild(readonlyLabel)
2386
+ foot.appendChild(stopButton)
2387
+
2388
+ panel.appendChild(head)
2389
+ panel.appendChild(stage)
2390
+ panel.appendChild(foot)
2391
+ layer.appendChild(openButton)
2392
+ layer.appendChild(panel)
2393
+ // Deliberately NOT appended here. The entry is mounted only when the host reports that watching
2394
+ // is on — reported as issue #40: with the feature off, the button still sat on every page and
2395
+ // the bridge-status request fired at startup, so a setting nobody turned on produced a permanent
2396
+ // control and a permanent diagnostic call.
2397
+
2398
+ /** Localized text, falling back to the key so a missing entry is visible rather than blank. */
2399
+ // Localized text.
2400
+ //
2401
+ // The try/catch that used to sit here was dead code, as Mzy123l pointed out on #40: the locale
2402
+ // service does not throw on a missing entry — it returns the key. So a miss shows the key, which
2403
+ // is diagnostic, and an empty answer is the only case worth substituting.
2404
+ const say = key => {
2405
+ const text = translate(key)
2406
+ return typeof text === "string" && text !== "" ? text : key
2407
+ }
2408
+
2409
+ /**
2410
+ * Apply the current locale to every static label.
2411
+ *
2412
+ * Called at mount, after a locale change, and again once the dictionaries are bound. The panel
2413
+ * used to set these exactly once, inside `apply()`, *before* `locale.register` had run — so the
2414
+ * shipped build showed `watch.title` as its title and the key was never replaced (issue #40).
2415
+ */
2416
+ const relabel = () => {
2417
+ openLabel.textContent = say("watch.open")
2418
+ title.textContent = say("watch.title")
2419
+ readonlyLabel.textContent = say("watch.readOnly")
2420
+ stopButton.textContent = say("watch.stop")
2421
+ openButton.title = say("watch.open")
2422
+ sessionSelect.title = say("watch.session")
2423
+ sessionSelect.setAttribute("aria-label", say("watch.session"))
2424
+ }
2425
+ relabel()
2426
+ // A runtime language switch must reach labels that are already on screen. `subscribe` fires on
2427
+ // every locale snapshot change — a switch, and also a late dictionary registration — which is
2428
+ // exactly the set of moments these four strings can go stale.
2429
+ refreshWatchLabels = () => { relabel() }
2430
+
2431
+ let mounted = false
2432
+ /** Put the entry on the page. Idempotent, so a second enable cannot stack copies. */
2433
+ const mount = () => {
2434
+ if (mounted) return
2435
+ mounted = true
2436
+ document.body.appendChild(layer)
2437
+ relabel()
2438
+ }
2439
+ /** Take it off again — the host turned the feature off after it had been on. */
2440
+ const unmount = () => {
2441
+ if (!mounted) return
2442
+ mounted = false
2443
+ layer.remove()
2444
+ }
2445
+
2446
+ /**
2447
+ * One running view. `generation` is the identity of a single watching run: a stop, a session
2448
+ * switch and a reopen all advance it, so a request already in flight can never paint into the
2449
+ * new run or resurrect a second scheduling chain.
2450
+ */
2451
+ const view = {
2452
+ session: undefined, timer: undefined, running: false, lastAt: 0, objectUrl: undefined,
2453
+ generation: 0, controller: undefined,
2454
+ }
2455
+ /** Guards the async probe: two clicks in the same tick must not both reach start(). */
2456
+ let starting = false
2457
+
2458
+ const setState = text => { state.textContent = text }
2459
+ const showNote = text => {
2460
+ note.textContent = text
2461
+ note.hidden = false
2462
+ img.hidden = true
2463
+ }
2464
+ /** Release the previous frame. A viewer that keeps every frame is a memory leak in a phone browser. */
2465
+ const dropFrame = () => {
2466
+ if (view.objectUrl !== undefined) {
2467
+ URL.revokeObjectURL(view.objectUrl)
2468
+ view.objectUrl = undefined
2469
+ }
2470
+ }
2471
+ /** End one generation: cancel its request, timer and frame, without touching the panel chrome. */
2472
+ const cancelLoop = () => {
2473
+ view.running = false
2474
+ view.generation += 1
2475
+ if (view.controller !== undefined) {
2476
+ try { view.controller.abort() } catch { /* an already settled controller is harmless */ }
2477
+ view.controller = undefined
2478
+ }
2479
+ if (view.timer !== undefined) { clearTimeout(view.timer); view.timer = undefined }
2480
+ dropFrame()
2481
+ img.removeAttribute("src")
2482
+ img.hidden = true
2483
+ }
2484
+ const stop = () => {
2485
+ cancelLoop()
2486
+ setState(say("watch.stopped"))
2487
+ showNote(say("watch.stopped"))
2488
+ panel.hidden = true
2489
+ }
2490
+
2491
+ /** Ask which sessions exist; returns whether watching is enabled at all. */
2492
+ const probe = async () => {
2493
+ try {
2494
+ const response = await fetch(SESSIONS, { headers: { accept: "application/json" } })
2495
+ if (!response.ok) return { enabled: false, sessions: [] }
2496
+ const data = await response.json()
2497
+ return { enabled: data?.enabled === true, sessions: Array.isArray(data?.sessions) ? data.sessions : [] }
2498
+ } catch {
2499
+ return { enabled: false, sessions: [] }
2500
+ }
2501
+ }
2502
+
2503
+ /** Show the sessions the host handed out, so a later-created one can actually be chosen. */
2504
+ const fillSessions = sessions => {
2505
+ // Clearing via innerHTML is the one exception to "build element by element": it removes
2506
+ // options, it does not parse markup, and a stale option list would keep a dead session on screen.
2507
+ sessionSelect.innerHTML = ""
2508
+ for (let index = 0; index < sessions.length; index += 1) {
2509
+ const id = String(sessions[index])
2510
+ const option = make("option")
2511
+ option.setAttribute("value", id)
2512
+ const short = id.length > 24 ? `${id.slice(0, 15)}…${id.slice(-6)}` : id
2513
+ option.textContent = `#${index + 1} ${short}`
2514
+ sessionSelect.appendChild(option)
2515
+ }
2516
+ sessionSelect.hidden = sessions.length < 2
2517
+ }
2518
+
2519
+ /**
2520
+ * Pull frames until stopped. One request in flight at a time, and the next one is scheduled only
2521
+ * after the current image has painted — that is what makes a slow link degrade into fewer
2522
+ * frames rather than a growing queue. `gen` is captured once per run and re-checked after every
2523
+ * await: a frame belonging to a superseded run is dropped instead of painted.
2524
+ */
2525
+ const pump = async gen => {
2526
+ if (!view.running || gen !== view.generation) return
2527
+ if (document.visibilityState === "hidden") {
2528
+ // The design's rule: a hidden panel stops pulling immediately. Resuming is the user's
2529
+ // action, not a timer's.
2530
+ setState(say("watch.paused"))
2531
+ showNote(say("watch.paused"))
2532
+ view.timer = setTimeout(() => pump(gen), MIN_INTERVAL_MS * 4)
2533
+ return
2534
+ }
2535
+ const waited = Date.now() - view.lastAt
2536
+ if (waited < MIN_INTERVAL_MS) {
2537
+ view.timer = setTimeout(() => pump(gen), MIN_INTERVAL_MS - waited)
2538
+ return
2539
+ }
2540
+ view.lastAt = Date.now()
2541
+ let nextDelay = MIN_INTERVAL_MS
2542
+ const controller = view.controller
2543
+ try {
2544
+ const url = `${FRAME}?session=${encodeURIComponent(String(view.session))}`
2545
+ const init = { headers: { accept: "image/jpeg" } }
2546
+ if (controller !== undefined) init.signal = controller.signal
2547
+ const response = await fetch(url, init)
2548
+ if (!view.running || gen !== view.generation) return
2549
+ if (!response.ok) {
2550
+ const body = await response.json().catch(() => undefined)
2551
+ if (!view.running || gen !== view.generation) return
2552
+ setState(say("watch.paused"))
2553
+ showNote(body?.error === "remote-view-disabled"
2554
+ ? say("watch.disabled")
2555
+ : body?.error === "no-such-session"
2556
+ ? say("watch.noPage")
2557
+ : say("watch.paused"))
2558
+ // Slower polling while paused: a paused view must not turn into a hot loop.
2559
+ nextDelay = MIN_INTERVAL_MS * 4
2560
+ } else {
2561
+ const blob = await response.blob()
2562
+ if (!view.running || gen !== view.generation) return
2563
+ const painted = new Promise(resolve => {
2564
+ img.onload = () => resolve()
2565
+ img.onerror = () => resolve()
2566
+ })
2567
+ dropFrame()
2568
+ view.objectUrl = URL.createObjectURL(blob)
2569
+ img.src = view.objectUrl
2570
+ img.hidden = false
2571
+ note.hidden = true
2572
+ await painted
2573
+ if (!view.running || gen !== view.generation) return
2574
+ setState(say("watch.live"))
2575
+ }
2576
+ } catch {
2577
+ if (!view.running || gen !== view.generation) return
2578
+ setState(say("watch.disconnected"))
2579
+ showNote(say("watch.disconnected"))
2580
+ nextDelay = MIN_INTERVAL_MS * 4
2581
+ }
2582
+ if (view.running && gen === view.generation) view.timer = setTimeout(() => pump(gen), nextDelay)
2583
+ }
2584
+
2585
+ const start = async session => {
2586
+ cancelLoop()
2587
+ view.session = session
2588
+ view.running = true
2589
+ view.lastAt = 0
2590
+ view.controller = typeof AbortController === "function" ? new AbortController() : undefined
2591
+ const gen = view.generation
2592
+ panel.hidden = false
2593
+ setState(say("watch.connecting"))
2594
+ showNote(say("watch.connecting"))
2595
+ await pump(gen)
2596
+ }
2597
+
2598
+ /**
2599
+ * The session a viewer most likely means when the host cannot name the current conversation:
2600
+ * the newest session it created, rather than always the first entry of the map.
2601
+ */
2602
+ const preferredSession = sessions => sessions[sessions.length - 1]
2603
+
2604
+ openButton.addEventListener("click", () => {
2605
+ void (async () => {
2606
+ if (view.running || starting) return
2607
+ starting = true
2608
+ try {
2609
+ const found = await probe()
2610
+ if (!found.enabled) { showNote(say("watch.disabled")); panel.hidden = false; return }
2611
+ if (found.sessions.length === 0) { showNote(say("watch.noPage")); panel.hidden = false; return }
2612
+ fillSessions(found.sessions)
2613
+ sessionSelect.value = String(preferredSession(found.sessions))
2614
+ const chosen = sessionSelect.value
2615
+ // Release before start(): the first frame may take a long time (or never arrive), and
2616
+ // holding the guard until then would also block a legitimate stop-then-reopen.
2617
+ // There is no await between here and start(), whose synchronous part sets view.running.
2618
+ starting = false
2619
+ await start(chosen)
2620
+ } finally { starting = false }
2621
+ })()
2622
+ })
2623
+ // Switching sessions replaces the run; it never adds a second loop alongside the live one.
2624
+ sessionSelect.addEventListener("change", () => {
2625
+ if (!view.running) return
2626
+ const chosen = sessionSelect.value
2627
+ if (typeof chosen === "string" && chosen !== "") void start(chosen)
2628
+ })
2629
+ closeButton.addEventListener("click", stop)
2630
+ stopButton.addEventListener("click", stop)
2631
+ // A panel hidden by a closed button must not keep pulling frames.
2632
+ document.addEventListener("visibilitychange", () => {
2633
+ if (document.visibilityState === "hidden" && view.running) {
2634
+ if (view.timer !== undefined) { clearTimeout(view.timer); view.timer = undefined }
2635
+ const gen = view.generation
2636
+ view.timer = setTimeout(() => pump(gen), MIN_INTERVAL_MS)
2637
+ }
2638
+ })
2639
+
2640
+ ctx.effect(() => () => {
2641
+ stop()
2642
+ unmount()
2643
+ refreshWatchEntry = () => {}
2644
+ refreshWatchLabels = () => {}
2645
+ }, "dsh-builtin-browser: live view panel")
2646
+
2647
+ /**
2648
+ * Report the sidebar bridge's install state next to the entry button.
2649
+ *
2650
+ * A missing bridge used to be a log line and nothing else, so a user on `channel: sidebar` saw
2651
+ * "another window opened again" with no way to connect that to the actual cause (issue #36).
2652
+ * The reading comes from the install tree, so it is true even before anything has been watched.
2653
+ *
2654
+ * The repair command is shown, never run: a page that could decide to close the desktop shell
2655
+ * would be a worse problem than the one this line solves.
2656
+ */
2657
+ const showBridgeStatus = async () => {
2658
+ let status
2659
+ try {
2660
+ const response = await fetch(BRIDGE_STATUS_ROUTE, { headers: { accept: "application/json" } })
2661
+ if (!response.ok) return
2662
+ const data = await response.json()
2663
+ status = data?.bridge
2664
+ } catch {
2665
+ return
2666
+ }
2667
+ if (status === undefined) return
2668
+ // Only the two states a user can act on: an installed bridge needs no notice, and a host
2669
+ // without a desktop install has nothing to repair here.
2670
+ if (status.state === "installed" || status.present !== true) return
2671
+ const notice = make("div", "dsh-bw-watch-bridge")
2672
+ const line = make("div", "dsh-bw-watch-bridge-line",
2673
+ status.state === "stale" ? say("watch.bridgeStale") : say("watch.bridgeMissing"))
2674
+ notice.appendChild(line)
2675
+ if (typeof status.command === "string" && status.command !== "" && typeof window.dshDesktop?.mainExtensions?.status !== "function") {
2676
+ const code = make("code", "dsh-bw-watch-bridge-cmd", status.command)
2677
+ notice.appendChild(code)
2678
+ }
2679
+ panel.insertBefore(notice, panel.firstChild)
2680
+ }
2681
+
2682
+ /**
2683
+ * Mount the entry only if the host says viewing is enabled, and only then ask about the bridge.
2684
+ *
2685
+ * Both halves are the point of the ordering: the probe answers "is this feature on", and the
2686
+ * bridge-status request is a diagnostic for a feature that is on. Issuing it for a feature that
2687
+ * is off is what the review called a default entry manufacturing a call (issue #40).
2688
+ *
2689
+ * A host that does not serve the sessions endpoint answers `enabled: false`, so the fallback is
2690
+ * "no entry" rather than "an entry that cannot work".
2691
+ */
2692
+ const mountIfEnabled = async () => {
2693
+ const found = await probe()
2694
+ if (!found.enabled) {
2695
+ // Turning the feature off must also stop what it started: a running stream outliving its own
2696
+ // switch is the sort of state that looks like a ghost later.
2697
+ stop()
2698
+ unmount()
2699
+ return
2700
+ }
2701
+ mount()
2702
+ await showBridgeStatus()
2703
+ }
2704
+ // The settings switch calls this after writing `remoteView.enabled` (issue #46): no page reload,
2705
+ // which is the difference between usable and useless on a phone.
2706
+ refreshWatchEntry = () => { void mountIfEnabled() }
2707
+ void mountIfEnabled()
2708
+ }
2709
+
2710
+ function apply(ctx) {
2711
+ // Before anything renders: the rows need a hover state, and inline styles cannot express
2712
+ // one. Idempotent, so a re-apply does not stack copies.
2713
+ installStyles()
2714
+ installPanelService(ctx)
2715
+ // Dictionaries and the bound `t` come BEFORE anything that sets text from them. The watch panel
2716
+ // used to be installed first, so its static labels were written while `translate` still returned
2717
+ // the key and were never rewritten — the panel shipped with `watch.title` as its title
2718
+ // (issue #40).
2719
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), "dsh-builtin-browser: dictionaries")
2720
+ const t = ctx.locale.bind(NS)
2721
+ translate = t
2722
+ updateCurrentLocale(ctx.locale)
2723
+ // A language switch has to reach text that is already on screen. `subscribe` fires on every
2724
+ // locale snapshot change (switch, and late dictionary registration); guarded, because a host
2725
+ // without it must still get the panel — the labels then simply keep their first language.
2726
+ if (typeof ctx.locale.subscribe === "function") {
2727
+ ctx.effect(() => {
2728
+ const off = ctx.locale.subscribe(() => {
2729
+ translate = ctx.locale.bind(NS)
2730
+ updateCurrentLocale(ctx.locale)
2731
+ // Two audiences, one notification: the vanilla watch panel rewrites its own text, and the
2732
+ // React settings section re-renders (see `useLocaleVersion`). Bumping the counter here is
2733
+ // what makes `t()` inside a mounted component return the new language at all.
2734
+ localeVersion += 1
2735
+ for (const update of localeWatchers) update()
2736
+ refreshWatchLabels()
2737
+ })
2738
+ return () => { if (typeof off === "function") off() }
2739
+ }, "dsh-builtin-browser: locale changes")
2740
+ }
2741
+ installWatchPanel(ctx)
2742
+ // Test seam. The readiness section is composed by the settings component, so a harness that
2743
+ // renders that component can see the element but never run it — and running it is what proves a
2744
+ // user reads a state label rather than `readiness.electron.failed`. Exported on the module rather
2745
+ // than published on `globalThis` (where the product's own `__dshBuiltinBrowser` lives, for the
2746
+ // shell's benefit): nothing in the product reads this name, and a page-level global would be a
2747
+ // side effect of shipping a test.
2748
+ exports.__readinessSection = Readiness
2749
+ // Same seam, same reason: the record list is now composed inside the
2750
+ // on-demand menu, so a harness must be able to render it without driving
2751
+ // the popover's own state.
2752
+ exports.__references = References
2753
+ exports.__hostPatchSection = HostPatchControls
2754
+ ctx.slots.inject("settings.section", () => ctx.slots.register({
2755
+ name: "settings.section",
2756
+ id: "dsh-builtin-browser",
2757
+ // Above the rows the host ships (its furthest sits at 40), so this panel
2758
+ // lands beneath them in the settings page.
2759
+ order: 60,
2760
+ label: () => t("nav"),
2761
+ locale: NS,
2762
+ inject: () => ({ t }),
2763
+ }, SettingsRoot))
2764
+ // No `conversation.input.left` entry: references are rendered one card per
2765
+ // selection inside the composer dock, so an aggregate record menu beside
2766
+ // the input only duplicated it.
2767
+ }
2768
+
2769
+ exports.name = name
2770
+ exports.inject = inject
2771
+ exports.apply = apply
2772
+ return module.exports as unknown as LegacyClientModule
2773
+ }