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,447 @@
1
+ /**
2
+ * Cordis assembly entry (the `apply(ctx)` the standalone deploy patch loads).
3
+ *
4
+ * The host context is typed STRUCTURALLY: no `@deepseek-ai/cordis` runtime (or
5
+ * type) import, so this package stays self-contained and compilable with
6
+ * `types: []`. The real cordis Context satisfies this shape. `apply` wires:
7
+ * - an HTTP client over the plugin's loopback surface (host cookie),
8
+ * - the fully-injected production runtime,
9
+ * - the dock card into `conversation.input.overlay` (scope: session), i.e. the
10
+ * pill rail INSIDE the composer card, above the text surface,
11
+ * - the reply-side link into `conversation.user.text.node`,
12
+ * - cancellable polling started once and disposed through `ctx.effect`.
13
+ *
14
+ * React renders the dock and feedback through the host's shared platform
15
+ * modules. A reference reaches the model through the composer: its quote and its image attachments.
16
+ *
17
+ * @module dsh-browser-reference/production/assembly
18
+ */
19
+ import { createMemoryStorage, type KeyValueStorage } from '../types.ts'
20
+ import {
21
+ createFetchRequest,
22
+ createReferenceHttpClient,
23
+ type RequestLike,
24
+ } from './http-transport.ts'
25
+ import {
26
+ createCancellationSource,
27
+ type PollerScheduler,
28
+ } from './delivery-client.ts'
29
+ import {
30
+ createProductionRuntime,
31
+ type AdmitAssetResult,
32
+ type DockSnapshot,
33
+ type ProductionRuntime,
34
+ } from './runtime.ts'
35
+ import type { HostInputFace } from './draft-adapter.ts'
36
+ import type { AssetResponse } from './protocol.ts'
37
+ import type { TextPosition } from '../ordered-submission.ts'
38
+ import { ensureDockStyles } from './styles.ts'
39
+ import { buildBrowserRefLinkProps } from '../BrowserRefLink.tsx'
40
+ import { installReplyLinkBridge } from './reply-link-bridge.ts'
41
+ import { createBrowserSourceRule } from './user-text-rule.ts'
42
+ import { decodeBrowserRefUri } from '../scheme.ts'
43
+ import { createElement as element, useSyncExternalStore } from 'react'
44
+ import { createRoot } from 'react-dom/client'
45
+ import { ReferenceDock } from './ReferenceDock.tsx'
46
+ import { ReferenceCapsules } from './ReferenceCapsules.tsx'
47
+ import { ReferenceFeedback } from './ReferenceFeedback.tsx'
48
+ import { referenceCopy, referenceLabels, REFERENCE_LOCALE, type ReferenceLabels, type ReferenceLabelKey } from './reference-labels.ts'
49
+
50
+ /** Services this plugin needs from the host context (cordis `inject`). */
51
+ export const inject = [
52
+ 'slots', 'sessions', 'uiConversation', 'conversation', 'uiSession', 'locale',
53
+ ] as const
54
+
55
+ /** Opaque element factory: the host passes its React.createElement. */
56
+ export type HostElementFactory = (
57
+ tag: string,
58
+ props: Readonly<Record<string, unknown>>,
59
+ ...children: readonly unknown[]
60
+ ) => unknown
61
+
62
+ export interface AssemblyConfig {
63
+ /** Plugin loopback origin, e.g. `http://127.0.0.1:<port>`; '' = same origin. */
64
+ readonly baseUrl?: string
65
+ readonly storage?: KeyValueStorage
66
+ readonly request?: RequestLike
67
+ readonly fetchImpl?: Parameters<typeof createFetchRequest>[0]
68
+ readonly initialSessionId?: string
69
+ readonly hostInputFor?: (sessionId: string) => HostInputFace
70
+ readonly admitAsset?: (asset: AssetResponse, sessionId: string) => Promise<AdmitAssetResult | undefined>
71
+ readonly pollIntervalMs?: number
72
+ readonly scheduler?: PollerScheduler
73
+ readonly textPosition?: TextPosition
74
+ /** Host React.createElement, used for the dock card and reply link. */
75
+ readonly createElement?: HostElementFactory
76
+ /**
77
+ * Host `useSyncExternalStore`. When present the dock subscribes to the
78
+ * runtime and repaints on its own; without it (SSR / unit calls) the dock
79
+ * renders one static snapshot.
80
+ */
81
+ readonly useSnapshot?: SnapshotHook
82
+ /**
83
+ * Receives the dock's session-scope props on every render. The real
84
+ * `conversation.input.chips` registration is handed `inputActions` for its
85
+ * Session; this callback lets the plugin drive the host draft adapter from
86
+ * those actions instead of requiring a separate `browserReferenceDeps`
87
+ * service published by another package.
88
+ */
89
+ readonly onDockProps?: (props: unknown) => void
90
+ }
91
+
92
+ /**
93
+ * Host-specific adapters that CANNOT live in a YAML `config` block (functions).
94
+ * L01 publishes this bundle as a scope service before this plugin is applied,
95
+ * e.g. `ctx.set('browserReferenceDeps', deps)` from ui-conversation's assembly,
96
+ * or passes the same fields through `AssemblyConfig` in tests. Declaration of
97
+ * this service on the host is an L01 wiring action, NOT done in this repo.
98
+ */
99
+ export interface BrowserReferenceDeps {
100
+ readonly hostInputFor: (sessionId: string) => HostInputFace
101
+ readonly admitAsset?: (asset: AssetResponse, sessionId: string) => Promise<AdmitAssetResult | undefined>
102
+ readonly createElement?: HostElementFactory
103
+ readonly baseUrl?: string
104
+ }
105
+
106
+ /** Minimal structural face of the cordis Context this plugin touches. */
107
+ export interface HostContext {
108
+ get(name: string): unknown
109
+ /**
110
+ * Declare AND publish a service in one call. Cordis rejects a bare `set()`
111
+ * for a name that was never `provide()`d, so this is the primary path; the
112
+ * value stays optional because declaring a name without a value is legal.
113
+ */
114
+ provide?(name: string, value?: unknown): unknown
115
+ /** Fallback for a host that already provided the name. */
116
+ set?(name: string, value: unknown): void
117
+ effect(effect: () => void | (() => void), label: string): void
118
+ readonly slots: {
119
+ inject(name: string, producer: () => Iterable<unknown>): void
120
+ register(registration: unknown, component: unknown): unknown
121
+ }
122
+ }
123
+
124
+ function storageOrDefault(config: AssemblyConfig): KeyValueStorage {
125
+ if (config.storage !== undefined) return config.storage
126
+ if (typeof localStorage !== 'undefined') {
127
+ return {
128
+ getItem: (key) => { try { return localStorage.getItem(key) } catch { return null } },
129
+ // A failed write (quota / disabled storage) MUST surface: the asset store
130
+ // rolls its in-memory binding back and the draft's saveSucceeded becomes
131
+ // false, so the delivery is retried instead of ACKed over a gap.
132
+ setItem: (key, value) => { localStorage.setItem(key, value) },
133
+ removeItem: (key) => { try { localStorage.removeItem(key) } catch { /* storage unavailable */ } },
134
+ }
135
+ }
136
+ return createMemoryStorage()
137
+ }
138
+
139
+ function requestOrDefault(config: AssemblyConfig, cancellationSignal: () => AbortSignal | undefined): RequestLike {
140
+ if (config.request !== undefined) return config.request
141
+ if (config.fetchImpl !== undefined) return createFetchRequest(config.fetchImpl, cancellationSignal)
142
+ if (typeof fetch !== 'undefined') {
143
+ return createFetchRequest(
144
+ (input, init) => fetch(input, init as unknown as RequestInit),
145
+ cancellationSignal,
146
+ )
147
+ }
148
+ throw new Error('ui-browser-reference: no HTTP request implementation provided')
149
+ }
150
+
151
+ /**
152
+ * The registered dock component: it subscribes to the runtime through the
153
+ * host's `useSyncExternalStore`, so a delivery that lands while the user is
154
+ * idle repaints the rail by itself. `snapshot()` is a stable object identity, so
155
+ * an unchanged poll does not re-render — which keeps the note editor's focus and
156
+ * caret intact.
157
+ */
158
+ export function createLiveCardDockComponent(
159
+ runtime: ProductionRuntime,
160
+ _createElement: HostElementFactory,
161
+ ): (props?: unknown) => unknown {
162
+ return (props?: unknown) => {
163
+ // The repaint channel is the HOST's, not ours: the registration publishes
164
+ // `hooks.dockCards` and the slot runtime binds it into a `useDockCards`
165
+ // selector hook rendered by its own React. Calling React's hook here instead
166
+ // failed on the real desktop — the client bundle's `react` is a second module
167
+ // instance, so every hook threw "invalid hook call" and the dock never mounted.
168
+ const face = props as {
169
+ readonly useDockCards?: (selector: (value: DockSnapshot) => DockSnapshot) => DockSnapshot
170
+ readonly noteDockProps?: (props: unknown) => void
171
+ readonly t?: (key: ReferenceLabelKey, args?: { count: number }) => string
172
+ } | undefined
173
+ face?.noteDockProps?.(props)
174
+ const view = face?.useDockCards === undefined ? runtime.snapshot() : face.useDockCards(value => value)
175
+ // 这里曾经在 render 里写 `document.documentElement.dataset.dshChips`,为的是让上游发送闸门能读到
176
+ // 胶囊数量(那需要改上游,已弃)。这条写入现在没有任何读方,却在**每次渲染**时改 `<html>` 的属性:
177
+ // 每次写入都让整篇文档的样式失效 → 布局重算 → 所有 ResizeObserver(上游输入区自适应、主视觉 canvas)
178
+ // 收到通知。它们的回调若再改一次尺寸,浏览器就报
179
+ // `ResizeObserver loop completed with undelivered notifications.`,dev 下直接红屏。
180
+ // 读数走 dock 自己的 snapshot,不再经文档属性传递。
181
+ return element(ReferenceDock, {
182
+ key: view.sessionId,
183
+ sessionId: view.sessionId,
184
+ cards: view.cards,
185
+ labels: referenceLabels(face?.t, view.cards.length),
186
+ actions: {
187
+ onEditComment: (referenceId, comment) => { runtime.setComment(referenceId, comment) },
188
+ onReveal: (referenceId) => { void runtime.revealReference(referenceId) },
189
+ // The dock chip keeps its remove affordance. Dropping this in the submission-seam rework left
190
+ // the chip unremovable even though the capsules still render the button when it exists.
191
+ onRemove: (referenceId) => { void runtime.removeCard(referenceId) },
192
+ },
193
+ ...(view.issue === undefined ? {} : { notice: view.issue }),
194
+ })
195
+ }
196
+ }
197
+
198
+ /** The subset of React's `useSyncExternalStore` this package needs. */
199
+ export type SnapshotHook = <T>(subscribe: (listener: () => void) => () => void, getSnapshot: () => T) => T
200
+
201
+ /**
202
+ * Build the reply-side link component over the injected element factory.
203
+ *
204
+ * `conversation.user.text.node` is a KEYED slot: the host hands a component
205
+ * `{ node, raw, interactive }`, never a bare `uri`. The installed desktop has
206
+ * no `browser-ref` node rule, so this registration is defensive — it must never
207
+ * render a disabled button over `undefined`. A props shape without a canonical
208
+ * browser-ref URI yields `null`, which keeps the host's raw-text fallback.
209
+ * Live reply-side links are handled by {@link installReplyLinkBridge}.
210
+ */
211
+ export function createReplyLinkComponent(
212
+ runtime: ProductionRuntime,
213
+ createElement: HostElementFactory,
214
+ ): (props: unknown) => unknown {
215
+ return (props: unknown) => {
216
+ const typed = props as {
217
+ readonly uri?: unknown
218
+ readonly children?: string
219
+ readonly raw?: unknown
220
+ readonly node?: { readonly data?: { readonly uri?: unknown; readonly href?: unknown; readonly label?: string } }
221
+ readonly useSourceReferences?: (selector: (value: DockSnapshot) => DockSnapshot) => DockSnapshot
222
+ } | undefined
223
+ typed?.useSourceReferences?.(value => value)
224
+ // A bare `uri` is the documented programmatic shape (and what the existing
225
+ // contract asserts). A keyed-slot owner has neither `uri` nor node data, so
226
+ // it must fall back to the host's raw-text renderer instead of a disabled
227
+ // button over `undefined`.
228
+ const candidate = typed?.uri ?? typed?.node?.data?.uri ?? typed?.node?.data?.href
229
+ if (typeof candidate !== 'string') return null
230
+ // A plain https (or any non-canonical) URL must keep the host's raw-text
231
+ // fallback; without this gate it was rendered as a disabled "来源不可用"
232
+ // dead button. createBrowserRefRenderer applies the same scheme check.
233
+ if (!candidate.startsWith(BROWSER_REF_SCHEME)) return null
234
+ return renderSentCapsule(runtime, createElement, candidate, typed?.children ?? typed?.node?.data?.label)
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Global key shared with `ui-primitives/src/markdown/render.tsx`'s
240
+ * `registerBrowserRefRenderer`. The client plugin and the low-level markdown
241
+ * library never import each other; they meet only through this optional hook.
242
+ * When the renderer is absent the markdown renderer keeps its original
243
+ * `sanitizeUrl`/anchor behavior (backwards compatible).
244
+ */
245
+ export const BROWSER_REF_RENDERER_GLOBAL = '__DSH_BROWSER_REF_RENDERER__'
246
+ /** Live-DOM diagnostic handle for the deployment-compatible link bridge. */
247
+ export const REPLY_LINK_BRIDGE_GLOBAL = '__DSH_BROWSER_REF_LINK_BRIDGE__'
248
+ export const BROWSER_REF_SCHEME = 'dsh-browser-ref:'
249
+
250
+ function SentReferenceCapsules(props: { readonly runtime: ProductionRuntime; readonly capsule: Parameters<typeof ReferenceCapsules>[0] }): ReturnType<typeof ReferenceCapsules> {
251
+ const view = useSyncExternalStore(props.runtime.subscribe, props.runtime.snapshot, props.runtime.snapshot)
252
+ const notice = view.reveal?.referenceId === props.capsule.cards[0]?.referenceId ? view.reveal?.message : undefined
253
+ return element(ReferenceCapsules, { ...props.capsule, ...(notice === undefined ? {} : { notice }) })
254
+ }
255
+
256
+ function renderSentCapsule(runtime: ProductionRuntime, createElement: HostElementFactory, uri: string, label?: string, key?: unknown, anchor?: HTMLElement): unknown {
257
+ let referenceId: string | undefined
258
+ try { referenceId = decodeBrowserRefUri(uri).referenceId } catch { /* invalid URI */ }
259
+ const detail = referenceId === undefined ? undefined : runtime.referenceDetail(referenceId)
260
+ const owner = referenceId === undefined ? undefined : runtime.ownerFor(referenceId)
261
+ if (detail !== undefined && owner?.sessionId === runtime.currentSessionId()) {
262
+ const index = Number(/引用来源\s*(\d+)/u.exec(label ?? '')?.[1]) || detail.card.index
263
+ return element(SentReferenceCapsules, {
264
+ key: String(key ?? uri),
265
+ runtime,
266
+ capsule: {
267
+ sessionId: runtime.currentSessionId(),
268
+ cards: [{ ...detail.card, index }],
269
+ labels: referenceLabels(),
270
+ actions: { onReveal: () => { void runtime.activateUri(uri) } },
271
+ ...(anchor === undefined ? {} : { anchor }),
272
+ },
273
+ })
274
+ }
275
+ if (anchor !== undefined) return null
276
+ const dom = buildBrowserRefLinkProps(runtime.revealer.linkSpec(uri, label))
277
+ return createElement('button', { ...dom, key }, dom.children)
278
+ }
279
+
280
+ /**
281
+ * Build the reply-side `dsh-browser-ref:` link renderer. It is installed on
282
+ * `globalThis` by `apply` so the host markdown renderer can divert only that
283
+ * scheme to a dedicated button (never a system `href`), reusing the additive
284
+ * `BrowserRefLink` contract through `buildBrowserRefLinkProps`.
285
+ */
286
+ export function createBrowserRefRenderer(
287
+ runtime: ProductionRuntime,
288
+ createElement: HostElementFactory,
289
+ ): (url: string, children: readonly unknown[], key: unknown) => unknown {
290
+ return (url, children, key) => {
291
+ if (!url.startsWith(BROWSER_REF_SCHEME)) return undefined
292
+ const first = children[0]
293
+ return renderSentCapsule(runtime, createElement, url, typeof first === 'string' ? first : undefined, key)
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Load the production feature into the host. Returns the runtime so the caller
299
+ * (and unit tests) can drive/inspect it; also exposes the submission seam.
300
+ */
301
+ export function apply(ctx: HostContext, config: AssemblyConfig = {}): ProductionRuntime {
302
+ ensureDockStyles()
303
+ const locale = ctx.get('locale') as { register(namespace: string, copy: Readonly<Record<string, ReferenceLabels>>): void | (() => void) } | undefined
304
+ if (typeof locale?.register === 'function') ctx.effect(() => locale.register(REFERENCE_LOCALE, referenceCopy), 'ui-browser-reference: copy')
305
+ // Functions cannot come from the YAML config block, so L01 publishes them as
306
+ // a scope service; explicit config (tests / programmatic wiring) wins.
307
+ const deps = ctx.get('browserReferenceDeps') as BrowserReferenceDeps | undefined
308
+ const hostInputFor = config.hostInputFor ?? deps?.hostInputFor
309
+ const admitAsset = config.admitAsset ?? deps?.admitAsset
310
+ const elementFactory: HostElementFactory = config.createElement ?? deps?.createElement
311
+ ?? ((tag, props, ...children) => ({ tag, props, children }))
312
+ const baseUrl = config.baseUrl ?? deps?.baseUrl
313
+ const cancellation = createCancellationSource()
314
+ const http = createReferenceHttpClient({
315
+ ...(baseUrl === undefined ? {} : { baseUrl }),
316
+ request: requestOrDefault(config, () => cancellation.signal()),
317
+ })
318
+ const runtime = createProductionRuntime({
319
+ http,
320
+ storage: storageOrDefault(config),
321
+ initialSessionId: config.initialSessionId ?? '',
322
+ cancellation,
323
+ hostInputFor: hostInputFor ?? (() => ({
324
+ captureInsertion: () => ({ start: 0, end: 0, draftRev: 0 }),
325
+ insertText: () => true,
326
+ persistDraft: () => {},
327
+ readText: () => '',
328
+ })),
329
+ ...(admitAsset === undefined ? {} : { admitAsset }),
330
+ ...(config.pollIntervalMs === undefined ? {} : { pollIntervalMs: config.pollIntervalMs }),
331
+ ...(config.scheduler === undefined ? {} : { scheduler: config.scheduler }),
332
+ ...(config.textPosition === undefined ? {} : { textPosition: config.textPosition }),
333
+ })
334
+
335
+ const cardComponent = createLiveCardDockComponent(runtime, elementFactory)
336
+ const replyComponent = createReplyLinkComponent(runtime, elementFactory)
337
+
338
+ // Divert only `dsh-browser-ref:` markdown destinations to the dedicated
339
+ // button; the global hook is optional so old messages / builds without this
340
+ // plugin keep their exact previous rendering.
341
+ const globalHost = globalThis as unknown as Record<string, unknown>
342
+ const browserRefRenderer = createBrowserRefRenderer(runtime, elementFactory)
343
+ globalHost[BROWSER_REF_RENDERER_GLOBAL] = browserRefRenderer
344
+ ctx.effect(() => () => {
345
+ if (globalHost[BROWSER_REF_RENDERER_GLOBAL] === browserRefRenderer) {
346
+ delete globalHost.__DSH_BROWSER_REF_RENDERER__
347
+ }
348
+ }, 'ui-browser-reference: markdown link renderer')
349
+
350
+ // The deployed markdown renderer predates the optional hook above. A
351
+ // document-level bridge is what makes `dsh-browser-ref:` links clickable in
352
+ // the installed desktop without downgrading its frontend bundle.
353
+ const replyLinkBridge = installReplyLinkBridge({
354
+ isAvailable: uri => runtime.revealer.linkSpec(uri).available,
355
+ activate: (uri) => { void runtime.activateUri(uri) },
356
+ mountCard: (uri, anchor) => {
357
+ const card = renderSentCapsule(runtime, elementFactory, uri, anchor.textContent ?? undefined, undefined, anchor)
358
+ if (card === null) return undefined
359
+ const container = anchor.ownerDocument.createElement('span')
360
+ anchor.ownerDocument.body.append(container)
361
+ const root = createRoot(container)
362
+ root.render(card as Parameters<typeof root.render>[0])
363
+ return () => { root.unmount(); container.remove() }
364
+ },
365
+ })
366
+ globalHost[REPLY_LINK_BRIDGE_GLOBAL] = replyLinkBridge
367
+ ctx.effect(() => () => {
368
+ if (globalHost[REPLY_LINK_BRIDGE_GLOBAL] === replyLinkBridge) {
369
+ delete globalHost.__DSH_BROWSER_REF_LINK_BRIDGE__
370
+ }
371
+ replyLinkBridge.dispose()
372
+ }, 'ui-browser-reference: reply link bridge')
373
+
374
+ /**
375
+ * Prefer the Session standard kit over stale owner snapshots.
376
+ */
377
+ const dockComponent = (props: unknown): unknown => {
378
+ const face = props as {
379
+ readonly sessionId?: string
380
+ readonly session?: { readonly sessionId?: string }
381
+ readonly input?: { readonly draft?: string }
382
+ readonly useInput?: (
383
+ selector: (state: { readonly draft?: string }) => { readonly draft?: string },
384
+ ) => { readonly draft?: string }
385
+ } | undefined
386
+ const input = face?.useInput === undefined ? undefined : face.useInput(value => value)
387
+ // Delegated by call rather than through an element so the seat renders the
388
+ // dock itself: one React boundary, same hook order on every render.
389
+ const dockProps = {
390
+ ...(props as Readonly<Record<string, unknown>>),
391
+ session: { sessionId: face?.sessionId ?? face?.session?.sessionId ?? '' },
392
+ input: { draft: input?.draft ?? face?.input?.draft ?? '' },
393
+ }
394
+ config.onDockProps?.(dockProps)
395
+ return cardComponent(dockProps)
396
+ }
397
+ ctx.slots.inject('conversation.input.dock', function* () {
398
+ yield ctx.slots.register({
399
+ name: 'conversation.input.dock', id: 'dsh-browser-reference', priority: 50,
400
+ // The dictionary rides the same namespace `apply` registers with the host
401
+ // locale service, so the rail's copy follows the active language.
402
+ locale: REFERENCE_LOCALE,
403
+ // `hooks.dockCards` becomes the host-bound selector hook.
404
+ inject: () => ({
405
+ hooks: { dockCards: { getSnapshot: () => runtime.snapshot(), subscribe: (listener: () => void) => runtime.subscribe(listener) } },
406
+ }),
407
+ }, dockComponent)
408
+ })
409
+ ctx.slots.inject('conversation.user.text.node', function* () {
410
+ yield ctx.slots.register({
411
+ name: 'conversation.user.text.node', key: 'browser-ref', priority: 100,
412
+ inject: () => ({ hooks: { sourceReferences: {
413
+ getSnapshot: () => runtime.snapshot(), subscribe: (listener: () => void) => runtime.subscribe(listener),
414
+ } } }),
415
+ }, replyComponent)
416
+ })
417
+ ctx.slots.inject('shell.overlay', function* () {
418
+ yield ctx.slots.register({
419
+ name: 'shell.overlay', id: 'dsh-browser-reference-feedback',
420
+ inject: () => ({ hooks: { referenceFeedback: {
421
+ getSnapshot: () => runtime.snapshot(), subscribe: (listener: () => void) => runtime.subscribe(listener),
422
+ } } }),
423
+ }, (props: { readonly useReferenceFeedback?: (selector: (value: DockSnapshot) => DockSnapshot) => DockSnapshot }) => {
424
+ const view = props.useReferenceFeedback?.(value => value) ?? runtime.snapshot()
425
+ return element(ReferenceFeedback, view.reveal === undefined ? {} : { notice: view.reveal })
426
+ })
427
+ })
428
+
429
+ // 投递泵必须在**任何可选集成之前**启动。旧顺序把它放在最后,于是后面任何一步(可选的
430
+ // `uiConversation.userText` 注册等)抛错时,dock 已经渲染、会话也绑好了,唯独轮询没起来:
431
+ // 现象就是「引用卡片永远不出现、发送一直禁用」,而外层 try/catch 把它吞成静默失败。
432
+ runtime.start()
433
+ ctx.effect(() => () => { runtime.dispose() }, 'ui-browser-reference: production runtime')
434
+
435
+ const sourceRule = createBrowserSourceRule(referenceId => runtime.referenceDetail(referenceId) !== undefined)
436
+ const textOwner = ctx.get('uiConversation') as {
437
+ readonly userText?: { register(rule: typeof sourceRule): () => void }
438
+ } | undefined
439
+ if (textOwner?.userText !== undefined) {
440
+ try {
441
+ ctx.effect(() => textOwner.userText?.register(sourceRule), 'ui-browser-reference: source text rule')
442
+ } catch {
443
+ // 文本来源高亮是可选的展示增强:注册失败不能拖垮引用投递。
444
+ }
445
+ }
446
+ return runtime
447
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Session-scoped durable asset bindings.
3
+ *
4
+ * An image part is a content hash (`assetKey`), NOT a URL and NOT alt text.
5
+ * Before a delivery may be ACKed, every required key must have real bytes from
6
+ * `GET /reference/asset?encoding=base64` AND a durable host attachment
7
+ * admission (`receiptId` from the host's createDrafts/serializeAttachments).
8
+ * Both facts are persisted per session so a restart restores the exact bytes
9
+ * and the receipt, and the card can render a real thumbnail without the page.
10
+ *
11
+ * All persistence goes through an injected `KeyValueStorage`; no globals.
12
+ *
13
+ * @module dsh-browser-reference/production/asset-store
14
+ */
15
+ import type { KeyValueStorage } from '../types.ts'
16
+ import { decodeBase64 } from './bytes.ts'
17
+ import type { AssetResponse } from './protocol.ts'
18
+
19
+ export const ASSET_STORE_PREFIX = 'dsh.browser-reference.assets.'
20
+
21
+ export function assetStoreKey(sessionId: string): string {
22
+ return `${ASSET_STORE_PREFIX}${sessionId}`
23
+ }
24
+
25
+ /** One durably bound image asset. `data` is base64 of the real bytes. */
26
+ export interface AssetBinding {
27
+ readonly key: string
28
+ readonly mime: string
29
+ readonly bytes: number
30
+ readonly sha256: string
31
+ readonly data: string
32
+ /** Opaque receipt from the host attachment admission service, when uploaded. */
33
+ readonly receiptId?: string
34
+ }
35
+
36
+ export interface AssetStore {
37
+ /** Bind one asset fetched from the plugin, optionally with a host receipt. */
38
+ bind(asset: AssetResponse, receiptId?: string): AssetBinding
39
+ get(key: string): AssetBinding | undefined
40
+ /** Real bytes decoded from `data`, or undefined when unbound. */
41
+ bytesOf(key: string): Uint8Array | undefined
42
+ hasAll(keys: readonly string[]): boolean
43
+ missing(keys: readonly string[]): readonly string[]
44
+ keys(): readonly string[]
45
+ values(): readonly AssetBinding[]
46
+ restore(): void
47
+ dispose(): void
48
+ }
49
+
50
+ const FORMAT_VERSION = 1
51
+
52
+ interface SerializedAssets {
53
+ readonly version: typeof FORMAT_VERSION
54
+ readonly bindings: readonly AssetBinding[]
55
+ }
56
+
57
+ function isRecord(value: unknown): value is Record<string, unknown> {
58
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
59
+ }
60
+
61
+ function isBinding(value: unknown): value is AssetBinding {
62
+ if (!isRecord(value)) return false
63
+ return typeof value.key === 'string' && /^[0-9a-f]{64}$/u.test(value.key)
64
+ && typeof value.mime === 'string'
65
+ && typeof value.bytes === 'number' && Number.isInteger(value.bytes) && value.bytes >= 0
66
+ && typeof value.sha256 === 'string'
67
+ && typeof value.data === 'string'
68
+ && (value.receiptId === undefined || typeof value.receiptId === 'string')
69
+ }
70
+
71
+ function parse(raw: string): Map<string, AssetBinding> | undefined {
72
+ try {
73
+ const parsed: unknown = JSON.parse(raw)
74
+ if (!isRecord(parsed) || parsed.version !== FORMAT_VERSION || !Array.isArray(parsed.bindings)) return undefined
75
+ const map = new Map<string, AssetBinding>()
76
+ for (const entry of parsed.bindings as readonly unknown[]) {
77
+ if (!isBinding(entry)) return undefined
78
+ map.set(entry.key, entry)
79
+ }
80
+ return map
81
+ } catch {
82
+ return undefined
83
+ }
84
+ }
85
+
86
+ /** Build the store for ONE DSH session; construction restores its persisted state. */
87
+ export function createAssetStore(storage: KeyValueStorage, sessionId: string): AssetStore {
88
+ const key = assetStoreKey(sessionId)
89
+ let bindings = new Map<string, AssetBinding>()
90
+ let disposed = false
91
+
92
+ const persist = (): void => {
93
+ const snapshot: SerializedAssets = { version: FORMAT_VERSION, bindings: [...bindings.values()] }
94
+ storage.setItem(key, JSON.stringify(snapshot))
95
+ }
96
+
97
+ const load = (): void => {
98
+ const raw = storage.getItem(key)
99
+ bindings = raw === null ? new Map() : parse(raw) ?? new Map()
100
+ }
101
+
102
+ load()
103
+
104
+ return {
105
+ bind(asset, receiptId) {
106
+ if (disposed) throw new Error('asset store is disposed')
107
+ if (asset.sha256 !== asset.key) {
108
+ throw new Error(`asset sha256 ${asset.sha256} does not match key ${asset.key}`)
109
+ }
110
+ const binding: AssetBinding = {
111
+ key: asset.key,
112
+ mime: asset.mime,
113
+ bytes: asset.bytes,
114
+ sha256: asset.sha256,
115
+ data: asset.data,
116
+ ...(receiptId === undefined ? {} : { receiptId }),
117
+ }
118
+ const previous = bindings.get(asset.key)
119
+ bindings.set(asset.key, binding)
120
+ try {
121
+ persist()
122
+ } catch (error: unknown) {
123
+ // Never leave an in-memory "bound" asset when the durable write failed:
124
+ // missing() would report it as present and the delivery would be ACKed
125
+ // over an image that turns into a placeholder after a restart.
126
+ if (previous === undefined) bindings.delete(asset.key)
127
+ else bindings.set(asset.key, previous)
128
+ throw error
129
+ }
130
+ return binding
131
+ },
132
+ get(assetKey) { return bindings.get(assetKey) },
133
+ bytesOf(assetKey) {
134
+ const binding = bindings.get(assetKey)
135
+ return binding === undefined ? undefined : decodeBase64(binding.data)
136
+ },
137
+ hasAll(keys) { return keys.every(assetKey => bindings.has(assetKey)) },
138
+ missing(keys) { return keys.filter(assetKey => !bindings.has(assetKey)) },
139
+ keys() { return [...bindings.keys()] },
140
+ values() { return [...bindings.values()] },
141
+ restore() { load() },
142
+ dispose() { disposed = true; bindings.clear() },
143
+ }
144
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Explicit availability states for the browser-reference delivery pipeline.
3
+ *
4
+ * The client talks to the plugin's `/dsh-builtin-browser/reference/*` routes on
5
+ * the SAME ORIGIN (relative paths, never a hardcoded port). A 404 means the
6
+ * installed plugin copy does not ship the delivery endpoints; a malformed body
7
+ * or 5xx means delivery is temporarily unavailable; a network/abort failure
8
+ * means the plugin host cannot be reached. None of these are a silent success:
9
+ * each maps to a human-readable state the dock renders instead of an empty
10
+ * (falsely "clean") card list.
11
+ *
12
+ * @module dsh-browser-reference/production/availability
13
+ */
14
+ import { ReferenceHttpError, type DeliveriesResponse } from './protocol.ts'
15
+
16
+ export type DeliveryAvailability = 'ok' | 'plugin-too-old' | 'delivery-unavailable' | 'offline'
17
+
18
+ export interface AvailabilityState {
19
+ readonly status: DeliveryAvailability
20
+ /** One human sentence; '' when everything is fine. */
21
+ readonly message: string
22
+ }
23
+
24
+ /** Human-readable copy for each non-ok state (Chinese, matches the host UI). */
25
+ export const AVAILABILITY_MESSAGES: Readonly<Record<DeliveryAvailability, string>> = {
26
+ ok: '',
27
+ 'plugin-too-old': '浏览器插件需要更新到包含引用交付的版本(未找到引用交付端点)。',
28
+ 'delivery-unavailable': '引用交付暂不可用(返回数据不符合预期),稍后会自动重试。',
29
+ offline: '无法连接浏览器插件,请确认 DSH 内置浏览器已启动。',
30
+ }
31
+
32
+ export const OK: AvailabilityState = { status: 'ok', message: '' }
33
+
34
+ /** Classify the last poll error into an explicit, user-facing state. */
35
+ export function availabilityOf(error: unknown): AvailabilityState {
36
+ if (error === undefined || error === null) return OK
37
+ if (error instanceof ReferenceHttpError) {
38
+ if (error.status === 404) return { status: 'plugin-too-old', message: AVAILABILITY_MESSAGES['plugin-too-old'] }
39
+ // status 0 is reserved for a successfully-fetched but malformed payload.
40
+ return { status: 'delivery-unavailable', message: AVAILABILITY_MESSAGES['delivery-unavailable'] }
41
+ }
42
+ if (error instanceof Error && error.name === 'AbortError') {
43
+ // A cancelled poll (dispose / session switch) is not a user-visible outage.
44
+ return OK
45
+ }
46
+ return { status: 'offline', message: AVAILABILITY_MESSAGES.offline }
47
+ }
48
+
49
+ /**
50
+ * Strict shape check for `GET /reference/deliveries`. A plugin that answers
51
+ * 200 with an unexpected body is a real failure, not an empty delivery list.
52
+ */
53
+ export function isDeliveriesResponse(value: unknown): value is DeliveriesResponse {
54
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
55
+ const record = value as Record<string, unknown>
56
+ if (record.ok !== true || typeof record.sequence !== 'number' || !Number.isFinite(record.sequence)) return false
57
+ if (!Array.isArray(record.deliveries)) return false
58
+ for (const entry of record.deliveries as readonly unknown[]) {
59
+ if (typeof entry !== 'object' || entry === null) return false
60
+ const delivery = entry as Record<string, unknown>
61
+ if (typeof delivery.intentId !== 'string' || typeof delivery.sessionId !== 'string'
62
+ || typeof delivery.state !== 'string' || delivery.state !== 'prepared'
63
+ && delivery.state !== 'draft-applied' && delivery.state !== 'acknowledged' && delivery.state !== 'consumed') return false
64
+ if (typeof delivery.snapshot !== 'object' || delivery.snapshot === null) return false
65
+ const snapshot = delivery.snapshot as Record<string, unknown>
66
+ if (typeof snapshot.referenceId !== 'string' || !Array.isArray(snapshot.parts)) return false
67
+ if (!Array.isArray(delivery.failures) || !Array.isArray(delivery.assetKeys)
68
+ || !Array.isArray(delivery.requiredAssets)) return false
69
+ if (typeof delivery.sequence !== 'number' || !Number.isFinite(delivery.sequence)) return false
70
+ }
71
+ return true
72
+ }