dsh-builtin-browser 1.0.1 → 1.0.4

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 (222) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/assets/browser-panel-locales.mjs +37 -5
  4. package/assets/browser-policy.d.mts +29 -0
  5. package/assets/browser-policy.mjs +40 -0
  6. package/desktop-bridge/desktop-discovery.d.mts +1 -1
  7. package/desktop-bridge/desktop-discovery.mjs +59 -9
  8. package/desktop-bridge/desktop-identity.json +12 -0
  9. package/desktop-bridge/install.mjs +14 -7
  10. package/desktop-bridge/plugin-browser-bridge.js +19 -7
  11. package/docs/acceptance-2026-11-27.md +67 -0
  12. package/docs/architecture.md +1 -1
  13. package/docs/development.md +33 -4
  14. package/docs/dsh-0.2.3-host-patch-task.md +34 -0
  15. package/docs/hardcoding-audit.md +28 -8
  16. package/docs/known-issues.md +26 -0
  17. package/docs/limitations.md +6 -2
  18. package/docs/tool-reference.md +1 -1
  19. package/docs/v1.1.0-bu-data-batching-task.md +66 -0
  20. package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
  21. package/dsh-host-patch/README.md +4 -0
  22. package/dsh-host-patch/apply.mjs +61 -13
  23. package/dsh-host-patch/rc3-revision9.json.gz +0 -0
  24. package/dsh-host-patch/rc5-revision9.json.gz +0 -0
  25. package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
  26. package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
  27. package/dsh-host-patch/tauri-revision1.json +39 -0
  28. package/dsh-host-patch/tauri.json +43 -0
  29. package/dsh-host-patch/v023-alpha2.json +153 -0
  30. package/lib/browser/anti-bot.js +215 -0
  31. package/lib/browser/deep-dom.js +39 -0
  32. package/lib/browser/runtime.js +15 -0
  33. package/lib/browser/takeover-target.js +13 -6
  34. package/lib/browser/types.js +30 -1
  35. package/lib/browser-electron/authenticated-route.js +16 -2
  36. package/lib/browser-electron/automatic-maintenance.js +16 -10
  37. package/lib/browser-electron/bridge-connection.js +3 -8
  38. package/lib/browser-electron/bridge-install.js +2 -1
  39. package/lib/browser-electron/bridge-status.js +55 -26
  40. package/lib/browser-electron/desktop-bridge-host.js +7 -6
  41. package/lib/browser-electron/desktop-identity.js +28 -5
  42. package/lib/browser-electron/desktop-shell.js +64 -0
  43. package/lib/browser-electron/electron-provision.js +105 -18
  44. package/lib/browser-electron/entry.js +129 -44
  45. package/lib/browser-electron/extension-browser.js +4 -4
  46. package/lib/browser-electron/foreground-watch.js +134 -0
  47. package/lib/browser-electron/guest-cookie-jar.js +13 -13
  48. package/lib/browser-electron/guest-route.js +181 -32
  49. package/lib/browser-electron/guest-runtime.js +61 -10
  50. package/lib/browser-electron/guest-storage.js +2 -2
  51. package/lib/browser-electron/history-store.js +1 -5
  52. package/lib/browser-electron/host-main.js +8 -4
  53. package/lib/browser-electron/host-patch-maintenance.js +14 -8
  54. package/lib/browser-electron/maintenance-route.js +2 -1
  55. package/lib/browser-electron/missing-system-browser.js +5 -9
  56. package/lib/browser-electron/preferred-browser.js +7 -3
  57. package/lib/browser-electron/preview-route.js +9 -13
  58. package/lib/browser-electron/process-ownership.js +1 -1
  59. package/lib/browser-electron/profile-command.js +2 -1
  60. package/lib/browser-electron/profile-extension.js +5 -0
  61. package/lib/browser-electron/profile-lease.js +152 -47
  62. package/lib/browser-electron/provider-core.js +527 -0
  63. package/lib/browser-electron/provider-interaction.js +963 -0
  64. package/lib/browser-electron/provider-media.js +518 -0
  65. package/lib/browser-electron/provider-navigation.js +301 -0
  66. package/lib/browser-electron/provider-observation.js +623 -0
  67. package/lib/browser-electron/provider-tabs.js +372 -0
  68. package/lib/browser-electron/provider.js +150 -3301
  69. package/lib/browser-electron/reference-route.js +9 -18
  70. package/lib/browser-electron/remote-host.js +79 -34
  71. package/lib/browser-electron/runtime-status.js +56 -6
  72. package/lib/browser-electron/settings-store.js +3 -6
  73. package/lib/browser-electron/sidebar-only-host.js +1 -1
  74. package/lib/browser-electron/system-browser.js +539 -172
  75. package/lib/browser-electron/tauri-host.js +208 -0
  76. package/lib/browser-electron/virtual-cursor.js +23 -13
  77. package/lib/browser-reference/service.js +22 -4
  78. package/lib/browser-reference/web-sources.js +1 -1
  79. package/lib/client.js +43409 -0
  80. package/lib/compat/host-features.js +75 -0
  81. package/lib/reference-source.js +1 -1
  82. package/lib/reference-text.js +23 -1
  83. package/lib/takeover-protocol.js +1 -1
  84. package/lib/tool-browser/block-recovery.js +69 -0
  85. package/lib/tool-browser/code-tool.js +170 -19
  86. package/lib/tool-browser/code-worker.js +115 -20
  87. package/lib/tool-browser/errors.js +34 -0
  88. package/lib/tool-browser/index.js +66 -3593
  89. package/lib/tool-browser/page-probe.js +227 -28
  90. package/lib/tool-browser/panel-page.js +2 -1
  91. package/lib/tool-browser/probe-client.js +157 -0
  92. package/lib/tool-browser/screenshot-annotations.js +108 -0
  93. package/lib/tool-browser/state.js +337 -0
  94. package/lib/tool-browser/takeover.js +1 -1
  95. package/lib/tool-browser/tools-debug.js +862 -0
  96. package/lib/tool-browser/tools-interaction.js +993 -0
  97. package/lib/tool-browser/tools-navigation.js +807 -0
  98. package/lib/tool-browser/tools-observation.js +461 -0
  99. package/lib/tool-browser/tools-reference.js +293 -0
  100. package/lib/web-guest.js +1 -0
  101. package/package.json +16 -36
  102. package/scripts/build-client.mjs +305 -0
  103. package/scripts/build.mjs +15 -12
  104. package/scripts/fix-exports.mjs +6 -16
  105. package/scripts/install-electron.mjs +55 -5
  106. package/scripts/pack.mjs +99 -0
  107. package/scripts/publish-manifest.mjs +56 -0
  108. package/scripts/verify-exports.mjs +26 -15
  109. package/skills/dsh-builtin-browser/SKILL.md +27 -2
  110. package/skills/dsh-builtin-browser/references/batch.md +15 -0
  111. package/src/browser/anti-bot.ts +251 -0
  112. package/src/browser/deep-dom.ts +40 -0
  113. package/src/browser/runtime.ts +18 -0
  114. package/src/browser/takeover-target.ts +16 -7
  115. package/src/browser/types.ts +56 -3
  116. package/src/browser-electron/authenticated-route.ts +29 -4
  117. package/src/browser-electron/automatic-maintenance.ts +23 -13
  118. package/src/browser-electron/bridge-connection.ts +11 -10
  119. package/src/browser-electron/bridge-install.ts +2 -1
  120. package/src/browser-electron/bridge-status.ts +61 -22
  121. package/src/browser-electron/desktop-bridge-host.ts +9 -7
  122. package/src/browser-electron/desktop-identity.ts +38 -5
  123. package/src/browser-electron/desktop-shell.ts +100 -0
  124. package/src/browser-electron/electron-provision.ts +104 -18
  125. package/src/browser-electron/entry.ts +1378 -1299
  126. package/src/browser-electron/extension-browser.ts +11 -4
  127. package/src/browser-electron/foreground-watch.ts +142 -0
  128. package/src/browser-electron/guest-cookie-jar.ts +3 -2
  129. package/src/browser-electron/guest-route.ts +180 -32
  130. package/src/browser-electron/guest-runtime.ts +61 -10
  131. package/src/browser-electron/guest-storage.ts +5 -2
  132. package/src/browser-electron/history-store.ts +3 -6
  133. package/src/browser-electron/host-main.ts +8 -4
  134. package/src/browser-electron/host-patch-maintenance.ts +18 -9
  135. package/src/browser-electron/maintenance-route.ts +2 -1
  136. package/src/browser-electron/missing-system-browser.ts +11 -10
  137. package/src/browser-electron/preferred-browser.ts +13 -3
  138. package/src/browser-electron/preview-route.ts +9 -12
  139. package/src/browser-electron/process-ownership.ts +9 -3
  140. package/src/browser-electron/profile-command.ts +2 -1
  141. package/src/browser-electron/profile-extension.ts +5 -0
  142. package/src/browser-electron/profile-lease.ts +131 -35
  143. package/src/browser-electron/provider-core.ts +1107 -0
  144. package/src/browser-electron/provider-interaction.ts +1034 -0
  145. package/src/browser-electron/provider-media.ts +589 -0
  146. package/src/browser-electron/provider-navigation.ts +323 -0
  147. package/src/browser-electron/provider-observation.ts +664 -0
  148. package/src/browser-electron/provider-tabs.ts +372 -0
  149. package/src/browser-electron/provider.ts +158 -4063
  150. package/src/browser-electron/reference-route.ts +598 -608
  151. package/src/browser-electron/remote-host.ts +118 -42
  152. package/src/browser-electron/runtime-status.ts +80 -13
  153. package/src/browser-electron/settings-store.ts +10 -6
  154. package/src/browser-electron/sidebar-only-host.ts +4 -2
  155. package/src/browser-electron/system-browser.ts +537 -184
  156. package/src/browser-electron/tauri-host.ts +194 -0
  157. package/src/browser-electron/virtual-cursor.ts +24 -14
  158. package/src/browser-reference/service.ts +38 -7
  159. package/src/browser-reference/web-sources.ts +4 -1
  160. package/src/client/apply-guard.ts +22 -0
  161. package/src/client/browser/BrowserController.ts +3 -3
  162. package/src/client/browser/IframeImpl.ts +182 -176
  163. package/src/client/browser/frame-history.ts +125 -0
  164. package/src/client/browser/frame-state.ts +27 -0
  165. package/src/client/browser/web-reference-source.ts +5 -1
  166. package/src/client/definition.tsx +36 -30
  167. package/src/client/electron/ElectronWebViewImpl.ts +20 -13
  168. package/src/client/electron/ElectronWebviewPresentation.ts +4 -2
  169. package/src/client/electron/NativeChildPresentation.ts +11 -3
  170. package/src/client/electron/NativeViewPage.ts +19 -5
  171. package/src/client/index.ts +333 -293
  172. package/src/client/locales.ts +9 -6
  173. package/src/client/reference/client/plugin.ts +21 -2
  174. package/src/client/reference/client/production/ReferenceCapsules.tsx +3 -3
  175. package/src/client/reference/client/production/assembly.ts +4 -28
  176. package/src/client/reference/client/production/availability.ts +0 -2
  177. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  178. package/src/client/reference/client/production/draft-adapter.ts +4 -0
  179. package/src/client/reference/client/production/http-transport.ts +0 -5
  180. package/src/client/reference/client/production/production-submission.ts +50 -290
  181. package/src/client/reference/client/production/protocol.ts +7 -4
  182. package/src/client/reference/client/production/runtime.ts +41 -86
  183. package/src/client/reference/client/production/source-marker.ts +49 -13
  184. package/src/client/reference/client/production/user-text-rule.ts +10 -1
  185. package/src/client/reference/client/reveal.ts +3 -1
  186. package/src/client/reference/client/session-schedule.ts +36 -0
  187. package/src/client/settings/index.ts +8 -0
  188. package/src/client/settings/mount-guard.ts +31 -0
  189. package/src/client/settings/panel.ts +163 -52
  190. package/src/client/startpage/controller.ts +3 -6
  191. package/src/client/view/BrowserBody.tsx +2 -1
  192. package/src/client/view/IframePresentation.ts +37 -16
  193. package/src/client/view/StartPage.tsx +2 -1
  194. package/src/compat/host-features.ts +92 -0
  195. package/src/reference-source.ts +1 -1
  196. package/src/reference-text.ts +23 -1
  197. package/src/takeover-protocol.ts +11 -2
  198. package/src/tool-browser/block-recovery.ts +85 -0
  199. package/src/tool-browser/code-tool.ts +173 -19
  200. package/src/tool-browser/code-worker.ts +101 -15
  201. package/src/tool-browser/errors.ts +40 -0
  202. package/src/tool-browser/index.ts +66 -3534
  203. package/src/tool-browser/page-probe.ts +229 -28
  204. package/src/tool-browser/panel-page.ts +3 -1
  205. package/src/tool-browser/probe-client.ts +183 -0
  206. package/src/tool-browser/screenshot-annotations.ts +131 -0
  207. package/src/tool-browser/state.ts +375 -0
  208. package/src/tool-browser/takeover.ts +3 -2
  209. package/src/tool-browser/tools-debug.ts +806 -0
  210. package/src/tool-browser/tools-interaction.ts +956 -0
  211. package/src/tool-browser/tools-navigation.ts +786 -0
  212. package/src/tool-browser/tools-observation.ts +474 -0
  213. package/src/tool-browser/tools-reference.ts +294 -0
  214. package/src/web-guest.ts +35 -34
  215. package/dist/client.cjs +0 -43167
  216. package/dist/client.d.cts +0 -516
  217. package/dist/client.d.mts +0 -516
  218. package/dist/index.cjs +0 -92
  219. package/dist/index.d.mts +0 -2960
  220. package/dist/index.mjs +0 -24
  221. package/lib/browser-reference/submission-receipts.js +0 -139
  222. package/src/browser-reference/submission-receipts.ts +0 -122
