dsh-builtin-browser 0.5.6 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.en.md +75 -81
  3. package/README.md +75 -82
  4. package/client.js +831 -384
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +322 -141
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +157 -19
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/tool-reference.md +20 -1
  11. package/docs/user-guide.md +28 -4
  12. package/lib/browser/runtime.d.ts +3 -1
  13. package/lib/browser/runtime.js +9 -0
  14. package/lib/browser/types.d.ts +42 -0
  15. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  16. package/lib/browser-electron/authenticated-route.js +39 -0
  17. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  18. package/lib/browser-electron/automatic-maintenance.js +426 -0
  19. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  20. package/lib/browser-electron/bridge-auto.js +113 -0
  21. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  22. package/lib/browser-electron/bridge-connection.js +2 -4
  23. package/lib/browser-electron/bridge-endpoint.js +8 -19
  24. package/lib/browser-electron/bridge-install.d.ts +85 -0
  25. package/lib/browser-electron/bridge-install.js +211 -0
  26. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  27. package/lib/browser-electron/bridge-maintenance.js +125 -0
  28. package/lib/browser-electron/bridge-status.d.ts +10 -3
  29. package/lib/browser-electron/bridge-status.js +74 -24
  30. package/lib/browser-electron/desktop-bridge-host.d.ts +11 -5
  31. package/lib/browser-electron/desktop-bridge-host.js +67 -25
  32. package/lib/browser-electron/desktop-identity.js +21 -9
  33. package/lib/browser-electron/electron-provision.d.ts +1 -1
  34. package/lib/browser-electron/electron-provision.js +36 -13
  35. package/lib/browser-electron/entry.js +173 -67
  36. package/lib/browser-electron/ephemeral-profile.js +67 -26
  37. package/lib/browser-electron/history-store.js +2 -2
  38. package/lib/browser-electron/host-main.js +48 -38
  39. package/lib/browser-electron/http-body.d.ts +24 -0
  40. package/lib/browser-electron/http-body.js +33 -0
  41. package/lib/browser-electron/json-reply.d.ts +13 -1
  42. package/lib/browser-electron/json-reply.js +16 -2
  43. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  44. package/lib/browser-electron/maintenance-broker.js +114 -0
  45. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  46. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  47. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  48. package/lib/browser-electron/maintenance-route.js +75 -0
  49. package/lib/browser-electron/paths.d.ts +4 -0
  50. package/lib/browser-electron/paths.js +19 -0
  51. package/lib/browser-electron/process.d.ts +14 -0
  52. package/lib/browser-electron/process.js +24 -0
  53. package/lib/browser-electron/provider.d.ts +16 -9
  54. package/lib/browser-electron/provider.js +87 -18
  55. package/lib/browser-electron/remote-host.js +22 -20
  56. package/lib/browser-electron/runtime-route.d.ts +3 -5
  57. package/lib/browser-electron/runtime-status.d.ts +27 -13
  58. package/lib/browser-electron/runtime-status.js +28 -6
  59. package/lib/browser-electron/settings-route.d.ts +5 -18
  60. package/lib/browser-electron/settings-route.js +4 -14
  61. package/lib/browser-electron/settings-store.d.ts +28 -0
  62. package/lib/browser-electron/settings-store.js +32 -2
  63. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  64. package/lib/browser-electron/sidebar-only-host.js +192 -0
  65. package/lib/browser-electron/system-browser.d.ts +6 -11
  66. package/lib/browser-electron/system-browser.js +29 -24
  67. package/lib/browser-electron/timing.d.ts +8 -0
  68. package/lib/browser-electron/timing.js +13 -0
  69. package/lib/browser-electron/windows-system.d.ts +3 -0
  70. package/lib/browser-electron/windows-system.js +19 -0
  71. package/lib/tool-browser/index.js +1045 -7
  72. package/lib/tool-browser/page-probe.d.ts +86 -0
  73. package/lib/tool-browser/page-probe.js +460 -0
  74. package/package.json +5 -3
  75. package/scripts/run-tests.mjs +32 -0
  76. package/scripts/verify-preview-route.mjs +19 -1
  77. package/scripts/verify-runtime-status.mjs +14 -0
  78. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  79. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  80. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  81. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  82. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  83. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  84. package/src/browser/runtime.ts +11 -0
  85. package/src/browser/types.ts +19 -0
  86. package/src/browser-electron/authenticated-route.ts +56 -0
  87. package/src/browser-electron/automatic-maintenance.ts +414 -0
  88. package/src/browser-electron/bridge-auto.ts +158 -0
  89. package/src/browser-electron/bridge-connection.ts +2 -4
  90. package/src/browser-electron/bridge-endpoint.ts +8 -18
  91. package/src/browser-electron/bridge-install.ts +253 -0
  92. package/src/browser-electron/bridge-maintenance.ts +161 -0
  93. package/src/browser-electron/bridge-status.ts +76 -26
  94. package/src/browser-electron/desktop-bridge-host.ts +60 -26
  95. package/src/browser-electron/desktop-identity.ts +18 -9
  96. package/src/browser-electron/electron-provision.ts +35 -14
  97. package/src/browser-electron/entry.ts +152 -62
  98. package/src/browser-electron/ephemeral-profile.ts +65 -28
  99. package/src/browser-electron/history-store.ts +2 -2
  100. package/src/browser-electron/host-main.ts +40 -34
  101. package/src/browser-electron/http-body.ts +42 -0
  102. package/src/browser-electron/json-reply.ts +18 -3
  103. package/src/browser-electron/maintenance-broker.ts +142 -0
  104. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  105. package/src/browser-electron/maintenance-route.ts +64 -0
  106. package/src/browser-electron/paths.ts +21 -0
  107. package/src/browser-electron/process.ts +23 -0
  108. package/src/browser-electron/provider.ts +106 -22
  109. package/src/browser-electron/remote-host.ts +23 -23
  110. package/src/browser-electron/runtime-route.ts +3 -5
  111. package/src/browser-electron/runtime-status.ts +56 -19
  112. package/src/browser-electron/settings-route.ts +9 -32
  113. package/src/browser-electron/settings-store.ts +59 -3
  114. package/src/browser-electron/sidebar-only-host.ts +199 -0
  115. package/src/browser-electron/system-browser.ts +26 -23
  116. package/src/browser-electron/timing.ts +16 -0
  117. package/src/browser-electron/windows-system.ts +23 -0
  118. package/src/tool-browser/index.ts +995 -10
  119. package/src/tool-browser/page-probe.ts +474 -0
