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
@@ -14,27 +14,33 @@
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 { detectBrowser, type BrowserChannel, type DetectedBrowser } from './system-browser.js'
26
27
 
27
28
  /** The part of the carrier the channel names, in the terms the panel has to explain. */
28
29
  export type CarrierKind = 'sidebar' | 'bundled' | 'system' | 'auto'
29
30
 
30
- /**
31
- * Whether the readiness question has an answer at all.
32
- *
33
- * `unknown` is not a defect: an explicit Chrome / Edge choice is only falsifiable by launching one,
34
- * and launching a browser to answer a status question is exactly what this report must not do. The
35
- * panel says so in words instead of guessing a colour.
36
- */
37
- export type Readiness = 'ready' | 'blocked' | 'unknown'
31
+ /** Whether the chosen carrier's required files or running bridge are available. */
32
+ export type Readiness = 'ready' | 'blocked'
33
+
34
+ /** The system-browser discovery result, obtained without launching an executable. */
35
+ export interface SystemBrowserReadiness {
36
+ /** False for channels that use the sidebar or bundled runtime directly. */
37
+ readonly checked: boolean
38
+ readonly present: boolean
39
+ readonly kind?: DetectedBrowser['kind']
40
+ readonly path?: string
41
+ /** What was found or which configured product is missing. */
42
+ readonly detail: string
43
+ }
38
44
 
39
45
  /** The Electron runtime's state, as the panel needs it. */
