dsh-builtin-browser 0.5.7 → 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 (94) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.en.md +48 -22
  3. package/README.md +48 -22
  4. package/client.js +469 -81
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +251 -159
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +151 -18
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/user-guide.md +28 -4
  11. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  12. package/lib/browser-electron/automatic-maintenance.js +426 -0
  13. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  14. package/lib/browser-electron/bridge-auto.js +113 -0
  15. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  16. package/lib/browser-electron/bridge-connection.js +2 -4
  17. package/lib/browser-electron/bridge-endpoint.js +1 -19
  18. package/lib/browser-electron/bridge-install.d.ts +41 -4
  19. package/lib/browser-electron/bridge-install.js +131 -18
  20. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  21. package/lib/browser-electron/bridge-maintenance.js +125 -0
  22. package/lib/browser-electron/bridge-status.d.ts +10 -3
  23. package/lib/browser-electron/bridge-status.js +76 -45
  24. package/lib/browser-electron/desktop-bridge-host.d.ts +5 -2
  25. package/lib/browser-electron/desktop-bridge-host.js +54 -33
  26. package/lib/browser-electron/desktop-identity.js +21 -9
  27. package/lib/browser-electron/electron-provision.js +5 -2
  28. package/lib/browser-electron/entry.js +104 -74
  29. package/lib/browser-electron/ephemeral-profile.js +67 -26
  30. package/lib/browser-electron/history-store.js +2 -2
  31. package/lib/browser-electron/host-main.js +26 -37
  32. package/lib/browser-electron/http-body.d.ts +24 -0
  33. package/lib/browser-electron/http-body.js +33 -0
  34. package/lib/browser-electron/json-reply.d.ts +13 -1
  35. package/lib/browser-electron/json-reply.js +16 -2
  36. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  37. package/lib/browser-electron/maintenance-broker.js +114 -0
  38. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  39. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  40. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  41. package/lib/browser-electron/maintenance-route.js +75 -0
  42. package/lib/browser-electron/paths.d.ts +4 -0
  43. package/lib/browser-electron/paths.js +19 -0
  44. package/lib/browser-electron/process.d.ts +14 -0
  45. package/lib/browser-electron/process.js +24 -0
  46. package/lib/browser-electron/provider.d.ts +7 -7
  47. package/lib/browser-electron/provider.js +13 -14
  48. package/lib/browser-electron/remote-host.js +18 -16
  49. package/lib/browser-electron/runtime-status.d.ts +27 -13
  50. package/lib/browser-electron/runtime-status.js +24 -4
  51. package/lib/browser-electron/settings-store.d.ts +11 -0
  52. package/lib/browser-electron/settings-store.js +8 -2
  53. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  54. package/lib/browser-electron/sidebar-only-host.js +192 -0
  55. package/lib/browser-electron/system-browser.d.ts +1 -9
  56. package/lib/browser-electron/system-browser.js +19 -22
  57. package/lib/browser-electron/timing.d.ts +8 -0
  58. package/lib/browser-electron/timing.js +13 -0
  59. package/lib/browser-electron/windows-system.d.ts +3 -0
  60. package/lib/browser-electron/windows-system.js +19 -0
  61. package/lib/tool-browser/index.js +5 -4
  62. package/package.json +2 -2
  63. package/scripts/run-tests.mjs +32 -0
  64. package/scripts/verify-preview-route.mjs +19 -1
  65. package/src/browser-electron/automatic-maintenance.ts +414 -0
  66. package/src/browser-electron/bridge-auto.ts +158 -0
  67. package/src/browser-electron/bridge-connection.ts +2 -4
  68. package/src/browser-electron/bridge-endpoint.ts +1 -18
  69. package/src/browser-electron/bridge-install.ts +151 -20
  70. package/src/browser-electron/bridge-maintenance.ts +161 -0
  71. package/src/browser-electron/bridge-status.ts +78 -48
  72. package/src/browser-electron/desktop-bridge-host.ts +48 -32
  73. package/src/browser-electron/desktop-identity.ts +18 -9
  74. package/src/browser-electron/electron-provision.ts +5 -2
  75. package/src/browser-electron/entry.ts +91 -69
  76. package/src/browser-electron/ephemeral-profile.ts +65 -28
  77. package/src/browser-electron/history-store.ts +2 -2
  78. package/src/browser-electron/host-main.ts +23 -36
  79. package/src/browser-electron/http-body.ts +42 -0
  80. package/src/browser-electron/json-reply.ts +18 -3
  81. package/src/browser-electron/maintenance-broker.ts +142 -0
  82. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  83. package/src/browser-electron/maintenance-route.ts +64 -0
  84. package/src/browser-electron/paths.ts +21 -0
  85. package/src/browser-electron/process.ts +23 -0
  86. package/src/browser-electron/provider.ts +18 -18
  87. package/src/browser-electron/remote-host.ts +19 -19
  88. package/src/browser-electron/runtime-status.ts +52 -17
  89. package/src/browser-electron/settings-store.ts +20 -3
  90. package/src/browser-electron/sidebar-only-host.ts +199 -0
  91. package/src/browser-electron/system-browser.ts +19 -22
  92. package/src/browser-electron/timing.ts +16 -0
  93. package/src/browser-electron/windows-system.ts +23 -0
  94. package/src/tool-browser/index.ts +5 -4
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Compatibility for historical automatic-install settings and explicit bridge-maintenance intent.
3
+ * Runtime automatic installation is disabled. Bridge maintenance requires the user to close DSH
4
+ * Desktop before explicitly running the installer; loading a plugin never changes the installation.
5
+ * Historical marker readers remain available for diagnostics.
6
+ * @module dsh-browser/browser-electron/bridge-auto
7
+ */
8
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { writeFileAtomic } from './settings-store.js';
11
+ /** Historical attempt-record interval, retained for compatibility with existing diagnostics. */
12
+ export const AUTO_INSTALL_COOLDOWN_MS = 24 * 60 * 60 * 1_000;
13
+ /**
14
+ * Report that runtime bridge installation is deferred to explicit maintenance.
15
+ *
16
+ * @param input - the readings described by {@link AutoInstallInput}.
17
+ * @returns whether to run, and why.
18
+ */
19
+ export function autoInstallDecision(_input) {
20
+ return { run: false, why: 'runtime automatic bridge installation is disabled; close DSH Desktop and run bridge maintenance explicitly' };
21
+ }
22
+ /**
23
+ * Read the profile identity supplied by DSH's launcher before plugins mount.
24
+ * A Desktop installation or Electron executable can also belong to a Web/CLI invocation,
25
+ * so neither is used to infer the current surface.
26
+ * @param ctx - plugin context; older or custom compositions may omit the profile service.
27
+ * @returns the current profile name, or undefined when the launcher did not provide it.
28
+ */
29
+ export function readAutoInstallProfile(ctx) {
30
+ try {
31
+ const context = ctx;
32
+ if (typeof context?.get !== 'function')
33
+ return undefined;
34
+ const profile = context.get('profileContext');
35
+ return typeof profile?.name === 'string' ? profile.name : undefined;
36
+ }
37
+ catch {
38
+ return undefined;
39
+ }
40
+ }
41
+ /** A manual uninstall could not record the operator's automatic-install opt-out. */
42
+ export class BridgeAutoInstallPreferenceError extends Error {
43
+ constructor(cause) {
44
+ super(`could not save automatic bridge installation preference: ${String(cause)}`, { cause });
45
+ this.name = 'BridgeAutoInstallPreferenceError';
46
+ }
47
+ }
48
+ /**
49
+ * Preserve an explicit uninstall as an automatic-install opt-out in historical settings.
50
+ * The preference is written before the installer starts, so a failed write cannot launch maintenance.
51
+ * A failed uninstall retains the opt-out; an explicit install leaves an existing opt-out unchanged.
52
+ * @param action - the authenticated user's selected action.
53
+ * @param update - persist the operator's bridge preference.
54
+ * @param run - perform the installer action after its preference is durable.
55
+ * @returns the installer's result.
56
+ */
57
+ export async function runWithManualBridgePreference(action, update, run) {
58
+ if (action === 'uninstall') {
59
+ try {
60
+ update({ bridge: { autoInstall: false } });
61
+ }
62
+ catch (error) {
63
+ throw new BridgeAutoInstallPreferenceError(error);
64
+ }
65
+ }
66
+ return await run();
67
+ }
68
+ /** Where the attempt record lives, beside the settings the plugin already owns. */
69
+ export function autoInstallMarkerPath(dshHome) {
70
+ return join(dshHome, 'dsh-builtin-browser-host', 'bridge-auto-install.json');
71
+ }
72
+ /**
73
+ * Read the last attempt.
74
+ *
75
+ * A record that cannot be parsed is treated as absent: the guard exists to prevent loops, and a single
76
+ * extra attempt after a corrupt file is cheaper than refusing to ever install again.
77
+ * @param path - marker file path.
78
+ * @returns the marker, or undefined.
79
+ */
80
+ export function readAutoInstallMarker(path) {
81
+ if (!existsSync(path))
82
+ return undefined;
83
+ try {
84
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
85
+ if (typeof parsed.build !== 'string' || typeof parsed.attemptedAt !== 'string')
86
+ return undefined;
87
+ return {
88
+ build: parsed.build,
89
+ attemptedAt: parsed.attemptedAt,
90
+ outcome: typeof parsed.outcome === 'string' ? parsed.outcome : 'unknown',
91
+ };
92
+ }
93
+ catch {
94
+ return undefined;
95
+ }
96
+ }
97
+ /**
98
+ * Record an attempt. Written before the installer runs: if the shell is killed mid-install, the next
99
+ * launch must still see that an attempt happened rather than starting another restart.
100
+ * @param path - marker file path.
101
+ * @param marker - what to record.
102
+ * @returns whether the record was saved; callers skip automatic restarts without a durable guard.
103
+ */
104
+ export function writeAutoInstallMarker(path, marker) {
105
+ try {
106
+ mkdirSync(dirname(path), { recursive: true });
107
+ writeFileAtomic(path, `${JSON.stringify(marker, null, 2)}\n`);
108
+ return true;
109
+ }
110
+ catch {
111
+ return false;
112
+ }
113
+ }
@@ -39,8 +39,6 @@ export declare class BridgeConnection {
39
39
  /** Ids of the requests sent on the current socket, oldest first. */
40
40
  private readonly queue;
41
41
  private nextId;
42
- /** True once any reply arrived without an id: this bridge does not echo request ids. */
43
- private idLessBridge;
44
42
  /** True once this connection may only have one request in flight at a time. */
45
43
  private serialisable;
46
44
  /** True once the shell behind this connection has been reported gone. */
@@ -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
  *
@@ -3,7 +3,7 @@ export type BridgeAction = 'install' | 'uninstall';
3
3
  /** Everything this module touches from outside, so a test can drive it without spawning. */
4
4
  export interface BridgeActionDeps {
5
5
  /** Runs the installer; resolves with an exit code and the tail of its output. */
6
- readonly run: (command: string, argv: readonly string[]) => Promise<{
6
+ readonly run: (command: string, argv: readonly string[], environment?: Readonly<Record<string, string>>) => Promise<{
7
7
  readonly code: number | null;
8
8
  readonly output: string;
9
9
  }>;
@@ -11,10 +11,16 @@ export interface BridgeActionDeps {
11
11
  readonly installer: () => string;
12
12
  /** Node executable used to run it (the host's own, so no PATH surprises). */
13
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;
14
20
  }
15
21
  /** What the panel is told. */
16
22
  export interface BridgeActionResult {
17
- /** Whether the installer exited 0. */
23
+ /** Whether the requested file maintenance completed successfully. */
18
24
  readonly ok: boolean;
19
25
  /** Its exit code, or null when it was killed. */
20
26
  readonly code: number | null;
@@ -22,12 +28,43 @@ export interface BridgeActionResult {
22
28
  readonly output: string;
23
29
  /** The exact command line, so a failure can be reproduced by hand. */
24
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;
25
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>;
26
63
  /**
27
64
  * The argv the installer expects, in one place so the panel and a human run the same thing.
28
65
  *
29
- * `--restart --yes` is not a convenience: the shell holds `app.asar` open, so an install with the
30
- * app running fails with EBUSY, and a prompt would block an unattended click.
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.
31
68
  * @param action - install/repair, or restore the pre-bridge state.
32
69
  * @param installRoot - the desktop install directory that was discovered.
33
70
  * @returns argv for the installer.
@@ -1,23 +1,100 @@
1
1
  /**
2
2
  * Install, repair or remove the desktop bridge from the settings panel.
3
3
  *
4
- * The panel used to print a command and leave the user to copy it into a terminal. That is a defect
5
- * for this plugin specifically: the command closes and reopens the desktop app, so a half-done manual
6
- * run (wrong cwd, wrong node, wrong quoting on a path with spaces) leaves the shell in a state the
7
- * user has to diagnose. The installer already knows how to do the whole dance unattended
8
- * (`--restart --yes`), so the panel calls it and reports what happened.
9
- *
10
- * What this deliberately does NOT do: invent its own patching. Every path, backup and identity check
11
- * stays inside `desktop-bridge/install.mjs`, which is the same file a human would run.
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.
12
7
  * @module dsh-browser/browser-electron/bridge-install
13
8
  */
14
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';
15
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
+ }
16
93
  /**
17
94
  * The argv the installer expects, in one place so the panel and a human run the same thing.
18
95
  *
19
- * `--restart --yes` is not a convenience: the shell holds `app.asar` open, so an install with the
20
- * app running fails with EBUSY, and a prompt would block an unattended click.
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.
21
98
  * @param action - install/repair, or restore the pre-bridge state.
22
99
  * @param installRoot - the desktop install directory that was discovered.
23
100
  * @returns argv for the installer.
@@ -26,7 +103,6 @@ export function bridgeActionArgv(action, installRoot) {
26
103
  const argv = [installRoot];
27
104
  if (action === 'uninstall')
28
105
  argv.push('--revert');
29
- argv.push('--restart', '--yes');
30
106
  return argv;
31
107
  }
32
108
  /** The packaged installer, resolved from this module rather than from a build-time path. */
@@ -39,9 +115,12 @@ function tail(text, limit = 600) {
39
115
  return trimmed.length > limit ? '…' + trimmed.slice(-limit) : trimmed;
40
116
  }
41
117
  /** Default runner: the host's own node, a bounded wait, and no shell (so a path with spaces is data). */
42
- function defaultRun(command, argv) {
118
+ function defaultRun(command, argv, environment) {
43
119
  return new Promise(resolve => {
44
- const child = spawn(command, [...argv], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
120
+ const child = spawn(command, [...argv], {
121
+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
122
+ env: environment === undefined ? process.env : { ...process.env, ...environment },
123
+ });
45
124
  let output = '';
46
125
  const collect = (chunk) => { output += String(chunk); if (output.length > 20_000)
47
126
  output = output.slice(-20_000); };
@@ -52,7 +131,7 @@ function defaultRun(command, argv) {
52
131
  }
53
132
  catch { /* already gone */ } }, 180_000);
54
133
  child.on('error', error => { clearTimeout(timer); resolve({ code: null, output: `${output}\nfailed to start: ${String(error)}` }); });
55
- child.on('exit', code => { clearTimeout(timer); resolve({ code, output }); });
134
+ child.on('close', code => { clearTimeout(timer); resolve({ code, output }); });
56
135
  });
57
136
  }
58
137
  /**
@@ -65,10 +144,26 @@ function defaultRun(command, argv) {
65
144
  * @param deps - effects; defaulted to this process's.
66
145
  * @returns the outcome, with the command line for reproduction.
67
146
  */
68
- export async function runBridgeAction(action, installRoot, deps = { run: defaultRun, installer: defaultInstallerPath, node: () => process.execPath }) {
147
+ export async function runBridgeAction(action, installRoot, deps = {
148
+ run: defaultRun, installer: defaultInstallerPath, node: () => process.execPath, trackResult: true,
149
+ }) {
69
150
  const command = deps.node();
70
151
  const argv = [deps.installer(), ...bridgeActionArgv(action, installRoot)];
71
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
+ };
72
167
  try {
73
168
  // Ask the installer to check identity FIRST, without touching anything. It is the same preflight
74
169
  // a human can run, and it turns "the button did nothing" into a named reason.
@@ -89,10 +184,28 @@ export async function runBridgeAction(action, installRoot, deps = { run: default
89
184
  command: printable,
90
185
  };
91
186
  }
92
- const result = await deps.run(command, argv);
93
- return { ok: result.code === 0, code: result.code, output: tail(result.output), command: printable };
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 } };
94
205
  }
95
206
  catch (error) {
96
- return { ok: false, code: null, output: tail(String(error)), command: printable };
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 } };
97
210
  }
98
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
  }