dsh-builtin-browser 0.5.6 → 0.5.8

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 (119) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.en.md +75 -81
  3. package/README.md +75 -82
  4. package/client.js +831 -384
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +322 -141
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +157 -19
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/tool-reference.md +20 -1
  11. package/docs/user-guide.md +28 -4
  12. package/lib/browser/runtime.d.ts +3 -1
  13. package/lib/browser/runtime.js +9 -0
  14. package/lib/browser/types.d.ts +42 -0
  15. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  16. package/lib/browser-electron/authenticated-route.js +39 -0
  17. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  18. package/lib/browser-electron/automatic-maintenance.js +426 -0
  19. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  20. package/lib/browser-electron/bridge-auto.js +113 -0
  21. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  22. package/lib/browser-electron/bridge-connection.js +2 -4
  23. package/lib/browser-electron/bridge-endpoint.js +8 -19
  24. package/lib/browser-electron/bridge-install.d.ts +85 -0
  25. package/lib/browser-electron/bridge-install.js +211 -0
  26. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  27. package/lib/browser-electron/bridge-maintenance.js +125 -0
  28. package/lib/browser-electron/bridge-status.d.ts +10 -3
  29. package/lib/browser-electron/bridge-status.js +74 -24
  30. package/lib/browser-electron/desktop-bridge-host.d.ts +11 -5
  31. package/lib/browser-electron/desktop-bridge-host.js +67 -25
  32. package/lib/browser-electron/desktop-identity.js +21 -9
  33. package/lib/browser-electron/electron-provision.d.ts +1 -1
  34. package/lib/browser-electron/electron-provision.js +36 -13
  35. package/lib/browser-electron/entry.js +173 -67
  36. package/lib/browser-electron/ephemeral-profile.js +67 -26
  37. package/lib/browser-electron/history-store.js +2 -2
  38. package/lib/browser-electron/host-main.js +48 -38
  39. package/lib/browser-electron/http-body.d.ts +24 -0
  40. package/lib/browser-electron/http-body.js +33 -0
  41. package/lib/browser-electron/json-reply.d.ts +13 -1
  42. package/lib/browser-electron/json-reply.js +16 -2
  43. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  44. package/lib/browser-electron/maintenance-broker.js +114 -0
  45. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  46. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  47. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  48. package/lib/browser-electron/maintenance-route.js +75 -0
  49. package/lib/browser-electron/paths.d.ts +4 -0
  50. package/lib/browser-electron/paths.js +19 -0
  51. package/lib/browser-electron/process.d.ts +14 -0
  52. package/lib/browser-electron/process.js +24 -0
  53. package/lib/browser-electron/provider.d.ts +16 -9
  54. package/lib/browser-electron/provider.js +87 -18
  55. package/lib/browser-electron/remote-host.js +22 -20
  56. package/lib/browser-electron/runtime-route.d.ts +3 -5
  57. package/lib/browser-electron/runtime-status.d.ts +27 -13
  58. package/lib/browser-electron/runtime-status.js +28 -6
  59. package/lib/browser-electron/settings-route.d.ts +5 -18
  60. package/lib/browser-electron/settings-route.js +4 -14
  61. package/lib/browser-electron/settings-store.d.ts +28 -0
  62. package/lib/browser-electron/settings-store.js +32 -2
  63. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  64. package/lib/browser-electron/sidebar-only-host.js +192 -0
  65. package/lib/browser-electron/system-browser.d.ts +6 -11
  66. package/lib/browser-electron/system-browser.js +29 -24
  67. package/lib/browser-electron/timing.d.ts +8 -0
  68. package/lib/browser-electron/timing.js +13 -0
  69. package/lib/browser-electron/windows-system.d.ts +3 -0
  70. package/lib/browser-electron/windows-system.js +19 -0
  71. package/lib/tool-browser/index.js +1045 -7
  72. package/lib/tool-browser/page-probe.d.ts +86 -0
  73. package/lib/tool-browser/page-probe.js +460 -0
  74. package/package.json +5 -3
  75. package/scripts/run-tests.mjs +32 -0
  76. package/scripts/verify-preview-route.mjs +19 -1
  77. package/scripts/verify-runtime-status.mjs +14 -0
  78. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  79. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  80. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  81. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  82. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  83. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  84. package/src/browser/runtime.ts +11 -0
  85. package/src/browser/types.ts +19 -0
  86. package/src/browser-electron/authenticated-route.ts +56 -0
  87. package/src/browser-electron/automatic-maintenance.ts +414 -0
  88. package/src/browser-electron/bridge-auto.ts +158 -0
  89. package/src/browser-electron/bridge-connection.ts +2 -4
  90. package/src/browser-electron/bridge-endpoint.ts +8 -18
  91. package/src/browser-electron/bridge-install.ts +253 -0
  92. package/src/browser-electron/bridge-maintenance.ts +161 -0
  93. package/src/browser-electron/bridge-status.ts +76 -26
  94. package/src/browser-electron/desktop-bridge-host.ts +60 -26
  95. package/src/browser-electron/desktop-identity.ts +18 -9
  96. package/src/browser-electron/electron-provision.ts +35 -14
  97. package/src/browser-electron/entry.ts +152 -62
  98. package/src/browser-electron/ephemeral-profile.ts +65 -28
  99. package/src/browser-electron/history-store.ts +2 -2
  100. package/src/browser-electron/host-main.ts +40 -34
  101. package/src/browser-electron/http-body.ts +42 -0
  102. package/src/browser-electron/json-reply.ts +18 -3
  103. package/src/browser-electron/maintenance-broker.ts +142 -0
  104. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  105. package/src/browser-electron/maintenance-route.ts +64 -0
  106. package/src/browser-electron/paths.ts +21 -0
  107. package/src/browser-electron/process.ts +23 -0
  108. package/src/browser-electron/provider.ts +106 -22
  109. package/src/browser-electron/remote-host.ts +23 -23
  110. package/src/browser-electron/runtime-route.ts +3 -5
  111. package/src/browser-electron/runtime-status.ts +56 -19
  112. package/src/browser-electron/settings-route.ts +9 -32
  113. package/src/browser-electron/settings-store.ts +59 -3
  114. package/src/browser-electron/sidebar-only-host.ts +199 -0
  115. package/src/browser-electron/system-browser.ts +26 -23
  116. package/src/browser-electron/timing.ts +16 -0
  117. package/src/browser-electron/windows-system.ts +23 -0
  118. package/src/tool-browser/index.ts +995 -10
  119. package/src/tool-browser/page-probe.ts +474 -0