@@ -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. */
@@ -124,6 +124,34 @@ export interface BrowserSettings {
124
124
  /** Write cookies — importing login state (`dsh_browser_auth` restore). */
125
125
  readonly allowCredentialWrite: boolean
126
126
  }
127
+ /**
128
+ * Where a downloaded file goes after it lands on disk.
129
+ *
130
+ * An ATTRIBUTE of a download, not a new concept: an empty `tool` means the behaviour is exactly
131
+ * what it was before this existed. The user owns the field, can point it at any MCP tool that
132
+ * takes a path (Feishu drive, Baidu Netdisk), and can empty it again at any time.
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
+ }
145
+ readonly delivery: {
146
+ /** MCP tool that receives the saved file. Empty = save locally and stop there. */
147
+ readonly tool: string
148
+ /** Flat argument template; {path}, {name} and {size} are substituted into string values. */
149
+ readonly args: Readonly<Record<string, string>>
150
+ /** `keep-local` reports both outcomes; `stop` reports the handoff failure as the result. */
151
+ readonly onFail: 'keep-local' | 'stop'
152
+ /** Per-site override: page host → tool name. */
153
+ readonly sites: Readonly<Record<string, string>>
154
+ }
127
155
  }
128
156
 
129
157
  /** Defaults for every switch: the documented out-of-the-box behaviour. */
