dsh-builtin-browser 1.0.1 → 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.
Files changed (360) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/assets/browser-panel-locales.mjs +37 -5
  4. package/assets/browser-policy.d.mts +29 -0
  5. package/assets/browser-policy.mjs +40 -0
  6. package/desktop-bridge/desktop-discovery.d.mts +1 -1
  7. package/desktop-bridge/desktop-discovery.mjs +59 -9
  8. package/desktop-bridge/desktop-identity.json +12 -0
  9. package/desktop-bridge/install.mjs +14 -7
  10. package/desktop-bridge/plugin-browser-bridge.js +19 -7
  11. package/docs/acceptance-2026-11-27.md +67 -0
  12. package/docs/architecture.md +1 -1
  13. package/docs/development.md +33 -4
  14. package/docs/dsh-0.2.3-host-patch-task.md +34 -0
  15. package/docs/hardcoding-audit.md +28 -8
  16. package/docs/known-issues.md +26 -0
  17. package/docs/limitations.md +6 -2
  18. package/docs/tool-reference.md +1 -1
  19. package/docs/v1.1.0-bu-data-batching-task.md +66 -0
  20. package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
  21. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  22. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  23. package/dsh-host-patch/README.md +4 -0
  24. package/dsh-host-patch/apply.mjs +61 -13
  25. package/dsh-host-patch/rc3-revision9.json.gz +0 -0
  26. package/dsh-host-patch/rc5-revision9.json.gz +0 -0
  27. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  28. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  29. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  30. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  31. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  32. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  33. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  34. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  35. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  36. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  37. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  38. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  39. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  40. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  41. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  42. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  43. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  44. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  45. package/dsh-host-patch/sources/manifest.json +218 -0
  46. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  47. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  48. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  49. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  50. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  51. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  52. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  53. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  54. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  55. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  56. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  57. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  58. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  59. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  60. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  61. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  62. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  63. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  64. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  65. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  66. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  67. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  68. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  69. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  70. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  71. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  72. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  73. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  74. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  75. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  76. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  77. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  78. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  79. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  80. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  81. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  82. package/dsh-host-patch/sources/series.json +260 -0
  83. package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
  84. package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
  85. package/dsh-host-patch/tauri-revision1.json +39 -0
  86. package/dsh-host-patch/tauri.json +43 -0
  87. package/dsh-host-patch/v023-alpha2.json +153 -0
  88. package/lib/browser/anti-bot.js +215 -0
  89. package/lib/browser/deep-dom.js +39 -0
  90. package/lib/browser/runtime.js +15 -0
  91. package/lib/browser/takeover-target.js +13 -6
  92. package/lib/browser/types.js +30 -1
  93. package/lib/browser-electron/authenticated-route.js +16 -2
  94. package/lib/browser-electron/automatic-maintenance.js +16 -10
  95. package/lib/browser-electron/bridge-connection.js +3 -8
  96. package/lib/browser-electron/bridge-install.js +2 -1
  97. package/lib/browser-electron/bridge-status.js +55 -26
  98. package/lib/browser-electron/desktop-bridge-host.js +7 -6
  99. package/lib/browser-electron/desktop-identity.js +28 -5
  100. package/lib/browser-electron/desktop-shell.js +64 -0
  101. package/lib/browser-electron/electron-provision.js +105 -18
  102. package/lib/browser-electron/entry.js +129 -44
  103. package/lib/browser-electron/extension-browser.js +4 -4
  104. package/lib/browser-electron/foreground-watch.js +134 -0
  105. package/lib/browser-electron/guest-cookie-jar.js +13 -13
  106. package/lib/browser-electron/guest-route.js +181 -32
  107. package/lib/browser-electron/guest-runtime.js +61 -10
  108. package/lib/browser-electron/guest-storage.js +2 -2
  109. package/lib/browser-electron/history-store.js +1 -5
  110. package/lib/browser-electron/host-main.js +8 -4
  111. package/lib/browser-electron/host-patch-maintenance.js +14 -8
  112. package/lib/browser-electron/maintenance-route.js +2 -1
  113. package/lib/browser-electron/missing-system-browser.js +5 -9
  114. package/lib/browser-electron/preferred-browser.js +7 -3
  115. package/lib/browser-electron/preview-route.js +9 -13
  116. package/lib/browser-electron/process-ownership.js +1 -1
  117. package/lib/browser-electron/profile-command.js +2 -1
  118. package/lib/browser-electron/profile-extension.js +5 -0
  119. package/lib/browser-electron/profile-lease.js +152 -47
  120. package/lib/browser-electron/provider-core.js +527 -0
  121. package/lib/browser-electron/provider-interaction.js +963 -0
  122. package/lib/browser-electron/provider-media.js +518 -0
  123. package/lib/browser-electron/provider-navigation.js +301 -0
  124. package/lib/browser-electron/provider-observation.js +623 -0
  125. package/lib/browser-electron/provider-tabs.js +372 -0
  126. package/lib/browser-electron/provider.js +150 -3301
  127. package/lib/browser-electron/reference-route.js +9 -18
  128. package/lib/browser-electron/remote-host.js +79 -34
  129. package/lib/browser-electron/runtime-status.js +56 -6
  130. package/lib/browser-electron/settings-store.js +3 -6
  131. package/lib/browser-electron/sidebar-only-host.js +1 -1
  132. package/lib/browser-electron/system-browser.js +539 -172
  133. package/lib/browser-electron/tauri-host.js +208 -0
  134. package/lib/browser-electron/virtual-cursor.js +23 -13
  135. package/lib/browser-reference/service.js +22 -4
  136. package/lib/browser-reference/web-sources.js +1 -1
  137. package/lib/client.js +43409 -0
  138. package/lib/compat/host-features.js +75 -0
  139. package/lib/reference-source.js +1 -1
  140. package/lib/reference-text.js +23 -1
  141. package/lib/takeover-protocol.js +1 -1
  142. package/lib/tool-browser/block-recovery.js +69 -0
  143. package/lib/tool-browser/code-tool.js +170 -19
  144. package/lib/tool-browser/code-worker.js +115 -20
  145. package/lib/tool-browser/errors.js +34 -0
  146. package/lib/tool-browser/index.js +66 -3593
  147. package/lib/tool-browser/page-probe.js +227 -28
  148. package/lib/tool-browser/panel-page.js +2 -1
  149. package/lib/tool-browser/probe-client.js +157 -0
  150. package/lib/tool-browser/screenshot-annotations.js +108 -0
  151. package/lib/tool-browser/state.js +337 -0
  152. package/lib/tool-browser/takeover.js +1 -1
  153. package/lib/tool-browser/tools-debug.js +862 -0
  154. package/lib/tool-browser/tools-interaction.js +993 -0
  155. package/lib/tool-browser/tools-navigation.js +807 -0
  156. package/lib/tool-browser/tools-observation.js +461 -0
  157. package/lib/tool-browser/tools-reference.js +293 -0
  158. package/lib/web-guest.js +1 -0
  159. package/package.json +15 -53
  160. package/README.en.md +0 -89
  161. package/browser-extension/constants.mjs +0 -20
  162. package/browser-extension/controller.mjs +0 -293
  163. package/browser-extension/locales.mjs +0 -15
  164. package/browser-extension/manifest.json +0 -12
  165. package/browser-extension/options.html +0 -14
  166. package/browser-extension/options.mjs +0 -9
  167. package/browser-extension/permission-guard.mjs +0 -13
  168. package/browser-extension/worker.mjs +0 -74
  169. package/dist/client.cjs +0 -43167
  170. package/lib/browser-reference/submission-receipts.js +0 -139
  171. package/scripts/build.mjs +0 -66
  172. package/scripts/bundle-host.mjs +0 -28
  173. package/scripts/fix-exports.mjs +0 -50
  174. package/scripts/install-electron.mjs +0 -51
  175. package/scripts/verify-exports.mjs +0 -47
  176. package/scripts/verify-preview-sdk.mjs +0 -93
  177. package/skills/dsh-builtin-browser/SKILL.md +0 -73
  178. package/skills/dsh-builtin-browser/references/batch.md +0 -53
  179. package/skills/dsh-builtin-browser/references/deliver.md +0 -31
  180. package/skills/dsh-builtin-browser/references/locate.md +0 -11
  181. package/skills/dsh-builtin-browser/references/recover.md +0 -11
  182. package/skills/dsh-builtin-browser/references/verify.md +0 -13
  183. package/skills/dsh-debug-host/SKILL.md +0 -56
  184. package/skills/dsh-debug-self/SKILL.md +0 -50
  185. package/src/bridge-compatibility.ts +0 -39
  186. package/src/browser/handles.ts +0 -89
  187. package/src/browser/runtime.ts +0 -560
  188. package/src/browser/takeover-target.ts +0 -36
  189. package/src/browser/types.ts +0 -817
  190. package/src/browser-electron/authenticated-route.ts +0 -84
  191. package/src/browser-electron/automatic-maintenance.ts +0 -726
  192. package/src/browser-electron/bridge-auto.ts +0 -159
  193. package/src/browser-electron/bridge-connection.ts +0 -385
  194. package/src/browser-electron/bridge-endpoint.ts +0 -129
  195. package/src/browser-electron/bridge-install.ts +0 -289
  196. package/src/browser-electron/bridge-maintenance.ts +0 -189
  197. package/src/browser-electron/bridge-status.ts +0 -347
  198. package/src/browser-electron/desktop-bridge-host.ts +0 -251
  199. package/src/browser-electron/desktop-identity.ts +0 -320
  200. package/src/browser-electron/document-readiness.ts +0 -45
  201. package/src/browser-electron/electron-provision.ts +0 -261
  202. package/src/browser-electron/entry.ts +0 -1299
  203. package/src/browser-electron/ephemeral-profile.ts +0 -189
  204. package/src/browser-electron/extension-browser.ts +0 -223
  205. package/src/browser-electron/extension-setup.ts +0 -67
  206. package/src/browser-electron/file-write.ts +0 -31
  207. package/src/browser-electron/guest-cookie-jar.ts +0 -176
  208. package/src/browser-electron/guest-cookie-store.ts +0 -59
  209. package/src/browser-electron/guest-css-runtime.ts +0 -76
  210. package/src/browser-electron/guest-css.ts +0 -68
  211. package/src/browser-electron/guest-route.ts +0 -568
  212. package/src/browser-electron/guest-runtime.ts +0 -357
  213. package/src/browser-electron/guest-storage-runtime.ts +0 -54
  214. package/src/browser-electron/guest-storage.ts +0 -117
  215. package/src/browser-electron/history-store.ts +0 -227
  216. package/src/browser-electron/host-main.ts +0 -1381
  217. package/src/browser-electron/host-patch-maintenance.ts +0 -112
  218. package/src/browser-electron/http-body.ts +0 -65
  219. package/src/browser-electron/json-reply.ts +0 -47
  220. package/src/browser-electron/maintenance-broker.ts +0 -166
  221. package/src/browser-electron/maintenance-lifecycle.ts +0 -91
  222. package/src/browser-electron/maintenance-route.ts +0 -67
  223. package/src/browser-electron/missing-system-browser.ts +0 -113
  224. package/src/browser-electron/open-slot.ts +0 -49
  225. package/src/browser-electron/paths.ts +0 -25
  226. package/src/browser-electron/preferred-browser.ts +0 -120
  227. package/src/browser-electron/preview-route.ts +0 -218
  228. package/src/browser-electron/process-ownership.ts +0 -168
  229. package/src/browser-electron/process.ts +0 -23
  230. package/src/browser-electron/profile-checkpoint.ts +0 -187
  231. package/src/browser-electron/profile-command.ts +0 -46
  232. package/src/browser-electron/profile-extension.ts +0 -124
  233. package/src/browser-electron/profile-lease.ts +0 -115
  234. package/src/browser-electron/profile-residue.ts +0 -49
  235. package/src/browser-electron/provider.ts +0 -4571
  236. package/src/browser-electron/reference-route.ts +0 -608
  237. package/src/browser-electron/remote-host.ts +0 -1462
  238. package/src/browser-electron/rpc-input.ts +0 -13
  239. package/src/browser-electron/rpc-ops.ts +0 -41
  240. package/src/browser-electron/runtime-diagnostics.ts +0 -38
  241. package/src/browser-electron/runtime-route.ts +0 -105
  242. package/src/browser-electron/runtime-status.ts +0 -242
  243. package/src/browser-electron/settings-route.ts +0 -64
  244. package/src/browser-electron/settings-store.ts +0 -589
  245. package/src/browser-electron/shortcuts-route.ts +0 -112
  246. package/src/browser-electron/sidebar-only-host.ts +0 -298
  247. package/src/browser-electron/startpage-shortcuts.ts +0 -213
  248. package/src/browser-electron/system-browser.ts +0 -1497
  249. package/src/browser-electron/timing.ts +0 -16
  250. package/src/browser-electron/virtual-cursor.ts +0 -152
  251. package/src/browser-electron/windows-system.ts +0 -24
  252. package/src/browser-reference/delivery.ts +0 -384
  253. package/src/browser-reference/entry.ts +0 -631
  254. package/src/browser-reference/export.ts +0 -339
  255. package/src/browser-reference/import.ts +0 -303
  256. package/src/browser-reference/page-script.ts +0 -1537
  257. package/src/browser-reference/service.ts +0 -1315
  258. package/src/browser-reference/store.ts +0 -172
  259. package/src/browser-reference/submission-receipts.ts +0 -122
  260. package/src/browser-reference/text-quote.ts +0 -219
  261. package/src/browser-reference/types.ts +0 -195
  262. package/src/browser-reference/visible.ts +0 -367
  263. package/src/browser-reference/web-sources.ts +0 -103
  264. package/src/client/browser/BrowserController.ts +0 -693
  265. package/src/client/browser/BrowserFrame.ts +0 -78
  266. package/src/client/browser/BrowserNavigation.ts +0 -169
  267. package/src/client/browser/BrowserPage.ts +0 -23
  268. package/src/client/browser/BrowserPersistence.ts +0 -44
  269. package/src/client/browser/IframeImpl.ts +0 -176
  270. package/src/client/browser/child-tabs.ts +0 -14
  271. package/src/client/browser/iframe-reference.ts +0 -67
  272. package/src/client/browser/initialization.ts +0 -262
  273. package/src/client/browser/omnibox.ts +0 -243
  274. package/src/client/browser/store.ts +0 -38
  275. package/src/client/browser/takeover-channel.ts +0 -72
  276. package/src/client/browser/url.ts +0 -46
  277. package/src/client/browser/web-reference-source.ts +0 -52
  278. package/src/client/css-modules.d.ts +0 -4
  279. package/src/client/definition.tsx +0 -30
  280. package/src/client/electron/ElectronWebViewImpl.ts +0 -364
  281. package/src/client/electron/ElectronWebviewPresentation.ts +0 -138
  282. package/src/client/electron/NativeChildPresentation.ts +0 -45
  283. package/src/client/electron/NativeViewPage.ts +0 -251
  284. package/src/client/electron/pages.ts +0 -23
  285. package/src/client/electron/reference-overlay.ts +0 -53
  286. package/src/client/electron/workspace.ts +0 -33
  287. package/src/client/index.ts +0 -293
  288. package/src/client/locales.ts +0 -857
  289. package/src/client/pages.ts +0 -28
  290. package/src/client/reference/client/BrowserRefLink.tsx +0 -142
  291. package/src/client/reference/client/draft-reference.ts +0 -167
  292. package/src/client/reference/client/index.ts +0 -7
  293. package/src/client/reference/client/ordered-submission.ts +0 -108
  294. package/src/client/reference/client/pending-delivery.ts +0 -216
  295. package/src/client/reference/client/plugin.ts +0 -189
  296. package/src/client/reference/client/production/ReferenceCapsules.tsx +0 -345
  297. package/src/client/reference/client/production/ReferenceDock.module.css +0 -193
  298. package/src/client/reference/client/production/ReferenceDock.tsx +0 -6
  299. package/src/client/reference/client/production/ReferenceFeedback.tsx +0 -15
  300. package/src/client/reference/client/production/ReferenceMath.tsx +0 -44
  301. package/src/client/reference/client/production/ReferenceText.tsx +0 -36
  302. package/src/client/reference/client/production/assembly.ts +0 -471
  303. package/src/client/reference/client/production/asset-store.ts +0 -144
  304. package/src/client/reference/client/production/availability.ts +0 -74
  305. package/src/client/reference/client/production/bytes.ts +0 -36
  306. package/src/client/reference/client/production/delivery-client.ts +0 -211
  307. package/src/client/reference/client/production/draft-adapter.ts +0 -508
  308. package/src/client/reference/client/production/http-transport.ts +0 -217
  309. package/src/client/reference/client/production/production-submission.ts +0 -310
  310. package/src/client/reference/client/production/protocol.ts +0 -231
  311. package/src/client/reference/client/production/reference-card.ts +0 -240
  312. package/src/client/reference/client/production/reference-labels.ts +0 -29
  313. package/src/client/reference/client/production/reply-link-bridge.ts +0 -222
  314. package/src/client/reference/client/production/reveal.ts +0 -215
  315. package/src/client/reference/client/production/runtime.ts +0 -1101
  316. package/src/client/reference/client/production/snapshot-adapter.ts +0 -154
  317. package/src/client/reference/client/production/source-marker.ts +0 -63
  318. package/src/client/reference/client/production/source-opener.ts +0 -55
  319. package/src/client/reference/client/production/styles.ts +0 -104
  320. package/src/client/reference/client/production/user-text-rule.ts +0 -58
  321. package/src/client/reference/client/reveal.ts +0 -107
  322. package/src/client/reference/client/scheme.ts +0 -114
  323. package/src/client/reference/client/types.ts +0 -168
  324. package/src/client/reference/css-modules.d.ts +0 -4
  325. package/src/client/reference/index.ts +0 -11
  326. package/src/client/reference-capture-owner.ts +0 -162
  327. package/src/client/reference-intents.ts +0 -36
  328. package/src/client/settings/index.ts +0 -34
  329. package/src/client/settings/panel.ts +0 -2657
  330. package/src/client/shortcut-open.ts +0 -30
  331. package/src/client/startpage/binding.ts +0 -99
  332. package/src/client/startpage/controller.ts +0 -303
  333. package/src/client/startpage/model.ts +0 -279
  334. package/src/client/view/Browser.module.css +0 -751
  335. package/src/client/view/BrowserBody.tsx +0 -314
  336. package/src/client/view/BrowserPresentation.ts +0 -9
  337. package/src/client/view/BrowserTitle.tsx +0 -17
  338. package/src/client/view/IframePresentation.ts +0 -344
  339. package/src/client/view/StartPage.tsx +0 -597
  340. package/src/client/view/TakeoverBanner.tsx +0 -21
  341. package/src/index.ts +0 -110
  342. package/src/reference-owner.ts +0 -5
  343. package/src/reference-page.ts +0 -9
  344. package/src/reference-source.ts +0 -3
  345. package/src/reference-text.ts +0 -197
  346. package/src/startpage-settings.ts +0 -103
  347. package/src/startpage.ts +0 -71
  348. package/src/takeover-protocol.ts +0 -19
  349. package/src/tool-browser/code-tool.ts +0 -401
  350. package/src/tool-browser/code-worker.ts +0 -639
  351. package/src/tool-browser/element-fields.ts +0 -167
  352. package/src/tool-browser/index.ts +0 -3733
  353. package/src/tool-browser/page-probe.ts +0 -474
  354. package/src/tool-browser/panel-page.ts +0 -124
  355. package/src/tool-browser/screenshot-image.ts +0 -49
  356. package/src/tool-browser/takeover.ts +0 -198
  357. package/src/types/electron-shim.d.ts +0 -144
  358. package/src/types.ts +0 -85
  359. package/src/web-guest.ts +0 -34
  360. 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
- }