@@ -1,15 +1,14 @@
1
1
  @echo off
2
- REM Install (or repair) the desktop bridge and restart DSH Desktop, in one step.
2
+ REM Install (or repair) the bridge after DSH Desktop has exited, then start Desktop.
3
3
  REM
4
- REM Reported as issue #36: installing by hand meant closing DSH first, because the archive cannot be
5
- REM moved while the shell holds it, and every "wait for the exit" arrangement lost its waiter. This
6
- REM runs the installer with --restart, which closes the shell itself, installs, and starts it again.
4
+ REM Exit DSH Desktop normally before running this file from an external terminal.
5
+ REM A running target is refused; this launcher does not close or terminate it.
7
6
  REM
8
7
  REM No arguments needed: the installer probes for the install directory. Pass one to override it.
9
8
  REM install-and-start.cmd "C:\path\to\DSH Desktop"
10
9
  REM install-and-start.cmd "C:\path\to\DSH Desktop" --yes
11
10
  REM
12
- REM --yes skips the confirmation prompt; without it the installer asks before closing DSH.
11
+ REM Legacy --yes is accepted for command-line compatibility; it does not permit closing Desktop.
13
12
 
14
13
  setlocal
15
14
  set "HERE=%~dp0"
@@ -61,16 +61,76 @@
61
61
  * Default path: probed under %LOCALAPPDATA%\Programs (see findDefaultInstall)
62
62
  * Pass --revert to restore the pre-bridge state instead.
63
63
  *
64
- * Pass --restart to have THIS process close DSH, install, and start it again. That is the supported
65
- * way to install while the shell is running: the archive cannot be moved while the shell holds it,
66
- * and nothing started from outside survives the exit far enough to install afterwards (issue #36).
67
- * --restart asks for confirmation on a console; add --yes for an unattended run.
64
+ * Exit DSH Desktop normally before maintenance. --restart is an external-terminal opt-in to
65
+ * start the already-closed app after maintenance; it never closes a running application.
68
66
  */
69
- import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
67
+ import * as nodeFs from 'node:fs'
70
68
  import { execFileSync, spawn } from 'node:child_process'
71
- import { dirname, join } from 'node:path'
69
+ import { createRequire } from 'node:module'
72
70
 
73
- const DEFAULT_INSTALL = findDefaultInstall()
71
+ /**
72
+ * The filesystem used for every installer operation.
73
+ *
74
+ * Electron patches `fs` so that a `*.asar` path answers from the archive's virtual tree; opening the
75
+ * archive to read its header then fails with ENOENT (measured when the panel's button ran this file
76
+ * from the desktop shell). Even a patched existsSync(app.asar) creates Electron's archive cache
77
+ * and keeps a Windows handle open until process exit. A raw rename cannot release that cache.
78
+ * Use the same untouched module for discovery, validation, extraction and rename, so no earlier
79
+ * probe can lock the file this process later moves. Plain Node uses its ordinary filesystem.
80
+ */
81
+ const archiveFs = (() => {
82
+ try {
83
+ return createRequire(import.meta.url)('original-fs')
84
+ } catch {
85
+ return nodeFs
86
+ }
87
+ })()
88
+ const { closeSync, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readSync,
89
+ readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } = archiveFs
90
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
91
+
92
+ function isWithin(root, path) {
93
+ const part = relative(root, path)
94
+ return part !== '' && part !== '..' && !part.startsWith('..\\') && !part.startsWith('../') && !isAbsolute(part)
95
+ }
96
+
97
+ /** Tests may inspect or modify only an explicitly marked, canonical sandbox. */
98
+ function testBoundary() {
99
+ if (process.env.DSH_BROWSER_TEST !== '1' && process.env.NODE_TEST_CONTEXT === undefined) return undefined
100
+ const configured = process.env.DSH_BRIDGE_TEST_ROOT
101
+ if (!configured || !isAbsolute(configured) || lstatSync(configured).isSymbolicLink()) {
102
+ throw new Error('installer test isolation requires an absolute, non-linked DSH_BRIDGE_TEST_ROOT')
103
+ }
104
+ const root = realpathSync(configured)
105
+ const marker = join(root, '.dsh-bridge-test-root')
106
+ if (!lstatSync(marker).isFile() || lstatSync(marker).isSymbolicLink()
107
+ || readFileSync(marker, 'utf8') !== 'dsh-browser-installer-test-root-v1\n') {
108
+ throw new Error('installer test isolation marker is missing or invalid')
109
+ }
110
+ return root
111
+ }
112
+
113
+ function assertTestTarget(root, path) {
114
+ if (root === undefined) return
115
+ if (!isWithin(root, resolve(path)) || !isWithin(root, realpathSync(path))) {
116
+ throw new Error('installer test target must stay strictly inside DSH_BRIDGE_TEST_ROOT')
117
+ }
118
+ const inspect = directory => {
119
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
120
+ if (entry.isSymbolicLink()) throw new Error('installer test targets cannot contain linked files or directories')
121
+ if (entry.isDirectory()) inspect(join(directory, entry.name))
122
+ }
123
+ }
124
+ inspect(path)
125
+ for (const key of ['DSH_BRIDGE_ACTION_RESULT_FILE', 'DSH_BRIDGE_ACTION_LOG_FILE']) {
126
+ const output = process.env[key]
127
+ if (output !== undefined && (!isWithin(root, resolve(output))
128
+ || !isWithin(root, realpathSync(dirname(output)))
129
+ || (existsSync(output) && !isWithin(root, realpathSync(output))))) {
130
+ throw new Error('installer test result and log files must stay inside DSH_BRIDGE_TEST_ROOT')
131
+ }
132
+ }
133
+ }
74
134
  /**
75
135
  * The desktop install to patch when none is given on the command line.
76
136
  *
@@ -80,25 +140,51 @@ const DEFAULT_INSTALL = findDefaultInstall()
80
140
  * `resources/app.asar` — is stable across both, so that is what is probed.
81
141
  * @returns the install directory, or the historical default when nothing matches.
82
142
  */