@@ -140,7 +168,11 @@ export const DEFAULT_SETTINGS: BrowserSettings = {
140
168
  // Off unless the host turns it on. A frame can show a CAPTCHA, an account name, or logged-in
141
169
  // content, so watching is an explicit decision rather than something a remote client can arrange.
142
170
  remoteView: { enabled: false },
171
+ bridge: { autoInstall: false },
143
172
  actions: { allowExecute: true, allowDownload: true, allowCredentialWrite: true },
173
+ // Local by default: the file lands in downloadDir and nothing leaves the machine until the user
174
+ // names a tool here. {file_path} is the argument name both Feishu's and Netdisk's upload tools use.
175
+ delivery: { tool: '', args: { file_path: '{path}' }, onFail: 'keep-local', sites: {} },
144
176
  }
145
177
 
146
178
  /**
@@ -149,7 +181,7 @@ export const DEFAULT_SETTINGS: BrowserSettings = {
149
181
  * @returns the settings file path.
150
182
  */
151
183
  export function settingsPath(): string {
152
- const home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
184
+ const home = dshHome()
153
185
  return join(home, 'dsh-builtin-browser-host', 'settings.json')
154
186
  }
155
187
 
@@ -299,6 +331,17 @@ export function resolveSettings(raw: unknown, warn?: (message: string) => void):
299
331
  const browser = section(source, 'browser')
300
332
  const actions = section(source, 'actions')
301
333
  const remoteView = section(source, 'remoteView')
334
+ // Read defensively: this section is hand-editable, and a bad value must fall back to "local only"
335
+ // rather than fail the whole document.
336
+ const deliverySection = (section(source, 'delivery') ?? {}) as { tool?: unknown; args?: unknown; onFail?: unknown; sites?: unknown }
337
+ const strings = (value: unknown, fallback: Record<string, string>): Record<string, string> => {
338
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return { ...fallback }
339
+ const out: Record<string, string> = {}
340
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
341
+ if (typeof entry === 'string') out[key] = entry
342
+ }
343
+ return Object.keys(out).length === 0 ? { ...fallback } : out
344
+ }
302
345
  // A section that is present but unreadable refuses its gates rather than defaulting them
303
346
  // open. The rest of a broken section keeps its defaults: refusing history or presentation
304
347
  // would punish the user for a bad file without protecting anything.
@@ -346,11 +389,24 @@ export function resolveSettings(raw: unknown, warn?: (message: string) => void):
346
389
  // Fail-closed, and stated separately from `gate`'s fallback so the intent is visible: an
347
390
  // unreadable or absent section means nobody watches. Unlike the other switches, whose defaults
348
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
+ },
349
397
  remoteView: {
350
398
  enabled: remoteView === undefined
351
399
  ? false
352
400
  : gate((remoteView as { enabled?: unknown }).enabled, false),
353
401
  },
402
+ delivery: {
403
+ tool: typeof deliverySection.tool === 'string' && /^[A-Za-z0-9_.-]+$/.test(deliverySection.tool)
404
+ ? deliverySection.tool
405
+ : '',
406
+ args: strings(deliverySection.args, DEFAULT_SETTINGS.delivery.args),
407
+ onFail: deliverySection.onFail === 'stop' ? 'stop' : 'keep-local',
408
+ sites: strings(deliverySection.sites, {}),
409
+ },
354
410
  }
355
411
  }
356
412
 
@@ -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
@@ -592,6 +584,7 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
592
584
  * and why a display-less host needs headless at all (issue #32).
593
585
  */
594
586
  private readonly headlessMode: HeadlessMode = 'auto',
587
+ private readonly isQuiet: () => boolean = () => false,
595
588
  ) {}
596
589
 
597
590
  /** Which product this host would drive (for diagnostics). */
@@ -710,10 +703,10 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
710
703
  * not a browser at all. What makes adoption safe HERE is that this runs BEFORE launching, on a
711
704
  * file that lives inside this plugin's own profile directory — only a browser started with this
