dsh-builtin-browser 1.0.1 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) 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-host-patch/README.md +4 -0
  22. package/dsh-host-patch/apply.mjs +61 -13
  23. package/dsh-host-patch/rc3-revision9.json.gz +0 -0
  24. package/dsh-host-patch/rc5-revision9.json.gz +0 -0
  25. package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
  26. package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
  27. package/dsh-host-patch/tauri-revision1.json +39 -0
  28. package/dsh-host-patch/tauri.json +43 -0
  29. package/dsh-host-patch/v023-alpha2.json +153 -0
  30. package/lib/browser/anti-bot.js +215 -0
  31. package/lib/browser/deep-dom.js +39 -0
  32. package/lib/browser/runtime.js +15 -0
  33. package/lib/browser/takeover-target.js +13 -6
  34. package/lib/browser/types.js +30 -1
  35. package/lib/browser-electron/authenticated-route.js +16 -2
  36. package/lib/browser-electron/automatic-maintenance.js +16 -10
  37. package/lib/browser-electron/bridge-connection.js +3 -8
  38. package/lib/browser-electron/bridge-install.js +2 -1
  39. package/lib/browser-electron/bridge-status.js +55 -26
  40. package/lib/browser-electron/desktop-bridge-host.js +7 -6
  41. package/lib/browser-electron/desktop-identity.js +28 -5
  42. package/lib/browser-electron/desktop-shell.js +64 -0
  43. package/lib/browser-electron/electron-provision.js +105 -18
  44. package/lib/browser-electron/entry.js +129 -44
  45. package/lib/browser-electron/extension-browser.js +4 -4
  46. package/lib/browser-electron/foreground-watch.js +134 -0
  47. package/lib/browser-electron/guest-cookie-jar.js +13 -13
  48. package/lib/browser-electron/guest-route.js +181 -32
  49. package/lib/browser-electron/guest-runtime.js +61 -10
  50. package/lib/browser-electron/guest-storage.js +2 -2
  51. package/lib/browser-electron/history-store.js +1 -5
  52. package/lib/browser-electron/host-main.js +8 -4
  53. package/lib/browser-electron/host-patch-maintenance.js +14 -8
  54. package/lib/browser-electron/maintenance-route.js +2 -1
  55. package/lib/browser-electron/missing-system-browser.js +5 -9
  56. package/lib/browser-electron/preferred-browser.js +7 -3
  57. package/lib/browser-electron/preview-route.js +9 -13
  58. package/lib/browser-electron/process-ownership.js +1 -1
  59. package/lib/browser-electron/profile-command.js +2 -1
  60. package/lib/browser-electron/profile-extension.js +5 -0
  61. package/lib/browser-electron/profile-lease.js +152 -47
  62. package/lib/browser-electron/provider-core.js +527 -0
  63. package/lib/browser-electron/provider-interaction.js +963 -0
  64. package/lib/browser-electron/provider-media.js +518 -0
  65. package/lib/browser-electron/provider-navigation.js +301 -0
  66. package/lib/browser-electron/provider-observation.js +623 -0
  67. package/lib/browser-electron/provider-tabs.js +372 -0
  68. package/lib/browser-electron/provider.js +150 -3301
  69. package/lib/browser-electron/reference-route.js +9 -18
  70. package/lib/browser-electron/remote-host.js +79 -34
  71. package/lib/browser-electron/runtime-status.js +56 -6
  72. package/lib/browser-electron/settings-store.js +3 -6
  73. package/lib/browser-electron/sidebar-only-host.js +1 -1
  74. package/lib/browser-electron/system-browser.js +539 -172
  75. package/lib/browser-electron/tauri-host.js +208 -0
  76. package/lib/browser-electron/virtual-cursor.js +23 -13
  77. package/lib/browser-reference/service.js +22 -4
  78. package/lib/browser-reference/web-sources.js +1 -1
  79. package/lib/client.js +43409 -0
  80. package/lib/compat/host-features.js +75 -0
  81. package/lib/reference-source.js +1 -1
  82. package/lib/reference-text.js +23 -1
  83. package/lib/takeover-protocol.js +1 -1
  84. package/lib/tool-browser/block-recovery.js +69 -0
  85. package/lib/tool-browser/code-tool.js +170 -19
  86. package/lib/tool-browser/code-worker.js +115 -20
  87. package/lib/tool-browser/errors.js +34 -0
  88. package/lib/tool-browser/index.js +66 -3593
  89. package/lib/tool-browser/page-probe.js +227 -28
  90. package/lib/tool-browser/panel-page.js +2 -1
  91. package/lib/tool-browser/probe-client.js +157 -0
  92. package/lib/tool-browser/screenshot-annotations.js +108 -0
  93. package/lib/tool-browser/state.js +337 -0
  94. package/lib/tool-browser/takeover.js +1 -1
  95. package/lib/tool-browser/tools-debug.js +862 -0
  96. package/lib/tool-browser/tools-interaction.js +993 -0
  97. package/lib/tool-browser/tools-navigation.js +807 -0
  98. package/lib/tool-browser/tools-observation.js +461 -0
  99. package/lib/tool-browser/tools-reference.js +293 -0
  100. package/lib/web-guest.js +1 -0
  101. package/package.json +16 -36
  102. package/scripts/build-client.mjs +305 -0
  103. package/scripts/build.mjs +15 -12
  104. package/scripts/fix-exports.mjs +6 -16
  105. package/scripts/install-electron.mjs +55 -5
  106. package/scripts/pack.mjs +99 -0
  107. package/scripts/publish-manifest.mjs +56 -0
  108. package/scripts/verify-exports.mjs +26 -15
  109. package/skills/dsh-builtin-browser/SKILL.md +27 -2
  110. package/skills/dsh-builtin-browser/references/batch.md +15 -0
  111. package/src/browser/anti-bot.ts +251 -0
  112. package/src/browser/deep-dom.ts +40 -0
  113. package/src/browser/runtime.ts +18 -0
  114. package/src/browser/takeover-target.ts +16 -7
  115. package/src/browser/types.ts +56 -3
  116. package/src/browser-electron/authenticated-route.ts +29 -4
  117. package/src/browser-electron/automatic-maintenance.ts +23 -13
  118. package/src/browser-electron/bridge-connection.ts +11 -10
  119. package/src/browser-electron/bridge-install.ts +2 -1
  120. package/src/browser-electron/bridge-status.ts +61 -22
  121. package/src/browser-electron/desktop-bridge-host.ts +9 -7
  122. package/src/browser-electron/desktop-identity.ts +38 -5
  123. package/src/browser-electron/desktop-shell.ts +100 -0
  124. package/src/browser-electron/electron-provision.ts +104 -18
  125. package/src/browser-electron/entry.ts +1378 -1299
  126. package/src/browser-electron/extension-browser.ts +11 -4
  127. package/src/browser-electron/foreground-watch.ts +142 -0
  128. package/src/browser-electron/guest-cookie-jar.ts +3 -2
  129. package/src/browser-electron/guest-route.ts +180 -32
  130. package/src/browser-electron/guest-runtime.ts +61 -10
  131. package/src/browser-electron/guest-storage.ts +5 -2
  132. package/src/browser-electron/history-store.ts +3 -6
  133. package/src/browser-electron/host-main.ts +8 -4
  134. package/src/browser-electron/host-patch-maintenance.ts +18 -9
  135. package/src/browser-electron/maintenance-route.ts +2 -1
  136. package/src/browser-electron/missing-system-browser.ts +11 -10
  137. package/src/browser-electron/preferred-browser.ts +13 -3
  138. package/src/browser-electron/preview-route.ts +9 -12
  139. package/src/browser-electron/process-ownership.ts +9 -3
  140. package/src/browser-electron/profile-command.ts +2 -1
  141. package/src/browser-electron/profile-extension.ts +5 -0
  142. package/src/browser-electron/profile-lease.ts +131 -35
  143. package/src/browser-electron/provider-core.ts +1107 -0
  144. package/src/browser-electron/provider-interaction.ts +1034 -0
  145. package/src/browser-electron/provider-media.ts +589 -0
  146. package/src/browser-electron/provider-navigation.ts +323 -0
  147. package/src/browser-electron/provider-observation.ts +664 -0
  148. package/src/browser-electron/provider-tabs.ts +372 -0
  149. package/src/browser-electron/provider.ts +158 -4063
  150. package/src/browser-electron/reference-route.ts +598 -608
  151. package/src/browser-electron/remote-host.ts +118 -42
  152. package/src/browser-electron/runtime-status.ts +80 -13
  153. package/src/browser-electron/settings-store.ts +10 -6
  154. package/src/browser-electron/sidebar-only-host.ts +4 -2
  155. package/src/browser-electron/system-browser.ts +537 -184
  156. package/src/browser-electron/tauri-host.ts +194 -0
  157. package/src/browser-electron/virtual-cursor.ts +24 -14
  158. package/src/browser-reference/service.ts +38 -7
  159. package/src/browser-reference/web-sources.ts +4 -1
  160. package/src/client/apply-guard.ts +22 -0
  161. package/src/client/browser/BrowserController.ts +3 -3
  162. package/src/client/browser/IframeImpl.ts +182 -176
  163. package/src/client/browser/frame-history.ts +125 -0
  164. package/src/client/browser/frame-state.ts +27 -0
  165. package/src/client/browser/web-reference-source.ts +5 -1
  166. package/src/client/definition.tsx +36 -30
  167. package/src/client/electron/ElectronWebViewImpl.ts +20 -13
  168. package/src/client/electron/ElectronWebviewPresentation.ts +4 -2
  169. package/src/client/electron/NativeChildPresentation.ts +11 -3
  170. package/src/client/electron/NativeViewPage.ts +19 -5
  171. package/src/client/index.ts +333 -293
  172. package/src/client/locales.ts +9 -6
  173. package/src/client/reference/client/plugin.ts +21 -2
  174. package/src/client/reference/client/production/ReferenceCapsules.tsx +3 -3
  175. package/src/client/reference/client/production/assembly.ts +4 -28
  176. package/src/client/reference/client/production/availability.ts +0 -2
  177. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  178. package/src/client/reference/client/production/draft-adapter.ts +4 -0
  179. package/src/client/reference/client/production/http-transport.ts +0 -5
  180. package/src/client/reference/client/production/production-submission.ts +50 -290
  181. package/src/client/reference/client/production/protocol.ts +7 -4
  182. package/src/client/reference/client/production/runtime.ts +41 -86
  183. package/src/client/reference/client/production/source-marker.ts +49 -13
  184. package/src/client/reference/client/production/user-text-rule.ts +10 -1
  185. package/src/client/reference/client/reveal.ts +3 -1
  186. package/src/client/reference/client/session-schedule.ts +36 -0
  187. package/src/client/settings/index.ts +8 -0
  188. package/src/client/settings/mount-guard.ts +31 -0
  189. package/src/client/settings/panel.ts +163 -52
  190. package/src/client/startpage/controller.ts +3 -6
  191. package/src/client/view/BrowserBody.tsx +2 -1
  192. package/src/client/view/IframePresentation.ts +37 -16
  193. package/src/client/view/StartPage.tsx +2 -1
  194. package/src/compat/host-features.ts +92 -0
  195. package/src/reference-source.ts +1 -1
  196. package/src/reference-text.ts +23 -1
  197. package/src/takeover-protocol.ts +11 -2
  198. package/src/tool-browser/block-recovery.ts +85 -0
  199. package/src/tool-browser/code-tool.ts +173 -19
  200. package/src/tool-browser/code-worker.ts +101 -15
  201. package/src/tool-browser/errors.ts +40 -0
  202. package/src/tool-browser/index.ts +66 -3534
  203. package/src/tool-browser/page-probe.ts +229 -28
  204. package/src/tool-browser/panel-page.ts +3 -1
  205. package/src/tool-browser/probe-client.ts +183 -0
  206. package/src/tool-browser/screenshot-annotations.ts +131 -0
  207. package/src/tool-browser/state.ts +375 -0
  208. package/src/tool-browser/takeover.ts +3 -2
  209. package/src/tool-browser/tools-debug.ts +806 -0
  210. package/src/tool-browser/tools-interaction.ts +956 -0
  211. package/src/tool-browser/tools-navigation.ts +786 -0
  212. package/src/tool-browser/tools-observation.ts +474 -0
  213. package/src/tool-browser/tools-reference.ts +294 -0
  214. package/src/web-guest.ts +35 -34
  215. package/dist/client.cjs +0 -43167
  216. package/dist/client.d.cts +0 -516
  217. package/dist/client.d.mts +0 -516
  218. package/dist/index.cjs +0 -92
  219. package/dist/index.d.mts +0 -2960
  220. package/dist/index.mjs +0 -24
  221. package/lib/browser-reference/submission-receipts.js +0 -139
  222. package/src/browser-reference/submission-receipts.ts +0 -122
