dsh-builtin-browser 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/README.en.md +89 -0
  2. package/browser-extension/constants.mjs +20 -0
  3. package/browser-extension/controller.mjs +293 -0
  4. package/browser-extension/locales.mjs +15 -0
  5. package/browser-extension/manifest.json +12 -0
  6. package/browser-extension/options.html +14 -0
  7. package/browser-extension/options.mjs +9 -0
  8. package/browser-extension/permission-guard.mjs +13 -0
  9. package/browser-extension/worker.mjs +74 -0
  10. package/package.json +20 -2
  11. package/scripts/build-client.mjs +305 -0
  12. package/scripts/build.mjs +69 -0
  13. package/scripts/bundle-host.mjs +28 -0
  14. package/scripts/fix-exports.mjs +40 -0
  15. package/scripts/install-electron.mjs +101 -0
  16. package/scripts/pack.mjs +99 -0
  17. package/scripts/publish-manifest.mjs +56 -0
  18. package/scripts/verify-exports.mjs +58 -0
  19. package/scripts/verify-preview-sdk.mjs +93 -0
  20. package/skills/dsh-builtin-browser/SKILL.md +98 -0
  21. package/skills/dsh-builtin-browser/references/batch.md +68 -0
  22. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  23. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  24. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  25. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  26. package/skills/dsh-debug-host/SKILL.md +56 -0
  27. package/skills/dsh-debug-self/SKILL.md +50 -0
  28. package/src/bridge-compatibility.ts +39 -0
  29. package/src/browser/anti-bot.ts +251 -0
  30. package/src/browser/deep-dom.ts +40 -0
  31. package/src/browser/handles.ts +89 -0
  32. package/src/browser/runtime.ts +578 -0
  33. package/src/browser/takeover-target.ts +45 -0
  34. package/src/browser/types.ts +870 -0
  35. package/src/browser-electron/authenticated-route.ts +109 -0
  36. package/src/browser-electron/automatic-maintenance.ts +736 -0
  37. package/src/browser-electron/bridge-auto.ts +159 -0
  38. package/src/browser-electron/bridge-connection.ts +386 -0
  39. package/src/browser-electron/bridge-endpoint.ts +129 -0
  40. package/src/browser-electron/bridge-install.ts +290 -0
  41. package/src/browser-electron/bridge-maintenance.ts +189 -0
  42. package/src/browser-electron/bridge-status.ts +386 -0
  43. package/src/browser-electron/desktop-bridge-host.ts +253 -0
  44. package/src/browser-electron/desktop-identity.ts +353 -0
  45. package/src/browser-electron/desktop-shell.ts +100 -0
  46. package/src/browser-electron/document-readiness.ts +45 -0
  47. package/src/browser-electron/electron-provision.ts +347 -0
  48. package/src/browser-electron/entry.ts +1378 -0
  49. package/src/browser-electron/ephemeral-profile.ts +189 -0
  50. package/src/browser-electron/extension-browser.ts +230 -0
  51. package/src/browser-electron/extension-setup.ts +67 -0
  52. package/src/browser-electron/file-write.ts +31 -0
  53. package/src/browser-electron/foreground-watch.ts +142 -0
  54. package/src/browser-electron/guest-cookie-jar.ts +177 -0
  55. package/src/browser-electron/guest-cookie-store.ts +59 -0
  56. package/src/browser-electron/guest-css-runtime.ts +76 -0
  57. package/src/browser-electron/guest-css.ts +68 -0
  58. package/src/browser-electron/guest-route.ts +716 -0
  59. package/src/browser-electron/guest-runtime.ts +408 -0
  60. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  61. package/src/browser-electron/guest-storage.ts +120 -0
  62. package/src/browser-electron/history-store.ts +224 -0
  63. package/src/browser-electron/host-main.ts +1385 -0
  64. package/src/browser-electron/host-patch-maintenance.ts +121 -0
  65. package/src/browser-electron/http-body.ts +65 -0
  66. package/src/browser-electron/json-reply.ts +47 -0
  67. package/src/browser-electron/maintenance-broker.ts +166 -0
  68. package/src/browser-electron/maintenance-lifecycle.ts +91 -0
  69. package/src/browser-electron/maintenance-route.ts +68 -0
  70. package/src/browser-electron/missing-system-browser.ts +114 -0
  71. package/src/browser-electron/open-slot.ts +49 -0
  72. package/src/browser-electron/paths.ts +25 -0
  73. package/src/browser-electron/preferred-browser.ts +130 -0
  74. package/src/browser-electron/preview-route.ts +215 -0
  75. package/src/browser-electron/process-ownership.ts +174 -0
  76. package/src/browser-electron/process.ts +23 -0
  77. package/src/browser-electron/profile-checkpoint.ts +187 -0
  78. package/src/browser-electron/profile-command.ts +47 -0
  79. package/src/browser-electron/profile-extension.ts +129 -0
  80. package/src/browser-electron/profile-lease.ts +211 -0
  81. package/src/browser-electron/profile-residue.ts +49 -0
  82. package/src/browser-electron/provider-core.ts +1107 -0
  83. package/src/browser-electron/provider-interaction.ts +1034 -0
  84. package/src/browser-electron/provider-media.ts +589 -0
  85. package/src/browser-electron/provider-navigation.ts +323 -0
  86. package/src/browser-electron/provider-observation.ts +664 -0
  87. package/src/browser-electron/provider-tabs.ts +372 -0
  88. package/src/browser-electron/provider.ts +666 -0
  89. package/src/browser-electron/reference-route.ts +598 -0
  90. package/src/browser-electron/remote-host.ts +1538 -0
  91. package/src/browser-electron/rpc-input.ts +13 -0
  92. package/src/browser-electron/rpc-ops.ts +41 -0
  93. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  94. package/src/browser-electron/runtime-route.ts +105 -0
  95. package/src/browser-electron/runtime-status.ts +309 -0
  96. package/src/browser-electron/settings-route.ts +64 -0
  97. package/src/browser-electron/settings-store.ts +593 -0
  98. package/src/browser-electron/shortcuts-route.ts +112 -0
  99. package/src/browser-electron/sidebar-only-host.ts +300 -0
  100. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  101. package/src/browser-electron/system-browser.ts +1850 -0
  102. package/src/browser-electron/tauri-host.ts +194 -0
  103. package/src/browser-electron/timing.ts +16 -0
  104. package/src/browser-electron/virtual-cursor.ts +162 -0
  105. package/src/browser-electron/windows-system.ts +24 -0
  106. package/src/browser-reference/delivery.ts +384 -0
  107. package/src/browser-reference/entry.ts +631 -0
  108. package/src/browser-reference/export.ts +339 -0
  109. package/src/browser-reference/import.ts +303 -0
  110. package/src/browser-reference/page-script.ts +1537 -0
  111. package/src/browser-reference/service.ts +1346 -0
  112. package/src/browser-reference/store.ts +172 -0
  113. package/src/browser-reference/text-quote.ts +219 -0
  114. package/src/browser-reference/types.ts +195 -0
  115. package/src/browser-reference/visible.ts +367 -0
  116. package/src/browser-reference/web-sources.ts +106 -0
  117. package/src/client/apply-guard.ts +22 -0
  118. package/src/client/browser/BrowserController.ts +693 -0
  119. package/src/client/browser/BrowserFrame.ts +78 -0
  120. package/src/client/browser/BrowserNavigation.ts +169 -0
  121. package/src/client/browser/BrowserPage.ts +23 -0
  122. package/src/client/browser/BrowserPersistence.ts +44 -0
  123. package/src/client/browser/IframeImpl.ts +182 -0
  124. package/src/client/browser/child-tabs.ts +14 -0
  125. package/src/client/browser/frame-history.ts +125 -0
  126. package/src/client/browser/frame-state.ts +27 -0
  127. package/src/client/browser/iframe-reference.ts +67 -0
  128. package/src/client/browser/initialization.ts +262 -0
  129. package/src/client/browser/omnibox.ts +243 -0
  130. package/src/client/browser/store.ts +38 -0
  131. package/src/client/browser/takeover-channel.ts +72 -0
  132. package/src/client/browser/url.ts +46 -0
  133. package/src/client/browser/web-reference-source.ts +56 -0
  134. package/src/client/css-modules.d.ts +4 -0
  135. package/src/client/definition.tsx +36 -0
  136. package/src/client/electron/ElectronWebViewImpl.ts +371 -0
  137. package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
  138. package/src/client/electron/NativeChildPresentation.ts +53 -0
  139. package/src/client/electron/NativeViewPage.ts +265 -0
  140. package/src/client/electron/pages.ts +23 -0
  141. package/src/client/electron/reference-overlay.ts +53 -0
  142. package/src/client/electron/workspace.ts +33 -0
  143. package/src/client/index.ts +333 -0
  144. package/src/client/locales.ts +860 -0
  145. package/src/client/pages.ts +28 -0
  146. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  147. package/src/client/reference/client/draft-reference.ts +167 -0
  148. package/src/client/reference/client/index.ts +7 -0
  149. package/src/client/reference/client/ordered-submission.ts +108 -0
  150. package/src/client/reference/client/pending-delivery.ts +216 -0
  151. package/src/client/reference/client/plugin.ts +208 -0
  152. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  153. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  154. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  155. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  156. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  157. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  158. package/src/client/reference/client/production/assembly.ts +447 -0
  159. package/src/client/reference/client/production/asset-store.ts +144 -0
  160. package/src/client/reference/client/production/availability.ts +72 -0
  161. package/src/client/reference/client/production/bytes.ts +36 -0
  162. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  163. package/src/client/reference/client/production/delivery-client.ts +211 -0
  164. package/src/client/reference/client/production/draft-adapter.ts +512 -0
  165. package/src/client/reference/client/production/http-transport.ts +212 -0
  166. package/src/client/reference/client/production/production-submission.ts +70 -0
  167. package/src/client/reference/client/production/protocol.ts +234 -0
  168. package/src/client/reference/client/production/reference-card.ts +240 -0
  169. package/src/client/reference/client/production/reference-labels.ts +29 -0
  170. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  171. package/src/client/reference/client/production/reveal.ts +215 -0
  172. package/src/client/reference/client/production/runtime.ts +1056 -0
  173. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  174. package/src/client/reference/client/production/source-marker.ts +99 -0
  175. package/src/client/reference/client/production/source-opener.ts +55 -0
  176. package/src/client/reference/client/production/styles.ts +104 -0
  177. package/src/client/reference/client/production/user-text-rule.ts +67 -0
  178. package/src/client/reference/client/reveal.ts +109 -0
  179. package/src/client/reference/client/scheme.ts +114 -0
  180. package/src/client/reference/client/session-schedule.ts +36 -0
  181. package/src/client/reference/client/types.ts +168 -0
  182. package/src/client/reference/css-modules.d.ts +4 -0
  183. package/src/client/reference/index.ts +11 -0
  184. package/src/client/reference-capture-owner.ts +162 -0
  185. package/src/client/reference-intents.ts +36 -0
  186. package/src/client/settings/index.ts +42 -0
  187. package/src/client/settings/mount-guard.ts +31 -0
  188. package/src/client/settings/panel.ts +2768 -0
  189. package/src/client/shortcut-open.ts +30 -0
  190. package/src/client/startpage/binding.ts +99 -0
  191. package/src/client/startpage/controller.ts +300 -0
  192. package/src/client/startpage/model.ts +279 -0
  193. package/src/client/view/Browser.module.css +751 -0
  194. package/src/client/view/BrowserBody.tsx +315 -0
  195. package/src/client/view/BrowserPresentation.ts +9 -0
  196. package/src/client/view/BrowserTitle.tsx +17 -0
  197. package/src/client/view/IframePresentation.ts +365 -0
  198. package/src/client/view/StartPage.tsx +598 -0
  199. package/src/client/view/TakeoverBanner.tsx +21 -0
  200. package/src/compat/host-features.ts +92 -0
  201. package/src/index.ts +110 -0
  202. package/src/reference-owner.ts +5 -0
  203. package/src/reference-page.ts +9 -0
  204. package/src/reference-source.ts +3 -0
  205. package/src/reference-text.ts +219 -0
  206. package/src/startpage-settings.ts +103 -0
  207. package/src/startpage.ts +71 -0
  208. package/src/takeover-protocol.ts +28 -0
  209. package/src/tool-browser/block-recovery.ts +85 -0
  210. package/src/tool-browser/code-tool.ts +555 -0
  211. package/src/tool-browser/code-worker.ts +725 -0
  212. package/src/tool-browser/element-fields.ts +167 -0
  213. package/src/tool-browser/errors.ts +40 -0
  214. package/src/tool-browser/index.ts +265 -0
  215. package/src/tool-browser/page-probe.ts +675 -0
  216. package/src/tool-browser/panel-page.ts +126 -0
  217. package/src/tool-browser/probe-client.ts +183 -0
  218. package/src/tool-browser/screenshot-annotations.ts +131 -0
  219. package/src/tool-browser/screenshot-image.ts +49 -0
  220. package/src/tool-browser/state.ts +375 -0
  221. package/src/tool-browser/takeover.ts +199 -0
  222. package/src/tool-browser/tools-debug.ts +806 -0
  223. package/src/tool-browser/tools-interaction.ts +956 -0
  224. package/src/tool-browser/tools-navigation.ts +786 -0
  225. package/src/tool-browser/tools-observation.ts +474 -0
  226. package/src/tool-browser/tools-reference.ts +294 -0
  227. package/src/types/electron-shim.d.ts +144 -0
  228. package/src/types.ts +85 -0
  229. package/src/web-guest.ts +35 -0
  230. package/tools/accept-desktop.mjs +148 -0
  231. package/dist/client.d.cts +0 -516
  232. package/dist/client.d.mts +0 -516
  233. package/dist/index.cjs +0 -92
  234. package/dist/index.d.mts +0 -2960
  235. package/dist/index.mjs +0 -24
  236. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  237. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  238. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  239. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  240. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  241. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  242. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  243. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  244. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  245. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  246. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  247. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  248. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  249. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  250. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  251. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  252. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  253. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  254. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  255. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  256. package/dsh-host-patch/sources/manifest.json +0 -218
  257. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  258. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  259. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  260. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  261. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  262. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  263. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  264. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  265. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  266. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  267. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  268. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  269. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  270. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  271. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  272. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  273. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  274. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  275. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  276. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  277. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  278. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  279. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  280. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  281. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  282. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  283. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  284. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  285. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  286. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  287. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  288. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  289. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  290. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  291. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  292. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  293. package/dsh-host-patch/sources/series.json +0 -260
