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
@@ -0,0 +1,253 @@
1
+ /**
2
+ * Install, repair or remove the desktop bridge from the settings panel.
3
+ *
4
+ * Maintenance changes files after the target Desktop has exited. The installer checks this before
5
+ * writing; the panel never asks it to close or restart its own host. The same packaged installer
6
+ * owns identity checks, backups and patching for both the panel and an external terminal.
7
+ * @module dsh-browser/browser-electron/bridge-install
8
+ */
9
+ import { spawn } from 'node:child_process'
10
+ import { mkdtemp, readFile } from 'node:fs/promises'
11
+ import { tmpdir } from 'node:os'
12
+ import { join } from 'node:path'
13
+ import { fileURLToPath } from 'node:url'
14
+ import { BridgeConnection } from './bridge-connection.js'
15
+ import { bridgeEndpointPath } from './paths.js'
16
+
17
+ /** What the panel may ask for. */
18
+ export type BridgeAction = 'install' | 'uninstall'
19
+
20
+ /** Everything this module touches from outside, so a test can drive it without spawning. */
21
+ export interface BridgeActionDeps {
22
+ /** Runs the installer; resolves with an exit code and the tail of its output. */
23
+ readonly run: (command: string, argv: readonly string[], environment?: Readonly<Record<string, string>>) => Promise<{ readonly code: number | null; readonly output: string }>
24
+ /** Absolute path of the packaged installer. */
25
+ readonly installer: () => string
26
+ /** Node executable used to run it (the host's own, so no PATH surprises). */
27
+ readonly node: () => string
28
+ /** Follow the installer's atomic completion file. */
29
+ readonly trackResult?: boolean
30
+ /** Completion budget, injectable for a fast failure test. */
31
+ readonly resultTimeoutMs?: number
32
+ /** Poll interval for the installer's atomic completion file. */
33
+ readonly resultPollMs?: number
34
+ }
35
+
36
+ /** What the panel is told. */
37
+ export interface BridgeActionResult {
38
+ /** Whether the requested file maintenance completed successfully. */
39
+ readonly ok: boolean
40
+ /** Its exit code, or null when it was killed. */
41
+ readonly code: number | null
42
+ /** The tail of its output, for the one line the panel shows. */
43
+ readonly output: string
44
+ /** The exact command line, so a failure can be reproduced by hand. */
45
+ readonly command: string
46
+ /** Persisted completion and installer output, retained for diagnosis. */
47
+ readonly resultFile?: string
48
+ readonly logFile?: string
49
+ readonly restarted?: boolean
50
+ readonly pid?: number
51
+ }
52
+
53
+ /** Final record written by the installer that actually performed the operation. */
54
+ export interface BridgeActionCompletion {
55
+ readonly action: BridgeAction
56
+ readonly ok: boolean
57
+ readonly code: number
58
+ readonly restarted: boolean
59
+ readonly pid?: number
60
+ readonly error?: string
61
+ readonly completedAt: string
62
+ }
63
+
64
+ /** Read-only startup verification, with a private endpoint path available to isolated tests. */
65
+ export interface BridgeReadyOptions {
66
+ readonly endpointPath?: string
67
+ readonly timeoutMs?: number
68
+ readonly pollMs?: number
69
+ }
70
+
71
+ /**
72
+ * Verify that the restarted process published a working authenticated bridge.
73
+ * A previous shell's endpoint, a listening socket, or an authentication refusal is insufficient.
74
+ */
75
+ export async function waitForRestartedBridge(pid: number, options: BridgeReadyOptions = {}): Promise<void> {
76
+ const path = options.endpointPath ?? bridgeEndpointPath()
77
+ const timeoutMs = options.timeoutMs ?? 30_000
78
+ const deadline = Date.now() + timeoutMs
79
+ while (Date.now() < deadline) {
80
+ try {
81
+ const endpoint = JSON.parse(await readFile(path, 'utf8')) as { port?: unknown; token?: unknown; pid?: unknown }
82
+ if (endpoint !== null && typeof endpoint === 'object' && endpoint.pid === pid
83
+ && Number.isInteger(endpoint.port) && Number(endpoint.port) > 0 && Number(endpoint.port) <= 65535
84
+ && typeof endpoint.token === 'string' && endpoint.token.trim() !== '') {
85
+ const remaining = deadline - Date.now()
86
+ if (remaining <= 0) break
87
+ const connection = new BridgeConnection({ port: Number(endpoint.port), token: endpoint.token, pid })
88
+ try {
89
+ const answer = await connection.call({ op: 'list' }, Math.min(1_000, remaining))
90
+ if (answer.ok === true && Array.isArray(answer.guests) && Array.isArray(answer.sidebar)) return
91
+ } finally { connection.close() }
92
+ }
93
+ } catch {
94
+ // Endpoint publication and the socket can race startup. Diagnostics deliberately exclude
95
+ // the endpoint body and authentication token; the caller retains the installer's own log.
96
+ }
97
+ const remaining = deadline - Date.now()
98
+ if (remaining > 0) await new Promise(resolve => setTimeout(resolve, Math.min(options.pollMs ?? 100, remaining)))
99
+ }
100
+ throw new Error(`the restarted DSH Desktop bridge did not become ready within ${String(timeoutMs)}ms`)
101
+ }
102
+
103
+ /**
104
+ * Wait for completed file maintenance. The installer publishes this file by rename so a reader
105
+ * cannot accept a partial result. A panel operation must report no Desktop restart.
106
+ */
107
+ export async function waitForBridgeActionCompletion(
108
+ path: string,
109
+ action: BridgeAction,
110
+ timeoutMs = 180_000,
111
+ pollMs = 100,
112
+ ): Promise<BridgeActionCompletion> {
113
+ const deadline = Date.now() + timeoutMs
114
+ for (;;) {
115
+ let text: string | undefined
116
+ try { text = await readFile(path, 'utf8') } catch (error) {
117
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
118
+ }
119
+ if (text !== undefined) {
120
+ let record: Partial<BridgeActionCompletion>
121
+ try { record = JSON.parse(text) as Partial<BridgeActionCompletion> } catch {
122
+ throw new Error('the bridge installer wrote an unreadable completion record')
123
+ }
124
+ if (record === null || typeof record !== 'object'
125
+ || record.action !== action || typeof record.ok !== 'boolean'
126
+ || !Number.isSafeInteger(record.code) || record.restarted !== false
127
+ || typeof record.completedAt !== 'string' || !Number.isFinite(Date.parse(record.completedAt))
128
+ || record.pid !== undefined
129
+ || (record.error !== undefined && typeof record.error !== 'string')
130
+ || (record.ok !== (record.code === 0))) {
131
+ throw new Error('the bridge installer wrote an invalid completion record')
132
+ }
133
+ return record as BridgeActionCompletion
134
+ }
135
+ if (Date.now() >= deadline) throw new Error(`the bridge installer did not report completion within ${String(timeoutMs)}ms`)
136
+ await new Promise(resolve => setTimeout(resolve, Math.min(pollMs, Math.max(1, deadline - Date.now()))))
137
+ }
138
+ }
139
+
140
+ /**
141
+ * The argv the installer expects, in one place so the panel and a human run the same thing.
142
+ *
143
+ * The target Desktop must already be closed. In particular, the panel cannot grant its child
144
+ * permission to terminate the process that owns the current tool call or settings request.
145
+ * @param action - install/repair, or restore the pre-bridge state.
146
+ * @param installRoot - the desktop install directory that was discovered.
147
+ * @returns argv for the installer.
148
+ */
149
+ export function bridgeActionArgv(action: BridgeAction, installRoot: string): string[] {
150
+ const argv = [installRoot]
151
+ if (action === 'uninstall') argv.push('--revert')
152
+ return argv
153
+ }
154
+
155
+ /** The packaged installer, resolved from this module rather than from a build-time path. */
156
+ export function defaultInstallerPath(): string {
157
+ return fileURLToPath(new URL('../../desktop-bridge/install.mjs', import.meta.url))
158
+ }
159
+
160
+ /** One line from a long output: the tail is what names the failure. */
161
+ function tail(text: string, limit = 600): string {
162
+ const trimmed = text.trim()
163
+ return trimmed.length > limit ? '…' + trimmed.slice(-limit) : trimmed
164
+ }
165
+
166
+ /** Default runner: the host's own node, a bounded wait, and no shell (so a path with spaces is data). */
167
+ function defaultRun(command: string, argv: readonly string[], environment?: Readonly<Record<string, string>>): Promise<{ code: number | null; output: string }> {
168
+ return new Promise(resolve => {
169
+ const child = spawn(command, [...argv], {
170
+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
171
+ env: environment === undefined ? process.env : { ...process.env, ...environment },
172
+ })
173
+ let output = ''
174
+ const collect = (chunk: unknown): void => { output += String(chunk); if (output.length > 20_000) output = output.slice(-20_000) }
175
+ child.stdout?.on('data', collect)
176
+ child.stderr?.on('data', collect)
177
+ const timer = setTimeout(() => { try { child.kill() } catch { /* already gone */ } }, 180_000)
178
+ child.on('error', error => { clearTimeout(timer); resolve({ code: null, output: `${output}\nfailed to start: ${String(error)}` }) })
179
+ child.on('close', code => { clearTimeout(timer); resolve({ code, output }) })
180
+ })
181
+ }
182
+
183
+ /**
184
+ * Run one bridge action.
185
+ *
186
+ * Never throws for an installer failure: the panel needs the exit code and the line that explains it,
187
+ * and an exception would lose both.
188
+ * @param action - install/repair or uninstall.
189
+ * @param installRoot - the desktop install directory.
190
+ * @param deps - effects; defaulted to this process's.
191
+ * @returns the outcome, with the command line for reproduction.
192
+ */
193
+ export async function runBridgeAction(
194
+ action: BridgeAction,
195
+ installRoot: string,
196
+ deps: BridgeActionDeps = {
197
+ run: defaultRun, installer: defaultInstallerPath, node: () => process.execPath, trackResult: true,
198
+ },
199
+ ): Promise<BridgeActionResult> {
200
+ const command = deps.node()
201
+ const argv = [deps.installer(), ...bridgeActionArgv(action, installRoot)]
202
+ const printable = [command, ...argv].map(part => (/\s/.test(part) ? `"${part}"` : part)).join(' ')
203
+ let resultFile: string | undefined
204
+ let logFile: string | undefined
205
+ let installerOutput = ''
206
+ const recordedOutput = async (): Promise<string> => {
207
+ if (logFile === undefined) return ''
208
+ try { return (await readFile(logFile, 'utf8')).slice(-20_000) }
209
+ catch (error) {
210
+ console.error(`[dsh-browser] cannot read the installer log: ${String(error)}`)
211
+ return ''
212
+ }
213
+ }
214
+ try {
215
+ // Ask the installer to check identity FIRST, without touching anything. It is the same preflight
216
+ // a human can run, and it turns "the button did nothing" into a named reason.
217
+ const preflight = await deps.run(command, [argv[0] as string, installRoot, '--preflight'])
218
+ const verdict = (() => {
219
+ try { return JSON.parse(preflight.output.trim().split('\n').at(-1) ?? '{}') as { ok?: boolean; reason?: string } }
220
+ catch { return {} as { ok?: boolean; reason?: string } }
221
+ })()
222
+ if (preflight.code !== 0 || verdict.ok !== true) {
223
+ return {
224
+ ok: false,
225
+ code: preflight.code,
226
+ output: tail(String(verdict.reason ?? preflight.output)),
227
+ command: printable,
228
+ }
229
+ }
230
+ let environment: Record<string, string> | undefined
231
+ const deadline = Date.now() + (deps.resultTimeoutMs ?? 180_000)
232
+ if (deps.trackResult === true) {
233
+ const directory = await mkdtemp(join(tmpdir(), 'dsh-bridge-action-'))
234
+ resultFile = join(directory, 'result.json')
235
+ logFile = join(directory, 'installer.log')
236
+ environment = { DSH_BRIDGE_ACTION_RESULT_FILE: resultFile, DSH_BRIDGE_ACTION_LOG_FILE: logFile }
237
+ }
238
+ const result = await deps.run(command, argv, environment)
239
+ installerOutput = result.output
240
+ if (result.code !== 0 || resultFile === undefined) {
241
+ return { ok: result.code === 0, code: result.code, output: tail(result.output), command: printable, restarted: false,
242
+ ...resultFile === undefined ? {} : { resultFile, logFile } }
243
+ }
244
+ const final = await waitForBridgeActionCompletion(resultFile, action, Math.max(0, deadline - Date.now()), deps.resultPollMs)
245
+ const output = [installerOutput, await recordedOutput(), final.error].filter(Boolean).join('\n')
246
+ return { ok: final.ok, code: final.code, output: tail(output), command: printable, resultFile, logFile,
247
+ restarted: final.restarted, ...final.pid === undefined ? {} : { pid: final.pid } }
248
+ } catch (error) {
249
+ return { ok: false, code: null,
250
+ output: tail([installerOutput, await recordedOutput(), String(error)].filter(Boolean).join('\n')),
251
+ command: printable, ...resultFile === undefined ? {} : { resultFile, logFile } }
252
+ }
253
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Prepare Windows bridge maintenance for the user to run after exiting DSH Desktop.
3
+ * Preparation writes a private launcher and plan; it never starts a process or changes Desktop.
4
+ * The current packaged installer performs identity and running-process checks at execution time.
5
+ * @module dsh-browser/browser-electron/bridge-maintenance
6
+ */
7
+ import { existsSync, realpathSync, statSync } from 'node:fs'
8
+ import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'
9
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { readDesktopIdentity } from './desktop-identity.js'
12
+ import { dshHome as dshHomePath } from './paths.js'
13
+ import type { BridgeAction } from './bridge-install.js'
14
+
15
+ export interface BridgeMaintenanceOptions {
16
+ /** Parent of a new, unique maintenance directory; defaults to the user's DSH home. */
17
+ readonly directory?: string
18
+ /** Explicit Node executable; a verified Desktop executable may be used in Electron Node mode. */
19
+ readonly nodePath?: string
20
+ }
21
+
22
+ export interface PreparedBridgeMaintenance {
23
+ readonly ok: true
24
+ readonly prepared: true
25
+ readonly action: BridgeAction
26
+ readonly path: string
27
+ /** Literal-path invocation for the user's PowerShell terminal. */
28
+ readonly command: string
29
+ readonly commandShell: 'powershell'
30
+ readonly directory: string
31
+ readonly runnerPath: string
32
+ readonly planPath: string
33
+ }
34
+
35
+ interface MaintenancePlan {
36
+ readonly version: 1
37
+ readonly action: BridgeAction
38
+ readonly installRoot: string
39
+ readonly installerPath: string
40
+ readonly nodePath: string
41
+ readonly electronNode: boolean
42
+ readonly dshHome: string
43
+ }
44
+
45
+ /** Batch literals cannot contain these characters; other path content stays in JSON arguments. */
46
+ function checkedPath(value: string, label: string): string {
47
+ if (!isAbsolute(value) || /[\0\r\n"]/.test(value)) throw new Error(`${label} must be an absolute path without quotes or control characters`)
48
+ return resolve(value)
49
+ }
50
+
51
+ /** Escape only a batch literal. Delayed expansion is disabled before a literal is read. */
52
+ function batchLiteral(value: string): string {
53
+ return value.replace(/%/g, '%%')
54
+ }
55
+
56
+ function withinOrEqual(root: string, path: string): boolean {
57
+ const part = relative(root, path)
58
+ return part === '' || (!isAbsolute(part) && part !== '..' && !part.startsWith('..\\') && !part.startsWith('../'))
59
+ }
60
+
61
+ /** Resolve existing ancestors before mkdir so a redirected output cannot create files in Desktop. */
62
+ function prospectiveRealPath(path: string): string {
63
+ let ancestor = path
64
+ const missing: string[] = []
65
+ while (!existsSync(ancestor)) {
66
+ const parent = dirname(ancestor)
67
+ if (parent === ancestor) throw new Error('maintenance directory has no existing ancestor')
68
+ missing.unshift(basename(ancestor))
69
+ ancestor = parent
70
+ }
71
+ return resolve(realpathSync(ancestor), ...missing)
72
+ }
73
+
74
+ /** This runner is deliberately data-driven: paths and actions are never evaluated as shell text. */
75
+ const RUNNER = `import { readFileSync, existsSync } from 'node:fs';
76
+ import { isAbsolute } from 'node:path';
77
+ import { spawnSync } from 'node:child_process';
78
+ const plan = JSON.parse(readFileSync(new URL('./maintenance.json', import.meta.url), 'utf8'));
79
+ if (plan.version !== 1 || !['install', 'uninstall'].includes(plan.action)
80
+ || ![plan.installRoot, plan.installerPath, plan.nodePath, plan.dshHome].every(value => typeof value === 'string' && isAbsolute(value))
81
+ || typeof plan.electronNode !== 'boolean') throw new Error('Invalid bridge maintenance plan');
82
+ if (!existsSync(plan.installerPath)) throw new Error('The browser plugin installer is missing. Install or update the plugin and prepare maintenance again.');
83
+ const environment = { ...process.env };
84
+ for (const key of Object.keys(environment)) {
85
+ if (['DSH_BRIDGE_DETACHED', 'DSH_BRIDGE_HANDOFF_PARENT', 'DSH_BRIDGE_ACTION_RESULT_FILE', 'DSH_BRIDGE_ACTION_LOG_FILE', 'ELECTRON_RUN_AS_NODE'].includes(key.toUpperCase())) delete environment[key];
86
+ }
87
+ if (plan.electronNode) environment.ELECTRON_RUN_AS_NODE = '1';
88
+ // Test boundaries and their private home must survive this launcher unchanged.
89
+ if (environment.DSH_BROWSER_TEST !== '1' && environment.NODE_TEST_CONTEXT === undefined) environment.DSH_HOME = plan.dshHome;
90
+ const args = [...(plan.electronNode ? ['--expose-internals'] : []), plan.installerPath, plan.installRoot, ...(plan.action === 'uninstall' ? ['--revert'] : [])];
91
+ const result = spawnSync(plan.nodePath, args, { shell: false, windowsHide: true, stdio: 'inherit', env: environment });
92
+ if (result.error) { console.error('Bridge maintenance could not start: ' + result.error.message); process.exitCode = 1; }
93
+ else process.exitCode = result.status ?? 1;
94
+ `
95
+
96
+ /**
97
+ * Prepare an offline Windows launcher. The target may still be running during preparation.
98
+ * User execution remains subject to the installer's closed-Desktop and ancestry guards.
99
+ */
100
+ export async function prepareBridgeMaintenance(
101
+ action: BridgeAction,
102
+ installRoot: string,
103
+ options: BridgeMaintenanceOptions = {},
104
+ ): Promise<PreparedBridgeMaintenance> {
105
+ if (action !== 'install' && action !== 'uninstall') throw new Error('bridge maintenance action must be install or uninstall')
106
+ const requestedRoot = checkedPath(installRoot, 'Desktop installation')
107
+ const identity = readDesktopIdentity(requestedRoot)
108
+ if (!identity.ok) throw new Error(`cannot prepare bridge maintenance: ${identity.reason}`)
109
+ const target = realpathSync(requestedRoot)
110
+ const installerPath = fileURLToPath(new URL('../../desktop-bridge/install.mjs', import.meta.url))
111
+ if (!existsSync(installerPath)) throw new Error('the packaged bridge installer is missing')
112
+
113
+ const currentIsNode = /^(?:node|node\.exe)$/i.test(basename(process.execPath))
114
+ const selected = options.nodePath ?? (currentIsNode ? process.execPath : join(target, 'DeepSeek Harness.exe'))
115
+ const nodePath = checkedPath(selected, 'Maintenance runtime')
116
+ if (!existsSync(nodePath) || !statSync(nodePath).isFile()) throw new Error('the maintenance runtime does not exist')
117
+ const electronNode = !/^(?:node|node\.exe)$/i.test(basename(nodePath))
118
+ const desktopRuntime = join(target, 'DeepSeek Harness.exe')
119
+ if (electronNode && (!existsSync(desktopRuntime) || realpathSync(nodePath).toLowerCase() !== realpathSync(desktopRuntime).toLowerCase())) {
120
+ throw new Error('the Electron maintenance runtime must belong to the verified Desktop installation')
121
+ }
122
+
123
+ const dshHome = checkedPath(dshHomePath(), 'DSH home')
124
+ const testContext = process.env.DSH_BROWSER_TEST === '1' || process.env.NODE_TEST_CONTEXT !== undefined
125
+ if (testContext && options.directory === undefined && process.env.DSH_BRIDGE_TEST_ROOT === undefined) {
126
+ throw new Error('test preparation requires an explicit private maintenance directory')
127
+ }
128
+ const directory = checkedPath(options.directory ?? join(dshHome, 'dsh-builtin-browser-host', 'maintenance'), 'Maintenance directory')
129
+ if (withinOrEqual(target, directory) || withinOrEqual(target, prospectiveRealPath(directory))) {
130
+ throw new Error('maintenance launchers must be stored outside the Desktop installation')
131
+ }
132
+ await mkdir(directory, { recursive: true, mode: 0o700 })
133
+ if (withinOrEqual(target, realpathSync(directory))) throw new Error('maintenance directory resolves inside the Desktop installation')
134
+ const output = await mkdtemp(join(directory, `${action}-`))
135
+ const runnerPath = join(output, 'run-maintenance.mjs')
136
+ const planPath = join(output, 'maintenance.json')
137
+ const path = join(output, action === 'uninstall' ? 'uninstall-bridge.cmd' : 'install-bridge.cmd')
138
+ const plan: MaintenancePlan = { version: 1, action, installRoot: target, installerPath, nodePath, electronNode, dshHome }
139
+ const command = [
140
+ '@echo off',
141
+ 'setlocal DisableDelayedExpansion',
142
+ 'chcp 65001 >nul',
143
+ 'echo Exit DSH Desktop normally before running bridge maintenance.',
144
+ `set "ELECTRON_RUN_AS_NODE=${electronNode ? '1' : ''}"`,
145
+ `"${batchLiteral(nodePath)}"${electronNode ? ' --expose-internals' : ''} "%~dp0run-maintenance.mjs"`,
146
+ 'set "DSH_BRIDGE_MAINTENANCE_EXIT=%ERRORLEVEL%"',
147
+ 'if not "%DSH_BRIDGE_MAINTENANCE_EXIT%"=="0" goto failed',
148
+ 'echo Bridge maintenance completed. You can now open DSH Desktop.',
149
+ 'goto finished',
150
+ ':failed',
151
+ 'echo Bridge maintenance failed. Read the reason above, then prepare maintenance again if needed.',
152
+ ':finished',
153
+ 'if not "%DSH_BRIDGE_MAINTENANCE_NO_PAUSE%"=="1" pause',
154
+ 'exit /b %DSH_BRIDGE_MAINTENANCE_EXIT%',
155
+ '',
156
+ ].join('\r\n')
157
+ await writeFile(planPath, JSON.stringify(plan, null, 2) + '\n', { flag: 'wx', mode: 0o600 })
158
+ await writeFile(runnerPath, RUNNER, { flag: 'wx', mode: 0o600 })
159
+ await writeFile(path, command, { flag: 'wx', mode: 0o600 })
160
+ return { ok: true, prepared: true, action, path, command: `& '${path.replace(/'/g, "''")}'`, commandShell: 'powershell', directory: output, runnerPath, planPath }
161
+ }
@@ -8,20 +8,26 @@
8
8
  *
9
9
  * The states are the three that actually occur:
10
10
  *
11
- * - `installed` — the shell's main.js carries our marker and the archive is still moved aside.
11
+ * - `installed` — the loaded main.js carries our marker and its bridge matches this plugin.
12
12
  * - `missing` — no marker. Either never installed, or the shell was upgraded (which restores
13
13
  * `app.asar` and replaces `lib/main.js`) and the bridge went with it.
14
- * - `stale` — the marker is present but `app.asar` is back. That is the signature of a desktop
15
- * update that restored the archive without removing our patch: the shell loads the archive, so the
16
- * patch inside the unpacked tree has no effect. This is the case that looks installed and is not.
14
+ * - `stale` — the archive is back, or the deployed bridge module is missing or outdated.
17
15
  * @module dsh-browser/browser-electron/bridge-status
18
16
  */
19
17
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
20
18
  import { join } from 'node:path'
21
19
  import { fileURLToPath } from 'node:url'
20
+ import { createRequire } from 'node:module'
22
21
 
23
22
  import { readDesktopIdentity } from './desktop-identity.js'
24
23
 
24
+ // A normal Electron existsSync(app.asar) caches the archive and keeps it locked on Windows.
25
+ // Status inspection must leave maintenance free to rename it after Desktop exits.
26
+ const rawExistsSync: typeof existsSync = (() => {
27
+ try { return (createRequire(import.meta.url)('original-fs') as typeof import('node:fs')).existsSync }
28
+ catch { return existsSync }
29
+ })()
30
+
25
31
  /**
26
32
  * Find the desktop install to report on.
27
33
  *
@@ -33,22 +39,44 @@ import { readDesktopIdentity } from './desktop-identity.js'
33
39
  * @param localAppData - the base directory; defaults to the environment's.
34
40
  * @returns the install directory, or undefined when nothing matches.
35
41
  */
36
- export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''): string | undefined {
37
- if (localAppData === '') return undefined
38
- const programs = join(localAppData, 'Programs')
42
+ export function findDesktopInstall(localAppData?: string): string | undefined {
43
+ // Not every install lives in %LOCALAPPDATA%\\Programs: people put the app on another drive, under
44
+ // Program Files, or in their own folder. DSH_DESKTOP_PATH names one explicitly, and the usual roots
45
+ // are all probed. A test or a caller that passes a base directory gets exactly that base, so the
46
+ // behaviour stays pinnable.
39
47
  const isDesktop = (candidate: string): boolean => readDesktopIdentity(candidate).ok
40
- for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
41
- const candidate = join(programs, named)
42
- if (isDesktop(candidate)) return candidate
48
+ const explicit = process.env.DSH_DESKTOP_PATH
49
+ if (explicit !== undefined && explicit !== '') {
50
+ const named = explicit
51
+ if (isDesktop(named)) return named
52
+ // A parent directory is a reasonable thing to point at too: look one level down.
53
+ try {
54
+ for (const entry of readdirSync(named, { withFileTypes: true })) {
55
+ if (entry.isDirectory() && isDesktop(join(named, entry.name))) return join(named, entry.name)
56
+ }
57
+ } catch {
58
+ // Not a directory: fall through to the usual roots.
59
+ }
43
60
  }
44
- try {
45
- for (const entry of readdirSync(programs, { withFileTypes: true })) {
46
- if (!entry.isDirectory()) continue
47
- const candidate = join(programs, entry.name)
61
+ const roots = localAppData === undefined
62
+ ? [process.env.LOCALAPPDATA ?? '', process.env['ProgramFiles'] ?? '', process.env['ProgramFiles(x86)'] ?? '', process.env.APPDATA ?? '', process.env.ProgramData ?? '']
63
+ .filter(base => base !== '')
64
+ .map(base => (base === process.env.LOCALAPPDATA ? join(base, 'Programs') : base))
65
+ : [join(localAppData, 'Programs')]
66
+ for (const base of roots) {
67
+ for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
68
+ const candidate = join(base, named)
48
69
  if (isDesktop(candidate)) return candidate
49
70
  }
50
- } catch {
51
- // No Programs directory: nothing to report on, which is a state rather than an error.
71
+ try {
72
+ for (const entry of readdirSync(base, { withFileTypes: true })) {
73
+ if (!entry.isDirectory()) continue
74
+ const candidate = join(base, entry.name)
75
+ if (isDesktop(candidate)) return candidate
76
+ }
77
+ } catch {
78
+ // A root that does not exist is a state, not an error.
79
+ }
52
80
  }
53
81
  return undefined
54
82
  }
@@ -60,8 +88,15 @@ const MARKER = '// dsh-builtin-browser: hand the plugin a way to drive the sideb
60
88
  export interface BridgeStatus {
61
89
  /** `installed`, `missing` or `stale`; see the module comment for what each means. */
62
90
  readonly state: 'installed' | 'missing' | 'stale'
63
- /** Whether the install directory looks like a DSH Desktop install at all. */
91
+ /** Whether the loaded application passed DSH Desktop identity verification. */
64
92
  readonly present: boolean
93
+ /**
94
+ * The desktop build this reading belongs to, when the identity check could name one.
95
+ *
96
+ * The automatic install runs once per build: a desktop update is exactly when the bridge has to be
97
+ * installed again, so the guard needs to tell the two apart.
98
+ */
99
+ readonly version?: string
65
100
  /** The directory that was inspected, when one was found. */
66
101
  readonly installRoot?: string
67
102
  /** Whether `resources/app.asar` exists — the archive the shell actually loads. */
@@ -73,8 +108,8 @@ export interface BridgeStatus {
73
108
  /**
74
109
  * The command that installs or repairs the bridge.
75
110
  *
76
- * Shown rather than run. Executing it from a web request would mean a page can decide to close the
77
- * desktop shell, and no amount of same-origin checking makes that a good idea; the user runs it.
111
+ * The panel can show this command for manual use. Its install button calls the same packaged
112
+ * installer through the separately authenticated local bridge-action route.
78
113
  */
79
114
  readonly command?: string
80
115
  }
@@ -112,7 +147,7 @@ function repairCommand(installRoot: string | undefined): string | undefined {
112
147
  // No absolute path means the package is laid out in a way this module cannot navigate; the bare
113
148
  // relative form is still better than nothing, but it is the fallback, not the default.
114
149
  const runner = script === undefined ? 'desktop-bridge/install.mjs' : `"${script}"`
115
- return `node ${runner} "${installRoot}" --restart`
150
+ return `node ${runner} "${installRoot}"`
116
151
  }
117
152
 
118
153
  /**
@@ -146,6 +181,7 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
146
181
  }
147
182
 
148
183
  const archivePresent = safeExists(archivePath)
184
+ const version = identity.version ?? 'unknown'
149
185
  const mainPresent = safeExists(mainPath)
150
186
  if (!mainPresent && !archivePresent) {
151
187
  // Unreachable once identity has passed (identity requires the loaded main entry), kept as the
@@ -155,6 +191,7 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
155
191
  present: false,
156
192
  installRoot,
157
193
  archivePresent,
194
+ version,
158
195
  detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
159
196
  }
160
197
  }
@@ -172,9 +209,10 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
172
209
  present: true,
173
210
  installRoot,
174
211
  archivePresent,
212
+ version,
175
213
  ...backupAt === undefined ? {} : { backupAt },
176
214
  command: repairCommand(installRoot),
177
- detail: 'packed layout with no bridge in the loaded tree: the bridge is not installed',
215
+ detail: 'packed layout with no bridge in the loaded tree: the bridge is not installed',
178
216
  }
179
217
  }
180
218
  if (archivePresent) {
@@ -183,9 +221,10 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
183
221
  present: true,
184
222
  installRoot,
185
223
  archivePresent,
224
+ version,
186
225
  ...backupAt === undefined ? {} : { backupAt },
187
226
  command: repairCommand(installRoot),
188
- detail: 'the archive is back alongside the patched tree, so the shell loads the archive: '
227
+ detail: 'the archive is back alongside the patched tree, so the shell loads the archive: '
189
228
  + 'a desktop update restored it. Re-run the installer to repair.',
190
229
  }
191
230
  }
@@ -195,25 +234,36 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
195
234
  present: true,
196
235
  installRoot,
197
236
  archivePresent,
237
+ version,
198
238
  ...backupAt === undefined ? {} : { backupAt },
199
239
  command: repairCommand(installRoot),
200
- detail: 'unpacked layout without the bridge patch: the bridge is not installed',
240
+ detail: 'unpacked layout without the bridge patch: the bridge is not installed',
201
241
  }
202
242
  }
243
+ const bridgePath = join(appDir, 'lib', 'plugin-browser-bridge.js')
244
+ let bridgeDetail: string | undefined
245
+ try {
246
+ const deployed = readFileSync(bridgePath)
247
+ const shipped = readFileSync(new URL('../../desktop-bridge/plugin-browser-bridge.js', import.meta.url))
248
+ if (!deployed.equals(shipped)) bridgeDetail = 'the deployed bridge module differs from this plugin version; reinstall the bridge to refresh it'
249
+ } catch {
250
+ bridgeDetail = 'the bridge module is missing or cannot be verified; reinstall the bridge to restore it'
251
+ }
203
252
  return {
204
- state: 'installed',
253
+ state: bridgeDetail === undefined ? 'installed' : 'stale',
205
254
  present: true,
206
255
  installRoot,
207
256
  archivePresent,
257
+ version,
208
258
  ...backupAt === undefined ? {} : { backupAt },
209
259
  command: repairCommand(installRoot),
210
- detail: 'the shell loads the patched tree and the bridge is in it',
260
+ detail: bridgeDetail ?? 'the shell loads the patched tree and its bridge module matches this plugin version',
211
261
  }
212
262
  }
213
263
 
214
264
  /** Whether a path exists, treating any error as absence. */
215
265
  function safeExists(path: string): boolean {
216
- try { return existsSync(path) } catch { return false }
266
+ try { return rawExistsSync(path) } catch { return false }
217
267
  }
218
268
 
219
269
  /** Whether a file contains a string, treating any error as absence. */