83
- function findDefaultInstall() {
84
- const programs = join(process.env.LOCALAPPDATA ?? '', 'Programs')
85
- const looksInstalled = candidate => existsSync(join(candidate, 'resources', 'app', 'lib', 'main.js'))
86
- || existsSync(join(candidate, 'resources', 'app.asar'))
87
- for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
88
- const candidate = join(programs, named)
89
- if (looksInstalled(candidate)) return candidate
143
+ function findDefaultInstall(testRoot) {
144
+ const permitted = candidate => {
145
+ if (testRoot === undefined) return true
146
+ if (!isWithin(testRoot, resolve(candidate))) return false
147
+ try { return isWithin(testRoot, realpathSync(candidate)) } catch { return false }
90
148
  }
91
- try {
92
- for (const entry of readdirSync(programs, { withFileTypes: true })) {
93
- if (!entry.isDirectory()) continue
94
- const candidate = join(programs, entry.name)
149
+ const looksInstalled = candidate => permitted(candidate) && (existsSync(join(candidate, 'resources', 'app', 'lib', 'main.js'))
150
+ || existsSync(join(candidate, 'resources', 'app.asar')))
151
+ const probe = (base) => {
152
+ if (!permitted(base)) return undefined
153
+ for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
154
+ const candidate = join(base, named)
95
155
  if (looksInstalled(candidate)) return candidate
96
156
  }
97
- } catch {
98
- // No Programs directory, or it cannot be read: fall through so the error below names a
99
- // concrete path instead of throwing before the check that explains what to pass.
157
+ try {
158
+ for (const entry of readdirSync(base, { withFileTypes: true })) {
159
+ if (!entry.isDirectory()) continue
160
+ const candidate = join(base, entry.name)
161
+ if (looksInstalled(candidate)) return candidate
162
+ }
163
+ } catch {
164
+ // A root that does not exist is a state, not an error.
165
+ }
166
+ return undefined
100
167
  }
101
- return join(programs, 'DeepSeek Harness')
168
+ // Same roots the panel probes: an explicit DSH_DESKTOP_PATH, then the places people actually install
169
+ // to. An install on another drive used to be invisible to both the panel and this default.
170
+ const explicit = process.env.DSH_DESKTOP_PATH
171
+ if (explicit !== undefined && explicit !== '') {
172
+ if (looksInstalled(explicit)) return explicit
173
+ const below = probe(explicit)
174
+ if (below !== undefined) return below
175
+ }
176
+ const localAppData = process.env.LOCALAPPDATA ?? ''
177
+ const roots = [
178
+ ...(localAppData === '' ? [] : [join(localAppData, 'Programs')]),
179
+ process.env['ProgramFiles'], process.env['ProgramFiles(x86)'], process.env.APPDATA, process.env.ProgramData,
180
+ ].filter(base => typeof base === 'string' && base !== '')
181
+ for (const base of roots) {
182
+ const found = probe(base)
183
+ if (found !== undefined) return found
184
+ }
185
+ return testRoot === undefined
186
+ ? join(localAppData === '' ? '.' : join(localAppData, 'Programs'), 'DeepSeek Harness')
187
+ : join(testRoot, 'no-test-desktop-found')
102
188
  }
103
189
 
104
190
  /**
@@ -118,30 +204,66 @@ function withoutOurSnippet(text) {
118
204
  }
119
205
 
120
206
  /**
121
- * Every process whose image is the desktop shell.
122
- *
123
- * Matched by executable name because that is what the installed product uses, and because a
124
- * process-id based approach would miss the children Electron spawns for the renderer and GPU — any
125
- * of which holds the archive. The install root's own path is checked where a command line is
126
- * readable, so a second installation of the same product is not closed by mistake.
127
- * @param root - the install directory whose processes count as this shell.
128
- * @returns the matching process ids and names.
207
+ * Select only the GUI processes owned by this installation.
208
+ * Native DSH CLI processes share the same executable but run JavaScript in Node mode.
209
+ * @param rows - the process table, including parent ids for the installer's ancestry.
210
+ * @param root - verified Desktop installation directory.
211
+ * @param selfPid - the installer process.
212
+ * @returns GUI and Chromium helper process ids.
213
+ */
214
+ function selectShellProcesses(rows, root, selfPid) {
215
+ const byPid = new Map(rows.map(row => [row.ProcessId, row]))
216
+ const ancestors = new Set()
217
+ let cursor = selfPid
218
+ while (typeof cursor === 'number' && cursor > 0 && !ancestors.has(cursor)) {
219
+ ancestors.add(cursor)
220
+ cursor = byPid.get(cursor)?.ParentProcessId
221
+ }
222
+ const expectedExe = resolve(root, 'DeepSeek Harness.exe').toLowerCase()
223
+ const selected = []
224
+ for (const row of rows) {
225
+ if (String(row.Name ?? '').toLowerCase() !== 'deepseek harness.exe') continue
226
+ if (typeof row.ExecutablePath !== 'string' || row.ExecutablePath === '') {
227
+ throw new Error('could not identify a running DeepSeek Harness process; refusing to close or patch the application')
228
+ }
229
+ if (resolve(row.ExecutablePath).toLowerCase() !== expectedExe) continue
230
+ if (!Number.isSafeInteger(row.ProcessId) || row.ProcessId <= 0 || typeof row.CommandLine !== 'string') {
231
+ throw new Error('the Desktop process table is incomplete; refusing to close or patch the application')
232
+ }
233
+ if (row.ProcessId === selfPid) continue
234
+ const nodeMode = /(?:^|\s)--expose-internals(?:\s|$)|\.[cm]?js(?:"|\s|$)|(?:^|\s)(?:--eval|--print|--input-type)(?:=|\s|$)|(?:^|\s)-(?:e|p)(?:\s|$)/i.test(row.CommandLine)
235
+ if (nodeMode) continue
236
+ if (ancestors.has(row.ProcessId)) {
237
+ const error = new Error('the installer is a child of DSH Desktop; run this command from a separate terminal with Node.js')
238
+ error.code = 'DSH_CHILD_OF_SHELL'
239
+ throw error
240
+ }
241
+ selected.push(row.ProcessId)
242
+ }
243
+ return selected
244
+ }
245
+
246
+ /**
247
+ * Read the complete process table so ancestry is available before any process is closed.
248
+ * Enumeration failure refuses the install rather than treating the shell as stopped.
249
+ * @param root - verified Desktop installation directory.
250
+ * @returns GUI and Chromium helper process ids.
129
251
  */
130
252
  function shellProcesses(root) {
131
253
  const text = runCapture('powershell.exe', [
132
254
  '-NoProfile', '-NonInteractive', '-Command',
133
- 'Get-CimInstance Win32_Process -Filter "Name=\'DeepSeek Harness.exe\'" | '
134
- + 'Select-Object ProcessId,ExecutablePath | ConvertTo-Json -Compress',
255
+ '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); '
256
+ + 'Get-CimInstance Win32_Process -ErrorAction Stop | '
257
+ + 'Select-Object ProcessId,ParentProcessId,Name,ExecutablePath,CommandLine | ConvertTo-Json -Compress',
135
258
  ])
136
- if (text === undefined || text.trim() === '') return []
259
+ if (text === undefined || text.trim() === '') throw new Error('could not enumerate Desktop processes')
137
260
  let parsed
138
- try { parsed = JSON.parse(text) } catch { return [] }
261
+ try { parsed = JSON.parse(text) } catch { throw new Error('could not parse the Desktop process table') }
139
262
  const rows = Array.isArray(parsed) ? parsed : [parsed]
140
- return rows
141
- .filter(row => typeof row?.ProcessId === 'number')
142
- .filter(row => typeof row.ExecutablePath !== 'string'
143
- || row.ExecutablePath.toLowerCase().startsWith(root.toLowerCase()))
144
- .map(row => row.ProcessId)
263
+ if (rows.length === 0 || rows.some(row => row === null || typeof row !== 'object'
264
+ || !Number.isSafeInteger(row.ProcessId) || !Number.isSafeInteger(row.ParentProcessId)
265
+ || typeof row.Name !== 'string')) throw new Error('the Desktop process table is invalid')
266
+ return selectShellProcesses(rows, root, process.pid)
145
267
  }
146
268
 
147
269
  /**
@@ -152,46 +274,12 @@ function shellProcesses(root) {
152
274
  */
153
275
  function runCapture(command, argv) {
154
276
  try {
155
- return execFileSync(command, argv, { encoding: 'utf8', stdio: 'pipe', timeout: 30_000 })
277
+ return execFileSync(command, argv, { encoding: 'utf8', stdio: 'pipe', windowsHide: true, timeout: 30_000 })
156
278
  } catch {
157
279
  return undefined
158
280
  }
159
281
  }
160
282
 
161
- /**
162
- * Close the desktop shell and wait until nothing holds the archive.
163
- *
164
- * Asks first and forces only if the polite request is ignored: a forced kill can lose work in
165
- * progress, and the user was told the shell would be closed, not that it would be killed. The wait
166
- * is bounded — a process that refuses to die must not hang the installer forever.
167
- * @param root - the install directory whose processes to close.
168
- * @param graceMs - how long to wait after the polite request before forcing.
169
- * @returns whether nothing is left running.
170
- */
171
- async function stopShell(root, graceMs) {
172
- const before = shellProcesses(root)
173
- if (before.length === 0) return true
174
- console.log(` closing DSH Desktop (${before.length} process(es))…`)
175
- // No /F: this is a normal window close, so the shell can flush and prompt.
176
- runCapture('taskkill.exe', ['/PID', ...before.map(String), '/T'])
177
- const deadline = Date.now() + graceMs
178
- while (Date.now() < deadline) {
179
- if (shellProcesses(root).length === 0) return true
180
- await new Promise(resolve => setTimeout(resolve, 250))
181
- }
182
- const left = shellProcesses(root)
183
- if (left.length > 0) {
184
- console.log(` ${left.length} process(es) still running after ${String(graceMs)} ms; forcing`)
185
- runCapture('taskkill.exe', ['/IM', 'DeepSeek Harness.exe', '/F', '/T'])
186
- const forcedBy = Date.now() + 15_000
187
- while (Date.now() < forcedBy) {
188
- if (shellProcesses(root).length === 0) return true
189
- await new Promise(resolve => setTimeout(resolve, 250))
190
- }
191
- }
192
- return shellProcesses(root).length === 0
193
- }
194
-
195
283
  /**
196
284
  * Start the desktop shell again, detached from this process.
197
285
  *
@@ -200,14 +288,26 @@ async function stopShell(root, graceMs) {
200
288
  * @param root - the install directory.
201
289
  * @returns whether the executable was spawned.
202
290
  */
291
+ let lastStartedPid
203
292
  function startShell(root) {
204
293
  const exe = join(root, 'DeepSeek Harness.exe')
205
294
  if (!existsSync(exe)) {
206
295
  console.error(`could not start DSH Desktop: ${exe} does not exist; start it yourself.`)
207
296
  return false
208
297
  }
298
+ if (process.env.DSH_BROWSER_TEST === '1' || process.env.NODE_TEST_CONTEXT !== undefined) {
299
+ console.error('test mode forbids launching DSH Desktop')
300
+ return false
301
+ }
209
302
  try {
210
- const child = spawn(exe, [], { detached: true, stdio: 'ignore', cwd: root })
303
+ const env = { ...process.env }
304
+ for (const key of Object.keys(env)) {
305
+ if (key.toUpperCase() === 'ELECTRON_RUN_AS_NODE' || key.toUpperCase().startsWith('DSH_BRIDGE_')) delete env[key]
306
+ }
307
+ const child = spawn(exe, [], { detached: true, stdio: 'ignore', cwd: root, env })
308
+ child.on('error', error => { console.error('could not start DSH Desktop: ' + String(error)) })
309
+ if (child.pid === undefined) return false
310
+ lastStartedPid = child.pid
211
311
  child.unref()
212
312
  console.log(` started ${exe}`)
213
313
  return true
@@ -218,21 +318,26 @@ function startShell(root) {
218
318
  }
219
319
 
220
320
  const args = process.argv.slice(2)
321
+ let installRoot
322
+ try {
323
+ const boundary = testBoundary()
324
+ installRoot = args.find(arg => !arg.startsWith('--')) ?? findDefaultInstall(boundary)
325
+ assertTestTarget(boundary, installRoot)
326
+ } catch (error) {
327
+ console.error('bridge installer test isolation refused the operation: ' + String(error))
328
+ process.exit(1)
329
+ }
330
+ // Identity only, no side effects: the panel and a human both need a way to ask "would this work"
331
+ // without closing the shell first.
332
+ if (args.includes('--preflight')) {
333
+ const target = installRoot
334
+ const verdict = verifyDesktopIdentity(target)
335
+ console.log(JSON.stringify({ target, ...verdict }))
336
+ process.exit(verdict.ok ? 0 : 1)
337
+ }
221
338
  const revert = args.includes('--revert')
222
- /**
223
- * Close DSH, install, then start it again — all in THIS process.
224
- *
225
- * Reported as issue #36: moving `app.asar` aside fails with EBUSY while the shell is running, and
226
- * every "wait for the user to close it" arrangement loses the waiter. Two arrangements were measured
227
- * on Windows and both died at the moment the shell exited: a hidden PowerShell started through WMI
228
- * vanished with the process tree, and a scheduled task reported `LastTaskResult = 0xC000013A`
229
- * (STATUS_CONTROL_C_EXIT). The lesson is that nothing may straddle the exit — so this process closes
230
- * the shell itself, does the work, and starts it again.
231
- */
339
+ /** Start after maintenance only when the target was already closed; never close a running shell. */
232
340
  const restart = args.includes('--restart')
233
- /** Skip the interactive confirmation; required for an unattended run. */
234
- const assumeYes = args.includes('--yes') || args.includes('-y')
235
- const installRoot = args.find(arg => !arg.startsWith('--')) ?? DEFAULT_INSTALL
236
341
 
237
342
  const resourcesDir = join(installRoot, 'resources')
238
343
  const appDir = join(resourcesDir, 'app')
@@ -259,6 +364,50 @@ const hostCliBackup = `${hostCliPath}.before-bridge`
259
364
  const CLI_SHIM_MARKER = 'dsh-builtin-browser: resolve the app directory'
260
365
  const HOST_CLI_MARKER = 'dsh-builtin-browser: recognize an unpacked `app` directory'
261
366
 
367
+ let targetWasClosed = false
368
+ const resultFile = process.env.DSH_BRIDGE_ACTION_RESULT_FILE
369
+ const installErrors = []
370
+ if (resultFile !== undefined) {
371
+ const originalError = console.error
372
+ console.error = (...values) => {
373
+ installErrors.push(values.map(String).join(' '))
374
+ if (installErrors.length > 12) installErrors.shift()
375
+ originalError(...values)
376
+ }
377
+ }
378
+
379
+ // Report maintenance only after its file operations complete. Starting the app is an external
380
+ // command-line opt-in and cannot happen after a running-target or ancestry refusal.
381
+ process.once('exit', code => {
382
+ let restarted = false
383
+ if (restart && targetWasClosed && code === 0) {
384
+ restarted = startShell(installRoot)
385
+ if (restarted) console.log('DSH Desktop was restarted.')
386
+ }
387
+ const finalCode = code === 0 && (!restart || restarted) ? 0 : code || 1
388
+ process.exitCode = finalCode
389
+ if (resultFile !== undefined) {
390
+ const result = {
391
+ ok: finalCode === 0, code: finalCode, action: revert ? 'uninstall' : 'install', restarted,
392
+ ...lastStartedPid === undefined ? {} : { pid: lastStartedPid },
393
+ ...installErrors.length === 0 ? {} : { error: installErrors.join('\n').slice(-2400) },
394
+ completedAt: new Date().toISOString(),
395
+ }
396
+ try {
397
+ const temporary = `${resultFile}.${process.pid}.tmp`
398
+ writeFileSync(temporary, JSON.stringify(result))
399
+ renameSync(temporary, resultFile)
400
+ } catch (error) {
401
+ originalResultError(error)
402
+ }
403
+ }
404
+ })
405
+
406
+ function originalResultError(error) {
407
+ console.error('could not record the bridge installer result: ' + String(error))
408
+ process.exitCode = 1
409
+ }
410
+
262
411
  /** The exact block appended to main.js. Keep it recognisable: idempotence and
263
412
  * reverting both key off this marker. */
264
413
  const MARKER = '// dsh-builtin-browser: hand the plugin a way to drive the sidebar'
@@ -307,15 +456,22 @@ app.whenReady().then(async () => {
307
456
  * @returns the parsed header tree plus the offset where file content starts.
308
457
  */
309
458
  function readAsarHeader(file) {
310
- const fd = openSync(file, 'r')
311
- const sizeBuf = Buffer.alloc(8)
312
- readSync(fd, sizeBuf, 0, 8, 0)
313
- const headerSize = sizeBuf.readUInt32LE(4)
314
- const headerBuf = Buffer.alloc(headerSize)
315
- readSync(fd, headerBuf, 0, headerSize, 8)
316
- const jsonLength = headerBuf.readUInt32LE(4)
317
- const header = JSON.parse(headerBuf.toString('utf8', 8, 8 + jsonLength))
318
- return { fd, header, contentBase: 8 + headerSize }
459
+ const fd = archiveFs.openSync(file, 'r')
460
+ try {
461
+ const sizeBuf = Buffer.alloc(8)
462
+ if (archiveFs.readSync(fd, sizeBuf, 0, 8, 0) !== 8) throw new Error('the archive header is truncated')
463
+ const headerSize = sizeBuf.readUInt32LE(4)
464
+ if (headerSize < 8 || headerSize > 64 * 1024 * 1024) throw new Error('the archive header size is invalid')
465
+ const headerBuf = Buffer.alloc(headerSize)
466
+ if (archiveFs.readSync(fd, headerBuf, 0, headerSize, 8) !== headerSize) throw new Error('the archive header is truncated')
467
+ const jsonLength = headerBuf.readUInt32LE(4)
468
+ if (jsonLength <= 0 || jsonLength > headerSize - 8) throw new Error('the archive JSON length is invalid')
469
+ const header = JSON.parse(headerBuf.toString('utf8', 8, 8 + jsonLength))
470
+ return { fd, header, contentBase: 8 + headerSize }
471
+ } catch (error) {
472
+ archiveFs.closeSync(fd)
473
+ throw error
474
+ }
319
475
  }
320
476
 
321
477
  /**
@@ -348,7 +504,7 @@ function extractAsar(asar, outDir) {
348
504
  unpackedFiles += 1
349
505
  } else {
350
506
  const buffer = Buffer.alloc(entry.size)
351
- readSync(fd, buffer, 0, entry.size, contentBase + Number(entry.offset))
507
+ archiveFs.readSync(fd, buffer, 0, entry.size, contentBase + Number(entry.offset))
352
508
  writeFileSync(target, buffer)
353
509
  }
354
510
  const actual = statSync(target).size
@@ -357,9 +513,11 @@ function extractAsar(asar, outDir) {
357
513
  bytes += actual
358
514
  }
359
515
  }
360
- mkdirSync(outDir, { recursive: true })
361
- walk(header, '')
362
- return { files, bytes, unpackedFiles }
516
+ try {
517
+ mkdirSync(outDir, { recursive: true })
518
+ walk(header, '')
519
+ return { files, bytes, unpackedFiles }
520
+ } finally { archiveFs.closeSync(fd) }
363
521
  }
364
522
 
365
523
  /**
@@ -498,7 +656,7 @@ function readAsarEntry(archive, entryPath) {
498
656
  const offset = Number(node.offset)
499
657
  if (!Number.isFinite(size) || !Number.isFinite(offset) || size < 0) return undefined
500
658
  const buffer = Buffer.alloc(size)
501
- const read = readSync(fd, buffer, 0, size, parsed.contentBase + offset)
659
+ const read = archiveFs.readSync(fd, buffer, 0, size, parsed.contentBase + offset)
502
660
  return read === size ? buffer : undefined
503
661
  } catch {
504
662
  return undefined
@@ -525,7 +683,8 @@ function validateArchive(archive) {
525
683
  }
526
684
  const { fd, header, contentBase } = parsed
527
685
  try {
528
- const fileSize = statSync(archive).size
686
+ // Statistics go through the same unpatched module as the raw archive reads.
687
+ const fileSize = archiveFs.statSync(archive).size
529
688
  const problems = []
530
689
  const walk = (node, prefix) => {
531
690
  for (const [name, entry] of Object.entries(node.files ?? {})) {
@@ -594,9 +753,14 @@ function verifyDesktopIdentity(root) {
594
753
 
595
754
  let manifestText
596
755
  if (archivePresent) {
597
- const bytes = readAsarEntry(archive, 'package.json')
756
+ let bytes = readAsarEntry(archive, 'package.json')
757
+ if (bytes === undefined) {
758
+ // Some builds ship package.json OUTSIDE the archive (marked `unpacked`): the real file is
759
+ // then beside it, and reading it there is the honest answer rather than "cannot be read".
760
+ try { bytes = readFileSync(join(resources, 'app.asar.unpacked', 'package.json')) } catch { bytes = undefined }
761
+ }
598
762
  if (bytes === undefined) {
599
- return { ok: false, reason: `${archive} exists but its package.json cannot be read` }
763
+ return { ok: false, reason: `${archive}: the package manifest could not be read; executable names and archive text are not proof of DSH identity` }
600
764
  }
601
765
  manifestText = bytes.toString('utf8')
602
766
  } else {
@@ -644,37 +808,25 @@ if (!identity.ok) {
644
808
  process.exit(1)
645
809
  }
646
810
 
647
- // `--restart` closes the shell BEFORE anything else, because the archive cannot be moved while the
648
- // shell holds it (EBUSY), and because there is no safe way to wait across the exit from outside —
649
- // both arrangements measured in issue #36 died at that moment. Doing it here keeps the whole
650
- // sequence inside one front-facing process.
651
- let shellStopped = false
652
- if (restart && !revert) {
653
- if (!assumeYes) {
654
- console.log('')
655
- console.log('--restart will CLOSE DSH Desktop, install the bridge, and start it again.')
656
- console.log('Any unsaved work in a conversation is lost. Re-run with --yes to skip this notice.')
657
- console.log('')
658
- try {
659
- const answer = readFileSync(0, 'utf8').trim().toLowerCase()
660
- if (answer !== '' && answer !== 'y' && answer !== 'yes') {
661
- console.error('cancelled; nothing was changed.')
662
- process.exit(1)
663
- }
664
- } catch {
665
- // No stdin (a service, a detached shell): refuse rather than close a window nobody agreed to.
666
- console.error('--restart needs confirmation; pass --yes when there is no console to ask.')
667
- process.exit(1)
668
- }
811
+ // Refuse before any write whenever the target is running. A window close can mean "hide to tray",
812
+ // so maintenance cannot infer consent to terminate the host or its tools.
813
+ try {
814
+ if (shellProcesses(installRoot).length !== 0) {
815
+ console.error('DSH Desktop is running. Exit it normally, then run bridge maintenance from an external terminal.')
816
+ process.exit(1)
669
817
  }
670
- shellStopped = await stopShell(installRoot, 20_000)
671
- if (!shellStopped) {
672
- console.error('DSH Desktop did not exit, so the archive cannot be replaced.')
673
- console.error('Close it yourself and run this again without --restart.')
818
+ targetWasClosed = true
819
+ } catch (error) {
820
+ console.error('bridge maintenance refused: ' + String(error))
821
+ process.exit(1)
822
+ }
823
+ if (!revert && existsSync(asarPath)) {
824
+ const checked = validateArchive(asarPath)
825
+ if (!checked.ok) {
826
+ console.error(`refusing to rebuild from an archive that cannot be verified: ${checked.reason}`)
674
827
  process.exit(1)
675
828
  }
676
829
  }
677
-
678
830
  // The archive wins whenever it exists, so ITS presence — not the absence of the
679
831
  // directory — decides the layout. After a desktop update the archive is back
680
832
  // (a new build) while an older extraction is still lying around, and keying off
@@ -690,7 +842,11 @@ if (!existsSync(mainPath) && !existsSync(asarPath)) {
690
842
  }
691
843
 
692
844
  if (revert) {
845
+ // Tracked separately: restoring a CLI launcher or the runtime resolution is NOT an
846
+ // uninstall. `reverted` only means some component was restored; whether the bridge is
847
+ // actually gone is decided from the entry Electron loads, at the end of this branch.
693
848
  let reverted = false
849
+ let mainEntrySkipped = false
694
850
  if (existsSync(asarMoved)) {
695
851
  if (existsSync(asarPath)) {
696
852
  console.error('refusing to replace an app archive that already exists: a desktop upgrade may have installed a newer build')
@@ -745,6 +901,7 @@ if (revert) {
745
901
  } else if (!identical) {
746
902
  // It carries our marker but does not reduce to the backup: something was patched around
747
903
  // our snippet. The backup is left untouched, because guessing here is what destroyed it.
904
+ mainEntrySkipped = true
748
905
  console.error(`WARNING: ${mainPath} carries the bridge import, but removing it does not`)
749
906
  console.error(` reproduce ${backupPath} — another tool has patched this file too`)
750
907
  console.error(' (dsh-purge patches it). Reverting would discard those changes, so nothing')
@@ -768,6 +925,36 @@ if (revert) {
768
925
  console.error(`nothing to revert in ${installRoot}`)
769
926
  process.exit(1)
770
927
  }
928
+ // Verify the OUTCOME, not the actions. `reverted` only says a component was restored, and
929
+ // the CLI launcher used to set it while `main.js` still imported the bridge — so `--revert`
930
+ // exited 0 and reported success even though a fresh check still said "installed".
931
+ // The bridge is gone only when the entry Electron will actually load no longer carries our
932
+ // marker: in the unpacked layout that is resources/app/lib/main.js; when app.asar is back
933
+ // the archive wins and the unpacked tree is inert.
934
+ const archiveBack = existsSync(asarPath)
935
+ let bridgeStillLoaded = false
936
+ if (!archiveBack && existsSync(mainPath)) {
937
+ try {
938
+ bridgeStillLoaded = readFileSync(mainPath, 'utf8').includes(MARKER)
939
+ } catch (error) {
940
+ // An entry we cannot read cannot be certified clean; never claim success on it.
941
+ console.error(`WARNING: cannot read ${mainPath} to verify the uninstall: ${String(error)}`)
942
+ bridgeStillLoaded = true
943
+ }
944
+ }
945
+ if (bridgeStillLoaded) {
946
+ console.error('bridge uninstall is INCOMPLETE: the loaded main entry still imports the bridge.')
947
+ console.error(` main entry: ${mainPath} (still patched)`)
948
+ console.error(` backup: ${backupPath}`)
949
+ if (mainEntrySkipped) {
950
+ console.error(' Another tool patched main.js around our snippet. That patch was preserved on')
951
+ console.error(' purpose, so our snippet could not be removed without discarding their work.')
952
+ }
953
+ console.error(' The CLI launcher / runtime resolution may already be restored — that is not')
954
+ console.error(' an uninstall. Restore the main entry by hand, or run --revert again after the')
955
+ console.error(' other patch is reconciled, then re-check the bridge status.')
956
+ process.exit(1)
957
+ }
771
958
  // Only where an archive actually exists. In the unpacked layout `resources/app` IS what Electron
772
959
  // loads, so telling the user it is inert and safe to delete would invite them to remove the
773
960
  // application.
@@ -801,7 +988,7 @@ if (packedLayout) {
801
988
  // installation working.
802
989
  rmSync(appDir, { recursive: true, force: true })
803
990
  }
804
- console.log(`extracting into ${appDir} — this writes ~355 MB and can take a minute (measured: 8-55s)...`)
991
+ console.log(`extracting into ${appDir} — large desktop packages can take several minutes...`)
805
992
  const result = extractAsar(asarPath, appDir)
806
993
  const megabytes = (result.bytes / 1024 / 1024).toFixed(1)
807
994
  const seconds = ((Date.now() - started) / 1000).toFixed(1)
@@ -816,7 +1003,7 @@ if (packedLayout) {
816
1003
  console.log(` Electron now loads ${appDir}; the archive is untouched, so the asar integrity fuse cannot trip`)
817
1004
  } catch (error) {
818
1005
  console.error(`could not move app.asar aside: ${String(error)}`)
819
- console.error('close DSH Desktop completely and run this again.')
1006
+ console.error('the original archive is still active and unchanged; the extracted files were not activated. Check the process holding the archive before retrying.')
820
1007
  process.exit(1)
821
1008
  }
822
1009
  }
@@ -849,12 +1036,6 @@ console.log(`installed bridge into ${appDir}`)
849
1036
  console.log(` module: ${bridgeTarget}`)
850
1037
  console.log(` patch: ${mainPath} (+${SNIPPET.split('\n').length} lines)`)
851
1038
  installCliCompatibility()
852
- if (restart && shellStopped) {
853
- // Started detached and unref'd: this process exits on the next line, and a child that died with
854
- // its parent would leave the user with nothing running — the trap the wait-for-exit daemons hit.
855
- if (startShell(installRoot)) {
856
- console.log('DSH Desktop was restarted; the bridge is active.')
857
- }
858
- } else {
1039
+ if (!restart) {
859
1040
  console.log('restart DSH Desktop to activate it.')
860
1041
  }