dsh-builtin-browser 1.0.3 → 1.1.0
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.
- package/CHANGELOG.md +16 -1
- package/README.en.md +89 -0
- package/browser-extension/constants.mjs +20 -0
- package/browser-extension/controller.mjs +293 -0
- package/browser-extension/locales.mjs +15 -0
- package/browser-extension/manifest.json +12 -0
- package/browser-extension/options.html +14 -0
- package/browser-extension/options.mjs +9 -0
- package/browser-extension/permission-guard.mjs +13 -0
- package/browser-extension/worker.mjs +74 -0
- package/desktop-bridge/desktop-identity.json +10 -2
- package/desktop-bridge/install.mjs +28 -2
- package/docs/issue-replies-2026-11-28.md +141 -0
- package/dsh-host-patch/apply.mjs +1 -1
- package/dsh-host-patch/rc3.json +4 -4
- package/dsh-host-patch/rc5.json +4 -4
- package/dsh-host-patch/v023-alpha2.json +2 -2
- package/lib/browser-electron/bridge-status.js +24 -1
- package/lib/browser-electron/desktop-identity.js +47 -8
- package/lib/client.js +2 -1
- package/native-host/install.mjs +5 -0
- package/package.json +20 -2
- package/scripts/build-client.mjs +305 -0
- package/scripts/build.mjs +69 -0
- package/scripts/bundle-host.mjs +28 -0
- package/scripts/fix-exports.mjs +40 -0
- package/scripts/install-electron.mjs +101 -0
- package/scripts/pack.mjs +99 -0
- package/scripts/publish-manifest.mjs +56 -0
- package/scripts/verify-exports.mjs +58 -0
- package/scripts/verify-preview-sdk.mjs +93 -0
- package/skills/dsh-builtin-browser/SKILL.md +98 -0
- package/skills/dsh-builtin-browser/references/batch.md +68 -0
- package/skills/dsh-builtin-browser/references/deliver.md +31 -0
- package/skills/dsh-builtin-browser/references/locate.md +11 -0
- package/skills/dsh-builtin-browser/references/recover.md +11 -0
- package/skills/dsh-builtin-browser/references/verify.md +13 -0
- package/skills/dsh-debug-host/SKILL.md +56 -0
- package/skills/dsh-debug-self/SKILL.md +50 -0
- package/src/bridge-compatibility.ts +39 -0
- package/src/browser/anti-bot.ts +251 -0
- package/src/browser/deep-dom.ts +40 -0
- package/src/browser/handles.ts +89 -0
- package/src/browser/runtime.ts +578 -0
- package/src/browser/takeover-target.ts +45 -0
- package/src/browser/types.ts +870 -0
- package/src/browser-electron/authenticated-route.ts +109 -0
- package/src/browser-electron/automatic-maintenance.ts +736 -0
- package/src/browser-electron/bridge-auto.ts +159 -0
- package/src/browser-electron/bridge-connection.ts +386 -0
- package/src/browser-electron/bridge-endpoint.ts +129 -0
- package/src/browser-electron/bridge-install.ts +290 -0
- package/src/browser-electron/bridge-maintenance.ts +189 -0
- package/src/browser-electron/bridge-status.ts +412 -0
- package/src/browser-electron/desktop-bridge-host.ts +253 -0
- package/src/browser-electron/desktop-identity.ts +400 -0
- package/src/browser-electron/desktop-shell.ts +100 -0
- package/src/browser-electron/document-readiness.ts +45 -0
- package/src/browser-electron/electron-provision.ts +347 -0
- package/src/browser-electron/entry.ts +1378 -0
- package/src/browser-electron/ephemeral-profile.ts +189 -0
- package/src/browser-electron/extension-browser.ts +230 -0
- package/src/browser-electron/extension-setup.ts +67 -0
- package/src/browser-electron/file-write.ts +31 -0
- package/src/browser-electron/foreground-watch.ts +142 -0
- package/src/browser-electron/guest-cookie-jar.ts +177 -0
- package/src/browser-electron/guest-cookie-store.ts +59 -0
- package/src/browser-electron/guest-css-runtime.ts +76 -0
- package/src/browser-electron/guest-css.ts +68 -0
- package/src/browser-electron/guest-route.ts +716 -0
- package/src/browser-electron/guest-runtime.ts +408 -0
- package/src/browser-electron/guest-storage-runtime.ts +54 -0
- package/src/browser-electron/guest-storage.ts +120 -0
- package/src/browser-electron/history-store.ts +224 -0
- package/src/browser-electron/host-main.ts +1385 -0
- package/src/browser-electron/host-patch-maintenance.ts +121 -0
- package/src/browser-electron/http-body.ts +65 -0
- package/src/browser-electron/json-reply.ts +47 -0
- package/src/browser-electron/maintenance-broker.ts +166 -0
- package/src/browser-electron/maintenance-lifecycle.ts +91 -0
- package/src/browser-electron/maintenance-route.ts +68 -0
- package/src/browser-electron/missing-system-browser.ts +114 -0
- package/src/browser-electron/open-slot.ts +49 -0
- package/src/browser-electron/paths.ts +25 -0
- package/src/browser-electron/preferred-browser.ts +130 -0
- package/src/browser-electron/preview-route.ts +215 -0
- package/src/browser-electron/process-ownership.ts +174 -0
- package/src/browser-electron/process.ts +23 -0
- package/src/browser-electron/profile-checkpoint.ts +187 -0
- package/src/browser-electron/profile-command.ts +47 -0
- package/src/browser-electron/profile-extension.ts +129 -0
- package/src/browser-electron/profile-lease.ts +211 -0
- package/src/browser-electron/profile-residue.ts +49 -0
- package/src/browser-electron/provider-core.ts +1107 -0
- package/src/browser-electron/provider-interaction.ts +1034 -0
- package/src/browser-electron/provider-media.ts +589 -0
- package/src/browser-electron/provider-navigation.ts +323 -0
- package/src/browser-electron/provider-observation.ts +664 -0
- package/src/browser-electron/provider-tabs.ts +372 -0
- package/src/browser-electron/provider.ts +666 -0
- package/src/browser-electron/reference-route.ts +598 -0
- package/src/browser-electron/remote-host.ts +1538 -0
- package/src/browser-electron/rpc-input.ts +13 -0
- package/src/browser-electron/rpc-ops.ts +41 -0
- package/src/browser-electron/runtime-diagnostics.ts +38 -0
- package/src/browser-electron/runtime-route.ts +105 -0
- package/src/browser-electron/runtime-status.ts +309 -0
- package/src/browser-electron/settings-route.ts +64 -0
- package/src/browser-electron/settings-store.ts +593 -0
- package/src/browser-electron/shortcuts-route.ts +112 -0
- package/src/browser-electron/sidebar-only-host.ts +300 -0
- package/src/browser-electron/startpage-shortcuts.ts +213 -0
- package/src/browser-electron/system-browser.ts +1850 -0
- package/src/browser-electron/tauri-host.ts +194 -0
- package/src/browser-electron/timing.ts +16 -0
- package/src/browser-electron/virtual-cursor.ts +162 -0
- package/src/browser-electron/windows-system.ts +24 -0
- package/src/browser-reference/delivery.ts +384 -0
- package/src/browser-reference/entry.ts +631 -0
- package/src/browser-reference/export.ts +339 -0
- package/src/browser-reference/import.ts +303 -0
- package/src/browser-reference/page-script.ts +1537 -0
- package/src/browser-reference/service.ts +1346 -0
- package/src/browser-reference/store.ts +172 -0
- package/src/browser-reference/text-quote.ts +219 -0
- package/src/browser-reference/types.ts +195 -0
- package/src/browser-reference/visible.ts +367 -0
- package/src/browser-reference/web-sources.ts +106 -0
- package/src/client/apply-guard.ts +22 -0
- package/src/client/browser/BrowserController.ts +693 -0
- package/src/client/browser/BrowserFrame.ts +78 -0
- package/src/client/browser/BrowserNavigation.ts +169 -0
- package/src/client/browser/BrowserPage.ts +23 -0
- package/src/client/browser/BrowserPersistence.ts +44 -0
- package/src/client/browser/IframeImpl.ts +182 -0
- package/src/client/browser/child-tabs.ts +14 -0
- package/src/client/browser/frame-history.ts +125 -0
- package/src/client/browser/frame-state.ts +27 -0
- package/src/client/browser/iframe-reference.ts +67 -0
- package/src/client/browser/initialization.ts +262 -0
- package/src/client/browser/omnibox.ts +243 -0
- package/src/client/browser/store.ts +38 -0
- package/src/client/browser/takeover-channel.ts +72 -0
- package/src/client/browser/url.ts +46 -0
- package/src/client/browser/web-reference-source.ts +56 -0
- package/src/client/css-modules.d.ts +4 -0
- package/src/client/definition.tsx +36 -0
- package/src/client/electron/ElectronWebViewImpl.ts +371 -0
- package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
- package/src/client/electron/NativeChildPresentation.ts +53 -0
- package/src/client/electron/NativeViewPage.ts +265 -0
- package/src/client/electron/pages.ts +23 -0
- package/src/client/electron/reference-overlay.ts +53 -0
- package/src/client/electron/workspace.ts +33 -0
- package/src/client/index.ts +333 -0
- package/src/client/locales.ts +860 -0
- package/src/client/pages.ts +28 -0
- package/src/client/reference/client/BrowserRefLink.tsx +142 -0
- package/src/client/reference/client/draft-reference.ts +167 -0
- package/src/client/reference/client/index.ts +7 -0
- package/src/client/reference/client/ordered-submission.ts +108 -0
- package/src/client/reference/client/pending-delivery.ts +216 -0
- package/src/client/reference/client/plugin.ts +208 -0
- package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
- package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
- package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
- package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
- package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
- package/src/client/reference/client/production/ReferenceText.tsx +36 -0
- package/src/client/reference/client/production/assembly.ts +447 -0
- package/src/client/reference/client/production/asset-store.ts +144 -0
- package/src/client/reference/client/production/availability.ts +72 -0
- package/src/client/reference/client/production/bytes.ts +36 -0
- package/src/client/reference/client/production/composer-attachments.ts +44 -0
- package/src/client/reference/client/production/delivery-client.ts +211 -0
- package/src/client/reference/client/production/draft-adapter.ts +512 -0
- package/src/client/reference/client/production/http-transport.ts +212 -0
- package/src/client/reference/client/production/production-submission.ts +70 -0
- package/src/client/reference/client/production/protocol.ts +234 -0
- package/src/client/reference/client/production/reference-card.ts +240 -0
- package/src/client/reference/client/production/reference-labels.ts +29 -0
- package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
- package/src/client/reference/client/production/reveal.ts +215 -0
- package/src/client/reference/client/production/runtime.ts +1056 -0
- package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
- package/src/client/reference/client/production/source-marker.ts +99 -0
- package/src/client/reference/client/production/source-opener.ts +55 -0
- package/src/client/reference/client/production/styles.ts +104 -0
- package/src/client/reference/client/production/user-text-rule.ts +67 -0
- package/src/client/reference/client/reveal.ts +109 -0
- package/src/client/reference/client/scheme.ts +114 -0
- package/src/client/reference/client/session-schedule.ts +36 -0
- package/src/client/reference/client/types.ts +168 -0
- package/src/client/reference/css-modules.d.ts +4 -0
- package/src/client/reference/index.ts +11 -0
- package/src/client/reference-capture-owner.ts +162 -0
- package/src/client/reference-intents.ts +36 -0
- package/src/client/settings/index.ts +42 -0
- package/src/client/settings/mount-guard.ts +31 -0
- package/src/client/settings/panel.ts +2773 -0
- package/src/client/shortcut-open.ts +30 -0
- package/src/client/startpage/binding.ts +99 -0
- package/src/client/startpage/controller.ts +300 -0
- package/src/client/startpage/model.ts +279 -0
- package/src/client/view/Browser.module.css +751 -0
- package/src/client/view/BrowserBody.tsx +315 -0
- package/src/client/view/BrowserPresentation.ts +9 -0
- package/src/client/view/BrowserTitle.tsx +17 -0
- package/src/client/view/IframePresentation.ts +365 -0
- package/src/client/view/StartPage.tsx +598 -0
- package/src/client/view/TakeoverBanner.tsx +21 -0
- package/src/compat/host-features.ts +92 -0
- package/src/index.ts +110 -0
- package/src/reference-owner.ts +5 -0
- package/src/reference-page.ts +9 -0
- package/src/reference-source.ts +3 -0
- package/src/reference-text.ts +219 -0
- package/src/startpage-settings.ts +103 -0
- package/src/startpage.ts +71 -0
- package/src/takeover-protocol.ts +28 -0
- package/src/tool-browser/block-recovery.ts +85 -0
- package/src/tool-browser/code-tool.ts +555 -0
- package/src/tool-browser/code-worker.ts +725 -0
- package/src/tool-browser/element-fields.ts +167 -0
- package/src/tool-browser/errors.ts +40 -0
- package/src/tool-browser/index.ts +265 -0
- package/src/tool-browser/page-probe.ts +675 -0
- package/src/tool-browser/panel-page.ts +126 -0
- package/src/tool-browser/probe-client.ts +183 -0
- package/src/tool-browser/screenshot-annotations.ts +131 -0
- package/src/tool-browser/screenshot-image.ts +49 -0
- package/src/tool-browser/state.ts +375 -0
- package/src/tool-browser/takeover.ts +199 -0
- package/src/tool-browser/tools-debug.ts +806 -0
- package/src/tool-browser/tools-interaction.ts +956 -0
- package/src/tool-browser/tools-navigation.ts +786 -0
- package/src/tool-browser/tools-observation.ts +474 -0
- package/src/tool-browser/tools-reference.ts +294 -0
- package/src/types/electron-shim.d.ts +144 -0
- package/src/types.ts +85 -0
- package/src/web-guest.ts +35 -0
- package/tools/accept-desktop.mjs +148 -0
- package/dist/client.d.cts +0 -516
- package/dist/client.d.mts +0 -516
- package/dist/index.cjs +0 -92
- package/dist/index.d.mts +0 -2960
- package/dist/index.mjs +0 -24
- package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
- package/dsh-builtin-browser-1.0.3.tgz +0 -0
- package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/manifest.json +0 -218
- package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/series.json +0 -260
|
@@ -0,0 +1,1850 @@
|
|
|
1
|
+
import { PATH_NAMES, INSTALL_LOCATIONS } from '../../assets/browser-products.mjs'
|
|
2
|
+
import { CARRIER_CALL_TIMEOUT_MS, cdpVersionUrl, CDP_DEFAULT_ATTACH_PORT, CDP_ATTACH_PROBE_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
|
|
3
|
+
/**
|
|
4
|
+
* Drive the browser the user already has (Chrome / Edge / any Chromium) instead of
|
|
5
|
+
* the Electron we ship — the same approach Codex Browser Use takes.
|
|
6
|
+
*
|
|
7
|
+
* WHY
|
|
8
|
+
* The bundled Electron is a private copy with its own profile, so it can never see
|
|
9
|
+
* the logins the user already has in Chrome, and on a managed machine the user may
|
|
10
|
+
* simply prefer their own browser. Launching their browser with a *separate*
|
|
11
|
+
* `--user-data-dir` gives us a real Chromium we can drive over CDP without touching
|
|
12
|
+
* their everyday profile, bookmarks or windows: nothing of theirs is opened, locked
|
|
13
|
+
* or modified, and closing us never closes them.
|
|
14
|
+
*
|
|
15
|
+
* HOW
|
|
16
|
+
* Chromium exposes CDP on `--remote-debugging-port=0`, and writes the port it chose
|
|
17
|
+
* into `<profile>/DevToolsActivePort`. That file is the discovery mechanism — no
|
|
18
|
+
* port guessing, no collisions. From there everything is CDP over one WebSocket:
|
|
19
|
+
* `Target.createTarget` makes a page, `Target.attachToTarget` (flattened) gives a
|
|
20
|
+
* session for it, and the plugin's commands ride that session. Node 22 ships a global
|
|
21
|
+
* `WebSocket`, so this needs no dependency at all.
|
|
22
|
+
*
|
|
23
|
+
* WHAT IT IMPLEMENTS
|
|
24
|
+
* The same `ElectronBrowserViewHost` seam as the self-hosted and sidebar hosts, so
|
|
25
|
+
* the provider, the tools, history, the cursor and teardown rules are unchanged —
|
|
26
|
+
* only the carrier differs.
|
|
27
|
+
* @module dsh-browser/browser-electron/system-browser
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { readFileSync, rmSync, statSync } from 'node:fs'
|
|
31
|
+
import { existsSync } from 'node:fs'
|
|
32
|
+
import { join } from 'node:path'
|
|
33
|
+
import { acquireProfileLease, type ProfileLease } from './profile-lease.ts'
|
|
34
|
+
import { watchForeground, type ForegroundEvent, type ForegroundWatch, type ForegroundWatcher } from './foreground-watch.ts'
|
|
35
|
+
import { BrowserProcessOwnership, type ProcessOwnershipOptions } from './process-ownership.ts'
|
|
36
|
+
// Type-only: settings-store imports BrowserChannel from here, so a value import would be a cycle.
|
|
37
|
+
// `hasDisplay` lives here instead of there for the same reason — it is a runtime function.
|
|
38
|
+
import type { HeadlessMode } from './settings-store.ts'
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* How long a killed browser is given to actually exit before the launch proceeds.
|
|
42
|
+
*
|
|
43
|
+
* `kill()` only sends the signal — on Windows it is TerminateProcess, which is asynchronous —
|
|
44
|
+
* and the browser may hold this profile's singleton lock for a while afterwards. Spawning
|
|
45
|
+
* immediately meant the replacement saw a live instance, handed its command line over and
|
|
46
|
+
* exited, and that exit was reported as a bad browser path.
|
|
47
|
+
*/
|
|
48
|
+
const EXIT_GRACE_MS = 3_000
|
|
49
|
+
/**
|
|
50
|
+
* How long a browser is given to close itself after being asked, before it is killed.
|
|
51
|
+
*
|
|
52
|
+
* Long enough for Chrome to flush its profile, which is what keeps the next launch from reading
|
|
53
|
+
* the profile as crashed and offering a session restore. Deliberately not the same knob as
|
|
54
|
+
* {@link EXIT_GRACE_MS}: that one waits for a browser to die because a NEW one cannot start until
|
|
55
|
+
* it does, this one merely prefers a graceful exit to a kill.
|
|
56
|
+
*/
|
|
57
|
+
const CLOSE_GRACE_MS = 6_000
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Ceiling on one attempt to ask a discovered CDP port who it is.
|
|
61
|
+
*
|
|
62
|
+
* The launch loop below polls: it reads `DevToolsActivePort`, tries `/json/version` on the port
|
|
63
|
+
* inside it, and waits 250 ms between attempts under a 30 s deadline. An unbounded fetch can
|
|
64
|
+
* park inside one iteration for the whole budget, so a bound is needed — but it has to be
|
|
65
|
+
* small enough that the loop still behaves like a loop.
|
|
66
|
+
*
|
|
67
|
+
* The usual case is NOT a slow answer, it is NO answer: a browser that has written the file but
|
|
68
|
+
* is not listening yet refuses the connection instantly, and that immediacy is what lets the
|
|
69
|
+
* loop spin. Any timeout added here is paid on every iteration in which the port is not ready,
|
|
70
|
+
* so an earlier attempt at this used 2000 ms — eight times the poll interval — and cut the
|
|
71
|
+
* attempts available in the budget from roughly 120 to 15. This value is the same size as the
|
|
72
|
+
* interval, so a worst-case iteration costs 500 ms and the budget still affords ~60 attempts.
|
|
73
|
+
*/
|
|
74
|
+
const PORT_PROBE_MS = 250
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Starts a browser process and returns a handle to it.
|
|
78
|
+
*
|
|
79
|
+
* Injectable so tests can supply something that speaks CDP — the seam a recovery test needs
|
|
80
|
+
* and could not have while the launch was hardcoded to a stub that rejects Chromium's args.
|
|
81
|
+
* @param path - the executable to run.
|
|
82
|
+
* @param args - its arguments.
|
|
83
|
+
* @returns the child process.
|
|
84
|
+
*/
|
|
85
|
+
export type BrowserLauncher = (path: string, args: readonly string[]) => ReturnType<typeof spawn>
|
|
86
|
+
|
|
87
|
+
export interface SystemBrowserLaunchDiagnostic {
|
|
88
|
+
cleanup?: 'ownership-unverified'
|
|
89
|
+
stderrTail: string
|
|
90
|
+
exitCode: number | null
|
|
91
|
+
signal: string | null
|
|
92
|
+
devToolsActivePortPresent: boolean
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function diagnosticTail(value: string): string {
|
|
96
|
+
return value.replace(/\b(?:https?|wss?):\/\/[^\s]+/giu, '[URL redacted]')
|
|
97
|
+
.replace(/\b(authorization|cookie|password|token|secret)(\s*[:=]\s*)[^\r\n]+/giu, '$1$2[redacted]')
|
|
98
|
+
.replace(/\bBearer\s+[^\s]+/giu, 'Bearer [redacted]')
|
|
99
|
+
.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/gu, '')
|
|
100
|
+
.split('\n').slice(-12).join('\n').slice(-2048)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The real launcher: retain stderr for bounded launch diagnostics. */
|
|
104
|
+
const defaultLauncher: BrowserLauncher = (path, args) =>
|
|
105
|
+
spawn(path, [...args], { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: false })
|
|
106
|
+
import { spawn, type ChildProcess } from 'node:child_process'
|
|
107
|
+
import { randomUUID } from 'node:crypto'
|
|
108
|
+
import type { CommandOptions, ElectronBrowserViewHost, ElectronViewHandle, QuietRevealOptions } from './provider.ts'
|
|
109
|
+
import type { CarrierPage } from '../browser/types.ts'
|
|
110
|
+
import { readTabHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId, type BrowserSessionWireId, type BrowserTabWireId } from '../browser/handles.ts'
|
|
111
|
+
|
|
112
|
+
/** Which browser the user asked for. */
|
|
113
|
+
export type BrowserChannel = 'bundled' | 'electron' | 'chrome' | 'edge' | 'auto' | 'sidebar'
|
|
114
|
+
|
|
115
|
+
/** A resolved browser installation. */
|
|
116
|
+
export interface DetectedBrowser {
|
|
117
|
+
/** Which product this is. */
|
|
118
|
+
readonly kind: 'chrome' | 'edge' | 'brave'
|
|
119
|
+
/** Absolute path to the executable. */
|
|
120
|
+
readonly path: string
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Whether a browser's self-reported product name is one this carrier could have launched.
|
|
125
|
+
*
|
|
126
|
+
* `edg`, not `edge`: Edge reports itself as `Edg/155.0.4283.45`, both over HTTP and over the
|
|
127
|
+
* protocol. Testing for the full word rejected a live Edge that had just been started, so the
|
|
128
|
+
* call failed with the hand-off error this check was added to prevent — while the browser was
|
|
129
|
+
* running the whole time, answering on its own port.
|
|
130
|
+
* @param product - the product string a browser reports about itself.
|
|
131
|
+
*/
|
|
132
|
+
function isBrowserProduct(product: unknown): boolean {
|
|
133
|
+
return typeof product === 'string' && /chrome|chromium|edg/i.test(product)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Whether this process has somewhere to draw a window.
|
|
138
|
+
*
|
|
139
|
+
* The same test Chromium makes: with neither `DISPLAY` nor `WAYLAND_DISPLAY` set it cannot open a
|
|
140
|
+
* window and exits with "could not connect to display". Declared here rather than in
|
|
141
|
+
* settings-store because that module imports from this one, and a value import back would be a
|
|
142
|
+
* cycle; the equivalent export there delegates to this.
|
|
143
|
+
* @param env - the environment to inspect; defaults to the current process.
|
|
144
|
+
* @returns true when a display is advertised.
|
|
145
|
+
*/
|
|
146
|
+
function hasDisplay(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
147
|
+
// Windows and macOS use neither variable, and always have a window server.
|
|
148
|
+
if (process.platform === 'win32' || process.platform === 'darwin') return true
|
|
149
|
+
return (env.DISPLAY ?? '') !== '' || (env.WAYLAND_DISPLAY ?? '') !== ''
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Resolve `auto` into a concrete decision, and say why.
|
|
154
|
+
*
|
|
155
|
+
* Chromium refuses to start without a display: with neither `DISPLAY` nor `WAYLAND_DISPLAY` set it
|
|
156
|
+
* exits at once with "could not connect to display", and the caller sees only "exited immediately
|
|
157
|
+
* after launch (exit code 1)". That is the ordinary state of a systemd service, a container, and an
|
|
158
|
+
* SSH-only server — the deployment where a server-side browser is most useful, and the one reported
|
|
159
|
+
* as issue #32: every `dsh_browser_*` call failed, with nothing in the message pointing at the
|
|
160
|
+
* display.
|
|
161
|
+
*
|
|
162
|
+
* `auto` therefore launches headless exactly when there is no display, which leaves desktop and
|
|
163
|
+
* sidebar users with the visible window they expect. An environment override wins over the setting
|
|
164
|
+
* so an operator can fix a running deployment without editing settings: `DSH_BROWSER_HEADLESS=1`
|
|
165
|
+
* forces headless, `=0` forces a window.
|
|
166
|
+
* @param mode - the configured mode.
|
|
167
|
+
* @param env - the environment to inspect; defaults to the current process.
|
|
168
|
+
* @returns whether to launch headless, and a one-line reason for the log.
|
|
169
|
+
*/
|
|
170
|
+
function resolveLaunchMode(
|
|
171
|
+
mode: HeadlessMode,
|
|
172
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
173
|
+
): { readonly headless: boolean; readonly why: string } {
|
|
174
|
+
const override = env.DSH_BROWSER_HEADLESS
|
|
175
|
+
if (override === '1' || override === 'true') return { headless: true, why: 'DSH_BROWSER_HEADLESS' }
|
|
176
|
+
if (override === '0' || override === 'false') return { headless: false, why: 'DSH_BROWSER_HEADLESS' }
|
|
177
|
+
if (mode === 'headless') return { headless: true, why: 'browser.headless = headless' }
|
|
178
|
+
if (mode === 'windowed') return { headless: false, why: 'browser.headless = windowed' }
|
|
179
|
+
const display = hasDisplay(env)
|
|
180
|
+
return display
|
|
181
|
+
? { headless: false, why: 'a display is available' }
|
|
182
|
+
: { headless: true, why: 'no DISPLAY or WAYLAND_DISPLAY' }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Whether a target URL is one of the blanks a browser opens by itself.
|
|
187
|
+
*
|
|
188
|
+
* Deliberately narrow: `about:blank` and Chrome's own new-tab pages, and nothing else. A wider
|
|
189
|
+
* test ("has no path", "starts with chrome://") would sooner or later match a page the user is
|
|
190
|
+
* reading, and the caller closes what this returns.
|
|
191
|
+
* @param url - the target's reported URL.
|
|
192
|
+
*/
|
|
193
|
+
function isBlankUrl(url: unknown): boolean {
|
|
194
|
+
if (typeof url !== 'string') return false
|
|
195
|
+
return url === 'about:blank'
|
|
196
|
+
|| url.startsWith('chrome://newtab')
|
|
197
|
+
|| url.startsWith('chrome://new-tab-page')
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function expandLocation(location: string, env: NodeJS.ProcessEnv): string {
|
|
201
|
+
return location.replace(/%([^%]+)%/g, (whole, name: string) =>
|
|
202
|
+
env[name] ?? env[name.toUpperCase()] ?? env[name.toLowerCase()] ?? whole)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Find an executable by name on PATH.
|
|
207
|
+
*
|
|
208
|
+
* PATH is read from the supplied environment rather than the process's own, so the
|
|
209
|
+
* detection stays testable. On Windows a bare name needs its extension; elsewhere
|
|
210
|
+
* the launcher is the file itself.
|
|
211
|
+
* @param names - candidate launcher names, in preference order.
|
|
212
|
+
* @param env - the environment to read PATH from.
|
|
213
|
+
* @param platform - the platform whose PATH and extension conventions apply.
|
|
214
|
+
* @returns the first existing absolute path, or undefined.
|
|
215
|
+
*/
|
|
216
|
+
function findOnPath(names: readonly string[], env: NodeJS.ProcessEnv, platform: NodeJS.Platform): string | undefined {
|
|
217
|
+
// Windows spells it Path as often as PATH; the separator differs too.
|
|
218
|
+
const raw = env.PATH ?? env.Path ?? env.path ?? ''
|
|
219
|
+
const separator = platform === 'win32' ? ';' : ':'
|
|
220
|
+
const directories = raw.split(separator).map(entry => entry.trim()).filter(entry => entry !== '')
|
|
221
|
+
const suffixes = platform === 'win32' ? ['.exe', '.cmd', ''] : ['']
|
|
222
|
+
for (const name of names) {
|
|
223
|
+
for (const directory of directories) {
|
|
224
|
+
for (const suffix of suffixes) {
|
|
225
|
+
const candidate = join(directory, `${name}${suffix}`)
|
|
226
|
+
if (existsSync(candidate)) return candidate
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return undefined
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Find an installed Chromium browser.
|
|
235
|
+
*
|
|
236
|
+
* `auto` prefers Chrome, then Edge, then Brave — the order reflects how likely each
|
|
237
|
+
* is to be the browser a user actually chose rather than one the system shipped.
|
|
238
|
+
* Each candidate is looked up in three places, most specific first: an explicit
|
|
239
|
+
* environment override, then PATH, then the platform's conventional install
|
|
240
|
+
* locations. PATH comes before the fixed paths because it is what actually reflects
|
|
241
|
+
* how the browser was installed.
|
|
242
|
+
* @param channel - the configured choice; `bundled` / `electron` never resolve to a system browser.
|
|
243
|
+
* @param env - environment lookup, injected so tests need no real machine.
|
|
244
|
+
* @param platform - the platform to use conventions for; injected for the same reason.
|
|
245
|
+
* @returns the detected browser, or undefined when the choice is unavailable.
|
|
246
|
+
*/
|
|
247
|
+
export function detectBrowser(
|
|
248
|
+
channel: BrowserChannel,
|
|
249
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
250
|
+
platform: NodeJS.Platform = process.platform,
|
|
251
|
+
): DetectedBrowser | undefined {
|
|
252
|
+
if (channel === 'bundled' || channel === 'electron' || channel === 'sidebar') return undefined
|
|
253
|
+
const order: DetectedBrowser['kind'][] = channel === 'auto' ? ['chrome', 'edge', 'brave'] : [channel as DetectedBrowser['kind']]
|
|
254
|
+
for (const kind of order) {
|
|
255
|
+
const fromEnv = (kind === 'chrome' ? env.DSH_BROWSER_CHROME_PATH : kind === 'edge' ? env.DSH_BROWSER_EDGE_PATH : undefined)
|
|
256
|
+
if (fromEnv !== undefined && fromEnv !== '' && existsSync(fromEnv)) return { kind, path: fromEnv }
|
|
257
|
+
const onPath = findOnPath(PATH_NAMES[kind]?.[platform] ?? [], env, platform)
|
|
258
|
+
if (onPath !== undefined) return { kind, path: onPath }
|
|
259
|
+
for (const raw of INSTALL_LOCATIONS[kind]?.[platform] ?? []) {
|
|
260
|
+
const candidate = expandLocation(raw, env)
|
|
261
|
+
if (existsSync(candidate)) return { kind, path: candidate }
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return undefined
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Everything that was checked for one product, for reporting a miss.
|
|
269
|
+
*
|
|
270
|
+
* Detection returns undefined with no explanation, which left the caller able to say
|
|
271
|
+
* only "not found". This gives the user the actual list so they can see whether the
|
|
272
|
+
* plugin looked somewhere their browser is not.
|
|
273
|
+
* @param kind - the product to describe.
|
|
274
|
+
* @param platform - the platform whose names and locations apply.
|
|
275
|
+
* @returns the launcher names (as PATH lookups) and the fixed locations checked.
|
|
276
|
+
*/
|
|
277
|
+
export function searchSummary(
|
|
278
|
+
kind: DetectedBrowser['kind'],
|
|
279
|
+
platform: NodeJS.Platform = process.platform,
|
|
280
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
281
|
+
): string[] {
|
|
282
|
+
const onPath = (PATH_NAMES[kind]?.[platform] ?? []).map(name => `${name} (on PATH)`)
|
|
283
|
+
// Expanded, so the report names the location that was actually tested rather than a template
|
|
284
|
+
// the user cannot paste into a file manager.
|
|
285
|
+
const located = (INSTALL_LOCATIONS[kind]?.[platform] ?? []).map(entry => expandLocation(entry, env))
|
|
286
|
+
return [...onPath, ...located]
|
|
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
|
+
|
|
315
|
+
/** One CDP connection to a browser-level WebSocket, with flattened sessions. */
|
|
316
|
+
class CdpClient {
|
|
317
|
+
private nextId = 1
|
|
318
|
+
private readonly pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>()
|
|
319
|
+
private readonly ready: Promise<void>
|
|
320
|
+
readonly destroyedTargets = new Set<string>()
|
|
321
|
+
headless = false
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* @param url - the browser's `webSocketDebuggerUrl`.
|
|
325
|
+
*/
|
|
326
|
+
constructor(url: string) {
|
|
327
|
+
// Node 22 provides WebSocket globally; no dependency is added for this.
|
|
328
|
+
const socket = new WebSocket(url)
|
|
329
|
+
this.socket = socket
|
|
330
|
+
this.ready = new Promise<void>((resolve, reject) => {
|
|
331
|
+
socket.addEventListener('open', () => resolve())
|
|
332
|
+
socket.addEventListener('error', () => reject(new Error('dsh-builtin-browser: could not reach the browser over CDP')))
|
|
333
|
+
})
|
|
334
|
+
socket.addEventListener('message', event => this.onMessage(String((event as MessageEvent).data)))
|
|
335
|
+
socket.addEventListener('close', () => this.fail(new Error('dsh-builtin-browser: the browser closed the CDP connection')))
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
private readonly socket: WebSocket
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Resolve once the socket is open.
|
|
342
|
+
*
|
|
343
|
+
* Bounded on purpose. `ready` settles on the socket's own `open` or `error` events, and
|
|
344
|
+
* a connection that is dropped by something in between may deliver neither — in which
|
|
345
|
+
* case an unbounded await here would hang the tool call forever, because the caller's
|
|
346
|
+
* own deadline is only checked between polls and this await happens inside one of them.
|
|
347
|
+
* @returns when the handshake completed.
|
|
348
|
+
*/
|
|
349
|
+
/**
|
|
350
|
+
* Whether the socket is still usable.
|
|
351
|
+
*
|
|
352
|
+
* A dropped connection is not reported to the caller of send(); the pending command
|
|
353
|
+
* would simply never complete. Asking the socket directly is what lets a cached client
|
|
354
|
+
* be discarded instead of reused, which is the difference between a restart and a 30s
|
|
355
|
+
* hang on every subsequent call.
|
|
356
|
+
* @returns true while the socket is open.
|
|
357
|
+
*/
|
|
358
|
+
isAlive(): boolean {
|
|
359
|
+
return this.socket.readyState === WebSocket.OPEN
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async whenReady(deadline = Date.now() + CARRIER_CALL_TIMEOUT_MS): Promise<void> {
|
|
363
|
+
const timeoutMs = Math.max(1, deadline - Date.now())
|
|
364
|
+
let timer: NodeJS.Timeout | undefined
|
|
365
|
+
try {
|
|
366
|
+
await Promise.race([
|
|
367
|
+
this.ready,
|
|
368
|
+
new Promise<never>((_resolve, reject) => {
|
|
369
|
+
timer = setTimeout(
|
|
370
|
+
() => reject(new Error(`dsh-builtin-browser: the browser did not complete the CDP handshake within ${timeoutMs / 1000}s`)),
|
|
371
|
+
timeoutMs,
|
|
372
|
+
)
|
|
373
|
+
}),
|
|
374
|
+
])
|
|
375
|
+
} finally {
|
|
376
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
async whenClosed(): Promise<void> {
|
|
381
|
+
if (this.socket.readyState === WebSocket.CLOSED) return
|
|
382
|
+
await new Promise<void>(resolve => this.socket.addEventListener('close', () => resolve(), { once: true }))
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Send one CDP command, optionally on an attached session.
|
|
387
|
+
* @param method - the CDP method.
|
|
388
|
+
* @param params - its parameters.
|
|
389
|
+
* @param sessionId - the flattened session to target, when this is a page command.
|
|
390
|
+
* @returns the CDP result.
|
|
391
|
+
*/
|
|
392
|
+
async send(method: string, params?: Record<string, unknown>, sessionId?: string, timeoutMs = CARRIER_CALL_TIMEOUT_MS): Promise<unknown> {
|
|
393
|
+
// Fail fast and say why. Waiting out the timeout on a closed socket produced
|
|
394
|
+
// only "timed out", which reads as a slow page and hides the real cause.
|
|
395
|
+
if (!this.isAlive()) {
|
|
396
|
+
throw new Error('dsh-builtin-browser: the browser connection is closed (the browser window was probably closed); the next command will start it again')
|
|
397
|
+
}
|
|
398
|
+
await this.ready
|
|
399
|
+
const id = this.nextId++
|
|
400
|
+
const message = { id, method, ...params !== undefined ? { params } : {}, ...sessionId !== undefined ? { sessionId } : {} }
|
|
401
|
+
return await new Promise<unknown>((resolve, reject) => {
|
|
402
|
+
this.pending.set(id, { resolve, reject })
|
|
403
|
+
this.socket.send(JSON.stringify(message))
|
|
404
|
+
setTimeout(() => {
|
|
405
|
+
if (this.pending.delete(id)) reject(new Error(`dsh-builtin-browser: ${method} timed out`))
|
|
406
|
+
}, timeoutMs).unref?.()
|
|
407
|
+
})
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Close the socket. */
|
|
411
|
+
close(): void {
|
|
412
|
+
try { this.socket.close() } catch { /* already closed */ }
|
|
413
|
+
}
|
|
414
|
+
|
|
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
|
+
|
|
421
|
+
private onMessage(raw: string): void {
|
|
422
|
+
let message: { id?: number; method?: string; params?: unknown; result?: unknown; error?: { message?: string } }
|
|
423
|
+
try { message = JSON.parse(raw) } catch { 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
|
+
}
|
|
430
|
+
const entry = this.pending.get(message.id)
|
|
431
|
+
if (entry === undefined) return
|
|
432
|
+
this.pending.delete(message.id)
|
|
433
|
+
if (message.error !== undefined) entry.reject(new Error(`dsh-builtin-browser: CDP error: ${message.error.message ?? 'unknown'}`))
|
|
434
|
+
else entry.resolve(message.result)
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Fail everything in flight. */
|
|
438
|
+
private fail(error: Error): void {
|
|
439
|
+
const pending = [...this.pending.values()]
|
|
440
|
+
this.pending.clear()
|
|
441
|
+
for (const entry of pending) entry.reject(error)
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** A system browser driven over CDP, presented as a browser view host. */
|
|
446
|
+
export class SystemBrowserViewHost implements ElectronBrowserViewHost {
|
|
447
|
+
/**
|
|
448
|
+
* viewId -> the session that view rides, and the client that issued it.
|
|
449
|
+
*
|
|
450
|
+
* The client is part of the value on purpose. A session id means nothing to a browser other
|
|
451
|
+
* than the one that handed it out, and this host replaces browsers routinely: the process
|
|
452
|
+
* dies, or its debugging socket closes while the process lives on. Keeping only the id meant
|
|
453
|
+
* the host could start a NEW browser successfully and then send every command to it carrying
|
|
454
|
+
* a session the old one had issued — `Session with given id not found`, on every call, with a
|
|
455
|
+
* browser that answers /json/version perfectly well and nothing the user can do short of
|
|
456
|
+
* restarting DSH. Comparing identity catches it with no round trip; validating each cached
|
|
457
|
+
* session against the browser would put one on every page command.
|
|
458
|
+
*/
|
|
459
|
+
private readonly views = new Map<string, { session: string; client: CdpClient }>()
|
|
460
|
+
private disposed = false
|
|
461
|
+
/**
|
|
462
|
+
* The browser is started on FIRST USE, never on construction.
|
|
463
|
+
*
|
|
464
|
+
* A plugin that launches Chrome the moment its host loads is a plugin that takes
|
|
465
|
+
* over the machine before anyone asked it to: simply starting DSH would spawn a
|
|
466
|
+
* browser window. Registration must therefore be inert, and the process is only
|
|
467
|
+
* spawned when a view is actually needed.
|
|
468
|
+
*/
|
|
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
|
|
473
|
+
/**
|
|
474
|
+
* Set when a command went unanswered rather than being refused.
|
|
475
|
+
*
|
|
476
|
+
* A timeout says nothing about the connection: the page may simply be slow. It marks the
|
|
477
|
+
* client for a cheap check before the next command trusts it, which keeps a slow page
|
|
478
|
+
* from being mistaken for a dead browser while still catching one that has truly stopped
|
|
479
|
+
* answering.
|
|
480
|
+
*/
|
|
481
|
+
private clientSuspect = false
|
|
482
|
+
private child: ChildProcess | undefined
|
|
483
|
+
private launchParked = false
|
|
484
|
+
private profileLease: ProfileLease | undefined
|
|
485
|
+
private profileLeasing: Promise<ProfileLease> | undefined
|
|
486
|
+
private starting: Promise<CdpClient> | undefined
|
|
487
|
+
private lastLaunchError: string | undefined
|
|
488
|
+
private launchDiagnostic: SystemBrowserLaunchDiagnostic | undefined
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Browsers that ignored a kill.
|
|
492
|
+
*
|
|
493
|
+
* They are no longer this host's child — a replacement has taken that slot — but they
|
|
494
|
+
* are still running, still holding the profile, and still something release must try to
|
|
495
|
+
* stop. Forgetting them is what allowed a launch this host could not undo.
|
|
496
|
+
*/
|
|
497
|
+
private readonly stubborn: ChildProcess[] = []
|
|
498
|
+
private readonly ownership: BrowserProcessOwnership
|
|
499
|
+
private readonly ownedClients = new WeakMap<CdpClient, ChildProcess>()
|
|
500
|
+
private readonly ownedChildren = new WeakSet<ChildProcess>()
|
|
501
|
+
private readonly createdTargets = new WeakMap<CdpClient, Map<string, BrowserTabWireId>>()
|
|
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
|
|
510
|
+
constructor(
|
|
511
|
+
browser: DetectedBrowser,
|
|
512
|
+
profileDir: string,
|
|
513
|
+
extraArgs: readonly string[] = [],
|
|
514
|
+
ephemeralDir?: string,
|
|
515
|
+
launcher: BrowserLauncher = defaultLauncher,
|
|
516
|
+
/**
|
|
517
|
+
* Whether this launch should get a window. See {@link resolveLaunchMode} for how `auto` decides
|
|
518
|
+
* and why a display-less host needs headless at all (issue #32).
|
|
519
|
+
*/
|
|
520
|
+
headlessMode: HeadlessMode = 'auto',
|
|
521
|
+
isQuiet: () => boolean = () => false,
|
|
522
|
+
profileError?: string,
|
|
523
|
+
ownership: ProcessOwnershipOptions = { managed: false },
|
|
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
|
|
533
|
+
this.ownership = new BrowserProcessOwnership(browser.path, profileDir, ownership)
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
private async stopChild(child: ChildProcess): Promise<boolean> {
|
|
537
|
+
if (child.exitCode !== null || child.signalCode !== null) return true
|
|
538
|
+
if (await this.ownership.terminate(child)) return true
|
|
539
|
+
this.lastLaunchError = 'Cleanup refused: process ownership could not be verified; browser left running.'
|
|
540
|
+
if (this.launchDiagnostic) this.launchDiagnostic.cleanup = 'ownership-unverified'
|
|
541
|
+
return false
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
async prepare(): Promise<void> {
|
|
545
|
+
try {
|
|
546
|
+
await this.ensureClient()
|
|
547
|
+
} catch (error) {
|
|
548
|
+
const launch = this.connectionStatus().launch
|
|
549
|
+
if (!(error instanceof Error) || launch === undefined) throw error
|
|
550
|
+
throw Object.assign(new Error(`${error.message} Launch diagnostic: ${JSON.stringify(launch)}`, { cause: error }),
|
|
551
|
+
'code' in error ? { code: error.code } : {})
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
connectionStatus(): { connected: boolean; detail: string; launch?: SystemBrowserLaunchDiagnostic } {
|
|
556
|
+
const connected = !this.disposed && this.client?.isAlive() === true && !this.clientSuspect
|
|
557
|
+
return { connected, detail: connected ? 'Browser launched and connected over CDP.'
|
|
558
|
+
: this.profileError ?? this.lastLaunchError ?? (this.disposed ? 'Browser carrier was released.'
|
|
559
|
+
: this.starting ? 'Browser launch is in progress; no live CDP connection yet.'
|
|
560
|
+
: this.client ? 'Browser CDP connection was lost or is awaiting verification.'
|
|
561
|
+
: 'Browser has not launched; run a browser command to establish CDP. No live CDP connection.'),
|
|
562
|
+
...this.launchDiagnostic === undefined ? {} : { launch: {
|
|
563
|
+
...this.launchDiagnostic, devToolsActivePortPresent: existsSync(join(this.profileDir, 'DevToolsActivePort')),
|
|
564
|
+
} },
|
|
565
|
+
}
|
|
566
|
+
}
|
|
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
|
+
|
|
589
|
+
/** Which product this host would drive (for diagnostics). */
|
|
590
|
+
get kind(): DetectedBrowser['kind'] {
|
|
591
|
+
return this.browser.kind
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** Whether the browser has actually been started yet (diagnostics and tests). */
|
|
595
|
+
get started(): boolean {
|
|
596
|
+
return this.child !== undefined
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* The CDP client, starting the browser on first use.
|
|
601
|
+
* @returns the connected client.
|
|
602
|
+
*/
|
|
603
|
+
/**
|
|
604
|
+
* Whether a client that reports itself open is actually answering.
|
|
605
|
+
*
|
|
606
|
+
* An open socket proves nothing: a browser can hold the connection and never reply, and
|
|
607
|
+
* that state must not be cached, or every later command waits out its own timeout. Asking
|
|
608
|
+
* the browser something cheap is a fact; reading the failure text is a guess, and the
|
|
609
|
+
* guess was wrong in both directions (it killed healthy browsers on a slow page, and it
|
|
610
|
+
* mistook the browser's own free text for a verdict).
|
|
611
|
+
*
|
|
612
|
+
* This is only reached when the socket is open, so the common path costs nothing.
|
|
613
|
+
* @param client - the client to question.
|
|
614
|
+
* @returns true when it answered.
|
|
615
|
+
*/
|
|
616
|
+
private async probeClient(client: CdpClient): Promise<boolean> {
|
|
617
|
+
try {
|
|
618
|
+
// The command budget (30s) on purpose, not a shorter "probe" value, because of what the
|
|
619
|
+
// answer is used for: a false verdict discards the client and replaces the browser,
|
|
620
|
+
// which KILLS the window the human is looking at. A page that is merely slow must not
|
|
621
|
+
// lose its browser, so this errs toward waiting. The price is that a truly wedged
|
|
622
|
+
// browser takes the full budget to be declared dead — the tool call that triggered the
|
|
623
|
+
// probe answers first, and its timeout is the error the caller sees. Trading a later
|
|
624
|
+
// error for a window that is not destroyed is the right way round.
|
|
625
|
+
await client.send('Browser.getVersion', {})
|
|
626
|
+
return true
|
|
627
|
+
} catch {
|
|
628
|
+
// No answer within the budget, or the socket failed while asking: unusable either way.
|
|
629
|
+
return false
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Forget which browser issued what, after that browser is gone.
|
|
635
|
+
*
|
|
636
|
+
* The two maps must move together: `views` maps a view id to a session id and `sessions`
|
|
637
|
+
* maps a session id to a target id, so clearing one alone leaves a mapping the next command
|
|
638
|
+
* will act on. Every path that abandons a browser calls this rather than spelling the pair
|
|
639
|
+
* out — four separate copies is how the third one came to be missing.
|
|
640
|
+
*/
|
|
641
|
+
private forgetBrowserState(): void {
|
|
642
|
+
this.views.clear()
|
|
643
|
+
this.sessions.clear()
|
|
644
|
+
this.quietParked.clear()
|
|
645
|
+
this.parkedTargets.clear()
|
|
646
|
+
this.quietFront = undefined
|
|
647
|
+
this.quietRevealed.clear()
|
|
648
|
+
this.stopForeground()
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
private async ensureClient(): Promise<CdpClient> {
|
|
652
|
+
// A disposed host must never start a browser: doing so would spawn a process
|
|
653
|
+
// nobody owns and nobody will kill.
|
|
654
|
+
if (this.disposed) throw new Error('dsh-builtin-browser: this browser host was released')
|
|
655
|
+
if (this.profileError !== undefined) throw new Error(this.profileError)
|
|
656
|
+
// The exit listener clears this, but a socket can also die without the process doing so
|
|
657
|
+
// (the browser closing its debugging endpoint, a dropped connection). Checking the
|
|
658
|
+
// socket's own state costs nothing and turns a 30s hang into a restart.
|
|
659
|
+
if (this.client !== undefined) {
|
|
660
|
+
// A closed socket means the browser is gone; an OPEN socket proves nothing, because
|
|
661
|
+
// a browser can hold the connection and never answer. Only probe when the socket is
|
|
662
|
+
// closed or a previous command went unanswered without being refused — probing every
|
|
663
|
+
// call would add a round trip to the common path for nothing.
|
|
664
|
+
const current = this.client
|
|
665
|
+
if (current.isAlive() && !this.clientSuspect) return current
|
|
666
|
+
if (current.isAlive() && await this.probeClient(current)) {
|
|
667
|
+
this.clientSuspect = false
|
|
668
|
+
return current
|
|
669
|
+
}
|
|
670
|
+
current.close()
|
|
671
|
+
this.client = undefined
|
|
672
|
+
this.clientSuspect = false
|
|
673
|
+
// Everything this client issued dies with it. `start()` clears these too, but only
|
|
674
|
+
// inside its "kill the old child" branch — and the shape of this failure usually has no
|
|
675
|
+
// child left to kill: the process already exited, its exit listener already set
|
|
676
|
+
// `this.child` to undefined, so start() skips that branch and publishes a new browser
|
|
677
|
+
// while the views still point at the dead one. That is the state that never recovers.
|
|
678
|
+
this.forgetBrowserState()
|
|
679
|
+
}
|
|
680
|
+
// Concurrent first calls share one startup rather than racing two browsers.
|
|
681
|
+
this.starting ??= this.start().then(client => {
|
|
682
|
+
this.lastLaunchError = undefined
|
|
683
|
+
return client
|
|
684
|
+
}).catch(error => {
|
|
685
|
+
this.lastLaunchError = error instanceof Error ? error.message : String(error)
|
|
686
|
+
throw error
|
|
687
|
+
}).finally(() => { this.starting = undefined })
|
|
688
|
+
return await this.starting
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Take over a browser already serving this profile, instead of racing it.
|
|
693
|
+
*
|
|
694
|
+
* A previous DSH process leaves its browser running: the child handle died with that process, so
|
|
695
|
+
* nothing here knows about it, and `start()`'s cleanup branch is skipped because it keys on
|
|
696
|
+
* `this.child`. Launching then does something worse than fail — on Windows Chrome hands the
|
|
697
|
+
* request to the instance already holding the profile and exits 0, and that exit is read as a
|
|
698
|
+
* launch failure. The user is told to go kill the leftovers by hand, on every restart, which is
|
|
699
|
+
* exactly what was reported.
|
|
700
|
+
*
|
|
701
|
+
* The launch loop deliberately refuses to trust a `<profile>/DevToolsActivePort` left by a
|
|
702
|
+
* previous launch, and it is right to: a stale port number can be reused by something that is
|
|
703
|
+
* not a browser at all. What makes adoption safe HERE is that this runs BEFORE launching, on a
|
|
704
|
+
* file that lives inside this plugin's own profile directory — only a browser started with this
|
|
705
|
+
* `--user-data-dir` writes it — and the endpoint is then asked to identify itself.
|
|
706
|
+
* @param _why - a short phrase for the log, naming which attempt this is.
|
|
707
|
+
* @returns a connected client for the running browser, or undefined when there is none.
|
|
708
|
+
*/
|
|
709
|
+
private async adoptRunningBrowser(_why: string, explicitPort?: number, deadline = Date.now() + CARRIER_CALL_TIMEOUT_MS): Promise<CdpClient | undefined> {
|
|
710
|
+
const portFile = join(this.profileDir, 'DevToolsActivePort')
|
|
711
|
+
let port: number
|
|
712
|
+
if (typeof explicitPort === 'number' && explicitPort > 0) {
|
|
713
|
+
port = explicitPort
|
|
714
|
+
} else try {
|
|
715
|
+
if (!existsSync(portFile)) return undefined
|
|
716
|
+
const value = Number(readFileSync(portFile, 'utf8').split('\n')[0]?.trim() ?? '')
|
|
717
|
+
if (!Number.isInteger(value) || value <= 0) return undefined
|
|
718
|
+
port = value
|
|
719
|
+
} catch {
|
|
720
|
+
return undefined
|
|
721
|
+
}
|
|
722
|
+
let client: CdpClient | undefined
|
|
723
|
+
let identified = false
|
|
724
|
+
try {
|
|
725
|
+
const version = await (await fetch(cdpVersionUrl(port), {
|
|
726
|
+
signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())),
|
|
727
|
+
})).json() as { webSocketDebuggerUrl?: string; Browser?: string }
|
|
728
|
+
if (typeof version.webSocketDebuggerUrl !== 'string') return undefined
|
|
729
|
+
// The port number alone proves nothing — it can be reused once the browser that owned it
|
|
730
|
+
// exits. The endpoint's own answer is the evidence, and it has to name a browser.
|
|
731
|
+
if (!isBrowserProduct(version.Browser)) return undefined
|
|
732
|
+
identified = true
|
|
733
|
+
client = new CdpClient(version.webSocketDebuggerUrl)
|
|
734
|
+
await client.whenReady(deadline)
|
|
735
|
+
// Asked through the protocol too, so a websocket that merely accepts connections is not
|
|
736
|
+
// mistaken for a browser that answers.
|
|
737
|
+
const info = await client.send('Browser.getVersion', {}, undefined, Math.max(1, deadline - Date.now())) as { product?: string }
|
|
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 ?? '')
|
|
740
|
+
if (this.disposed) { client.close(); return undefined }
|
|
741
|
+
await client.send('Target.setDiscoverTargets', { discover: true }, undefined, Math.max(1, deadline - Date.now()))
|
|
742
|
+
if (this.disposed || Date.now() >= deadline) { client.close(); return undefined }
|
|
743
|
+
this.launchParked = false
|
|
744
|
+
this.client = client
|
|
745
|
+
this.placeOpenedWindows(client)
|
|
746
|
+
this.plainUserAgent = undefined
|
|
747
|
+
return client
|
|
748
|
+
} catch (error) {
|
|
749
|
+
client?.close()
|
|
750
|
+
if (identified) throw error
|
|
751
|
+
if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
|
|
752
|
+
throw new Error('browser did not acknowledge its discovery endpoint before the launch deadline', { cause: error })
|
|
753
|
+
}
|
|
754
|
+
// No endpoint, nothing listening, or not a browser: all of them mean "launch one".
|
|
755
|
+
return undefined
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* Launch the browser with a private profile and connect over CDP.
|
|
761
|
+
*
|
|
762
|
+
* `--remote-debugging-port=0` plus the `DevToolsActivePort` file is the only
|
|
763
|
+
* reliable way to learn the port: a fixed port collides with whatever else the
|
|
764
|
+
* machine is running, and parsing stderr is fragile across versions.
|
|
765
|
+
* @returns the connected client.
|
|
766
|
+
*/
|
|
767
|
+
private async start(): Promise<CdpClient> {
|
|
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
|
+
}
|
|
774
|
+
// Before spawning anything: is a browser for THIS profile already running? A DSH restart
|
|
775
|
+
// leaves one behind, and launching into it is the failure reported as "exited immediately
|
|
776
|
+
// after launch (exit code 0)" that required killing seven processes by hand.
|
|
777
|
+
// A browser the human started with an explicit debugging port. Port 0 makes Chromium write the chosen
|
|
778
|
+
// port into the profile, which the probe below already finds; an explicit port leaves no file, so this
|
|
779
|
+
// is the only way to reach it. Attaching means driving the window they already have open.
|
|
780
|
+
const explicitPort = Number(process.env.DSH_BROWSER_ATTACH_PORT ?? '')
|
|
781
|
+
const attached = Number.isSafeInteger(explicitPort) && explicitPort > 0
|
|
782
|
+
? await this.adoptRunningBrowser('explicit attach port', explicitPort, deadline) : undefined
|
|
783
|
+
if (attached !== undefined) {
|
|
784
|
+
;(globalThis as unknown as Record<string, unknown>).__dshBrowserCarrier = 'attached'
|
|
785
|
+
return attached
|
|
786
|
+
}
|
|
787
|
+
const adopted = await this.adoptRunningBrowser('before launch', undefined, deadline)
|
|
788
|
+
if (adopted !== undefined) return adopted
|
|
789
|
+
// Whether a window exists is decided by `browser.headless` ALONE (plus the operator's
|
|
790
|
+
// DSH_BROWSER_HEADLESS override inside resolveLaunchMode). `ui.quiet` must not force
|
|
791
|
+
// headless: it describes how the agent presents its work — no activation, no raising,
|
|
792
|
+
// background targets — not whether the human is allowed to see a browser at all.
|
|
793
|
+
// Overriding the setting here made an explicit `headless: windowed`/`headed` invisible on
|
|
794
|
+
// Chrome/Edge, so the human could not take over a login or a challenge, and an already
|
|
795
|
+
// headless process cannot become visible by toggling quiet later. Quiet still governs
|
|
796
|
+
// presentView() and createTarget() below, which is where activation belongs.
|
|
797
|
+
const launch = resolveLaunchMode(this.headlessMode)
|
|
798
|
+
const args = [
|
|
799
|
+
'--remote-debugging-port=0',
|
|
800
|
+
`--user-data-dir=${this.profileDir}`,
|
|
801
|
+
// Behave like a fresh, unattended browser: no first-run UI, no default-browser
|
|
802
|
+
// prompt, no restore bubble, and no "Chrome is being controlled" infobar.
|
|
803
|
+
'--no-first-run',
|
|
804
|
+
'--no-default-browser-check',
|
|
805
|
+
'--disable-features=Translate,MediaRouter',
|
|
806
|
+
'--disable-session-crashed-bubble',
|
|
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',
|
|
817
|
+
// Headless only where there is nothing to draw on. `--headless=new` rather than the legacy
|
|
818
|
+
// flag: the new mode behaves like a windowed browser, which matters because every command
|
|
819
|
+
// here was written and measured against one — including CDP input, which Chromium silently
|
|
820
|
+
// drops for a view it believes has no display surface. `--disable-gpu` and
|
|
821
|
+
// `--disable-dev-shm-usage` are what make that mode usable on a server: no GPU, and a
|
|
822
|
+
// /dev/shm far smaller than a desktop. See resolveLaunchMode for why this is conditional.
|
|
823
|
+
...launch.headless ? ['--headless=new', '--disable-gpu', '--disable-dev-shm-usage'] : [],
|
|
824
|
+
...this.extraArgs,
|
|
825
|
+
// NOT `about:blank`. Every page this plugin drives is created by `Target.createTarget` when a
|
|
826
|
+
// session first needs one (`buildSession`, which adopts a blank if the browser opened one and
|
|
827
|
+
// creates one otherwise), so a startup page is a tab nobody asked for and nobody closes: the
|
|
828
|
+
// tab strip showed `about:blank` next to the real page while `dsh_browser_list_tabs` reported
|
|
829
|
+
// only the real one. Reported as issue #33, banner and all.
|
|
830
|
+
//
|
|
831
|
+
// `--no-startup-window` keeps the browser alive with no window and no initial page; measured
|
|
832
|
+
// by the reporter on Chrome 156 as writing DevToolsActivePort in 599 ms, answering
|
|
833
|
+
// `/json/version`, listing two extension targets and no page, and then creating windows
|
|
834
|
+
// normally through `Target.createTarget`.
|
|
835
|
+
'--no-startup-window',
|
|
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}`)
|
|
841
|
+
if (launch.headless) {
|
|
842
|
+
process.stderr.write(`[dsh-browser] launching headless (${launch.why}); `
|
|
843
|
+
+ 'the browser has no window but every tool works the same\n')
|
|
844
|
+
}
|
|
845
|
+
// A browser from a previous attempt may still be running with this same
|
|
846
|
+
// --user-data-dir. On Windows the new one would merely hand off to it and exit, and that
|
|
847
|
+
// exit would then be treated as the launch failing.
|
|
848
|
+
if (this.child !== undefined) {
|
|
849
|
+
const dying = this.child
|
|
850
|
+
if (!await this.stopChild(dying)) throw new Error(this.lastLaunchError)
|
|
851
|
+
this.child = undefined
|
|
852
|
+
|
|
853
|
+
// Whatever the old browser issued is worthless now, and its exit listener cannot clean
|
|
854
|
+
// up after itself: this.child is reassigned below, so the old child's exit event returns
|
|
855
|
+
// early and the session ids it handed out would be reused against a browser that never
|
|
856
|
+
// heard of them — the "Session with given id not found" loop, which never clears.
|
|
857
|
+
this.client?.close()
|
|
858
|
+
this.client = undefined
|
|
859
|
+
this.forgetBrowserState()
|
|
860
|
+
|
|
861
|
+
// Wait for it to actually die. kill() only sends the signal: on Windows it is
|
|
862
|
+
// TerminateProcess, which is asynchronous, and the browser may still hold this profile's
|
|
863
|
+
// singleton lock for a while. Spawning immediately meant the replacement saw an existing
|
|
864
|
+
// instance, handed its command line over and exited — and that exit was then reported as
|
|
865
|
+
// "check that the path is a runnable browser", blaming the user's install for a race this
|
|
866
|
+
// code created. Bounded, because a process that refuses to die must not hang the call.
|
|
867
|
+
await new Promise<void>(resolve => {
|
|
868
|
+
if (dying.exitCode !== null || dying.signalCode !== null) { resolve(); return }
|
|
869
|
+
const done = (): void => { clearTimeout(timer); resolve() }
|
|
870
|
+
const timer = setTimeout(done, EXIT_GRACE_MS)
|
|
871
|
+
dying.once('exit', done)
|
|
872
|
+
// It did not exit in time. Dropping the reference here was how this host could
|
|
873
|
+
// launch a browser it could never kill again: dispose() only knows about this.child,
|
|
874
|
+
// and this process still holds the profile's singleton lock. Remember it so release
|
|
875
|
+
// still reaches it.
|
|
876
|
+
if (dying.exitCode === null && dying.signalCode === null) this.stubborn.push(dying)
|
|
877
|
+
dying.once('exit', () => {
|
|
878
|
+
const at2 = this.stubborn.indexOf(dying)
|
|
879
|
+
if (at2 !== -1) this.stubborn.splice(at2, 1)
|
|
880
|
+
})
|
|
881
|
+
})
|
|
882
|
+
if (dying.exitCode === null && dying.signalCode === null) throw new Error('dsh-builtin-browser: the previous browser still holds this profile; refusing another launch')
|
|
883
|
+
}
|
|
884
|
+
// The port file is deliberately NOT deleted here, and that is a reversal.
|
|
885
|
+
//
|
|
886
|
+
// It used to be removed so the launch loop below could not read a previous browser's port. But
|
|
887
|
+
// the loop judges freshness against a snapshot taken below, so the deletion never protected it
|
|
888
|
+
// — while it DID destroy the only record of a browser that may still be running for this
|
|
889
|
+
// profile. That record is what `adoptRunningBrowser` needs when the launch comes back as a
|
|
890
|
+
// hand-off: the browser was alive the whole time, and without the file there is no way to find
|
|
891
|
+
// it again.
|
|
892
|
+
const portFile = join(this.profileDir, 'DevToolsActivePort')
|
|
893
|
+
/**
|
|
894
|
+
* What the port file was like BEFORE this launch, so "fresh" is judged against a snapshot
|
|
895
|
+
* rather than against a clock.
|
|
896
|
+
*
|
|
897
|
+
* The test used to be `mtimeMs < spawnedAt` — a filesystem timestamp compared to `Date.now()`.
|
|
898
|
+
* Those are different clocks with different resolutions, and CI is where it showed: a file the
|
|
899
|
+
* fake browser had just written was rejected as stale, so the loop waited out its full 30s
|
|
900
|
+
* against a browser that was already listening, because the file's mtime had rounded down
|
|
901
|
+
* below the spawn time. That is not a test-only problem: on any filesystem whose mtime
|
|
902
|
+
* resolution is coarser than a millisecond, the plugin would fail to see the browser it had
|
|
903
|
+
* just launched, and report a CDP timeout for a browser that was up the whole time.
|
|
904
|
+
*
|
|
905
|
+
* `undefined` means there was no file, so any file that appears afterwards is fresh. When one
|
|
906
|
+
* existed, a later mtime OR different contents makes the new one fresh. Byte-identical contents
|
|
907
|
+
* with an unchanged mtime is the PREVIOUS browser's port, and adopting it is what this whole
|
|
908
|
+
* check exists to prevent: it may name a port that now belongs to something else entirely.
|
|
909
|
+
*/
|
|
910
|
+
const portFileBefore = ((): { mtimeMs: number; contents: string } | undefined => {
|
|
911
|
+
try {
|
|
912
|
+
return { mtimeMs: statSync(portFile).mtimeMs, contents: readFileSync(portFile, 'utf8') }
|
|
913
|
+
} catch {
|
|
914
|
+
return undefined
|
|
915
|
+
}
|
|
916
|
+
})()
|
|
917
|
+
let child: ReturnType<typeof spawn>
|
|
918
|
+
if (this.disposed || Date.now() >= deadline) throw new Error('dsh-builtin-browser: launch was cancelled or its deadline expired')
|
|
919
|
+
const launchDiagnostic: SystemBrowserLaunchDiagnostic = {
|
|
920
|
+
stderrTail: '', exitCode: null, signal: null, devToolsActivePortPresent: existsSync(portFile),
|
|
921
|
+
}
|
|
922
|
+
this.launchDiagnostic = launchDiagnostic
|
|
923
|
+
try {
|
|
924
|
+
child = this.launcher(this.browser.path, args)
|
|
925
|
+
} catch (error) {
|
|
926
|
+
// spawn throws synchronously for some targets (a .cmd on Windows, a path that cannot
|
|
927
|
+
// be executed). Without this the exception escaped start() and skipped every
|
|
928
|
+
// diagnostic below it.
|
|
929
|
+
throw new Error(`dsh-builtin-browser: could not launch ${this.browser.path}: ${error instanceof Error ? error.message : String(error)}`)
|
|
930
|
+
}
|
|
931
|
+
this.child = child
|
|
932
|
+
launchDiagnostic.exitCode = child.exitCode
|
|
933
|
+
launchDiagnostic.signal = child.signalCode
|
|
934
|
+
child.on('exit', (code, signal) => {
|
|
935
|
+
launchDiagnostic.exitCode = code ?? child.exitCode
|
|
936
|
+
launchDiagnostic.signal = signal ?? child.signalCode
|
|
937
|
+
})
|
|
938
|
+
/**
|
|
939
|
+
* A launch that fails (ENOENT, no permission, a broken binary) is reported by an
|
|
940
|
+
* asynchronous 'error' event on the child, NOT by a throw here and NOT by exitCode.
|
|
941
|
+
* Without this listener Node treats it as unhandled and takes the whole host process
|
|
942
|
+
* down — one bad browser path would kill DSH, not just fail a tool call.
|
|
943
|
+
*/
|
|
944
|
+
let launchError: Error | undefined
|
|
945
|
+
let diagnostic = ''
|
|
946
|
+
child.stderr?.on('data', chunk => {
|
|
947
|
+
diagnostic = (diagnostic + String(chunk)).slice(-4096)
|
|
948
|
+
launchDiagnostic.stderrTail = diagnosticTail(diagnostic)
|
|
949
|
+
if (/remote debugging requires a non-default data directory/iu.test(diagnostic)) {
|
|
950
|
+
launchError = new Error('The browser refused remote debugging on its default user profile. A live CDP connection is required; no alternative profile was substituted.')
|
|
951
|
+
}
|
|
952
|
+
})
|
|
953
|
+
child.on('error', error => {
|
|
954
|
+
launchError = error
|
|
955
|
+
launchDiagnostic.exitCode = child.exitCode
|
|
956
|
+
launchDiagnostic.signal = child.signalCode
|
|
957
|
+
})
|
|
958
|
+
// A browser that exits later is as unusable as one that never started, and the failure
|
|
959
|
+
// has to reach the NEXT call rather than being swallowed: clearing the client here is
|
|
960
|
+
// what makes ensureClient() start a fresh browser instead of returning a socket to a
|
|
961
|
+
// dead process and letting every command time out.
|
|
962
|
+
child.on('exit', () => {
|
|
963
|
+
if (this.child !== child) return
|
|
964
|
+
this.client?.close()
|
|
965
|
+
this.client = undefined
|
|
966
|
+
this.child = undefined
|
|
967
|
+
this.lastLaunchError = 'Browser exited; the CDP connection is no longer live.'
|
|
968
|
+
// The pages this client opened belong to the process that just died; keeping their
|
|
969
|
+
// session ids means every later command is sent to a browser that never issued them.
|
|
970
|
+
// Clearing these is what makes the restart usable rather than merely alive.
|
|
971
|
+
this.forgetBrowserState()
|
|
972
|
+
})
|
|
973
|
+
await this.ownership.capture(child)
|
|
974
|
+
/**
|
|
975
|
+
* The port this launch wrote, or undefined while it has not written one yet.
|
|
976
|
+
*
|
|
977
|
+
* A file left by the PREVIOUS browser is not evidence about this one. Its contents name a port
|
|
978
|
+
* that may now belong to something else entirely — another Chromium, a `node --inspect` — and
|
|
979
|
+
* connecting there publishes a client this host does not own and dispose() can never kill.
|
|
980
|
+
* Only a file that CHANGED across this launch counts, which is what `portFileBefore` records.
|
|
981
|
+
*/
|
|
982
|
+
const freshPort = (): number | undefined => {
|
|
983
|
+
try {
|
|
984
|
+
if (!existsSync(portFile)) return undefined
|
|
985
|
+
const after = statSync(portFile)
|
|
986
|
+
const contents = readFileSync(portFile, 'utf8')
|
|
987
|
+
// Unchanged since before the launch: this is the previous browser's file, whatever its
|
|
988
|
+
// mtime says. Comparing against the snapshot rather than a wall-clock instant is what
|
|
989
|
+
// keeps this correct on a filesystem whose timestamps are coarser than a millisecond.
|
|
990
|
+
if (portFileBefore !== undefined
|
|
991
|
+
&& after.mtimeMs <= portFileBefore.mtimeMs
|
|
992
|
+
&& contents === portFileBefore.contents && child.exitCode !== 0) return undefined
|
|
993
|
+
const value = Number(contents.split('\n')[0]?.trim() ?? '')
|
|
994
|
+
return Number.isInteger(value) && value > 0 ? value : undefined
|
|
995
|
+
} catch {
|
|
996
|
+
return undefined
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* Why the loop stopped, so the failure can say what actually happened. Reporting
|
|
1001
|
+
* every ending as "did not expose CDP within 30s" was wrong three ways: the cause,
|
|
1002
|
+
* the words, and the elapsed time — a browser that cannot be launched says so in
|
|
1003
|
+
* half a second, and the caller then looks for a CDP problem that does not exist.
|
|
1004
|
+
*/
|
|
1005
|
+
let stopped: 'released' | 'timeout' | 'exited' | 'launch-failed' = 'timeout'
|
|
1006
|
+
for (;;) {
|
|
1007
|
+
// Released while we were starting: stop here rather than keep polling for a
|
|
1008
|
+
// browser that dispose() has already killed, which would leave a connection
|
|
1009
|
+
// to a dead process behind. The child is killed here too — dispose() may have
|
|
1010
|
+
// run before this child was recorded, leaving nobody else to do it.
|
|
1011
|
+
if (this.disposed) { await this.stopChild(child); if (this.child === child) this.child = undefined; stopped = 'released'; break }
|
|
1012
|
+
if (launchError !== undefined) { if (this.child === child) this.child = undefined; stopped = 'launch-failed'; break }
|
|
1013
|
+
if (Date.now() > deadline) { await this.stopChild(child); stopped = 'timeout'; break }
|
|
1014
|
+
// signalCode too: a browser killed by a signal never sets exitCode, so checking exitCode
|
|
1015
|
+
// alone made a killed browser look alive and the launch run out its full 30s deadline
|
|
1016
|
+
// before reporting "did not expose CDP" — a timeout for something that died at once.
|
|
1017
|
+
// The sibling check on the release path already looked at both.
|
|
1018
|
+
if (child.signalCode !== null || (child.exitCode !== null && child.exitCode !== 0)) { if (this.child === child) this.child = undefined; stopped = 'exited'; break }
|
|
1019
|
+
// Only a port THIS launch wrote: reading whatever file happened to be there is how a
|
|
1020
|
+
// restart could adopt the previous browser, or any process now holding that port.
|
|
1021
|
+
const port = freshPort()
|
|
1022
|
+
if (port !== undefined) {
|
|
1023
|
+
try {
|
|
1024
|
+
const version = await (await fetch(cdpVersionUrl(port), {
|
|
1025
|
+
// Bounded: an unanswered loopback request would otherwise park inside this
|
|
1026
|
+
// iteration for the rest of the budget, and the deadline above is only re-checked
|
|
1027
|
+
// between iterations. Deliberately no larger than the 250 ms sleep — see
|
|
1028
|
+
// PORT_PROBE_MS.
|
|
1029
|
+
signal: AbortSignal.timeout(Math.max(1, Math.min(PORT_PROBE_MS, deadline - Date.now()))),
|
|
1030
|
+
})).json() as { webSocketDebuggerUrl?: string; Browser?: string }
|
|
1031
|
+
if (typeof version.webSocketDebuggerUrl === 'string') {
|
|
1032
|
+
const client = new CdpClient(version.webSocketDebuggerUrl)
|
|
1033
|
+
// `whenReady` has its own 30 s ceiling, and it is reached only after the port
|
|
1034
|
+
// answered above — so the browser is listening and this is a handshake, not a
|
|
1035
|
+
// discovery. A handshake that outlives the launch is reported as the timeout it
|
|
1036
|
+
// is, by the same deadline that governs everything else here.
|
|
1037
|
+
try {
|
|
1038
|
+
await client.whenReady(deadline)
|
|
1039
|
+
const info = await client.send('Browser.getVersion', {}, undefined, Math.max(1, deadline - Date.now())) as { product?: string }
|
|
1040
|
+
if (typeof info.product !== 'string' || info.product === '' || info.product !== version.Browser) throw Object.assign(new Error('browser did not acknowledge its identity'), { code: 'BROWSER_LAUNCH_UNACKNOWLEDGED' })
|
|
1041
|
+
await client.send('Target.setDiscoverTargets', { discover: true }, undefined, Math.max(1, deadline - Date.now()))
|
|
1042
|
+
} catch (error) { client.close(); throw error }
|
|
1043
|
+
// Still wanted? A dispose() during the handshake has already killed the
|
|
1044
|
+
// process, so publishing the client would leave a dangling connection.
|
|
1045
|
+
if (this.disposed || Date.now() >= deadline) { client.close(); break }
|
|
1046
|
+
if (await this.ownership.verify(child)) {
|
|
1047
|
+
try {
|
|
1048
|
+
const processes = await client.send('SystemInfo.getProcessInfo', {}, undefined, 1000) as { processInfo?: { type: string; id: number }[] }
|
|
1049
|
+
if (processes.processInfo?.some(entry => entry.type === 'browser' && entry.id === child.pid)
|
|
1050
|
+
&& await this.ownership.verify(child)) {
|
|
1051
|
+
this.ownedClients.set(client, child)
|
|
1052
|
+
this.ownedChildren.add(child)
|
|
1053
|
+
}
|
|
1054
|
+
} catch { /* An unidentified endpoint is borrowed, never owned. */ }
|
|
1055
|
+
}
|
|
1056
|
+
if (this.disposed) { client.close(); break }
|
|
1057
|
+
client.headless = launch.headless
|
|
1058
|
+
this.client = client
|
|
1059
|
+
this.placeOpenedWindows(client)
|
|
1060
|
+
this.plainUserAgent = undefined
|
|
1061
|
+
return client
|
|
1062
|
+
}
|
|
1063
|
+
} catch (error) {
|
|
1064
|
+
if ((error as { code?: string })?.code === 'BROWSER_LAUNCH_UNACKNOWLEDGED') throw error
|
|
1065
|
+
// The file can exist a moment before the port answers; poll again.
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
await new Promise(resolve => setTimeout(resolve, 250))
|
|
1069
|
+
}
|
|
1070
|
+
// Each ending gets its own message. The old single message blamed a CDP timeout for
|
|
1071
|
+
// all of them, which sent the reader looking for a port problem when the browser had
|
|
1072
|
+
// simply failed to launch.
|
|
1073
|
+
const target = `${this.browser.kind} (${this.browser.path})`
|
|
1074
|
+
if (stopped === 'launch-failed') {
|
|
1075
|
+
throw new Error(`dsh-builtin-browser: could not launch ${target}: ${launchError?.message ?? 'unknown error'}`)
|
|
1076
|
+
}
|
|
1077
|
+
if (stopped === 'exited') {
|
|
1078
|
+
// Only exit code 0 is the hand-off story. A non-zero code or a signal means the browser
|
|
1079
|
+
// died on its own — a crash, a missing library, a sandbox refusal — and asserting the
|
|
1080
|
+
// profile story for those sent people looking for a leftover process that was not there,
|
|
1081
|
+
// which is the same mistake this message was written to correct, pointing the other way.
|
|
1082
|
+
const code = child.exitCode
|
|
1083
|
+
const signal = child.signalCode
|
|
1084
|
+
throw new Error(
|
|
1085
|
+
`dsh-builtin-browser: ${target} exited immediately after launch `
|
|
1086
|
+
+ `(${signal !== null ? `killed by ${signal}` : `exit code ${String(code)}`}), so it did not `
|
|
1087
|
+
+ 'hand the request anywhere — the browser failed to start rather than deferring to another '
|
|
1088
|
+
+ 'instance. Check that it can run at all: run it by hand, and look for a crash or a missing '
|
|
1089
|
+
+ 'dependency rather than a leftover process.',
|
|
1090
|
+
)
|
|
1091
|
+
}
|
|
1092
|
+
if (stopped === 'released') {
|
|
1093
|
+
throw new Error(`dsh-builtin-browser: ${target} was released while it was starting`)
|
|
1094
|
+
}
|
|
1095
|
+
throw new Error(`dsh-builtin-browser: ${target} did not expose CDP within 30s. `
|
|
1096
|
+
+ (child.exitCode === 0 && !existsSync(portFile)
|
|
1097
|
+
? 'The launcher exited successfully without DevToolsActivePort; it may have handed off to an already-running browser without debugging enabled. '
|
|
1098
|
+
: 'The selected profile did not provide a live debugging endpoint. ')
|
|
1099
|
+
+ 'No alternative browser profile was substituted.')
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
/**
|
|
1103
|
+
* Whether this host can back views.
|
|
1104
|
+
*
|
|
1105
|
+
* True while the host is usable — including before the browser has been started,
|
|
1106
|
+
* since the first command is what starts it. Reporting "unavailable" here would
|
|
1107
|
+
* make the plugin fall back for no reason.
|
|
1108
|
+
*/
|
|
1109
|
+
available(): boolean {
|
|
1110
|
+
return !this.disposed
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/**
|
|
1114
|
+
* Every page the browser holds that THIS HOST did not open.
|
|
1115
|
+
*
|
|
1116
|
+
* Chrome and Edge own their own page creation. A click on a link that opens a new page — or any
|
|
1117
|
+
* `window.open` — produces a page the provider never asked for, and nothing reports it back.
|
|
1118
|
+
* Those pages are real: they hold memory and stay until something closes them. Measured on a real
|
|
1119
|
+
* window: four pages present while `dsh_browser_list_tabs` reported one.
|
|
1120
|
+
*
|
|
1121
|
+
* Pages this host opened are EXCLUDED here rather than deduplicated by the caller, because the
|
|
1122
|
+
* caller cannot do it: the provider knows a tab by its own id, the carrier knows a page by its
|
|
1123
|
+
* CDP target id, and the two never match. The first version returned everything and relied on the
|
|
1124
|
+
* caller to filter, which reported the same page twice.
|
|
1125
|
+
*
|
|
1126
|
+
* Discovery is enabled before the connection is published, so
|
|
1127
|
+
* `Target.getTargets` also lists pages that existed before this client connected.
|
|
1128
|
+
* @returns the browser's pages that are not ours, or an empty list when it cannot answer.
|
|
1129
|
+
*/
|
|
1130
|
+
async listPages(
|
|
1131
|
+
// The installed browser is one shared instance, not a per-conversation
|
|
1132
|
+
// panel, so ownership does not scope its listing.
|
|
1133
|
+
scope: BrowserSessionWireId,
|
|
1134
|
+
options: { readonly requireRunning?: boolean } = {},
|
|
1135
|
+
): Promise<readonly CarrierPage[]> {
|
|
1136
|
+
// Looking for a page must never START the human's browser. Before this
|
|
1137
|
+
// check the reference-bar pump called listPages on every tick, whose
|
|
1138
|
+
// ensureClient() launched Edge on its own within seconds of the plugin
|
|
1139
|
+
// loading — measured with no open/navigate call at all.
|
|
1140
|
+
const liveClient = this.client
|
|
1141
|
+
if (options.requireRunning === true && (this.disposed || liveClient === undefined || !liveClient.isAlive())) return []
|
|
1142
|
+
try {
|
|
1143
|
+
const client = options.requireRunning === true && liveClient !== undefined ? liveClient : await this.ensureClient()
|
|
1144
|
+
const listed = await client.send('Target.getTargets', {}) as {
|
|
1145
|
+
targetInfos?: Array<{ targetId?: string; type?: string; url?: string; title?: string }>
|
|
1146
|
+
}
|
|
1147
|
+
const ours = new Set(this.sessions.values())
|
|
1148
|
+
return (listed?.targetInfos ?? [])
|
|
1149
|
+
.filter(entry => entry.type === 'page' && typeof entry.targetId === 'string')
|
|
1150
|
+
.filter(entry => !/^edge:\/\/sync-confirmation-dialog(?:\/|$)/.test(entry.url ?? ''))
|
|
1151
|
+
.filter(entry => !ours.has(entry.targetId as string))
|
|
1152
|
+
.map(entry => ({
|
|
1153
|
+
id: tabWireId({ ...resolveSessionHandle(scope), tab: `page:${entry.targetId as string}` }),
|
|
1154
|
+
url: typeof entry.url === 'string' ? entry.url : '',
|
|
1155
|
+
...typeof entry.title === 'string' && entry.title !== '' ? { title: entry.title } : {},
|
|
1156
|
+
}))
|
|
1157
|
+
} catch {
|
|
1158
|
+
// A listing must not fail harder than driving does; the next command reports a real problem.
|
|
1159
|
+
return []
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
/**
|
|
1164
|
+
* Close one page by the target id {@link listPages} reported.
|
|
1165
|
+
*
|
|
1166
|
+
* Only targets created by this owner/session on this connection may be closed.
|
|
1167
|
+
* @param id - the CDP target id.
|
|
1168
|
+
*/
|
|
1169
|
+
async closePage(id: BrowserTabWireId, scope = sessionWireId(readTabHandle(id))): Promise<void> {
|
|
1170
|
+
const identity = resolveTabHandle(resolveSessionHandle(scope), id)
|
|
1171
|
+
const view = this.views.get(id)
|
|
1172
|
+
if (view === undefined && !identity.tab.startsWith('page:')) return
|
|
1173
|
+
const client = await this.ensureClient()
|
|
1174
|
+
const targetId = view === undefined ? identity.tab.replace(/^page:/, '') : this.sessions.get(view.session)
|
|
1175
|
+
if (targetId === undefined) throw new Error('dsh-builtin-browser: browser page is stale')
|
|
1176
|
+
const creator = this.createdTargets.get(client)?.get(targetId)
|
|
1177
|
+
if (creator === undefined) throw new Error('dsh-builtin-browser: personal or adopted tabs are detach-only; close the tab in the browser')
|
|
1178
|
+
resolveTabHandle(resolveSessionHandle(scope), creator)
|
|
1179
|
+
const answer = await client.send('Target.closeTarget', { targetId }) as { success?: boolean }
|
|
1180
|
+
if (answer.success !== true) throw new Error('dsh-builtin-browser: browser close was not acknowledged')
|
|
1181
|
+
this.createdTargets.get(client)?.delete(targetId)
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
createView(identity?: BrowserTabWireId): ElectronViewHandle {
|
|
1185
|
+
const viewId = identity ?? tabWireId({ owner: 'standalone', session: randomUUID(), tab: randomUUID() })
|
|
1186
|
+
readTabHandle(viewId)
|
|
1187
|
+
return {
|
|
1188
|
+
id: viewId,
|
|
1189
|
+
// This is the real browser, not Electron: CDP's JPEG encoder works here, so the
|
|
1190
|
+
// provider may pass format and quality through instead of falling back to PNG.
|
|
1191
|
+
supportsCdpJpeg: true,
|
|
1192
|
+
sendCommand: async (method: string, params?: Record<string, unknown>, options?: CommandOptions) => {
|
|
1193
|
+
if (method === 'Browser.close' || method === 'Target.closeTarget' || method === 'Page.close') {
|
|
1194
|
+
throw new Error('dsh-builtin-browser: use explicit tab close; browser-wide and unowned-tab closes are not allowed')
|
|
1195
|
+
}
|
|
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
|
+
}
|
|
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
|
+
}
|
|
1218
|
+
// A session belongs to the browser that issued it. Clearing the cache whenever a client is
|
|
1219
|
+
// dropped covers the ordinary case, but not this one: another call can be inside
|
|
1220
|
+
// ensureSession() holding the OLD client while this one discards it and clears, and that
|
|
1221
|
+
// call's `views.set` then lands afterwards — re-adding an entry naming a browser that is
|
|
1222
|
+
// gone. The identity check is what refuses it, and it costs a comparison rather than the
|
|
1223
|
+
// round trip that validating every cached session against the browser would cost.
|
|
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
|
|
1230
|
+
: await this.ensureSession(viewId)
|
|
1231
|
+
/**
|
|
1232
|
+
* Send one page command, rebuilding the attach once if the browser no longer knows the
|
|
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).
|
|
1236
|
+
*/
|
|
1237
|
+
const sendWithAttach = async (target: string): Promise<Record<string, unknown>> => {
|
|
1238
|
+
try {
|
|
1239
|
+
const result = await client.send(method, params, target)
|
|
1240
|
+
return (result ?? {}) as Record<string, unknown>
|
|
1241
|
+
} catch (error) {
|
|
1242
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
1243
|
+
if (!/Session with given id not found|No session with given id/i.test(message)) throw error
|
|
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)
|
|
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
|
+
}
|
|
1273
|
+
const rebuilt = await this.ensureSession(viewId)
|
|
1274
|
+
const retried = await client.send(method, params, rebuilt)
|
|
1275
|
+
return (retried ?? {}) as Record<string, unknown>
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
try {
|
|
1279
|
+
return await sendWithAttach(session)
|
|
1280
|
+
} catch (error) {
|
|
1281
|
+
if (error instanceof Error && /timed out/.test(error.message)) this.clientSuspect = true
|
|
1282
|
+
if (!client.isAlive()) {
|
|
1283
|
+
if (this.client === client) {
|
|
1284
|
+
this.client = undefined
|
|
1285
|
+
this.forgetBrowserState()
|
|
1286
|
+
}
|
|
1287
|
+
client.close()
|
|
1288
|
+
}
|
|
1289
|
+
throw error
|
|
1290
|
+
}
|
|
1291
|
+
},
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
destroyView(handle: ElectronViewHandle, _options?: { readonly keepPage?: boolean }): void {
|
|
1296
|
+
const cachedView = this.views.get(handle.id)
|
|
1297
|
+
this.views.delete(handle.id)
|
|
1298
|
+
if (cachedView === undefined) return
|
|
1299
|
+
const session = cachedView.session
|
|
1300
|
+
const targetId = this.sessions.get(session)
|
|
1301
|
+
this.sessions.delete(session)
|
|
1302
|
+
// Nothing to close if the browser was never started.
|
|
1303
|
+
if (targetId !== undefined && this.client !== undefined) {
|
|
1304
|
+
void cachedView.client.send('Target.detachFromTarget', { sessionId: session }).catch(() => undefined)
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
/** Nothing to show: the browser owns its own windows. */
|
|
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
|
+
}
|
|
1312
|
+
|
|
1313
|
+
/**
|
|
1314
|
+
* Bring the target's page to the front, then report success.
|
|
1315
|
+
*
|
|
1316
|
+
* A failure is swallowed rather than propagated: a real Chrome window that refuses to come
|
|
1317
|
+
* forward is not a reason to refuse the click that follows. The barrier exists to order the
|
|
1318
|
+
* two, and the order is honoured either way.
|
|
1319
|
+
* @param handle - the view to present.
|
|
1320
|
+
*/
|
|
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
|
+
}
|
|
1326
|
+
try {
|
|
1327
|
+
await handle.sendCommand('Page.bringToFront')
|
|
1328
|
+
} catch {
|
|
1329
|
+
// Backgrounded, minimised, or a target that went away between the snapshot and the
|
|
1330
|
+
// click. The command that called this will report its own failure if the page is gone.
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
/**
|
|
1335
|
+
* Best effort at bringing the browser's window forward.
|
|
1336
|
+
*/
|
|
1337
|
+
async focus(): Promise<void> {
|
|
1338
|
+
if (this.child && await this.ownership.verify(this.child)) {
|
|
1339
|
+
try { this.child.kill('SIGCONT') } catch { /* Windows has no SIGCONT. */ }
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
/**
|
|
1344
|
+
* Close the browser we launched, if we ever launched one.
|
|
1345
|
+
*/
|
|
1346
|
+
dispose(): void {
|
|
1347
|
+
this.stopForeground()
|
|
1348
|
+
if (this.disposed) return
|
|
1349
|
+
this.disposed = true
|
|
1350
|
+
const client = this.client
|
|
1351
|
+
this.forgetBrowserState()
|
|
1352
|
+
this.client = undefined
|
|
1353
|
+
const disconnect = async (): Promise<void> => {
|
|
1354
|
+
if (!client) return
|
|
1355
|
+
const owner = this.ownedClients.get(client)
|
|
1356
|
+
try {
|
|
1357
|
+
if (owner && await this.ownership.verify(owner)) {
|
|
1358
|
+
const result = await client.send('SystemInfo.getProcessInfo', {}, undefined, 1000) as { processInfo?: { type: string; id: number }[] }
|
|
1359
|
+
if (result.processInfo?.some(entry => entry.type === 'browser' && entry.id === owner.pid)
|
|
1360
|
+
&& await this.ownership.verify(owner)) await client.send('Browser.close', {}, undefined, 1000)
|
|
1361
|
+
}
|
|
1362
|
+
} catch { /* An unverified endpoint is detach-only. */ }
|
|
1363
|
+
finally { client.close() }
|
|
1364
|
+
}
|
|
1365
|
+
void disconnect()
|
|
1366
|
+
const doomed = [this.child, ...this.stubborn.splice(0)].filter(
|
|
1367
|
+
(entry): entry is ChildProcess => entry !== undefined,
|
|
1368
|
+
)
|
|
1369
|
+
this.child = undefined
|
|
1370
|
+
for (const dying of doomed) {
|
|
1371
|
+
const force = (): void => { void this.stopChild(dying) }
|
|
1372
|
+
const timer = setTimeout(force, CLOSE_GRACE_MS)
|
|
1373
|
+
timer.unref?.()
|
|
1374
|
+
dying.once('exit', () => { clearTimeout(timer) })
|
|
1375
|
+
}
|
|
1376
|
+
const ephemeral = this.ephemeralDir
|
|
1377
|
+
const cleanup = (): void => {
|
|
1378
|
+
void (async () => {
|
|
1379
|
+
const removeProfile = (): void => {
|
|
1380
|
+
if (ephemeral !== undefined && doomed.length > 0 && doomed.every(child => this.ownership.ownsDirectory(child, ephemeral) && this.ownedChildren.has(child)
|
|
1381
|
+
&& (child.exitCode !== null || child.signalCode !== null))) rmSync(ephemeral, { recursive: true, force: true })
|
|
1382
|
+
}
|
|
1383
|
+
if (this.profileLease !== undefined) await this.profileLease.release(removeProfile)
|
|
1384
|
+
else removeProfile()
|
|
1385
|
+
this.profileLease = undefined
|
|
1386
|
+
})().catch(error => process.stderr.write(`[dsh-browser] profile release failed: ${String(error)}\n`))
|
|
1387
|
+
}
|
|
1388
|
+
const live = doomed.filter(child => child.exitCode === null && child.signalCode === null)
|
|
1389
|
+
if (live.length > 0) {
|
|
1390
|
+
const remaining = new Set(live)
|
|
1391
|
+
for (const child of live) child.once('exit', () => {
|
|
1392
|
+
remaining.delete(child)
|
|
1393
|
+
if (remaining.size === 0) cleanup()
|
|
1394
|
+
})
|
|
1395
|
+
} else if (client !== undefined) {
|
|
1396
|
+
void client.whenClosed().then(cleanup)
|
|
1397
|
+
} else {
|
|
1398
|
+
cleanup()
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
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
|
+
|
|
1439
|
+
/**
|
|
1440
|
+
* The flattened session for a view, creating its page on first use.
|
|
1441
|
+
*/
|
|
1442
|
+
private async ensureSession(viewId: string): Promise<string> {
|
|
1443
|
+
const inFlight = this.sessionBuilding.get(viewId)
|
|
1444
|
+
if (inFlight !== undefined) return await inFlight
|
|
1445
|
+
const building = this.buildSession(viewId).finally(() => {
|
|
1446
|
+
this.sessionBuilding.delete(viewId)
|
|
1447
|
+
})
|
|
1448
|
+
this.sessionBuilding.set(viewId, building)
|
|
1449
|
+
return await building
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
/** Create and attach the target for one view. Serialised by {@link ensureSession}. */
|
|
1453
|
+
private async buildSession(viewId: string): Promise<string> {
|
|
1454
|
+
const client = await this.ensureClient()
|
|
1455
|
+
const previous = this.targetBuilds.get(client) ?? Promise.resolve()
|
|
1456
|
+
let release!: () => void
|
|
1457
|
+
const building = new Promise<void>(resolve => { release = resolve })
|
|
1458
|
+
this.targetBuilds.set(client, building)
|
|
1459
|
+
await previous
|
|
1460
|
+
try {
|
|
1461
|
+
const adopted = await this.adoptBlankTarget(client)
|
|
1462
|
+
const targetId = adopted ?? await this.createTarget(client, viewId)
|
|
1463
|
+
const attached = await client.send('Target.attachToTarget', { targetId, flatten: true }) as { sessionId?: string }
|
|
1464
|
+
const sessionId = attached?.sessionId
|
|
1465
|
+
if (typeof sessionId !== 'string') throw new Error('dsh-builtin-browser: the browser did not attach to the new page')
|
|
1466
|
+
if (adopted !== undefined) this.rememberTarget(client, targetId, viewId)
|
|
1467
|
+
await this.clearDisplays(client, sessionId, targetId)
|
|
1468
|
+
await this.presentAsChrome(client, sessionId)
|
|
1469
|
+
this.sessions.set(sessionId, targetId)
|
|
1470
|
+
this.views.set(viewId, { session: sessionId, client })
|
|
1471
|
+
return sessionId
|
|
1472
|
+
} finally {
|
|
1473
|
+
release()
|
|
1474
|
+
if (this.targetBuilds.get(client) === building) this.targetBuilds.delete(client)
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
|
|
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
|
+
|
|
1487
|
+
async adoptPage(identity: BrowserTabWireId, scope = sessionWireId(readTabHandle(identity))): Promise<ElectronViewHandle> {
|
|
1488
|
+
const tab = resolveTabHandle(resolveSessionHandle(scope), identity).tab
|
|
1489
|
+
if (!tab.startsWith('page:')) throw new Error('dsh-builtin-browser: invalid carrier page handle')
|
|
1490
|
+
const targetId = tab.slice('page:'.length)
|
|
1491
|
+
const handle = this.createView(identity)
|
|
1492
|
+
const client = await this.ensureClient()
|
|
1493
|
+
const attached = await client.send('Target.attachToTarget', { targetId, flatten: true }) as { sessionId?: string }
|
|
1494
|
+
const sessionId = attached?.sessionId
|
|
1495
|
+
if (typeof sessionId !== 'string') {
|
|
1496
|
+
throw new Error(`dsh-builtin-browser: could not attach to the existing page ${targetId}`)
|
|
1497
|
+
}
|
|
1498
|
+
this.sessions.set(sessionId, targetId)
|
|
1499
|
+
this.views.set(handle.id, { session: sessionId, client })
|
|
1500
|
+
return handle
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
private async adoptBlankTarget(client: CdpClient): Promise<string | undefined> {
|
|
1504
|
+
const listed = await client.send('Target.getTargets', {}) as {
|
|
1505
|
+
targetInfos?: Array<{ targetId?: string; type?: string; url?: string }>
|
|
1506
|
+
}
|
|
1507
|
+
if (!Array.isArray(listed?.targetInfos)) throw new Error('dsh-builtin-browser: the browser did not acknowledge its target inventory')
|
|
1508
|
+
const claimed = new Set(this.sessions.values())
|
|
1509
|
+
for (const entry of listed.targetInfos) {
|
|
1510
|
+
if (entry.type !== 'page' || typeof entry.targetId !== 'string') continue
|
|
1511
|
+
if (!isBlankUrl(entry.url)) continue
|
|
1512
|
+
if (claimed.has(entry.targetId)) continue
|
|
1513
|
+
return entry.targetId
|
|
1514
|
+
}
|
|
1515
|
+
return undefined
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
/** Create one page, refusing to go on without an id. */
|
|
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
|
|
1574
|
+
if (typeof targetId !== 'string' || targetId === '') throw new Error('dsh-builtin-browser: the browser did not create a page')
|
|
1575
|
+
this.rememberTarget(client, targetId, viewId)
|
|
1576
|
+
if (parked) await this.parkQuietWindow(client, targetId)
|
|
1577
|
+
return targetId
|
|
1578
|
+
}
|
|
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
|
+
|
|
1811
|
+
private rememberTarget(client: CdpClient, targetId: string, viewId: string): void {
|
|
1812
|
+
let targets = this.createdTargets.get(client)
|
|
1813
|
+
if (!targets) { targets = new Map(); this.createdTargets.set(client, targets) }
|
|
1814
|
+
targets.set(targetId, viewId as BrowserTabWireId)
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
/** Views whose session is being created right now, so a second caller waits for the first. */
|
|
1818
|
+
private readonly sessionBuilding = new Map<string, Promise<string>>()
|
|
1819
|
+
|
|
1820
|
+
/** Serialises page selection/creation and attachment for each browser connection. */
|
|
1821
|
+
private readonly targetBuilds = new WeakMap<CdpClient, Promise<void>>()
|
|
1822
|
+
|
|
1823
|
+
/** sessionId -> targetId, so a destroyed view can close the right page. */
|
|
1824
|
+
private readonly sessions = new Map<string, string>()
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
/**
|
|
1828
|
+
* Probe for a browser the human already has open with a debugging port.
|
|
1829
|
+
*
|
|
1830
|
+
* Chromium exposes CDP only when it was STARTED with --remote-debugging-port, so an already-running Edge
|
|
1831
|
+
* cannot be attached unless it was launched that way. Attaching is therefore opt-in: this probe answers
|
|
1832
|
+
* "is there something to attach to right now", and the caller decides whether to use it.
|
|
1833
|
+
* @param port - the debugging port to try (default 9222).
|
|
1834
|
+
* @param timeoutMs - how long to wait for the endpoint.
|
|
1835
|
+
* @returns the browser banner when an endpoint answers, undefined otherwise.
|
|
1836
|
+
*/
|
|
1837
|
+
export async function probeAttach(port: number = CDP_DEFAULT_ATTACH_PORT, timeoutMs: number = CDP_ATTACH_PROBE_TIMEOUT_MS): Promise<string | undefined> {
|
|
1838
|
+
const controller = new AbortController()
|
|
1839
|
+
const timer = setTimeout(() => { controller.abort() }, timeoutMs)
|
|
1840
|
+
try {
|
|
1841
|
+
const response = await fetch(cdpVersionUrl(port), { signal: controller.signal })
|
|
1842
|
+
if (!response.ok) return undefined
|
|
1843
|
+
const body = await response.json() as { Browser?: unknown }
|
|
1844
|
+
return typeof body.Browser === 'string' ? body.Browser : 'unknown'
|
|
1845
|
+
} catch {
|
|
1846
|
+
return undefined
|
|
1847
|
+
} finally {
|
|
1848
|
+
clearTimeout(timer)
|
|
1849
|
+
}
|
|
1850
|
+
}
|