40
46
  export interface ElectronReadiness {
@@ -75,8 +81,13 @@ export interface RuntimeStatusReport {
75
81
  readonly channel: BrowserChannel
76
82
  /** What that channel resolves to, in panel terms. */
77
83
  readonly carrier: CarrierKind
78
- /** Whether the browser this channel names can serve a call right now. */
84
+ /** The concrete carrier selected by the same discovery priority as the browser provider. */
85
+ readonly resolvedCarrier: Exclude<CarrierKind, 'auto'>
86
+ /** Whether the carrier's environment requirements are available. */
79
87
  readonly readiness: Readiness
88
+ readonly systemBrowser: SystemBrowserReadiness
89
+ /** The system executable selected for the resolved carrier, when applicable. */
90
+ readonly executable?: string
80
91
  readonly electron: ElectronReadiness
81
92
  readonly bridge: BridgeReadiness
82
93
  /** Whether "Prepare the bundled browser" is worth offering (it is not while one is running). */
@@ -95,6 +106,10 @@ export interface RuntimeStatusDeps {
95
106
  readonly bridge: () => BridgeStatus | undefined
96
107
  /** The endpoint the shell publishes while it runs; undefined when nothing published one. */
97
108
  readonly endpoint: () => BridgeEndpointState | undefined
109
+ /** The launch path's filesystem-only browser discovery; defaults to the production reader. */
110
+ readonly detectBrowser?: (channel: BrowserChannel) => DetectedBrowser | undefined
111
+ /** The provider's current carrier, including a fallback selected after sidebar loss. */
112
+ readonly selectedCarrier?: () => Exclude<CarrierKind, 'auto'> | undefined
98
113
  }
99
114
 
100
115
  /** Which carrier a channel names. */
@@ -162,23 +177,43 @@ export function readRuntimeStatus(deps: RuntimeStatusDeps): RuntimeStatusReport
162
177
  // shell actually running. Either one alone is the false green this report exists to prevent.
163
178
  const sidebarReady = bridge.state === 'installed' && bridge.running
164
179
 
180
+ const checkSystemBrowser = carrier === 'system' || carrier === 'auto'
181
+ const detected = checkSystemBrowser ? (deps.detectBrowser ?? detectBrowser)(channel) : undefined
182
+ const systemBrowser: SystemBrowserReadiness = {
183
+ checked: checkSystemBrowser,
184
+ present: detected !== undefined,
185
+ ...detected === undefined ? {} : { kind: detected.kind, path: detected.path },
186
+ detail: detected !== undefined ? `${detected.kind} is available at ${detected.path}`
187
+ : !checkSystemBrowser ? `the ${carrier} channel uses its own carrier`
188
+ : channel === 'auto' ? 'no Chrome, Edge or Brave installation was found'
189
+ : `the selected ${channel} installation was not found`,
190
+ }
191
+
165
192
  let readiness: Readiness
193
+ let resolvedCarrier: RuntimeStatusReport['resolvedCarrier']
166
194
  if (carrier === 'sidebar') {
195
+ resolvedCarrier = 'sidebar'
167
196
  readiness = sidebarReady ? 'ready' : 'blocked'
168
197
  } else if (carrier === 'bundled') {
198
+ resolvedCarrier = 'bundled'
169
199
  readiness = electronReady(state) ? 'ready' : 'blocked'
170
200
  } else if (carrier === 'auto') {
171
- // `auto` is satisfied by either carrier, so a working sidebar covers a missing runtime. An
172
- // explicit Chrome / Edge install would satisfy it too, but proving that means launching one.
173
- readiness = electronReady(state) || sidebarReady ? 'ready' : 'unknown'
201
+ // Discovery may adopt a live desktop bridge after initially choosing a system browser. Match
202
+ // that priority here, then use the bundled runtime when no system browser was found.
203
+ resolvedCarrier = deps.selectedCarrier?.() ?? (sidebarReady ? 'sidebar' : detected !== undefined ? 'system' : 'bundled')
204
+ readiness = (resolvedCarrier === 'sidebar' ? sidebarReady : resolvedCarrier === 'system' ? detected !== undefined : electronReady(state)) ? 'ready' : 'blocked'
174
205
  } else {
175
- readiness = 'unknown'
206
+ resolvedCarrier = 'system'
207
+ readiness = detected !== undefined ? 'ready' : 'blocked'
176
208
  }
177
209
 
178
210
  return {
179
211
  channel,
180
212
  carrier,
213
+ resolvedCarrier,
181
214
  readiness,
215
+ systemBrowser,
216
+ ...resolvedCarrier === 'system' && detected !== undefined ? { executable: detected.path } : {},
182
217
  electron,
183
218
  bridge,
184
219
  // Offering the button while a download runs would be a second download, which is the one thing
@@ -9,9 +9,9 @@
9
9
  * @module dsh-browser/browser-electron/settings-store
10
10
  */
11
11
 
12
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
13
- import { homedir } from 'node:os'
12
+ import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
14
13
  import { dirname, join } from 'node:path'
14
+ import { dshHome } from './paths.js'
15
15
  import type { BrowserChannel } from './system-browser.js'
16
16
 
17
17
  /** Vision/operation strategy the provider prefers when the model can see. */
@@ -131,6 +131,17 @@ export interface BrowserSettings {
131
131
  * what it was before this existed. The user owns the field, can point it at any MCP tool that
132
132
  * takes a path (Feishu drive, Baidu Netdisk), and can empty it again at any time.
133
133
  */
134
+ /**
135
+ * Desktop bridge handled without asking.
136
+ *
137
+ * Historical automatic-install preference retained when reading existing settings documents.
138
+ * Runtime automatic installation is disabled; bridge maintenance is an explicit action after
139
+ * DSH Desktop is closed, even when an older document contains autoInstall=true.
140
+ */
141
+ readonly bridge: {
142
+ /** Legacy preference; it does not trigger installation at runtime. Default false. */
143
+ readonly autoInstall: boolean
144
+ }
134
145
  readonly delivery: {
135
146
  /** MCP tool that receives the saved file. Empty = save locally and stop there. */
136
147
  readonly tool: string
@@ -157,6 +168,7 @@ export const DEFAULT_SETTINGS: BrowserSettings = {
157
168
  // Off unless the host turns it on. A frame can show a CAPTCHA, an account name, or logged-in
158
169
  // content, so watching is an explicit decision rather than something a remote client can arrange.
159
170
  remoteView: { enabled: false },
171
+ bridge: { autoInstall: false },
160
172
  actions: { allowExecute: true, allowDownload: true, allowCredentialWrite: true },
161
173
  // Local by default: the file lands in downloadDir and nothing leaves the machine until the user
162
174
  // names a tool here. {file_path} is the argument name both Feishu's and Netdisk's upload tools use.
@@ -169,7 +181,7 @@ export const DEFAULT_SETTINGS: BrowserSettings = {
169
181
  * @returns the settings file path.
170
182
  */
171
183
  export function settingsPath(): string {
172
- const home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
184
+ const home = dshHome()
173
185
  return join(home, 'dsh-builtin-browser-host', 'settings.json')
174
186
  }
175
187
 
@@ -377,6 +389,11 @@ export function resolveSettings(raw: unknown, warn?: (message: string) => void):
377
389
  // Fail-closed, and stated separately from `gate`'s fallback so the intent is visible: an
378
390
  // unreadable or absent section means nobody watches. Unlike the other switches, whose defaults
379
391
  // are "on", this one has no safe default other than off.
392
+ bridge: {
393
+ autoInstall: section(source, 'bridge') === undefined
394
+ ? DEFAULT_SETTINGS.bridge.autoInstall
395
+ : gate((section(source, 'bridge') as { autoInstall?: unknown }).autoInstall, DEFAULT_SETTINGS.bridge.autoInstall),
396
+ },
380
397
  remoteView: {
381
398
  enabled: remoteView === undefined
382
399
  ? false
@@ -0,0 +1,199 @@
1
+ /** A lazy, reconnectable sidebar carrier that preserves the provider's view handles. */
2
+ import { randomUUID } from 'node:crypto'
3
+ import type { CarrierLossReason, CarrierPage } from '../browser/types.js'
4
+ import type {
5
+ CommandOptions, ElectronBrowserViewHost, ElectronViewHandle, PresentOptions,
6
+ } from './provider.js'
7
+
8
+ interface HostLease {
9
+ readonly host: ElectronBrowserViewHost
10
+ }
11
+
12
+ interface BoundView {
13
+ readonly lease: HostLease
14
+ readonly handle: ElectronViewHandle
15
+ }
16
+
17
+ interface SidebarView {
18
+ readonly handle: ElectronViewHandle
19
+ readonly owner: string | undefined
20
+ bound?: BoundView
21
+ pending?: Promise<BoundView>
22
+ }
23
+
24
+ /**
25
+ * Keep an explicit sidebar selection while its bridge starts or reconnects.
26
+ * Discovery is deferred until a command needs the bridge; it never selects another carrier.
27
+ */
28
+ export class SidebarOnlyHost implements ElectronBrowserViewHost {
29
+ private readonly views = new Map<string, SidebarView>()
30
+ private lease: HostLease | undefined
31
+ private loading: Promise<HostLease> | undefined
32
+ private disposed = false
33
+ private lostListener: ((reason: CarrierLossReason) => void) | undefined
34
+
35
+ constructor(private readonly loader: () => Promise<ElectronBrowserViewHost>) {}
36
+
37
+ /** Keep the explicit selection available so discovery failures reach the caller unchanged. */
38
+ available(): boolean { return !this.disposed }
39
+
40
+ /** Return a stable handle without opening a sidebar or discovering a bridge. */
41
+ createView(owner?: string): ElectronViewHandle {
42
+ this.assertOpen()
43
+ const handle: ElectronViewHandle = {
44
+ id: randomUUID(),
45
+ sendCommand: (method, params, options) => this.send(view, method, params, options),
46
+ download: async (url, savePath) => {
47
+ const bound = await this.bind(view)
48
+ this.assertView(view)
49
+ this.assertLease(bound.lease)
50
+ if (bound.handle.download === undefined) throw new Error('dsh-builtin-browser: update the desktop bridge for sidebar downloads')
51
+ await bound.handle.download(url, savePath)
52
+ },
53
+ }
54
+ const view: SidebarView = { handle, owner }
55
+ this.views.set(handle.id, view)
56
+ return handle
57
+ }
58
+
59
+ destroyView(handle: ElectronViewHandle): void {
60
+ const view = this.views.get(handle.id)
61
+ if (view?.handle !== handle) return
62
+ this.views.delete(handle.id)
63
+ if (view.bound !== undefined) view.bound.lease.host.destroyView(view.bound.handle)
64
+ view.bound = undefined
65
+ }
66
+
67
+ /** Presentation must not turn the provider's initial show into a blank-page navigation. */
68
+ showView(handle: ElectronViewHandle, label?: string, options?: PresentOptions): void {
69
+ const view = this.views.get(handle.id)
70
+ const bound = view?.handle === handle ? view.bound : undefined
71
+ if (!this.disposed && bound !== undefined && bound.lease === this.lease) {
72
+ bound.lease.host.showView?.(bound.handle, label, options)
73
+ }
74
+ }
75
+
76
+ async listPages(owner?: string): Promise<readonly CarrierPage[]> {
77
+ const lease = await this.load()
78
+ this.assertLease(lease)
79
+ return lease.host.listPages === undefined ? [] : lease.host.listPages(owner)
80
+ }
81
+
82
+ async closePage(id: string, owner?: string): Promise<void> {
83
+ const lease = await this.load()
84
+ this.assertLease(lease)
85
+ if (lease.host.closePage === undefined) throw new Error('dsh-builtin-browser: this sidebar bridge cannot close pages')
86
+ await lease.host.closePage(id, owner)
87
+ }
88
+
89
+ /** Retire only this conversation's handles before awaiting an in-flight discovery. */
90
+ async releasePage(owner?: string): Promise<void> {
91
+ for (const view of [...this.views.values()]) {
92
+ if (owner === undefined || view.owner === owner) this.destroyView(view.handle)
93
+ }
94
+ const lease = this.lease ?? await this.loading?.catch(() => undefined)
95
+ if (!this.disposed && lease !== undefined && lease === this.lease) await lease.host.releasePage?.(owner)
96
+ }
97
+
98
+ async collapse(): Promise<void> {
99
+ if (!this.disposed) await this.lease?.host.collapse?.()
100
+ }
101
+
102
+ onLost(listener: (reason: CarrierLossReason) => void): void {
103
+ this.lostListener = listener
104
+ }
105
+
106
+ dispose(): void {
107
+ if (this.disposed) return
108
+ this.disposed = true
109
+ this.views.clear()
110
+ const lease = this.lease
111
+ this.lease = undefined
112
+ this.lostListener = undefined
113
+ lease?.host.dispose?.()
114
+ }
115
+
116
+ private assertOpen(): void {
117
+ if (this.disposed) throw new Error('dsh-builtin-browser: sidebar host is disposed')
118
+ }
119
+
120
+ private assertView(view: SidebarView): void {
121
+ this.assertOpen()
122
+ if (this.views.get(view.handle.id) !== view) throw new Error('dsh-builtin-browser: sidebar view is destroyed')
123
+ }
124
+
125
+ private assertLease(lease: HostLease): void {
126
+ this.assertOpen()
127
+ if (this.lease !== lease) throw new Error('dsh-builtin-browser: sidebar bridge changed before the operation')
128
+ }
129
+
130
+ private load(): Promise<HostLease> {
131
+ this.assertOpen()
132
+ if (this.lease !== undefined) return Promise.resolve(this.lease)
133
+ if (this.loading !== undefined) return this.loading
134
+ const pending = Promise.resolve().then(this.loader).then(host => {
135
+ if (this.disposed) {
136
+ host.dispose?.()
137
+ this.assertOpen()
138
+ }
139
+ const lease: HostLease = { host }
140
+ this.lease = lease
141
+ try {
142
+ host.onLost?.(reason => this.lost(lease, reason))
143
+ } catch (error) {
144
+ if (this.lease === lease) this.lease = undefined
145
+ host.dispose?.()
146
+ throw error
147
+ }
148
+ if (this.lease !== lease) throw new Error('dsh-builtin-browser: sidebar bridge was lost during discovery')
149
+ return lease
150
+ })
151
+ this.loading = pending
152
+ const clear = (): void => { if (this.loading === pending) this.loading = undefined }
153
+ void pending.then(clear, clear)
154
+ return pending
155
+ }
156
+
157
+ private lost(lease: HostLease, reason: CarrierLossReason): void {
158
+ if (this.disposed || this.lease !== lease) return
159
+ this.lease = undefined
160
+ this.loading = undefined
161
+ for (const view of this.views.values()) {
162
+ view.bound = undefined
163
+ view.pending = undefined
164
+ }
165
+ // A command already in flight keeps its original outcome; the next call rediscovers.
166
+ try { lease.host.dispose?.() } catch { /* The next discovery replaces this failed carrier. */ }
167
+ try { this.lostListener?.(reason) } catch { /* Transport recovery must survive a listener failure. */ }
168
+ }
169
+
170
+ private bind(view: SidebarView): Promise<BoundView> {
171
+ this.assertView(view)
172
+ if (view.bound !== undefined && view.bound.lease === this.lease) return Promise.resolve(view.bound)
173
+ if (view.pending !== undefined) return view.pending
174
+ const pending = this.load().then(lease => {
175
+ this.assertView(view)
176
+ if (this.lease !== lease) throw new Error('dsh-builtin-browser: sidebar bridge changed before binding the view')
177
+ const handle = lease.host.createView(view.owner)
178
+ if (this.disposed || this.views.get(view.handle.id) !== view || this.lease !== lease) {
179
+ lease.host.destroyView(handle)
180
+ this.assertView(view)
181
+ throw new Error('dsh-builtin-browser: sidebar bridge changed while binding the view')
182
+ }
183
+ const bound = { lease, handle }
184
+ view.bound = bound
185
+ return bound
186
+ })
187
+ view.pending = pending
188
+ const clear = (): void => { if (view.pending === pending) view.pending = undefined }
189
+ void pending.then(clear, clear)
190
+ return pending
191
+ }
192
+
193
+ private async send(view: SidebarView, method: string, params?: Record<string, unknown>, options?: CommandOptions): Promise<Record<string, unknown>> {
194
+ const bound = await this.bind(view)
195
+ this.assertView(view)
196
+ if (this.lease !== bound.lease) throw new Error('dsh-builtin-browser: sidebar bridge changed before the command')
197
+ return bound.handle.sendCommand(method, params, options)
198
+ }
199
+ }
@@ -151,8 +151,8 @@ const PATH_NAMES: Record<DetectedBrowser['kind'], Partial<Record<NodeJS.Platform
151
151
  const INSTALL_LOCATIONS: Record<DetectedBrowser['kind'], Partial<Record<NodeJS.Platform, string[]>>> = {
152
152
  chrome: {
153
153
  win32: [
154
- String.raw`C:\Program Files\Google\Chrome\Application\chrome.exe`,
155
- String.raw`C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
154
+ String.raw`%ProgramFiles%\Google\Chrome\Application\chrome.exe`,
155
+ String.raw`%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe`,
156
156
  // Where a per-user install lands, which is what Chrome's own installer chooses when it
157
157
  // cannot (or should not) write to Program Files. Missing this meant the plugin reported
158
158
  // "no browser found" on machines that plainly had one.
@@ -173,8 +173,8 @@ const INSTALL_LOCATIONS: Record<DetectedBrowser['kind'], Partial<Record<NodeJS.P
173
173
  },
174
174
  edge: {
175
175
  win32: [
176
- String.raw`C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`,
177
- String.raw`C:\Program Files\Microsoft\Edge\Application\msedge.exe`,
176
+ String.raw`%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe`,
177
+ String.raw`%ProgramFiles%\Microsoft\Edge\Application\msedge.exe`,
178
178
  String.raw`%LOCALAPPDATA%\Microsoft\Edge\Application\msedge.exe`,
179
179
  ],
180
180
  darwin: ['/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'],
@@ -186,8 +186,8 @@ const INSTALL_LOCATIONS: Record<DetectedBrowser['kind'], Partial<Record<NodeJS.P
186
186
  },
187
187
  brave: {
188
188
  win32: [
189
- String.raw`C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe`,
190
- String.raw`C:\Program Files (x86)\BraveSoftware\Brave-Browser\Application\brave.exe`,
189
+ String.raw`%ProgramFiles%\BraveSoftware\Brave-Browser\Application\brave.exe`,
190
+ String.raw`%ProgramFiles(x86)%\BraveSoftware\Brave-Browser\Application\brave.exe`,
191
191
  String.raw`%LOCALAPPDATA%\BraveSoftware\Brave-Browser\Application\brave.exe`,
192
192
  ],
193
193
  darwin: ['/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'],
@@ -546,14 +546,6 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
546
546
  */
547
547
  private clientSuspect = false
548
548
  private child: ChildProcess | undefined
549
- /**
550
- * True when the browser in use was adopted from a previous run rather than launched here.
551
- *
552
- * Worth recording because the two differ on teardown: a browser this host spawned is its to
553
- * kill, while one it merely took over belongs to a process that is already gone — closing it is
554
- * still right (it holds the profile nobody else can use), but it is a decision, not cleanup.
555
- */
556
- private adoptedRunning = false
557
549
  /** Whether this connection's surplus blank pages have been collapsed already. */
558
550
  private blanksNormalized = false
559
551
  private starting: Promise<CdpClient> | undefined
@@ -711,10 +703,10 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
711
703
  * not a browser at all. What makes adoption safe HERE is that this runs BEFORE launching, on a
712
704
  * file that lives inside this plugin's own profile directory — only a browser started with this
713
705
  * `--user-data-dir` writes it — and the endpoint is then asked to identify itself.
714
- * @param why - a short phrase for the log, naming which attempt this is.
706
+ * @param _why - a short phrase for the log, naming which attempt this is.
715
707
  * @returns a connected client for the running browser, or undefined when there is none.
716
708
  */
717
- private async adoptRunningBrowser(why: string): Promise<CdpClient | undefined> {
709
+ private async adoptRunningBrowser(_why: string): Promise<CdpClient | undefined> {
718
710
  const portFile = join(this.profileDir, 'DevToolsActivePort')
719
711
  let port: number
720
712
  try {
@@ -744,7 +736,6 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
744
736
  }
745
737
  if (this.disposed) { client.close(); return undefined }
746
738
  this.client = client
747
- this.adoptedRunning = true
748
739
  return client
749
740
  } catch {
750
741
  // No endpoint, nothing listening, or not a browser: all of them mean "launch one".
@@ -766,7 +757,15 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
766
757
  // after launch (exit code 0)" that required killing seven processes by hand.
767
758
  const adopted = await this.adoptRunningBrowser('before launch')
768
759
  if (adopted !== undefined) return adopted
769
- const launch = resolveLaunchMode(this.isQuiet() ? 'headless' : this.headlessMode)
760
+ // Whether a window exists is decided by `browser.headless` ALONE (plus the operator's
761
+ // DSH_BROWSER_HEADLESS override inside resolveLaunchMode). `ui.quiet` must not force
762
+ // headless: it describes how the agent presents its work — no activation, no raising,
763
+ // background targets — not whether the human is allowed to see a browser at all.
764
+ // Overriding the setting here made an explicit `headless: windowed`/`headed` invisible on
765
+ // Chrome/Edge, so the human could not take over a login or a challenge, and an already
766
+ // headless process cannot become visible by toggling quiet later. Quiet still governs
767
+ // presentView() and createTarget() below, which is where activation belongs.
768
+ const launch = resolveLaunchMode(this.headlessMode)
770
769
  const args = [
771
770
  '--remote-debugging-port=0',
772
771
  `--user-data-dir=${this.profileDir}`,
@@ -882,8 +881,6 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
882
881
  return undefined
883
882
  }
884
883
  })()
885
- // Kept for the failure message and for the exit listener's diagnostics; no longer a judgement.
886
- const spawnedAt = Date.now()
887
884
  let child: ReturnType<typeof spawn>
888
885
  try {
889
886
  child = this.launcher(this.browser.path, args)
@@ -930,8 +927,8 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
930
927
  const after = statSync(portFile)
931
928
  const contents = readFileSync(portFile, 'utf8')
932
929
  // Unchanged since before the launch: this is the previous browser's file, whatever its
933
- // mtime says. Comparing against the snapshot rather than the spawn time is what keeps this
934
- // correct on a filesystem whose timestamps are coarser than the clock behind spawnedAt.
930
+ // mtime says. Comparing against the snapshot rather than a wall-clock instant is what
931
+ // keeps this correct on a filesystem whose timestamps are coarser than a millisecond.
935
932
  if (portFileBefore !== undefined
936
933
  && after.mtimeMs <= portFileBefore.mtimeMs
937
934
  && contents === portFileBefore.contents) return undefined
@@ -0,0 +1,16 @@
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<T>(promise: Promise<T>, ms: number, timedOut: () => Error): Promise<T> {
9
+ return new Promise<T>((resolve, reject) => {
10
+ const timer = setTimeout(() => { reject(timedOut()) }, ms)
11
+ promise.then(
12
+ (value) => { clearTimeout(timer); resolve(value) },
13
+ (error) => { clearTimeout(timer); reject(error) },
14
+ )
15
+ })
16
+ }
@@ -0,0 +1,23 @@
1
+ /** Locate Windows system tools from the running system rather than an assumed system drive. */
2
+ import { existsSync } from 'node:fs'
3
+ import { win32 } from 'node:path'
4
+
5
+ /** PowerShell's `-EncodedCommand` expects a UTF-16LE script encoded as base64. */
6
+ export function encodePowerShellScript(script: string): string {
7
+ return Buffer.from(script, 'utf16le').toString('base64')
8
+ }
9
+
10
+ export function windowsPowerShellPath(
11
+ environment: NodeJS.ProcessEnv = process.env,
12
+ exists: (path: string) => boolean = existsSync,
13
+ ): string {
14
+ const read = (name: string): string | undefined => Object.entries(environment)
15
+ .find(([key]) => key.toUpperCase() === name)?.[1]
16
+ const root = read('SYSTEMROOT') || read('WINDIR')
17
+ if (root === undefined || !/^(?:[A-Za-z]:[\\/]|\\\\[^\\/]+[\\/][^\\/]+)/.test(root)) {
18
+ throw new Error('Windows system directory is unavailable; SystemRoot or WINDIR must identify the current system')
19
+ }
20
+ const path = win32.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
21
+ if (!exists(path)) throw new Error('Windows PowerShell is unavailable in the detected system directory')
22
+ return path
23
+ }
@@ -368,7 +368,7 @@ export function apply(ctx: Context, config: Config = {}): void {
368
368
  // Tool guidance band is 100-199; 150 keeps clear of the common 110/120
369
369
  // tool sections so ordering does not depend on plugin load sequence.
370
370
  order: 150,
371
- text: 'Use the dsh_browser_* tools to operate the built-in browser. Each task gets its own browser session AND its own window (with a real toolbar: address bar, back/forward/reload, tab strip) — the human can see it, use it like any browser, and take over at any time; your tabs and history are isolated from other tasks, so do not assume another task\'s navigation state is visible to you. Understand a page with dsh_browser_a11y (semantic roles/names/states — the best structure map) or dsh_browser_snapshot (numbered interactive elements), then drive it: dsh_browser_click/dsh_browser_type accept a target {by: css|text|xpath, value} for semantic locating, or coordinates from dsh_browser_screenshot for visual targeting. For form filling prefer dsh_browser_fill (batch) or dsh_browser_set_value/dsh_browser_check/dsh_browser_select/dsh_browser_clear (single control, target-based); verify with dsh_browser_get_value. Use dsh_browser_scrape for structured extraction from list pages instead of hand-written dsh_browser_execute. After navigating on slow sites, dsh_browser_wait for the page. For a run of steps use dsh_browser_do (one call, stops at the first step that cannot proceed, waits settle by themselves), and use dsh_browser_assert to check a result instead of trusting a screenshot — dsh_browser_console/network explain what the page did when the screen does not. Keep the human informed of what you are doing on the page. If a snapshot or dsh_browser_challenge reports a human-verification challenge (CAPTCHA), stop retrying and ask the human to complete it in the browser window, then re-check.',
371
+ text: 'Use dsh_browser_* tools to operate the built-in browser. Each task has its own session and window (real toolbar): the human can watch and take over, and other tasks\' pages are not visible to you. Map a page with dsh_browser_a11y (semantic roles/names/states) or dsh_browser_snapshot (numbered elements), then drive it: dsh_browser_click/dsh_browser_type take a target {by: css|text|xpath, value}, or coordinates from dsh_browser_screenshot. Prefer dsh_browser_fill (batch) or dsh_browser_set_value/check/select/clear for forms; verify with dsh_browser_get_value. Use dsh_browser_scrape (not hand-written dsh_browser_execute) for list pages; dsh_browser_wait after slow navigation. Use dsh_browser_do for a run of steps, dsh_browser_assert to check results, and dsh_browser_console/network when the screen is unclear. Say what you are doing on the page. On a CAPTCHA (dsh_browser_challenge), stop retrying and ask the human to solve it in the browser window, then re-check.',
372
372
  })
373
373
 
374
374
  /**
@@ -433,7 +433,7 @@ export function apply(ctx: Context, config: Config = {}): void {
433
433
  // dsh_browser_open is an overview of what just loaded, not a locator: it has no
434
434
  // `coords` parameter, so coordinates stay off here (dsh_browser_snapshot owns
435
435
  // that switch for callers that actually target pixels).
436
- render: (args, value) => [{ type: 'text', text: formatSnapshot(value, {}) }],
436
+ render: (_args, value) => [{ type: 'text', text: formatSnapshot(value, {}) }],
437
437
  },
438
438
  timeoutMs,
439
439
  isConcurrencySafe: () => false, // opens tabs / navigates; exclusive within a task
@@ -574,8 +574,9 @@ export function apply(ctx: Context, config: Config = {}): void {
574
574
  return `${indent}[${n.ref}] ${n.role} "${n.name}"${valuePart}${coordsPart}${statePart}${selectorPart}${n.frame === true ? ' (iframe)' : ''}`
575
575
  })
576
576
  const header = `URL: ${value.url}${value.title !== undefined ? `\nTitle: ${value.title}` : ''}`
577
- const hint = showCoords ? '' : '\n(no coords; pass coords: true)'
578
- return [{ type: 'text', text: `${header}\n\n${lines.length > 0 ? lines.join('\n') : '(no accessible interactive nodes)'}${value.truncated === true ? '\n(truncated)' : ''}${hint}` }]
577
+ // The "coords: true" hint used to be appended to EVERY a11y result. It already lives in
578
+ // the parameter description, so repeating it in each model turn was pure token cost.
579
+ return [{ type: 'text', text: `${header}\n\n${lines.length > 0 ? lines.join('\n') : '(no accessible interactive nodes)'}${value.truncated === true ? '\n(truncated)' : ''}` }]
579
580
  },
580
581
  },
581
582
  timeoutMs,