@@ -65,15 +65,12 @@ export class HistoryStore {
65
65
  private limitsChanged = false
66
66
  private maxEntries: number
67
67
  private maxAgeMs: number
68
-
69
- /**
70
- * @param file - absolute path of the JSONL history file.
71
- * @param limits - retention overrides (entry count and age).
72
- */
68
+ private readonly file: string
73
69
  constructor(
74
- private readonly file: string = visitedHistoryPath(),
70
+ file: string = visitedHistoryPath(),
75
71
  limits: HistoryLimits = {},
76
72
  ) {
73
+ this.file = file
77
74
  this.maxEntries = limits.maxEntries ?? DEFAULT_MAX_ENTRIES
78
75
  this.maxAgeMs = (limits.maxAgeDays ?? DEFAULT_MAX_AGE_DAYS) * 24 * 60 * 60 * 1000
79
76
  // The first rewrite is due once the file has grown the slack past the cap.
@@ -44,7 +44,7 @@ import { writeFileNoReplace } from './file-write.ts'
44
44
  import { electronRuntimeDiagnosticLines } from './runtime-diagnostics.ts'
45
45
  import { createRpcLineReader } from './rpc-input.ts'
46
46
  import { tmpdir } from 'node:os'
47
- import { join } from 'node:path'
47
+ import { isAbsolute, join } from 'node:path'
48
48
  import { withTimeoutShared } from './timing.ts'
49
49
  import { dshHome } from './paths.ts'
50
50
 
@@ -65,10 +65,14 @@ for (const line of electronRuntimeDiagnosticLines(process.versions)) {
65
65
  // several Electron instances sharing Roaming\Electron fight over the GPU
66
66
  // cache/session locks, which can leave the window without a display surface
67
67
  // (capturePage then fails). A dedicated userData also persists cookies across
68
- // host restarts (on top of dsh_browser_auth). Must run before app is ready.
68
+ // host restarts (on top of dsh_browser_auth) unless an ephemeral userData dir
69
+ // is passed via DSH_BROWSER_USER_DATA_DIR. Must run before app is ready.
69
70
  try {
70
- const base = dshHome()
71
- app.setPath('userData', join(base, BROWSER_PROFILE_DIR))
71
+ const overrideUserData = process.env.DSH_BROWSER_USER_DATA_DIR
72
+ const userDataDir = typeof overrideUserData === 'string' && overrideUserData !== '' && isAbsolute(overrideUserData)
73
+ ? overrideUserData
74
+ : join(dshHome(), BROWSER_PROFILE_DIR)
75
+ app.setPath('userData', userDataDir)
72
76
  } catch (error) {
73
77
  process.stderr.write(`[dsh-browser host] userData setup failed: ${String(error)}\n`)
74
78
  }
@@ -8,7 +8,9 @@ import { isDirectLoopback } from './authenticated-route.ts'
8
8
  import { readJsonBody } from './http-body.ts'
9
9
  import { replyJson } from './json-reply.ts'
10
10
 
11
- export const HOST_PATCH_ROUTE = '/dsh-builtin-browser/host-patch-maintenance'
11
+ import { HOST_PATCH_ROUTE } from '../../assets/browser-policy.mjs'
12
+ export { HOST_PATCH_ROUTE }
13
+
12
14
  const sidebar = '@deepseek-ai/dsh-client-ui-sidebar-right'
13
15
 
14
16
  /** The registry owns the exact npm or source-checkout bundle served by this Host. */
@@ -18,7 +20,7 @@ export interface ServedClientModules {
18
20
  }
19
21
 
20
22
  interface PatchState extends HostPatchResult {
21
- readonly surface: 'web' | 'desktop'
23
+ readonly surface: 'web' | 'desktop' | 'tauri'
22
24
  readonly canInstall: boolean
23
25
  readonly canRestore: boolean
24
26
  readonly restartRequired: boolean
@@ -49,6 +51,8 @@ export function servedSidebarPackage(modules: ServedClientModules | undefined):
49
51
  export function createHostPatchMaintenance(deps: {
50
52
  readonly modules: () => ServedClientModules | undefined
51
53
  readonly desktop: () => boolean
54
+ /** The electron-rs runtime directory of the DSH Tauri hosting this process, if any. */
55
+ readonly tauri?: () => string | undefined
52
56
  }): (request: IncomingMessage, response: ServerResponse) => Promise<void> {
53
57
  let running = false
54
58
  return async (request, response) => {
@@ -56,13 +60,16 @@ export function createHostPatchMaintenance(deps: {
56
60
  if (!sameOrigin(request, request.method === 'POST') || !isDirectLoopback(request)) {
57
61
  replyJson(response, 403, { ok: false, error: 'same-origin-local-request-required' }); return
58
62
  }
59
- if (deps.desktop()) {
63
+ const tauri = deps.tauri?.()
64
+ if (tauri === undefined && deps.desktop()) {
60
65
  replyJson(response, request.method === 'GET' ? 200 : 409, { ok: request.method === 'GET', hostPatch: { surface: 'desktop', status: 'absent', canInstall: false, canRestore: false,
61
66
  restartRequired: false, reason: 'Use Desktop bridge maintenance to change host files after Desktop exits.' } }); return
62
67
  }
63
68
  let directory: string
64
69
  const modules = deps.modules()
65
- try { directory = servedSidebarPackage(modules) }
70
+ const surface = tauri === undefined ? 'web' : 'tauri'
71
+ const target = tauri === undefined ? 'lib/client.js' : 'runtime/browser.cjs'
72
+ try { directory = tauri ?? servedSidebarPackage(modules) }
66
73
  catch (error) {
67
74
  replyJson(response, request.method === 'GET' ? 200 : 409, { ok: request.method === 'GET', hostPatch: {
68
75
  surface: 'web', status: 'anchors mismatch', canInstall: false, canRestore: false, restartRequired: false, reason: String(error),
@@ -74,14 +81,16 @@ export function createHostPatchMaintenance(deps: {
74
81
  let writable = true
75
82
  let reason = result.reason
76
83
  try {
77
- for (const path of [join(directory, 'lib'), join(directory, 'lib/client.js')]) {
84
+ for (const path of [dirname(join(directory, target)), join(directory, target)]) {
78
85
  if ((statSync(path).mode & 0o222) === 0) throw new Error('read-only permissions')
79
86
  accessSync(path, constants.W_OK)
80
87
  }
81
- } catch (error) { writable = false; reason = 'The served sidebar package is not writable: ' + String(error) }
82
- return { ...result, ...(reason === undefined ? {} : { reason }), surface: 'web',
88
+ } catch (error) { writable = false; reason = `The ${surface === 'web' ? 'served sidebar package' : 'DSH Tauri runtime'} is not writable: ` + String(error) }
89
+ const needed = typeof patcher.hostPatchNeeded === 'function' ? patcher.hostPatchNeeded(directory) : undefined
90
+ return { ...result, ...(reason === undefined ? {} : { reason }), surface,
91
+ ...(needed === undefined ? {} : { needed }),
83
92
  canInstall: writable && result.status === 'absent',
84
- canRestore: writable && result.status === 'applied' && existsSync(join(directory, 'lib/client.js.before-dsh-host-patch')),
93
+ canRestore: writable && result.status === 'applied' && existsSync(join(directory, `${target}.before-dsh-host-patch`)),
85
94
  restartRequired: false }
86
95
  }
87
96
  if (request.method === 'GET') { replyJson(response, 200, { ok: true, hostPatch: read() }); return }
@@ -102,7 +111,7 @@ export function createHostPatchMaintenance(deps: {
102
111
  const ok = result.status === (action === 'install' ? 'applied' : 'absent')
103
112
  let restartRequired = ok && result.changed === true
104
113
  let reason = result.reason
105
- if (restartRequired && typeof modules?.rebuilt === 'function') {
114
+ if (restartRequired && surface === 'web' && typeof modules?.rebuilt === 'function') {
106
115
  try { modules.rebuilt(sidebar); restartRequired = false }
107
116
  catch (error) { reason = 'Files changed, but DSH could not refresh its bundle cache: ' + String(error) }
108
117
  }
@@ -6,7 +6,8 @@ import { replyJson } from './json-reply.ts'
6
6
  import { readJsonBody } from './http-body.ts'
7
7
  import type { AutomaticMaintenanceJob, AutomaticMaintenanceOptions } from './automatic-maintenance.ts'
8
8
 
9
- export const AUTOMATIC_MAINTENANCE_ROUTE = '/dsh-builtin-browser/bridge-maintenance'
9
+ import { AUTOMATIC_MAINTENANCE_ROUTE } from '../../assets/browser-policy.mjs'
10
+ export { AUTOMATIC_MAINTENANCE_ROUTE }
10
11
  export interface AutomaticMaintenanceRouteDeps {
11
12
  readonly supported: () => boolean
12
13
  /** How Desktop is asked to quit: `menu` waits for the panel to open the native menu, `self` needs nothing from it. */
@@ -42,10 +42,10 @@ const PRODUCT: Record<string, { label: string; install: string; variable: string
42
42
 
43
43
  /** How the setting is named to the user. */
44
44
  const SETTING_LABEL: Record<string, string> = {
45
- chrome: '本机 Chrome / installed Chrome',
46
- edge: '本机 Edge / installed Edge',
47
- auto: '自动 / automatic',
48
- bundled: '内置 / bundled',
45
+ chrome: 'installed Chrome',
46
+ edge: 'installed Edge',
47
+ auto: 'automatic',
48
+ bundled: 'bundled',
49
49
  }
50
50
 
51
51
  /**
@@ -55,11 +55,12 @@ const SETTING_LABEL: Record<string, string> = {
55
55
  * requested, where the plugin looked, and the three concrete ways to resolve it.
56
56
  */
57
57
  export class MissingSystemBrowserHost implements ElectronBrowserViewHost {
58
- /**
59
- * @param kind - the browser the user asked for.
60
- * @param searched - the names and locations that were checked, for the report.
61
- */
62
- constructor(private readonly kind: Exclude<BrowserChannel, 'bundled' | 'auto'>, private readonly searched: readonly string[]) {}
58
+ private readonly kind: Exclude<BrowserChannel, 'bundled' | 'auto'>
59
+ private readonly searched: readonly string[]
60
+ constructor(kind: Exclude<BrowserChannel, 'bundled' | 'auto'>, searched: readonly string[]) {
61
+ this.kind = kind
62
+ this.searched = searched
63
+ }
63
64
 
64
65
  /** @returns always true: see the module comment — reporting false would hide this. */
65
66
  available(): boolean {
@@ -86,7 +87,7 @@ export class MissingSystemBrowserHost implements ElectronBrowserViewHost {
86
87
  `To fix it, any ONE of these is enough:`,
87
88
  ` 1. ${product.install}, then restart DSH;`,
88
89
  ` 2. point ${product.variable} at its executable;`,
89
- ` 3. set the browser carrier back to "内置 / bundled" (or "自动 / automatic" to let it`,
90
+ ` 3. set the browser carrier back to "bundled" (or "automatic" to let it`,
90
91
  ` fall back on its own next time).`,
91
92
  ].join('\n')
92
93
  }
@@ -1,7 +1,7 @@
1
1
  import { EXTENSION_READY_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
2
2
  import { ExtensionBrowserViewHost } from './extension-browser.ts'
3
3
  import type { NativeBrowserClient } from '../../native-host/client.mjs'
4
- import type { ElectronBrowserViewHost, ElectronViewHandle } from './provider.ts'
4
+ import type { ElectronBrowserViewHost, ElectronViewHandle, QuietRevealOptions } from './provider.ts'
5
5
  import { readTabHandle, sessionWireId, type BrowserTabWireId } from '../browser/handles.ts'
6
6
  import type { BrowserSessionId } from '../browser/types.ts'
7
7
 
@@ -27,8 +27,13 @@ export class PreferredBrowserViewHost implements ElectronBrowserViewHost {
27
27
  private selected?: 'extension' | 'cdp'
28
28
  fallbackReason?: string
29
29
  private readonly extension: ExtensionBrowserViewHost
30
-
31
- constructor(readonly browser: 'edge' | 'chrome', readonly fallback: ElectronBrowserViewHost & { connectionStatus?: () => { connected: boolean; detail: string } }, client?: NativeBrowserClient, private readonly bound = EXTENSION_READY_TIMEOUT_MS) {
30
+ readonly browser: 'edge' | 'chrome'
31
+ readonly fallback: ElectronBrowserViewHost & { connectionStatus?: () => { connected: boolean; detail: string } }
32
+ private readonly bound = EXTENSION_READY_TIMEOUT_MS
33
+ constructor(browser: 'edge' | 'chrome', fallback: ElectronBrowserViewHost & { connectionStatus?: () => { connected: boolean; detail: string } }, client?: NativeBrowserClient, bound = EXTENSION_READY_TIMEOUT_MS) {
34
+ this.browser = browser
35
+ this.fallback = fallback
36
+ this.bound = bound
32
37
  this.extension = new ExtensionBrowserViewHost(browser, client)
33
38
  }
34
39
 
@@ -47,6 +52,11 @@ export class PreferredBrowserViewHost implements ElectronBrowserViewHost {
47
52
  ? this.fallback.connectionStatus?.().connected === true : this.extension.connectedView(id))
48
53
  }
49
54
 
55
+ async revealQuietWindow(handle: ElectronViewHandle, options?: QuietRevealOptions): Promise<boolean> {
56
+ const real = await this.mapped.get(handle.id)?.real?.catch(() => undefined)
57
+ return await real?.host.revealQuietWindow?.(real.handle, options) === true
58
+ }
59
+
50
60
  private route(scope: BrowserSessionId): Promise<ElectronBrowserViewHost> {
51
61
  if (this.released) return Promise.reject(new Error('browser carrier was released'))
52
62
  let route = this.routes.get(scope)
@@ -18,7 +18,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http'
18
18
  import type { BrowserError } from '../browser/types.ts'
19
19
  import { replyJson } from './json-reply.ts'
20
20
  import { sameOrigin } from './settings-route.ts'
21
- import { findDesktopInstall, readBridgeStatus } from './bridge-status.ts'
21
+ import { detectDesktopShell, readBridgeStatus } from './bridge-status.ts'
22
22
  import type { MainExtensionStatus } from './profile-extension.ts'
23
23
 
24
24
  /** Where the frame endpoint lives. The viewer must use exactly this path, same origin. */
@@ -195,6 +195,7 @@ export async function handleBridgeStatus(
195
195
  mainExtension?: MainExtensionStatus,
196
196
  registry?: () => readonly string[],
197
197
  conventions?: () => readonly string[],
198
+ preferredBrowser?: string,
198
199
  ): Promise<void> {
199
200
  if (request.method !== 'GET') {
200
201
  replyJson(response, 405, { error: 'method-not-allowed' })
@@ -204,15 +205,11 @@ export async function handleBridgeStatus(
204
205
  replyJson(response, 403, { error: 'not-same-origin' })
205
206
  return
206
207
  }
207
- const installRoot = findDesktopInstall(localAppData, registry, conventions)
208
- const status = installRoot === undefined
209
- ? {
210
- state: 'missing' as const,
211
- present: false,
212
- archivePresent: false,
213
- detail: 'no DSH Desktop install found in the usual roots, at DSH_DESKTOP_PATH or DSH_DESKTOP_APP, '
214
- + 'in the uninstall registry, or at this platform\'s conventional locations',
215
- }
216
- : readBridgeStatus(installRoot, mainExtension)
217
- replyJson(response, 200, { ok: true, bridge: status })
208
+ const shell = detectDesktopShell({ localAppData, registry, conventions, preferredBrowser })
209
+ // Only a verified official install is read for a bridge; any other shell is reported as missing
210
+ // without a repair command, and `shell` says why.
211
+ const status = shell.kind === 'official-supported' && shell.root !== undefined
212
+ ? readBridgeStatus(shell.root, mainExtension)
213
+ : { state: 'missing' as const, present: false, archivePresent: false, detail: shell.reason }
214
+ replyJson(response, 200, { ok: true, bridge: status, shell })
218
215
  }
@@ -119,9 +119,15 @@ function dataDirectory(argv: readonly string[]): string | undefined {
119
119
 
120
120
  export class BrowserProcessOwnership {
121
121
  private readonly records = new WeakMap<ChildProcess, { identity: ProcessIdentity; executable: string; directory: string }>()
122
-
123
- constructor(private readonly executable: string, private readonly directory: string,
124
- private readonly options: ProcessOwnershipOptions) {}
122
+ private readonly executable: string
123
+ private readonly directory: string
124
+ private readonly options: ProcessOwnershipOptions
125
+ constructor(executable: string, directory: string,
126
+ options: ProcessOwnershipOptions) {
127
+ this.executable = executable
128
+ this.directory = directory
129
+ this.options = options
130
+ }
125
131
 
126
132
  private live(child: ChildProcess): boolean {
127
133
  return Number.isSafeInteger(child.pid) && child.exitCode === null && child.signalCode === null
@@ -1,10 +1,11 @@
1
+ import { PROFILE_COMMAND_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
1
2
  import { execFile, spawn } from 'node:child_process'
2
3
  import { dirname, join } from 'node:path'
3
4
  import { windowsPowerShellPath } from './windows-system.ts'
4
5
  import { MaintenanceRecoveryError } from './maintenance-lifecycle.ts'
5
6
 
6
7
  /** Terminate the complete package-manager tree before allowing a profile rollback. */
7
- export async function runProfileCommand(command: string, args: readonly string[], environment: NodeJS.ProcessEnv, timeoutMs = 60_000): Promise<{ code: number; output: string }> {
8
+ export async function runProfileCommand(command: string, args: readonly string[], environment: NodeJS.ProcessEnv, timeoutMs = PROFILE_COMMAND_TIMEOUT_MS): Promise<{ code: number; output: string }> {
8
9
  const taskkill = process.platform === 'win32' ? join(dirname(dirname(dirname(windowsPowerShellPath(environment)))), 'taskkill.exe') : undefined
9
10
  return await new Promise((resolve, reject) => {
10
11
  const child = spawn(command, [...args], { env: environment, windowsHide: true, shell: false, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] })
@@ -110,7 +110,12 @@ function profileEnvironment(home: string, packedCli = false): NodeJS.ProcessEnv
110
110
  for (const key of Object.keys(env)) {
111
111
  if (key.toUpperCase() === 'ELECTRON_NO_ASAR') delete env[key]
112
112
  }
113
+ // `CI` makes pnpm non-interactive. Without it a reconcile answered a supply-chain prompt with
114
+ // "?" and exited non-zero, the maintenance transaction rolled back, and the bridge stayed
115
+ // "已失效" — a repair path that could not repair. The reporter is pinned for the same reason:
116
+ // an unattended command must produce a log, not a question.
113
117
  return { ...env, DSH_HOME: home, ELECTRON_RUN_AS_NODE: '1', ...(packedCli ? {} : { ELECTRON_NO_ASAR: '1' }),
118
+ CI: 'true', npm_config_reporter: 'append-only', PNPM_CONFIG_REPORTER: 'append-only',
114
119
  npm_config_ignore_scripts: 'true', npm_config_auto_install_peers: 'false',
115
120
  PNPM_CONFIG_IGNORE_SCRIPTS: 'true', PNPM_CONFIG_AUTO_INSTALL_PEERS: 'false' }
116
121
  }
@@ -1,23 +1,88 @@
1
1
  import { closeSync, mkdirSync, openSync, readFileSync, realpathSync, rmdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
2
- import { randomUUID } from 'node:crypto'
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import { connect, createServer, type Server } from 'node:net'
4
+ import { execFileSync } from 'node:child_process'
3
5
  import { basename, dirname, join } from 'node:path'
4
6
 
5
7
  const STALE_GUARD_MS = 10_000
8
+ const PIPE_PROBE_MS = 1000
9
+ const PIPE_PREFIX = '\\\\.\\pipe\\dsh-browser-lease-'
10
+ /**
11
+ * How the OS identifies process `pid`'s start, as an opaque string; undefined when it cannot tell.
12
+ * Owner and checker derive it the same way from the same OS record, so clock or DST changes cancel out.
13
+ */
14
+ export function processIdentity(pid: number): string | undefined {
15
+ try {
16
+ if (process.platform === 'win32') return undefined
17
+ if (process.platform === 'linux') {
18
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
19
+ return stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19] || undefined
20
+ }
21
+ const text = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], { encoding: 'utf8', timeout: 2000, env: { ...process.env, TZ: 'UTC', LC_ALL: 'C' } })
22
+ return text.trim() || undefined
23
+ } catch {
24
+ return undefined
25
+ }
26
+ }
27
+
28
+ let ownIdentity: string | undefined
29
+
30
+ /** A named pipe exists only while its server is open, so it dies with the owner however that ends. */
31
+ function openOwnerPipe(root: string, token: string): Promise<{ readonly name: string; readonly server: Server } | undefined> {
32
+ const name = `${PIPE_PREFIX}${createHash('sha256').update(root).digest('hex').slice(0, 32)}-${token}`
33
+ return new Promise(resolve => {
34
+ const server = createServer(socket => socket.destroy())
35
+ server.once('error', () => resolve(undefined))
36
+ server.listen(name, () => { server.unref(); resolve({ name, server }) })
37
+ })
38
+ }
39
+
40
+ function pipeAnswers(name: string): Promise<boolean> {
41
+ return new Promise(resolve => {
42
+ const socket = connect(name)
43
+ const done = (alive: boolean): void => { clearTimeout(timer); socket.destroy(); resolve(alive) }
44
+ const timer = setTimeout(() => done(true), PIPE_PROBE_MS)
45
+ socket.once('connect', () => done(true))
46
+ socket.once('error', error => {
47
+ const code = (error as NodeJS.ErrnoException).code
48
+ done(code !== 'ENOENT' && code !== 'ECONNREFUSED')
49
+ })
50
+ })
51
+ }
52
+
53
+ /** A live PID is still the owner only if the OS ties it to the owner; Windows reuses PIDs quickly. */
54
+ async function ownerAlive(owner: { pid?: unknown; pipe?: unknown; identity?: unknown }): Promise<boolean> {
55
+ try { process.kill(Number(owner.pid), 0) }
56
+ catch (error) { return (error as NodeJS.ErrnoException).code !== 'ESRCH' }
57
+ if (process.platform === 'win32') {
58
+ return typeof owner.pipe !== 'string' || !owner.pipe.startsWith(PIPE_PREFIX) || await pipeAnswers(owner.pipe)
59
+ }
60
+ if (typeof owner.identity !== 'string' || owner.identity === '') return true
61
+ const actual = processIdentity(Number(owner.pid))
62
+ return actual === undefined || actual === owner.identity
63
+ }
6
64
 
7
65
  export interface ProfileLease {
8
66
  release(cleanup?: () => void): Promise<void>
9
67
  }
10
68
 
11
- function isStaleGuard(guardPath: string, leasePath: string): boolean {
69
+ async function isStaleGuard(guardPath: string, leasePath: string): Promise<boolean> {
12
70
  try {
13
- const ownerPath = statSync(guardPath).isDirectory() ? leasePath : guardPath
14
- const raw = JSON.parse(readFileSync(ownerPath, 'utf8')) as { pid?: unknown } | null
71
+ const isDir = statSync(guardPath).isDirectory()
72
+ const ownerPath = isDir ? leasePath : guardPath
73
+ const rawText = readFileSync(ownerPath, 'utf8')
74
+ const raw = JSON.parse(rawText) as { pid?: unknown; pipe?: unknown; identity?: unknown } | null
15
75
  if (raw && Number.isSafeInteger(raw.pid) && Number(raw.pid) > 0) {
16
- try { process.kill(Number(raw.pid), 0) }
17
- catch (error) {
18
- if ((error as NodeJS.ErrnoException).code === 'ESRCH') return true
76
+ if (await ownerAlive(raw)) return false
77
+ // Re-verify the guard has not already been released or replaced by a live successor
78
+ // while we were probing its owner's liveness.
79
+ try {
80
+ const after = statSync(guardPath)
81
+ if (isDir) return after.isDirectory()
82
+ return !after.isDirectory() && readFileSync(guardPath, 'utf8') === rawText
83
+ } catch {
84
+ return false
19
85
  }
20
- return false
21
86
  }
22
87
  } catch { /* fall through to mtime check */ }
23
88
  try {
@@ -28,25 +93,43 @@ function isStaleGuard(guardPath: string, leasePath: string): boolean {
28
93
  }
29
94
 
30
95
  /** Exclusive ownership of the plugin profile, including launch and shutdown. */
31
- export function acquireProfileLease(directory: string): ProfileLease {
96
+ export async function acquireProfileLease(directory: string): Promise<ProfileLease> {
32
97
  mkdirSync(directory, { recursive: true })
33
98
  const root = realpathSync(directory)
34
99
  const file = join(root, '.dsh-browser-lease.json')
35
100
  const guard = join(dirname(root), `.${basename(root)}.dsh-browser-lease.guard`)
36
101
  const token = randomUUID()
102
+ const identity = ownIdentity ??= processIdentity(process.pid)
103
+ let pipe: { readonly name: string; readonly server: Server } | undefined
37
104
  const busy = (): Error => new Error(`dsh-builtin-browser: browser profile is leased or its ownership cannot be verified: ${root}`)
38
- const guarded = <T>(operation: () => T): T => {
105
+ const guarded = async <T>(operation: () => T | Promise<T>): Promise<T> => {
39
106
  let acquired = false
107
+ let guardPipe: { readonly name: string; readonly server: Server } | undefined
40
108
  for (let attempt = 0; attempt < 2; attempt += 1) {
41
109
  let fd: number | undefined
42
110
  try {
43
111
  fd = openSync(guard, 'wx', 0o600)
44
- writeFileSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }))
112
+ const guardToken = randomUUID()
113
+ if (process.platform === 'win32') guardPipe = await openOwnerPipe(root, `guard-${guardToken}`)
114
+ writeFileSync(fd, JSON.stringify({
115
+ pid: process.pid,
116
+ at: Date.now(),
117
+ token: guardToken,
118
+ ...(identity === undefined ? {} : { identity }),
119
+ ...(guardPipe === undefined ? {} : { pipe: guardPipe.name }),
120
+ }))
45
121
  acquired = true
46
122
  break
47
123
  } catch (error) {
124
+ if (fd !== undefined) {
125
+ try { closeSync(fd) } catch {}
126
+ fd = undefined
127
+ try { unlinkSync(guard) } catch {}
128
+ }
129
+ guardPipe?.server.close()
130
+ guardPipe = undefined
48
131
  if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw busy()
49
- if (attempt === 0 && isStaleGuard(guard, file)) {
132
+ if (attempt === 0 && await isStaleGuard(guard, file)) {
50
133
  try {
51
134
  if (statSync(guard).isDirectory()) rmdirSync(guard)
52
135
  else unlinkSync(guard)
@@ -58,33 +141,45 @@ export function acquireProfileLease(directory: string): ProfileLease {
58
141
  if (fd !== undefined) { try { closeSync(fd) } catch {} }
59
142
  }
60
143
  }
61
- if (!acquired) throw busy()
62
- try { return operation() } finally {
63
- try { unlinkSync(guard) } catch (error) {
64
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
144
+ if (!acquired) {
145
+ guardPipe?.server.close()
146
+ throw busy()
147
+ }
148
+ try { return await operation() } finally {
149
+ try {
150
+ // Unlink before closing the liveness pipe so another contender probing the pipe
151
+ // never sees a still-present guard file after a normal release.
152
+ try { unlinkSync(guard) } catch (error) {
153
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
154
+ }
155
+ } finally {
156
+ guardPipe?.server.close()
65
157
  }
66
158
  }
67
159
  }
68
- guarded(() => {
69
- let previous: unknown
70
- try { previous = JSON.parse(readFileSync(file, 'utf8')) }
71
- catch (error) {
72
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw busy()
73
- previous = undefined
74
- }
75
- if (previous !== undefined) {
76
- const owner = previous as { pid?: unknown; token?: unknown } | null
77
- if (!owner || !Number.isSafeInteger(owner.pid) || Number(owner.pid) <= 0 || typeof owner.token !== 'string') throw busy()
78
- try { process.kill(Number(owner.pid), 0); throw busy() }
160
+ try {
161
+ await guarded(async () => {
162
+ let previous: unknown
163
+ try { previous = JSON.parse(readFileSync(file, 'utf8')) }
79
164
  catch (error) {
80
- if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw busy()
165
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw busy()
166
+ previous = undefined
81
167
  }
82
- unlinkSync(file)
83
- }
84
- const fd = openSync(file, 'wx', 0o600)
85
- try { writeFileSync(fd, JSON.stringify({ pid: process.pid, token })) }
86
- finally { closeSync(fd) }
87
- })
168
+ if (previous !== undefined) {
169
+ const owner = previous as { pid?: unknown; token?: unknown } | null
170
+ if (!owner || !Number.isSafeInteger(owner.pid) || Number(owner.pid) <= 0 || typeof owner.token !== 'string') throw busy()
171
+ if (await ownerAlive(owner as { pid?: unknown; pipe?: unknown; identity?: unknown })) throw busy()
172
+ unlinkSync(file)
173
+ }
174
+ if (process.platform === 'win32') pipe = await openOwnerPipe(root, token)
175
+ const fd = openSync(file, 'wx', 0o600)
176
+ try { writeFileSync(fd, JSON.stringify({ pid: process.pid, token, ...(identity === undefined ? {} : { identity }), ...(pipe === undefined ? {} : { pipe: pipe.name }) })) }
177
+ finally { closeSync(fd) }
178
+ })
179
+ } catch (error) {
180
+ pipe?.server.close()
181
+ throw error
182
+ }
88
183
  let released = false
89
184
  return {
90
185
  async release(cleanup) {
@@ -92,7 +187,7 @@ export function acquireProfileLease(directory: string): ProfileLease {
92
187
  const deadline = Date.now() + 1000
93
188
  for (;;) {
94
189
  try {
95
- guarded(() => {
190
+ await guarded(() => {
96
191
  let owner: { token?: unknown }
97
192
  try { owner = JSON.parse(readFileSync(file, 'utf8')) as { token?: unknown } }
98
193
  catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error }
@@ -104,6 +199,7 @@ export function acquireProfileLease(directory: string): ProfileLease {
104
199
  }
105
200
  })
106
201
  released = true
202
+ pipe?.server.close()
107
203
  return
108
204
  } catch (error) {
109
205
  if (Date.now() >= deadline) throw error