dsh-builtin-browser 1.0.0 → 1.0.3
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 +61 -0
- package/README.md +1 -1
- package/assets/browser-panel-locales.mjs +37 -5
- package/assets/browser-policy.d.mts +29 -0
- package/assets/browser-policy.mjs +40 -0
- package/desktop-bridge/desktop-discovery.d.mts +1 -1
- package/desktop-bridge/desktop-discovery.mjs +59 -9
- package/desktop-bridge/desktop-identity.json +12 -0
- package/desktop-bridge/install.mjs +14 -7
- package/desktop-bridge/plugin-browser-bridge.js +19 -7
- package/docs/acceptance-2026-11-27.md +67 -0
- package/docs/architecture.md +1 -1
- package/docs/development.md +33 -4
- package/docs/dsh-0.2.3-host-patch-task.md +34 -0
- package/docs/hardcoding-audit.md +28 -8
- package/docs/known-issues.md +26 -0
- package/docs/limitations.md +6 -2
- package/docs/pr64-maintenance.md +1 -1
- package/docs/tool-reference.md +1 -1
- package/docs/user-guide.md +1 -1
- package/docs/v1.1.0-bu-data-batching-task.md +66 -0
- package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
- package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
- package/dsh-builtin-browser-1.0.3.tgz +0 -0
- package/dsh-host-patch/README.md +4 -0
- package/dsh-host-patch/apply.mjs +61 -13
- package/dsh-host-patch/rc3-revision9.json.gz +0 -0
- package/dsh-host-patch/rc5-revision9.json.gz +0 -0
- package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/manifest.json +218 -0
- package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/series.json +260 -0
- package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
- package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
- package/dsh-host-patch/tauri-revision1.json +39 -0
- package/dsh-host-patch/tauri.json +43 -0
- package/dsh-host-patch/v023-alpha2.json +153 -0
- package/lib/browser/anti-bot.js +215 -0
- package/lib/browser/deep-dom.js +39 -0
- package/lib/browser/runtime.js +15 -0
- package/lib/browser/takeover-target.js +13 -6
- package/lib/browser/types.js +30 -1
- package/lib/browser-electron/authenticated-route.js +16 -2
- package/lib/browser-electron/automatic-maintenance.js +16 -10
- package/lib/browser-electron/bridge-connection.js +3 -8
- package/lib/browser-electron/bridge-install.js +2 -1
- package/lib/browser-electron/bridge-status.js +55 -26
- package/lib/browser-electron/desktop-bridge-host.js +7 -6
- package/lib/browser-electron/desktop-identity.js +28 -5
- package/lib/browser-electron/desktop-shell.js +64 -0
- package/lib/browser-electron/electron-provision.js +105 -18
- package/lib/browser-electron/entry.js +129 -46
- package/lib/browser-electron/extension-browser.js +4 -4
- package/lib/browser-electron/foreground-watch.js +134 -0
- package/lib/browser-electron/guest-cookie-jar.js +13 -13
- package/lib/browser-electron/guest-route.js +181 -32
- package/lib/browser-electron/guest-runtime.js +61 -10
- package/lib/browser-electron/guest-storage.js +2 -2
- package/lib/browser-electron/history-store.js +1 -5
- package/lib/browser-electron/host-main.js +8 -4
- package/lib/browser-electron/host-patch-maintenance.js +14 -8
- package/lib/browser-electron/maintenance-route.js +2 -1
- package/lib/browser-electron/missing-system-browser.js +5 -9
- package/lib/browser-electron/preferred-browser.js +7 -3
- package/lib/browser-electron/preview-route.js +9 -13
- package/lib/browser-electron/process-ownership.js +1 -1
- package/lib/browser-electron/profile-command.js +2 -1
- package/lib/browser-electron/profile-extension.js +5 -0
- package/lib/browser-electron/profile-lease.js +152 -47
- package/lib/browser-electron/provider-core.js +527 -0
- package/lib/browser-electron/provider-interaction.js +963 -0
- package/lib/browser-electron/provider-media.js +518 -0
- package/lib/browser-electron/provider-navigation.js +301 -0
- package/lib/browser-electron/provider-observation.js +623 -0
- package/lib/browser-electron/provider-tabs.js +372 -0
- package/lib/browser-electron/provider.js +150 -3301
- package/lib/browser-electron/reference-route.js +9 -18
- package/lib/browser-electron/remote-host.js +79 -34
- package/lib/browser-electron/runtime-status.js +56 -6
- package/lib/browser-electron/settings-store.js +3 -6
- package/lib/browser-electron/sidebar-only-host.js +1 -1
- package/lib/browser-electron/system-browser.js +539 -172
- package/lib/browser-electron/tauri-host.js +208 -0
- package/lib/browser-electron/virtual-cursor.js +23 -13
- package/lib/browser-reference/service.js +22 -4
- package/lib/browser-reference/web-sources.js +1 -1
- package/lib/client.js +43409 -0
- package/lib/compat/host-features.js +75 -0
- package/lib/reference-source.js +1 -1
- package/lib/reference-text.js +23 -1
- package/lib/takeover-protocol.js +1 -1
- package/lib/tool-browser/block-recovery.js +69 -0
- package/lib/tool-browser/code-tool.js +170 -19
- package/lib/tool-browser/code-worker.js +115 -20
- package/lib/tool-browser/errors.js +34 -0
- package/lib/tool-browser/index.js +66 -3593
- package/lib/tool-browser/page-probe.js +227 -28
- package/lib/tool-browser/panel-page.js +2 -1
- package/lib/tool-browser/probe-client.js +157 -0
- package/lib/tool-browser/screenshot-annotations.js +108 -0
- package/lib/tool-browser/state.js +337 -0
- package/lib/tool-browser/takeover.js +1 -1
- package/lib/tool-browser/tools-debug.js +862 -0
- package/lib/tool-browser/tools-interaction.js +993 -0
- package/lib/tool-browser/tools-navigation.js +807 -0
- package/lib/tool-browser/tools-observation.js +461 -0
- package/lib/tool-browser/tools-reference.js +293 -0
- package/lib/web-guest.js +1 -0
- package/package.json +16 -54
- package/README.en.md +0 -89
- package/browser-extension/constants.mjs +0 -20
- package/browser-extension/controller.mjs +0 -293
- package/browser-extension/locales.mjs +0 -15
- package/browser-extension/manifest.json +0 -12
- package/browser-extension/options.html +0 -14
- package/browser-extension/options.mjs +0 -9
- package/browser-extension/permission-guard.mjs +0 -13
- package/browser-extension/worker.mjs +0 -74
- package/dist/client.cjs +0 -43167
- package/lib/browser-electron/package-removal.js +0 -5
- package/lib/browser-reference/submission-receipts.js +0 -139
- package/scripts/build.mjs +0 -66
- package/scripts/bundle-host.mjs +0 -28
- package/scripts/fix-exports.mjs +0 -50
- package/scripts/install-electron.mjs +0 -51
- package/scripts/verify-exports.mjs +0 -47
- package/scripts/verify-preview-sdk.mjs +0 -93
- package/skills/dsh-builtin-browser/SKILL.md +0 -73
- package/skills/dsh-builtin-browser/references/batch.md +0 -53
- package/skills/dsh-builtin-browser/references/deliver.md +0 -31
- package/skills/dsh-builtin-browser/references/locate.md +0 -11
- package/skills/dsh-builtin-browser/references/recover.md +0 -11
- package/skills/dsh-builtin-browser/references/verify.md +0 -13
- package/skills/dsh-debug-host/SKILL.md +0 -56
- package/skills/dsh-debug-self/SKILL.md +0 -50
- package/src/bridge-compatibility.ts +0 -39
- package/src/browser/handles.ts +0 -89
- package/src/browser/runtime.ts +0 -560
- package/src/browser/takeover-target.ts +0 -36
- package/src/browser/types.ts +0 -817
- package/src/browser-electron/authenticated-route.ts +0 -84
- package/src/browser-electron/automatic-maintenance.ts +0 -726
- package/src/browser-electron/bridge-auto.ts +0 -159
- package/src/browser-electron/bridge-connection.ts +0 -385
- package/src/browser-electron/bridge-endpoint.ts +0 -129
- package/src/browser-electron/bridge-install.ts +0 -289
- package/src/browser-electron/bridge-maintenance.ts +0 -189
- package/src/browser-electron/bridge-status.ts +0 -347
- package/src/browser-electron/desktop-bridge-host.ts +0 -251
- package/src/browser-electron/desktop-identity.ts +0 -320
- package/src/browser-electron/document-readiness.ts +0 -45
- package/src/browser-electron/electron-provision.ts +0 -261
- package/src/browser-electron/entry.ts +0 -1301
- package/src/browser-electron/ephemeral-profile.ts +0 -189
- package/src/browser-electron/extension-browser.ts +0 -223
- package/src/browser-electron/extension-setup.ts +0 -67
- package/src/browser-electron/file-write.ts +0 -31
- package/src/browser-electron/guest-cookie-jar.ts +0 -176
- package/src/browser-electron/guest-cookie-store.ts +0 -59
- package/src/browser-electron/guest-css-runtime.ts +0 -76
- package/src/browser-electron/guest-css.ts +0 -68
- package/src/browser-electron/guest-route.ts +0 -568
- package/src/browser-electron/guest-runtime.ts +0 -357
- package/src/browser-electron/guest-storage-runtime.ts +0 -54
- package/src/browser-electron/guest-storage.ts +0 -117
- package/src/browser-electron/history-store.ts +0 -227
- package/src/browser-electron/host-main.ts +0 -1381
- package/src/browser-electron/host-patch-maintenance.ts +0 -112
- package/src/browser-electron/http-body.ts +0 -65
- package/src/browser-electron/json-reply.ts +0 -47
- package/src/browser-electron/maintenance-broker.ts +0 -166
- package/src/browser-electron/maintenance-lifecycle.ts +0 -91
- package/src/browser-electron/maintenance-route.ts +0 -67
- package/src/browser-electron/missing-system-browser.ts +0 -113
- package/src/browser-electron/open-slot.ts +0 -49
- package/src/browser-electron/package-removal.ts +0 -4
- package/src/browser-electron/paths.ts +0 -25
- package/src/browser-electron/preferred-browser.ts +0 -120
- package/src/browser-electron/preview-route.ts +0 -218
- package/src/browser-electron/process-ownership.ts +0 -168
- package/src/browser-electron/process.ts +0 -23
- package/src/browser-electron/profile-checkpoint.ts +0 -187
- package/src/browser-electron/profile-command.ts +0 -46
- package/src/browser-electron/profile-extension.ts +0 -124
- package/src/browser-electron/profile-lease.ts +0 -115
- package/src/browser-electron/profile-residue.ts +0 -49
- package/src/browser-electron/provider.ts +0 -4571
- package/src/browser-electron/reference-route.ts +0 -608
- package/src/browser-electron/remote-host.ts +0 -1462
- package/src/browser-electron/rpc-input.ts +0 -13
- package/src/browser-electron/rpc-ops.ts +0 -41
- package/src/browser-electron/runtime-diagnostics.ts +0 -38
- package/src/browser-electron/runtime-route.ts +0 -105
- package/src/browser-electron/runtime-status.ts +0 -242
- package/src/browser-electron/settings-route.ts +0 -64
- package/src/browser-electron/settings-store.ts +0 -589
- package/src/browser-electron/shortcuts-route.ts +0 -112
- package/src/browser-electron/sidebar-only-host.ts +0 -298
- package/src/browser-electron/startpage-shortcuts.ts +0 -213
- package/src/browser-electron/system-browser.ts +0 -1497
- package/src/browser-electron/timing.ts +0 -16
- package/src/browser-electron/virtual-cursor.ts +0 -152
- package/src/browser-electron/windows-system.ts +0 -24
- package/src/browser-reference/delivery.ts +0 -384
- package/src/browser-reference/entry.ts +0 -631
- package/src/browser-reference/export.ts +0 -339
- package/src/browser-reference/import.ts +0 -303
- package/src/browser-reference/page-script.ts +0 -1537
- package/src/browser-reference/service.ts +0 -1315
- package/src/browser-reference/store.ts +0 -172
- package/src/browser-reference/submission-receipts.ts +0 -122
- package/src/browser-reference/text-quote.ts +0 -219
- package/src/browser-reference/types.ts +0 -195
- package/src/browser-reference/visible.ts +0 -367
- package/src/browser-reference/web-sources.ts +0 -103
- package/src/client/browser/BrowserController.ts +0 -693
- package/src/client/browser/BrowserFrame.ts +0 -78
- package/src/client/browser/BrowserNavigation.ts +0 -169
- package/src/client/browser/BrowserPage.ts +0 -23
- package/src/client/browser/BrowserPersistence.ts +0 -44
- package/src/client/browser/IframeImpl.ts +0 -176
- package/src/client/browser/child-tabs.ts +0 -14
- package/src/client/browser/iframe-reference.ts +0 -67
- package/src/client/browser/initialization.ts +0 -262
- package/src/client/browser/omnibox.ts +0 -243
- package/src/client/browser/store.ts +0 -38
- package/src/client/browser/takeover-channel.ts +0 -72
- package/src/client/browser/url.ts +0 -46
- package/src/client/browser/web-reference-source.ts +0 -52
- package/src/client/css-modules.d.ts +0 -4
- package/src/client/definition.tsx +0 -30
- package/src/client/electron/ElectronWebViewImpl.ts +0 -364
- package/src/client/electron/ElectronWebviewPresentation.ts +0 -138
- package/src/client/electron/NativeChildPresentation.ts +0 -45
- package/src/client/electron/NativeViewPage.ts +0 -251
- package/src/client/electron/pages.ts +0 -23
- package/src/client/electron/reference-overlay.ts +0 -53
- package/src/client/electron/workspace.ts +0 -33
- package/src/client/index.ts +0 -293
- package/src/client/locales.ts +0 -857
- package/src/client/pages.ts +0 -28
- package/src/client/reference/client/BrowserRefLink.tsx +0 -142
- package/src/client/reference/client/draft-reference.ts +0 -167
- package/src/client/reference/client/index.ts +0 -7
- package/src/client/reference/client/ordered-submission.ts +0 -108
- package/src/client/reference/client/pending-delivery.ts +0 -216
- package/src/client/reference/client/plugin.ts +0 -189
- package/src/client/reference/client/production/ReferenceCapsules.tsx +0 -345
- package/src/client/reference/client/production/ReferenceDock.module.css +0 -193
- package/src/client/reference/client/production/ReferenceDock.tsx +0 -6
- package/src/client/reference/client/production/ReferenceFeedback.tsx +0 -15
- package/src/client/reference/client/production/ReferenceMath.tsx +0 -44
- package/src/client/reference/client/production/ReferenceText.tsx +0 -36
- package/src/client/reference/client/production/assembly.ts +0 -471
- package/src/client/reference/client/production/asset-store.ts +0 -144
- package/src/client/reference/client/production/availability.ts +0 -74
- package/src/client/reference/client/production/bytes.ts +0 -36
- package/src/client/reference/client/production/delivery-client.ts +0 -211
- package/src/client/reference/client/production/draft-adapter.ts +0 -508
- package/src/client/reference/client/production/http-transport.ts +0 -217
- package/src/client/reference/client/production/production-submission.ts +0 -310
- package/src/client/reference/client/production/protocol.ts +0 -231
- package/src/client/reference/client/production/reference-card.ts +0 -240
- package/src/client/reference/client/production/reference-labels.ts +0 -29
- package/src/client/reference/client/production/reply-link-bridge.ts +0 -222
- package/src/client/reference/client/production/reveal.ts +0 -215
- package/src/client/reference/client/production/runtime.ts +0 -1101
- package/src/client/reference/client/production/snapshot-adapter.ts +0 -154
- package/src/client/reference/client/production/source-marker.ts +0 -63
- package/src/client/reference/client/production/source-opener.ts +0 -55
- package/src/client/reference/client/production/styles.ts +0 -104
- package/src/client/reference/client/production/user-text-rule.ts +0 -58
- package/src/client/reference/client/reveal.ts +0 -107
- package/src/client/reference/client/scheme.ts +0 -114
- package/src/client/reference/client/types.ts +0 -168
- package/src/client/reference/css-modules.d.ts +0 -4
- package/src/client/reference/index.ts +0 -11
- package/src/client/reference-capture-owner.ts +0 -162
- package/src/client/reference-intents.ts +0 -36
- package/src/client/settings/index.ts +0 -34
- package/src/client/settings/panel.ts +0 -2657
- package/src/client/shortcut-open.ts +0 -30
- package/src/client/startpage/binding.ts +0 -99
- package/src/client/startpage/controller.ts +0 -303
- package/src/client/startpage/model.ts +0 -279
- package/src/client/view/Browser.module.css +0 -751
- package/src/client/view/BrowserBody.tsx +0 -314
- package/src/client/view/BrowserPresentation.ts +0 -9
- package/src/client/view/BrowserTitle.tsx +0 -17
- package/src/client/view/IframePresentation.ts +0 -344
- package/src/client/view/StartPage.tsx +0 -597
- package/src/client/view/TakeoverBanner.tsx +0 -21
- package/src/index.ts +0 -110
- package/src/reference-owner.ts +0 -5
- package/src/reference-page.ts +0 -9
- package/src/reference-source.ts +0 -3
- package/src/reference-text.ts +0 -197
- package/src/startpage-settings.ts +0 -103
- package/src/startpage.ts +0 -71
- package/src/takeover-protocol.ts +0 -19
- package/src/tool-browser/code-tool.ts +0 -401
- package/src/tool-browser/code-worker.ts +0 -639
- package/src/tool-browser/element-fields.ts +0 -167
- package/src/tool-browser/index.ts +0 -3733
- package/src/tool-browser/page-probe.ts +0 -474
- package/src/tool-browser/panel-page.ts +0 -124
- package/src/tool-browser/screenshot-image.ts +0 -49
- package/src/tool-browser/takeover.ts +0 -198
- package/src/types/electron-shim.d.ts +0 -144
- package/src/types.ts +0 -85
- package/src/web-guest.ts +0 -34
- package/tools/accept-desktop.mjs +0 -148
|
@@ -1,726 +0,0 @@
|
|
|
1
|
-
import { BROWSER_PROFILE_DIR } from '../../assets/browser-policy.mjs'
|
|
2
|
-
/** User-requested Desktop maintenance (Windows and macOS), coordinated outside the Desktop process tree. */
|
|
3
|
-
import { execFile, spawn } from 'node:child_process'
|
|
4
|
-
import * as fs from 'node:fs'
|
|
5
|
-
import { existsSync, readFileSync } from 'node:fs'
|
|
6
|
-
import { cp, mkdir, open, readFile, stat as statAsync, unlink, writeFile } from 'node:fs/promises'
|
|
7
|
-
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
8
|
-
import { fileURLToPath } from 'node:url'
|
|
9
|
-
import { prepareBridgeMaintenance } from './bridge-maintenance.ts'
|
|
10
|
-
import { launchMaintenanceBroker, type MaintenanceBrokerOptions, type MaintenanceBrokerResult } from './maintenance-broker.ts'
|
|
11
|
-
import { runMaintenanceLifecycle, type MaintenanceState } from './maintenance-lifecycle.ts'
|
|
12
|
-
import { defaultInstallerPath, runBridgeAction, waitForRestartedBridge, type BridgeActionResult, type HostPatchResult } from './bridge-install.ts'
|
|
13
|
-
import { desktopLayout, desktopPaths, readAsarFile, readDesktopIdentity } from './desktop-identity.ts'
|
|
14
|
-
import { dshHome } from './paths.ts'
|
|
15
|
-
import { encodePowerShellScript, windowsPowerShellPath } from './windows-system.ts'
|
|
16
|
-
import { renameMaintenanceFile } from '../../desktop-bridge/maintenance-files.mjs'
|
|
17
|
-
import { isDesktopExecutable } from '../../desktop-bridge/desktop-processes.mjs'
|
|
18
|
-
import { installedProfileExtension, repairProfileExtension, reconcileProfile, profileDependencySpec, profileRuntimeDirectory, MAIN_EXTENSION_NAME, type InstalledExtension } from './profile-extension.ts'
|
|
19
|
-
import { withProfileCheckpoint } from './profile-checkpoint.ts'
|
|
20
|
-
import { runProfileCommand } from './profile-command.ts'
|
|
21
|
-
import { cleanProfileResidue, inspectProfileResidue } from './profile-residue.ts'
|
|
22
|
-
|
|
23
|
-
const { hostPatchStatus }: { hostPatchStatus: (packages: readonly string[], options?: { fs: object }) => HostPatchResult } = await import(new URL('../../dsh-host-patch/apply.mjs', import.meta.url).href)
|
|
24
|
-
const { stripLegacyBridge }: { stripLegacyBridge: (text: string) => string | undefined } = await import(new URL('../../dsh-host-patch/legacy-bridge.mjs', import.meta.url).href)
|
|
25
|
-
|
|
26
|
-
interface DesktopProcess { readonly pid: number; readonly path: string; readonly command: string; readonly started: string }
|
|
27
|
-
export interface AutomaticMaintenanceJob extends MaintenanceState { readonly id: string; readonly workerPid?: number; readonly startedAt?: string }
|
|
28
|
-
export interface AutomaticMaintenanceOptions {
|
|
29
|
-
readonly locale?: 'zh' | 'en'
|
|
30
|
-
}
|
|
31
|
-
interface AutomaticPlan {
|
|
32
|
-
readonly version: 1
|
|
33
|
-
readonly id: string
|
|
34
|
-
readonly action: 'reinstall'
|
|
35
|
-
readonly root: string
|
|
36
|
-
readonly nodePath: string
|
|
37
|
-
readonly electronNode: boolean
|
|
38
|
-
readonly home: string
|
|
39
|
-
readonly directory: string
|
|
40
|
-
readonly target: DesktopProcess
|
|
41
|
-
readonly createdAt: string
|
|
42
|
-
readonly locale?: 'zh' | 'en'
|
|
43
|
-
readonly dependency: string
|
|
44
|
-
readonly nestedResidue?: readonly string[]
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export class ReinstallPreflightError extends Error {
|
|
48
|
-
constructor(readonly code: string, message: string) { super(message) }
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function archiveExists(path: string): boolean {
|
|
52
|
-
const runtime = process as NodeJS.Process & { noAsar?: boolean }
|
|
53
|
-
const previous = runtime.noAsar
|
|
54
|
-
runtime.noAsar = true
|
|
55
|
-
try { return existsSync(path) } finally { runtime.noAsar = previous }
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function patchDirectories(root: string): string[] {
|
|
59
|
-
const app = join(desktopPaths(root).resources, 'app')
|
|
60
|
-
return [app, join(app, 'dsh', 'node_modules', '@deepseek-ai', 'dsh-client-ui-sidebar-right')]
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
function validateCliBackup(path: string, kind: 'host' | 'shim'): void {
|
|
64
|
-
const backup = path + '.before-bridge'
|
|
65
|
-
if (!existsSync(backup)) return
|
|
66
|
-
if (![path, backup].every(file => fs.lstatSync(file).isFile() && !fs.lstatSync(file).isSymbolicLink())) {
|
|
67
|
-
throw new ReinstallPreflightError('REINSTALL_BACKUP_CONFLICT', 'A CLI restore baseline is not a regular file.')
|
|
68
|
-
}
|
|
69
|
-
const original = readFileSync(backup, 'utf8'), current = readFileSync(path, 'utf8')
|
|
70
|
-
if (current === original) return
|
|
71
|
-
const eol = original.includes('\r\n') ? '\r\n' : '\n'
|
|
72
|
-
let expected: string
|
|
73
|
-
if (kind === 'host') {
|
|
74
|
-
const call = /^(\t)await runDesktopCli\(((?:runtimeDir, )?)join\(dirname\(runtimeArchivePath\(runtimeDir\) \?\? runtimeDir\), "runtime"\)\);$/m.exec(original)
|
|
75
|
-
if (call === null) throw new ReinstallPreflightError('REINSTALL_BACKUP_CONFLICT', 'The CLI differs from its recognized restore baseline.')
|
|
76
|
-
expected = original.replace(call[0], () => [
|
|
77
|
-
'\t// dsh-builtin-browser: recognize an unpacked `app` directory as the app root,',
|
|
78
|
-
'\t// so an installation whose app.asar was moved aside still finds its runtime.',
|
|
79
|
-
'\tconst cliOwnerDir = dirname(runtimeDir);',
|
|
80
|
-
'\tconst cliSupportRoot = basename(cliOwnerDir) === "app" || basename(cliOwnerDir) === "app.asar" ? dirname(cliOwnerDir) : cliOwnerDir;',
|
|
81
|
-
`\tawait runDesktopCli(${call[2]}join(cliSupportRoot, "runtime"));`,
|
|
82
|
-
].join(eol))
|
|
83
|
-
} else {
|
|
84
|
-
const injection = [
|
|
85
|
-
'rem dsh-builtin-browser: resolve the app directory (resources\\app when the bridge is installed,',
|
|
86
|
-
'rem resources\\app.asar on a stock installation).',
|
|
87
|
-
'set "DSH_APP=%~dp0..\\..\\..\\app"',
|
|
88
|
-
'if not exist "%DSH_APP%\\dsh\\node_modules\\@deepseek-ai\\dsh-desktop-host\\lib\\cli.js" set "DSH_APP=%~dp0..\\..\\..\\app.asar"',
|
|
89
|
-
].join(eol)
|
|
90
|
-
const setLocal = /^.*setlocal.*$/m.exec(original)
|
|
91
|
-
expected = (setLocal === null ? injection + eol + original : original.replace(setLocal[0], () => setLocal[0] + eol + injection))
|
|
92
|
-
.replace(/%~dp0(?:\.\.\\)+app\.asar\\dsh\\/, () => '%DSH_APP%\\dsh\\')
|
|
93
|
-
}
|
|
94
|
-
if (current !== expected) throw new ReinstallPreflightError('REINSTALL_BACKUP_CONFLICT', 'The CLI differs from its recognized restore baseline.')
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** Inspect the archive Electron will load, never a leftover extraction beside it. */
|
|
98
|
-
export function inspectReinstallHost(root: string): ReturnType<typeof hostPatchStatus> {
|
|
99
|
-
const identity = readDesktopIdentity(root)
|
|
100
|
-
if (!identity.ok) throw new ReinstallPreflightError('REINSTALL_DESKTOP_INVALID', identity.reason)
|
|
101
|
-
const archive = join(desktopPaths(root).resources, 'app.asar')
|
|
102
|
-
if (archiveExists(archive) && existsSync(archive + '.before-bridge')) {
|
|
103
|
-
throw new ReinstallPreflightError('REINSTALL_BACKUP_CONFLICT', 'Both the Desktop archive and its restore baseline exist.')
|
|
104
|
-
}
|
|
105
|
-
if (identity.layout === 'unpacked') return hostPatchStatus(patchDirectories(root))
|
|
106
|
-
const app = patchDirectories(root)[0]!
|
|
107
|
-
const archiveFile = (path: fs.PathLike): Buffer | undefined => readAsarFile(archive, relative(app, String(path)).split('\\').join('/'))
|
|
108
|
-
const snapshot = {
|
|
109
|
-
...fs,
|
|
110
|
-
realpathSync: (path: fs.PathLike) => resolve(String(path)),
|
|
111
|
-
readFileSync: (path: fs.PathLike) => {
|
|
112
|
-
const content = archiveFile(path)
|
|
113
|
-
if (content === undefined) throw new Error(`Missing or unreadable archive entry: ${relative(app, String(path))}`)
|
|
114
|
-
return content.toString('utf8')
|
|
115
|
-
},
|
|
116
|
-
existsSync: (path: fs.PathLike) => archiveFile(path) !== undefined,
|
|
117
|
-
lstatSync: () => ({ isFile: () => true, isSymbolicLink: () => false }),
|
|
118
|
-
statSync: () => ({ mode: 0o644 }),
|
|
119
|
-
}
|
|
120
|
-
return hostPatchStatus(patchDirectories(root), { fs: snapshot })
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/** Entirely read-only: a missing dependency never creates a lock, plan or replacement source. */
|
|
124
|
-
export async function preflightReinstall(root: string, home: string): Promise<string> {
|
|
125
|
-
let dependency: string
|
|
126
|
-
try { dependency = await profileDependencySpec(home) } catch (error) {
|
|
127
|
-
if ((error as NodeJS.ErrnoException).code === 'ENOENT') throw new ReinstallPreflightError('REINSTALL_DEPENDENCY_MISSING', 'The Desktop profile has no dependency specification to reinstall.')
|
|
128
|
-
throw error
|
|
129
|
-
}
|
|
130
|
-
if (/^(?:file|link):/.test(dependency)) {
|
|
131
|
-
const path = resolve(home, 'profiles', 'desktop', dependency.slice(dependency.indexOf(':') + 1))
|
|
132
|
-
try { fs.accessSync(path, fs.constants.R_OK) } catch {
|
|
133
|
-
throw new ReinstallPreflightError('REINSTALL_DEPENDENCY_UNAVAILABLE', 'The captured local dependency source is not readable.')
|
|
134
|
-
}
|
|
135
|
-
const installed = join(home, 'profiles', 'desktop', 'node_modules', MAIN_EXTENSION_NAME)
|
|
136
|
-
if (existsSync(installed)) {
|
|
137
|
-
const source = fs.realpathSync(path)
|
|
138
|
-
const owner = fs.lstatSync(installed).isSymbolicLink() ? resolve(home, 'profiles', 'desktop', 'node_modules') : fs.realpathSync(installed)
|
|
139
|
-
if (source === owner || inside(owner, source)) throw new ReinstallPreflightError('REINSTALL_DEPENDENCY_UNSAFE', 'The captured dependency source would be deleted by plugin removal.')
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
await inspectProfileResidue(home)
|
|
143
|
-
const status = inspectReinstallHost(root)
|
|
144
|
-
if (status.status !== 'absent' && status.status !== 'applied') throw new ReinstallPreflightError('REINSTALL_HOST_CONFLICT', status.reason ?? status.status)
|
|
145
|
-
const cli = 'dsh/node_modules/@deepseek-ai/dsh-desktop-host/lib/cli.js'
|
|
146
|
-
const archive = join(desktopPaths(root).resources, 'app.asar')
|
|
147
|
-
if (status.status === 'applied' && (archiveExists(archive) || ![
|
|
148
|
-
join(desktopPaths(root).resources, 'app', 'lib', 'main.js'), join(desktopPaths(root).resources, 'app', 'lib', 'preload-app.cjs'),
|
|
149
|
-
join(patchDirectories(root)[1]!, 'lib', 'client.js'),
|
|
150
|
-
].every(path => existsSync(path + '.before-dsh-host-patch')))) {
|
|
151
|
-
throw new ReinstallPreflightError('REINSTALL_BACKUP_CONFLICT', 'An applied host patch has no usable external restore baseline.')
|
|
152
|
-
}
|
|
153
|
-
if (archiveExists(archive) ? readAsarFile(archive, cli) === undefined : !existsSync(join(desktopPaths(root).resources, 'app', cli))) {
|
|
154
|
-
throw new ReinstallPreflightError('REINSTALL_CLI_MISSING', 'The authoritative Desktop CLI is missing or unreadable.')
|
|
155
|
-
}
|
|
156
|
-
validateCliBackup(join(desktopPaths(root).resources, 'runtime', 'cli', 'bin', 'dsh.cmd'), 'shim')
|
|
157
|
-
if (!archiveExists(archive)) validateCliBackup(join(desktopPaths(root).resources, 'app', cli), 'host')
|
|
158
|
-
const main = join(desktopPaths(root).resources, 'app', 'lib', 'main.js')
|
|
159
|
-
if (!archiveExists(join(desktopPaths(root).resources, 'app.asar')) && existsSync(main + '.before-bridge')) {
|
|
160
|
-
const original = readFileSync(main + '.before-bridge', 'utf8')
|
|
161
|
-
const current = readFileSync(existsSync(main + '.before-dsh-host-patch') ? main + '.before-dsh-host-patch' : main, 'utf8')
|
|
162
|
-
if ((stripLegacyBridge(current) ?? current) !== original) {
|
|
163
|
-
throw new ReinstallPreflightError('REINSTALL_BACKUP_CONFLICT', 'The legacy bridge differs from its restore baseline.')
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
if (!archiveExists(archive) && existsSync(archive + '.before-bridge')) {
|
|
167
|
-
const preserved = readAsarFile(archive + '.before-bridge', 'lib/main.js')
|
|
168
|
-
const current = readFileSync(existsSync(main + '.before-dsh-host-patch') ? main + '.before-dsh-host-patch' : main, 'utf8')
|
|
169
|
-
if (preserved === undefined || preserved.toString('utf8') !== (stripLegacyBridge(current) ?? current)) {
|
|
170
|
-
throw new ReinstallPreflightError('REINSTALL_BACKUP_CONFLICT', 'The preserved archive belongs to different Desktop bytes.')
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
await profileRuntimeDirectory(root)
|
|
174
|
-
return dependency
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
/** Copy only shipped runtime files; the running worker and installer survive profile removal. */
|
|
178
|
-
export async function stageReinstallRuntime(directory: string, source = fileURLToPath(new URL('../../', import.meta.url))): Promise<string> {
|
|
179
|
-
const destination = join(directory, 'runtime')
|
|
180
|
-
const packageDirectory = fs.realpathSync(source)
|
|
181
|
-
const parent = fs.realpathSync(directory)
|
|
182
|
-
if (parent === packageDirectory || inside(packageDirectory, parent)) throw new Error('Reinstall runtime must be staged outside the removed package')
|
|
183
|
-
await mkdir(destination, { mode: 0o700 })
|
|
184
|
-
for (const name of ['lib', 'assets', 'desktop-bridge', 'dsh-host-patch', 'package.json']) {
|
|
185
|
-
await cp(join(packageDirectory, name), join(destination, name), { recursive: true, dereference: true, errorOnExist: true, force: false })
|
|
186
|
-
}
|
|
187
|
-
return join(destination, 'lib', 'browser-electron', 'automatic-maintenance.js')
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
export interface ReinstallSteps {
|
|
191
|
-
readonly remove: () => Promise<BridgeActionResult>
|
|
192
|
-
readonly absent: () => Promise<boolean>
|
|
193
|
-
readonly revert: () => Promise<BridgeActionResult>
|
|
194
|
-
readonly hostAbsent: () => boolean
|
|
195
|
-
readonly apply: () => Promise<BridgeActionResult>
|
|
196
|
-
readonly add: () => Promise<BridgeActionResult>
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/** Called under the automatic job lock, only after the closed-process barrier. */
|
|
200
|
-
export async function runReinstallTransaction(steps: ReinstallSteps): Promise<BridgeActionResult> {
|
|
201
|
-
const removed = await steps.absent() ? undefined : await steps.remove()
|
|
202
|
-
if (removed && !removed.ok) throw new Error(`REINSTALL_REMOVE_FAILED: ${removed.output}`)
|
|
203
|
-
if (!await steps.absent()) throw new Error('REINSTALL_REMOVE_FAILED: profile dependency remains installed')
|
|
204
|
-
const wasAbsent = steps.hostAbsent()
|
|
205
|
-
const reverted = await steps.revert()
|
|
206
|
-
if (!reverted.ok && !(wasAbsent && steps.hostAbsent() && reverted.code === 1 && /^nothing to revert in /m.test(reverted.output)
|
|
207
|
-
&& !/error|refus|incomplete|EACCES|EPERM/i.test(reverted.output))) throw new Error(`REINSTALL_REVERT_FAILED: ${reverted.output}`)
|
|
208
|
-
if (!steps.hostAbsent()) throw new Error('REINSTALL_REVERT_FAILED: host patch is still present')
|
|
209
|
-
const applied = await steps.apply()
|
|
210
|
-
if (!applied.ok || applied.hostPatch?.status !== 'applied') throw new Error(`REINSTALL_APPLY_FAILED: ${applied.output}`)
|
|
211
|
-
const added = await steps.add()
|
|
212
|
-
if (!added.ok) throw new Error(`REINSTALL_ADD_FAILED: ${added.output}`)
|
|
213
|
-
return { ...added, hostPatch: applied.hostPatch, output: [removed?.output, reverted.output, applied.output, added.output].filter(Boolean).join('\n').slice(-20_000) }
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
const terminal = new Set(['completed', 'failed', 'cancelled'])
|
|
217
|
-
const workerPath = fileURLToPath(new URL('./automatic-maintenance.js', import.meta.url))
|
|
218
|
-
const quitPath = fileURLToPath(new URL('../../desktop-bridge/request-desktop-quit.ps1', import.meta.url))
|
|
219
|
-
const progressPath = fileURLToPath(new URL('../../desktop-bridge/maintenance-progress.ps1', import.meta.url))
|
|
220
|
-
const delay = async (ms: number): Promise<void> => await new Promise(resolve => setTimeout(resolve, ms))
|
|
221
|
-
|
|
222
|
-
/** A swallowed maintenance write still deserves one line of diagnostics; it never changes the answer. */
|
|
223
|
-
function reportMaintenanceFailure(label: string, error: unknown): void {
|
|
224
|
-
console.error(`[dsh-browser maintenance] ${label}: ${String(error)}`)
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
function homePath(): string { return resolve(dshHome()) }
|
|
228
|
-
function basePath(home = homePath()): string { return join(home, BROWSER_PROFILE_DIR, 'maintenance') }
|
|
229
|
-
function inside(base: string, path: string): boolean {
|
|
230
|
-
const part = relative(base, path)
|
|
231
|
-
return part !== '' && !isAbsolute(part) && part !== '..' && !part.startsWith('..\\') && !part.startsWith('../')
|
|
232
|
-
}
|
|
233
|
-
/** Platforms whose Desktop can be quit, patched and reopened by the independent worker. */
|
|
234
|
-
export function automaticMaintenanceSupported(platform: NodeJS.Platform = process.platform): boolean {
|
|
235
|
-
return platform === 'win32' || platform === 'darwin'
|
|
236
|
-
}
|
|
237
|
-
/** Same-path comparison: case-insensitive on Windows, by on-disk spelling elsewhere (APFS may be either). */
|
|
238
|
-
function samePath(a: string, b: string): boolean {
|
|
239
|
-
return isDesktopExecutable(a, b)
|
|
240
|
-
}
|
|
241
|
-
function requireLiveDesktop(): void {
|
|
242
|
-
if (!automaticMaintenanceSupported()) throw new Error('automatic bridge maintenance requires DSH Desktop on Windows or macOS')
|
|
243
|
-
if (process.env.DSH_BROWSER_TEST === '1' || process.env.NODE_TEST_CONTEXT !== undefined) {
|
|
244
|
-
throw new Error('automatic Desktop maintenance is forbidden in a test process')
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
async function execute(command: string, args: readonly string[], timeout = 15_000, environment?: NodeJS.ProcessEnv): Promise<{ code: number; output: string; stdout: string }> {
|
|
248
|
-
return await new Promise(resolve => {
|
|
249
|
-
execFile(command, [...args], { windowsHide: true, shell: false, encoding: 'utf8', timeout, maxBuffer: 1_048_576,
|
|
250
|
-
...(environment === undefined ? {} : { env: environment }) }, (error, stdout, stderr) => {
|
|
251
|
-
resolve({ code: error === null ? 0 : typeof error.code === 'number' ? error.code : 1, output: `${stdout}\n${stderr}`.trim(), stdout })
|
|
252
|
-
})
|
|
253
|
-
})
|
|
254
|
-
}
|
|
255
|
-
/** The Desktop GUI process on macOS: `ps` gives pid, start time, executable path and argv. */
|
|
256
|
-
async function posixDesktopProcesses(root: string, includeBundleHelpers = false): Promise<DesktopProcess[]> {
|
|
257
|
-
const psEnv: NodeJS.ProcessEnv = { ...process.env, LC_ALL: 'C', LANG: 'C' }
|
|
258
|
-
const [started, commands] = await Promise.all([
|
|
259
|
-
execute('ps', ['-axww', '-o', 'pid=,lstart=,comm='], 15_000, psEnv),
|
|
260
|
-
execute('ps', ['-axww', '-o', 'pid=,args='], 15_000, psEnv),
|
|
261
|
-
])
|
|
262
|
-
if (started.code !== 0 || commands.code !== 0) throw new Error('cannot inspect running DSH Desktop processes')
|
|
263
|
-
const argv = new Map<number, string>()
|
|
264
|
-
for (const line of commands.stdout.split('\n')) {
|
|
265
|
-
const match = /^\s*(\d+)\s(.*)$/.exec(line)
|
|
266
|
-
if (match !== null) argv.set(Number(match[1]), match[2] as string)
|
|
267
|
-
}
|
|
268
|
-
const expected = desktopPaths(root).executable
|
|
269
|
-
const layout = desktopLayout(root)
|
|
270
|
-
const bundleRoot = includeBundleHelpers && !('error' in layout) && layout.name === 'macos-bundle'
|
|
271
|
-
? root
|
|
272
|
-
: undefined
|
|
273
|
-
const rows: DesktopProcess[] = []
|
|
274
|
-
for (const line of started.stdout.split('\n')) {
|
|
275
|
-
// lstart is always five fields under C locale: "Fri Nov 20 04:10:00 2026".
|
|
276
|
-
const match = /^\s*(\d+)\s+(\S+\s+\S+\s+\d+\s+[\d:]+\s+\d{4})\s+(.+)$/.exec(line)
|
|
277
|
-
if (match === null) continue
|
|
278
|
-
const path = (match[3] as string).trim()
|
|
279
|
-
if (!isAbsolute(path)) continue
|
|
280
|
-
const matched = isDesktopExecutable(path, expected, bundleRoot)
|
|
281
|
-
if (!matched) continue
|
|
282
|
-
const at = Date.parse(match[2] as string)
|
|
283
|
-
if (!Number.isFinite(at)) throw new Error('cannot identify a running DSH Desktop process')
|
|
284
|
-
rows.push({ pid: Number(match[1]), path, command: argv.get(Number(match[1])) ?? '', started: new Date(at).toISOString() })
|
|
285
|
-
}
|
|
286
|
-
return rows.filter(p => !NODE_MODE.test(p.command))
|
|
287
|
-
}
|
|
288
|
-
// The Desktop also ships a Node-mode CLI under its executable; it is not a GUI to close.
|
|
289
|
-
const NODE_MODE = /(?:^|\s)--expose-internals(?:\s|$)|\.[cm]?js(?:"|\s|$)|(?:^|\s)(?:--eval|--print|--input-type)(?:=|\s|$)|(?:^|\s)-(?:e|p)(?:\s|$)/i
|
|
290
|
-
async function desktopProcesses(root: string, includeBundleHelpers = false): Promise<DesktopProcess[]> {
|
|
291
|
-
if (process.platform !== 'win32') return await posixDesktopProcesses(root, includeBundleHelpers)
|
|
292
|
-
const script = "$ProgressPreference='SilentlyContinue'; $ErrorActionPreference='Stop'; [Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false); $rows = @((Get-CimInstance Win32_Process -Filter \"Name='DeepSeek Harness.exe'\" -ErrorAction Stop) | ForEach-Object { @{pid=[int]$_.ProcessId;path=$_.ExecutablePath;command=$_.CommandLine;started=$_.CreationDate.ToUniversalTime().ToString('o')} }); ConvertTo-Json -InputObject $rows -Compress"
|
|
293
|
-
const r = await execute(windowsPowerShellPath(), ['-NoProfile', '-NonInteractive', '-EncodedCommand', encodePowerShellScript(script)])
|
|
294
|
-
if (r.code !== 0) throw new Error('cannot inspect running DSH Desktop processes')
|
|
295
|
-
let value: unknown
|
|
296
|
-
try { value = JSON.parse(r.stdout.replace(/^\uFEFF/, '').trim()) } catch { throw new Error('Desktop process inspection returned invalid data') }
|
|
297
|
-
return identifyDesktopProcesses(root, value)
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
class DesktopProcessIdentityUnavailable extends Error {}
|
|
301
|
-
|
|
302
|
-
/** Validate a CIM snapshot without treating an incomplete process identity as an exited process. */
|
|
303
|
-
export function identifyDesktopProcesses(root: string, value: unknown): DesktopProcess[] {
|
|
304
|
-
const rows = Array.isArray(value) ? value : value === null ? [] : [value]
|
|
305
|
-
const expected = desktopPaths(root).executable
|
|
306
|
-
return rows.filter((row): row is DesktopProcess => {
|
|
307
|
-
if (row === null || typeof row !== 'object') throw new Error('Desktop process inspection was incomplete')
|
|
308
|
-
const p = row as Partial<DesktopProcess>
|
|
309
|
-
if (typeof p.path !== 'string' || p.path === '' || typeof p.command !== 'string' || !Number.isSafeInteger(p.pid) || typeof p.started !== 'string') {
|
|
310
|
-
throw new DesktopProcessIdentityUnavailable('cannot identify a running DSH Desktop process')
|
|
311
|
-
}
|
|
312
|
-
if (!isDesktopExecutable(p.path, expected, undefined, 'win32')) return false
|
|
313
|
-
return !NODE_MODE.test(p.command)
|
|
314
|
-
})
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
/** Wait through incomplete shutdown snapshots, but require a complete empty snapshot before writing. */
|
|
318
|
-
export async function waitForDesktopExit(deps: {
|
|
319
|
-
readonly inspect: () => Promise<readonly DesktopProcess[]>
|
|
320
|
-
readonly checkCancelled: () => void
|
|
321
|
-
readonly pause?: () => Promise<void>
|
|
322
|
-
readonly now?: () => number
|
|
323
|
-
}): Promise<void> {
|
|
324
|
-
const now = deps.now ?? Date.now
|
|
325
|
-
const deadline = now() + 60_000
|
|
326
|
-
let incomplete = false
|
|
327
|
-
while (now() < deadline) {
|
|
328
|
-
deps.checkCancelled()
|
|
329
|
-
try {
|
|
330
|
-
const rows = await deps.inspect()
|
|
331
|
-
deps.checkCancelled()
|
|
332
|
-
if (rows.length === 0) return
|
|
333
|
-
incomplete = false
|
|
334
|
-
} catch (error) {
|
|
335
|
-
if (!(error instanceof DesktopProcessIdentityUnavailable)) throw error
|
|
336
|
-
incomplete = true
|
|
337
|
-
}
|
|
338
|
-
await (deps.pause ?? (() => delay(1_000)))()
|
|
339
|
-
}
|
|
340
|
-
throw new Error(incomplete
|
|
341
|
-
? 'cannot verify that DSH Desktop exited: process identity remains unavailable; maintenance was cancelled'
|
|
342
|
-
: 'Desktop did not exit; maintenance was cancelled. Any running-task confirmation remains under your control.')
|
|
343
|
-
}
|
|
344
|
-
async function atomicJson(path: string, value: unknown, exclusive = false): Promise<void> {
|
|
345
|
-
if (exclusive && existsSync(path)) {
|
|
346
|
-
const error: NodeJS.ErrnoException = new Error(`EEXIST: ${path} already exists`)
|
|
347
|
-
error.code = 'EEXIST'
|
|
348
|
-
throw error
|
|
349
|
-
}
|
|
350
|
-
const temp = `${path}.${String(process.pid)}.tmp`
|
|
351
|
-
await writeFile(temp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 })
|
|
352
|
-
try { await renameMaintenanceFile(temp, path) } finally {
|
|
353
|
-
await unlink(temp).catch(error => {
|
|
354
|
-
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') reportMaintenanceFailure('cannot remove maintenance temporary file', error)
|
|
355
|
-
})
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
export interface MaintenanceProgressOptions {
|
|
360
|
-
readonly jobId: string
|
|
361
|
-
readonly directory: string
|
|
362
|
-
readonly locale?: 'zh' | 'en'
|
|
363
|
-
}
|
|
364
|
-
export interface MaintenanceProgressNotification {
|
|
365
|
-
readonly started: boolean
|
|
366
|
-
readonly at: string
|
|
367
|
-
readonly pid?: number
|
|
368
|
-
readonly error?: string
|
|
369
|
-
readonly skipped?: boolean
|
|
370
|
-
}
|
|
371
|
-
export interface MaintenanceProgressDeps {
|
|
372
|
-
readonly launch?: (options: MaintenanceBrokerOptions) => Promise<MaintenanceBrokerResult>
|
|
373
|
-
readonly helperExists?: (path: string) => boolean
|
|
374
|
-
readonly powershellPath?: () => string
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
/** Data-only argv for the independent, read-only progress window. This function starts nothing. */
|
|
378
|
-
export function maintenanceProgressLaunchOptions(
|
|
379
|
-
jobId: string,
|
|
380
|
-
directory: string,
|
|
381
|
-
locale: 'zh' | 'en' = 'zh',
|
|
382
|
-
powershellPath = windowsPowerShellPath(),
|
|
383
|
-
): MaintenanceBrokerOptions {
|
|
384
|
-
if (typeof jobId !== 'string' || !/^(?:install|uninstall|reinstall)-[A-Za-z0-9]+$/.test(jobId)
|
|
385
|
-
|| typeof directory !== 'string' || !isAbsolute(directory) || basename(directory) !== jobId
|
|
386
|
-
|| !['zh', 'en'].includes(locale)) throw new Error('invalid maintenance progress request')
|
|
387
|
-
return {
|
|
388
|
-
runtimePath: powershellPath,
|
|
389
|
-
args: ['-NoLogo', '-NoProfile', '-NonInteractive', '-STA', '-ExecutionPolicy', 'Bypass', '-File', progressPath,
|
|
390
|
-
'-StatePath', join(directory, 'state.json'), '-JobId', jobId, '-Locale', locale],
|
|
391
|
-
cwd: directory,
|
|
392
|
-
environment: { ELECTRON_RUN_AS_NODE: undefined },
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
/**
|
|
397
|
-
* Attempt the optional window once per job, after commit and before requesting normal Desktop quit.
|
|
398
|
-
* A missing helper, denied broker or diagnostic write cannot change the maintenance outcome.
|
|
399
|
-
*/
|
|
400
|
-
export async function startMaintenanceProgressNotification(
|
|
401
|
-
options: MaintenanceProgressOptions,
|
|
402
|
-
deps: MaintenanceProgressDeps = {},
|
|
403
|
-
): Promise<MaintenanceProgressNotification> {
|
|
404
|
-
let directory: string | undefined
|
|
405
|
-
let result: MaintenanceProgressNotification
|
|
406
|
-
try {
|
|
407
|
-
const request = maintenanceProgressLaunchOptions(options.jobId, options.directory, options.locale ?? 'zh',
|
|
408
|
-
(deps.powershellPath ?? windowsPowerShellPath)())
|
|
409
|
-
directory = options.directory
|
|
410
|
-
try {
|
|
411
|
-
const claim = await open(join(directory, 'progress-notification.claim'), 'wx', 0o600)
|
|
412
|
-
await claim.close()
|
|
413
|
-
} catch (error) {
|
|
414
|
-
if ((error as NodeJS.ErrnoException).code === 'EEXIST') return { started: false, skipped: true, at: new Date().toISOString() }
|
|
415
|
-
throw error
|
|
416
|
-
}
|
|
417
|
-
if (!(deps.helperExists ?? existsSync)(progressPath)) throw new Error('the packaged maintenance progress window is unavailable')
|
|
418
|
-
const launched = await (deps.launch ?? launchMaintenanceBroker)(request)
|
|
419
|
-
result = { started: true, at: new Date().toISOString(), pid: launched.pid }
|
|
420
|
-
} catch (error) {
|
|
421
|
-
result = { started: false, at: new Date().toISOString(), error: String(error) }
|
|
422
|
-
}
|
|
423
|
-
if (directory !== undefined) {
|
|
424
|
-
await atomicJson(join(directory, 'progress-notification.json'), { ...result, jobId: options.jobId })
|
|
425
|
-
.catch(error => reportMaintenanceFailure('cannot write the progress notification', error))
|
|
426
|
-
}
|
|
427
|
-
return result
|
|
428
|
-
}
|
|
429
|
-
/** Last durable outcome survives both the settings page and the HTTP host restarting. */
|
|
430
|
-
export function readAutomaticMaintenance(home = homePath()): AutomaticMaintenanceJob | undefined {
|
|
431
|
-
try {
|
|
432
|
-
const base = basePath(home)
|
|
433
|
-
const pointer = JSON.parse(readFileSync(join(base, 'latest.json'), 'utf8')) as { id?: unknown; directory?: unknown }
|
|
434
|
-
if (typeof pointer.id !== 'string' || typeof pointer.directory !== 'string' || !inside(base, pointer.directory)
|
|
435
|
-
|| basename(pointer.directory) !== pointer.id) return undefined
|
|
436
|
-
const state = JSON.parse(readFileSync(join(pointer.directory, 'state.json'), 'utf8')) as AutomaticMaintenanceJob
|
|
437
|
-
if (state.id !== pointer.id || !['armed', 'closing', 'installing', 'restarting', 'verifying', ...terminal].includes(state.phase)
|
|
438
|
-
|| !['install', 'uninstall', 'reinstall'].includes(state.action) || !Number.isFinite(Date.parse(state.at))) return undefined
|
|
439
|
-
return state
|
|
440
|
-
} catch { return undefined }
|
|
441
|
-
}
|
|
442
|
-
/** A lock left behind by a killed worker never releases itself; clear only clearly stale ones. */
|
|
443
|
-
async function clearStaleLock(lockPath: string, home: string): Promise<boolean> {
|
|
444
|
-
try {
|
|
445
|
-
const info = await statAsync(lockPath)
|
|
446
|
-
// Never touch a lock another request may still be preparing (concurrent start window).
|
|
447
|
-
if (Date.now() - info.mtimeMs < 5 * 60_000) return false
|
|
448
|
-
const id = (await readFile(lockPath, 'utf8')).trim()
|
|
449
|
-
if (!/^(?:install|uninstall|reinstall)-[A-Za-z0-9]+$/.test(id)) return false
|
|
450
|
-
const prior = readAutomaticMaintenance(home)
|
|
451
|
-
if (prior === undefined || prior.id !== id) return true
|
|
452
|
-
if (terminal.has(prior.phase)) return true
|
|
453
|
-
const pid = Number(prior.workerPid)
|
|
454
|
-
if (Number.isSafeInteger(pid) && pid > 0) {
|
|
455
|
-
try { process.kill(pid, 0) } catch (error) {
|
|
456
|
-
if ((error as NodeJS.ErrnoException).code === 'ESRCH') return true
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
return false
|
|
460
|
-
} catch (error) {
|
|
461
|
-
reportMaintenanceFailure('cannot inspect a stale maintenance lock', error)
|
|
462
|
-
return false
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
async function releaseLock(plan: AutomaticPlan): Promise<void> {
|
|
467
|
-
const lock = join(basePath(plan.home), 'active.lock')
|
|
468
|
-
try { if ((await readFile(lock, 'utf8')).trim() === plan.id) await unlink(lock) } catch { /* no other job's lock is touched */ }
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
/** Validate the staged plan again in the independent process before it can request a quit. */
|
|
472
|
-
function validatePlan(value: unknown, path: string, now = Date.now()): AutomaticPlan {
|
|
473
|
-
if (value === null || typeof value !== 'object') throw new Error('invalid automatic maintenance plan')
|
|
474
|
-
const plan = value as Partial<AutomaticPlan>
|
|
475
|
-
const created = typeof plan.createdAt === 'string' ? Date.parse(plan.createdAt) : NaN
|
|
476
|
-
if (plan.version !== 1 || plan.action !== 'reinstall'
|
|
477
|
-
|| typeof plan.dependency !== 'string' || plan.dependency.trim() === ''
|
|
478
|
-
|| typeof plan.id !== 'string' || !/^reinstall-[A-Za-z0-9]+$/.test(plan.id)
|
|
479
|
-
|| ![plan.root, plan.home, plan.nodePath, plan.directory].every(p => typeof p === 'string' && isAbsolute(p))
|
|
480
|
-
|| typeof plan.electronNode !== 'boolean' || !Number.isFinite(created) || created > now || now - created > 30_000
|
|
481
|
-
|| (plan.locale !== undefined && !['zh', 'en'].includes(plan.locale))) {
|
|
482
|
-
throw new Error('invalid or expired automatic maintenance plan')
|
|
483
|
-
}
|
|
484
|
-
const checked = plan as AutomaticPlan
|
|
485
|
-
if (!inside(basePath(checked.home), checked.directory) || dirname(checked.directory) !== basePath(checked.home)
|
|
486
|
-
|| basename(checked.directory) !== checked.id || checked.id.split('-')[0] !== checked.action
|
|
487
|
-
|| resolve(path) !== join(checked.directory, 'automatic.json') || !readDesktopIdentity(checked.root).ok) {
|
|
488
|
-
throw new Error('invalid automatic maintenance plan paths or target')
|
|
489
|
-
}
|
|
490
|
-
const target = checked.target
|
|
491
|
-
if (target === null || typeof target !== 'object' || !Number.isSafeInteger(target.pid) || target.pid <= 0
|
|
492
|
-
|| typeof target.path !== 'string' || !samePath(target.path, desktopPaths(checked.root).executable)
|
|
493
|
-
|| typeof target.command !== 'string' || /(?:^|\s)--type(?:=|\s)/i.test(target.command)
|
|
494
|
-
|| typeof target.started !== 'string' || !Number.isFinite(Date.parse(target.started)) || Date.parse(target.started) > now) {
|
|
495
|
-
throw new Error('invalid automatic maintenance target process')
|
|
496
|
-
}
|
|
497
|
-
return checked
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
/** Commit only the armed job after its accepted HTTP response has finished writing. */
|
|
501
|
-
export async function commitAutomaticMaintenance(jobId: string, home = homePath()): Promise<void> {
|
|
502
|
-
if (typeof jobId !== 'string' || !/^reinstall-[A-Za-z0-9]+$/.test(jobId)) throw new Error('invalid bridge maintenance job id')
|
|
503
|
-
const state = readAutomaticMaintenance(home)
|
|
504
|
-
if (state?.id !== jobId || state.phase !== 'armed' || !Number.isSafeInteger(state.workerPid) || Number(state.workerPid) <= 0) {
|
|
505
|
-
throw new Error('the bridge maintenance job is no longer armed')
|
|
506
|
-
}
|
|
507
|
-
const directory = join(basePath(home), jobId)
|
|
508
|
-
const planPath = join(directory, 'automatic.json')
|
|
509
|
-
const plan = validatePlan(JSON.parse(await readFile(planPath, 'utf8')), planPath)
|
|
510
|
-
if (plan.home !== resolve(home) || plan.action !== state.action || existsSync(join(directory, 'cancel.json'))) {
|
|
511
|
-
throw new Error('the bridge maintenance job cannot be committed')
|
|
512
|
-
}
|
|
513
|
-
try {
|
|
514
|
-
await atomicJson(join(directory, 'commit.json'), { id: jobId, workerPid: state.workerPid, at: new Date().toISOString() }, true)
|
|
515
|
-
} catch (error) {
|
|
516
|
-
// The worker is polling this file; cancel it at once instead of leaving a successful-looking
|
|
517
|
-
// 202 to turn into a generic "not committed" twenty seconds later. An EEXIST is a duplicate
|
|
518
|
-
// commit of an already-approved job, not a failure: cancelling it would abort good work.
|
|
519
|
-
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
|
|
520
|
-
await atomicJson(join(directory, 'cancel.json'), { at: new Date().toISOString(), reason: String(error) }).catch(() => {})
|
|
521
|
-
}
|
|
522
|
-
throw error
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
/** Only the new, authenticated explicit-click endpoint calls this function. */
|
|
527
|
-
export async function startAutomaticMaintenance(action: 'reinstall', root: string, options: AutomaticMaintenanceOptions = {}): Promise<AutomaticMaintenanceJob> {
|
|
528
|
-
requireLiveDesktop()
|
|
529
|
-
if (action !== 'reinstall') throw new Error('invalid bridge maintenance action')
|
|
530
|
-
if (options.locale !== undefined && !['zh', 'en'].includes(options.locale)) throw new Error('invalid bridge maintenance locale')
|
|
531
|
-
const dependency = await preflightReinstall(root, homePath())
|
|
532
|
-
if (!readDesktopIdentity(root).ok) throw new Error('the maintenance target is not a verified DSH Desktop installation')
|
|
533
|
-
if (process.platform === 'win32' && !existsSync(quitPath)) throw new Error('the packaged Desktop quit helper is missing')
|
|
534
|
-
const processes = await desktopProcesses(root)
|
|
535
|
-
const mains = processes.filter(p => !/(?:^|\s)--type(?:=|\s)/i.test(p.command))
|
|
536
|
-
if (mains.length !== 1) throw new Error('automatic maintenance requires one running DSH Desktop window')
|
|
537
|
-
const home = homePath()
|
|
538
|
-
const base = basePath(home)
|
|
539
|
-
await mkdir(base, { recursive: true, mode: 0o700 })
|
|
540
|
-
const lockPath = join(base, 'active.lock')
|
|
541
|
-
let lock
|
|
542
|
-
try { lock = await open(lockPath, 'wx', 0o600) }
|
|
543
|
-
catch {
|
|
544
|
-
if (!(await clearStaleLock(lockPath, home))) throw new Error('bridge maintenance is already in progress')
|
|
545
|
-
await unlink(lockPath).catch(error => reportMaintenanceFailure('cannot remove a stale maintenance lock', error))
|
|
546
|
-
lock = await open(lockPath, 'wx', 0o600)
|
|
547
|
-
}
|
|
548
|
-
let plan: AutomaticPlan | undefined
|
|
549
|
-
try {
|
|
550
|
-
const prepared = await prepareBridgeMaintenance('install', root, { directory: base })
|
|
551
|
-
const original = JSON.parse(await readFile(prepared.planPath, 'utf8')) as { nodePath: string; electronNode: boolean }
|
|
552
|
-
const id = basename(prepared.directory).replace(/^install-/, 'reinstall-')
|
|
553
|
-
const directory = join(base, id)
|
|
554
|
-
await renameMaintenanceFile(prepared.directory, directory)
|
|
555
|
-
const stagedWorker = await stageReinstallRuntime(directory)
|
|
556
|
-
await lock.writeFile(id + '\n')
|
|
557
|
-
await lock.close()
|
|
558
|
-
plan = { version: 1, id, action, dependency, nestedResidue: await inspectProfileResidue(home), root: resolve(root), nodePath: original.nodePath, electronNode: original.electronNode,
|
|
559
|
-
home, directory, target: mains[0] as DesktopProcess, createdAt: new Date().toISOString(),
|
|
560
|
-
...options.locale === undefined ? {} : { locale: options.locale } }
|
|
561
|
-
const path = join(directory, 'automatic.json')
|
|
562
|
-
await writeFile(path, JSON.stringify(plan, null, 2) + '\n', { flag: 'wx', mode: 0o600 })
|
|
563
|
-
await atomicJson(join(base, 'latest.json'), { id, directory })
|
|
564
|
-
const launched = await launchMaintenanceBroker({ runtimePath: plan.nodePath,
|
|
565
|
-
args: [...plan.electronNode ? ['--expose-internals'] : [], stagedWorker, '--automatic-maintenance', path], cwd: directory,
|
|
566
|
-
environment: { DSH_HOME: home, ELECTRON_RUN_AS_NODE: plan.electronNode ? '1' : undefined, ELECTRON_NO_ASAR: '1' } })
|
|
567
|
-
// WMI's return code proves creation only. The worker must actually load and publish its arm.
|
|
568
|
-
const deadline = Date.now() + 12_000
|
|
569
|
-
while (Date.now() < deadline) {
|
|
570
|
-
const state = readAutomaticMaintenance(home)
|
|
571
|
-
if (state?.id === id && state.workerPid === launched.pid) {
|
|
572
|
-
if (state.phase !== 'armed') throw new Error(state.error ?? 'the maintenance worker did not arm')
|
|
573
|
-
return state
|
|
574
|
-
}
|
|
575
|
-
await delay(100)
|
|
576
|
-
}
|
|
577
|
-
throw new Error('the independent maintenance worker did not become ready')
|
|
578
|
-
} catch (error) {
|
|
579
|
-
await lock.close().catch(error => reportMaintenanceFailure('cannot close the maintenance lock', error))
|
|
580
|
-
if (plan !== undefined) {
|
|
581
|
-
await atomicJson(join(plan.directory, 'cancel.json'), { at: new Date().toISOString() })
|
|
582
|
-
.catch(error => reportMaintenanceFailure('cannot stage the maintenance cancellation', error))
|
|
583
|
-
await atomicJson(join(plan.directory, 'state.json'), { id: plan.id, action, phase: 'failed', ok: false, restarted: false,
|
|
584
|
-
at: new Date().toISOString(), startedAt: plan.createdAt, error: String(error) })
|
|
585
|
-
.catch(writeError => reportMaintenanceFailure('cannot record the failed maintenance state', writeError))
|
|
586
|
-
await releaseLock(plan)
|
|
587
|
-
} else { await unlink(lockPath).catch(error => reportMaintenanceFailure('cannot remove the unused maintenance lock', error)) }
|
|
588
|
-
throw error
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
/**
|
|
593
|
-
* Ask the verified macOS Desktop to quit through its own Quit command (Apple event), exactly as
|
|
594
|
-
* Cmd-Q does: any running-task confirmation stays with the user. The pid and start time are
|
|
595
|
-
* re-read first, so a reused pid or a second copy of the app is never asked.
|
|
596
|
-
*/
|
|
597
|
-
async function requestPosixQuit(plan: AutomaticPlan): Promise<void> {
|
|
598
|
-
const current = (await desktopProcesses(plan.root)).filter(p => !/(?:^|\s)--type(?:=|\s)/i.test(p.command))
|
|
599
|
-
if (current.length !== 1 || current[0]?.pid !== plan.target.pid || current[0].started !== plan.target.started) {
|
|
600
|
-
throw new Error('the running Desktop is not the one maintenance was requested from; no quit was sent')
|
|
601
|
-
}
|
|
602
|
-
const result = await execute('osascript', ['-e', 'on run argv', '-e', 'tell application (item 1 of argv) to quit', '-e', 'end run', plan.root], 25_000)
|
|
603
|
-
if (result.code !== 0) throw new Error(result.output || 'the Desktop Quit command was not accepted')
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
async function runWorker(path: string): Promise<void> {
|
|
607
|
-
requireLiveDesktop()
|
|
608
|
-
const plan = validatePlan(JSON.parse(await readFile(path, 'utf8')), path)
|
|
609
|
-
let extension: InstalledExtension | undefined
|
|
610
|
-
const checkCancelled = (): void => {
|
|
611
|
-
if (existsSync(join(plan.directory, 'cancel.json'))) throw new Error('bridge maintenance was cancelled before Desktop exited')
|
|
612
|
-
}
|
|
613
|
-
process.env.DSH_HOME = plan.home
|
|
614
|
-
const publish = async (state: MaintenanceState): Promise<void> => {
|
|
615
|
-
// If the host gave up on this job (readiness timeout), its terminal state wins. Without this
|
|
616
|
-
// a late worker flips "failed" back to "armed" and the settings page oscillates.
|
|
617
|
-
const prior = readAutomaticMaintenance(plan.home)
|
|
618
|
-
if (prior?.id === plan.id && terminal.has(prior.phase)) return
|
|
619
|
-
await atomicJson(join(plan.directory, 'state.json'), { ...state, id: plan.id, workerPid: process.pid, startedAt: plan.createdAt })
|
|
620
|
-
}
|
|
621
|
-
try {
|
|
622
|
-
checkCancelled()
|
|
623
|
-
await runMaintenanceLifecycle(plan.action, {
|
|
624
|
-
publish,
|
|
625
|
-
requestQuit: async () => {
|
|
626
|
-
// Arming proves the worker is independent and loaded. It grants no permission to quit
|
|
627
|
-
// until the original request's response has finished and its host commits this exact job.
|
|
628
|
-
const deadline = Date.now() + 20_000
|
|
629
|
-
let committed = false
|
|
630
|
-
while (Date.now() < deadline) {
|
|
631
|
-
checkCancelled()
|
|
632
|
-
try {
|
|
633
|
-
const record = JSON.parse(await readFile(join(plan.directory, 'commit.json'), 'utf8')) as { id?: unknown; workerPid?: unknown; at?: unknown }
|
|
634
|
-
if (record.id !== plan.id || record.workerPid !== process.pid || typeof record.at !== 'string' || !Number.isFinite(Date.parse(record.at))) {
|
|
635
|
-
throw new Error('invalid bridge maintenance commit')
|
|
636
|
-
}
|
|
637
|
-
committed = true
|
|
638
|
-
break
|
|
639
|
-
} catch (error) {
|
|
640
|
-
// An empty or half-written commit.json is a transient state, not a cancellation.
|
|
641
|
-
if ((error as NodeJS.ErrnoException).code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error
|
|
642
|
-
}
|
|
643
|
-
await delay(100)
|
|
644
|
-
}
|
|
645
|
-
if (!committed) throw new Error('the maintenance request was not committed; Desktop remains open')
|
|
646
|
-
checkCancelled()
|
|
647
|
-
await publish({ phase: 'closing', action: plan.action, at: new Date().toISOString() })
|
|
648
|
-
if (process.platform !== 'win32') {
|
|
649
|
-
await requestPosixQuit(plan)
|
|
650
|
-
return
|
|
651
|
-
}
|
|
652
|
-
await startMaintenanceProgressNotification({ jobId: plan.id, directory: plan.directory, locale: plan.locale ?? 'zh' })
|
|
653
|
-
const result = await execute(windowsPowerShellPath(), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', quitPath,
|
|
654
|
-
'-TargetPid', String(plan.target.pid), '-ExpectedExecutable', plan.target.path,
|
|
655
|
-
'-ExpectedStartTimeUtc', plan.target.started, '-TimeoutSeconds', '20'], 25_000)
|
|
656
|
-
checkCancelled()
|
|
657
|
-
if (result.code !== 0) throw new Error(result.output || 'the official Desktop Quit menu was not available')
|
|
658
|
-
},
|
|
659
|
-
waitUntilClosed: async () => {
|
|
660
|
-
await waitForDesktopExit({ inspect: async () => await desktopProcesses(plan.root, true), checkCancelled })
|
|
661
|
-
},
|
|
662
|
-
maintain: async () => {
|
|
663
|
-
checkCancelled()
|
|
664
|
-
if ((await desktopProcesses(plan.root, true)).length > 0) throw new Error('DSH Desktop was reopened during maintenance; refusing to modify its files')
|
|
665
|
-
if (await preflightReinstall(plan.root, plan.home) !== plan.dependency) throw new Error('REINSTALL_DEPENDENCY_CHANGED')
|
|
666
|
-
const bridge = async (action: 'install' | 'uninstall'): Promise<BridgeActionResult> => await runBridgeAction(action, plan.root, {
|
|
667
|
-
node: () => plan.nodePath, installer: defaultInstallerPath, trackResult: true,
|
|
668
|
-
run: async (cmd, args, extra) => await execute(cmd, [...plan.electronNode ? ['--expose-internals'] : [], ...args], 180_000,
|
|
669
|
-
{ ...process.env, ...extra, ELECTRON_RUN_AS_NODE: plan.electronNode ? '1' : undefined, ELECTRON_NO_ASAR: '1' }),
|
|
670
|
-
})
|
|
671
|
-
const profile = async (action: 'install' | 'uninstall'): Promise<BridgeActionResult> => await repairProfileExtension(action, plan.root, plan.home,
|
|
672
|
-
runProfileCommand, plan.dependency)
|
|
673
|
-
return await withProfileCheckpoint(plan.home, plan.directory, async () => {
|
|
674
|
-
const residue = await cleanProfileResidue(plan.home)
|
|
675
|
-
const result = await runReinstallTransaction({
|
|
676
|
-
remove: () => profile('uninstall'),
|
|
677
|
-
absent: async () => {
|
|
678
|
-
const manifest = JSON.parse(await readFile(join(plan.home, 'profiles', 'desktop', 'package.json'), 'utf8')) as { dependencies?: Record<string, unknown> }
|
|
679
|
-
return manifest.dependencies?.[MAIN_EXTENSION_NAME] === undefined && !existsSync(join(plan.home, 'profiles', 'desktop', 'node_modules', MAIN_EXTENSION_NAME))
|
|
680
|
-
},
|
|
681
|
-
revert: () => bridge('uninstall'),
|
|
682
|
-
hostAbsent: () => inspectReinstallHost(plan.root).status === 'absent',
|
|
683
|
-
apply: () => bridge('install'), add: () => profile('install'),
|
|
684
|
-
})
|
|
685
|
-
extension = await installedProfileExtension(plan.home)
|
|
686
|
-
return { ...result, output: [residue, result.output].filter(Boolean).join('\n') }
|
|
687
|
-
}, { reconcile: () => reconcileProfile(plan.root, plan.home) })
|
|
688
|
-
},
|
|
689
|
-
restart: async () => {
|
|
690
|
-
if ((await desktopProcesses(plan.root, true)).length > 0) throw new Error('DSH Desktop is already running; not opening a second instance')
|
|
691
|
-
const identity = readDesktopIdentity(plan.root)
|
|
692
|
-
if (!identity.ok) throw new Error(`Desktop cannot be safely reopened: ${identity.reason}`)
|
|
693
|
-
const environment: NodeJS.ProcessEnv = { ...process.env, DSH_HOME: plan.home }
|
|
694
|
-
for (const key of Object.keys(environment)) {
|
|
695
|
-
const upper = key.toUpperCase()
|
|
696
|
-
if (upper === 'ELECTRON_RUN_AS_NODE' || upper === 'ELECTRON_NO_ASAR' || upper.startsWith('DSH_BRIDGE_')) {
|
|
697
|
-
delete environment[key]
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
return await new Promise<number>((resolve, reject) => {
|
|
701
|
-
const child = spawn(desktopPaths(plan.root).executable, [], { cwd: plan.root, env: environment, stdio: 'ignore', windowsHide: true, detached: true })
|
|
702
|
-
child.once('error', reject)
|
|
703
|
-
child.once('spawn', () => { child.unref(); resolve(child.pid as number) })
|
|
704
|
-
})
|
|
705
|
-
},
|
|
706
|
-
verify: async (pid, action) => {
|
|
707
|
-
if (action === 'reinstall') {
|
|
708
|
-
if (inspectReinstallHost(plan.root).status !== 'applied') throw new Error('REINSTALL_HOST_VERIFY_FAILED')
|
|
709
|
-
await waitForRestartedBridge(pid, { timeoutMs: 45_000, endpointPath: join(plan.home, 'dsh-builtin-browser-bridge.json'),
|
|
710
|
-
...(extension === undefined ? {} : { extension, home: plan.home }) })
|
|
711
|
-
return
|
|
712
|
-
}
|
|
713
|
-
await delay(1_500)
|
|
714
|
-
if (!(await desktopProcesses(plan.root)).some(p => p.pid === pid)) throw new Error('the reopened Desktop did not remain running')
|
|
715
|
-
},
|
|
716
|
-
})
|
|
717
|
-
} catch (error) {
|
|
718
|
-
await publish({ phase: 'cancelled', action: plan.action, at: new Date().toISOString(), ok: false, restarted: false, error: String(error) })
|
|
719
|
-
.catch(writeError => reportMaintenanceFailure('cannot publish the cancelled maintenance state', writeError))
|
|
720
|
-
} finally { await releaseLock(plan) }
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
// Importing this module only exposes functions. Execution requires the private staged plan.
|
|
724
|
-
if (process.argv[2] === '--automatic-maintenance' && process.argv[1] !== undefined && resolve(process.argv[1]) === workerPath) {
|
|
725
|
-
void runWorker(resolve(process.argv[3] ?? '')).catch(error => { console.error(String(error)); process.exitCode = 1 })
|
|
726
|
-
}
|