@@ -0,0 +1,1056 @@
1
+ /**
2
+ * Production runtime: the object the assembly builds and the unit tests drive.
3
+ *
4
+ * It ties together the injected HTTP client, the per-session draft store, the
5
+ * durable asset store, the additive pending-delivery queue (tombstone +
6
+ * idempotent intents), the cancellable poller, the ordered submission seam and
7
+ * the production revealer. Every dependency is injected; NO host module is
8
+ * imported at runtime, so this file compiles and runs standalone.
9
+ *
10
+ * ACK rule (§12.1): a final `phase: 'acknowledged'` is sent ONLY after
11
+ * 1. every required image asset is durably bound (real bytes + optional host
12
+ * attachment receipt), and
13
+ * 2. the ordered group is durably saved with the user's question/caret intact.
14
+ * Otherwise the delivery stays visible on the server and is retried next poll.
15
+ * The runtime NEVER auto-submits: the user sends the message themselves.
16
+ *
17
+ * @module dsh-browser-reference/production/runtime
18
+ */
19
+ import type { KeyValueStorage, OrderedReferenceGroup } from '../types.ts'
20
+ import { referenceOwnerKey } from '../../../../reference-owner.ts'
21
+ import type { ReferenceSourcePage } from '../../../browser/iframe-reference.ts'
22
+ import { createDeliveryQueue, type DeliveryQueue } from '../pending-delivery.ts'
23
+ import type { TextPosition } from '../ordered-submission.ts'
24
+ import {
25
+ capturePreservation,
26
+ createSessionDraftStore,
27
+ preservationIntact,
28
+ preserveAndAppend,
29
+ reflectionFromDelivery,
30
+ type HostInputFace,
31
+ type SessionDraftStore,
32
+ type StoredReflection,
33
+ } from './draft-adapter.ts'
34
+ import { createAssetStore, type AssetStore } from './asset-store.ts'
35
+ import { requiredAssetKeys, toOrderedGroup } from './snapshot-adapter.ts'
36
+ import {
37
+ buildCardViewModel,
38
+ type CardViewModel,
39
+ } from './reference-card.ts'
40
+ import { encodeBrowserRefUri, parseBrowserRefUri } from '../scheme.ts'
41
+ import type { RevealStatus } from '../types.ts'
42
+ import { composerReference } from './production-submission.ts'
43
+ import {
44
+ createProductionRevealer,
45
+ type ProductionRevealer,
46
+ type RevealOwner,
47
+ } from './reveal.ts'
48
+ import {
49
+ createCancellationSource,
50
+ createDeliveryPoller,
51
+ type CancellationSource,
52
+ type DeliveryPoller,
53
+ type PollerScheduler,
54
+ } from './delivery-client.ts'
55
+ import type {
56
+ AssetResponse,
57
+ DeliveriesResponse,
58
+ DeliveryAckPhase,
59
+ DeliveryRecord,
60
+ ExportFormat,
61
+ } from './protocol.ts'
62
+ import type { ReferenceHttpClient } from './http-transport.ts'
63
+ import { availabilityOf, type AvailabilityState } from './availability.ts'
64
+
65
+ export interface AdmitAssetResult {
66
+ readonly receiptId?: string
67
+ }
68
+
69
+ export interface ProductionRuntimeOptions {
70
+ readonly http: ReferenceHttpClient
71
+ readonly storage: KeyValueStorage
72
+ readonly initialSessionId: string
73
+ /** Resolve the host input face for one DSH session (inputActions + input snapshot). */
74
+ readonly hostInputFor: (sessionId: string) => HostInputFace
75
+ /**
76
+ * Host image/file attachment admission. Given a fetched asset it returns an
77
+ * optional durable `receiptId`; `{}`/undefined means inline real bytes.
78
+ * Throwing leaves the asset unbound so the next poll retries.
79
+ */
80
+ readonly admitAsset?: (asset: AssetResponse, sessionId: string) => Promise<AdmitAssetResult | undefined>
81
+ readonly now?: () => number
82
+ readonly pollIntervalMs?: number
83
+ readonly scheduler?: PollerScheduler
84
+ readonly textPosition?: TextPosition
85
+ /** Shared abort source; when absent one is created and exposed on the runtime. */
86
+ readonly cancellation?: CancellationSource
87
+ readonly queueKey?: string
88
+ }
89
+
90
+ export type ApplyOutcome =
91
+ | { readonly kind: 'skipped'; readonly reason: 'wrong-session' | 'tombstoned' | 'queue-deleted' | 'consumed' }
92
+ | { readonly kind: 'rendered' }
93
+ | { readonly kind: 'recovered'; readonly from: 'snapshot' }
94
+ | { readonly kind: 'waiting-assets'; readonly missing: readonly string[] }
95
+ | { readonly kind: 'save-failed'; readonly reason: string }
96
+ | { readonly kind: 'ack-pending'; readonly reason: string }
97
+ | {
98
+ readonly kind: 'acknowledged'
99
+ readonly draftRev: number
100
+ readonly assetKeys: readonly string[]
101
+ readonly phases: readonly DeliveryAckPhase[]
102
+ }
103
+
104
+ export interface PollReport {
105
+ readonly sessionId: string
106
+ readonly since: number
107
+ readonly outcomes: readonly { readonly intentId: string; readonly outcome: ApplyOutcome }[]
108
+ /** Per-delivery processing errors, kept OUT of the transport's lastError. */
109
+ readonly internalErrors?: readonly string[]
110
+ }
111
+
112
+ /** One immutable dock view: stable identity until the runtime actually changes. */
113
+ export interface DockSnapshot {
114
+ readonly sessionId: string
115
+ readonly revision: number
116
+ readonly cards: readonly CardViewModel[]
117
+ readonly availability: AvailabilityState
118
+ /** Outcome of the last "回到原文" attempt, so a failure is never silent. */
119
+ readonly reveal?: { readonly status: string; readonly message: string; readonly referenceId?: string }
120
+ /** Why a captured reference has not reached the composer yet, in one sentence. */
121
+ readonly issue?: string
122
+ }
123
+
124
+ /**
125
+ * Human copy for a reveal attempt; only failures are worth interrupting for.
126
+ *
127
+ * Each failure names its own cause. One shared sentence for all of them made a
128
+ * page that merely scrolled away read as "the sidebar browser is broken".
129
+ */
130
+ const REVEAL_MESSAGES: Readonly<Record<string, string>> = {
131
+ revealed: '',
132
+ cancelled: '已取消定位。',
133
+ superseded: '已切换到更新的定位请求。',
134
+ 'unknown-reference': '这条引用已不在当前会话中,无法回到原文。',
135
+ 'session-mismatch': '这条引用属于另一个会话,无法在当前会话定位。',
136
+ 'not-found': '这条引用的原文记录已不存在。',
137
+ 'session-unavailable': '侧栏网页已不在原来的标签页里,无法回到原文。',
138
+ 'page-mismatch': '侧栏当前打开的是另一个页面,无法定位原文。',
139
+ missing: '侧栏页面里已找不到这段文字,页面内容可能已变化。',
140
+ ambiguous: '这段文字在页面里出现多处,无法确定是哪一处。',
141
+ unavailable: '侧栏网页没有响应,无法定位原文(页面可能正在加载或已关闭)。',
142
+ }
143
+
144
+ /**
145
+ * Why a captured reference is not on screen yet.
146
+ *
147
+ * The delivery stays on the server and is retried, so the card eventually
148
+ * appears; until then the dock has to say so. A capture that silently produces
149
+ * nothing is the single most confusing state this feature can be in.
150
+ */
151
+ const DELIVERY_ISSUES: Readonly<Record<string, string>> = {
152
+ 'waiting-assets': '引用里的图片还在读取,稍后会自动加入。',
153
+ 'save-failed': '引用已捕获,但当前输入框暂不可写,恢复后会自动加入。',
154
+ 'ack-pending': '引用已加入,正在确认…',
155
+ }
156
+
157
+ /** 插入引文的最大尝试次数;超过即放弃,避免每轮轮询重复写入。 */
158
+ const MAX_INSERT_ATTEMPTS = 3
159
+
160
+ export interface ProductionRuntime {
161
+ currentSessionId(): string
162
+ /** 订阅会话切换(会话 id 从空变成已知时也要通知);返回取消订阅。 */
163
+ onSessionChange(listener: (sessionId: string) => void): () => void
164
+ setSession(sessionId: string): void
165
+ /** 每次 dock 渲染时把当前草稿交给运行时:草稿由非空变空即视为已发送,退役本会话的引用。 */
166
+ noteDraft(sessionId: string, draft: string): void
167
+ /** One poll cycle; also the body of the interval. Returns a content-level report. */
168
+ pollOnce(): Promise<PollReport | undefined>
169
+ start(): void
170
+ stop(): void
171
+ dispose(): void
172
+ readonly disposed: boolean
173
+ readonly poller: DeliveryPoller
174
+ readonly cancellation: CancellationSource
175
+ /** Dock cards for the current session (content-complete view models). */
176
+ cards(): readonly CardViewModel[]
177
+ /**
178
+ * Stable, declarative view of the dock: the SAME object identity until
179
+ * something actually changed. `subscribe` + this method are what the React
180
+ * dock reads through `useSyncExternalStore`, so a delivery that lands in the
181
+ * background repaints without the user typing.
182
+ */
183
+ snapshot(): DockSnapshot
184
+ /** Subscribe to dock changes (delivery, comment edit, removal, session switch). */
185
+ subscribe(listener: () => void): () => void
186
+ /**
187
+ * Explicit delivery availability. A 404 -> plugin-too-old, a malformed body
188
+ * -> delivery-unavailable, a network failure -> offline, success -> ok.
189
+ * Never a silent "empty but healthy" state.
190
+ */
191
+ availability(): AvailabilityState
192
+ /** All sessions' reflections, for reveal routing. */
193
+ ownerFor(referenceId: string): RevealOwner | undefined
194
+ /** Remove a card for good: tombstoned locally and dropped on the plugin side. */
195
+ removeCard(referenceId: string): Promise<void>
196
+ /** Jump the sidebar browser back to a reference's原文 and highlight it. */
197
+ revealReference(referenceId: string, partId?: string): Promise<RevealStatus>
198
+ /**
199
+ * "Open this URL in the sidebar browser", supplied by the client shell.
200
+ *
201
+ * Reveal needs it to actually GO to the source: when the sidebar shows
202
+ * another page (or none at all) the only useful answer is to open the stored
203
+ * URL there and try again, not to explain that it could not.
204
+ */
205
+ setSourceOpener(opener: ((url: string, signal: AbortSignal) => Promise<ReferenceSourcePage>) | undefined): void
206
+ /** 一条引用的可展示详情(消息胶囊悬停卡用)。 */
207
+ referenceDetail(referenceId: string): (StoredReflection & { readonly sessionId: string; readonly card: CardViewModel }) | undefined
208
+ /** Activate a canonical `dsh-browser-ref:` URI (reply-side link bridge). */
209
+ activateUri(uri: string): Promise<RevealStatus>
210
+ /** Edit the draft's own copy of the user's note (§5); never rewrites the snapshot. */
211
+ setComment(referenceId: string, comment: string): boolean
212
+ /** Production revealer (activate a `dsh-browser-ref:` link). */
213
+ readonly revealer: ProductionRevealer
214
+ exportBundle(format: ExportFormat, sessionId?: string): Promise<Uint8Array>
215
+ importBundle(zip: Uint8Array): Promise<unknown>
216
+ /** Introspection for tests/recovery assertions. */
217
+ draftState(sessionId?: string): Readonly<ReturnType<SessionDraftStore['state']>>
218
+ assetStore(sessionId?: string): AssetStore
219
+ }
220
+
221
+ function errorMessage(error: unknown): string {
222
+ return error instanceof Error ? error.message : String(error)
223
+ }
224
+
225
+ /** Build the fully-wired production runtime. */
226
+ export function createProductionRuntime(options: ProductionRuntimeOptions): ProductionRuntime {
227
+ const http = options.http
228
+ const storage = options.storage
229
+ const now = options.now ?? (() => Date.now())
230
+ const admitAsset = options.admitAsset
231
+ const hostInputFor = options.hostInputFor
232
+ const cancellation = options.cancellation ?? createCancellationSource()
233
+ let current = referenceOwnerKey(options.initialSessionId)
234
+ /** 会话切换的订阅者:侧栏页要在 id 到手后立刻收到,而不是只能靠下一次询问。 */
235
+ const sessionListeners = new Set<(sessionId: string) => void>()
236
+ /** 每条引用的插入尝试次数(本运行时实例内有效),用于限次重试。 */
237
+ const insertAttempts = new Map<string, number>()
238
+ /** 上一次看到的草稿文本,用于识别「发送后草稿被清空」。 */
239
+ let lastDraft = ''
240
+ let disposed = false
241
+
242
+ // --- declarative dock state -------------------------------------------------
243
+ // The dock is a React component: it reads `snapshot()` through
244
+ // `useSyncExternalStore(runtime.subscribe, runtime.snapshot)`. `dirty` is
245
+ // bumped only when the visible content actually changed, so an idle poll
246
+ // never re-renders the card tree (a re-render would steal focus from the
247
+ // comment editor while the user is typing).
248
+ let dirty = 0
249
+ let published = 0
250
+ let cachedSnapshot: DockSnapshot | undefined
251
+ const listeners = new Set<() => void>()
252
+ // `undefined` until the first publish, so startup itself is not a change.
253
+ let lastAvailabilityStatus: string | undefined
254
+
255
+ let lastReveal: DockSnapshot['reveal']
256
+ /**
257
+ * Silences the per-attempt hint while `revealReference` retries after opening
258
+ * the source page: only the outcome the person ends up with is reported.
259
+ */
260
+ let mutedReveal = 0
261
+ let sourceOpener: ((url: string, signal: AbortSignal) => Promise<ReferenceSourcePage>) | undefined
262
+ let sourceOpening: AbortController | undefined
263
+ let revealIntent = 0
264
+ let pendingReveal: { readonly referenceId: string; readonly partId: string | undefined; readonly intent: number; readonly promise: Promise<RevealStatus> } | undefined
265
+ let lastIssue: string | undefined
266
+ const REVEAL_HINT_MS = 5_000
267
+ let revealTimer: ReturnType<typeof setTimeout> | undefined
268
+ const clearRevealHint = (): void => {
269
+ if (revealTimer === undefined) return
270
+ clearTimeout(revealTimer)
271
+ revealTimer = undefined
272
+ }
273
+ const showReveal = (status: string, detail?: string, referenceId?: string): void => {
274
+ clearRevealHint()
275
+ lastReveal = { status, message: [REVEAL_MESSAGES[status] ?? '', detail].filter(Boolean).join(' '), ...(referenceId === undefined ? {} : { referenceId }) }
276
+ markDirty()
277
+ publish()
278
+ if (lastReveal.message === '' || detail?.includes('桥接版本过旧') || detail?.includes('浏览器桥接不可用')) return
279
+ revealTimer = setTimeout(() => {
280
+ revealTimer = undefined
281
+ lastReveal = undefined
282
+ markDirty()
283
+ publish()
284
+ }, REVEAL_HINT_MS)
285
+ const unref = (revealTimer as unknown as { unref?: () => void }).unref
286
+ if (typeof unref === 'function') unref.call(revealTimer)
287
+ }
288
+ const activateUri = async (uri: string): Promise<RevealStatus> => {
289
+ const parsed = parseBrowserRefUri(uri)
290
+ if (parsed !== undefined) return revealReference(parsed.referenceId, parsed.partId)
291
+ revealIntent += 1
292
+ sourceOpening?.abort()
293
+ showReveal('unknown-reference')
294
+ return 'unknown-reference'
295
+ }
296
+
297
+ // --- wake-on-visible --------------------------------------------------------
298
+ // Chromium throttles a hidden renderer's timers to about one per minute. A
299
+ // capture made while the window was in the background used to surface up to
300
+ // 41 s later — the "界面不会自动更新" report. Poll immediately when the window
301
+ // regains focus instead of waiting for the throttled interval.
302
+ let stopWake: (() => void) | undefined
303
+
304
+ const markDirty = (): void => { dirty += 1 }
305
+
306
+ const publish = (): void => {
307
+ const status = availabilityOf(poller.lastError).status
308
+ // `undefined` means "never published"; treat it as the initial healthy
309
+ // state so the FIRST outage (404 / offline / malformed body) also bumps
310
+ // dirty and notifies the dock, instead of leaving a cached "ok" banner up.
311
+ const previous = lastAvailabilityStatus ?? 'ok'
312
+ if (status !== previous) dirty += 1
313
+ lastAvailabilityStatus = status
314
+ if (dirty === published) return
315
+ published = dirty
316
+ cachedSnapshot = undefined
317
+ for (const listener of [...listeners]) listener()
318
+ }
319
+
320
+ const stores = new Map<string, SessionDraftStore>()
321
+ const assets = new Map<string, AssetStore>()
322
+
323
+ const draftStoreFor = (sessionId: string): SessionDraftStore => {
324
+ let store = stores.get(sessionId)
325
+ if (store === undefined) {
326
+ store = createSessionDraftStore(storage, sessionId)
327
+ stores.set(sessionId, store)
328
+ }
329
+ return store
330
+ }
331
+ const assetStoreFor = (sessionId: string): AssetStore => {
332
+ let store = assets.get(sessionId)
333
+ if (store === undefined) {
334
+ store = createAssetStore(storage, sessionId)
335
+ assets.set(sessionId, store)
336
+ }
337
+ return store
338
+ }
339
+
340
+ // The delivery queue is independent of localStorage: a consumed marker on
341
+ // the Host prevents an old draft from returning after a quota-blocked exit.
342
+ const pendingConsumptions = new Map<string, { readonly sessionId: string; readonly intentId: string }>()
343
+ let consuming: Promise<void> | undefined
344
+ const flushConsumptions = (): Promise<void> => {
345
+ if (http.consume === undefined) return Promise.resolve()
346
+ if (consuming !== undefined) return consuming
347
+ const consume = http.consume.bind(http)
348
+ const task = (async () => {
349
+ for (const [key, pending] of pendingConsumptions) {
350
+ try {
351
+ await consume(pending.sessionId, pending.intentId)
352
+ if (pendingConsumptions.get(key) === pending) pendingConsumptions.delete(key)
353
+ } catch { /* the next poll or accepted send retries the durable marker */ }
354
+ }
355
+ })().finally(() => { if (consuming === task) consuming = undefined })
356
+ consuming = task
357
+ return task
358
+ }
359
+
360
+ // Reuse the additive pending-delivery queue: intent-id idempotency +
361
+ // durable tombstone (a removed reference stays removed under late retries).
362
+ const queue: DeliveryQueue = createDeliveryQueue({
363
+ storage,
364
+ ...(options.queueKey === undefined ? {} : { key: options.queueKey }),
365
+ onApply: () => { /* final ACK is awaited explicitly, not fired here */ },
366
+ })
367
+
368
+ /**
369
+ * Retry the durable archive of any session whose accepted send left a pending
370
+ * marker (a localStorage quota failure during phase 2). Idempotent: a store
371
+ * with nothing pending returns immediately, and a store whose archive already
372
+ * succeeded has an empty marker. Driven by the poller, by the next commit and
373
+ * by the host's retry hook, so the sent message's provenance is completed as
374
+ * soon as quota recovers — without ever re-sending or re-ACKing anything.
375
+ */
376
+ const flushPendingArchives = (): void => {
377
+ for (const store of stores.values()) {
378
+ try { store.flushPendingArchive() } catch { /* keep the pending marker for the next retry */ }
379
+ }
380
+ }
381
+
382
+ const requiredKeys = (delivery: DeliveryRecord): readonly string[] =>
383
+ [...new Set([...delivery.requiredAssets, ...requiredAssetKeys(delivery.snapshot)])]
384
+
385
+ /** Bind every required asset, returning the keys still missing. */
386
+ const bindAssets = async (delivery: DeliveryRecord, sessionId: string): Promise<readonly string[]> => {
387
+ const store = assetStoreFor(sessionId)
388
+ const required = requiredKeys(delivery)
389
+ for (const key of required) {
390
+ if (store.get(key) !== undefined) continue
391
+ try {
392
+ const asset = await http.assetBase64(key)
393
+ let receiptId: string | undefined
394
+ if (admitAsset !== undefined) {
395
+ const result = await admitAsset(asset, sessionId)
396
+ receiptId = result?.receiptId
397
+ }
398
+ store.bind(asset, receiptId)
399
+ } catch {
400
+ // A transient asset/admission failure leaves the key unbound; the
401
+ // delivery stays visible server-side and is retried on the next poll.
402
+ }
403
+ }
404
+ return store.missing(required)
405
+ }
406
+
407
+ const makeReflection = (delivery: DeliveryRecord, state: StoredReflection['deliveryState']): StoredReflection => {
408
+ const group = toOrderedGroup(delivery.snapshot)
409
+ const base = reflectionFromDelivery(delivery, group, now())
410
+ return { ...base, deliveryState: state }
411
+ }
412
+
413
+ /**
414
+ * Reference ids whose durable save THIS process has confirmed. A persisted
415
+ * reflection alone is NOT proof: after a host `persistDraft` failure the card
416
+ * is already in the store, and the old `hasReference` short-circuit ACKed the
417
+ * next poll without ever re-checking the "durably saved with the user's text
418
+ * intact" gate. A restart starts empty and simply re-validates — the already
419
+ * appended card is never deleted.
420
+ */
421
+ const confirmedSaved = new Set<string>()
422
+ const savedKey = (sessionId: string, referenceId: string): string => `${sessionId}\u0000${referenceId}`
423
+
424
+ /** Ensure the group + reflection exist; returns the saved CAS revision. */
425
+ const ensureDraft = (
426
+ delivery: DeliveryRecord,
427
+ sessionId: string,
428
+ state: StoredReflection['deliveryState'],
429
+ ): { readonly ok: boolean; readonly draftRev: number; readonly reason?: string } => {
430
+ const store = draftStoreFor(sessionId)
431
+ const key = savedKey(sessionId, delivery.referenceId)
432
+ if (store.hasReference(delivery.referenceId)) {
433
+ store.setDeliveryState(delivery.referenceId, state)
434
+ if (confirmedSaved.has(key)) return { ok: true, draftRev: store.state().draftRev }
435
+ // The card is already appended, but we have no proof this process durably
436
+ // saved it with the question/caret intact. Re-run the persistence +
437
+ // preservation checks before allowing an ACK (never drop the card).
438
+ const host = hostInputFor(sessionId)
439
+ const before = capturePreservation(host)
440
+ let saveSucceeded = false
441
+ try {
442
+ host.persistDraft()
443
+ store.persist()
444
+ saveSucceeded = true
445
+ } catch {
446
+ saveSucceeded = false
447
+ }
448
+ const preserved = preservationIntact(host, before)
449
+ if (saveSucceeded && preserved) {
450
+ confirmedSaved.add(key)
451
+ return { ok: true, draftRev: store.state().draftRev }
452
+ }
453
+ return {
454
+ ok: false,
455
+ draftRev: store.state().draftRev,
456
+ reason: !saveSucceeded ? 'persist failed' : 'user text/caret changed',
457
+ }
458
+ }
459
+ const reflection = makeReflection(delivery, state)
460
+ const result = preserveAndAppend({
461
+ host: hostInputFor(sessionId),
462
+ store,
463
+ makeReflection: () => reflection,
464
+ })
465
+ if (result.ok) {
466
+ confirmedSaved.add(key)
467
+ return { ok: true, draftRev: result.draftRev }
468
+ }
469
+ if (result.status === 'duplicate') {
470
+ store.ensureReflection(reflection)
471
+ confirmedSaved.add(key)
472
+ return { ok: true, draftRev: store.state().draftRev }
473
+ }
474
+ const reason = !result.saveSucceeded ? 'persist failed'
475
+ : !result.preserved ? 'user text/caret changed' : result.status
476
+ return { ok: false, draftRev: result.draftRev, reason }
477
+ }
478
+
479
+
480
+ /**
481
+ * Insert one delivery as a native reference chip, when the host exposes the editor entry point.
482
+ * @param delivery - the delivery being reflected into the draft.
483
+ * @param sessionId - owning Session.
484
+ */
485
+ const insertChip = (delivery: DeliveryRecord, sessionId: string): boolean => {
486
+ const host = hostInputFor(sessionId)
487
+ const title = delivery.snapshot.source.title
488
+ const index = (draftStoreFor(sessionId).state().reflections ?? []).length
489
+ const reference = composerReference(toOrderedGroup(delivery.snapshot), {
490
+ index: index - 1, assets: assetStoreFor(sessionId), ...title === undefined ? {} : { title },
491
+ })
492
+ // 插入需要编辑器里有光标:确认按钮是在侧栏 iframe 里点的,先聚焦编辑器。
493
+ try { host.focusEditor?.() } catch { /* 没有编辑器就交给下面的失败路径 */ }
494
+ const uri = encodeBrowserRefUri({ referenceId: delivery.referenceId })
495
+ let inserted = false
496
+ try {
497
+ inserted = host.insertQuote?.(reference.text) === true
498
+ || host.insertReference?.({
499
+ source: 'browser-reference', ref: uri, label: title || '网页引用',
500
+ appearance: 'session', clipboardText: reference.text,
501
+ }, host.captureInsertion()) === true
502
+ } catch {
503
+ return false
504
+ }
505
+ if (inserted && reference.images.length > 0) {
506
+ try {
507
+ const ids = host.attachImages?.(reference.images) ?? []
508
+ if (ids.length > 0) attachedImages.set(`${sessionId}${delivery.referenceId}`, ids)
509
+ } catch { /* 图片附件是尽力而为:引文已带占位说明 */ }
510
+ }
511
+ return inserted
512
+ }
513
+
514
+ const processDelivery = async (delivery: DeliveryRecord, sessionId: string): Promise<ApplyOutcome> => {
515
+ if (delivery.sessionId !== sessionId) return { kind: 'skipped', reason: 'wrong-session' }
516
+ const store = draftStoreFor(sessionId)
517
+ if (delivery.state === 'consumed') {
518
+ // The Host already consumed this reference. `retire` clears the in-memory
519
+ // draft even when its durable write fails (see draft-adapter), so the
520
+ // quote cannot leak into the next message. The queue tombstone is the
521
+ // same idempotent call `consumeSubmitted` guards: a full localStorage
522
+ // must NOT make `prepare()` throw and block the user from sending again.
523
+ store.retire([delivery.referenceId], [makeReflection(delivery, 'acknowledged')])
524
+ try { queue.markDeleted(delivery.referenceId) } catch { /* tombstone is idempotent; the poller retries */ }
525
+ try { store.flushPendingArchive() } catch { /* preserve the pending archive for retry */ }
526
+ markDirty()
527
+ return { kind: 'skipped', reason: 'consumed' }
528
+ }
529
+ if (store.isTombstoned(delivery.referenceId)) return { kind: 'skipped', reason: 'tombstoned' }
530
+ const group: OrderedReferenceGroup = toOrderedGroup(delivery.snapshot)
531
+ const capture = queue.capture({ intentId: delivery.intentId, sessionId, group })
532
+ if (capture.status === 'deleted') return { kind: 'skipped', reason: 'queue-deleted' }
533
+
534
+ const required = requiredKeys(delivery)
535
+ await bindAssets(delivery, sessionId)
536
+ const assetStore = assetStoreFor(sessionId)
537
+
538
+ if (delivery.state === 'acknowledged') {
539
+ // An acknowledged delivery still has to re-fetch any asset that was not
540
+ // durably bound the first time. A transient asset failure used to leave
541
+ // the card rendered with zero images and the projection full of
542
+ // `image unavailable` placeholders, with the cursor already past the
543
+ // delivery so nothing ever retried. `waiting-assets` is RETRYABLE: it
544
+ // pins the cursor below this sequence so the next poll keeps calling
545
+ // bindAssets until every required asset is bound. No ACK, no re-send.
546
+ const missing = assetStore.missing(required)
547
+ if (missing.length > 0) return { kind: 'waiting-assets', missing }
548
+ // Only render the card; recover the full group from the frozen snapshot
549
+ // when a restart left our draft empty. No ACK, no re-send.
550
+ const existed = store.hasReference(delivery.referenceId)
551
+ const draft = ensureDraft(delivery, sessionId, 'acknowledged')
552
+ if (!draft.ok) return { kind: 'save-failed', reason: draft.reason ?? 'recovery failed' }
553
+ // 引文只在**这张卡第一次出现时**插入编辑器。旧代码不看 `existed`,于是每条已确认的投递在
554
+ // 每轮轮询里都再插一次:几十轮下来草稿被同一段引文灌满(界面上一整屏引号),而且每次插入
555
+ // 都改一次草稿修订号。恢复路径(重启后重建卡片)本来就该只还原卡片,不重放插入。
556
+ // 记账放在**草稿 store**里(持久化):运行时实例会被 dock 重挂载重建,内存记账跟着丢,
557
+ // 同一条投递就会被反复插进草稿(界面上一整屏引号)。
558
+ // 先记账再插:插入失败(编辑器被锁、修订号变动)时若不留记录,就会每个轮询周期重试一次,
559
+ // 界面表现为引文每秒叠加一条。记账是「这条引用已经处理过」,重试交给用户动作。
560
+ // 限次重试:插入可能因为编辑器还没聚焦或修订号刚变而失败,但绝不能每轮都试——
561
+ // 那会让引文在界面上每秒叠加一条。三次仍不成功就记账放弃,重试交给用户动作。
562
+ if (!store.hasInserted(delivery.referenceId)) {
563
+ const attempts = insertAttempts.get(delivery.referenceId) ?? 0
564
+ if (attempts >= MAX_INSERT_ATTEMPTS) {
565
+ store.markInserted(delivery.referenceId)
566
+ insertAttempts.delete(delivery.referenceId)
567
+ } else {
568
+ insertAttempts.set(delivery.referenceId, attempts + 1)
569
+ if (insertChip(delivery, sessionId)) {
570
+ store.markInserted(delivery.referenceId)
571
+ insertAttempts.delete(delivery.referenceId)
572
+ }
573
+ }
574
+ }
575
+ return existed ? { kind: 'rendered' } : { kind: 'recovered', from: 'snapshot' }
576
+ }
577
+
578
+ // 'prepared' | 'draft-applied': gate the ACK on assets + a durable draft.
579
+ const missing = assetStore.missing(required)
580
+ if (missing.length > 0) return { kind: 'waiting-assets', missing }
581
+
582
+ const draft = ensureDraft(delivery, sessionId, delivery.state)
583
+ if (!draft.ok) return { kind: 'save-failed', reason: draft.reason ?? 'draft not saved' }
584
+ if (draft.draftRev < 1) return { kind: 'save-failed', reason: 'no saved draft revision' }
585
+
586
+ const phases: DeliveryAckPhase[] = []
587
+ try {
588
+ if (delivery.state === 'prepared') {
589
+ await http.ack({
590
+ intentId: delivery.intentId,
591
+ draftRev: draft.draftRev,
592
+ assetKeys: required,
593
+ phase: 'draft-applied',
594
+ })
595
+ phases.push('draft-applied')
596
+ }
597
+ await http.ack({
598
+ intentId: delivery.intentId,
599
+ draftRev: draft.draftRev,
600
+ assetKeys: required,
601
+ phase: 'acknowledged',
602
+ })
603
+ phases.push('acknowledged')
604
+ } catch (error: unknown) {
605
+ return { kind: 'ack-pending', reason: errorMessage(error) }
606
+ }
607
+ store.setDeliveryState(delivery.referenceId, 'acknowledged')
608
+ queue.acknowledge(delivery.intentId)
609
+ return { kind: 'acknowledged', draftRev: draft.draftRev, assetKeys: required, phases }
610
+ }
611
+
612
+ /**
613
+ * Outcomes that must be retried. The server returns `sequence > since`, so a
614
+ * cursor that advanced past them would strand the reference forever: the
615
+ * card would never appear even after the network recovered.
616
+ */
617
+ const RETRYABLE: ReadonlySet<ApplyOutcome['kind']> = new Set(['waiting-assets', 'save-failed', 'ack-pending'])
618
+
619
+ const runCycle = async (
620
+ response: DeliveriesResponse,
621
+ sessionId: string,
622
+ isActive?: () => boolean,
623
+ ): Promise<PollReport> => {
624
+ // Recover any archive an accepted send left pending when storage was at
625
+ // quota. Idempotent and write-free when nothing is pending.
626
+ flushPendingArchives()
627
+ await flushConsumptions()
628
+ const outcomes: { intentId: string; outcome: ApplyOutcome }[] = []
629
+ let since = draftStoreFor(sessionId).state().since
630
+ // Lowest sequence that still has unfinished work. The cursor may not pass it.
631
+ let blockedAt = Number.POSITIVE_INFINITY
632
+ // A record belonging to another session is not ours to skip past: advancing
633
+ // the cursor for it would drop a delivery of OUR own that shares the range.
634
+ let foreign = false
635
+ // True while every record seen so far belongs to another session.
636
+ let foreignOnly = true
637
+ let issue: string | undefined
638
+ // Processing errors are recorded here, NEVER written into the transport's
639
+ // lastError (that would make availabilityOf misreport "plugin not started").
640
+ const internalErrors: string[] = []
641
+ for (const delivery of response.deliveries) {
642
+ // A session switch can land while a previous cycle is still awaiting a
643
+ // delivery. Stop before touching the OLD session again (no ACK, no cursor).
644
+ if (isActive !== undefined && !isActive()) {
645
+ return { sessionId, since, outcomes, ...(internalErrors.length > 0 ? { internalErrors } : {}) }
646
+ }
647
+ let outcome: ApplyOutcome
648
+ try {
649
+ outcome = await processDelivery(delivery, sessionId)
650
+ } catch (error: unknown) {
651
+ // One malformed delivery must not abort the whole batch or strand the
652
+ // cursor. Record it as retryable and keep processing the rest.
653
+ const lastCycleError = errorMessage(error)
654
+ internalErrors.push(lastCycleError)
655
+ outcome = { kind: 'ack-pending', reason: lastCycleError }
656
+ }
657
+ outcomes.push({ intentId: delivery.intentId, outcome })
658
+ if (outcome.kind === 'skipped' && outcome.reason === 'wrong-session') { foreign = true; continue }
659
+ foreignOnly = false
660
+ if (outcome.kind !== 'skipped') markDirty()
661
+ if (RETRYABLE.has(outcome.kind)) {
662
+ if (delivery.sequence < blockedAt) blockedAt = delivery.sequence
663
+ if (issue === undefined) issue = DELIVERY_ISSUES[outcome.kind]
664
+ } else if (delivery.sequence > since) {
665
+ since = delivery.sequence
666
+ }
667
+ }
668
+ // 临时诊断:把这一轮每个投递的处置结果挂到 window,定位「有投递但不上卡」。
669
+ // The banner follows the newest cycle: it appears while work is stuck and
670
+ // clears by itself as soon as that work lands.
671
+ if (lastIssue !== issue) { lastIssue = issue; markDirty() }
672
+ // A batch made only of OTHER sessions' deliveries used to pin the cursor at
673
+ // `since` forever, replaying the same records every 1.5 s. With no own
674
+ // unfinished work it is safe to jump to the queue's global high-water mark.
675
+ const noRetryable = blockedAt === Number.POSITIVE_INFINITY
676
+ const highest = foreignOnly && foreign && noRetryable
677
+ ? Math.max(since, response.sequence)
678
+ : foreign ? since : Math.max(since, response.sequence)
679
+ // Retryable work pins the cursor below itself; the next poll asks for it again.
680
+ const next = noRetryable ? highest : Math.min(highest, blockedAt - 1)
681
+ // setSince short-circuits when the value is unchanged (no needless
682
+ // JSON.stringify + localStorage write on a steady-state poll).
683
+ draftStoreFor(sessionId).setSince(next)
684
+ return { sessionId, since: next, outcomes, ...(internalErrors.length > 0 ? { internalErrors } : {}) }
685
+ }
686
+
687
+ let lastReport: PollReport | undefined
688
+ /** 只有显式 start() 之后,setSession 才自动重起轮询(测试里用 pollOnce 手动驱动)。 */
689
+ let pollingRequested = false
690
+ const poller = createDeliveryPoller({
691
+ http,
692
+ getSessionId: () => current,
693
+ getSince: () => draftStoreFor(current).state().since,
694
+ onCycle: async (response, sessionId, isActive) => {
695
+ const report = await runCycle(response, sessionId, isActive)
696
+ // A switch mid-cycle invalidates this (OLD session) report.
697
+ if (isActive !== undefined && !isActive()) return
698
+ lastReport = report
699
+ // Publish from the poll path too: the interval is what delivers a card
700
+ // while the user is not touching the UI.
701
+ publish()
702
+ },
703
+ // A settled poll must publish even when onCycle never ran (network failure
704
+ // / 404 / plugin not running), otherwise useSyncExternalStore keeps the
705
+ // cached "ok" banner on screen forever.
706
+ onSettled: () => { publish() },
707
+ ...(options.pollIntervalMs === undefined ? {} : { intervalMs: options.pollIntervalMs }),
708
+ ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
709
+ cancellation,
710
+ })
711
+
712
+ /**
713
+ * Retire the references a just-accepted send carried, in TWO phases.
714
+ *
715
+ * They are now message content, not draft state: leaving them in the store
716
+ * made the next send attach the same quote again. The old single-step archive
717
+ * copied the full FrozenSnapshot into `sent` and persisted BEFORE removing it
718
+ * — at a tight localStorage quota that copy threw, so the removal never ran,
719
+ * the card stayed, the next message repeated
720
+ * the reference, and the throw bubbled out of the send as a false failure
721
+ * even though the Host had already accepted the prompt.
722
+ *
723
+ * Phase 1 (`retire`) is a light, atomic MOVE out of the draft groups into a
724
+ * `pendingArchive` marker: it never copies the full snapshot, so it succeeds
725
+ * even at that quota. This is the step that MUST leave no draft residue.
726
+ * Phase 2 (`flushPendingArchive`) writes the archive into `sent`, deduplicated
727
+ * by referenceId; it may fail on quota and is then retried, with the pending
728
+ * marker surviving until it succeeds. Neither phase can turn an accepted send
729
+ * into a failure: the whole operation is best-effort and never throws.
730
+ *
731
+ * Only `referenceIds` — the set frozen when the content was projected — are
732
+ * consumed. A reference added while the send was in flight stays in the draft.
733
+ * @param sessionId - the session whose references were submitted.
734
+ * @param referenceIds - exactly the references that send carried.
735
+ */
736
+ const consumeSubmitted = (sessionId: string, referenceIds: readonly string[]): Promise<void> => {
737
+ const store = draftStoreFor(sessionId)
738
+ for (const reflection of store.state().reflections) {
739
+ if (referenceIds.includes(reflection.referenceId)) {
740
+ pendingConsumptions.set(JSON.stringify([sessionId, reflection.intentId]), { sessionId, intentId: reflection.intentId })
741
+ }
742
+ }
743
+ try {
744
+ // Phase 1: atomically retire (no full-snapshot copy; always clears the draft).
745
+ const retired = store.retire(referenceIds)
746
+ for (const referenceId of retired) {
747
+ try { queue.markDeleted(referenceId) } catch { /* tombstone is idempotent; the poller retries */ }
748
+ }
749
+ // Phase 2: durable archive, deduplicated by referenceId. A quota failure
750
+ // keeps the pending marker for the next commit / poll / retrySubmitted.
751
+ store.flushPendingArchive()
752
+ } catch {
753
+ // Never let a LOCAL cleanup error bubble out: the Host already accepted
754
+ // the message. Any pending marker is flushed by the poller / next commit.
755
+ }
756
+ markDirty()
757
+ publish()
758
+ return flushConsumptions()
759
+ }
760
+
761
+ const referenceDetail = (referenceId: string): (StoredReflection & { readonly sessionId: string; readonly card: CardViewModel }) | undefined => {
762
+ draftStoreFor(current)
763
+ for (const [sessionId, store] of stores) {
764
+ // A reference carried by a sent message lives in the archive, not in the
765
+ // draft: its source link must keep working after the card clears. It may
766
+ // also sit in `pendingArchive` between an accepted send's retire and the
767
+ // durable archive (quota failure), so resolve that window too — otherwise
768
+ // the sent message's link would read "来源不可用" until quota recovers.
769
+ const reflection = store.state().reflections.find(entry => entry.referenceId === referenceId)
770
+ ?? store.sentReflection(referenceId)
771
+ ?? store.pendingReflection(referenceId)
772
+ if (reflection === undefined) continue
773
+ const index = store.state().reflections.indexOf(reflection) + 1
774
+ return { ...reflection, sessionId, card: buildCardViewModel(reflection, assetStoreFor(sessionId), index || 1) }
775
+ }
776
+ return undefined
777
+ }
778
+
779
+ const ownerFor = (referenceId: string): RevealOwner | undefined => {
780
+ const detail = referenceDetail(referenceId)
781
+ if (detail === undefined) return undefined
782
+ const { snapshot } = detail
783
+ return {
784
+ sessionId: referenceOwnerKey(snapshot.owner.sessionId ?? detail.sessionId),
785
+ browserSessionId: detail.browserSessionId,
786
+ label: snapshot.source.title,
787
+ ...(snapshot.source.frameRoute === undefined ? {} : { frameRoute: snapshot.source.frameRoute }),
788
+ ...(snapshot.source.frameSelector === undefined ? {} : { frameSelector: snapshot.source.frameSelector }),
789
+ }
790
+ }
791
+
792
+ const revealer = createProductionRevealer({
793
+ http,
794
+ resolveOwner: ownerFor,
795
+ currentSessionId: () => current,
796
+ onActivate: activateUri,
797
+ // A failed reply-side source link (linkSpec.onActivate) now surfaces the
798
+ // same dock hint as the document-level bridge (B6). A retry in progress
799
+ // stays quiet: intermediate "still on the wrong page" hints would flash
800
+ // while the source page is loading.
801
+ report: status => { if (mutedReveal === 0) showReveal(status) },
802
+ })
803
+
804
+ const revealReference = (referenceId: string, partId?: string): Promise<RevealStatus> => {
805
+ if (!disposed && pendingReveal?.intent === revealIntent && pendingReveal.referenceId === referenceId && pendingReveal.partId === partId) {
806
+ return pendingReveal.promise
807
+ }
808
+ const promise = performReveal(referenceId, partId)
809
+ const pending = { referenceId, partId, intent: revealIntent, promise }
810
+ pendingReveal = pending
811
+ const clear = (): void => { if (pendingReveal === pending) pendingReveal = undefined }
812
+ void promise.then(clear, clear)
813
+ return promise
814
+ }
815
+
816
+ const performReveal = async (referenceId: string, partId?: string): Promise<RevealStatus> => {
817
+ sourceOpening?.abort()
818
+ const opening = new AbortController()
819
+ sourceOpening = opening
820
+ const intent = ++revealIntent
821
+ const sessionId = current
822
+ const active = (): boolean => !disposed && intent === revealIntent && current === sessionId
823
+ const uri = encodeBrowserRefUri({ referenceId, ...(partId === undefined ? {} : { partId }) })
824
+ const attempt = async (sourcePageId?: string): Promise<RevealStatus> => {
825
+ if (!active()) return 'superseded'
826
+ mutedReveal += 1
827
+ try { return await revealer.activate(uri, { sourcePageId }) }
828
+ finally { mutedReveal -= 1 }
829
+ }
830
+ let status = await attempt()
831
+ const bridgeFailure = (): string | undefined => {
832
+ const reason = revealer.lastReason()
833
+ return reason?.includes('桥接版本过旧') || reason?.includes('浏览器桥接不可用') ? reason : undefined
834
+ }
835
+ let sourceFailure: string | undefined
836
+ try {
837
+ const url = referenceDetail(referenceId)?.snapshot.source.pageUrl
838
+ if (active() && bridgeFailure() === undefined && (status === 'session-unavailable' || status === 'page-mismatch' || status === 'unavailable') && url && sourceOpener !== undefined) {
839
+ const ready = await sourceOpener(url, opening.signal)
840
+ const detail = referenceDetail(referenceId)
841
+ if (!active()) return 'superseded'
842
+ status = ready.reveal !== undefined && detail !== undefined
843
+ ? await ready.reveal(detail.snapshot, partId, opening.signal)
844
+ : await attempt(ready.pageId)
845
+ }
846
+ } catch (error) {
847
+ status = 'unavailable'
848
+ sourceFailure = errorMessage(error)
849
+ }
850
+ if (!active()) return 'superseded'
851
+ showReveal(status, sourceFailure ?? bridgeFailure(), referenceId)
852
+ return status
853
+ }
854
+
855
+ const snapshot = (): DockSnapshot => {
856
+ const availability = availabilityOf(poller.lastError)
857
+ // The availability status is part of the cached view: a transport that went
858
+ // from ok to offline must rebuild the snapshot even when no card changed,
859
+ // otherwise the banner would only appear on the next unrelated repaint.
860
+ if (cachedSnapshot !== undefined
861
+ && cachedSnapshot.availability.status === availability.status
862
+ && cachedSnapshot.issue === lastIssue) {
863
+ return cachedSnapshot
864
+ }
865
+ const store = draftStoreFor(current)
866
+ const assetStore = assetStoreFor(current)
867
+ const cards = store.state().reflections
868
+ .filter(reflection => !store.isTombstoned(reflection.referenceId))
869
+ .map((reflection, index) => buildCardViewModel(reflection, assetStore, index + 1))
870
+ cachedSnapshot = {
871
+ sessionId: current,
872
+ revision: published,
873
+ cards,
874
+ availability,
875
+ ...lastReveal === undefined || lastReveal.message === '' ? {} : { reveal: lastReveal },
876
+ ...lastIssue === undefined ? {} : { issue: lastIssue },
877
+ }
878
+ return cachedSnapshot
879
+ }
880
+
881
+ /**
882
+ * Remove a card's references for good.
883
+ *
884
+ * Removal is final: the card is tombstoned in the draft store, dropped from
885
+ * the delivery queue and removed on the plugin side in one step, so the next
886
+ * send simply does not see it (there is no window in which it can be undone).
887
+ */
888
+ const quotesSeen = new Set<string>()
889
+ const attachedImages = new Map<string, readonly string[]>()
890
+
891
+ const removeReferences = (sessionId: string, ids: readonly string[]): void => {
892
+ if (ids.length === 0) return
893
+ const store = draftStoreFor(sessionId)
894
+ for (const referenceId of ids) {
895
+ const reflection = store.state().reflections.find(entry => entry.referenceId === referenceId)
896
+ const intentId = reflection?.intentId ?? findIntentId(queue, referenceId)
897
+ store.remove(referenceId)
898
+ queue.markDeleted(referenceId)
899
+ if (intentId !== undefined) {
900
+ void http.remove(intentId).catch(() => undefined)
901
+ }
902
+ }
903
+ markDirty()
904
+ publish()
905
+ }
906
+
907
+ const runtime: ProductionRuntime = {
908
+ currentSessionId: () => current,
909
+ onSessionChange(listener) {
910
+ sessionListeners.add(listener)
911
+ return () => { sessionListeners.delete(listener) }
912
+ },
913
+ noteDraft(sessionId, draft) {
914
+ if (disposed) return
915
+ const previous = lastDraft
916
+ lastDraft = draft
917
+ const store = draftStoreFor(sessionId)
918
+ const ids = store.state().groups.map(group => group.referenceId)
919
+ // 上游接受消息后会清空草稿:这一刻把本会话的引用全部退役,输入框里的胶囊随之消失。
920
+ if (draft.trim() === '') {
921
+ if (previous.trim() !== '' && ids.length > 0) void consumeSubmitted(sessionId, ids)
922
+ return
923
+ }
924
+ // The host quote is what gets sent, so it is the single source of truth: once a quote has been
925
+ // seen in the draft, the user deleting it removes its card too.
926
+ const removed: string[] = []
927
+ for (const referenceId of ids) {
928
+ const key = `${sessionId}${referenceId}`
929
+ if (draft.includes(encodeBrowserRefUri({ referenceId }))) quotesSeen.add(key)
930
+ else if (quotesSeen.delete(key)) {
931
+ removed.push(referenceId)
932
+ const images = attachedImages.get(key)
933
+ attachedImages.delete(key)
934
+ if (images !== undefined) {
935
+ try { hostInputFor(sessionId).removeAttachments?.(images) } catch { /* the user can still remove them in the composer */ }
936
+ }
937
+ }
938
+ }
939
+ if (removed.length > 0) removeReferences(sessionId, removed)
940
+ },
941
+ setSession(sessionId) {
942
+ sessionId = referenceOwnerKey(sessionId)
943
+ if (disposed || sessionId === current) return
944
+ sourceOpening?.abort()
945
+ revealIntent += 1
946
+ clearRevealHint()
947
+ lastReveal = undefined
948
+ lastIssue = undefined
949
+ // A switch must not hand the NEW conversation the OLD session's report.
950
+ lastReport = undefined
951
+ current = sessionId
952
+ // Lazily materialise the new session's stores from persisted state so a
953
+ // switch instantly exposes its recovered cards/assets/cursor.
954
+ draftStoreFor(sessionId)
955
+ assetStoreFor(sessionId)
956
+ poller.setSession(sessionId)
957
+ // 自愈:dev 下插件 fiber 可能被热替换重挂载,旧实例的 disposer 会停掉轮询,而 dock 仍挂在
958
+ // 页面上。此时「有投递却永远不上卡、发送永远禁用」。会话每次绑定都确认轮询活着,停了就重起。
959
+ if (pollingRequested && !disposed && !poller.isPolling()) poller.start()
960
+ for (const listener of sessionListeners) listener(sessionId)
961
+ markDirty()
962
+ publish()
963
+ },
964
+ async pollOnce() {
965
+ const response = await poller.pollOnce()
966
+ publish()
967
+ return response === undefined ? undefined : lastReport
968
+ },
969
+ start() {
970
+ pollingRequested = true
971
+ poller.start()
972
+ if (stopWake !== undefined || typeof document === 'undefined' || typeof window === 'undefined') return
973
+ const wake = (): void => {
974
+ if (document.visibilityState === 'hidden') return
975
+ void poller.pollOnce().catch(() => undefined)
976
+ }
977
+ window.addEventListener('focus', wake)
978
+ document.addEventListener('visibilitychange', wake)
979
+ stopWake = () => {
980
+ window.removeEventListener('focus', wake)
981
+ document.removeEventListener('visibilitychange', wake)
982
+ }
983
+ },
984
+ stop() {
985
+ stopWake?.()
986
+ stopWake = undefined
987
+ poller.stop()
988
+ },
989
+ dispose() {
990
+ if (disposed) return
991
+ clearRevealHint()
992
+ stopWake?.()
993
+ stopWake = undefined
994
+ poller.dispose()
995
+ revealer.dispose()
996
+ queue.dispose()
997
+ for (const store of stores.values()) store.dispose()
998
+ for (const assetStore of assets.values()) assetStore.dispose()
999
+ stores.clear()
1000
+ assets.clear()
1001
+ disposed = true
1002
+ sourceOpening?.abort()
1003
+ },
1004
+ get disposed() { return disposed },
1005
+ poller,
1006
+ cancellation,
1007
+ cards() {
1008
+ return snapshot().cards
1009
+ },
1010
+ snapshot,
1011
+ subscribe(listener) {
1012
+ if (disposed) return () => {}
1013
+ listeners.add(listener)
1014
+ return () => { listeners.delete(listener) }
1015
+ },
1016
+ availability() {
1017
+ return availabilityOf(poller.lastError)
1018
+ },
1019
+ ownerFor,
1020
+ setComment(referenceId, comment) {
1021
+ if (disposed) return false
1022
+ for (const store of stores.values()) {
1023
+ if (store.state().reflections.some(entry => entry.referenceId === referenceId)) {
1024
+ const changed = store.setComment(referenceId, comment)
1025
+ if (changed) { markDirty(); publish() }
1026
+ return changed
1027
+ }
1028
+ }
1029
+ // A card that was never materialised in a live store (recovered later).
1030
+ return false
1031
+ },
1032
+ async removeCard(referenceId) {
1033
+ const store = draftStoreFor(current)
1034
+ if (!store.state().reflections.some(entry => entry.referenceId === referenceId)) return
1035
+ removeReferences(current, [referenceId])
1036
+ },
1037
+ revealReference,
1038
+ setSourceOpener(opener) { sourceOpener = opener },
1039
+ referenceDetail,
1040
+ activateUri,
1041
+ revealer,
1042
+ exportBundle(format, sessionId) {
1043
+ return http.exportBundle(format, sessionId ?? current)
1044
+ },
1045
+ importBundle(zip) { return http.importBundle(zip) },
1046
+ draftState(sessionId) { return draftStoreFor(sessionId ?? current).state() },
1047
+ assetStore(sessionId) { return assetStoreFor(sessionId ?? current) },
1048
+ }
1049
+
1050
+ return runtime
1051
+ }
1052
+
1053
+ /** Recover an intent id from the queue's persisted deliveries by referenceId. */
1054
+ function findIntentId(queue: DeliveryQueue, referenceId: string): string | undefined {
1055
+ return queue.snapshot().find(delivery => delivery.referenceId === referenceId)?.intentId
1056
+ }