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
@@ -33,6 +33,7 @@ import { createRequire } from 'node:module';
33
33
  import { existsSync, readFileSync, readdirSync, readlinkSync } from 'node:fs';
34
34
  import { basename, dirname, isAbsolute, join } from 'node:path';
35
35
  import { createServer } from 'node:net';
36
+ import { withTimeoutShared } from './timing.js';
36
37
  import { fileURLToPath } from 'node:url';
37
38
  /** How long to wait for the child to signal readiness before failing. */
38
39
  const READY_TIMEOUT_MS = 20_000;
@@ -223,15 +224,19 @@ function hostElectronViaProcessTree() {
223
224
  }
224
225
  return undefined;
225
226
  }
227
+ /** One scalar property of a Windows process, read through CIM. */
228
+ function cimQuery(pid, property) {
229
+ const out = execFileSync('powershell.exe', [
230
+ '-NoProfile', '-NonInteractive', '-Command',
231
+ `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").${property}`,
232
+ ], { encoding: 'utf8', windowsHide: true, timeout: 3000 });
233
+ return out.trim().split(/\r?\n/)[0] ?? '';
234
+ }
226
235
  /** The executable path of a running process, or undefined when unknown. */
227
236
  function processExecutable(pid) {
228
237
  try {
229
238
  if (process.platform === 'win32') {
230
- const out = execFileSync('powershell.exe', [
231
- '-NoProfile', '-NonInteractive', '-Command',
232
- `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").ExecutablePath`,
233
- ], { encoding: 'utf8', windowsHide: true, timeout: 3000 });
234
- const line = out.trim().split(/\r?\n/)[0] ?? '';
239
+ const line = cimQuery(pid, 'ExecutablePath');
235
240
  return line.length > 0 ? line : undefined;
236
241
  }
237
242
  const exe = readlinkSync(`/proc/${pid}/exe`);
@@ -245,11 +250,7 @@ function processExecutable(pid) {
245
250
  function processParent(pid) {
246
251
  try {
247
252
  if (process.platform === 'win32') {
248
- const out = execFileSync('powershell.exe', [
249
- '-NoProfile', '-NonInteractive', '-Command',
250
- `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").ParentProcessId`,
251
- ], { encoding: 'utf8', windowsHide: true, timeout: 3000 });
252
- const n = Number(out.trim().split(/\r?\n/)[0]);
253
+ const n = Number(cimQuery(pid, 'ParentProcessId'));
253
254
  return Number.isInteger(n) && n > 1 ? n : undefined;
254
255
  }
255
256
  const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
@@ -1367,18 +1368,19 @@ function appendHostLog(text) {
1367
1368
  writeFileSync(file, `${hostStamp()} log rotated: previous content exceeded ${String(HOST_LOG_MAX_BYTES)} bytes and was discarded\n`);
1368
1369
  }
1369
1370
  }
1370
- catch { /* first write, or unreadable: just append */ }
1371
- mkdirSync(dir, { recursive: true });
1371
+ catch {
1372
+ // No readable file yet: the log directory may not exist. When statSync
1373
+ // succeeded the file exists, so its directory does too and creating it
1374
+ // again was a redundant syscall on every child stdout/stderr line.
1375
+ mkdirSync(dir, { recursive: true });
1376
+ }
1372
1377
  appendFileSync(file, text);
1373
1378
  }
1374
1379
  catch { /* diagnostics are best-effort only */ }
1375
1380
  }
1376
1381
  /** Reject a promise if it does not settle within the budget. */
1377
1382
  function withTimeout(promise, ms, message) {
1378
- return new Promise((resolve, reject) => {
1379
- const timer = setTimeout(() => reject(new Error(`${message} (${ms}ms)`)), ms);
1380
- promise.then(value => { clearTimeout(timer); resolve(value); }, error => { clearTimeout(timer); reject(error); });
1381
- });
1383
+ return withTimeoutShared(promise, ms, () => new Error(`${message} (${ms}ms)`));
1382
1384
  }
1383
1385
  /** Default host-main path relative to this module's build output. */
1384
1386
  export function defaultHostMainPath() {
@@ -14,25 +14,30 @@
14
14
  * the settings panel renders it, and a test drives it without touching Electron, a desktop install
15
15
  * or the file system.
16
16
  *
17
- * Everything here is a cheap read by construction. `hasBinary` resolves a path (the same probe a
18
- * launch uses, so the answer can never disagree with a launch), and the bridge reading is the same
19
- * install-tree inspection the bridge-status route already serves. Nothing spawns anything.
17
+ * Everything here is a cheap environment check. The launch path's own binary probes resolve the
18
+ * bundled runtime and installed system browsers; bridge readers inspect the installation and its
19
+ * published endpoint. Available files establish availability, while browser calls establish whether
20
+ * a particular page can be driven. Nothing spawns anything.
20
21
  * @module dsh-browser/browser-electron/runtime-status
21
22
  */
22
23
  import type { BridgeStatus } from './bridge-status.js';
23
24
  import type { BridgeEndpointState } from './bridge-endpoint.js';
24
25
  import type { ProvisionSnapshot } from './electron-provision.js';
25
- import type { BrowserChannel } from './system-browser.js';
26
+ import { type BrowserChannel, type DetectedBrowser } from './system-browser.js';
26
27
  /** The part of the carrier the channel names, in the terms the panel has to explain. */
27
28
  export type CarrierKind = 'sidebar' | 'bundled' | 'system' | 'auto';
28
- /**
29
- * Whether the readiness question has an answer at all.
30
- *
31
- * `unknown` is not a defect: an explicit Chrome / Edge choice is only falsifiable by launching one,
32
- * and launching a browser to answer a status question is exactly what this report must not do. The
33
- * panel says so in words instead of guessing a colour.
34
- */
35
- export type Readiness = 'ready' | 'blocked' | 'unknown';
29
+ /** Whether the chosen carrier's required files or running bridge are available. */
30
+ export type Readiness = 'ready' | 'blocked';
31
+ /** The system-browser discovery result, obtained without launching an executable. */
32
+ export interface SystemBrowserReadiness {
33
+ /** False for channels that use the sidebar or bundled runtime directly. */
34
+ readonly checked: boolean;
35
+ readonly present: boolean;
36
+ readonly kind?: DetectedBrowser['kind'];
37
+ readonly path?: string;
38
+ /** What was found or which configured product is missing. */
39
+ readonly detail: string;
40
+ }
36
41
  /** The Electron runtime's state, as the panel needs it. */
37
42
  export interface ElectronReadiness {
38
43
  /** `present` — a launch would find a binary; `preparing` — a download is running now; and so on. */
@@ -70,8 +75,13 @@ export interface RuntimeStatusReport {
70
75
  readonly channel: BrowserChannel;
71
76
  /** What that channel resolves to, in panel terms. */
72
77
  readonly carrier: CarrierKind;
73
- /** Whether the browser this channel names can serve a call right now. */
78
+ /** The concrete carrier selected by the same discovery priority as the browser provider. */
79
+ readonly resolvedCarrier: Exclude<CarrierKind, 'auto'>;
80
+ /** Whether the carrier's environment requirements are available. */
74
81
  readonly readiness: Readiness;
82
+ readonly systemBrowser: SystemBrowserReadiness;
83
+ /** The system executable selected for the resolved carrier, when applicable. */
84
+ readonly executable?: string;
75
85
  readonly electron: ElectronReadiness;
76
86
  readonly bridge: BridgeReadiness;
77
87
  /** Whether "Prepare the bundled browser" is worth offering (it is not while one is running). */
@@ -89,6 +99,10 @@ export interface RuntimeStatusDeps {
89
99
  readonly bridge: () => BridgeStatus | undefined;
90
100
  /** The endpoint the shell publishes while it runs; undefined when nothing published one. */
91
101
  readonly endpoint: () => BridgeEndpointState | undefined;
102
+ /** The launch path's filesystem-only browser discovery; defaults to the production reader. */
103
+ readonly detectBrowser?: (channel: BrowserChannel) => DetectedBrowser | undefined;
104
+ /** The provider's current carrier, including a fallback selected after sidebar loss. */
105
+ readonly selectedCarrier?: () => Exclude<CarrierKind, 'auto'> | undefined;
92
106
  }
93
107
  /**
94
108
  * Assemble the report.
@@ -1,3 +1,4 @@
1
+ import { detectBrowser } from './system-browser.js';
1
2
  /** Which carrier a channel names. */
2
3
  function carrierOf(channel) {
3
4
  if (channel === 'sidebar')
@@ -60,25 +61,44 @@ export function readRuntimeStatus(deps) {
60
61
  // The sidebar needs BOTH halves: our patch inside the shell it will be driven through, and that
61
62
  // shell actually running. Either one alone is the false green this report exists to prevent.
62
63
  const sidebarReady = bridge.state === 'installed' && bridge.running;
64
+ const checkSystemBrowser = carrier === 'system' || carrier === 'auto';
65
+ const detected = checkSystemBrowser ? (deps.detectBrowser ?? detectBrowser)(channel) : undefined;
66
+ const systemBrowser = {
67
+ checked: checkSystemBrowser,
68
+ present: detected !== undefined,
69
+ ...detected === undefined ? {} : { kind: detected.kind, path: detected.path },
70
+ detail: detected !== undefined ? `${detected.kind} is available at ${detected.path}`
71
+ : !checkSystemBrowser ? `the ${carrier} channel uses its own carrier`
72
+ : channel === 'auto' ? 'no Chrome, Edge or Brave installation was found'
73
+ : `the selected ${channel} installation was not found`,
74
+ };
63
75
  let readiness;
76
+ let resolvedCarrier;
64
77
  if (carrier === 'sidebar') {
78
+ resolvedCarrier = 'sidebar';
65
79
  readiness = sidebarReady ? 'ready' : 'blocked';
66
80
  }
67
81
  else if (carrier === 'bundled') {
82
+ resolvedCarrier = 'bundled';
68
83
  readiness = electronReady(state) ? 'ready' : 'blocked';
69
84
  }
70
85
  else if (carrier === 'auto') {
71
- // `auto` is satisfied by either carrier, so a working sidebar covers a missing runtime. An
72
- // explicit Chrome / Edge install would satisfy it too, but proving that means launching one.
73
- readiness = electronReady(state) || sidebarReady ? 'ready' : 'unknown';
86
+ // Discovery may adopt a live desktop bridge after initially choosing a system browser. Match
87
+ // that priority here, then use the bundled runtime when no system browser was found.
88
+ resolvedCarrier = deps.selectedCarrier?.() ?? (sidebarReady ? 'sidebar' : detected !== undefined ? 'system' : 'bundled');
89
+ readiness = (resolvedCarrier === 'sidebar' ? sidebarReady : resolvedCarrier === 'system' ? detected !== undefined : electronReady(state)) ? 'ready' : 'blocked';
74
90
  }
75
91
  else {
76
- readiness = 'unknown';
92
+ resolvedCarrier = 'system';
93
+ readiness = detected !== undefined ? 'ready' : 'blocked';
77
94
  }
78
95
  return {
79
96
  channel,
80
97
  carrier,
98
+ resolvedCarrier,
81
99
  readiness,
100
+ systemBrowser,
101
+ ...resolvedCarrier === 'system' && detected !== undefined ? { executable: detected.path } : {},
82
102
  electron,
83
103
  bridge,
84
104
  // Offering the button while a download runs would be a second download, which is the one thing
@@ -123,6 +123,17 @@ export interface BrowserSettings {
123
123
  * what it was before this existed. The user owns the field, can point it at any MCP tool that
124
124
  * takes a path (Feishu drive, Baidu Netdisk), and can empty it again at any time.
125
125
  */
126
+ /**
127
+ * Desktop bridge handled without asking.
128
+ *
129
+ * Historical automatic-install preference retained when reading existing settings documents.
130
+ * Runtime automatic installation is disabled; bridge maintenance is an explicit action after
131
+ * DSH Desktop is closed, even when an older document contains autoInstall=true.
132
+ */
133
+ readonly bridge: {
134
+ /** Legacy preference; it does not trigger installation at runtime. Default false. */
135
+ readonly autoInstall: boolean;
136
+ };
126
137
  readonly delivery: {
127
138
  /** MCP tool that receives the saved file. Empty = save locally and stop there. */
128
139
  readonly tool: string;
@@ -9,8 +9,8 @@
9
9
  * @module dsh-browser/browser-electron/settings-store
10
10
  */
11
11
  import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
12
- import { homedir } from 'node:os';
13
12
  import { dirname, join } from 'node:path';
13
+ import { dshHome } from './paths.js';
14
14
  /** Every value {@link HeadlessMode} accepts, for validation and the settings UI. */
15
15
  export const HEADLESS_MODES = ['auto', 'headless', 'windowed'];
16
16
  /** Defaults for every switch: the documented out-of-the-box behaviour. */
@@ -27,6 +27,7 @@ export const DEFAULT_SETTINGS = {
27
27
  // Off unless the host turns it on. A frame can show a CAPTCHA, an account name, or logged-in
28
28
  // content, so watching is an explicit decision rather than something a remote client can arrange.
29
29
  remoteView: { enabled: false },
30
+ bridge: { autoInstall: false },
30
31
  actions: { allowExecute: true, allowDownload: true, allowCredentialWrite: true },
31
32
  // Local by default: the file lands in downloadDir and nothing leaves the machine until the user
32
33
  // names a tool here. {file_path} is the argument name both Feishu's and Netdisk's upload tools use.
@@ -38,7 +39,7 @@ export const DEFAULT_SETTINGS = {
38
39
  * @returns the settings file path.
39
40
  */
40
41
  export function settingsPath() {
41
- const home = process.env.DSH_HOME ?? join(homedir(), '.dsh');
42
+ const home = dshHome();
42
43
  return join(home, 'dsh-builtin-browser-host', 'settings.json');
43
44
  }
44
45
  /** Coerce one boolean field, keeping the default when absent or mistyped. */
@@ -244,6 +245,11 @@ export function resolveSettings(raw, warn) {
244
245
  // Fail-closed, and stated separately from `gate`'s fallback so the intent is visible: an
245
246
  // unreadable or absent section means nobody watches. Unlike the other switches, whose defaults
246
247
  // are "on", this one has no safe default other than off.
248
+ bridge: {
249
+ autoInstall: section(source, 'bridge') === undefined
250
+ ? DEFAULT_SETTINGS.bridge.autoInstall
251
+ : gate(section(source, 'bridge').autoInstall, DEFAULT_SETTINGS.bridge.autoInstall),
252
+ },
247
253
  remoteView: {
248
254
  enabled: remoteView === undefined
249
255
  ? false
@@ -0,0 +1,36 @@
1
+ import type { CarrierLossReason, CarrierPage } from '../browser/types.js';
2
+ import type { ElectronBrowserViewHost, ElectronViewHandle, PresentOptions } from './provider.js';
3
+ /**
4
+ * Keep an explicit sidebar selection while its bridge starts or reconnects.
5
+ * Discovery is deferred until a command needs the bridge; it never selects another carrier.
6
+ */
7
+ export declare class SidebarOnlyHost implements ElectronBrowserViewHost {
8
+ private readonly loader;
9
+ private readonly views;
10
+ private lease;
11
+ private loading;
12
+ private disposed;
13
+ private lostListener;
14
+ constructor(loader: () => Promise<ElectronBrowserViewHost>);
15
+ /** Keep the explicit selection available so discovery failures reach the caller unchanged. */
16
+ available(): boolean;
17
+ /** Return a stable handle without opening a sidebar or discovering a bridge. */
18
+ createView(owner?: string): ElectronViewHandle;
19
+ destroyView(handle: ElectronViewHandle): void;
20
+ /** Presentation must not turn the provider's initial show into a blank-page navigation. */
21
+ showView(handle: ElectronViewHandle, label?: string, options?: PresentOptions): void;
22
+ listPages(owner?: string): Promise<readonly CarrierPage[]>;
23
+ closePage(id: string, owner?: string): Promise<void>;
24
+ /** Retire only this conversation's handles before awaiting an in-flight discovery. */
25
+ releasePage(owner?: string): Promise<void>;
26
+ collapse(): Promise<void>;
27
+ onLost(listener: (reason: CarrierLossReason) => void): void;
28
+ dispose(): void;
29
+ private assertOpen;
30
+ private assertView;
31
+ private assertLease;
32
+ private load;
33
+ private lost;
34
+ private bind;
35
+ private send;
36
+ }
@@ -0,0 +1,192 @@
1
+ /** A lazy, reconnectable sidebar carrier that preserves the provider's view handles. */
2
+ import { randomUUID } from 'node:crypto';
3
+ /**
4
+ * Keep an explicit sidebar selection while its bridge starts or reconnects.
5
+ * Discovery is deferred until a command needs the bridge; it never selects another carrier.
6
+ */
7
+ export class SidebarOnlyHost {
8
+ loader;
9
+ views = new Map();
10
+ lease;
11
+ loading;
12
+ disposed = false;
13
+ lostListener;
14
+ constructor(loader) {
15
+ this.loader = loader;
16
+ }
17
+ /** Keep the explicit selection available so discovery failures reach the caller unchanged. */
18
+ available() { return !this.disposed; }
19
+ /** Return a stable handle without opening a sidebar or discovering a bridge. */
20
+ createView(owner) {
21
+ this.assertOpen();
22
+ const handle = {
23
+ id: randomUUID(),
24
+ sendCommand: (method, params, options) => this.send(view, method, params, options),
25
+ download: async (url, savePath) => {
26
+ const bound = await this.bind(view);
27
+ this.assertView(view);
28
+ this.assertLease(bound.lease);
29
+ if (bound.handle.download === undefined)
30
+ throw new Error('dsh-builtin-browser: update the desktop bridge for sidebar downloads');
31
+ await bound.handle.download(url, savePath);
32
+ },
33
+ };
34
+ const view = { handle, owner };
35
+ this.views.set(handle.id, view);
36
+ return handle;
37
+ }
38
+ destroyView(handle) {
39
+ const view = this.views.get(handle.id);
40
+ if (view?.handle !== handle)
41
+ return;
42
+ this.views.delete(handle.id);
43
+ if (view.bound !== undefined)
44
+ view.bound.lease.host.destroyView(view.bound.handle);
45
+ view.bound = undefined;
46
+ }
47
+ /** Presentation must not turn the provider's initial show into a blank-page navigation. */
48
+ showView(handle, label, options) {
49
+ const view = this.views.get(handle.id);
50
+ const bound = view?.handle === handle ? view.bound : undefined;
51
+ if (!this.disposed && bound !== undefined && bound.lease === this.lease) {
52
+ bound.lease.host.showView?.(bound.handle, label, options);
53
+ }
54
+ }
55
+ async listPages(owner) {
56
+ const lease = await this.load();
57
+ this.assertLease(lease);
58
+ return lease.host.listPages === undefined ? [] : lease.host.listPages(owner);
59
+ }
60
+ async closePage(id, owner) {
61
+ const lease = await this.load();
62
+ this.assertLease(lease);
63
+ if (lease.host.closePage === undefined)
64
+ throw new Error('dsh-builtin-browser: this sidebar bridge cannot close pages');
65
+ await lease.host.closePage(id, owner);
66
+ }
67
+ /** Retire only this conversation's handles before awaiting an in-flight discovery. */
68
+ async releasePage(owner) {
69
+ for (const view of [...this.views.values()]) {
70
+ if (owner === undefined || view.owner === owner)
71
+ this.destroyView(view.handle);
72
+ }
73
+ const lease = this.lease ?? await this.loading?.catch(() => undefined);
74
+ if (!this.disposed && lease !== undefined && lease === this.lease)
75
+ await lease.host.releasePage?.(owner);
76
+ }
77
+ async collapse() {
78
+ if (!this.disposed)
79
+ await this.lease?.host.collapse?.();
80
+ }
81
+ onLost(listener) {
82
+ this.lostListener = listener;
83
+ }
84
+ dispose() {
85
+ if (this.disposed)
86
+ return;
87
+ this.disposed = true;
88
+ this.views.clear();
89
+ const lease = this.lease;
90
+ this.lease = undefined;
91
+ this.lostListener = undefined;
92
+ lease?.host.dispose?.();
93
+ }
94
+ assertOpen() {
95
+ if (this.disposed)
96
+ throw new Error('dsh-builtin-browser: sidebar host is disposed');
97
+ }
98
+ assertView(view) {
99
+ this.assertOpen();
100
+ if (this.views.get(view.handle.id) !== view)
101
+ throw new Error('dsh-builtin-browser: sidebar view is destroyed');
102
+ }
103
+ assertLease(lease) {
104
+ this.assertOpen();
105
+ if (this.lease !== lease)
106
+ throw new Error('dsh-builtin-browser: sidebar bridge changed before the operation');
107
+ }
108
+ load() {
109
+ this.assertOpen();
110
+ if (this.lease !== undefined)
111
+ return Promise.resolve(this.lease);
112
+ if (this.loading !== undefined)
113
+ return this.loading;
114
+ const pending = Promise.resolve().then(this.loader).then(host => {
115
+ if (this.disposed) {
116
+ host.dispose?.();
117
+ this.assertOpen();
118
+ }
119
+ const lease = { host };
120
+ this.lease = lease;
121
+ try {
122
+ host.onLost?.(reason => this.lost(lease, reason));
123
+ }
124
+ catch (error) {
125
+ if (this.lease === lease)
126
+ this.lease = undefined;
127
+ host.dispose?.();
128
+ throw error;
129
+ }
130
+ if (this.lease !== lease)
131
+ throw new Error('dsh-builtin-browser: sidebar bridge was lost during discovery');
132
+ return lease;
133
+ });
134
+ this.loading = pending;
135
+ const clear = () => { if (this.loading === pending)
136
+ this.loading = undefined; };
137
+ void pending.then(clear, clear);
138
+ return pending;
139
+ }
140
+ lost(lease, reason) {
141
+ if (this.disposed || this.lease !== lease)
142
+ return;
143
+ this.lease = undefined;
144
+ this.loading = undefined;
145
+ for (const view of this.views.values()) {
146
+ view.bound = undefined;
147
+ view.pending = undefined;
148
+ }
149
+ // A command already in flight keeps its original outcome; the next call rediscovers.
150
+ try {
151
+ lease.host.dispose?.();
152
+ }
153
+ catch { /* The next discovery replaces this failed carrier. */ }
154
+ try {
155
+ this.lostListener?.(reason);
156
+ }
157
+ catch { /* Transport recovery must survive a listener failure. */ }
158
+ }
159
+ bind(view) {
160
+ this.assertView(view);
161
+ if (view.bound !== undefined && view.bound.lease === this.lease)
162
+ return Promise.resolve(view.bound);
163
+ if (view.pending !== undefined)
164
+ return view.pending;
165
+ const pending = this.load().then(lease => {
166
+ this.assertView(view);
167
+ if (this.lease !== lease)
168
+ throw new Error('dsh-builtin-browser: sidebar bridge changed before binding the view');
169
+ const handle = lease.host.createView(view.owner);
170
+ if (this.disposed || this.views.get(view.handle.id) !== view || this.lease !== lease) {
171
+ lease.host.destroyView(handle);
172
+ this.assertView(view);
173
+ throw new Error('dsh-builtin-browser: sidebar bridge changed while binding the view');
174
+ }
175
+ const bound = { lease, handle };
176
+ view.bound = bound;
177
+ return bound;
178
+ });
179
+ view.pending = pending;
180
+ const clear = () => { if (view.pending === pending)
181
+ view.pending = undefined; };
182
+ void pending.then(clear, clear);
183
+ return pending;
184
+ }
185
+ async send(view, method, params, options) {
186
+ const bound = await this.bind(view);
187
+ this.assertView(view);
188
+ if (this.lease !== bound.lease)
189
+ throw new Error('dsh-builtin-browser: sidebar bridge changed before the command');
190
+ return bound.handle.sendCommand(method, params, options);
191
+ }
192
+ }
@@ -119,14 +119,6 @@ export declare class SystemBrowserViewHost implements ElectronBrowserViewHost {
119
119
  */
120
120
  private clientSuspect;
121
121
  private child;
122
- /**
123
- * True when the browser in use was adopted from a previous run rather than launched here.
124
- *
125
- * Worth recording because the two differ on teardown: a browser this host spawned is its to
126
- * kill, while one it merely took over belongs to a process that is already gone — closing it is
127
- * still right (it holds the profile nobody else can use), but it is a decision, not cleanup.
128
- */
129
- private adoptedRunning;
130
122
  /** Whether this connection's surplus blank pages have been collapsed already. */
131
123
  private blanksNormalized;
132
124
  private starting;
@@ -205,7 +197,7 @@ export declare class SystemBrowserViewHost implements ElectronBrowserViewHost {
205
197
  * not a browser at all. What makes adoption safe HERE is that this runs BEFORE launching, on a
206
198
  * file that lives inside this plugin's own profile directory — only a browser started with this
207
199
  * `--user-data-dir` writes it — and the endpoint is then asked to identify itself.
208
- * @param why - a short phrase for the log, naming which attempt this is.
200
+ * @param _why - a short phrase for the log, naming which attempt this is.
209
201
  * @returns a connected client for the running browser, or undefined when there is none.
210
202
  */
211
203
  private adoptRunningBrowser;
@@ -116,8 +116,8 @@ const PATH_NAMES = {
116
116
  const INSTALL_LOCATIONS = {
117
117
  chrome: {
118
118
  win32: [
119
- String.raw `C:\Program Files\Google\Chrome\Application\chrome.exe`,
120
- String.raw `C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
119
+ String.raw `%ProgramFiles%\Google\Chrome\Application\chrome.exe`,
120
+ String.raw `%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe`,
121
121
  // Where a per-user install lands, which is what Chrome's own installer chooses when it
122
122
  // cannot (or should not) write to Program Files. Missing this meant the plugin reported
123
123
  // "no browser found" on machines that plainly had one.
@@ -138,8 +138,8 @@ const INSTALL_LOCATIONS = {
138
138
  },
139
139
  edge: {
140
140
  win32: [
141
- String.raw `C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`,
142
- String.raw `C:\Program Files\Microsoft\Edge\Application\msedge.exe`,
141
+ String.raw `%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe`,
142
+ String.raw `%ProgramFiles%\Microsoft\Edge\Application\msedge.exe`,
143
143
  String.raw `%LOCALAPPDATA%\Microsoft\Edge\Application\msedge.exe`,
144
144
  ],
145
145
  darwin: ['/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'],
@@ -151,8 +151,8 @@ const INSTALL_LOCATIONS = {
151
151
  },
152
152
  brave: {
153
153
  win32: [
154
- String.raw `C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe`,
155
- String.raw `C:\Program Files (x86)\BraveSoftware\Brave-Browser\Application\brave.exe`,
154
+ String.raw `%ProgramFiles%\BraveSoftware\Brave-Browser\Application\brave.exe`,
155
+ String.raw `%ProgramFiles(x86)%\BraveSoftware\Brave-Browser\Application\brave.exe`,
156
156
  String.raw `%LOCALAPPDATA%\BraveSoftware\Brave-Browser\Application\brave.exe`,
157
157
  ],
158
158
  darwin: ['/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'],
@@ -517,14 +517,6 @@ export class SystemBrowserViewHost {
517
517
  */
518
518
  clientSuspect = false;
519
519
  child;
520
- /**
521
- * True when the browser in use was adopted from a previous run rather than launched here.
522
- *
523
- * Worth recording because the two differ on teardown: a browser this host spawned is its to
524
- * kill, while one it merely took over belongs to a process that is already gone — closing it is
525
- * still right (it holds the profile nobody else can use), but it is a decision, not cleanup.
526
- */
527
- adoptedRunning = false;
528
520
  /** Whether this connection's surplus blank pages have been collapsed already. */
529
521
  blanksNormalized = false;
530
522
  starting;
@@ -678,10 +670,10 @@ export class SystemBrowserViewHost {
678
670
  * not a browser at all. What makes adoption safe HERE is that this runs BEFORE launching, on a
679
671
  * file that lives inside this plugin's own profile directory — only a browser started with this
680
672
  * `--user-data-dir` writes it — and the endpoint is then asked to identify itself.
681
- * @param why - a short phrase for the log, naming which attempt this is.
673
+ * @param _why - a short phrase for the log, naming which attempt this is.
682
674
  * @returns a connected client for the running browser, or undefined when there is none.
683
675
  */
684
- async adoptRunningBrowser(why) {
676
+ async adoptRunningBrowser(_why) {
685
677
  const portFile = join(this.profileDir, 'DevToolsActivePort');
686
678
  let port;
687
679
  try {
@@ -719,7 +711,6 @@ export class SystemBrowserViewHost {
719
711
  return undefined;
720
712
  }
721
713
  this.client = client;
722
- this.adoptedRunning = true;
723
714
  return client;
724
715
  }
725
716
  catch {
@@ -742,7 +733,15 @@ export class SystemBrowserViewHost {
742
733
  const adopted = await this.adoptRunningBrowser('before launch');
743
734
  if (adopted !== undefined)
744
735
  return adopted;
745
- const launch = resolveLaunchMode(this.isQuiet() ? 'headless' : this.headlessMode);
736
+ // Whether a window exists is decided by `browser.headless` ALONE (plus the operator's
737
+ // DSH_BROWSER_HEADLESS override inside resolveLaunchMode). `ui.quiet` must not force
738
+ // headless: it describes how the agent presents its work — no activation, no raising,
739
+ // background targets — not whether the human is allowed to see a browser at all.
740
+ // Overriding the setting here made an explicit `headless: windowed`/`headed` invisible on
741
+ // Chrome/Edge, so the human could not take over a login or a challenge, and an already
742
+ // headless process cannot become visible by toggling quiet later. Quiet still governs
743
+ // presentView() and createTarget() below, which is where activation belongs.
744
+ const launch = resolveLaunchMode(this.headlessMode);
746
745
  const args = [
747
746
  '--remote-debugging-port=0',
748
747
  `--user-data-dir=${this.profileDir}`,
@@ -865,8 +864,6 @@ export class SystemBrowserViewHost {
865
864
  return undefined;
866
865
  }
867
866
  })();
868
- // Kept for the failure message and for the exit listener's diagnostics; no longer a judgement.
869
- const spawnedAt = Date.now();
870
867
  let child;
871
868
  try {
872
869
  child = this.launcher(this.browser.path, args);
@@ -916,8 +913,8 @@ export class SystemBrowserViewHost {
916
913
  const after = statSync(portFile);
917
914
  const contents = readFileSync(portFile, 'utf8');
918
915
  // Unchanged since before the launch: this is the previous browser's file, whatever its
919
- // mtime says. Comparing against the snapshot rather than the spawn time is what keeps this
920
- // correct on a filesystem whose timestamps are coarser than the clock behind spawnedAt.
916
+ // mtime says. Comparing against the snapshot rather than a wall-clock instant is what
917
+ // keeps this correct on a filesystem whose timestamps are coarser than a millisecond.
921
918
  if (portFileBefore !== undefined
922
919
  && after.mtimeMs <= portFileBefore.mtimeMs
923
920
  && contents === portFileBefore.contents)
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Bound an await with a timeout, without dictating the caller's error wording.
3
+ *
4
+ * The two hosts phrase their timeout errors differently and those strings reach the panel, so
5
+ * the shared primitive takes a factory instead of a message.
6
+ * @module dsh-browser/browser-electron/timing
7
+ */
8
+ export declare function withTimeoutShared<T>(promise: Promise<T>, ms: number, timedOut: () => Error): Promise<T>;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Bound an await with a timeout, without dictating the caller's error wording.
3
+ *
4
+ * The two hosts phrase their timeout errors differently and those strings reach the panel, so
5
+ * the shared primitive takes a factory instead of a message.
6
+ * @module dsh-browser/browser-electron/timing
7
+ */
8
+ export function withTimeoutShared(promise, ms, timedOut) {
9
+ return new Promise((resolve, reject) => {
10
+ const timer = setTimeout(() => { reject(timedOut()); }, ms);
11
+ promise.then((value) => { clearTimeout(timer); resolve(value); }, (error) => { clearTimeout(timer); reject(error); });
12
+ });
13
+ }
@@ -0,0 +1,3 @@
1
+ /** PowerShell's `-EncodedCommand` expects a UTF-16LE script encoded as base64. */
2
+ export declare function encodePowerShellScript(script: string): string;
3
+ export declare function windowsPowerShellPath(environment?: NodeJS.ProcessEnv, exists?: (path: string) => boolean): string;