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
@@ -76,8 +76,6 @@ export class BridgeConnection {
76
76
  /** Ids of the requests sent on the current socket, oldest first. */
77
77
  queue = [];
78
78
  nextId = 1;
79
- /** True once any reply arrived without an id: this bridge does not echo request ids. */
80
- idLessBridge = false;
81
79
  /** True once this connection may only have one request in flight at a time. */
82
80
  serialisable = false;
83
81
  /** True once the shell behind this connection has been reported gone. */
@@ -287,7 +285,6 @@ export class BridgeConnection {
287
285
  // from the right one. Remember that this bridge does not echo ids, and serialise every
288
286
  // later call so the ambiguity cannot arise again.
289
287
  if (echoed === undefined) {
290
- this.idLessBridge = true;
291
288
  this.serialisable = true;
292
289
  }
293
290
  try {
@@ -345,7 +342,8 @@ function endpointExpired(updatedAt) {
345
342
  return false;
346
343
  return Date.now() - at > ENDPOINT_TTL_MS;
347
344
  }
348
- /** The request id a raw answer line echoes back, when it carries one. */ function echoOf(line) {
345
+ /** The request id a raw answer line echoes back, when it carries one. */
346
+ function echoOf(line) {
349
347
  try {
350
348
  const answer = JSON.parse(line);
351
349
  const value = answer[REQUEST_ID_FIELD];
@@ -23,25 +23,7 @@
23
23
  import { existsSync, readFileSync, statSync } from 'node:fs';
24
24
  import { ENDPOINT_STALE_AFTER_MS } from './bridge-connection.js';
25
25
  import { bridgeEndpointPath } from './desktop-bridge-host.js';
26
- /**
27
- * Whether a pid is alive, without signalling it.
28
- *
29
- * Signal 0 performs the permission and existence checks and delivers nothing. `EPERM` means the
30
- * process exists and belongs to someone else, which is still "alive" for this purpose.
31
- * @param pid - the process id from the endpoint file.
32
- * @returns whether that process exists.
33
- */
34
- function pidAlive(pid) {
35
- if (!Number.isSafeInteger(pid) || pid <= 0)
36
- return false;
37
- try {
38
- process.kill(pid, 0);
39
- return true;
40
- }
41
- catch (error) {
42
- return error?.code === 'EPERM';
43
- }
44
- }
26
+ import { pidAlive } from './process.js';
45
27
  /**
46
28
  * Read the endpoint the shell publishes.
47
29
  *
@@ -62,6 +44,13 @@ export function readBridgeEndpoint(path = bridgeEndpointPath(), now = Date.now()
62
44
  let raw;
63
45
  try {
64
46
  raw = JSON.parse(readFileSync(path, 'utf8'));
47
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)
48
+ || !Number.isInteger(raw.port) || Number(raw.port) < 1 || Number(raw.port) > 65535
49
+ || typeof raw.token !== 'string' || raw.token.trim() === ''
50
+ || !Number.isSafeInteger(raw.pid) || Number(raw.pid) <= 0
51
+ || (raw.updatedAt !== undefined && (typeof raw.updatedAt !== 'string' || !Number.isFinite(Date.parse(raw.updatedAt))))) {
52
+ throw new Error('expected a port, a nonempty token, a positive pid and an optional timestamp');
53
+ }
65
54
  }
66
55
  catch (error) {
67
56
  return {
@@ -0,0 +1,85 @@
1
+ /** What the panel may ask for. */
2
+ export type BridgeAction = 'install' | 'uninstall';
3
+ /** Everything this module touches from outside, so a test can drive it without spawning. */
4
+ export interface BridgeActionDeps {
5
+ /** Runs the installer; resolves with an exit code and the tail of its output. */
6
+ readonly run: (command: string, argv: readonly string[], environment?: Readonly<Record<string, string>>) => Promise<{
7
+ readonly code: number | null;
8
+ readonly output: string;
9
+ }>;
10
+ /** Absolute path of the packaged installer. */
11
+ readonly installer: () => string;
12
+ /** Node executable used to run it (the host's own, so no PATH surprises). */
13
+ readonly node: () => string;
14
+ /** Follow the installer's atomic completion file. */
15
+ readonly trackResult?: boolean;
16
+ /** Completion budget, injectable for a fast failure test. */
17
+ readonly resultTimeoutMs?: number;
18
+ /** Poll interval for the installer's atomic completion file. */
19
+ readonly resultPollMs?: number;
20
+ }
21
+ /** What the panel is told. */
22
+ export interface BridgeActionResult {
23
+ /** Whether the requested file maintenance completed successfully. */
24
+ readonly ok: boolean;
25
+ /** Its exit code, or null when it was killed. */
26
+ readonly code: number | null;
27
+ /** The tail of its output, for the one line the panel shows. */
28
+ readonly output: string;
29
+ /** The exact command line, so a failure can be reproduced by hand. */
30
+ readonly command: string;
31
+ /** Persisted completion and installer output, retained for diagnosis. */
32
+ readonly resultFile?: string;
33
+ readonly logFile?: string;
34
+ readonly restarted?: boolean;
35
+ readonly pid?: number;
36
+ }
37
+ /** Final record written by the installer that actually performed the operation. */
38
+ export interface BridgeActionCompletion {
39
+ readonly action: BridgeAction;
40
+ readonly ok: boolean;
41
+ readonly code: number;
42
+ readonly restarted: boolean;
43
+ readonly pid?: number;
44
+ readonly error?: string;
45
+ readonly completedAt: string;
46
+ }
47
+ /** Read-only startup verification, with a private endpoint path available to isolated tests. */
48
+ export interface BridgeReadyOptions {
49
+ readonly endpointPath?: string;
50
+ readonly timeoutMs?: number;
51
+ readonly pollMs?: number;
52
+ }
53
+ /**
54
+ * Verify that the restarted process published a working authenticated bridge.
55
+ * A previous shell's endpoint, a listening socket, or an authentication refusal is insufficient.
56
+ */
57
+ export declare function waitForRestartedBridge(pid: number, options?: BridgeReadyOptions): Promise<void>;
58
+ /**
59
+ * Wait for completed file maintenance. The installer publishes this file by rename so a reader
60
+ * cannot accept a partial result. A panel operation must report no Desktop restart.
61
+ */
62
+ export declare function waitForBridgeActionCompletion(path: string, action: BridgeAction, timeoutMs?: number, pollMs?: number): Promise<BridgeActionCompletion>;
63
+ /**
64
+ * The argv the installer expects, in one place so the panel and a human run the same thing.
65
+ *
66
+ * The target Desktop must already be closed. In particular, the panel cannot grant its child
67
+ * permission to terminate the process that owns the current tool call or settings request.
68
+ * @param action - install/repair, or restore the pre-bridge state.
69
+ * @param installRoot - the desktop install directory that was discovered.
70
+ * @returns argv for the installer.
71
+ */
72
+ export declare function bridgeActionArgv(action: BridgeAction, installRoot: string): string[];
73
+ /** The packaged installer, resolved from this module rather than from a build-time path. */
74
+ export declare function defaultInstallerPath(): string;
75
+ /**
76
+ * Run one bridge action.
77
+ *
78
+ * Never throws for an installer failure: the panel needs the exit code and the line that explains it,
79
+ * and an exception would lose both.
80
+ * @param action - install/repair or uninstall.
81
+ * @param installRoot - the desktop install directory.
82
+ * @param deps - effects; defaulted to this process's.
83
+ * @returns the outcome, with the command line for reproduction.
84
+ */
85
+ export declare function runBridgeAction(action: BridgeAction, installRoot: string, deps?: BridgeActionDeps): Promise<BridgeActionResult>;
@@ -0,0 +1,211 @@
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
+ * Verify that the restarted process published a working authenticated bridge.
18
+ * A previous shell's endpoint, a listening socket, or an authentication refusal is insufficient.
19
+ */
20
+ export async function waitForRestartedBridge(pid, options = {}) {
21
+ const path = options.endpointPath ?? bridgeEndpointPath();
22
+ const timeoutMs = options.timeoutMs ?? 30_000;
23
+ const deadline = Date.now() + timeoutMs;
24
+ while (Date.now() < deadline) {
25
+ try {
26
+ const endpoint = JSON.parse(await readFile(path, 'utf8'));
27
+ if (endpoint !== null && typeof endpoint === 'object' && endpoint.pid === pid
28
+ && Number.isInteger(endpoint.port) && Number(endpoint.port) > 0 && Number(endpoint.port) <= 65535
29
+ && typeof endpoint.token === 'string' && endpoint.token.trim() !== '') {
30
+ const remaining = deadline - Date.now();
31
+ if (remaining <= 0)
32
+ break;
33
+ const connection = new BridgeConnection({ port: Number(endpoint.port), token: endpoint.token, pid });
34
+ try {
35
+ const answer = await connection.call({ op: 'list' }, Math.min(1_000, remaining));
36
+ if (answer.ok === true && Array.isArray(answer.guests) && Array.isArray(answer.sidebar))
37
+ return;
38
+ }
39
+ finally {
40
+ connection.close();
41
+ }
42
+ }
43
+ }
44
+ catch {
45
+ // Endpoint publication and the socket can race startup. Diagnostics deliberately exclude
46
+ // the endpoint body and authentication token; the caller retains the installer's own log.
47
+ }
48
+ const remaining = deadline - Date.now();
49
+ if (remaining > 0)
50
+ await new Promise(resolve => setTimeout(resolve, Math.min(options.pollMs ?? 100, remaining)));
51
+ }
52
+ throw new Error(`the restarted DSH Desktop bridge did not become ready within ${String(timeoutMs)}ms`);
53
+ }
54
+ /**
55
+ * Wait for completed file maintenance. The installer publishes this file by rename so a reader
56
+ * cannot accept a partial result. A panel operation must report no Desktop restart.
57
+ */
58
+ export async function waitForBridgeActionCompletion(path, action, timeoutMs = 180_000, pollMs = 100) {
59
+ const deadline = Date.now() + timeoutMs;
60
+ for (;;) {
61
+ let text;
62
+ try {
63
+ text = await readFile(path, 'utf8');
64
+ }
65
+ catch (error) {
66
+ if (error.code !== 'ENOENT')
67
+ throw error;
68
+ }
69
+ if (text !== undefined) {
70
+ let record;
71
+ try {
72
+ record = JSON.parse(text);
73
+ }
74
+ catch {
75
+ throw new Error('the bridge installer wrote an unreadable completion record');
76
+ }
77
+ if (record === null || typeof record !== 'object'
78
+ || record.action !== action || typeof record.ok !== 'boolean'
79
+ || !Number.isSafeInteger(record.code) || record.restarted !== false
80
+ || typeof record.completedAt !== 'string' || !Number.isFinite(Date.parse(record.completedAt))
81
+ || record.pid !== undefined
82
+ || (record.error !== undefined && typeof record.error !== 'string')
83
+ || (record.ok !== (record.code === 0))) {
84
+ throw new Error('the bridge installer wrote an invalid completion record');
85
+ }
86
+ return record;
87
+ }
88
+ if (Date.now() >= deadline)
89
+ throw new Error(`the bridge installer did not report completion within ${String(timeoutMs)}ms`);
90
+ await new Promise(resolve => setTimeout(resolve, Math.min(pollMs, Math.max(1, deadline - Date.now()))));
91
+ }
92
+ }
93
+ /**
94
+ * The argv the installer expects, in one place so the panel and a human run the same thing.
95
+ *
96
+ * The target Desktop must already be closed. In particular, the panel cannot grant its child
97
+ * permission to terminate the process that owns the current tool call or settings request.
98
+ * @param action - install/repair, or restore the pre-bridge state.
99
+ * @param installRoot - the desktop install directory that was discovered.
100
+ * @returns argv for the installer.
101
+ */
102
+ export function bridgeActionArgv(action, installRoot) {
103
+ const argv = [installRoot];
104
+ if (action === 'uninstall')
105
+ argv.push('--revert');
106
+ return argv;
107
+ }
108
+ /** The packaged installer, resolved from this module rather than from a build-time path. */
109
+ export function defaultInstallerPath() {
110
+ return fileURLToPath(new URL('../../desktop-bridge/install.mjs', import.meta.url));
111
+ }
112
+ /** One line from a long output: the tail is what names the failure. */
113
+ function tail(text, limit = 600) {
114
+ const trimmed = text.trim();
115
+ return trimmed.length > limit ? '…' + trimmed.slice(-limit) : trimmed;
116
+ }
117
+ /** Default runner: the host's own node, a bounded wait, and no shell (so a path with spaces is data). */
118
+ function defaultRun(command, argv, environment) {
119
+ return new Promise(resolve => {
120
+ const child = spawn(command, [...argv], {
121
+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
122
+ env: environment === undefined ? process.env : { ...process.env, ...environment },
123
+ });
124
+ let output = '';
125
+ const collect = (chunk) => { output += String(chunk); if (output.length > 20_000)
126
+ output = output.slice(-20_000); };
127
+ child.stdout?.on('data', collect);
128
+ child.stderr?.on('data', collect);
129
+ const timer = setTimeout(() => { try {
130
+ child.kill();
131
+ }
132
+ catch { /* already gone */ } }, 180_000);
133
+ child.on('error', error => { clearTimeout(timer); resolve({ code: null, output: `${output}\nfailed to start: ${String(error)}` }); });
134
+ child.on('close', code => { clearTimeout(timer); resolve({ code, output }); });
135
+ });
136
+ }
137
+ /**
138
+ * Run one bridge action.
139
+ *
140
+ * Never throws for an installer failure: the panel needs the exit code and the line that explains it,
141
+ * and an exception would lose both.
142
+ * @param action - install/repair or uninstall.
143
+ * @param installRoot - the desktop install directory.
144
+ * @param deps - effects; defaulted to this process's.
145
+ * @returns the outcome, with the command line for reproduction.
146
+ */
147
+ export async function runBridgeAction(action, installRoot, deps = {
148
+ run: defaultRun, installer: defaultInstallerPath, node: () => process.execPath, trackResult: true,
149
+ }) {
150
+ const command = deps.node();
151
+ const argv = [deps.installer(), ...bridgeActionArgv(action, installRoot)];
152
+ const printable = [command, ...argv].map(part => (/\s/.test(part) ? `"${part}"` : part)).join(' ');
153
+ let resultFile;
154
+ let logFile;
155
+ let installerOutput = '';
156
+ const recordedOutput = async () => {
157
+ if (logFile === undefined)
158
+ return '';
159
+ try {
160
+ return (await readFile(logFile, 'utf8')).slice(-20_000);
161
+ }
162
+ catch (error) {
163
+ console.error(`[dsh-browser] cannot read the installer log: ${String(error)}`);
164
+ return '';
165
+ }
166
+ };
167
+ try {
168
+ // Ask the installer to check identity FIRST, without touching anything. It is the same preflight
169
+ // a human can run, and it turns "the button did nothing" into a named reason.
170
+ const preflight = await deps.run(command, [argv[0], installRoot, '--preflight']);
171
+ const verdict = (() => {
172
+ try {
173
+ return JSON.parse(preflight.output.trim().split('\n').at(-1) ?? '{}');
174
+ }
175
+ catch {
176
+ return {};
177
+ }
178
+ })();
179
+ if (preflight.code !== 0 || verdict.ok !== true) {
180
+ return {
181
+ ok: false,
182
+ code: preflight.code,
183
+ output: tail(String(verdict.reason ?? preflight.output)),
184
+ command: printable,
185
+ };
186
+ }
187
+ let environment;
188
+ const deadline = Date.now() + (deps.resultTimeoutMs ?? 180_000);
189
+ if (deps.trackResult === true) {
190
+ const directory = await mkdtemp(join(tmpdir(), 'dsh-bridge-action-'));
191
+ resultFile = join(directory, 'result.json');
192
+ logFile = join(directory, 'installer.log');
193
+ environment = { DSH_BRIDGE_ACTION_RESULT_FILE: resultFile, DSH_BRIDGE_ACTION_LOG_FILE: logFile };
194
+ }
195
+ const result = await deps.run(command, argv, environment);
196
+ installerOutput = result.output;
197
+ if (result.code !== 0 || resultFile === undefined) {
198
+ return { ok: result.code === 0, code: result.code, output: tail(result.output), command: printable, restarted: false,
199
+ ...resultFile === undefined ? {} : { resultFile, logFile } };
200
+ }
201
+ const final = await waitForBridgeActionCompletion(resultFile, action, Math.max(0, deadline - Date.now()), deps.resultPollMs);
202
+ const output = [installerOutput, await recordedOutput(), final.error].filter(Boolean).join('\n');
203
+ return { ok: final.ok, code: final.code, output: tail(output), command: printable, resultFile, logFile,
204
+ restarted: final.restarted, ...final.pid === undefined ? {} : { pid: final.pid } };
205
+ }
206
+ catch (error) {
207
+ return { ok: false, code: null,
208
+ output: tail([installerOutput, await recordedOutput(), String(error)].filter(Boolean).join('\n')),
209
+ command: printable, ...resultFile === undefined ? {} : { resultFile, logFile } };
210
+ }
211
+ }
@@ -0,0 +1,24 @@
1
+ import type { BridgeAction } from './bridge-install.js';
2
+ export interface BridgeMaintenanceOptions {
3
+ /** Parent of a new, unique maintenance directory; defaults to the user's DSH home. */
4
+ readonly directory?: string;
5
+ /** Explicit Node executable; a verified Desktop executable may be used in Electron Node mode. */
6
+ readonly nodePath?: string;
7
+ }
8
+ export interface PreparedBridgeMaintenance {
9
+ readonly ok: true;
10
+ readonly prepared: true;
11
+ readonly action: BridgeAction;
12
+ readonly path: string;
13
+ /** Literal-path invocation for the user's PowerShell terminal. */
14
+ readonly command: string;
15
+ readonly commandShell: 'powershell';
16
+ readonly directory: string;
17
+ readonly runnerPath: string;
18
+ readonly planPath: string;
19
+ }
20
+ /**
21
+ * Prepare an offline Windows launcher. The target may still be running during preparation.
22
+ * User execution remains subject to the installer's closed-Desktop and ancestry guards.
23
+ */
24
+ export declare function prepareBridgeMaintenance(action: BridgeAction, installRoot: string, options?: BridgeMaintenanceOptions): Promise<PreparedBridgeMaintenance>;
@@ -0,0 +1,125 @@
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
+ /** Batch literals cannot contain these characters; other path content stays in JSON arguments. */
14
+ function checkedPath(value, label) {
15
+ if (!isAbsolute(value) || /[\0\r\n"]/.test(value))
16
+ throw new Error(`${label} must be an absolute path without quotes or control characters`);
17
+ return resolve(value);
18
+ }
19
+ /** Escape only a batch literal. Delayed expansion is disabled before a literal is read. */
20
+ function batchLiteral(value) {
21
+ return value.replace(/%/g, '%%');
22
+ }
23
+ function withinOrEqual(root, path) {
24
+ const part = relative(root, path);
25
+ return part === '' || (!isAbsolute(part) && part !== '..' && !part.startsWith('..\\') && !part.startsWith('../'));
26
+ }
27
+ /** Resolve existing ancestors before mkdir so a redirected output cannot create files in Desktop. */
28
+ function prospectiveRealPath(path) {
29
+ let ancestor = path;
30
+ const missing = [];
31
+ while (!existsSync(ancestor)) {
32
+ const parent = dirname(ancestor);
33
+ if (parent === ancestor)
34
+ throw new Error('maintenance directory has no existing ancestor');
35
+ missing.unshift(basename(ancestor));
36
+ ancestor = parent;
37
+ }
38
+ return resolve(realpathSync(ancestor), ...missing);
39
+ }
40
+ /** This runner is deliberately data-driven: paths and actions are never evaluated as shell text. */
41
+ const RUNNER = `import { readFileSync, existsSync } from 'node:fs';
42
+ import { isAbsolute } from 'node:path';
43
+ import { spawnSync } from 'node:child_process';
44
+ const plan = JSON.parse(readFileSync(new URL('./maintenance.json', import.meta.url), 'utf8'));
45
+ if (plan.version !== 1 || !['install', 'uninstall'].includes(plan.action)
46
+ || ![plan.installRoot, plan.installerPath, plan.nodePath, plan.dshHome].every(value => typeof value === 'string' && isAbsolute(value))
47
+ || typeof plan.electronNode !== 'boolean') throw new Error('Invalid bridge maintenance plan');
48
+ if (!existsSync(plan.installerPath)) throw new Error('The browser plugin installer is missing. Install or update the plugin and prepare maintenance again.');
49
+ const environment = { ...process.env };
50
+ for (const key of Object.keys(environment)) {
51
+ 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];
52
+ }
53
+ if (plan.electronNode) environment.ELECTRON_RUN_AS_NODE = '1';
54
+ // Test boundaries and their private home must survive this launcher unchanged.
55
+ if (environment.DSH_BROWSER_TEST !== '1' && environment.NODE_TEST_CONTEXT === undefined) environment.DSH_HOME = plan.dshHome;
56
+ const args = [...(plan.electronNode ? ['--expose-internals'] : []), plan.installerPath, plan.installRoot, ...(plan.action === 'uninstall' ? ['--revert'] : [])];
57
+ const result = spawnSync(plan.nodePath, args, { shell: false, windowsHide: true, stdio: 'inherit', env: environment });
58
+ if (result.error) { console.error('Bridge maintenance could not start: ' + result.error.message); process.exitCode = 1; }
59
+ else process.exitCode = result.status ?? 1;
60
+ `;
61
+ /**
62
+ * Prepare an offline Windows launcher. The target may still be running during preparation.
63
+ * User execution remains subject to the installer's closed-Desktop and ancestry guards.
64
+ */
65
+ export async function prepareBridgeMaintenance(action, installRoot, options = {}) {
66
+ if (action !== 'install' && action !== 'uninstall')
67
+ throw new Error('bridge maintenance action must be install or uninstall');
68
+ const requestedRoot = checkedPath(installRoot, 'Desktop installation');
69
+ const identity = readDesktopIdentity(requestedRoot);
70
+ if (!identity.ok)
71
+ throw new Error(`cannot prepare bridge maintenance: ${identity.reason}`);
72
+ const target = realpathSync(requestedRoot);
73
+ const installerPath = fileURLToPath(new URL('../../desktop-bridge/install.mjs', import.meta.url));
74
+ if (!existsSync(installerPath))
75
+ throw new Error('the packaged bridge installer is missing');
76
+ const currentIsNode = /^(?:node|node\.exe)$/i.test(basename(process.execPath));
77
+ const selected = options.nodePath ?? (currentIsNode ? process.execPath : join(target, 'DeepSeek Harness.exe'));
78
+ const nodePath = checkedPath(selected, 'Maintenance runtime');
79
+ if (!existsSync(nodePath) || !statSync(nodePath).isFile())
80
+ throw new Error('the maintenance runtime does not exist');
81
+ const electronNode = !/^(?:node|node\.exe)$/i.test(basename(nodePath));
82
+ const desktopRuntime = join(target, 'DeepSeek Harness.exe');
83
+ if (electronNode && (!existsSync(desktopRuntime) || realpathSync(nodePath).toLowerCase() !== realpathSync(desktopRuntime).toLowerCase())) {
84
+ throw new Error('the Electron maintenance runtime must belong to the verified Desktop installation');
85
+ }
86
+ const dshHome = checkedPath(dshHomePath(), 'DSH home');
87
+ const testContext = process.env.DSH_BROWSER_TEST === '1' || process.env.NODE_TEST_CONTEXT !== undefined;
88
+ if (testContext && options.directory === undefined && process.env.DSH_BRIDGE_TEST_ROOT === undefined) {
89
+ throw new Error('test preparation requires an explicit private maintenance directory');
90
+ }
91
+ const directory = checkedPath(options.directory ?? join(dshHome, 'dsh-builtin-browser-host', 'maintenance'), 'Maintenance directory');
92
+ if (withinOrEqual(target, directory) || withinOrEqual(target, prospectiveRealPath(directory))) {
93
+ throw new Error('maintenance launchers must be stored outside the Desktop installation');
94
+ }
95
+ await mkdir(directory, { recursive: true, mode: 0o700 });
96
+ if (withinOrEqual(target, realpathSync(directory)))
97
+ throw new Error('maintenance directory resolves inside the Desktop installation');
98
+ const output = await mkdtemp(join(directory, `${action}-`));
99
+ const runnerPath = join(output, 'run-maintenance.mjs');
100
+ const planPath = join(output, 'maintenance.json');
101
+ const path = join(output, action === 'uninstall' ? 'uninstall-bridge.cmd' : 'install-bridge.cmd');
102
+ const plan = { version: 1, action, installRoot: target, installerPath, nodePath, electronNode, dshHome };
103
+ const command = [
104
+ '@echo off',
105
+ 'setlocal DisableDelayedExpansion',
106
+ 'chcp 65001 >nul',
107
+ 'echo Exit DSH Desktop normally before running bridge maintenance.',
108
+ `set "ELECTRON_RUN_AS_NODE=${electronNode ? '1' : ''}"`,
109
+ `"${batchLiteral(nodePath)}"${electronNode ? ' --expose-internals' : ''} "%~dp0run-maintenance.mjs"`,
110
+ 'set "DSH_BRIDGE_MAINTENANCE_EXIT=%ERRORLEVEL%"',
111
+ 'if not "%DSH_BRIDGE_MAINTENANCE_EXIT%"=="0" goto failed',
112
+ 'echo Bridge maintenance completed. You can now open DSH Desktop.',
113
+ 'goto finished',
114
+ ':failed',
115
+ 'echo Bridge maintenance failed. Read the reason above, then prepare maintenance again if needed.',
116
+ ':finished',
117
+ 'if not "%DSH_BRIDGE_MAINTENANCE_NO_PAUSE%"=="1" pause',
118
+ 'exit /b %DSH_BRIDGE_MAINTENANCE_EXIT%',
119
+ '',
120
+ ].join('\r\n');
121
+ await writeFile(planPath, JSON.stringify(plan, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
122
+ await writeFile(runnerPath, RUNNER, { flag: 'wx', mode: 0o600 });
123
+ await writeFile(path, command, { flag: 'wx', mode: 0o600 });
124
+ return { ok: true, prepared: true, action, path, command: `& '${path.replace(/'/g, "''")}'`, commandShell: 'powershell', directory: output, runnerPath, planPath };
125
+ }
@@ -14,8 +14,15 @@ export declare function findDesktopInstall(localAppData?: string): string | unde
14
14
  export interface BridgeStatus {
15
15
  /** `installed`, `missing` or `stale`; see the module comment for what each means. */
16
16
  readonly state: 'installed' | 'missing' | 'stale';
17
- /** Whether the install directory looks like a DSH Desktop install at all. */
17
+ /** Whether the loaded application passed DSH Desktop identity verification. */
18
18
  readonly present: boolean;
19
+ /**
20
+ * The desktop build this reading belongs to, when the identity check could name one.
21
+ *
22
+ * The automatic install runs once per build: a desktop update is exactly when the bridge has to be
23
+ * installed again, so the guard needs to tell the two apart.
24
+ */
25
+ readonly version?: string;
19
26
  /** The directory that was inspected, when one was found. */
20
27
  readonly installRoot?: string;
21
28
  /** Whether `resources/app.asar` exists — the archive the shell actually loads. */
@@ -27,8 +34,8 @@ export interface BridgeStatus {
27
34
  /**
28
35
  * The command that installs or repairs the bridge.
29
36
  *
30
- * Shown rather than run. Executing it from a web request would mean a page can decide to close the
31
- * desktop shell, and no amount of same-origin checking makes that a good idea; the user runs it.
37
+ * The panel can show this command for manual use. Its install button calls the same packaged
38
+ * installer through the separately authenticated local bridge-action route.
32
39
  */
33
40
  readonly command?: string;
34
41
  }