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.
@@ -30,6 +30,7 @@ import { readFileSync, rmSync, statSync } from 'node:fs';
30
30
  import { existsSync } from 'node:fs';
31
31
  import { join } from 'node:path';
32
32
  import { acquireProfileLease } from './profile-lease.js';
33
+ import { watchForeground } from './foreground-watch.js';
33
34
  import { BrowserProcessOwnership } from './process-ownership.js';
34
35
  /**
35
36
  * How long a killed browser is given to actually exit before the launch proceeds.
@@ -193,13 +194,13 @@ function findOnPath(names, env, platform) {
193
194
  * environment override, then PATH, then the platform's conventional install
194
195
  * locations. PATH comes before the fixed paths because it is what actually reflects
195
196
  * how the browser was installed.
196
- * @param channel - the configured choice; `bundled` never resolves to a system browser.
197
+ * @param channel - the configured choice; `bundled` / `electron` never resolve to a system browser.
197
198
  * @param env - environment lookup, injected so tests need no real machine.
198
199
  * @param platform - the platform to use conventions for; injected for the same reason.
199
200
  * @returns the detected browser, or undefined when the choice is unavailable.
200
201
  */
201
202
  export function detectBrowser(channel, env = process.env, platform = process.platform) {
202
- if (channel === 'bundled')
203
+ if (channel === 'bundled' || channel === 'electron' || channel === 'sidebar')
203
204
  return undefined;
204
205
  const order = channel === 'auto' ? ['chrome', 'edge', 'brave'] : [channel];
205
206
  for (const kind of order) {
@@ -234,11 +235,33 @@ export function searchSummary(kind, platform = process.platform, env = process.e
234
235
  const located = (INSTALL_LOCATIONS[kind]?.[platform] ?? []).map(entry => expandLocation(entry, env));
235
236
  return [...onPath, ...located];
236
237
  }
238
+ /**
239
+ * Where quiet mode first parks its window: past ordinary displays while staying under Win32's
240
+ * 16-bit signed coordinate ceiling (32767 physical pixels) even at 125%-300% DPI scaling. Any
241
+ * ultra-wide multi-monitor overlap is pushed further out by {@link clearDisplays}.
242
+ */
243
+ const QUIET_PARK = { left: 10000, top: 0, width: 1280, height: 800 };
244
+ const QUIET_PARK_GAP = 200;
245
+ const QUIET_PARK_LEFT_TOLERANCE = 2000;
246
+ const QUIET_PARK_TOP_TOLERANCE = 256;
247
+ const QUIET_REVEAL_INSET = 40;
248
+ const QUIET_FRONT_SLACK = 16;
249
+ /** The display the page's window is on (or nearest to), the window's outer rectangle, and whether the page is hidden. */
250
+ async function windowGeometry(client, sessionId) {
251
+ const out = await client.send('Runtime.evaluate', {
252
+ 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" })',
253
+ returnByValue: true,
254
+ }, sessionId);
255
+ const g = out?.result?.value;
256
+ 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;
257
+ }
237
258
  /** One CDP connection to a browser-level WebSocket, with flattened sessions. */
238
259
  class CdpClient {
239
260
  nextId = 1;
240
261
  pending = new Map();
241
262
  ready;
263
+ destroyedTargets = new Set();
264
+ headless = false;
242
265
  /**
243
266
  * @param url - the browser's `webSocketDebuggerUrl`.
244
267
  */
@@ -275,7 +298,7 @@ class CdpClient {
275
298
  isAlive() {
276
299
  return this.socket.readyState === WebSocket.OPEN;
277
300
  }
278
- async whenReady(deadline = Date.now() + 30_000) {
301
+ async whenReady(deadline = Date.now() + CARRIER_CALL_TIMEOUT_MS) {
279
302
  const timeoutMs = Math.max(1, deadline - Date.now());
280
303
  let timer;
281
304
  try {
@@ -303,7 +326,7 @@ class CdpClient {
303
326
  * @param sessionId - the flattened session to target, when this is a page command.
304
327
  * @returns the CDP result.
305
328
  */
306
- async send(method, params, sessionId, timeoutMs = 30_000) {
329
+ async send(method, params, sessionId, timeoutMs = CARRIER_CALL_TIMEOUT_MS) {
307
330
  // Fail fast and say why. Waiting out the timeout on a closed socket produced
308
331
  // only "timed out", which reads as a slow page and hides the real cause.
309
332
  if (!this.isAlive()) {
@@ -329,6 +352,9 @@ class CdpClient {
329
352
  catch { /* already closed */ }
330
353
  }
331
354
  /** Route one CDP message to its waiter. */
355
+ eventListeners = new Set();
356
+ /** Receive the browser's own CDP events (those without a command id). */
357
+ onEvent(listener) { this.eventListeners.add(listener); }
332
358
  onMessage(raw) {
333
359
  let message;
334
360
  try {
@@ -337,8 +363,15 @@ class CdpClient {
337
363
  catch {
338
364
  return;
339
365
  }
340
- if (message.id === undefined)
366
+ if (message.id === undefined) {
367
+ const targetId = message.method === 'Target.targetDestroyed' ? message.params?.targetId : undefined;
368
+ if (typeof targetId === 'string')
369
+ this.destroyedTargets.add(targetId);
370
+ if (typeof message.method === 'string')
371
+ for (const listener of this.eventListeners)
372
+ listener(message.method, message.params);
341
373
  return;
374
+ }
342
375
  const entry = this.pending.get(message.id);
343
376
  if (entry === undefined)
344
377
  return;
@@ -358,14 +391,6 @@ class CdpClient {
358
391
  }
359
392
  /** A system browser driven over CDP, presented as a browser view host. */
360
393
  export class SystemBrowserViewHost {
361
- browser;
362
- profileDir;
363
- extraArgs;
364
- ephemeralDir;
365
- launcher;
366
- headlessMode;
367
- isQuiet;
368
- profileError;
369
394
  /**
370
395
  * viewId -> the session that view rides, and the client that issued it.
371
396
  *
@@ -389,6 +414,9 @@ export class SystemBrowserViewHost {
389
414
  * spawned when a view is actually needed.
390
415
  */
391
416
  client;
417
+ /** Whether the running browser was launched headless, so its pages get a plain Chrome user agent. */
418
+ /** The browser's user agent without the `HeadlessChrome` token, read once per connection. */
419
+ plainUserAgent;
392
420
  /**
393
421
  * Set when a command went unanswered rather than being refused.
394
422
  *
@@ -399,7 +427,9 @@ export class SystemBrowserViewHost {
399
427
  */
400
428
  clientSuspect = false;
401
429
  child;
430
+ launchParked = false;
402
431
  profileLease;
432
+ profileLeasing;
403
433
  starting;
404
434
  lastLaunchError;
405
435
  launchDiagnostic;
@@ -415,20 +445,14 @@ export class SystemBrowserViewHost {
415
445
  ownedClients = new WeakMap();
416
446
  ownedChildren = new WeakSet();
417
447
  createdTargets = new WeakMap();
418
- /**
419
- * @param browser - the detected installation to launch on first use.
420
- * @param profileDir - a plugin-owned directory; the user's own profile is never touched.
421
- * @param extraArgs - additional Chromium switches.
422
- * @param ephemeralDir - a directory to delete on release, when the user has turned
423
- * persistence off so no login state outlives the session.
424
- * @param launcher - how to start the browser, for tests.
425
- *
426
- * Recovery after the browser dies was untestable without this: the suite spawns a stub
427
- * with Chromium's arguments, and a stub that is not a browser rejects them and exits, so
428
- * no CDP endpoint ever appears and no session is ever created. Verified by mutation —
429
- * removing every sessions.clear() left the recovery tests green. A launcher lets a test
430
- * provide something that actually speaks CDP, so the state those tests describe exists.
431
- */
448
+ browser;
449
+ profileDir;
450
+ extraArgs;
451
+ ephemeralDir;
452
+ launcher;
453
+ headlessMode;
454
+ isQuiet;
455
+ profileError;
432
456
  constructor(browser, profileDir, extraArgs = [], ephemeralDir, launcher = defaultLauncher,
433
457
  /**
434
458
  * Whether this launch should get a window. See {@link resolveLaunchMode} for how `auto` decides
@@ -478,6 +502,25 @@ export class SystemBrowserViewHost {
478
502
  } },
479
503
  };
480
504
  }
505
+ connectedView(id) {
506
+ const view = this.views.get(id), target = view === undefined ? undefined : this.sessions.get(view.session);
507
+ return view !== undefined && target !== undefined && view.client === this.client && !view.client.headless
508
+ && !view.client.destroyedTargets.has(target) && this.connectionStatus().connected;
509
+ }
510
+ /**
511
+ * Whether this view is live on the current connection but sits inside a headless browser, so there is
512
+ * no window a person could be handed. Mirrors {@link connectedView}, which requires the opposite.
513
+ *
514
+ * Takeover has to tell these apart instead of falling back to the sidebar: a headless session that
515
+ * silently produced a sidebar tab left the person acting on an unrelated page (issue #103).
516
+ * @param id - the view to classify.
517
+ * @returns true when the view is alive and headless.
518
+ */
519
+ headlessView(id) {
520
+ const view = this.views.get(id), target = view === undefined ? undefined : this.sessions.get(view.session);
521
+ return view !== undefined && target !== undefined && view.client === this.client && view.client.headless
522
+ && !view.client.destroyedTargets.has(target) && this.connectionStatus().connected;
523
+ }
481
524
  /** Which product this host would drive (for diagnostics). */
482
525
  get kind() {
483
526
  return this.browser.kind;
@@ -531,6 +574,11 @@ export class SystemBrowserViewHost {
531
574
  forgetBrowserState() {
532
575
  this.views.clear();
533
576
  this.sessions.clear();
577
+ this.quietParked.clear();
578
+ this.parkedTargets.clear();
579
+ this.quietFront = undefined;
580
+ this.quietRevealed.clear();
581
+ this.stopForeground();
534
582
  }
535
583
  async ensureClient() {
536
584
  // A disposed host must never start a browser: doing so would spawn a process
@@ -592,7 +640,7 @@ export class SystemBrowserViewHost {
592
640
  * @param _why - a short phrase for the log, naming which attempt this is.
593
641
  * @returns a connected client for the running browser, or undefined when there is none.
594
642
  */
595
- async adoptRunningBrowser(_why, explicitPort, deadline = Date.now() + 30_000) {
643
+ async adoptRunningBrowser(_why, explicitPort, deadline = Date.now() + CARRIER_CALL_TIMEOUT_MS) {
596
644
  const portFile = join(this.profileDir, 'DevToolsActivePort');
597
645
  let port;
598
646
  if (typeof explicitPort === 'number' && explicitPort > 0) {
@@ -630,6 +678,7 @@ export class SystemBrowserViewHost {
630
678
  const info = await client.send('Browser.getVersion', {}, undefined, Math.max(1, deadline - Date.now()));
631
679
  if (!isBrowserProduct(info?.product) || info.product !== version.Browser)
632
680
  throw new Error('browser did not acknowledge its identity');
681
+ client.headless = /^HeadlessChrome\//u.test(info.product ?? '');
633
682
  if (this.disposed) {
634
683
  client.close();
635
684
  return undefined;
@@ -639,7 +688,10 @@ export class SystemBrowserViewHost {
639
688
  client.close();
640
689
  return undefined;
641
690
  }
691
+ this.launchParked = false;
642
692
  this.client = client;
693
+ this.placeOpenedWindows(client);
694
+ this.plainUserAgent = undefined;
643
695
  return client;
644
696
  }
645
697
  catch (error) {
@@ -662,8 +714,15 @@ export class SystemBrowserViewHost {
662
714
  * @returns the connected client.
663
715
  */
664
716
  async start() {
665
- const deadline = Date.now() + 30_000;
666
- this.profileLease ??= acquireProfileLease(this.profileDir);
717
+ const deadline = Date.now() + CARRIER_CALL_TIMEOUT_MS;
718
+ if (this.profileLease === undefined) {
719
+ const lease = await (this.profileLeasing ??= acquireProfileLease(this.profileDir).finally(() => { this.profileLeasing = undefined; }));
720
+ if (this.disposed) {
721
+ await lease.release();
722
+ throw new Error('dsh-builtin-browser: the browser host was disposed while launching');
723
+ }
724
+ this.profileLease = lease;
725
+ }
667
726
  // Before spawning anything: is a browser for THIS profile already running? A DSH restart
668
727
  // leaves one behind, and launching into it is the failure reported as "exited immediately
669
728
  // after launch (exit code 0)" that required killing seven processes by hand.
@@ -700,6 +759,15 @@ export class SystemBrowserViewHost {
700
759
  '--disable-features=Translate,MediaRouter',
701
760
  '--disable-session-crashed-bubble',
702
761
  '--hide-crash-restore-bubble',
762
+ // The remote-debugging port this plugin drives makes Chrome set `navigator.webdriver` on every
763
+ // page, windowed or not, which bot walls read as "a script, not a person" — even while the
764
+ // person is the one browsing. Chrome's own switch turns that marker off; nothing else changes.
765
+ '--disable-blink-features=AutomationControlled',
766
+ // Quiet mode parks its first window off-screen; without these Windows occlusion tracking marks
767
+ // it hidden, pausing rAF, clamping timers and stalling screenshots. Passed always: quiet is a live setting.
768
+ '--disable-backgrounding-occluded-windows',
769
+ '--disable-renderer-backgrounding',
770
+ '--disable-background-timer-throttling',
703
771
  // Headless only where there is nothing to draw on. `--headless=new` rather than the legacy
704
772
  // flag: the new mode behaves like a windowed browser, which matters because every command
705
773
  // here was written and measured against one — including CDP input, which Chromium silently
@@ -720,6 +788,11 @@ export class SystemBrowserViewHost {
720
788
  // normally through `Target.createTarget`.
721
789
  '--no-startup-window',
722
790
  ];
791
+ // Chromium shows a new window at its default spot and only then applies Target.createTarget's
792
+ // left/top, so a quiet first window flashed on-screen; the launch position is applied before show.
793
+ this.launchParked = !launch.headless && this.isQuiet();
794
+ if (this.launchParked)
795
+ args.push(`--window-position=${QUIET_PARK.left},${QUIET_PARK.top}`, `--window-size=${QUIET_PARK.width},${QUIET_PARK.height}`);
723
796
  if (launch.headless) {
724
797
  process.stderr.write(`[dsh-browser] launching headless (${launch.why}); `
725
798
  + 'the browser has no window but every tool works the same\n');
@@ -980,7 +1053,10 @@ export class SystemBrowserViewHost {
980
1053
  client.close();
981
1054
  break;
982
1055
  }
1056
+ client.headless = launch.headless;
983
1057
  this.client = client;
1058
+ this.placeOpenedWindows(client);
1059
+ this.plainUserAgent = undefined;
984
1060
  return client;
985
1061
  }
986
1062
  }
@@ -1031,18 +1107,6 @@ export class SystemBrowserViewHost {
1031
1107
  available() {
1032
1108
  return !this.disposed;
1033
1109
  }
1034
- /**
1035
- * Every page the browser currently holds, including ones this plugin did not create.
1036
- *
1037
- * Chrome and Edge own their own page creation. A click on a link that opens a new page — or any
1038
- * `window.open` — produces a page the provider never asked for, and nothing reports it back.
1039
- * Those pages are real: they hold memory and stay until something closes them. Measured on a real
1040
- * window: four pages present while `dsh_browser_list_tabs` reported one.
1041
- *
1042
- * Discovery is enabled before the connection is published, so
1043
- * `Target.getTargets` also lists pages that existed before this client connected.
1044
- * @returns the browser's pages, or an empty list when it cannot answer.
1045
- */
1046
1110
  /**
1047
1111
  * Every page the browser holds that THIS HOST did not open.
1048
1112
  *
@@ -1068,10 +1132,11 @@ export class SystemBrowserViewHost {
1068
1132
  // check the reference-bar pump called listPages on every tick, whose
1069
1133
  // ensureClient() launched Edge on its own within seconds of the plugin
1070
1134
  // loading — measured with no open/navigate call at all.
1071
- if (options.requireRunning === true && !this.started)
1135
+ const liveClient = this.client;
1136
+ if (options.requireRunning === true && (this.disposed || liveClient === undefined || !liveClient.isAlive()))
1072
1137
  return [];
1073
1138
  try {
1074
- const client = await this.ensureClient();
1139
+ const client = options.requireRunning === true && liveClient !== undefined ? liveClient : await this.ensureClient();
1075
1140
  const listed = await client.send('Target.getTargets', {});
1076
1141
  const ours = new Set(this.sessions.values());
1077
1142
  return (listed?.targetInfos ?? [])
@@ -1121,43 +1186,52 @@ export class SystemBrowserViewHost {
1121
1186
  // This is the real browser, not Electron: CDP's JPEG encoder works here, so the
1122
1187
  // provider may pass format and quality through instead of falling back to PNG.
1123
1188
  supportsCdpJpeg: true,
1124
- sendCommand: async (method, params) => {
1189
+ sendCommand: async (method, params, options) => {
1125
1190
  if (method === 'Browser.close' || method === 'Target.closeTarget' || method === 'Page.close') {
1126
1191
  throw new Error('dsh-builtin-browser: use explicit tab close; browser-wide and unowned-tab closes are not allowed');
1127
1192
  }
1128
- // A command that never answered is the only signal that a client has wedged — the
1129
- // socket can stay OPEN while nothing comes back, which is the form the reporter saw with
1130
- // a live, healthy-looking Edge. Dropping the client here means the next call starts a new
1131
- // browser rather than hanging again, and the error names the cause instead of a timeout.
1132
- const client = await this.ensureClient();
1193
+ // Background probes (reference bar pump, readiness checks) pass initialize: false and
1194
+ // must never relaunch a killed browser or recreate a tab the user closed (issue #105).
1195
+ const initialize = options?.initialize !== false;
1196
+ let client;
1197
+ if (initialize) {
1198
+ client = await this.ensureClient();
1199
+ }
1200
+ else {
1201
+ const liveClient = this.client;
1202
+ if (this.disposed || liveClient === undefined || !liveClient.isAlive()) {
1203
+ throw new Error('dsh-builtin-browser: browser is not running');
1204
+ }
1205
+ client = liveClient;
1206
+ }
1133
1207
  const cachedView = this.views.get(viewId);
1208
+ if (cachedView !== undefined && cachedView.client === client) {
1209
+ const cachedTarget = this.sessions.get(cachedView.session);
1210
+ if (cachedTarget !== undefined && client.destroyedTargets.has(cachedTarget)) {
1211
+ this.views.delete(viewId);
1212
+ this.sessions.delete(cachedView.session);
1213
+ if (!initialize)
1214
+ throw new Error('dsh-builtin-browser: target was closed');
1215
+ }
1216
+ }
1134
1217
  // A session belongs to the browser that issued it. Clearing the cache whenever a client is
1135
1218
  // dropped covers the ordinary case, but not this one: another call can be inside
1136
1219
  // ensureSession() holding the OLD client while this one discards it and clears, and that
1137
1220
  // call's `views.set` then lands afterwards — re-adding an entry naming a browser that is
1138
1221
  // gone. The identity check is what refuses it, and it costs a comparison rather than the
1139
1222
  // round trip that validating every cached session against the browser would cost.
1140
- //
1141
- // (Not covered by the tests: the race needs two interleaved commands, and the suite's fake
1142
- // browser is synchronous enough that they never interleave. Verified by mutation instead —
1143
- // removing this check alone leaves every case green, which is why the comment says what it
1144
- // protects rather than claiming a case proves it.)
1145
- const session = cachedView !== undefined && cachedView.client === client
1146
- ? cachedView.session
1223
+ const liveView = this.views.get(viewId);
1224
+ if (!initialize && (liveView === undefined || liveView.client !== client)) {
1225
+ throw new Error('dsh-builtin-browser: view has no live page');
1226
+ }
1227
+ const session = liveView !== undefined && liveView.client === client
1228
+ ? liveView.session
1147
1229
  : await this.ensureSession(viewId);
1148
1230
  /**
1149
1231
  * Send one page command, rebuilding the attach once if the browser no longer knows the
1150
- * session.
1151
- *
1152
- * "Session with given id not found" means the session id is stale, and the causes differ:
1153
- * a replaced client (handled where the client is dropped), a target the browser destroyed,
1154
- * or a detach the page performed on itself. What they share is that the id is worthless and
1155
- * the VIEW is fine, so the right answer is one fresh attach — not an error to the caller and
1156
- * not a new page. Measured while solving a sudoku on a canvas page: after a tab switch every
1157
- * command failed with this text and nothing in the plugin ever recovered it.
1158
- *
1159
- * Retried exactly once: a failure that survives a fresh attach is not a stale id, and
1160
- * repeating it would turn an error into a loop.
1232
+ * session. Re-attaches to the original live target instead of spawning a blank page,
1233
+ * never rebuilds a target that was destroyed or closed by the user, and never initializes
1234
+ * a new page when `initialize: false` (issue #105).
1161
1235
  */
1162
1236
  const sendWithAttach = async (target) => {
1163
1237
  try {
@@ -1168,11 +1242,38 @@ export class SystemBrowserViewHost {
1168
1242
  const message = error instanceof Error ? error.message : String(error);
1169
1243
  if (!/Session with given id not found|No session with given id/i.test(message))
1170
1244
  throw error;
1171
- // Drop the dead attach so `ensureSession` builds a new one instead of returning the same id.
1172
- const stale = this.views.get(viewId);
1173
- if (stale !== undefined)
1245
+ // If another concurrent call already started or finished reattaching this view, join it
1246
+ // instead of falling through to ensureSession() and spawning an orphan about:blank tab.
1247
+ const inFlight = this.sessionBuilding.get(viewId);
1248
+ if (inFlight !== undefined) {
1249
+ if (!initialize)
1250
+ throw error;
1251
+ const joined = await inFlight;
1252
+ const retried = await client.send(method, params, joined);
1253
+ return (retried ?? {});
1254
+ }
1255
+ const current = this.views.get(viewId);
1256
+ if (current !== undefined && current.client === client && current.session !== target) {
1257
+ const retried = await client.send(method, params, current.session);
1258
+ return (retried ?? {});
1259
+ }
1260
+ // Drop only the stale mapping for this exact client+session.
1261
+ if (current !== undefined && current.client === client && current.session === target) {
1174
1262
  this.views.delete(viewId);
1263
+ }
1264
+ const deadTarget = this.sessions.get(target);
1175
1265
  this.sessions.delete(target);
1266
+ if (!initialize)
1267
+ throw error;
1268
+ if (deadTarget !== undefined) {
1269
+ if (client.destroyedTargets.has(deadTarget))
1270
+ throw error;
1271
+ // Register the reattach transaction synchronously before any await so concurrent
1272
+ // callers hitting the same stale session join it instead of spawning about:blank.
1273
+ const rebuilt = await this.reattachTarget(client, viewId, deadTarget);
1274
+ const retried = await client.send(method, params, rebuilt);
1275
+ return (retried ?? {});
1276
+ }
1176
1277
  const rebuilt = await this.ensureSession(viewId);
1177
1278
  const retried = await client.send(method, params, rebuilt);
1178
1279
  return (retried ?? {});
@@ -1182,31 +1283,11 @@ export class SystemBrowserViewHost {
1182
1283
  return await sendWithAttach(session);
1183
1284
  }
1184
1285
  catch (error) {
1185
- // A CDP protocol error means the browser ANSWERED and refused this one command, so the
1186
- // connection is healthy and must be kept. Deciding by the error TEXT misfires both
1187
- // ways: the inner timeout rejects with "… timed out", so a slow but healthy page read
1188
- // as a dead browser, the client was dropped, and the next call's start() killed the
1189
- // running child — the human's tabs and half-filled forms gone, which is worse than the
1190
- // bug that change was fixing. The browser's own free text is interpolated into
1191
- // protocol errors too, so any message containing those words misfired the same way.
1192
- // Unanswered versus refused. 'timed out' is the inner client's own budget expiring,
1193
- // which says the page was slow, not that the browser died — so it only marks the client
1194
- // for a probe. Being wrong here costs a two-second check; being wrong about the
1195
- // browser being dead cost the user their open tabs.
1196
1286
  if (error instanceof Error && /timed out/.test(error.message))
1197
1287
  this.clientSuspect = true;
1198
1288
  if (!client.isAlive()) {
1199
- // Only THIS call's client. Under concurrency the field may already hold a
1200
- // connection another call just published, and closing that would kill a healthy one.
1201
1289
  if (this.client === client) {
1202
1290
  this.client = undefined;
1203
- // This is the third of the three paths that discard a client, and it was the one
1204
- // that did not retire what the client had issued. A view holding a session id
1205
- // from the dead browser kept handing it to the replacement, which had never heard
1206
- // of it: every page command then failed with "Session with given id not found"
1207
- // and no later call could clear it, because the cached session was returned
1208
- // unconditionally. Gated on the same identity check as the field itself, so a
1209
- // concurrent call that just published a healthy client does not lose its maps.
1210
1291
  this.forgetBrowserState();
1211
1292
  }
1212
1293
  client.close();
@@ -1230,26 +1311,24 @@ export class SystemBrowserViewHost {
1230
1311
  }
1231
1312
  }
1232
1313
  /** Nothing to show: the browser owns its own windows. */
1233
- showView() { }
1314
+ showView(handle, _label, options) {
1315
+ if (options?.user === true && (options.quiet === true || this.isQuiet()))
1316
+ void this.revealQuietWindow(handle, { select: true });
1317
+ }
1234
1318
  /**
1235
1319
  * Bring the target's page to the front, then report success.
1236
1320
  *
1237
- * The comment on `focus` below used to say this was impossible — that raising the page needs
1238
- * `Page.bringToFront` on a target session, which is a view-level concern the host cannot
1239
- * reach. The handle this method is handed IS that view, and it can send commands, so the
1240
- * capability was here all along; it just was not used. Without it `presentView` was an empty
1241
- * async method, so the provider's whole presentation barrier — the one that stops
1242
- * `Input.*` from being silently dropped for a view with no display surface, and reports
1243
- * `BROWSER_VIEW_NOT_PRESENTED` when it cannot present — never ran on this carrier.
1244
- *
1245
1321
  * A failure is swallowed rather than propagated: a real Chrome window that refuses to come
1246
1322
  * forward is not a reason to refuse the click that follows. The barrier exists to order the
1247
1323
  * two, and the order is honoured either way.
1248
1324
  * @param handle - the view to present.
1249
1325
  */
1250
1326
  async presentView(handle, _label, options) {
1251
- if (options?.quiet === true || this.isQuiet())
1327
+ if (options?.quiet === true || this.isQuiet()) {
1328
+ if (options?.user === true)
1329
+ await this.revealQuietWindow(handle, { select: true });
1252
1330
  return;
1331
+ }
1253
1332
  try {
1254
1333
  await handle.sendCommand('Page.bringToFront');
1255
1334
  }
@@ -1260,15 +1339,6 @@ export class SystemBrowserViewHost {
1260
1339
  }
1261
1340
  /**
1262
1341
  * Best effort at bringing the browser's window forward.
1263
- *
1264
- * The browser is a separate application, so there is no view to raise. What this can
1265
- * actually do is ask its process to continue from a stopped state — which is a no-op on
1266
- * Windows, where `SIGCONT` is not a supported signal and the call throws. It is kept
1267
- * because it costs nothing and does help on POSIX (a process stopped with SIGSTOP
1268
- * resumes), but it must not be read as a promise that the window comes to the front;
1269
- * importantly, it does NOT raise a window that is merely behind another. Raising the
1270
- * page properly would need `Page.bringToFront` on a specific target session, which is a
1271
- * view-level concern and not available to the host.
1272
1342
  */
1273
1343
  async focus() {
1274
1344
  if (this.child && await this.ownership.verify(this.child)) {
@@ -1280,12 +1350,9 @@ export class SystemBrowserViewHost {
1280
1350
  }
1281
1351
  /**
1282
1352
  * Close the browser we launched, if we ever launched one.
1283
- *
1284
- * The user's own windows belong to a different process and are never touched. A
1285
- * host whose browser was never started (the common case when nobody used the
1286
- * browser) simply tears down its bookkeeping.
1287
1353
  */
1288
1354
  dispose() {
1355
+ this.stopForeground();
1289
1356
  if (this.disposed)
1290
1357
  return;
1291
1358
  this.disposed = true;
@@ -1310,18 +1377,9 @@ export class SystemBrowserViewHost {
1310
1377
  }
1311
1378
  };
1312
1379
  void disconnect();
1313
- // Both the browser we launched and anything that ignored an earlier kill. They hold this
1314
- // profile, so leaving them running means the next launch contends with a browser nobody owns.
1315
1380
  const doomed = [this.child, ...this.stubborn.splice(0)].filter((entry) => entry !== undefined);
1316
1381
  this.child = undefined;
1317
1382
  for (const dying of doomed) {
1318
- /**
1319
- * A bounded reprieve, then the kill we used to do immediately.
1320
- *
1321
- * The timer is unref'd so it never holds the process open: a DSH shutdown that is itself
1322
- * ending does not wait for this, and the browser — having been asked to close — generally
1323
- * gets there on its own. If it does not, the kill still lands while the process lives.
1324
- */
1325
1383
  const force = () => { void this.stopChild(dying); };
1326
1384
  const timer = setTimeout(force, CLOSE_GRACE_MS);
1327
1385
  timer.unref?.();
@@ -1342,7 +1400,6 @@ export class SystemBrowserViewHost {
1342
1400
  this.profileLease = undefined;
1343
1401
  })().catch(error => process.stderr.write(`[dsh-browser] profile release failed: ${String(error)}\n`));
1344
1402
  };
1345
- // Saved processes retain the profile until their exit events arrive.
1346
1403
  const live = doomed.filter(child => child.exitCode === null && child.signalCode === null);
1347
1404
  if (live.length > 0) {
1348
1405
  const remaining = new Set(live);
@@ -1360,18 +1417,48 @@ export class SystemBrowserViewHost {
1360
1417
  cleanup();
1361
1418
  }
1362
1419
  }
1420
+ /**
1421
+ * Verify an existing target is still alive and re-attach to it, sharing one in-flight transaction
1422
+ * across concurrent callers for the same view and never creating a replacement blank page.
1423
+ */
1424
+ async reattachTarget(client, viewId, targetId) {
1425
+ const existing = this.views.get(viewId);
1426
+ if (existing !== undefined && existing.client === client)
1427
+ return existing.session;
1428
+ const inFlight = this.sessionBuilding.get(viewId);
1429
+ if (inFlight !== undefined)
1430
+ return await inFlight;
1431
+ const building = (async () => {
1432
+ if (client.destroyedTargets.has(targetId)) {
1433
+ throw new Error('dsh-builtin-browser: CDP error: Session with given id not found.');
1434
+ }
1435
+ const alive = await client.send('Target.getTargets', {})
1436
+ .then(listed => Array.isArray(listed.targetInfos)
1437
+ ? listed.targetInfos.some(entry => entry.targetId === targetId)
1438
+ : true)
1439
+ .catch(() => true);
1440
+ if (!alive) {
1441
+ throw new Error('dsh-builtin-browser: CDP error: Session with given id not found.');
1442
+ }
1443
+ const attached = await client.send('Target.attachToTarget', { targetId, flatten: true });
1444
+ const sessionId = attached?.sessionId;
1445
+ if (typeof sessionId !== 'string') {
1446
+ throw new Error(`dsh-builtin-browser: could not reattach to existing page ${targetId}`);
1447
+ }
1448
+ await this.presentAsChrome(client, sessionId);
1449
+ this.sessions.set(sessionId, targetId);
1450
+ this.views.set(viewId, { session: sessionId, client });
1451
+ return sessionId;
1452
+ })().finally(() => {
1453
+ this.sessionBuilding.delete(viewId);
1454
+ });
1455
+ this.sessionBuilding.set(viewId, building);
1456
+ return await building;
1457
+ }
1363
1458
  /**
1364
1459
  * The flattened session for a view, creating its page on first use.
1365
- *
1366
- * No cache check here: the only caller has already established that the cached session does
1367
- * not belong to the client it is about to use. Re-checking would mean either a round trip or
1368
- * a second copy of that rule.
1369
1460
  */
1370
1461
  async ensureSession(viewId) {
1371
- // One target per view, even when two commands arrive together. The two CDP round trips
1372
- // below are awaits, so without this a second caller entering during the first's flight saw
1373
- // no session in `views` and created its own target — leaving an orphan page that nothing
1374
- // closes, because only the last id survives in the map.
1375
1462
  const inFlight = this.sessionBuilding.get(viewId);
1376
1463
  if (inFlight !== undefined)
1377
1464
  return await inFlight;
@@ -1384,21 +1471,12 @@ export class SystemBrowserViewHost {
1384
1471
  /** Create and attach the target for one view. Serialised by {@link ensureSession}. */
1385
1472
  async buildSession(viewId) {
1386
1473
  const client = await this.ensureClient();
1387
- // Different views can initialise concurrently. Selecting an unclaimed page and attaching
1388
- // it must be one transaction, including when the page is created by a preceding view.
1389
1474
  const previous = this.targetBuilds.get(client) ?? Promise.resolve();
1390
1475
  let release;
1391
1476
  const building = new Promise(resolve => { release = resolve; });
1392
1477
  this.targetBuilds.set(client, building);
1393
1478
  await previous;
1394
1479
  try {
1395
- // Adopt a blank page the browser opened on its own before creating another one.
1396
- //
1397
- // Chrome starts with more than one page when handed a URL on top of its own start page, so
1398
- // creating a target here discarded the original and left it behind as a tab that is not in
1399
- // the plugin's tab model — invisible to `dsh_browser_list_tabs`, and therefore unclosable
1400
- // through the tools. Taking the blank instead makes the page the browser already opened the
1401
- // one the caller gets.
1402
1480
  const adopted = await this.adoptBlankTarget(client);
1403
1481
  const targetId = adopted ?? await this.createTarget(client, viewId);
1404
1482
  const attached = await client.send('Target.attachToTarget', { targetId, flatten: true });
@@ -1407,7 +1485,8 @@ export class SystemBrowserViewHost {
1407
1485
  throw new Error('dsh-builtin-browser: the browser did not attach to the new page');
1408
1486
  if (adopted !== undefined)
1409
1487
  this.rememberTarget(client, targetId, viewId);
1410
- // The session id is what page commands ride; the target id is what closes it.
1488
+ await this.clearDisplays(client, sessionId, targetId);
1489
+ await this.presentAsChrome(client, sessionId);
1411
1490
  this.sessions.set(sessionId, targetId);
1412
1491
  this.views.set(viewId, { session: sessionId, client });
1413
1492
  return sessionId;
@@ -1418,21 +1497,15 @@ export class SystemBrowserViewHost {
1418
1497
  this.targetBuilds.delete(client);
1419
1498
  }
1420
1499
  }
1421
- /**
1422
- * Take over a page the browser already has, so a person's own tab becomes one this plugin drives.
1423
- *
1424
- * Reported as a defect: opening a window by hand, navigating it, and then asking a tool to read it
1425
- * produced a SECOND page, because the only tab the provider knew about was one it created itself.
1426
- * The page the human was looking at was listed by `dsh_browser_list_tabs` (under `page:`) and
1427
- * could be closed, but not read or driven — the opposite of what "the page you are looking at"
1428
- * means.
1429
- *
1430
- * Attaching is all it takes: a CDP session is not exclusive, so the browser's own tab becomes a
1431
- * target this plugin has a session on. The page is not moved, reloaded or focused, and its
1432
- * existing session (logins, scroll position, form state) is untouched.
1433
- * @param targetId - the carrier's page id, which for this carrier IS the CDP target id.
1434
- * @returns a handle for that page, in the same shape {@link createView} returns.
1435
- */
1500
+ async presentAsChrome(client, sessionId) {
1501
+ this.plainUserAgent ??= client.send('Browser.getVersion', {})
1502
+ .then(info => typeof info?.userAgent === 'string' && info.userAgent.includes('HeadlessChrome/')
1503
+ ? info.userAgent.replace(/HeadlessChrome\//u, 'Chrome/') : undefined, () => undefined);
1504
+ const userAgent = await this.plainUserAgent;
1505
+ if (userAgent === undefined)
1506
+ return;
1507
+ await client.send('Emulation.setUserAgentOverride', { userAgent }, sessionId).catch(() => { });
1508
+ }
1436
1509
  async adoptPage(identity, scope = sessionWireId(readTabHandle(identity))) {
1437
1510
  const tab = resolveTabHandle(resolveSessionHandle(scope), identity).tab;
1438
1511
  if (!tab.startsWith('page:'))
@@ -1445,20 +1518,10 @@ export class SystemBrowserViewHost {
1445
1518
  if (typeof sessionId !== 'string') {
1446
1519
  throw new Error(`dsh-builtin-browser: could not attach to the existing page ${targetId}`);
1447
1520
  }
1448
- // Point the view `createView` just made at the page that already exists, instead of the one it
1449
- // would otherwise build on first use.
1450
1521
  this.sessions.set(sessionId, targetId);
1451
1522
  this.views.set(handle.id, { session: sessionId, client });
1452
1523
  return handle;
1453
1524
  }
1454
- /**
1455
- * Take an unclaimed blank page, if the browser has one to spare.
1456
- *
1457
- * "Unclaimed" is what matters: a blank page the plugin is already driving belongs to a view, and
1458
- * handing the same target to a second view would make two views share one page.
1459
- * @param client - the connected browser.
1460
- * @returns the target id to reuse, or undefined when a new page has to be created.
1461
- */
1462
1525
  async adoptBlankTarget(client) {
1463
1526
  const listed = await client.send('Target.getTargets', {});
1464
1527
  if (!Array.isArray(listed?.targetInfos))
@@ -1476,17 +1539,321 @@ export class SystemBrowserViewHost {
1476
1539
  return undefined;
1477
1540
  }
1478
1541
  /** Create one page, refusing to go on without an id. */
1479
- async createTarget(client, viewId) {
1480
- const created = await client.send('Target.createTarget', {
1481
- url: 'about:blank',
1482
- ...this.isQuiet() ? { background: true } : {},
1542
+ createTarget(client, viewId) {
1543
+ const run = this.createTargetNow(client, viewId);
1544
+ this.creating = run.then(() => undefined, () => undefined);
1545
+ return run;
1546
+ }
1547
+ creating = Promise.resolve();
1548
+ /**
1549
+ * A quiet launch makes Chromium open every new window off-screen, so a window a person or a page
1550
+ * opens (Ctrl+N, a popup) is brought on-screen, unless it is a popup of a window still parked.
1551
+ */
1552
+ placeOpenedWindows(client) {
1553
+ client.onEvent((method, params) => {
1554
+ if (method !== 'Target.targetCreated' || !this.launchParked)
1555
+ return;
1556
+ const info = params?.targetInfo;
1557
+ if (info?.type === 'page' && typeof info.targetId === 'string')
1558
+ void this.placeOpenedWindow(client, info.targetId, info.openerId);
1483
1559
  });
1560
+ }
1561
+ async placeOpenedWindow(client, targetId, openerId) {
1562
+ try {
1563
+ for (let pending = this.creating;; pending = this.creating) {
1564
+ await pending;
1565
+ if (pending === this.creating)
1566
+ break;
1567
+ }
1568
+ if (this.createdTargets.get(client)?.has(targetId) === true)
1569
+ return;
1570
+ const windowOf = async (id) => await client.send('Browser.getWindowForTarget', { targetId: id });
1571
+ const found = await windowOf(targetId);
1572
+ const left = found?.bounds?.left;
1573
+ const top = found?.bounds?.top;
1574
+ // Allow tolerance for DPI rounding or Windows clamping when matching the parked launch spot.
1575
+ const nearParked = typeof left === 'number' && left >= QUIET_PARK.left - QUIET_PARK_LEFT_TOLERANCE
1576
+ && (typeof top !== 'number' || Math.abs(top - QUIET_PARK.top) <= QUIET_PARK_TOP_TOLERANCE);
1577
+ if (typeof found?.windowId !== 'number' || !nearParked || this.quietParked.has(found.windowId))
1578
+ return;
1579
+ if (typeof openerId === 'string' && openerId !== '') {
1580
+ const opener = await windowOf(openerId).catch(() => undefined);
1581
+ if (typeof opener?.windowId === 'number' && this.quietParked.has(opener.windowId)) {
1582
+ this.quietParked.add(found.windowId);
1583
+ this.watchQuietFocus(client);
1584
+ return;
1585
+ }
1586
+ }
1587
+ await this.moveOnScreen(client, found.windowId);
1588
+ }
1589
+ catch {
1590
+ // A window that closed or a browser that went away needs no placing.
1591
+ }
1592
+ }
1593
+ async createTargetNow(client, viewId) {
1594
+ const quiet = this.isQuiet();
1595
+ const { created, parked } = quiet
1596
+ ? await this.createQuietTarget(client)
1597
+ : { created: await this.createPlainTarget(client), parked: false };
1484
1598
  const targetId = created?.targetId;
1485
1599
  if (typeof targetId !== 'string' || targetId === '')
1486
1600
  throw new Error('dsh-builtin-browser: the browser did not create a page');
1487
1601
  this.rememberTarget(client, targetId, viewId);
1602
+ if (parked)
1603
+ await this.parkQuietWindow(client, targetId);
1488
1604
  return targetId;
1489
1605
  }
1606
+ /**
1607
+ * `background` only keeps the user's tab active inside an existing window; the first page after
1608
+ * `--no-startup-window` opens a new one. `focus: false` keeps keyboard focus where it was, and the
1609
+ * window is created off-screen in the normal state: a minimized window is hidden to the page, so
1610
+ * rAF stops and rAF-driven pages never render. A Chromium that rejects the bounds gets the page
1611
+ * without them and the window is moved off-screen right after. A tab joining an existing window
1612
+ * leaves that window where the user has it.
1613
+ */
1614
+ async createQuietTarget(client) {
1615
+ const params = { url: 'about:blank', background: true, focus: false };
1616
+ const listed = await client.send('Target.getTargets');
1617
+ if (listed?.targetInfos?.some(entry => entry.type === 'page') === true) {
1618
+ return { created: await client.send('Target.createTarget', params), parked: false };
1619
+ }
1620
+ try {
1621
+ return { created: await client.send('Target.createTarget', { ...params, newWindow: true, ...QUIET_PARK }), parked: true };
1622
+ }
1623
+ catch {
1624
+ return { created: await client.send('Target.createTarget', params), parked: true };
1625
+ }
1626
+ }
1627
+ /** A browser launched while quiet opens new windows off-screen, so a first window after quiet is turned off is placed on-screen. */
1628
+ async createPlainTarget(client) {
1629
+ const params = { url: 'about:blank' };
1630
+ if (!this.launchParked)
1631
+ return client.send('Target.createTarget', params);
1632
+ const listed = await client.send('Target.getTargets');
1633
+ if (listed?.targetInfos?.some(entry => entry.type === 'page') === true)
1634
+ return client.send('Target.createTarget', params);
1635
+ try {
1636
+ return await client.send('Target.createTarget', { ...params, newWindow: true, left: QUIET_REVEAL_INSET, top: QUIET_REVEAL_INSET });
1637
+ }
1638
+ catch {
1639
+ const created = await client.send('Target.createTarget', params);
1640
+ const targetId = created?.targetId;
1641
+ if (typeof targetId === 'string' && targetId !== '') {
1642
+ const found = await client.send('Browser.getWindowForTarget', { targetId }).catch(() => undefined);
1643
+ if (typeof found?.windowId === 'number')
1644
+ await this.moveOnScreen(client, found.windowId).catch(() => undefined);
1645
+ }
1646
+ return created;
1647
+ }
1648
+ }
1649
+ /** Windows quiet mode parked off-screen; a window quiet mode has revealed is not listed. */
1650
+ quietParked = new Set();
1651
+ /** Pages whose window was just parked, until their session checks the window is clear of every display. */
1652
+ parkedTargets = new Map();
1653
+ async parkQuietWindow(client, targetId) {
1654
+ try {
1655
+ const found = await client.send('Browser.getWindowForTarget', { targetId });
1656
+ if (typeof found?.windowId !== 'number')
1657
+ return;
1658
+ if (found.bounds?.left !== QUIET_PARK.left || found.bounds?.top !== QUIET_PARK.top) {
1659
+ await client.send('Browser.setWindowBounds', { windowId: found.windowId, bounds: { ...QUIET_PARK } });
1660
+ }
1661
+ this.quietParked.add(found.windowId);
1662
+ this.parkedTargets.set(targetId, found.windowId);
1663
+ this.watchQuietFocus(client);
1664
+ }
1665
+ catch {
1666
+ // Without its id the window cannot be moved or revealed later, so it stays where Chromium put it.
1667
+ }
1668
+ }
1669
+ /**
1670
+ * Move a parked window past any display it still overlaps. The page's `screen` is the display
1671
+ * the window overlaps most (or the nearest one), so stepping past it until no display claims the
1672
+ * window clears the union of all displays, wherever the provisional position landed.
1673
+ */
1674
+ async clearDisplays(client, sessionId, targetId) {
1675
+ const windowId = this.parkedTargets.get(targetId);
1676
+ if (windowId === undefined)
1677
+ return;
1678
+ this.parkedTargets.delete(targetId);
1679
+ try {
1680
+ for (let step = 0; step < 8; step++) {
1681
+ const g = await windowGeometry(client, sessionId);
1682
+ if (g === undefined)
1683
+ return;
1684
+ 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;
1685
+ if (!overlaps)
1686
+ return;
1687
+ await client.send('Browser.setWindowBounds', { windowId, bounds: { left: g.sl + g.sw + QUIET_PARK_GAP, top: g.st } });
1688
+ }
1689
+ }
1690
+ catch {
1691
+ // A page that cannot report its geometry keeps the provisional position.
1692
+ }
1693
+ }
1694
+ foreground;
1695
+ foregroundStarting = false;
1696
+ foregroundFailed = false;
1697
+ /** A takeover page hidden behind another tab, brought to the front once the person activates its revealed window. */
1698
+ quietFront;
1699
+ /** Windows quiet mode parked and has since put on-screen. */
1700
+ quietRevealed = new Set();
1701
+ /** The real watcher exists on Windows only; tests replace it. */
1702
+ watchForeground = watchForeground;
1703
+ quietWatched() { return this.quietParked.size > 0 || this.quietFront !== undefined; }
1704
+ /**
1705
+ * A CDP click focuses the page, not the window, but Chrome activates its window for a tab the click
1706
+ * opens; the watcher gives that foreground back. Our Chrome in the foreground off every display
1707
+ * otherwise means a person activated the parked window from the taskbar or Alt-Tab. Asked of the OS,
1708
+ * it works with no view attached (after a reset).
1709
+ */
1710
+ watchQuietFocus(client) {
1711
+ if (this.foreground !== undefined || this.foregroundStarting)
1712
+ return;
1713
+ this.foregroundStarting = true;
1714
+ void (async () => {
1715
+ try {
1716
+ const info = await client.send('SystemInfo.getProcessInfo', {}, undefined, 1000);
1717
+ const pid = info?.processInfo?.find(entry => entry.type === 'browser')?.id;
1718
+ if (typeof pid !== 'number' || this.disposed || !this.quietWatched())
1719
+ return this.sendQuietFront();
1720
+ const watch = this.watchForeground(event => { if (event.pid === pid)
1721
+ void this.onForeground(client, event); }, reason => {
1722
+ if (!this.foregroundFailed) {
1723
+ this.foregroundFailed = true;
1724
+ console.warn(`[dsh-browser] quiet window: cannot watch the foreground window (${reason}); the panel and takeovers still bring it on-screen`);
1725
+ }
1726
+ if (this.foreground === watch)
1727
+ this.foreground = undefined;
1728
+ this.sendQuietFront();
1729
+ }, pid);
1730
+ this.foreground = watch;
1731
+ if (watch === undefined)
1732
+ this.sendQuietFront();
1733
+ }
1734
+ catch {
1735
+ // Without the browser's process id, the panel and a takeover still reveal the window.
1736
+ this.sendQuietFront();
1737
+ }
1738
+ finally {
1739
+ this.foregroundStarting = false;
1740
+ }
1741
+ })();
1742
+ }
1743
+ async onForeground(client, event) {
1744
+ if (event.yielded === true)
1745
+ return;
1746
+ if (event.offscreen) {
1747
+ for (const windowId of [...this.quietParked]) {
1748
+ this.quietParked.delete(windowId);
1749
+ this.quietRevealed.add(windowId);
1750
+ await this.moveOnScreen(client, windowId, await this.sessionInWindow(client, windowId)).catch(() => undefined);
1751
+ }
1752
+ }
1753
+ else if (this.quietFront !== undefined && await this.isFrontWindow(this.quietFront, event)) {
1754
+ const front = this.quietFront;
1755
+ this.quietFront = undefined;
1756
+ await front.client.send('Page.bringToFront', {}, front.session).catch(() => undefined);
1757
+ }
1758
+ if (!this.quietWatched())
1759
+ this.stopForeground();
1760
+ }
1761
+ /** A page attached in the window, to measure the display it lands on. */
1762
+ async sessionInWindow(client, windowId) {
1763
+ for (const view of [...this.views.values()]) {
1764
+ const targetId = this.sessions.get(view.session);
1765
+ if (targetId === undefined || view.client !== client)
1766
+ continue;
1767
+ const found = await client.send('Browser.getWindowForTarget', { targetId }).catch(() => undefined);
1768
+ if (found?.windowId === windowId)
1769
+ return view.session;
1770
+ }
1771
+ return undefined;
1772
+ }
1773
+ /** The watcher names the process, not the window: only the takeover's own window, where it now is, counts. */
1774
+ async isFrontWindow(front, event) {
1775
+ if (event.left === undefined || event.top === undefined)
1776
+ return false;
1777
+ try {
1778
+ const found = await front.client.send('Browser.getWindowForTarget', { targetId: front.targetId });
1779
+ const left = found?.bounds?.left;
1780
+ const top = found?.bounds?.top;
1781
+ return typeof left === 'number' && typeof top === 'number' &&
1782
+ Math.abs(left - event.left) <= QUIET_FRONT_SLACK && Math.abs(top - event.top) <= QUIET_FRONT_SLACK;
1783
+ }
1784
+ catch {
1785
+ return false;
1786
+ }
1787
+ }
1788
+ /** Nothing can tell when the person activates the window, so a waiting hidden page comes to the front now. */
1789
+ sendQuietFront() {
1790
+ const front = this.quietFront;
1791
+ this.quietFront = undefined;
1792
+ if (front !== undefined)
1793
+ void front.client.send('Page.bringToFront', {}, front.session).catch(() => undefined);
1794
+ }
1795
+ stopForeground() {
1796
+ this.foreground?.stop();
1797
+ this.foreground = undefined;
1798
+ }
1799
+ /** Move a window onto the primary display (it holds the origin), sized to fit when its page can say so, without activating it. */
1800
+ async moveOnScreen(client, windowId, session) {
1801
+ await client.send('Browser.setWindowBounds', { windowId, bounds: { left: QUIET_REVEAL_INSET, top: QUIET_REVEAL_INSET } });
1802
+ const g = session === undefined ? undefined : await windowGeometry(client, session);
1803
+ if (g !== undefined && (g.ow > g.sw - QUIET_REVEAL_INSET || g.oh > g.sh - QUIET_REVEAL_INSET)) {
1804
+ await client.send('Browser.setWindowBounds', { windowId, bounds: {
1805
+ width: Math.min(g.ow, g.sw - QUIET_REVEAL_INSET), height: Math.min(g.oh, g.sh - QUIET_REVEAL_INSET)
1806
+ } });
1807
+ }
1808
+ return g;
1809
+ }
1810
+ /**
1811
+ * Move a window quiet mode parked onto the primary display. Quiet tabs open in the background, so
1812
+ * the window may be showing an earlier tab: a person's own selection brings the page to the front.
1813
+ * `Page.bringToFront` activates the window, so for a takeover of a hidden page it waits until the
1814
+ * person activates the revealed window (where nothing watches the foreground, it is sent at once).
1815
+ * From then on the window is the person's and quiet mode never moves it.
1816
+ * @returns whether a parked window was moved.
1817
+ */
1818
+ async revealQuietWindow(handle, options) {
1819
+ const view = this.views.get(handle.id);
1820
+ const targetId = view === undefined ? undefined : this.sessions.get(view.session);
1821
+ if ((this.quietParked.size === 0 && this.quietRevealed.size === 0) || view === undefined || targetId === undefined)
1822
+ return false;
1823
+ try {
1824
+ // Asked of the browser by target id: the view's own command path would replace a closed page with a blank one.
1825
+ const found = await view.client.send('Browser.getWindowForTarget', { targetId });
1826
+ if (typeof found?.windowId !== 'number')
1827
+ return false;
1828
+ const parked = this.quietParked.delete(found.windowId);
1829
+ if (!parked && !this.quietRevealed.has(found.windowId))
1830
+ return false;
1831
+ // A window already revealed (a skipped takeover, retried) stays where the person has it; only its tab is selected.
1832
+ const g = parked ? await this.moveOnScreen(view.client, found.windowId, view.session) : await windowGeometry(view.client, view.session);
1833
+ this.quietRevealed.add(found.windowId);
1834
+ if (options?.select === true)
1835
+ await view.client.send('Page.bringToFront', {}, view.session);
1836
+ else if (g?.hidden === true) {
1837
+ const front = { client: view.client, session: view.session, targetId };
1838
+ this.quietFront = front;
1839
+ options?.until?.addEventListener('abort', () => {
1840
+ if (this.quietFront !== front)
1841
+ return;
1842
+ this.quietFront = undefined;
1843
+ if (!this.quietWatched())
1844
+ this.stopForeground();
1845
+ }, { once: true });
1846
+ this.watchQuietFocus(view.client);
1847
+ }
1848
+ if (!this.quietWatched())
1849
+ this.stopForeground();
1850
+ return parked;
1851
+ }
1852
+ catch {
1853
+ // The page went away; the command that selected it reports that itself.
1854
+ return false;
1855
+ }
1856
+ }
1490
1857
  rememberTarget(client, targetId, viewId) {
1491
1858
  let targets = this.createdTargets.get(client);
1492
1859
  if (!targets) {