712
705
  * `--user-data-dir` writes it — and the endpoint is then asked to identify itself.
713
- * @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.
714
707
  * @returns a connected client for the running browser, or undefined when there is none.
715
708
  */
716
- private async adoptRunningBrowser(why: string): Promise<CdpClient | undefined> {
709
+ private async adoptRunningBrowser(_why: string): Promise<CdpClient | undefined> {
717
710
  const portFile = join(this.profileDir, 'DevToolsActivePort')
718
711
  let port: number
719
712
  try {
@@ -743,7 +736,6 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
743
736
  }
744
737
  if (this.disposed) { client.close(); return undefined }
745
738
  this.client = client
746
- this.adoptedRunning = true
747
739
  return client
748
740
  } catch {
749
741
  // No endpoint, nothing listening, or not a browser: all of them mean "launch one".
@@ -765,6 +757,14 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
765
757
  // after launch (exit code 0)" that required killing seven processes by hand.
766
758
  const adopted = await this.adoptRunningBrowser('before launch')
767
759
  if (adopted !== undefined) return adopted
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
768
  const launch = resolveLaunchMode(this.headlessMode)
769
769
  const args = [
770
770
  '--remote-debugging-port=0',
@@ -881,8 +881,6 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
881
881
  return undefined
882
882
  }
883
883
  })()
884
- // Kept for the failure message and for the exit listener's diagnostics; no longer a judgement.
885
- const spawnedAt = Date.now()
886
884
  let child: ReturnType<typeof spawn>
887
885
  try {
888
886
  child = this.launcher(this.browser.path, args)
@@ -929,8 +927,8 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
929
927
  const after = statSync(portFile)
930
928
  const contents = readFileSync(portFile, 'utf8')
931
929
  // Unchanged since before the launch: this is the previous browser's file, whatever its
932
- // mtime says. Comparing against the snapshot rather than the spawn time is what keeps this
933
- // 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.
934
932
  if (portFileBefore !== undefined
935
933
  && after.mtimeMs <= portFileBefore.mtimeMs
936
934
  && contents === portFileBefore.contents) return undefined
@@ -1093,6 +1091,7 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1093
1091
  const ours = new Set(this.sessions.values())
1094
1092
  return (listed?.targetInfos ?? [])
1095
1093
  .filter(entry => entry.type === 'page' && typeof entry.targetId === 'string')
1094
+ .filter(entry => !/^edge:\/\/sync-confirmation-dialog(?:\/|$)/.test(entry.url ?? ''))
1096
1095
  .filter(entry => !ours.has(entry.targetId as string))
1097
1096
  .map(entry => ({
1098
1097
  id: entry.targetId as string,
@@ -1248,7 +1247,8 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1248
1247
  * two, and the order is honoured either way.
1249
1248
  * @param handle - the view to present.
1250
1249
  */
1251
- async presentView(handle: ElectronViewHandle): Promise<void> {
1250
+ async presentView(handle: ElectronViewHandle, _label?: string, options?: { readonly quiet?: boolean }): Promise<void> {
1251
+ if (options?.quiet === true || this.isQuiet()) return
1252
1252
  try {
1253
1253
  await handle.sendCommand('Page.bringToFront')
1254
1254
  } catch {
@@ -1456,7 +1456,10 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1456
1456
 
1457
1457
  /** Create one page, refusing to go on without an id. */
1458
1458
  private async createTarget(client: CdpClient): Promise<string> {
1459
- const created = await client.send('Target.createTarget', { url: 'about:blank' }) as { targetId?: string }
1459
+ const created = await client.send('Target.createTarget', {
1460
+ url: 'about:blank',
1461
+ ...this.isQuiet() ? { background: true } : {},
1462
+ }) as { targetId?: string }
1460
1463
  const targetId = created?.targetId
1461
1464
  if (typeof targetId !== 'string') throw new Error('dsh-builtin-browser: the browser did not create a page')
1462
1465
  return targetId
@@ -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
+ }