@@ -1,5 +1,5 @@
1
1
  import { PATH_NAMES, INSTALL_LOCATIONS } from '../../assets/browser-products.mjs'
2
- import { cdpVersionUrl, CDP_DEFAULT_ATTACH_PORT, CDP_ATTACH_PROBE_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
2
+ import { CARRIER_CALL_TIMEOUT_MS, cdpVersionUrl, CDP_DEFAULT_ATTACH_PORT, CDP_ATTACH_PROBE_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
3
3
  /**
4
4
  * Drive the browser the user already has (Chrome / Edge / any Chromium) instead of
5
5
  * the Electron we ship — the same approach Codex Browser Use takes.
@@ -31,6 +31,7 @@ import { readFileSync, rmSync, statSync } from 'node:fs'
31
31
  import { existsSync } from 'node:fs'
32
32
  import { join } from 'node:path'
33
33
  import { acquireProfileLease, type ProfileLease } from './profile-lease.ts'
34
+ import { watchForeground, type ForegroundEvent, type ForegroundWatch, type ForegroundWatcher } from './foreground-watch.ts'
34
35
  import { BrowserProcessOwnership, type ProcessOwnershipOptions } from './process-ownership.ts'
35
36
  // Type-only: settings-store imports BrowserChannel from here, so a value import would be a cycle.
36
37
  // `hasDisplay` lives here instead of there for the same reason — it is a runtime function.
@@ -104,12 +105,12 @@ const defaultLauncher: BrowserLauncher = (path, args) =>
104
105
  spawn(path, [...args], { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: false })
105
106
  import { spawn, type ChildProcess } from 'node:child_process'
106
107
  import { randomUUID } from 'node:crypto'
107
- import type { ElectronBrowserViewHost, ElectronViewHandle } from './provider.ts'
108
+ import type { CommandOptions, ElectronBrowserViewHost, ElectronViewHandle, QuietRevealOptions } from './provider.ts'
108
109
  import type { CarrierPage } from '../browser/types.ts'
109
110
  import { readTabHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId, type BrowserSessionWireId, type BrowserTabWireId } from '../browser/handles.ts'
110
111
 
111
112
  /** Which browser the user asked for. */
112
- export type BrowserChannel = 'bundled' | 'chrome' | 'edge' | 'auto' | 'sidebar'
113
+ export type BrowserChannel = 'bundled' | 'electron' | 'chrome' | 'edge' | 'auto' | 'sidebar'
113
114
 
114
115
  /** A resolved browser installation. */
115
116
  export interface DetectedBrowser {
@@ -238,7 +239,7 @@ function findOnPath(names: readonly string[], env: NodeJS.ProcessEnv, platform:
238
239
  * environment override, then PATH, then the platform's conventional install
239
240
  * locations. PATH comes before the fixed paths because it is what actually reflects
240
241
  * how the browser was installed.
241
- * @param channel - the configured choice; `bundled` never resolves to a system browser.
242
+ * @param channel - the configured choice; `bundled` / `electron` never resolve to a system browser.
242
243
  * @param env - environment lookup, injected so tests need no real machine.
243
244
  * @param platform - the platform to use conventions for; injected for the same reason.
244
245
  * @returns the detected browser, or undefined when the choice is unavailable.
@@ -248,7 +249,7 @@ export function detectBrowser(
248
249
  env: NodeJS.ProcessEnv = process.env,
249
250
  platform: NodeJS.Platform = process.platform,
250
251
  ): DetectedBrowser | undefined {
251
- if (channel === 'bundled') return undefined
252
+ if (channel === 'bundled' || channel === 'electron' || channel === 'sidebar') return undefined
252
253
  const order: DetectedBrowser['kind'][] = channel === 'auto' ? ['chrome', 'edge', 'brave'] : [channel as DetectedBrowser['kind']]
253
254
  for (const kind of order) {
254
255
  const fromEnv = (kind === 'chrome' ? env.DSH_BROWSER_CHROME_PATH : kind === 'edge' ? env.DSH_BROWSER_EDGE_PATH : undefined)
@@ -285,11 +286,39 @@ export function searchSummary(
285
286
  return [...onPath, ...located]
286
287
  }
287
288
 
289
+ /**
290
+ * Where quiet mode first parks its window: past ordinary displays while staying under Win32's
291
+ * 16-bit signed coordinate ceiling (32767 physical pixels) even at 125%-300% DPI scaling. Any
292
+ * ultra-wide multi-monitor overlap is pushed further out by {@link clearDisplays}.
293
+ */
294
+ const QUIET_PARK = { left: 10000, top: 0, width: 1280, height: 800 } as const
295
+ const QUIET_PARK_GAP = 200
296
+ const QUIET_PARK_LEFT_TOLERANCE = 2000
297
+ const QUIET_PARK_TOP_TOLERANCE = 256
298
+ const QUIET_REVEAL_INSET = 40
299
+ const QUIET_FRONT_SLACK = 16
300
+
301
+ interface QuietFront { readonly client: CdpClient; readonly session: string; readonly targetId: string }
302
+
303
+ interface WindowGeometry { readonly sl: number; readonly st: number; readonly sw: number; readonly sh: number; readonly x: number; readonly y: number; readonly ow: number; readonly oh: number; readonly hidden: boolean }
304
+
305
+ /** The display the page's window is on (or nearest to), the window's outer rectangle, and whether the page is hidden. */
306
+ async function windowGeometry(client: CdpClient, sessionId: string): Promise<WindowGeometry | undefined> {
307
+ const out = await client.send('Runtime.evaluate', {
308
+ expression: '({ sl: screen.availLeft, st: screen.availTop, sw: screen.availWidth, sh: screen.availHeight, x: screenX, y: screenY, ow: outerWidth, oh: outerHeight, hidden: document.visibilityState === "hidden" })',
309
+ returnByValue: true,
310
+ }, sessionId) as { result?: { value?: WindowGeometry } } | undefined
311
+ const g = out?.result?.value
312
+ return g !== undefined && [g.sl, g.st, g.sw, g.sh, g.x, g.y, g.ow, g.oh].every(n => typeof n === 'number') ? g : undefined
313
+ }
314
+
288
315
  /** One CDP connection to a browser-level WebSocket, with flattened sessions. */
289
316
  class CdpClient {
290
317
  private nextId = 1
291
318
  private readonly pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>()
292
319
  private readonly ready: Promise<void>
320
+ readonly destroyedTargets = new Set<string>()
321
+ headless = false
293
322
 
294
323
  /**
295
324
  * @param url - the browser's `webSocketDebuggerUrl`.
@@ -330,7 +359,7 @@ class CdpClient {
330
359
  return this.socket.readyState === WebSocket.OPEN
331
360
  }
332
361
 
333
- async whenReady(deadline = Date.now() + 30_000): Promise<void> {
362
+ async whenReady(deadline = Date.now() + CARRIER_CALL_TIMEOUT_MS): Promise<void> {
334
363
  const timeoutMs = Math.max(1, deadline - Date.now())
335
364
  let timer: NodeJS.Timeout | undefined
336
365
  try {
@@ -360,7 +389,7 @@ class CdpClient {
360
389
  * @param sessionId - the flattened session to target, when this is a page command.
361
390
  * @returns the CDP result.
362
391
  */
363
- async send(method: string, params?: Record<string, unknown>, sessionId?: string, timeoutMs = 30_000): Promise<unknown> {
392
+ async send(method: string, params?: Record<string, unknown>, sessionId?: string, timeoutMs = CARRIER_CALL_TIMEOUT_MS): Promise<unknown> {
364
393
  // Fail fast and say why. Waiting out the timeout on a closed socket produced
365
394
  // only "timed out", which reads as a slow page and hides the real cause.
366
395
  if (!this.isAlive()) {
@@ -384,10 +413,20 @@ class CdpClient {
384
413
  }
385
414
 
386
415
  /** Route one CDP message to its waiter. */
416
+ private readonly eventListeners = new Set<(method: string, params: unknown) => void>()
417
+
418
+ /** Receive the browser's own CDP events (those without a command id). */
419
+ onEvent(listener: (method: string, params: unknown) => void): void { this.eventListeners.add(listener) }
420
+
387
421
  private onMessage(raw: string): void {
388
- let message: { id?: number; result?: unknown; error?: { message?: string } }
422
+ let message: { id?: number; method?: string; params?: unknown; result?: unknown; error?: { message?: string } }
389
423
  try { message = JSON.parse(raw) } catch { return }
390
- if (message.id === undefined) return
424
+ if (message.id === undefined) {
425
+ const targetId = message.method === 'Target.targetDestroyed' ? (message.params as { targetId?: unknown } | undefined)?.targetId : undefined
426
+ if (typeof targetId === 'string') this.destroyedTargets.add(targetId)
427
+ if (typeof message.method === 'string') for (const listener of this.eventListeners) listener(message.method, message.params)
428
+ return
429
+ }
391
430
  const entry = this.pending.get(message.id)
392
431
  if (entry === undefined) return
393
432
  this.pending.delete(message.id)
@@ -428,6 +467,9 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
428
467
  * spawned when a view is actually needed.
429
468
  */
430
469
  private client: CdpClient | undefined
470
+ /** Whether the running browser was launched headless, so its pages get a plain Chrome user agent. */
471
+ /** The browser's user agent without the `HeadlessChrome` token, read once per connection. */
472
+ private plainUserAgent: Promise<string | undefined> | undefined
431
473
  /**
432
474
  * Set when a command went unanswered rather than being refused.
433
475
  *
@@ -438,7 +480,9 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
438
480
  */
439
481
  private clientSuspect = false
440
482
  private child: ChildProcess | undefined
483
+ private launchParked = false
441
484
  private profileLease: ProfileLease | undefined
485
+ private profileLeasing: Promise<ProfileLease> | undefined
442
486
  private starting: Promise<CdpClient> | undefined
443
487
  private lastLaunchError: string | undefined
444
488
  private launchDiagnostic: SystemBrowserLaunchDiagnostic | undefined
@@ -455,36 +499,37 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
455
499
  private readonly ownedClients = new WeakMap<CdpClient, ChildProcess>()
456
500
  private readonly ownedChildren = new WeakSet<ChildProcess>()
457
501
  private readonly createdTargets = new WeakMap<CdpClient, Map<string, BrowserTabWireId>>()
458
-
459
- /**
460
- * @param browser - the detected installation to launch on first use.
461
- * @param profileDir - a plugin-owned directory; the user's own profile is never touched.
462
- * @param extraArgs - additional Chromium switches.
463
- * @param ephemeralDir - a directory to delete on release, when the user has turned
464
- * persistence off so no login state outlives the session.
465
- * @param launcher - how to start the browser, for tests.
466
- *
467
- * Recovery after the browser dies was untestable without this: the suite spawns a stub
468
- * with Chromium's arguments, and a stub that is not a browser rejects them and exits, so
469
- * no CDP endpoint ever appears and no session is ever created. Verified by mutation —
470
- * removing every sessions.clear() left the recovery tests green. A launcher lets a test
471
- * provide something that actually speaks CDP, so the state those tests describe exists.
472
- */
502
+ private readonly browser: DetectedBrowser
503
+ private readonly profileDir: string
504
+ private readonly extraArgs: readonly string[]
505
+ private readonly ephemeralDir?: string
506
+ private readonly launcher: BrowserLauncher
507
+ private readonly headlessMode: HeadlessMode
508
+ private readonly isQuiet: () => boolean
509
+ private readonly profileError?: string
473
510
  constructor(
474
- private readonly browser: DetectedBrowser,
475
- private readonly profileDir: string,
476
- private readonly extraArgs: readonly string[] = [],
477
- private readonly ephemeralDir?: string,
478
- private readonly launcher: BrowserLauncher = defaultLauncher,
511
+ browser: DetectedBrowser,
512
+ profileDir: string,
513
+ extraArgs: readonly string[] = [],
514
+ ephemeralDir?: string,
515
+ launcher: BrowserLauncher = defaultLauncher,
479
516
  /**
480
517
  * Whether this launch should get a window. See {@link resolveLaunchMode} for how `auto` decides
481
518
  * and why a display-less host needs headless at all (issue #32).
482
519
  */
483
- private readonly headlessMode: HeadlessMode = 'auto',
484
- private readonly isQuiet: () => boolean = () => false,
485
- private readonly profileError?: string,
520
+ headlessMode: HeadlessMode = 'auto',
521
+ isQuiet: () => boolean = () => false,
522
+ profileError?: string,
486
523
  ownership: ProcessOwnershipOptions = { managed: false },
487
524
  ) {
525
+ this.browser = browser
526
+ this.profileDir = profileDir
527
+ this.extraArgs = extraArgs
528
+ this.ephemeralDir = ephemeralDir
529
+ this.launcher = launcher
530
+ this.headlessMode = headlessMode
531
+ this.isQuiet = isQuiet
532
+ this.profileError = profileError
488
533
  this.ownership = new BrowserProcessOwnership(browser.path, profileDir, ownership)
489
534
  }
490
535
 
@@ -520,6 +565,27 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
520
565
  }
521
566
  }
522
567
 
568
+ connectedView(id: string): boolean {
569
+ const view = this.views.get(id), target = view === undefined ? undefined : this.sessions.get(view.session)
570
+ return view !== undefined && target !== undefined && view.client === this.client && !view.client.headless
571
+ && !view.client.destroyedTargets.has(target) && this.connectionStatus().connected
572
+ }
573
+
574
+ /**
575
+ * Whether this view is live on the current connection but sits inside a headless browser, so there is
576
+ * no window a person could be handed. Mirrors {@link connectedView}, which requires the opposite.
577
+ *
578
+ * Takeover has to tell these apart instead of falling back to the sidebar: a headless session that
579
+ * silently produced a sidebar tab left the person acting on an unrelated page (issue #103).
580
+ * @param id - the view to classify.
581
+ * @returns true when the view is alive and headless.
582
+ */
583
+ headlessView(id: string): boolean {
584
+ const view = this.views.get(id), target = view === undefined ? undefined : this.sessions.get(view.session)
585
+ return view !== undefined && target !== undefined && view.client === this.client && view.client.headless
586
+ && !view.client.destroyedTargets.has(target) && this.connectionStatus().connected
587
+ }
588
+
523
589
  /** Which product this host would drive (for diagnostics). */
524
590
  get kind(): DetectedBrowser['kind'] {
525
591
  return this.browser.kind
@@ -575,6 +641,11 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
575
641
  private forgetBrowserState(): void {
576
642
  this.views.clear()
577
643
  this.sessions.clear()
644
+ this.quietParked.clear()
645
+ this.parkedTargets.clear()
646
+ this.quietFront = undefined
647
+ this.quietRevealed.clear()
648
+ this.stopForeground()
578
649
  }
579
650
 
580
651
  private async ensureClient(): Promise<CdpClient> {
@@ -635,7 +706,7 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
635
706
  * @param _why - a short phrase for the log, naming which attempt this is.
636
707
  * @returns a connected client for the running browser, or undefined when there is none.
637
708
  */
638
- private async adoptRunningBrowser(_why: string, explicitPort?: number, deadline = Date.now() + 30_000): Promise<CdpClient | undefined> {
709
+ private async adoptRunningBrowser(_why: string, explicitPort?: number, deadline = Date.now() + CARRIER_CALL_TIMEOUT_MS): Promise<CdpClient | undefined> {
639
710
  const portFile = join(this.profileDir, 'DevToolsActivePort')
640
711
  let port: number
641
712
  if (typeof explicitPort === 'number' && explicitPort > 0) {
@@ -665,10 +736,14 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
665
736
  // mistaken for a browser that answers.
666
737
  const info = await client.send('Browser.getVersion', {}, undefined, Math.max(1, deadline - Date.now())) as { product?: string }
667
738
  if (!isBrowserProduct(info?.product) || info.product !== version.Browser) throw new Error('browser did not acknowledge its identity')
739
+ client.headless = /^HeadlessChrome\//u.test(info.product ?? '')
668
740
  if (this.disposed) { client.close(); return undefined }
669
741
  await client.send('Target.setDiscoverTargets', { discover: true }, undefined, Math.max(1, deadline - Date.now()))
670
742
  if (this.disposed || Date.now() >= deadline) { client.close(); return undefined }
743
+ this.launchParked = false
671
744
  this.client = client
745
+ this.placeOpenedWindows(client)
746
+ this.plainUserAgent = undefined
672
747
  return client
673
748
  } catch (error) {
674
749
  client?.close()
@@ -690,8 +765,12 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
690
765
  * @returns the connected client.
691
766
  */
692
767
  private async start(): Promise<CdpClient> {
693
- const deadline = Date.now() + 30_000
694
- this.profileLease ??= acquireProfileLease(this.profileDir)
768
+ const deadline = Date.now() + CARRIER_CALL_TIMEOUT_MS
769
+ if (this.profileLease === undefined) {
770
+ const lease = await (this.profileLeasing ??= acquireProfileLease(this.profileDir).finally(() => { this.profileLeasing = undefined }))
771
+ if (this.disposed) { await lease.release(); throw new Error('dsh-builtin-browser: the browser host was disposed while launching') }
772
+ this.profileLease = lease
773
+ }
695
774
  // Before spawning anything: is a browser for THIS profile already running? A DSH restart
696
775
  // leaves one behind, and launching into it is the failure reported as "exited immediately
697
776
  // after launch (exit code 0)" that required killing seven processes by hand.
@@ -726,6 +805,15 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
726
805
  '--disable-features=Translate,MediaRouter',
727
806
  '--disable-session-crashed-bubble',
728
807
  '--hide-crash-restore-bubble',
808
+ // The remote-debugging port this plugin drives makes Chrome set `navigator.webdriver` on every
809
+ // page, windowed or not, which bot walls read as "a script, not a person" — even while the
810
+ // person is the one browsing. Chrome's own switch turns that marker off; nothing else changes.
811
+ '--disable-blink-features=AutomationControlled',
812
+ // Quiet mode parks its first window off-screen; without these Windows occlusion tracking marks
813
+ // it hidden, pausing rAF, clamping timers and stalling screenshots. Passed always: quiet is a live setting.
814
+ '--disable-backgrounding-occluded-windows',
815
+ '--disable-renderer-backgrounding',
816
+ '--disable-background-timer-throttling',
729
817
  // Headless only where there is nothing to draw on. `--headless=new` rather than the legacy
730
818
  // flag: the new mode behaves like a windowed browser, which matters because every command
731
819
  // here was written and measured against one — including CDP input, which Chromium silently
@@ -746,6 +834,10 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
746
834
  // normally through `Target.createTarget`.
747
835
  '--no-startup-window',
748
836
  ]
837
+ // Chromium shows a new window at its default spot and only then applies Target.createTarget's
838
+ // left/top, so a quiet first window flashed on-screen; the launch position is applied before show.
839
+ this.launchParked = !launch.headless && this.isQuiet()
840
+ if (this.launchParked) args.push(`--window-position=${QUIET_PARK.left},${QUIET_PARK.top}`, `--window-size=${QUIET_PARK.width},${QUIET_PARK.height}`)
749
841
  if (launch.headless) {
750
842
  process.stderr.write(`[dsh-browser] launching headless (${launch.why}); `
751
843
  + 'the browser has no window but every tool works the same\n')
@@ -962,7 +1054,10 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
962
1054
  } catch { /* An unidentified endpoint is borrowed, never owned. */ }
963
1055
  }
964
1056
  if (this.disposed) { client.close(); break }
1057
+ client.headless = launch.headless
965
1058
  this.client = client
1059
+ this.placeOpenedWindows(client)
1060
+ this.plainUserAgent = undefined
966
1061
  return client
967
1062
  }
968
1063
  } catch (error) {
@@ -1015,18 +1110,6 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1015
1110
  return !this.disposed
1016
1111
  }
1017
1112
 
1018
- /**
1019
- * Every page the browser currently holds, including ones this plugin did not create.
1020
- *
1021
- * Chrome and Edge own their own page creation. A click on a link that opens a new page — or any
1022
- * `window.open` — produces a page the provider never asked for, and nothing reports it back.
1023
- * Those pages are real: they hold memory and stay until something closes them. Measured on a real
1024
- * window: four pages present while `dsh_browser_list_tabs` reported one.
1025
- *
1026
- * Discovery is enabled before the connection is published, so
1027
- * `Target.getTargets` also lists pages that existed before this client connected.
1028
- * @returns the browser's pages, or an empty list when it cannot answer.
1029
- */
1030
1113
  /**
1031
1114
  * Every page the browser holds that THIS HOST did not open.
1032
1115
  *
@@ -1054,9 +1137,10 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1054
1137
  // check the reference-bar pump called listPages on every tick, whose
1055
1138
  // ensureClient() launched Edge on its own within seconds of the plugin
1056
1139
  // loading — measured with no open/navigate call at all.
1057
- if (options.requireRunning === true && !this.started) return []
1140
+ const liveClient = this.client
1141
+ if (options.requireRunning === true && (this.disposed || liveClient === undefined || !liveClient.isAlive())) return []
1058
1142
  try {
1059
- const client = await this.ensureClient()
1143
+ const client = options.requireRunning === true && liveClient !== undefined ? liveClient : await this.ensureClient()
1060
1144
  const listed = await client.send('Target.getTargets', {}) as {
1061
1145
  targetInfos?: Array<{ targetId?: string; type?: string; url?: string; title?: string }>
1062
1146
  }
@@ -1105,43 +1189,50 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1105
1189
  // This is the real browser, not Electron: CDP's JPEG encoder works here, so the
1106
1190
  // provider may pass format and quality through instead of falling back to PNG.
1107
1191
  supportsCdpJpeg: true,
1108
- sendCommand: async (method: string, params?: Record<string, unknown>) => {
1192
+ sendCommand: async (method: string, params?: Record<string, unknown>, options?: CommandOptions) => {
1109
1193
  if (method === 'Browser.close' || method === 'Target.closeTarget' || method === 'Page.close') {
1110
1194
  throw new Error('dsh-builtin-browser: use explicit tab close; browser-wide and unowned-tab closes are not allowed')
1111
1195
  }
1112
- // A command that never answered is the only signal that a client has wedged — the
1113
- // socket can stay OPEN while nothing comes back, which is the form the reporter saw with
1114
- // a live, healthy-looking Edge. Dropping the client here means the next call starts a new
1115
- // browser rather than hanging again, and the error names the cause instead of a timeout.
1116
- const client = await this.ensureClient()
1196
+ // Background probes (reference bar pump, readiness checks) pass initialize: false and
1197
+ // must never relaunch a killed browser or recreate a tab the user closed (issue #105).
1198
+ const initialize = options?.initialize !== false
1199
+ let client: CdpClient
1200
+ if (initialize) {
1201
+ client = await this.ensureClient()
1202
+ } else {
1203
+ const liveClient = this.client
1204
+ if (this.disposed || liveClient === undefined || !liveClient.isAlive()) {
1205
+ throw new Error('dsh-builtin-browser: browser is not running')
1206
+ }
1207
+ client = liveClient
1208
+ }
1117
1209
  const cachedView = this.views.get(viewId)
1210
+ if (cachedView !== undefined && cachedView.client === client) {
1211
+ const cachedTarget = this.sessions.get(cachedView.session)
1212
+ if (cachedTarget !== undefined && client.destroyedTargets.has(cachedTarget)) {
1213
+ this.views.delete(viewId)
1214
+ this.sessions.delete(cachedView.session)
1215
+ if (!initialize) throw new Error('dsh-builtin-browser: target was closed')
1216
+ }
1217
+ }
1118
1218
  // A session belongs to the browser that issued it. Clearing the cache whenever a client is
1119
1219
  // dropped covers the ordinary case, but not this one: another call can be inside
1120
1220
  // ensureSession() holding the OLD client while this one discards it and clears, and that
1121
1221
  // call's `views.set` then lands afterwards — re-adding an entry naming a browser that is
1122
1222
  // gone. The identity check is what refuses it, and it costs a comparison rather than the
1123
1223
  // round trip that validating every cached session against the browser would cost.
1124
- //
1125
- // (Not covered by the tests: the race needs two interleaved commands, and the suite's fake
1126
- // browser is synchronous enough that they never interleave. Verified by mutation instead —
1127
- // removing this check alone leaves every case green, which is why the comment says what it
1128
- // protects rather than claiming a case proves it.)
1129
- const session = cachedView !== undefined && cachedView.client === client
1130
- ? cachedView.session
1224
+ const liveView = this.views.get(viewId)
1225
+ if (!initialize && (liveView === undefined || liveView.client !== client)) {
1226
+ throw new Error('dsh-builtin-browser: view has no live page')
1227
+ }
1228
+ const session = liveView !== undefined && liveView.client === client
1229
+ ? liveView.session
1131
1230
  : await this.ensureSession(viewId)
1132
1231
  /**
1133
1232
  * Send one page command, rebuilding the attach once if the browser no longer knows the
1134
- * session.
1135
- *
1136
- * "Session with given id not found" means the session id is stale, and the causes differ:
1137
- * a replaced client (handled where the client is dropped), a target the browser destroyed,
1138
- * or a detach the page performed on itself. What they share is that the id is worthless and
1139
- * the VIEW is fine, so the right answer is one fresh attach — not an error to the caller and
1140
- * not a new page. Measured while solving a sudoku on a canvas page: after a tab switch every
1141
- * command failed with this text and nothing in the plugin ever recovered it.
1142
- *
1143
- * Retried exactly once: a failure that survives a fresh attach is not a stale id, and
1144
- * repeating it would turn an error into a loop.
1233
+ * session. Re-attaches to the original live target instead of spawning a blank page,
1234
+ * never rebuilds a target that was destroyed or closed by the user, and never initializes
1235
+ * a new page when `initialize: false` (issue #105).
1145
1236
  */
1146
1237
  const sendWithAttach = async (target: string): Promise<Record<string, unknown>> => {
1147
1238
  try {
@@ -1150,10 +1241,35 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1150
1241
  } catch (error) {
1151
1242
  const message = error instanceof Error ? error.message : String(error)
1152
1243
  if (!/Session with given id not found|No session with given id/i.test(message)) throw error
1153
- // Drop the dead attach so `ensureSession` builds a new one instead of returning the same id.
1154
- const stale = this.views.get(viewId)
1155
- if (stale !== undefined) this.views.delete(viewId)
1244
+ // If another concurrent call already started or finished reattaching this view, join it
1245
+ // instead of falling through to ensureSession() and spawning an orphan about:blank tab.
1246
+ const inFlight = this.sessionBuilding.get(viewId)
1247
+ if (inFlight !== undefined) {
1248
+ if (!initialize) throw error
1249
+ const joined = await inFlight
1250
+ const retried = await client.send(method, params, joined)
1251
+ return (retried ?? {}) as Record<string, unknown>
1252
+ }
1253
+ const current = this.views.get(viewId)
1254
+ if (current !== undefined && current.client === client && current.session !== target) {
1255
+ const retried = await client.send(method, params, current.session)
1256
+ return (retried ?? {}) as Record<string, unknown>
1257
+ }
1258
+ // Drop only the stale mapping for this exact client+session.
1259
+ if (current !== undefined && current.client === client && current.session === target) {
1260
+ this.views.delete(viewId)
1261
+ }
1262
+ const deadTarget = this.sessions.get(target)
1156
1263
  this.sessions.delete(target)
1264
+ if (!initialize) throw error
1265
+ if (deadTarget !== undefined) {
1266
+ if (client.destroyedTargets.has(deadTarget)) throw error
1267
+ // Register the reattach transaction synchronously before any await so concurrent
1268
+ // callers hitting the same stale session join it instead of spawning about:blank.
1269
+ const rebuilt = await this.reattachTarget(client, viewId, deadTarget)
1270
+ const retried = await client.send(method, params, rebuilt)
1271
+ return (retried ?? {}) as Record<string, unknown>
1272
+ }
1157
1273
  const rebuilt = await this.ensureSession(viewId)
1158
1274
  const retried = await client.send(method, params, rebuilt)
1159
1275
  return (retried ?? {}) as Record<string, unknown>
@@ -1162,30 +1278,10 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1162
1278
  try {
1163
1279
  return await sendWithAttach(session)
1164
1280
  } catch (error) {
1165
- // A CDP protocol error means the browser ANSWERED and refused this one command, so the
1166
- // connection is healthy and must be kept. Deciding by the error TEXT misfires both
1167
- // ways: the inner timeout rejects with "… timed out", so a slow but healthy page read
1168
- // as a dead browser, the client was dropped, and the next call's start() killed the
1169
- // running child — the human's tabs and half-filled forms gone, which is worse than the
1170
- // bug that change was fixing. The browser's own free text is interpolated into
1171
- // protocol errors too, so any message containing those words misfired the same way.
1172
- // Unanswered versus refused. 'timed out' is the inner client's own budget expiring,
1173
- // which says the page was slow, not that the browser died — so it only marks the client
1174
- // for a probe. Being wrong here costs a two-second check; being wrong about the
1175
- // browser being dead cost the user their open tabs.
1176
1281
  if (error instanceof Error && /timed out/.test(error.message)) this.clientSuspect = true
1177
1282
  if (!client.isAlive()) {
1178
- // Only THIS call's client. Under concurrency the field may already hold a
1179
- // connection another call just published, and closing that would kill a healthy one.
1180
1283
  if (this.client === client) {
1181
1284
  this.client = undefined
1182
- // This is the third of the three paths that discard a client, and it was the one
1183
- // that did not retire what the client had issued. A view holding a session id
1184
- // from the dead browser kept handing it to the replacement, which had never heard
1185
- // of it: every page command then failed with "Session with given id not found"
1186
- // and no later call could clear it, because the cached session was returned
1187
- // unconditionally. Gated on the same identity check as the field itself, so a
1188
- // concurrent call that just published a healthy client does not lose its maps.
1189
1285
  this.forgetBrowserState()
1190
1286
  }
1191
1287
  client.close()
@@ -1210,26 +1306,23 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1210
1306
  }
1211
1307
 
1212
1308
  /** Nothing to show: the browser owns its own windows. */
1213
- showView(): void {}
1309
+ showView(handle: ElectronViewHandle, _label?: string, options?: { readonly quiet?: boolean; readonly select?: boolean; readonly user?: boolean }): void {
1310
+ if (options?.user === true && (options.quiet === true || this.isQuiet())) void this.revealQuietWindow(handle, { select: true })
1311
+ }
1214
1312
 
1215
1313
  /**
1216
1314
  * Bring the target's page to the front, then report success.
1217
1315
  *
1218
- * The comment on `focus` below used to say this was impossible — that raising the page needs
1219
- * `Page.bringToFront` on a target session, which is a view-level concern the host cannot
1220
- * reach. The handle this method is handed IS that view, and it can send commands, so the
1221
- * capability was here all along; it just was not used. Without it `presentView` was an empty
1222
- * async method, so the provider's whole presentation barrier — the one that stops
1223
- * `Input.*` from being silently dropped for a view with no display surface, and reports
1224
- * `BROWSER_VIEW_NOT_PRESENTED` when it cannot present — never ran on this carrier.
1225
- *
1226
1316
  * A failure is swallowed rather than propagated: a real Chrome window that refuses to come
1227
1317
  * forward is not a reason to refuse the click that follows. The barrier exists to order the
1228
1318
  * two, and the order is honoured either way.
1229
1319
  * @param handle - the view to present.
1230
1320
  */
1231
- async presentView(handle: ElectronViewHandle, _label?: string, options?: { readonly quiet?: boolean }): Promise<void> {
1232
- if (options?.quiet === true || this.isQuiet()) return
1321
+ async presentView(handle: ElectronViewHandle, _label?: string, options?: { readonly quiet?: boolean; readonly select?: boolean; readonly user?: boolean }): Promise<void> {
1322
+ if (options?.quiet === true || this.isQuiet()) {
1323
+ if (options?.user === true) await this.revealQuietWindow(handle, { select: true })
1324
+ return
1325
+ }
1233
1326
  try {
1234
1327
  await handle.sendCommand('Page.bringToFront')
1235
1328
  } catch {
@@ -1238,19 +1331,8 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1238
1331
  }
1239
1332
  }
1240
1333
 
1241
-
1242
-
1243
1334
  /**
1244
1335
  * Best effort at bringing the browser's window forward.
1245
- *
1246
- * The browser is a separate application, so there is no view to raise. What this can
1247
- * actually do is ask its process to continue from a stopped state — which is a no-op on
1248
- * Windows, where `SIGCONT` is not a supported signal and the call throws. It is kept
1249
- * because it costs nothing and does help on POSIX (a process stopped with SIGSTOP
1250
- * resumes), but it must not be read as a promise that the window comes to the front;
1251
- * importantly, it does NOT raise a window that is merely behind another. Raising the
1252
- * page properly would need `Page.bringToFront` on a specific target session, which is a
1253
- * view-level concern and not available to the host.
1254
1336
  */
1255
1337
  async focus(): Promise<void> {
1256
1338
  if (this.child && await this.ownership.verify(this.child)) {
@@ -1258,16 +1340,11 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1258
1340
  }
1259
1341
  }
1260
1342
 
1261
-
1262
-
1263
1343
  /**
1264
1344
  * Close the browser we launched, if we ever launched one.
1265
- *
1266
- * The user's own windows belong to a different process and are never touched. A
1267
- * host whose browser was never started (the common case when nobody used the
1268
- * browser) simply tears down its bookkeeping.
1269
1345
  */
1270
1346
  dispose(): void {
1347
+ this.stopForeground()
1271
1348
  if (this.disposed) return
1272
1349
  this.disposed = true
1273
1350
  const client = this.client
@@ -1286,20 +1363,11 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1286
1363
  finally { client.close() }
1287
1364
  }
1288
1365
  void disconnect()
1289
- // Both the browser we launched and anything that ignored an earlier kill. They hold this
1290
- // profile, so leaving them running means the next launch contends with a browser nobody owns.
1291
1366
  const doomed = [this.child, ...this.stubborn.splice(0)].filter(
1292
1367
  (entry): entry is ChildProcess => entry !== undefined,
1293
1368
  )
1294
1369
  this.child = undefined
1295
1370
  for (const dying of doomed) {
1296
- /**
1297
- * A bounded reprieve, then the kill we used to do immediately.
1298
- *
1299
- * The timer is unref'd so it never holds the process open: a DSH shutdown that is itself
1300
- * ending does not wait for this, and the browser — having been asked to close — generally
1301
- * gets there on its own. If it does not, the kill still lands while the process lives.
1302
- */
1303
1371
  const force = (): void => { void this.stopChild(dying) }
1304
1372
  const timer = setTimeout(force, CLOSE_GRACE_MS)
1305
1373
  timer.unref?.()
@@ -1317,7 +1385,6 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1317
1385
  this.profileLease = undefined
1318
1386
  })().catch(error => process.stderr.write(`[dsh-browser] profile release failed: ${String(error)}\n`))
1319
1387
  }
1320
- // Saved processes retain the profile until their exit events arrive.
1321
1388
  const live = doomed.filter(child => child.exitCode === null && child.signalCode === null)
1322
1389
  if (live.length > 0) {
1323
1390
  const remaining = new Set(live)
@@ -1332,18 +1399,47 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1332
1399
  }
1333
1400
  }
1334
1401
 
1402
+ /**
1403
+ * Verify an existing target is still alive and re-attach to it, sharing one in-flight transaction
1404
+ * across concurrent callers for the same view and never creating a replacement blank page.
1405
+ */
1406
+ private async reattachTarget(client: CdpClient, viewId: string, targetId: string): Promise<string> {
1407
+ const existing = this.views.get(viewId)
1408
+ if (existing !== undefined && existing.client === client) return existing.session
1409
+ const inFlight = this.sessionBuilding.get(viewId)
1410
+ if (inFlight !== undefined) return await inFlight
1411
+ const building = (async (): Promise<string> => {
1412
+ if (client.destroyedTargets.has(targetId)) {
1413
+ throw new Error('dsh-builtin-browser: CDP error: Session with given id not found.')
1414
+ }
1415
+ const alive = await client.send('Target.getTargets', {})
1416
+ .then(listed => Array.isArray((listed as { targetInfos?: unknown }).targetInfos)
1417
+ ? (listed as { targetInfos: Array<{ targetId?: unknown }> }).targetInfos.some(entry => entry.targetId === targetId)
1418
+ : true)
1419
+ .catch(() => true)
1420
+ if (!alive) {
1421
+ throw new Error('dsh-builtin-browser: CDP error: Session with given id not found.')
1422
+ }
1423
+ const attached = await client.send('Target.attachToTarget', { targetId, flatten: true }) as { sessionId?: string }
1424
+ const sessionId = attached?.sessionId
1425
+ if (typeof sessionId !== 'string') {
1426
+ throw new Error(`dsh-builtin-browser: could not reattach to existing page ${targetId}`)
1427
+ }
1428
+ await this.presentAsChrome(client, sessionId)
1429
+ this.sessions.set(sessionId, targetId)
1430
+ this.views.set(viewId, { session: sessionId, client })
1431
+ return sessionId
1432
+ })().finally(() => {
1433
+ this.sessionBuilding.delete(viewId)
1434
+ })
1435
+ this.sessionBuilding.set(viewId, building)
1436
+ return await building
1437
+ }
1438
+
1335
1439
  /**
1336
1440
  * The flattened session for a view, creating its page on first use.
1337
- *
1338
- * No cache check here: the only caller has already established that the cached session does
1339
- * not belong to the client it is about to use. Re-checking would mean either a round trip or
1340
- * a second copy of that rule.
1341
1441
  */
1342
1442
  private async ensureSession(viewId: string): Promise<string> {
1343
- // One target per view, even when two commands arrive together. The two CDP round trips
1344
- // below are awaits, so without this a second caller entering during the first's flight saw
1345
- // no session in `views` and created its own target — leaving an orphan page that nothing
1346
- // closes, because only the last id survives in the map.
1347
1443
  const inFlight = this.sessionBuilding.get(viewId)
1348
1444
  if (inFlight !== undefined) return await inFlight
1349
1445
  const building = this.buildSession(viewId).finally(() => {
@@ -1356,28 +1452,20 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1356
1452
  /** Create and attach the target for one view. Serialised by {@link ensureSession}. */
1357
1453
  private async buildSession(viewId: string): Promise<string> {
1358
1454
  const client = await this.ensureClient()
1359
- // Different views can initialise concurrently. Selecting an unclaimed page and attaching
1360
- // it must be one transaction, including when the page is created by a preceding view.
1361
1455
  const previous = this.targetBuilds.get(client) ?? Promise.resolve()
1362
1456
  let release!: () => void
1363
1457
  const building = new Promise<void>(resolve => { release = resolve })
1364
1458
  this.targetBuilds.set(client, building)
1365
1459
  await previous
1366
1460
  try {
1367
- // Adopt a blank page the browser opened on its own before creating another one.
1368
- //
1369
- // Chrome starts with more than one page when handed a URL on top of its own start page, so
1370
- // creating a target here discarded the original and left it behind as a tab that is not in
1371
- // the plugin's tab model — invisible to `dsh_browser_list_tabs`, and therefore unclosable
1372
- // through the tools. Taking the blank instead makes the page the browser already opened the
1373
- // one the caller gets.
1374
1461
  const adopted = await this.adoptBlankTarget(client)
1375
1462
  const targetId = adopted ?? await this.createTarget(client, viewId)
1376
1463
  const attached = await client.send('Target.attachToTarget', { targetId, flatten: true }) as { sessionId?: string }
1377
1464
  const sessionId = attached?.sessionId
1378
1465
  if (typeof sessionId !== 'string') throw new Error('dsh-builtin-browser: the browser did not attach to the new page')
1379
1466
  if (adopted !== undefined) this.rememberTarget(client, targetId, viewId)
1380
- // The session id is what page commands ride; the target id is what closes it.
1467
+ await this.clearDisplays(client, sessionId, targetId)
1468
+ await this.presentAsChrome(client, sessionId)
1381
1469
  this.sessions.set(sessionId, targetId)
1382
1470
  this.views.set(viewId, { session: sessionId, client })
1383
1471
  return sessionId
@@ -1387,21 +1475,15 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1387
1475
  }
1388
1476
  }
1389
1477
 
1390
- /**
1391
- * Take over a page the browser already has, so a person's own tab becomes one this plugin drives.
1392
- *
1393
- * Reported as a defect: opening a window by hand, navigating it, and then asking a tool to read it
1394
- * produced a SECOND page, because the only tab the provider knew about was one it created itself.
1395
- * The page the human was looking at was listed by `dsh_browser_list_tabs` (under `page:`) and
1396
- * could be closed, but not read or driven — the opposite of what "the page you are looking at"
1397
- * means.
1398
- *
1399
- * Attaching is all it takes: a CDP session is not exclusive, so the browser's own tab becomes a
1400
- * target this plugin has a session on. The page is not moved, reloaded or focused, and its
1401
- * existing session (logins, scroll position, form state) is untouched.
1402
- * @param targetId - the carrier's page id, which for this carrier IS the CDP target id.
1403
- * @returns a handle for that page, in the same shape {@link createView} returns.
1404
- */
1478
+ private async presentAsChrome(client: CdpClient, sessionId: string): Promise<void> {
1479
+ this.plainUserAgent ??= (client.send('Browser.getVersion', {}) as Promise<{ userAgent?: string }>)
1480
+ .then(info => typeof info?.userAgent === 'string' && info.userAgent.includes('HeadlessChrome/')
1481
+ ? info.userAgent.replace(/HeadlessChrome\//u, 'Chrome/') : undefined, () => undefined)
1482
+ const userAgent = await this.plainUserAgent
1483
+ if (userAgent === undefined) return
1484
+ await client.send('Emulation.setUserAgentOverride', { userAgent }, sessionId).catch(() => {})
1485
+ }
1486
+
1405
1487
  async adoptPage(identity: BrowserTabWireId, scope = sessionWireId(readTabHandle(identity))): Promise<ElectronViewHandle> {
1406
1488
  const tab = resolveTabHandle(resolveSessionHandle(scope), identity).tab
1407
1489
  if (!tab.startsWith('page:')) throw new Error('dsh-builtin-browser: invalid carrier page handle')
@@ -1413,21 +1495,11 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1413
1495
  if (typeof sessionId !== 'string') {
1414
1496
  throw new Error(`dsh-builtin-browser: could not attach to the existing page ${targetId}`)
1415
1497
  }
1416
- // Point the view `createView` just made at the page that already exists, instead of the one it
1417
- // would otherwise build on first use.
1418
1498
  this.sessions.set(sessionId, targetId)
1419
1499
  this.views.set(handle.id, { session: sessionId, client })
1420
1500
  return handle
1421
1501
  }
1422
1502
 
1423
- /**
1424
- * Take an unclaimed blank page, if the browser has one to spare.
1425
- *
1426
- * "Unclaimed" is what matters: a blank page the plugin is already driving belongs to a view, and
1427
- * handing the same target to a second view would make two views share one page.
1428
- * @param client - the connected browser.
1429
- * @returns the target id to reuse, or undefined when a new page has to be created.
1430
- */
1431
1503
  private async adoptBlankTarget(client: CdpClient): Promise<string | undefined> {
1432
1504
  const listed = await client.send('Target.getTargets', {}) as {
1433
1505
  targetInfos?: Array<{ targetId?: string; type?: string; url?: string }>
@@ -1444,17 +1516,298 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1444
1516
  }
1445
1517
 
1446
1518
  /** Create one page, refusing to go on without an id. */
1447
- private async createTarget(client: CdpClient, viewId: string): Promise<string> {
1448
- const created = await client.send('Target.createTarget', {
1449
- url: 'about:blank',
1450
- ...this.isQuiet() ? { background: true } : {},
1451
- }) as { targetId?: string }
1452
- const targetId = created?.targetId
1519
+ private createTarget(client: CdpClient, viewId: string): Promise<string> {
1520
+ const run = this.createTargetNow(client, viewId)
1521
+ this.creating = run.then(() => undefined, () => undefined)
1522
+ return run
1523
+ }
1524
+
1525
+ private creating: Promise<void> = Promise.resolve()
1526
+
1527
+ /**
1528
+ * A quiet launch makes Chromium open every new window off-screen, so a window a person or a page
1529
+ * opens (Ctrl+N, a popup) is brought on-screen, unless it is a popup of a window still parked.
1530
+ */
1531
+ private placeOpenedWindows(client: CdpClient): void {
1532
+ client.onEvent((method, params) => {
1533
+ if (method !== 'Target.targetCreated' || !this.launchParked) return
1534
+ const info = (params as { targetInfo?: { targetId?: unknown; type?: unknown; openerId?: unknown } } | undefined)?.targetInfo
1535
+ if (info?.type === 'page' && typeof info.targetId === 'string') void this.placeOpenedWindow(client, info.targetId, info.openerId)
1536
+ })
1537
+ }
1538
+
1539
+ private async placeOpenedWindow(client: CdpClient, targetId: string, openerId: unknown): Promise<void> {
1540
+ try {
1541
+ for (let pending = this.creating; ; pending = this.creating) {
1542
+ await pending
1543
+ if (pending === this.creating) break
1544
+ }
1545
+ if (this.createdTargets.get(client)?.has(targetId) === true) return
1546
+ const windowOf = async (id: string) => (await client.send('Browser.getWindowForTarget', { targetId: id }) as { windowId?: unknown; bounds?: { left?: unknown; top?: unknown } } | undefined)
1547
+ const found = await windowOf(targetId)
1548
+ const left = found?.bounds?.left
1549
+ const top = found?.bounds?.top
1550
+ // Allow tolerance for DPI rounding or Windows clamping when matching the parked launch spot.
1551
+ const nearParked = typeof left === 'number' && left >= QUIET_PARK.left - QUIET_PARK_LEFT_TOLERANCE
1552
+ && (typeof top !== 'number' || Math.abs(top - QUIET_PARK.top) <= QUIET_PARK_TOP_TOLERANCE)
1553
+ if (typeof found?.windowId !== 'number' || !nearParked || this.quietParked.has(found.windowId)) return
1554
+ if (typeof openerId === 'string' && openerId !== '') {
1555
+ const opener = await windowOf(openerId).catch(() => undefined)
1556
+ if (typeof opener?.windowId === 'number' && this.quietParked.has(opener.windowId)) {
1557
+ this.quietParked.add(found.windowId)
1558
+ this.watchQuietFocus(client)
1559
+ return
1560
+ }
1561
+ }
1562
+ await this.moveOnScreen(client, found.windowId)
1563
+ } catch {
1564
+ // A window that closed or a browser that went away needs no placing.
1565
+ }
1566
+ }
1567
+
1568
+ private async createTargetNow(client: CdpClient, viewId: string): Promise<string> {
1569
+ const quiet = this.isQuiet()
1570
+ const { created, parked } = quiet
1571
+ ? await this.createQuietTarget(client)
1572
+ : { created: await this.createPlainTarget(client), parked: false }
1573
+ const targetId = (created as { targetId?: string } | undefined)?.targetId
1453
1574
  if (typeof targetId !== 'string' || targetId === '') throw new Error('dsh-builtin-browser: the browser did not create a page')
1454
1575
  this.rememberTarget(client, targetId, viewId)
1576
+ if (parked) await this.parkQuietWindow(client, targetId)
1455
1577
  return targetId
1456
1578
  }
1457
1579
 
1580
+ /**
1581
+ * `background` only keeps the user's tab active inside an existing window; the first page after
1582
+ * `--no-startup-window` opens a new one. `focus: false` keeps keyboard focus where it was, and the
1583
+ * window is created off-screen in the normal state: a minimized window is hidden to the page, so
1584
+ * rAF stops and rAF-driven pages never render. A Chromium that rejects the bounds gets the page
1585
+ * without them and the window is moved off-screen right after. A tab joining an existing window
1586
+ * leaves that window where the user has it.
1587
+ */
1588
+ private async createQuietTarget(client: CdpClient): Promise<{ readonly created: unknown; readonly parked: boolean }> {
1589
+ const params = { url: 'about:blank', background: true, focus: false }
1590
+ const listed = await client.send('Target.getTargets') as { targetInfos?: Array<{ type?: string }> } | undefined
1591
+ if (listed?.targetInfos?.some(entry => entry.type === 'page') === true) {
1592
+ return { created: await client.send('Target.createTarget', params), parked: false }
1593
+ }
1594
+ try {
1595
+ return { created: await client.send('Target.createTarget', { ...params, newWindow: true, ...QUIET_PARK }), parked: true }
1596
+ } catch {
1597
+ return { created: await client.send('Target.createTarget', params), parked: true }
1598
+ }
1599
+ }
1600
+
1601
+ /** A browser launched while quiet opens new windows off-screen, so a first window after quiet is turned off is placed on-screen. */
1602
+ private async createPlainTarget(client: CdpClient): Promise<unknown> {
1603
+ const params = { url: 'about:blank' }
1604
+ if (!this.launchParked) return client.send('Target.createTarget', params)
1605
+ const listed = await client.send('Target.getTargets') as { targetInfos?: Array<{ type?: string }> } | undefined
1606
+ if (listed?.targetInfos?.some(entry => entry.type === 'page') === true) return client.send('Target.createTarget', params)
1607
+ try {
1608
+ return await client.send('Target.createTarget', { ...params, newWindow: true, left: QUIET_REVEAL_INSET, top: QUIET_REVEAL_INSET })
1609
+ } catch {
1610
+ const created = await client.send('Target.createTarget', params)
1611
+ const targetId = (created as { targetId?: string } | undefined)?.targetId
1612
+ if (typeof targetId === 'string' && targetId !== '') {
1613
+ const found = await client.send('Browser.getWindowForTarget', { targetId }).catch(() => undefined) as { windowId?: unknown } | undefined
1614
+ if (typeof found?.windowId === 'number') await this.moveOnScreen(client, found.windowId).catch(() => undefined)
1615
+ }
1616
+ return created
1617
+ }
1618
+ }
1619
+
1620
+ /** Windows quiet mode parked off-screen; a window quiet mode has revealed is not listed. */
1621
+ private readonly quietParked = new Set<number>()
1622
+ /** Pages whose window was just parked, until their session checks the window is clear of every display. */
1623
+ private readonly parkedTargets = new Map<string, number>()
1624
+
1625
+ private async parkQuietWindow(client: CdpClient, targetId: string): Promise<void> {
1626
+ try {
1627
+ const found = await client.send('Browser.getWindowForTarget', { targetId }) as { windowId?: unknown; bounds?: { left?: unknown; top?: unknown } } | undefined
1628
+ if (typeof found?.windowId !== 'number') return
1629
+ if (found.bounds?.left !== QUIET_PARK.left || found.bounds?.top !== QUIET_PARK.top) {
1630
+ await client.send('Browser.setWindowBounds', { windowId: found.windowId, bounds: { ...QUIET_PARK } })
1631
+ }
1632
+ this.quietParked.add(found.windowId)
1633
+ this.parkedTargets.set(targetId, found.windowId)
1634
+ this.watchQuietFocus(client)
1635
+ } catch {
1636
+ // Without its id the window cannot be moved or revealed later, so it stays where Chromium put it.
1637
+ }
1638
+ }
1639
+
1640
+ /**
1641
+ * Move a parked window past any display it still overlaps. The page's `screen` is the display
1642
+ * the window overlaps most (or the nearest one), so stepping past it until no display claims the
1643
+ * window clears the union of all displays, wherever the provisional position landed.
1644
+ */
1645
+ private async clearDisplays(client: CdpClient, sessionId: string, targetId: string): Promise<void> {
1646
+ const windowId = this.parkedTargets.get(targetId)
1647
+ if (windowId === undefined) return
1648
+ this.parkedTargets.delete(targetId)
1649
+ try {
1650
+ for (let step = 0; step < 8; step++) {
1651
+ const g = await windowGeometry(client, sessionId)
1652
+ if (g === undefined) return
1653
+ const overlaps = g.x < g.sl + g.sw && g.x + g.ow > g.sl && g.y < g.st + g.sh && g.y + g.oh > g.st
1654
+ if (!overlaps) return
1655
+ await client.send('Browser.setWindowBounds', { windowId, bounds: { left: g.sl + g.sw + QUIET_PARK_GAP, top: g.st } })
1656
+ }
1657
+ } catch {
1658
+ // A page that cannot report its geometry keeps the provisional position.
1659
+ }
1660
+ }
1661
+
1662
+ private foreground: ForegroundWatch | undefined
1663
+ private foregroundStarting = false
1664
+ private foregroundFailed = false
1665
+ /** A takeover page hidden behind another tab, brought to the front once the person activates its revealed window. */
1666
+ private quietFront: QuietFront | undefined
1667
+ /** Windows quiet mode parked and has since put on-screen. */
1668
+ private readonly quietRevealed = new Set<number>()
1669
+ /** The real watcher exists on Windows only; tests replace it. */
1670
+ watchForeground: ForegroundWatcher = watchForeground
1671
+
1672
+ private quietWatched(): boolean { return this.quietParked.size > 0 || this.quietFront !== undefined }
1673
+
1674
+ /**
1675
+ * A CDP click focuses the page, not the window, but Chrome activates its window for a tab the click
1676
+ * opens; the watcher gives that foreground back. Our Chrome in the foreground off every display
1677
+ * otherwise means a person activated the parked window from the taskbar or Alt-Tab. Asked of the OS,
1678
+ * it works with no view attached (after a reset).
1679
+ */
1680
+ private watchQuietFocus(client: CdpClient): void {
1681
+ if (this.foreground !== undefined || this.foregroundStarting) return
1682
+ this.foregroundStarting = true
1683
+ void (async () => {
1684
+ try {
1685
+ const info = await client.send('SystemInfo.getProcessInfo', {}, undefined, 1000) as { processInfo?: Array<{ type?: string; id?: number }> } | undefined
1686
+ const pid = info?.processInfo?.find(entry => entry.type === 'browser')?.id
1687
+ if (typeof pid !== 'number' || this.disposed || !this.quietWatched()) return this.sendQuietFront()
1688
+ const watch = this.watchForeground(event => { if (event.pid === pid) void this.onForeground(client, event) }, reason => {
1689
+ if (!this.foregroundFailed) {
1690
+ this.foregroundFailed = true
1691
+ console.warn(`[dsh-browser] quiet window: cannot watch the foreground window (${reason}); the panel and takeovers still bring it on-screen`)
1692
+ }
1693
+ if (this.foreground === watch) this.foreground = undefined
1694
+ this.sendQuietFront()
1695
+ }, pid)
1696
+ this.foreground = watch
1697
+ if (watch === undefined) this.sendQuietFront()
1698
+ } catch {
1699
+ // Without the browser's process id, the panel and a takeover still reveal the window.
1700
+ this.sendQuietFront()
1701
+ } finally {
1702
+ this.foregroundStarting = false
1703
+ }
1704
+ })()
1705
+ }
1706
+
1707
+ private async onForeground(client: CdpClient, event: ForegroundEvent): Promise<void> {
1708
+ if (event.yielded === true) return
1709
+ if (event.offscreen) {
1710
+ for (const windowId of [...this.quietParked]) {
1711
+ this.quietParked.delete(windowId)
1712
+ this.quietRevealed.add(windowId)
1713
+ await this.moveOnScreen(client, windowId, await this.sessionInWindow(client, windowId)).catch(() => undefined)
1714
+ }
1715
+ } else if (this.quietFront !== undefined && await this.isFrontWindow(this.quietFront, event)) {
1716
+ const front = this.quietFront
1717
+ this.quietFront = undefined
1718
+ await front.client.send('Page.bringToFront', {}, front.session).catch(() => undefined)
1719
+ }
1720
+ if (!this.quietWatched()) this.stopForeground()
1721
+ }
1722
+
1723
+ /** A page attached in the window, to measure the display it lands on. */
1724
+ private async sessionInWindow(client: CdpClient, windowId: number): Promise<string | undefined> {
1725
+ for (const view of [...this.views.values()]) {
1726
+ const targetId = this.sessions.get(view.session)
1727
+ if (targetId === undefined || view.client !== client) continue
1728
+ const found = await client.send('Browser.getWindowForTarget', { targetId }).catch(() => undefined) as { windowId?: unknown } | undefined
1729
+ if (found?.windowId === windowId) return view.session
1730
+ }
1731
+ return undefined
1732
+ }
1733
+
1734
+ /** The watcher names the process, not the window: only the takeover's own window, where it now is, counts. */
1735
+ private async isFrontWindow(front: QuietFront, event: ForegroundEvent): Promise<boolean> {
1736
+ if (event.left === undefined || event.top === undefined) return false
1737
+ try {
1738
+ const found = await front.client.send('Browser.getWindowForTarget', { targetId: front.targetId }) as { bounds?: { left?: unknown; top?: unknown } } | undefined
1739
+ const left = found?.bounds?.left
1740
+ const top = found?.bounds?.top
1741
+ return typeof left === 'number' && typeof top === 'number' &&
1742
+ Math.abs(left - event.left) <= QUIET_FRONT_SLACK && Math.abs(top - event.top) <= QUIET_FRONT_SLACK
1743
+ } catch {
1744
+ return false
1745
+ }
1746
+ }
1747
+
1748
+ /** Nothing can tell when the person activates the window, so a waiting hidden page comes to the front now. */
1749
+ private sendQuietFront(): void {
1750
+ const front = this.quietFront
1751
+ this.quietFront = undefined
1752
+ if (front !== undefined) void front.client.send('Page.bringToFront', {}, front.session).catch(() => undefined)
1753
+ }
1754
+
1755
+ private stopForeground(): void {
1756
+ this.foreground?.stop()
1757
+ this.foreground = undefined
1758
+ }
1759
+
1760
+ /** Move a window onto the primary display (it holds the origin), sized to fit when its page can say so, without activating it. */
1761
+ private async moveOnScreen(client: CdpClient, windowId: number, session?: string): Promise<WindowGeometry | undefined> {
1762
+ await client.send('Browser.setWindowBounds', { windowId, bounds: { left: QUIET_REVEAL_INSET, top: QUIET_REVEAL_INSET } })
1763
+ const g = session === undefined ? undefined : await windowGeometry(client, session)
1764
+ if (g !== undefined && (g.ow > g.sw - QUIET_REVEAL_INSET || g.oh > g.sh - QUIET_REVEAL_INSET)) {
1765
+ await client.send('Browser.setWindowBounds', { windowId, bounds: {
1766
+ width: Math.min(g.ow, g.sw - QUIET_REVEAL_INSET), height: Math.min(g.oh, g.sh - QUIET_REVEAL_INSET) } })
1767
+ }
1768
+ return g
1769
+ }
1770
+
1771
+ /**
1772
+ * Move a window quiet mode parked onto the primary display. Quiet tabs open in the background, so
1773
+ * the window may be showing an earlier tab: a person's own selection brings the page to the front.
1774
+ * `Page.bringToFront` activates the window, so for a takeover of a hidden page it waits until the
1775
+ * person activates the revealed window (where nothing watches the foreground, it is sent at once).
1776
+ * From then on the window is the person's and quiet mode never moves it.
1777
+ * @returns whether a parked window was moved.
1778
+ */
1779
+ async revealQuietWindow(handle: ElectronViewHandle, options?: QuietRevealOptions): Promise<boolean> {
1780
+ const view = this.views.get(handle.id)
1781
+ const targetId = view === undefined ? undefined : this.sessions.get(view.session)
1782
+ if ((this.quietParked.size === 0 && this.quietRevealed.size === 0) || view === undefined || targetId === undefined) return false
1783
+ try {
1784
+ // Asked of the browser by target id: the view's own command path would replace a closed page with a blank one.
1785
+ const found = await view.client.send('Browser.getWindowForTarget', { targetId }) as { windowId?: unknown } | undefined
1786
+ if (typeof found?.windowId !== 'number') return false
1787
+ const parked = this.quietParked.delete(found.windowId)
1788
+ if (!parked && !this.quietRevealed.has(found.windowId)) return false
1789
+ // A window already revealed (a skipped takeover, retried) stays where the person has it; only its tab is selected.
1790
+ const g = parked ? await this.moveOnScreen(view.client, found.windowId, view.session) : await windowGeometry(view.client, view.session)
1791
+ this.quietRevealed.add(found.windowId)
1792
+ if (options?.select === true) await view.client.send('Page.bringToFront', {}, view.session)
1793
+ else if (g?.hidden === true) {
1794
+ const front = { client: view.client, session: view.session, targetId }
1795
+ this.quietFront = front
1796
+ options?.until?.addEventListener('abort', () => {
1797
+ if (this.quietFront !== front) return
1798
+ this.quietFront = undefined
1799
+ if (!this.quietWatched()) this.stopForeground()
1800
+ }, { once: true })
1801
+ this.watchQuietFocus(view.client)
1802
+ }
1803
+ if (!this.quietWatched()) this.stopForeground()
1804
+ return parked
1805
+ } catch {
1806
+ // The page went away; the command that selected it reports that itself.
1807
+ return false
1808
+ }
1809
+ }
1810
+
1458
1811
  private rememberTarget(client: CdpClient, targetId: string, viewId: string): void {
1459
1812
  let targets = this.createdTargets.get(client)
1460
1813
  if (!targets) { targets = new Map(); this.createdTargets.set(client, targets) }
@@ -1494,4 +1847,4 @@ export async function probeAttach(port: number = CDP_DEFAULT_ATTACH_PORT, timeou
1494
1847
  } finally {
1495
1848
  clearTimeout(timer)
1496
1849
  }
1497
- }
1850
+ }