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