dsh-builtin-browser 1.0.0 → 1.0.3
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 +61 -0
- package/README.md +1 -1
- package/assets/browser-panel-locales.mjs +37 -5
- package/assets/browser-policy.d.mts +29 -0
- package/assets/browser-policy.mjs +40 -0
- package/desktop-bridge/desktop-discovery.d.mts +1 -1
- package/desktop-bridge/desktop-discovery.mjs +59 -9
- package/desktop-bridge/desktop-identity.json +12 -0
- package/desktop-bridge/install.mjs +14 -7
- package/desktop-bridge/plugin-browser-bridge.js +19 -7
- package/docs/acceptance-2026-11-27.md +67 -0
- package/docs/architecture.md +1 -1
- package/docs/development.md +33 -4
- package/docs/dsh-0.2.3-host-patch-task.md +34 -0
- package/docs/hardcoding-audit.md +28 -8
- package/docs/known-issues.md +26 -0
- package/docs/limitations.md +6 -2
- package/docs/pr64-maintenance.md +1 -1
- package/docs/tool-reference.md +1 -1
- package/docs/user-guide.md +1 -1
- package/docs/v1.1.0-bu-data-batching-task.md +66 -0
- package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
- 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/README.md +4 -0
- package/dsh-host-patch/apply.mjs +61 -13
- package/dsh-host-patch/rc3-revision9.json.gz +0 -0
- package/dsh-host-patch/rc5-revision9.json.gz +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 +218 -0
- 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 +260 -0
- package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
- package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
- package/dsh-host-patch/tauri-revision1.json +39 -0
- package/dsh-host-patch/tauri.json +43 -0
- package/dsh-host-patch/v023-alpha2.json +153 -0
- package/lib/browser/anti-bot.js +215 -0
- package/lib/browser/deep-dom.js +39 -0
- package/lib/browser/runtime.js +15 -0
- package/lib/browser/takeover-target.js +13 -6
- package/lib/browser/types.js +30 -1
- package/lib/browser-electron/authenticated-route.js +16 -2
- package/lib/browser-electron/automatic-maintenance.js +16 -10
- package/lib/browser-electron/bridge-connection.js +3 -8
- package/lib/browser-electron/bridge-install.js +2 -1
- package/lib/browser-electron/bridge-status.js +55 -26
- package/lib/browser-electron/desktop-bridge-host.js +7 -6
- package/lib/browser-electron/desktop-identity.js +28 -5
- package/lib/browser-electron/desktop-shell.js +64 -0
- package/lib/browser-electron/electron-provision.js +105 -18
- package/lib/browser-electron/entry.js +129 -46
- package/lib/browser-electron/extension-browser.js +4 -4
- package/lib/browser-electron/foreground-watch.js +134 -0
- package/lib/browser-electron/guest-cookie-jar.js +13 -13
- package/lib/browser-electron/guest-route.js +181 -32
- package/lib/browser-electron/guest-runtime.js +61 -10
- package/lib/browser-electron/guest-storage.js +2 -2
- package/lib/browser-electron/history-store.js +1 -5
- package/lib/browser-electron/host-main.js +8 -4
- package/lib/browser-electron/host-patch-maintenance.js +14 -8
- package/lib/browser-electron/maintenance-route.js +2 -1
- package/lib/browser-electron/missing-system-browser.js +5 -9
- package/lib/browser-electron/preferred-browser.js +7 -3
- package/lib/browser-electron/preview-route.js +9 -13
- package/lib/browser-electron/process-ownership.js +1 -1
- package/lib/browser-electron/profile-command.js +2 -1
- package/lib/browser-electron/profile-extension.js +5 -0
- package/lib/browser-electron/profile-lease.js +152 -47
- package/lib/browser-electron/provider-core.js +527 -0
- package/lib/browser-electron/provider-interaction.js +963 -0
- package/lib/browser-electron/provider-media.js +518 -0
- package/lib/browser-electron/provider-navigation.js +301 -0
- package/lib/browser-electron/provider-observation.js +623 -0
- package/lib/browser-electron/provider-tabs.js +372 -0
- package/lib/browser-electron/provider.js +150 -3301
- package/lib/browser-electron/reference-route.js +9 -18
- package/lib/browser-electron/remote-host.js +79 -34
- package/lib/browser-electron/runtime-status.js +56 -6
- package/lib/browser-electron/settings-store.js +3 -6
- package/lib/browser-electron/sidebar-only-host.js +1 -1
- package/lib/browser-electron/system-browser.js +539 -172
- package/lib/browser-electron/tauri-host.js +208 -0
- package/lib/browser-electron/virtual-cursor.js +23 -13
- package/lib/browser-reference/service.js +22 -4
- package/lib/browser-reference/web-sources.js +1 -1
- package/lib/client.js +43409 -0
- package/lib/compat/host-features.js +75 -0
- package/lib/reference-source.js +1 -1
- package/lib/reference-text.js +23 -1
- package/lib/takeover-protocol.js +1 -1
- package/lib/tool-browser/block-recovery.js +69 -0
- package/lib/tool-browser/code-tool.js +170 -19
- package/lib/tool-browser/code-worker.js +115 -20
- package/lib/tool-browser/errors.js +34 -0
- package/lib/tool-browser/index.js +66 -3593
- package/lib/tool-browser/page-probe.js +227 -28
- package/lib/tool-browser/panel-page.js +2 -1
- package/lib/tool-browser/probe-client.js +157 -0
- package/lib/tool-browser/screenshot-annotations.js +108 -0
- package/lib/tool-browser/state.js +337 -0
- package/lib/tool-browser/takeover.js +1 -1
- package/lib/tool-browser/tools-debug.js +862 -0
- package/lib/tool-browser/tools-interaction.js +993 -0
- package/lib/tool-browser/tools-navigation.js +807 -0
- package/lib/tool-browser/tools-observation.js +461 -0
- package/lib/tool-browser/tools-reference.js +293 -0
- package/lib/web-guest.js +1 -0
- package/package.json +16 -54
- package/README.en.md +0 -89
- package/browser-extension/constants.mjs +0 -20
- package/browser-extension/controller.mjs +0 -293
- package/browser-extension/locales.mjs +0 -15
- package/browser-extension/manifest.json +0 -12
- package/browser-extension/options.html +0 -14
- package/browser-extension/options.mjs +0 -9
- package/browser-extension/permission-guard.mjs +0 -13
- package/browser-extension/worker.mjs +0 -74
- package/dist/client.cjs +0 -43167
- package/lib/browser-electron/package-removal.js +0 -5
- package/lib/browser-reference/submission-receipts.js +0 -139
- package/scripts/build.mjs +0 -66
- package/scripts/bundle-host.mjs +0 -28
- package/scripts/fix-exports.mjs +0 -50
- package/scripts/install-electron.mjs +0 -51
- package/scripts/verify-exports.mjs +0 -47
- package/scripts/verify-preview-sdk.mjs +0 -93
- package/skills/dsh-builtin-browser/SKILL.md +0 -73
- package/skills/dsh-builtin-browser/references/batch.md +0 -53
- package/skills/dsh-builtin-browser/references/deliver.md +0 -31
- package/skills/dsh-builtin-browser/references/locate.md +0 -11
- package/skills/dsh-builtin-browser/references/recover.md +0 -11
- package/skills/dsh-builtin-browser/references/verify.md +0 -13
- package/skills/dsh-debug-host/SKILL.md +0 -56
- package/skills/dsh-debug-self/SKILL.md +0 -50
- package/src/bridge-compatibility.ts +0 -39
- package/src/browser/handles.ts +0 -89
- package/src/browser/runtime.ts +0 -560
- package/src/browser/takeover-target.ts +0 -36
- package/src/browser/types.ts +0 -817
- package/src/browser-electron/authenticated-route.ts +0 -84
- package/src/browser-electron/automatic-maintenance.ts +0 -726
- package/src/browser-electron/bridge-auto.ts +0 -159
- package/src/browser-electron/bridge-connection.ts +0 -385
- package/src/browser-electron/bridge-endpoint.ts +0 -129
- package/src/browser-electron/bridge-install.ts +0 -289
- package/src/browser-electron/bridge-maintenance.ts +0 -189
- package/src/browser-electron/bridge-status.ts +0 -347
- package/src/browser-electron/desktop-bridge-host.ts +0 -251
- package/src/browser-electron/desktop-identity.ts +0 -320
- package/src/browser-electron/document-readiness.ts +0 -45
- package/src/browser-electron/electron-provision.ts +0 -261
- package/src/browser-electron/entry.ts +0 -1301
- package/src/browser-electron/ephemeral-profile.ts +0 -189
- package/src/browser-electron/extension-browser.ts +0 -223
- package/src/browser-electron/extension-setup.ts +0 -67
- package/src/browser-electron/file-write.ts +0 -31
- package/src/browser-electron/guest-cookie-jar.ts +0 -176
- package/src/browser-electron/guest-cookie-store.ts +0 -59
- package/src/browser-electron/guest-css-runtime.ts +0 -76
- package/src/browser-electron/guest-css.ts +0 -68
- package/src/browser-electron/guest-route.ts +0 -568
- package/src/browser-electron/guest-runtime.ts +0 -357
- package/src/browser-electron/guest-storage-runtime.ts +0 -54
- package/src/browser-electron/guest-storage.ts +0 -117
- package/src/browser-electron/history-store.ts +0 -227
- package/src/browser-electron/host-main.ts +0 -1381
- package/src/browser-electron/host-patch-maintenance.ts +0 -112
- package/src/browser-electron/http-body.ts +0 -65
- package/src/browser-electron/json-reply.ts +0 -47
- package/src/browser-electron/maintenance-broker.ts +0 -166
- package/src/browser-electron/maintenance-lifecycle.ts +0 -91
- package/src/browser-electron/maintenance-route.ts +0 -67
- package/src/browser-electron/missing-system-browser.ts +0 -113
- package/src/browser-electron/open-slot.ts +0 -49
- package/src/browser-electron/package-removal.ts +0 -4
- package/src/browser-electron/paths.ts +0 -25
- package/src/browser-electron/preferred-browser.ts +0 -120
- package/src/browser-electron/preview-route.ts +0 -218
- package/src/browser-electron/process-ownership.ts +0 -168
- package/src/browser-electron/process.ts +0 -23
- package/src/browser-electron/profile-checkpoint.ts +0 -187
- package/src/browser-electron/profile-command.ts +0 -46
- package/src/browser-electron/profile-extension.ts +0 -124
- package/src/browser-electron/profile-lease.ts +0 -115
- package/src/browser-electron/profile-residue.ts +0 -49
- package/src/browser-electron/provider.ts +0 -4571
- package/src/browser-electron/reference-route.ts +0 -608
- package/src/browser-electron/remote-host.ts +0 -1462
- package/src/browser-electron/rpc-input.ts +0 -13
- package/src/browser-electron/rpc-ops.ts +0 -41
- package/src/browser-electron/runtime-diagnostics.ts +0 -38
- package/src/browser-electron/runtime-route.ts +0 -105
- package/src/browser-electron/runtime-status.ts +0 -242
- package/src/browser-electron/settings-route.ts +0 -64
- package/src/browser-electron/settings-store.ts +0 -589
- package/src/browser-electron/shortcuts-route.ts +0 -112
- package/src/browser-electron/sidebar-only-host.ts +0 -298
- package/src/browser-electron/startpage-shortcuts.ts +0 -213
- package/src/browser-electron/system-browser.ts +0 -1497
- package/src/browser-electron/timing.ts +0 -16
- package/src/browser-electron/virtual-cursor.ts +0 -152
- package/src/browser-electron/windows-system.ts +0 -24
- package/src/browser-reference/delivery.ts +0 -384
- package/src/browser-reference/entry.ts +0 -631
- package/src/browser-reference/export.ts +0 -339
- package/src/browser-reference/import.ts +0 -303
- package/src/browser-reference/page-script.ts +0 -1537
- package/src/browser-reference/service.ts +0 -1315
- package/src/browser-reference/store.ts +0 -172
- package/src/browser-reference/submission-receipts.ts +0 -122
- package/src/browser-reference/text-quote.ts +0 -219
- package/src/browser-reference/types.ts +0 -195
- package/src/browser-reference/visible.ts +0 -367
- package/src/browser-reference/web-sources.ts +0 -103
- package/src/client/browser/BrowserController.ts +0 -693
- package/src/client/browser/BrowserFrame.ts +0 -78
- package/src/client/browser/BrowserNavigation.ts +0 -169
- package/src/client/browser/BrowserPage.ts +0 -23
- package/src/client/browser/BrowserPersistence.ts +0 -44
- package/src/client/browser/IframeImpl.ts +0 -176
- package/src/client/browser/child-tabs.ts +0 -14
- package/src/client/browser/iframe-reference.ts +0 -67
- package/src/client/browser/initialization.ts +0 -262
- package/src/client/browser/omnibox.ts +0 -243
- package/src/client/browser/store.ts +0 -38
- package/src/client/browser/takeover-channel.ts +0 -72
- package/src/client/browser/url.ts +0 -46
- package/src/client/browser/web-reference-source.ts +0 -52
- package/src/client/css-modules.d.ts +0 -4
- package/src/client/definition.tsx +0 -30
- package/src/client/electron/ElectronWebViewImpl.ts +0 -364
- package/src/client/electron/ElectronWebviewPresentation.ts +0 -138
- package/src/client/electron/NativeChildPresentation.ts +0 -45
- package/src/client/electron/NativeViewPage.ts +0 -251
- package/src/client/electron/pages.ts +0 -23
- package/src/client/electron/reference-overlay.ts +0 -53
- package/src/client/electron/workspace.ts +0 -33
- package/src/client/index.ts +0 -293
- package/src/client/locales.ts +0 -857
- package/src/client/pages.ts +0 -28
- package/src/client/reference/client/BrowserRefLink.tsx +0 -142
- package/src/client/reference/client/draft-reference.ts +0 -167
- package/src/client/reference/client/index.ts +0 -7
- package/src/client/reference/client/ordered-submission.ts +0 -108
- package/src/client/reference/client/pending-delivery.ts +0 -216
- package/src/client/reference/client/plugin.ts +0 -189
- package/src/client/reference/client/production/ReferenceCapsules.tsx +0 -345
- package/src/client/reference/client/production/ReferenceDock.module.css +0 -193
- package/src/client/reference/client/production/ReferenceDock.tsx +0 -6
- package/src/client/reference/client/production/ReferenceFeedback.tsx +0 -15
- package/src/client/reference/client/production/ReferenceMath.tsx +0 -44
- package/src/client/reference/client/production/ReferenceText.tsx +0 -36
- package/src/client/reference/client/production/assembly.ts +0 -471
- package/src/client/reference/client/production/asset-store.ts +0 -144
- package/src/client/reference/client/production/availability.ts +0 -74
- package/src/client/reference/client/production/bytes.ts +0 -36
- package/src/client/reference/client/production/delivery-client.ts +0 -211
- package/src/client/reference/client/production/draft-adapter.ts +0 -508
- package/src/client/reference/client/production/http-transport.ts +0 -217
- package/src/client/reference/client/production/production-submission.ts +0 -310
- package/src/client/reference/client/production/protocol.ts +0 -231
- package/src/client/reference/client/production/reference-card.ts +0 -240
- package/src/client/reference/client/production/reference-labels.ts +0 -29
- package/src/client/reference/client/production/reply-link-bridge.ts +0 -222
- package/src/client/reference/client/production/reveal.ts +0 -215
- package/src/client/reference/client/production/runtime.ts +0 -1101
- package/src/client/reference/client/production/snapshot-adapter.ts +0 -154
- package/src/client/reference/client/production/source-marker.ts +0 -63
- package/src/client/reference/client/production/source-opener.ts +0 -55
- package/src/client/reference/client/production/styles.ts +0 -104
- package/src/client/reference/client/production/user-text-rule.ts +0 -58
- package/src/client/reference/client/reveal.ts +0 -107
- package/src/client/reference/client/scheme.ts +0 -114
- package/src/client/reference/client/types.ts +0 -168
- package/src/client/reference/css-modules.d.ts +0 -4
- package/src/client/reference/index.ts +0 -11
- package/src/client/reference-capture-owner.ts +0 -162
- package/src/client/reference-intents.ts +0 -36
- package/src/client/settings/index.ts +0 -34
- package/src/client/settings/panel.ts +0 -2657
- package/src/client/shortcut-open.ts +0 -30
- package/src/client/startpage/binding.ts +0 -99
- package/src/client/startpage/controller.ts +0 -303
- package/src/client/startpage/model.ts +0 -279
- package/src/client/view/Browser.module.css +0 -751
- package/src/client/view/BrowserBody.tsx +0 -314
- package/src/client/view/BrowserPresentation.ts +0 -9
- package/src/client/view/BrowserTitle.tsx +0 -17
- package/src/client/view/IframePresentation.ts +0 -344
- package/src/client/view/StartPage.tsx +0 -597
- package/src/client/view/TakeoverBanner.tsx +0 -21
- package/src/index.ts +0 -110
- package/src/reference-owner.ts +0 -5
- package/src/reference-page.ts +0 -9
- package/src/reference-source.ts +0 -3
- package/src/reference-text.ts +0 -197
- package/src/startpage-settings.ts +0 -103
- package/src/startpage.ts +0 -71
- package/src/takeover-protocol.ts +0 -19
- package/src/tool-browser/code-tool.ts +0 -401
- package/src/tool-browser/code-worker.ts +0 -639
- package/src/tool-browser/element-fields.ts +0 -167
- package/src/tool-browser/index.ts +0 -3733
- package/src/tool-browser/page-probe.ts +0 -474
- package/src/tool-browser/panel-page.ts +0 -124
- package/src/tool-browser/screenshot-image.ts +0 -49
- package/src/tool-browser/takeover.ts +0 -198
- package/src/types/electron-shim.d.ts +0 -144
- package/src/types.ts +0 -85
- package/src/web-guest.ts +0 -34
- package/tools/accept-desktop.mjs +0 -148
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { DEFAULT_OPERATION_TIMEOUT_MS } from '../../assets/browser-policy.mjs';
|
|
2
|
-
import { hostMessages } from '../../assets/browser-messages.mjs';
|
|
3
1
|
/**
|
|
4
2
|
* Electron-backed browser provider: `WebContentsView` sessions driven over
|
|
5
3
|
* `webContents.debugger` (CDP). The provider itself does not import Electron — it operates through the {@link ElectronBrowserViewHost} seam, which the
|
|
@@ -8,21 +6,16 @@ import { hostMessages } from '../../assets/browser-messages.mjs';
|
|
|
8
6
|
* shell that owns the `BrowserWindow`.
|
|
9
7
|
* @module dsh-browser/browser-electron
|
|
10
8
|
*/
|
|
11
|
-
import {
|
|
9
|
+
import { hostMessages } from '../../assets/browser-messages.mjs';
|
|
12
10
|
import { dispatchReferenceCaptureAction } from '../browser-reference/service.js';
|
|
13
|
-
import { MAX_REFERENCE_COMMENT, REFERENCE_INTENT_CHANNEL, overlayScript, standaloneScript
|
|
11
|
+
import { MAX_REFERENCE_COMMENT, REFERENCE_INTENT_CHANNEL, overlayScript, standaloneScript } from '../browser-reference/entry.js';
|
|
14
12
|
import { noticeScript, validateFrozenCapture } from '../browser-reference/page-script.js';
|
|
15
13
|
import { randomUUID } from 'node:crypto';
|
|
16
|
-
import { setLastOpen } from './open-slot.js';
|
|
17
|
-
import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs';
|
|
18
|
-
import { writeFileNoReplace } from './file-write.js';
|
|
19
|
-
import { homedir } from 'node:os';
|
|
20
|
-
import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
21
|
-
import { HistoryStore } from './history-store.js';
|
|
22
|
-
import { forgetCursor, paintCursor } from './virtual-cursor.js';
|
|
23
|
-
import { documentReady, mainDocument } from './document-readiness.js';
|
|
24
14
|
import { BrowserError } from '../browser/types.js';
|
|
25
15
|
import { browserSessionHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId } from '../browser/handles.js';
|
|
16
|
+
import { PROVIDER_TIMEOUTS, withTimeout, handleSendEvaluate } from './provider-core.js';
|
|
17
|
+
import { ProviderMedia } from './provider-media.js';
|
|
18
|
+
export { ELECTRON_BROWSER_PROVIDER_ID, CDP_PAGE_CAPTURE_SCREENSHOT, layoutSize, toExportedCookies, toCdpCookie, CDP_RUNTIME_EVALUATE, CDP_PAGE_NAVIGATE, BROWSER_KEY_NAMES } from './provider-core.js';
|
|
26
19
|
/**
|
|
27
20
|
* Consecutive failed evaluations after which the reference pump forgets an
|
|
28
21
|
* adopted sidebar tab. One or two misses are a navigation; five (≈6 s at the
|
|
@@ -31,285 +24,26 @@ import { browserSessionHandle, resolveSessionHandle, resolveTabHandle, sessionWi
|
|
|
31
24
|
const DEAD_REFERENCE_TAB_MISSES = 5;
|
|
32
25
|
/** How long a tab that stopped answering waits before the pump tries it again. */
|
|
33
26
|
const DEAD_REFERENCE_TAB_RETRY_MS = 15_000;
|
|
34
|
-
const PROVIDER_TIMEOUTS = Object.freeze({
|
|
35
|
-
evaluation: 3_000,
|
|
36
|
-
interaction: 5_000,
|
|
37
|
-
lookup: 10_000,
|
|
38
|
-
action: 15_000,
|
|
39
|
-
prepare: DEFAULT_OPERATION_TIMEOUT_MS + 1_000,
|
|
40
|
-
download: 60_000,
|
|
41
|
-
});
|
|
42
|
-
/**
|
|
43
|
-
* Page-context human-verification (CAPTCHA / bot-detection) detection. Runs
|
|
44
|
-
* inside the page; returns `{ blocked, kind?, reason? }`. Marker-based and
|
|
45
|
-
* best-effort: checks for Cloudflare's interstitial, hCaptcha, reCAPTCHA,
|
|
46
|
-
* Turnstile, and generic challenge wording.
|
|
47
|
-
*/
|
|
48
|
-
const CHALLENGE_DETECT_EXPRESSION = `(() => {
|
|
49
|
-
const title = (document.title || '').trim()
|
|
50
|
-
const bodyText = (document.body && document.body.innerText || '').slice(0, 4000)
|
|
51
|
-
// Challenge widgets often live in same-origin iframes or shadow roots;
|
|
52
|
-
// scan those too (cross-origin frames stay opaque).
|
|
53
|
-
let extraText = ''
|
|
54
|
-
try {
|
|
55
|
-
const seen = new Set()
|
|
56
|
-
const scan = (doc) => {
|
|
57
|
-
if (seen.has(doc)) return
|
|
58
|
-
seen.add(doc)
|
|
59
|
-
for (const el of doc.querySelectorAll('*')) {
|
|
60
|
-
if (el.shadowRoot) {
|
|
61
|
-
extraText += (el.shadowRoot.textContent || '').slice(0, 2000)
|
|
62
|
-
scan(el.shadowRoot)
|
|
63
|
-
}
|
|
64
|
-
if (el.tagName === 'IFRAME') {
|
|
65
|
-
try {
|
|
66
|
-
const d = el.contentDocument
|
|
67
|
-
if (d) {
|
|
68
|
-
extraText += ((d.body && d.body.innerText) || '').slice(0, 2000)
|
|
69
|
-
scan(d)
|
|
70
|
-
}
|
|
71
|
-
} catch { /* cross-origin */ }
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
scan(document)
|
|
76
|
-
} catch { /* never fail the challenge check */ }
|
|
77
|
-
const lower = (title + '\\n' + bodyText + '\\n' + extraText).toLowerCase()
|
|
78
|
-
const frameSrcs = [...document.querySelectorAll('iframe')].map(f => f.src || '').join(' ')
|
|
79
|
-
const framesLower = frameSrcs.toLowerCase()
|
|
80
|
-
const hasCfInterstitial = /just a moment|checking your browser|attention required|cf_chl/i.test(lower)
|
|
81
|
-
|| !!document.querySelector('#challenge-running, #challenge-stage, #cf-chl-container')
|
|
82
|
-
const hasHCaptcha = !!window.hcaptcha || !!document.querySelector('.h-captcha') || /hcaptcha\\.com/i.test(framesLower)
|
|
83
|
-
const hasRecaptcha = !!window.grecaptcha || !!document.querySelector('.g-recaptcha') || /recaptcha\\/api|google\\.com\\/recaptcha/i.test(framesLower)
|
|
84
|
-
const hasTurnstile = !!window.turnstile || /challenges\\.cloudflare\\.com/i.test(framesLower) || /turnstile|challenge-platform/i.test(lower)
|
|
85
|
-
const verifyWording = /verify you are human|verify you are not a robot|\\u4eba\\u673a\\u9a8c\\u8bc1|\\u5b89\\u5168\\u9a8c\\u8bc1|enable javascript and cookies|\\u8bf7.*\\u9a8c\\u8bc1/i.test(lower)
|
|
86
|
-
if (hasCfInterstitial) return { blocked: true, kind: 'cloudflare', reason: 'Cloudflare "Just a moment" interstitial' }
|
|
87
|
-
if (hasHCaptcha) return { blocked: true, kind: 'hcaptcha', reason: 'hCaptcha verification' }
|
|
88
|
-
if (hasRecaptcha) return { blocked: true, kind: 'recaptcha', reason: 'Google reCAPTCHA verification' }
|
|
89
|
-
if (hasTurnstile) return { blocked: true, kind: 'turnstile', reason: 'Cloudflare Turnstile verification' }
|
|
90
|
-
if (verifyWording && /challenge|captcha|verification|security check|access denied|blocked|\\u9a8c\\u8bc1/i.test(lower)) {
|
|
91
|
-
return { blocked: true, kind: 'generic', reason: 'Human-verification challenge' }
|
|
92
|
-
}
|
|
93
|
-
return { blocked: false }
|
|
94
|
-
})()`;
|
|
95
|
-
/** Stable provider id registered with `ctx.browser`. */
|
|
96
|
-
export const ELECTRON_BROWSER_PROVIDER_ID = 'electron';
|
|
97
|
-
/** CDP method for a full-page screenshot capture. */
|
|
98
|
-
export const CDP_PAGE_CAPTURE_SCREENSHOT = 'Page.captureScreenshot';
|
|
99
|
-
/**
|
|
100
|
-
* The document size out of a `Page.getLayoutMetrics` response.
|
|
101
|
-
*
|
|
102
|
-
* CDP returns `cssContentSize` (the whole document) and `cssLayoutViewport` (what is
|
|
103
|
-
* visible); the newer spellings `contentSize` / `layoutViewport` appear on some
|
|
104
|
-
* versions, so both are accepted. Returns undefined when neither is usable, leaving the
|
|
105
|
-
* caller to capture unscaled rather than guess.
|
|
106
|
-
* @param metrics - the raw CDP response.
|
|
107
|
-
* @returns the document and viewport size in CSS pixels.
|
|
108
|
-
*/
|
|
109
|
-
export function layoutSize(metrics) {
|
|
110
|
-
const pick = (candidates) => {
|
|
111
|
-
for (const candidate of candidates) {
|
|
112
|
-
if (typeof candidate !== 'object' || candidate === null)
|
|
113
|
-
continue;
|
|
114
|
-
const box = candidate;
|
|
115
|
-
if (typeof box.width === 'number' && typeof box.height === 'number' && box.width > 0 && box.height > 0) {
|
|
116
|
-
return { width: box.width, height: box.height };
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
return undefined;
|
|
120
|
-
};
|
|
121
|
-
const content = pick([metrics.cssContentSize, metrics.contentSize]);
|
|
122
|
-
const viewport = pick([metrics.cssLayoutViewport, metrics.layoutViewport]);
|
|
123
|
-
if (content === undefined)
|
|
124
|
-
return undefined;
|
|
125
|
-
return { width: content.width, height: content.height, viewportHeight: viewport?.height ?? content.height };
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* Map CDP cookies onto the shape `dsh_browser_auth` exports.
|
|
129
|
-
*
|
|
130
|
-
* CDP reports a cookie as domain + path rather than a URL, and in seconds rather than
|
|
131
|
-
* milliseconds, so both are converted. Entries missing a name, value or domain are
|
|
132
|
-
* dropped rather than exported as broken cookies the caller cannot restore.
|
|
133
|
-
* @param raw - the `cookies` array from a CDP response, of unknown shape.
|
|
134
|
-
* @returns the mappable cookies.
|
|
135
|
-
*/
|
|
136
|
-
export function toExportedCookies(raw) {
|
|
137
|
-
if (!Array.isArray(raw))
|
|
138
|
-
return [];
|
|
139
|
-
const out = [];
|
|
140
|
-
for (const entry of raw) {
|
|
141
|
-
if (typeof entry !== 'object' || entry === null)
|
|
142
|
-
continue;
|
|
143
|
-
const cookie = entry;
|
|
144
|
-
// An empty domain is as unusable as a missing one: it cannot form a cookie URL, so
|
|
145
|
-
// exporting it would hand the caller something that fails to restore.
|
|
146
|
-
if (typeof cookie.name !== 'string' || cookie.name === '')
|
|
147
|
-
continue;
|
|
148
|
-
if (typeof cookie.value !== 'string')
|
|
149
|
-
continue;
|
|
150
|
-
if (typeof cookie.domain !== 'string' || cookie.domain === '')
|
|
151
|
-
continue;
|
|
152
|
-
const path = typeof cookie.path === 'string' && cookie.path !== '' ? cookie.path : '/';
|
|
153
|
-
// A leading dot means "this domain and its subdomains"; a cookie URL must not keep it.
|
|
154
|
-
const host = cookie.domain.replace(/^\./, '');
|
|
155
|
-
out.push({
|
|
156
|
-
url: `${cookie.secure === true ? 'https' : 'http'}://${host}${path}`,
|
|
157
|
-
name: cookie.name,
|
|
158
|
-
value: cookie.value,
|
|
159
|
-
domain: cookie.domain,
|
|
160
|
-
path,
|
|
161
|
-
...cookie.secure === true ? { secure: true } : {},
|
|
162
|
-
...cookie.httpOnly === true ? { httpOnly: true } : {},
|
|
163
|
-
...typeof cookie.expires === 'number' && cookie.expires > 0 ? { expirationDate: cookie.expires } : {},
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
return out;
|
|
167
|
-
}
|
|
168
|
-
/**
|
|
169
|
-
* Map an exported cookie onto the fields `Storage.setCookies` expects.
|
|
170
|
-
*
|
|
171
|
-
* An exported cookie may carry only a URL, so the domain and path are recovered from it
|
|
172
|
-
* when they are absent; without either, CDP cannot place the cookie and it is skipped.
|
|
173
|
-
* @param cookie - the cookie to convert.
|
|
174
|
-
* @returns the CDP cookie, or undefined when it lacks a usable domain.
|
|
175
|
-
*/
|
|
176
|
-
export function toCdpCookie(cookie) {
|
|
177
|
-
let domain = cookie.domain;
|
|
178
|
-
let path = cookie.path;
|
|
179
|
-
if (domain === undefined || domain === '') {
|
|
180
|
-
try {
|
|
181
|
-
const parsed = new URL(cookie.url);
|
|
182
|
-
domain = parsed.hostname;
|
|
183
|
-
if (path === undefined || path === '')
|
|
184
|
-
path = parsed.pathname === '' ? '/' : parsed.pathname;
|
|
185
|
-
}
|
|
186
|
-
catch {
|
|
187
|
-
return undefined;
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
if (typeof domain !== 'string' || domain === '')
|
|
191
|
-
return undefined;
|
|
192
|
-
return {
|
|
193
|
-
name: cookie.name,
|
|
194
|
-
value: cookie.value,
|
|
195
|
-
domain,
|
|
196
|
-
path: path === undefined || path === '' ? '/' : path,
|
|
197
|
-
...cookie.secure === true ? { secure: true } : {},
|
|
198
|
-
...cookie.httpOnly === true ? { httpOnly: true } : {},
|
|
199
|
-
...typeof cookie.expirationDate === 'number' ? { expires: cookie.expirationDate } : {},
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
/** CDP method for runtime evaluation (the execute path). */
|
|
203
|
-
export const CDP_RUNTIME_EVALUATE = 'Runtime.evaluate';
|
|
204
|
-
/** CDP method for navigation. */
|
|
205
|
-
export const CDP_PAGE_NAVIGATE = 'Page.navigate';
|
|
206
|
-
/** Cap on content returned by a snapshot fetch to keep the wire bounded. */
|
|
207
|
-
const SNAPSHOT_LABEL_MAX = 120;
|
|
208
|
-
/** Named-key table for `key()`: CDP key/code names + Windows virtual key codes. */
|
|
209
|
-
const KEY_SPECS = {
|
|
210
|
-
// `text` is what makes a key produce CHARACTER INPUT rather than only a key event, and form
|
|
211
|
-
// submission depends on the character: pressing Enter in a text field submits the form because
|
|
212
|
-
// the browser processes a carriage return, not because a key went down. Without `text` the event
|
|
213
|
-
// still reaches the page, a `keydown` listener still fires, and nothing happens — reported as
|
|
214
|
-
// issue #36, where `requestSubmit()` worked and this did not.
|
|
215
|
-
//
|
|
216
|
-
// The same omission is why Space used to pass only its key event; that one was already fixed and
|
|
217
|
-
// is the reason the table has a `text` column at all.
|
|
218
|
-
Enter: { key: 'Enter', code: 'Enter', vk: 13, text: '\r' },
|
|
219
|
-
Tab: { key: 'Tab', code: 'Tab', vk: 9 },
|
|
220
|
-
Escape: { key: 'Escape', code: 'Escape', vk: 27 },
|
|
221
|
-
Backspace: { key: 'Backspace', code: 'Backspace', vk: 8 },
|
|
222
|
-
Delete: { key: 'Delete', code: 'Delete', vk: 46 },
|
|
223
|
-
ArrowUp: { key: 'ArrowUp', code: 'ArrowUp', vk: 38 },
|
|
224
|
-
ArrowDown: { key: 'ArrowDown', code: 'ArrowDown', vk: 40 },
|
|
225
|
-
ArrowLeft: { key: 'ArrowLeft', code: 'ArrowLeft', vk: 37 },
|
|
226
|
-
ArrowRight: { key: 'ArrowRight', code: 'ArrowRight', vk: 39 },
|
|
227
|
-
Home: { key: 'Home', code: 'Home', vk: 36 },
|
|
228
|
-
End: { key: 'End', code: 'End', vk: 35 },
|
|
229
|
-
PageUp: { key: 'PageUp', code: 'PageUp', vk: 33 },
|
|
230
|
-
PageDown: { key: 'PageDown', code: 'PageDown', vk: 34 },
|
|
231
|
-
// Space is the one printable key: CDP needs `text` on the keyDown for the
|
|
232
|
-
// character to land in a focused input; without it the key only scrolls.
|
|
233
|
-
Space: { key: ' ', code: 'Space', vk: 32, text: ' ' },
|
|
234
|
-
};
|
|
235
|
-
/** Supported key names, exported for the tool's enum and error messages. */
|
|
236
|
-
export const BROWSER_KEY_NAMES = Object.keys(KEY_SPECS);
|
|
237
|
-
/**
|
|
238
|
-
* Localized names a system Downloads folder may carry, in probe order: the
|
|
239
|
-
* English default first, then the Chinese spellings — a zh-CN desktop calls
|
|
240
|
-
* the folder `下载`, a zh-TW one `下載`, and neither is `Downloads`.
|
|
241
|
-
*/
|
|
242
|
-
const DOWNLOAD_DIR_NAMES = ['Downloads', '下载', '下載'];
|
|
243
|
-
/**
|
|
244
|
-
* Resolve the default download directory when the config names none: an
|
|
245
|
-
* existing `XDG_DOWNLOAD_DIR` wins (the freedesktop standard, which is what a
|
|
246
|
-
* localized Linux desktop writes), then the first localized `Downloads` folder
|
|
247
|
-
* that exists under the home directory, and finally the English name — created
|
|
248
|
-
* on first use — when none exists yet.
|
|
249
|
-
* @returns the absolute default download directory.
|
|
250
|
-
*/
|
|
251
|
-
function defaultDownloadDir() {
|
|
252
|
-
const xdg = process.env.XDG_DOWNLOAD_DIR;
|
|
253
|
-
if (typeof xdg === 'string' && xdg !== '' && existsSync(xdg))
|
|
254
|
-
return xdg;
|
|
255
|
-
for (const name of DOWNLOAD_DIR_NAMES) {
|
|
256
|
-
const candidate = join(homedir(), name);
|
|
257
|
-
if (existsSync(candidate))
|
|
258
|
-
return candidate;
|
|
259
|
-
}
|
|
260
|
-
return join(homedir(), DOWNLOAD_DIR_NAMES[0] ?? 'Downloads');
|
|
261
|
-
}
|
|
262
|
-
/**
|
|
263
|
-
* Whether a directory entry exists at `path`, judging the ENTRY rather than what it
|
|
264
|
-
* points at.
|
|
265
|
-
*
|
|
266
|
-
* `existsSync` follows links, so a DANGLING symlink — a link whose target does not
|
|
267
|
-
* exist — reads as "nothing here", and a write to that path creates the target
|
|
268
|
-
* instead: outside `downloadDir` whenever the link points out of it. `lstatSync`
|
|
269
|
-
* sees the link itself, which is the only correct answer to "is this name free".
|
|
270
|
-
* @param path - the path to judge.
|
|
271
|
-
* @returns true when any entry (file, directory, link) occupies the name.
|
|
272
|
-
*/
|
|
273
|
-
function entryExists(path) {
|
|
274
|
-
try {
|
|
275
|
-
lstatSync(path);
|
|
276
|
-
return true;
|
|
277
|
-
}
|
|
278
|
-
catch {
|
|
279
|
-
return false;
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
27
|
/**
|
|
283
|
-
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
*
|
|
291
|
-
* @param path - an absolute path that may not exist yet.
|
|
292
|
-
* @returns the resolved real path of its deepest existing ancestor.
|
|
28
|
+
* Best-effort interrupt of a wedged page-script evaluation. `Runtime.evaluate`
|
|
29
|
+
* with `awaitPromise` can hold the renderer (and the target's debugger queue)
|
|
30
|
+
* behind a busy loop or a never-settling promise; terminating kills the
|
|
31
|
+
* running script so subsequent commands are not stuck forever. Fire-and-forget:
|
|
32
|
+
* if the interrupt itself hangs, it is ignored. Capped at
|
|
33
|
+
* MAX_PENDING_TERMINATIONS per view to prevent unbounded pending entries
|
|
34
|
+
* when the child is truly stuck.
|
|
35
|
+
* @param handle - the view handle to terminate in.
|
|
293
36
|
*/
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
return current;
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
const parent = dirname(current);
|
|
308
|
-
if (parent === current)
|
|
309
|
-
return current;
|
|
310
|
-
current = parent;
|
|
311
|
-
}
|
|
312
|
-
return current;
|
|
37
|
+
const pendingTerminations = new WeakMap();
|
|
38
|
+
const MAX_PENDING_TERMINATIONS = 3;
|
|
39
|
+
function terminatePage(handle) {
|
|
40
|
+
const count = pendingTerminations.get(handle) ?? 0;
|
|
41
|
+
if (count >= MAX_PENDING_TERMINATIONS)
|
|
42
|
+
return;
|
|
43
|
+
pendingTerminations.set(handle, count + 1);
|
|
44
|
+
void handle.sendCommand('Runtime.terminateExecution', undefined, { present: false, initialize: false }).finally(() => {
|
|
45
|
+
pendingTerminations.set(handle, Math.max(0, (pendingTerminations.get(handle) ?? 1) - 1));
|
|
46
|
+
}).catch(() => { });
|
|
313
47
|
}
|
|
314
48
|
/**
|
|
315
49
|
* Browser provider over Electron views. Sessions hold an ordered list of
|
|
@@ -318,84 +52,7 @@ function realAncestorOf(path) {
|
|
|
318
52
|
* never loses state. Navigation is admitted only for HTTP(S) targets unless
|
|
319
53
|
* {@link ElectronBrowserProviderConfig.httpOnly} is disabled.
|
|
320
54
|
*/
|
|
321
|
-
export class ElectronBrowserProvider {
|
|
322
|
-
host;
|
|
323
|
-
config;
|
|
324
|
-
id = ELECTRON_BROWSER_PROVIDER_ID;
|
|
325
|
-
sessions = new Map();
|
|
326
|
-
carrierLaunchError;
|
|
327
|
-
/**
|
|
328
|
-
* Tick that installs the selection bar in every live tab and collects what the
|
|
329
|
-
* human confirmed. The Desktop sidebar carrier is the shell's own <webview>:
|
|
330
|
-
* the page has no preload bridge and the bridge protocol carries no user-action
|
|
331
|
-
* channel, so the bar leaves its intent in `window.__dshRefIntents` and this
|
|
332
|
-
* pump takes it over CDP. Without it the sidebar has no reference entry.
|
|
333
|
-
*/
|
|
334
|
-
referencePump;
|
|
335
|
-
/** Guards against overlapping pump runs (setInterval keeps firing while one is slow). */
|
|
336
|
-
referencePumping = false;
|
|
337
|
-
/**
|
|
338
|
-
* Set once the carrier swapped to a newer provider. `onUserAction` and
|
|
339
|
-
* `onViewClosed` return void and cannot be unsubscribed, so the callbacks
|
|
340
|
-
* themselves must go inert: otherwise one human click is handled by every
|
|
341
|
-
* old provider still retained by the view host, producing duplicate cards.
|
|
342
|
-
*/
|
|
343
|
-
disposed = false;
|
|
344
|
-
/**
|
|
345
|
-
* The session bound to the page the human has open, created on first sight.
|
|
346
|
-
*
|
|
347
|
-
* A reference is captured from a browser SESSION, and a page the human opened from
|
|
348
|
-
* the sidebar's own address bar belongs to no session of ours. Adopting it into one
|
|
349
|
-
* is what makes the selection bar appear there at all — and it is done here, inside
|
|
350
|
-
* the pump, so it needs nothing from the human and nothing from the agent.
|
|
351
|
-
*/
|
|
352
|
-
referenceSession;
|
|
353
|
-
/** Ticks between sidebar page scans while nothing is adopted yet. */
|
|
354
|
-
referenceScanCountdown = 0;
|
|
355
|
-
/** Last scan's diagnosis, surfaced by {@link referenceStatus}. */
|
|
356
|
-
referenceScan = { pages: 0 };
|
|
357
|
-
httpOnly;
|
|
358
|
-
snapshotMaxElements;
|
|
359
|
-
contentMaxChars;
|
|
360
|
-
downloadDir;
|
|
361
|
-
/**
|
|
362
|
-
* Persistent browsing history, or `undefined` when the user turned it off.
|
|
363
|
-
* Sessions come and go; this record outlives all of them.
|
|
364
|
-
*/
|
|
365
|
-
historyStore;
|
|
366
|
-
/** Live settings source; absent when nothing owns a settings document. */
|
|
367
|
-
settingsSource;
|
|
368
|
-
constructor(host, config = {}) {
|
|
369
|
-
this.host = host;
|
|
370
|
-
this.config = config;
|
|
371
|
-
this.httpOnly = config.httpOnly ?? true;
|
|
372
|
-
this.snapshotMaxElements = config.snapshotMaxElements ?? 60;
|
|
373
|
-
this.contentMaxChars = config.contentMaxChars;
|
|
374
|
-
// Confine downloads AND screenshot saves to a dedicated directory by
|
|
375
|
-
// default: the OS Downloads folder is the human-visible, browser-natural
|
|
376
|
-
// place for written files, and it is the one directory the DSH file
|
|
377
|
-
// sandbox does not have to arbitrate. The localized name is probed so a
|
|
378
|
-
// Chinese desktop (`~/下载`) works without configuring `downloadDir`.
|
|
379
|
-
this.downloadDir = config.downloadDir ?? defaultDownloadDir();
|
|
380
|
-
this.settingsSource = config.settings;
|
|
381
|
-
// Browsing history follows the browser profile's persistence rules (close
|
|
382
|
-
// the interface, lose nothing), and can be switched off from settings.
|
|
383
|
-
this.historyStore = config.history?.enabled === false
|
|
384
|
-
? undefined
|
|
385
|
-
: new HistoryStore(config.history?.file, {
|
|
386
|
-
...config.history?.maxEntries !== undefined ? { maxEntries: config.history.maxEntries } : {},
|
|
387
|
-
...config.history?.maxAgeDays !== undefined ? { maxAgeDays: config.history.maxAgeDays } : {},
|
|
388
|
-
});
|
|
389
|
-
// Route toolbar (host UI) actions into the session model: the human and
|
|
390
|
-
// the agent then always drive the same tabs, history, and navigation.
|
|
391
|
-
this.host.onUserAction?.(action => { if (!this.disposed)
|
|
392
|
-
void this.handleUserAction(action); });
|
|
393
|
-
// A window the human closed ends the session it showed: the next call opens a
|
|
394
|
-
// clean one instead of driving a page nobody can see.
|
|
395
|
-
this.host.onViewClosed?.(windowId => { if (!this.disposed)
|
|
396
|
-
void this.handleViewClosed(windowId); });
|
|
397
|
-
this.startReferenceEntryPump();
|
|
398
|
-
}
|
|
55
|
+
export class ElectronBrowserProvider extends ProviderMedia {
|
|
399
56
|
/** Retire a provider after a carrier swap; its listeners must not act again. */
|
|
400
57
|
dispose() {
|
|
401
58
|
this.disposed = true;
|
|
@@ -495,2754 +152,155 @@ export class ElectronBrowserProvider {
|
|
|
495
152
|
}
|
|
496
153
|
catch (error) {
|
|
497
154
|
this.referenceScan.lastError = 'capture refused: ' + (error instanceof Error ? error.message : String(error));
|
|
498
|
-
process.stderr.write(`[dsh-browser] ${this.referenceScan.lastError}\n`);
|
|
499
|
-
try {
|
|
500
|
-
await this.evaluateInTab(tab, standaloneScript(noticeScript(hostMessages.zh.referenceFailed)), PROVIDER_TIMEOUTS.evaluation);
|
|
501
|
-
}
|
|
502
|
-
catch { /* The failure remains in host diagnostics when the guest disappears. */ }
|
|
503
|
-
}
|
|
504
|
-
return true;
|
|
505
|
-
}
|
|
506
|
-
catch {
|
|
507
|
-
// A tab mid-navigation has no execution context yet; the next tick retries.
|
|
508
|
-
// A page that keeps failing backs off instead of being forgotten: the
|
|
509
|
-
// handle is the only way back to a page this host adopted, and dropping it
|
|
510
|
-
// made the bar stop delivering for the rest of the conversation.
|
|
511
|
-
tab.misses = (tab.misses ?? 0) + 1;
|
|
512
|
-
if (tab.misses >= DEAD_REFERENCE_TAB_MISSES) {
|
|
513
|
-
tab.misses = 0;
|
|
514
|
-
tab.retryAt = Date.now() + DEAD_REFERENCE_TAB_RETRY_MS;
|
|
515
|
-
}
|
|
516
|
-
return true;
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
/** Forget one dead adopted tab; the conversation's next page starts a fresh session. */
|
|
520
|
-
/**
|
|
521
|
-
* Bind the page the human has open in this conversation's sidebar into a session.
|
|
522
|
-
*
|
|
523
|
-
* Why this is the whole entry: the sidebar page is the shell's, opened by a person
|
|
524
|
-
* through the address bar, so no session of ours names it and nothing injects the
|
|
525
|
-
* selection bar into it. The shell DOES expose the panel's pages by conversation id
|
|
526
|
-
* (`listPages`), and can hand one over (`adoptPage`) — the same pair the tools use
|
|
527
|
-
* for `dsh_browser_list_tabs`. Doing it on a timer means the bar appears on a page
|
|
528
|
-
* the human opened themselves, which is the only entry they actually take.
|
|
529
|
-
*
|
|
530
|
-
* Rescans are spaced by one idle tick, not five: the listing crosses the
|
|
531
|
-
* bridge, and a page the human just opened must get its entry within a
|
|
532
|
-
* couple of seconds rather than five.
|
|
533
|
-
*/
|
|
534
|
-
async adoptSidebarPageForReference() {
|
|
535
|
-
const configured = this.config.referenceLabel;
|
|
536
|
-
const label = typeof configured === 'function' ? configured() : configured;
|
|
537
|
-
this.referenceScan.label = label;
|
|
538
|
-
if (label === undefined || label === '')
|
|
539
|
-
return;
|
|
540
|
-
if (this.host.listPages === undefined || this.host.adoptPage === undefined) {
|
|
541
|
-
this.referenceScan.lastError = 'this carrier cannot list or adopt a page it did not open';
|
|
542
|
-
return;
|
|
543
|
-
}
|
|
544
|
-
if (this.referenceScanCountdown > 0) {
|
|
545
|
-
this.referenceScanCountdown -= 1;
|
|
546
|
-
return;
|
|
547
|
-
}
|
|
548
|
-
// One idle tick between scans: a page the human opens must get its entry
|
|
549
|
-
// within a couple of seconds (measured: the shell creates the guest, then
|
|
550
|
-
// the next scan adopts it). The listing is a local bridge call, not a
|
|
551
|
-
// network request, so this is cheap.
|
|
552
|
-
this.referenceScanCountdown = 1;
|
|
553
|
-
let session = this.referenceSession === undefined ? undefined : this.sessions.get(this.referenceSession);
|
|
554
|
-
if (session?.label !== label)
|
|
555
|
-
session = undefined;
|
|
556
|
-
const candidate = session ?? {
|
|
557
|
-
id: sessionWireId(browserSessionHandle(label, randomUUID())), label,
|
|
558
|
-
tabs: [], activeIndex: 0, history: [], nextSeq: 1,
|
|
559
|
-
};
|
|
560
|
-
let pages;
|
|
561
|
-
try {
|
|
562
|
-
// `requireRunning` is what keeps a scan from launching the human's
|
|
563
|
-
// installed browser: only a carrier that is already up can have pages.
|
|
564
|
-
pages = await this.host.listPages(this.carrierScope(candidate), { requireRunning: true });
|
|
565
|
-
}
|
|
566
|
-
catch (error) {
|
|
567
|
-
this.referenceScan.lastError = error instanceof Error ? error.message : String(error);
|
|
568
|
-
return;
|
|
569
|
-
}
|
|
570
|
-
this.referenceScan.pages = pages.length;
|
|
571
|
-
const live = pages.filter(candidate => /^https?:\/\//iu.test(candidate.url));
|
|
572
|
-
// NOT pruned. The host's listing already EXCLUDES the pages this process
|
|
573
|
-
// adopted (that exclusion is what keeps `listTabs` from reporting one page
|
|
574
|
-
// twice), so "absent from the listing" means "already adopted" as often as
|
|
575
|
-
// it means "closed". Dropping those tabs would lose the bar on every page
|
|
576
|
-
// the human switches away from and re-adopt it under a new handle on the
|
|
577
|
-
// way back. A closed page's handle simply stops answering, and the pump
|
|
578
|
-
// already skips a tab it cannot evaluate.
|
|
579
|
-
if (live.length === 0) {
|
|
580
|
-
this.referenceScan.lastError = 'no http page is open in this conversation\'s sidebar';
|
|
581
|
-
return;
|
|
582
|
-
}
|
|
583
|
-
let refused;
|
|
584
|
-
for (const page of live) {
|
|
585
|
-
const tabId = this.carrierTab(candidate, page.id);
|
|
586
|
-
const existing = session?.tabs.find(tab => tab.id === tabId);
|
|
587
|
-
if (existing !== undefined) {
|
|
588
|
-
// A navigation changes the URL of a page we already hold.
|
|
589
|
-
if (existing.url !== page.url)
|
|
590
|
-
existing.url = page.url;
|
|
591
|
-
continue;
|
|
592
|
-
}
|
|
593
|
-
try {
|
|
594
|
-
// The owner is passed so the adopted view is released with THIS
|
|
595
|
-
// conversation and not swept up by, or lost to, another one.
|
|
596
|
-
const handle = await this.host.adoptPage(this.carrierTab(candidate, page.id), this.carrierScope(candidate));
|
|
597
|
-
if (session === undefined) {
|
|
598
|
-
session = candidate;
|
|
599
|
-
this.sessions.set(session.id, session);
|
|
600
|
-
this.referenceSession = session.id;
|
|
601
|
-
}
|
|
602
|
-
// Append only: discovery must never switch the page the human is
|
|
603
|
-
// looking at, nor open a tab they did not ask for.
|
|
604
|
-
session.tabs.push({ id: tabId, handle, url: page.url });
|
|
605
|
-
}
|
|
606
|
-
catch (error) {
|
|
607
|
-
refused = error instanceof Error ? error.message : String(error);
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
if (session !== undefined) {
|
|
611
|
-
session.activeIndex = Math.min(session.activeIndex, Math.max(0, session.tabs.length - 1));
|
|
612
|
-
}
|
|
613
|
-
this.referenceScan.lastError = session === undefined
|
|
614
|
-
? refused ?? 'no page could be adopted'
|
|
615
|
-
: refused;
|
|
616
|
-
}
|
|
617
|
-
/**
|
|
618
|
-
* What the sidebar reference entry is doing right now.
|
|
619
|
-
*
|
|
620
|
-
* Served on the reference route so "there is no selection bar on my page" has an
|
|
621
|
-
* answer that is not a guess: which conversation this process thinks it serves,
|
|
622
|
-
* whether a page was adopted, how many the shell reported, and the last refusal.
|
|
623
|
-
*/
|
|
624
|
-
referenceStatus() {
|
|
625
|
-
return {
|
|
626
|
-
...this.referenceScan.label === undefined ? {} : { label: this.referenceScan.label },
|
|
627
|
-
...this.referenceSession === undefined ? {} : { session: this.referenceSession },
|
|
628
|
-
pages: this.referenceScan.pages,
|
|
629
|
-
...this.referenceScan.lastError === undefined ? {} : { lastError: this.referenceScan.lastError },
|
|
630
|
-
};
|
|
631
|
-
}
|
|
632
|
-
/**
|
|
633
|
-
* Evaluate one expression in a tab and return its value.
|
|
634
|
-
*
|
|
635
|
-
* Bounded on purpose: the pump runs on a timer, and an unresponsive renderer
|
|
636
|
-
* would otherwise hold the whole tick (and every later one) forever.
|
|
637
|
-
* @param tab - the tab to evaluate in.
|
|
638
|
-
* @param expression - the JS expression.
|
|
639
|
-
* @param timeoutMs - how long to wait before treating the page as not answering.
|
|
640
|
-
*/
|
|
641
|
-
async evaluateInTab(tab, expression, timeoutMs = PROVIDER_TIMEOUTS.evaluation) {
|
|
642
|
-
const raw = await withTimeout(tab.handle.sendCommand('Runtime.evaluate', {
|
|
643
|
-
expression, returnByValue: true, awaitPromise: true,
|
|
644
|
-
}), timeoutMs, undefined, `browser: reference probe timed out after ${timeoutMs}ms`);
|
|
645
|
-
const result = raw.result;
|
|
646
|
-
return result?.value;
|
|
647
|
-
}
|
|
648
|
-
/**
|
|
649
|
-
* Usable when the host says it can back views (the self-hosted host probes
|
|
650
|
-
* for a usable Electron binary; the desktop shell is assumed usable).
|
|
651
|
-
*/
|
|
652
|
-
available() {
|
|
653
|
-
return this.host.available?.() ?? true;
|
|
654
|
-
}
|
|
655
|
-
/**
|
|
656
|
-
* Open a NEW browser session with its own view. Every call mints a fresh
|
|
657
|
-
* session id and backing view; per-task reuse is owned by the caller (the
|
|
658
|
-
* tool layer caches one session per DSH task). Sessions are isolated from
|
|
659
|
-
* each other: each keeps its own tabs, active tab, and history, and only
|
|
660
|
-
* the active tab of a session is made visible.
|
|
661
|
-
* @param label - optional human-readable label (e.g. the DSH task id) shown
|
|
662
|
-
* in the window title so a human can tell which task's page is visible.
|
|
663
|
-
*/
|
|
664
|
-
open(label) {
|
|
665
|
-
// The label is the calling DSH task, and it is handed to the view as its owner: a host shared
|
|
666
|
-
// by several conversations (the desktop's) keeps one conversation's page out of another's on
|
|
667
|
-
// the strength of it, so it is not decoration.
|
|
668
|
-
const id = sessionWireId(browserSessionHandle(label || 'default', randomUUID()));
|
|
669
|
-
const tabId = tabWireId({ ...resolveSessionHandle(id), tab: randomUUID() });
|
|
670
|
-
const handle = this.host.createView(tabId);
|
|
671
|
-
// Group the session's views under its own window (one window per
|
|
672
|
-
// session), carrying the label for the window title. Hosts without
|
|
673
|
-
// groupView keep the shared-window behavior.
|
|
674
|
-
this.host.groupView?.(handle, id, label);
|
|
675
|
-
this.sessions.set(id, { id, label, tabs: [{ id: tabId, handle, url: '' }], activeIndex: 0, history: [], nextSeq: 1 });
|
|
676
|
-
return Promise.resolve(id);
|
|
677
|
-
}
|
|
678
|
-
async prepareCarrier(signal, scope) {
|
|
679
|
-
if (this.host.prepare === undefined)
|
|
680
|
-
return;
|
|
681
|
-
signal?.throwIfAborted();
|
|
682
|
-
try {
|
|
683
|
-
await withTimeout(this.host.prepare(scope), PROVIDER_TIMEOUTS.prepare, signal, 'browser: carrier launch timed out before navigating a guest');
|
|
684
|
-
this.carrierLaunchError = undefined;
|
|
685
|
-
}
|
|
686
|
-
catch (error) {
|
|
687
|
-
if (!signal?.aborted)
|
|
688
|
-
this.carrierLaunchError = error;
|
|
689
|
-
throw error;
|
|
690
|
-
}
|
|
691
|
-
}
|
|
692
|
-
async bindPage(session, pageId) {
|
|
693
|
-
const s = this.session(session);
|
|
694
|
-
if (this.host.adoptPage === undefined || !s.label)
|
|
695
|
-
throw new Error('sidebar page binding unsupported');
|
|
696
|
-
if (s.tabs.some(tab => tab.url !== ''))
|
|
697
|
-
throw new Error('source binding requires a fresh browser session');
|
|
698
|
-
const id = tabWireId(resolveTabHandle(resolveSessionHandle(s.id), pageId));
|
|
699
|
-
const handle = await this.host.adoptPage(id, this.carrierScope(s));
|
|
700
|
-
const previous = [...s.tabs];
|
|
701
|
-
s.tabs.splice(0, s.tabs.length, { id: this.carrierTab(s, id), handle, url: '' });
|
|
702
|
-
s.activeIndex = 0;
|
|
703
|
-
for (const tab of previous)
|
|
704
|
-
this.destroyTab(tab);
|
|
705
|
-
}
|
|
706
|
-
/**
|
|
707
|
-
* The most recent open request, for the Web sidebar.
|
|
708
|
-
*
|
|
709
|
-
* On the desktop shell the host half tells the shell to place a tab (`__dshBuiltinBrowser.openPanel`)
|
|
710
|
-
* through the bridge. The Web shell has no such channel, so a tool-opened page lived only in the
|
|
711
|
-
* plugin's own browser while the panel stayed empty — and "open it in the sidebar" took several manual
|
|
712
|
-
* steps. The client polls this one slot and places the tab itself.
|
|
713
|
-
* @returns the last request and when it arrived, or undefined when nothing was opened yet.
|
|
714
|
-
*/
|
|
715
|
-
lastOpenRequest() {
|
|
716
|
-
return this.lastOpen;
|
|
717
|
-
}
|
|
718
|
-
/** Set by {@link openUrl}; read by the client through the HTTP surface. */
|
|
719
|
-
lastOpen;
|
|
720
|
-
async openUrl(session, request, signal) {
|
|
721
|
-
try {
|
|
722
|
-
setLastOpen(request.url, Date.now());
|
|
723
|
-
}
|
|
724
|
-
catch { /* best effort */ }
|
|
725
|
-
const s = this.session(session);
|
|
726
|
-
await this.prepareCarrier(signal, s.id);
|
|
727
|
-
if (request.newTab === true) {
|
|
728
|
-
this.newTab(s);
|
|
729
|
-
}
|
|
730
|
-
// A page the human already has, at the URL being asked for, is the page they mean.
|
|
731
|
-
//
|
|
732
|
-
// Reported as a defect: they opened a page by hand, then a tool call drove the plugin's own
|
|
733
|
-
// blank tab instead and reported nothing about the page on screen — so the obvious conclusion
|
|
734
|
-
// was "the page is broken", and opening the same URL again produced a SECOND tab. Reusing the
|
|
735
|
-
// existing page is both what the request says and what a person expects.
|
|
736
|
-
//
|
|
737
|
-
// Only an exact match after normalisation: a deliberate navigation to a different URL must not
|
|
738
|
-
// be redirected to whatever page happens to be open.
|
|
739
|
-
const tab = this.activeTab(s);
|
|
740
|
-
const transaction = this.beginNavigation(tab, signal);
|
|
741
|
-
const { navigation } = transaction;
|
|
742
|
-
signal = transaction.signal;
|
|
743
|
-
if (request.newTab !== true && await this.adoptMatchingPage(s, request.url, tab, navigation, signal))
|
|
744
|
-
return;
|
|
745
|
-
await this.navigateTab(s, tab, request.url, navigation, signal);
|
|
746
|
-
}
|
|
747
|
-
/**
|
|
748
|
-
* Bind the carrier page that already shows this URL, if there is one.
|
|
749
|
-
*
|
|
750
|
-
* Compare the part of a URL that says WHICH page it is: scheme, host, path and query. A hash is a
|
|
751
|
-
* position inside a document, and a trailing slash is spelling, so neither makes a different page.
|
|
752
|
-
* @param s - the session to bind the page into.
|
|
753
|
-
* @param url - the URL being opened.
|
|
754
|
-
* @returns whether an existing page was taken over.
|
|
755
|
-
*/
|
|
756
|
-
async adoptMatchingPage(s, url, target, navigation, signal) {
|
|
757
|
-
if (this.host.adoptPage === undefined || this.host.listPages === undefined)
|
|
758
|
-
return false;
|
|
759
|
-
const wanted = this.comparableUrl(url);
|
|
760
|
-
if (wanted === undefined)
|
|
761
|
-
return false;
|
|
762
|
-
let pages;
|
|
763
|
-
try {
|
|
764
|
-
pages = await this.host.listPages(this.carrierScope(s));
|
|
765
|
-
}
|
|
766
|
-
catch {
|
|
767
|
-
// A listing must not turn "nothing to reuse" into "open failed".
|
|
768
|
-
return false;
|
|
769
|
-
}
|
|
770
|
-
this.checkNavigation(target, navigation);
|
|
771
|
-
const match = pages.find(page => this.comparableUrl(page.url) === wanted);
|
|
772
|
-
if (match === undefined)
|
|
773
|
-
return false;
|
|
774
|
-
let handle;
|
|
775
|
-
try {
|
|
776
|
-
handle = await this.host.adoptPage(this.carrierTab(s, match.id), this.carrierScope(s));
|
|
777
|
-
}
|
|
778
|
-
catch {
|
|
779
|
-
// The page went away between listing and adopting: fall through to an ordinary navigation.
|
|
780
|
-
return false;
|
|
781
|
-
}
|
|
782
|
-
if (target.navigation !== navigation) {
|
|
783
|
-
this.host.destroyView(handle, { keepPage: true });
|
|
784
|
-
this.checkNavigation(target, navigation);
|
|
785
|
-
}
|
|
786
|
-
const tab = { id: this.carrierTab(s, match.id), handle, url: match.url, navigation, navigationAbort: target.navigationAbort };
|
|
787
|
-
delete target.navigationAbort;
|
|
788
|
-
s.tabs.push(tab);
|
|
789
|
-
s.activeIndex = s.tabs.length - 1;
|
|
790
|
-
const document = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation); });
|
|
791
|
-
await this.settleDocument(handle, document, signal, { frameId: document.id, loaderId: document.loaderId }, () => { this.checkNavigation(tab, navigation); });
|
|
792
|
-
this.showActive(s, true);
|
|
793
|
-
return true;
|
|
794
|
-
}
|
|
795
|
-
/** The parts of a URL that decide identity, or undefined when it cannot be parsed. */
|
|
796
|
-
comparableUrl(url) {
|
|
797
|
-
if (url === '' || url === 'about:blank')
|
|
798
|
-
return undefined;
|
|
799
|
-
try {
|
|
800
|
-
const parsed = new URL(url);
|
|
801
|
-
return `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\/+$/, '')}${parsed.search}`;
|
|
802
|
-
}
|
|
803
|
-
catch {
|
|
804
|
-
return undefined;
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
/** List the session's tabs with their titles. */
|
|
808
|
-
async listTabs(session) {
|
|
809
|
-
const s = this.session(session);
|
|
810
|
-
const result = [];
|
|
811
|
-
for (let i = 0; i < s.tabs.length; i++) {
|
|
812
|
-
const tab = s.tabs[i];
|
|
813
|
-
if (tab === undefined)
|
|
814
|
-
continue; // defensive: array can shift under concurrency
|
|
815
|
-
// A tab we know has never navigated is NOT probed: its view has committed no document, so
|
|
816
|
-
// the round trip can only answer nothing — and it is the round trip that costs. A tab that
|
|
817
|
-
// HAS navigated is re-read, because the page may have moved itself since; a read that fails
|
|
818
|
-
// keeps the last accepted URL rather than reporting the tab as blank.
|
|
819
|
-
const liveUrl = tab.failure !== undefined ? tab.url : tab.url === '' ? '' : await this.currentUrl(tab.handle).catch(() => tab.url);
|
|
820
|
-
if (liveUrl !== '')
|
|
821
|
-
tab.url = liveUrl;
|
|
822
|
-
result.push({
|
|
823
|
-
id: tab.id,
|
|
824
|
-
url: liveUrl,
|
|
825
|
-
active: i === s.activeIndex,
|
|
826
|
-
});
|
|
827
|
-
}
|
|
828
|
-
// Pages the CARRIER holds that this provider never created.
|
|
829
|
-
//
|
|
830
|
-
// A sidebar panel and an installed browser both open pages on their own: a click on a link
|
|
831
|
-
// that targets a new page, or any `window.open`, produces a page nothing tells us about.
|
|
832
|
-
// Reporting only our own tabs made those invisible to this tool and unclosable through
|
|
833
|
-
// `dsh_browser_close_tab`, so they accumulated for the life of the browser. Measured on the
|
|
834
|
-
// sidebar carrier: three clicks produced three webview guests while this listed one tab.
|
|
835
|
-
//
|
|
836
|
-
// Hosts exclude pages already attached to provider views.
|
|
837
|
-
const pages = await this.host.listPages?.(this.carrierScope(s)) ?? [];
|
|
838
|
-
for (const page of pages) {
|
|
839
|
-
// A page with no URL is a blank one the carrier opened for itself. Listing it would invite a
|
|
840
|
-
// caller to act on nothing, and the blank normalisation already closes those.
|
|
841
|
-
if (page.url === '' || page.url === 'about:blank')
|
|
842
|
-
continue;
|
|
843
|
-
result.push({ id: this.carrierTab(s, page.id), url: page.url, active: false });
|
|
844
|
-
}
|
|
845
|
-
return result;
|
|
846
|
-
}
|
|
847
|
-
/** Switch to a tab by id, making its view visible. */
|
|
848
|
-
async switchTab(session, tabId) {
|
|
849
|
-
const s = this.session(session);
|
|
850
|
-
// A page the carrier owns. Before this, switching to one threw "not open in this session" —
|
|
851
|
-
// while `dsh_browser_list_tabs` was happily listing it, so the two tools disagreed and the
|
|
852
|
-
// page the human was looking at could not be reached (reported as a defect).
|
|
853
|
-
const carrierId = this.carrierId(s, tabId);
|
|
854
|
-
if (carrierId !== undefined) {
|
|
855
|
-
const existing = s.tabs.findIndex(tab => tab.id === tabId);
|
|
856
|
-
if (existing !== -1) {
|
|
857
|
-
await this.host.presentView?.(s.tabs[existing].handle, s.label, { quiet: this.isQuiet(), select: true });
|
|
858
|
-
s.activeIndex = existing;
|
|
859
|
-
this.showActive(s, true);
|
|
860
|
-
return;
|
|
861
|
-
}
|
|
862
|
-
const id = carrierId;
|
|
863
|
-
if (this.host.adoptPage === undefined) {
|
|
864
|
-
throw new BrowserError('browser: this carrier cannot hand over a page it opened itself, so that page cannot be driven. '
|
|
865
|
-
+ 'Open the URL through dsh_browser_open instead — that creates a page this plugin owns.', 'BROWSER_TAB_NOT_FOUND');
|
|
866
|
-
}
|
|
867
|
-
const pages = await this.host.listPages?.(this.carrierScope(s)).catch(() => []) ?? [];
|
|
868
|
-
const page = pages.find(candidate => candidate.id === id);
|
|
869
|
-
const handle = await this.host.adoptPage(id, this.carrierScope(s));
|
|
870
|
-
try {
|
|
871
|
-
// An adopted guest already has a document. Marking it as our never-opened
|
|
872
|
-
// blank view makes the first snapshot/a11y return without reading it.
|
|
873
|
-
const url = page?.url || await this.currentUrl(handle);
|
|
874
|
-
if (url === '')
|
|
875
|
-
throw new BrowserError('browser: the adopted page did not report its document URL', 'BROWSER_TAB_NOT_FOUND');
|
|
876
|
-
const tab = { id: tabId, handle, url };
|
|
877
|
-
await this.host.presentView?.(handle, s.label, { quiet: this.isQuiet(), select: true });
|
|
878
|
-
s.tabs.push(tab);
|
|
879
|
-
s.activeIndex = s.tabs.length - 1;
|
|
880
|
-
this.showActive(s, true);
|
|
881
|
-
}
|
|
882
|
-
catch (error) {
|
|
883
|
-
this.host.destroyView(handle, { keepPage: true });
|
|
884
|
-
throw error;
|
|
885
|
-
}
|
|
886
|
-
return;
|
|
887
|
-
}
|
|
888
|
-
const found = this.locateTab(session, tabId);
|
|
889
|
-
found.s.activeIndex = found.index;
|
|
890
|
-
this.showActive(found.s, true);
|
|
891
|
-
}
|
|
892
|
-
/** Close one tab; closing the active tab activates the next. */
|
|
893
|
-
async closeTab(session, tabId) {
|
|
894
|
-
const current = this.session(session);
|
|
895
|
-
const carrierId = this.carrierId(current, tabId);
|
|
896
|
-
// A page the carrier owns rather than a view we created. It was reported by `listTabs` under
|
|
897
|
-
// this prefix, so closing it here is what keeps the two tools consistent — a page that can be
|
|
898
|
-
// listed must be closable, or the listing reads as a contradiction.
|
|
899
|
-
if (carrierId !== undefined) {
|
|
900
|
-
const id = carrierId;
|
|
901
|
-
if (this.host.closePage === undefined) {
|
|
902
|
-
return Promise.reject(new BrowserError('browser: this carrier does not expose the pages it opens on its own, so that page cannot be closed', 'BROWSER_TAB_NOT_FOUND'));
|
|
903
|
-
}
|
|
904
|
-
await this.host.closePage(id, this.carrierScope(current));
|
|
905
|
-
if (!this.session(session).tabs.some(tab => tab.id === tabId))
|
|
906
|
-
return;
|
|
907
|
-
}
|
|
908
|
-
const found = this.locateTab(session, tabId);
|
|
909
|
-
const s = found.s;
|
|
910
|
-
const index = found.index;
|
|
911
|
-
const removed = s.tabs[index];
|
|
912
|
-
if (removed !== undefined) {
|
|
913
|
-
s.tabs.splice(index, 1);
|
|
914
|
-
this.destroyTab(removed, { keepPage: carrierId !== undefined });
|
|
915
|
-
}
|
|
916
|
-
if (s.tabs.length === 0) {
|
|
917
|
-
// Session keeps one blank tab so it stays usable.
|
|
918
|
-
this.newTab(s);
|
|
919
|
-
}
|
|
920
|
-
else if (index < s.activeIndex) {
|
|
921
|
-
// Closing a tab before the active one shifts the array left; keep the
|
|
922
|
-
// same tab active by decrementing the index.
|
|
923
|
-
s.activeIndex -= 1;
|
|
924
|
-
}
|
|
925
|
-
else if (index === s.activeIndex) {
|
|
926
|
-
// The active tab itself was closed; activate the next tab (the one that
|
|
927
|
-
// shifted into its place), or the last one when the closed tab was the
|
|
928
|
-
// last.
|
|
929
|
-
s.activeIndex = Math.min(index, s.tabs.length - 1);
|
|
930
|
-
}
|
|
931
|
-
this.showActive(s);
|
|
932
|
-
return Promise.resolve();
|
|
933
|
-
}
|
|
934
|
-
/**
|
|
935
|
-
* Find a canonical tab within the calling session.
|
|
936
|
-
*/
|
|
937
|
-
locateTab(session, tabId) {
|
|
938
|
-
const s = this.session(session);
|
|
939
|
-
resolveTabHandle(resolveSessionHandle(session), tabId);
|
|
940
|
-
const own = s.tabs.findIndex(tab => tab.id === tabId);
|
|
941
|
-
if (own >= 0)
|
|
942
|
-
return { s, index: own };
|
|
943
|
-
const ownIds = s.tabs.map(t => t.id).join(', ') || '(none)';
|
|
944
|
-
throw new BrowserError(`browser: tab "${tabId}" is not open in this session (session tabs: ${ownIds})`, 'BROWSER_TAB_UNKNOWN');
|
|
945
|
-
}
|
|
946
|
-
/** Close every tab and reset to one blank tab. */
|
|
947
|
-
reset(session) {
|
|
948
|
-
const s = this.session(session);
|
|
949
|
-
for (const tab of s.tabs)
|
|
950
|
-
this.destroyTab(tab);
|
|
951
|
-
s.tabs.length = 0;
|
|
952
|
-
this.newTab(s);
|
|
953
|
-
s.activeIndex = 0;
|
|
954
|
-
this.showActive(s);
|
|
955
|
-
return Promise.resolve();
|
|
956
|
-
}
|
|
957
|
-
/** Navigate the active tab's view to a URL, honoring HTTP(S)-only admission. */
|
|
958
|
-
async navigate(session, request, signal) {
|
|
959
|
-
const s = this.session(session);
|
|
960
|
-
await this.prepareCarrier(signal, s.id);
|
|
961
|
-
const tab = this.activeTab(s);
|
|
962
|
-
const transaction = this.beginNavigation(tab, signal);
|
|
963
|
-
const { navigation } = transaction;
|
|
964
|
-
signal = transaction.signal;
|
|
965
|
-
await this.navigateTab(s, tab, request.url, navigation, signal);
|
|
966
|
-
}
|
|
967
|
-
beginNavigation(tab, signal) {
|
|
968
|
-
signal?.throwIfAborted();
|
|
969
|
-
const previous = tab.navigationAbort;
|
|
970
|
-
tab.navigation = Symbol();
|
|
971
|
-
tab.navigationAbort = new AbortController();
|
|
972
|
-
previous?.abort(Object.assign(new Error('a newer navigation was requested for this browser tab'), { code: 'panel-navigation-superseded' }));
|
|
973
|
-
return { navigation: tab.navigation, signal: signal === undefined ? tab.navigationAbort.signal : AbortSignal.any([signal, tab.navigationAbort.signal]) };
|
|
974
|
-
}
|
|
975
|
-
checkNavigation(tab, navigation) {
|
|
976
|
-
if (tab.failure !== undefined)
|
|
977
|
-
throw tab.failure;
|
|
978
|
-
if (![...this.sessions.values()].some(session => session.tabs.includes(tab))) {
|
|
979
|
-
throw new BrowserError('browser: the navigation guest was closed', 'BROWSER_GUEST_CLOSED');
|
|
980
|
-
}
|
|
981
|
-
if (tab.navigation !== navigation) {
|
|
982
|
-
throw Object.assign(new Error('a newer navigation was requested for this browser tab'), { code: 'panel-navigation-superseded' });
|
|
983
|
-
}
|
|
984
|
-
}
|
|
985
|
-
async navigateTab(s, tab, url, navigation, signal) {
|
|
986
|
-
const { handle } = tab;
|
|
987
|
-
this.checkNavigation(tab, navigation);
|
|
988
|
-
try {
|
|
989
|
-
if (this.httpOnly) {
|
|
990
|
-
let parsed;
|
|
991
|
-
try {
|
|
992
|
-
parsed = new URL(url);
|
|
993
|
-
}
|
|
994
|
-
catch {
|
|
995
|
-
throw new BrowserError(`browser: refusing navigation to unparseable URL "${url}"`, 'BROWSER_NAVIGATION_BLOCKED');
|
|
996
|
-
}
|
|
997
|
-
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
998
|
-
throw new BrowserError(`browser: refusing navigation to non-HTTP(S) URL "${url}"`, 'BROWSER_NAVIGATION_BLOCKED');
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
signal?.throwIfAborted();
|
|
1002
|
-
// Page.navigate can hang on an unreachable/slow host; bound it like the
|
|
1003
|
-
// evaluate paths so a wedged navigation surfaces as an error instead of
|
|
1004
|
-
// blocking the tool call forever.
|
|
1005
|
-
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
1006
|
-
const deadline = Date.now() + timeoutMs;
|
|
1007
|
-
// Document identity of the page we are leaving (see settleDocument).
|
|
1008
|
-
const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation); }, deadline).catch(() => undefined);
|
|
1009
|
-
this.checkNavigation(tab, navigation);
|
|
1010
|
-
signal?.throwIfAborted();
|
|
1011
|
-
const result = await withTimeout(handle.sendCommand(CDP_PAGE_NAVIGATE, { url }, { deadline, signal }), Math.max(1, deadline - Date.now()), signal, `browser: navigation timed out after ${timeoutMs}ms`,
|
|
1012
|
-
// Best-effort: cancel the in-flight navigation so a wedged load does
|
|
1013
|
-
// not leave the debugger queue busy.
|
|
1014
|
-
timedOut => { if (tab.navigation === navigation)
|
|
1015
|
-
this.interrupt(handle, timedOut); });
|
|
1016
|
-
// Page.navigate resolves even when the navigation fails; surface the
|
|
1017
|
-
// failure instead of leaving a silent white screen.
|
|
1018
|
-
this.checkNavigation(tab, navigation);
|
|
1019
|
-
const errorText = result?.errorText;
|
|
1020
|
-
if (typeof errorText === 'string' && errorText !== '') {
|
|
1021
|
-
throw new BrowserError(`browser: navigation to "${url}" failed: ${errorText}`, 'BROWSER_NAVIGATION_FAILED');
|
|
1022
|
-
}
|
|
1023
|
-
signal?.throwIfAborted();
|
|
1024
|
-
const acknowledgement = result;
|
|
1025
|
-
if (typeof acknowledgement?.frameId !== 'string' || acknowledgement.frameId === '') {
|
|
1026
|
-
throw new BrowserError('browser: navigation returned no frame acknowledgement', 'BROWSER_DOCUMENT_UNACKNOWLEDGED');
|
|
1027
|
-
}
|
|
1028
|
-
if (acknowledgement.loaderId === undefined ? before === undefined
|
|
1029
|
-
: typeof acknowledgement.loaderId !== 'string' || acknowledgement.loaderId === '') {
|
|
1030
|
-
throw new BrowserError('browser: navigation returned no document acknowledgement', 'BROWSER_DOCUMENT_UNACKNOWLEDGED');
|
|
1031
|
-
}
|
|
1032
|
-
tab.url = url;
|
|
1033
|
-
await this.settleDocument(handle, before, signal, acknowledgement, () => { this.checkNavigation(tab, navigation); }, undefined, deadline);
|
|
1034
|
-
this.checkNavigation(tab, navigation);
|
|
1035
|
-
this.record(s, 'navigate', { url }, true);
|
|
1036
|
-
this.recordVisit(s, handle);
|
|
1037
|
-
this.showActive(s, true);
|
|
1038
|
-
}
|
|
1039
|
-
catch (error) {
|
|
1040
|
-
const code = error?.code;
|
|
1041
|
-
if (tab.navigation === navigation && (code === 'BROWSER_DOCUMENT_TIMEOUT' || code === 'BROWSER_DOCUMENT_UNACKNOWLEDGED')) {
|
|
1042
|
-
this.quarantine(handle);
|
|
1043
|
-
}
|
|
1044
|
-
if (!(error instanceof BrowserError && error.code === 'BROWSER_NAVIGATION_BLOCKED')) {
|
|
1045
|
-
this.record(s, 'navigate', { url }, false, { error: String(error) });
|
|
1046
|
-
}
|
|
1047
|
-
throw error;
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
async documentIdentity(handle, signal, checkCurrent, deadline = Date.now() + PROVIDER_TIMEOUTS.evaluation, allowErrorDocument = false) {
|
|
1051
|
-
signal?.throwIfAborted();
|
|
1052
|
-
checkCurrent?.();
|
|
1053
|
-
return mainDocument(await withTimeout(handle.sendCommand('Page.getFrameTree', undefined, { present: false, initialize: false }), Math.max(1, Math.min(PROVIDER_TIMEOUTS.evaluation, deadline - Date.now())), signal, 'browser: document identity timed out', timedOut => {
|
|
1054
|
-
try {
|
|
1055
|
-
checkCurrent?.();
|
|
1056
|
-
}
|
|
1057
|
-
catch {
|
|
1058
|
-
return;
|
|
1059
|
-
}
|
|
1060
|
-
this.interrupt(handle, timedOut);
|
|
1061
|
-
}), { allowErrorDocument });
|
|
1062
|
-
}
|
|
1063
|
-
/**
|
|
1064
|
-
* Page.navigate resolves at navigation COMMIT, not at load: the new document
|
|
1065
|
-
* is already current (so location.href and document.title are the new page's)
|
|
1066
|
-
* while its DOM is still being parsed. dsh_browser_open snapshots immediately
|
|
1067
|
-
* after navigating, which is why it could report the right title with zero
|
|
1068
|
-
* interactive elements — and why a separate dsh_browser_snapshot right after
|
|
1069
|
-
* always found them.
|
|
1070
|
-
*
|
|
1071
|
-
* The CDP frame/loader acknowledgement, not elapsed time or URL equality,
|
|
1072
|
-
* identifies the document whose parse readiness can complete the transaction.
|
|
1073
|
-
*/
|
|
1074
|
-
async settleDocument(handle, before, signal, acknowledgement, checkCurrent, historyEntry, deadline = Date.now() + DEFAULT_OPERATION_TIMEOUT_MS, allowErrorDocument = false) {
|
|
1075
|
-
// The document is being replaced, so the synthetic pointer drawn into the old one
|
|
1076
|
-
// is gone. Dropping the remembered position is what lets it be painted again:
|
|
1077
|
-
// without this, a paint at coincidentally identical coordinates would be skipped
|
|
1078
|
-
// and the pointer would never come back after a navigation.
|
|
1079
|
-
forgetCursor(handle);
|
|
1080
|
-
for (;;) {
|
|
1081
|
-
signal?.throwIfAborted();
|
|
1082
|
-
checkCurrent?.();
|
|
1083
|
-
const remaining = deadline - Date.now();
|
|
1084
|
-
if (remaining <= 0) {
|
|
1085
|
-
this.quarantine(handle);
|
|
1086
|
-
throw new BrowserError('browser: the navigation document was not ready within its deadline', 'BROWSER_DOCUMENT_TIMEOUT');
|
|
1087
|
-
}
|
|
1088
|
-
const ready = await withTimeout((async () => {
|
|
1089
|
-
if (historyEntry !== undefined) {
|
|
1090
|
-
const history = await handle.sendCommand('Page.getNavigationHistory');
|
|
1091
|
-
if (history.entries?.[history.currentIndex ?? -1]?.id !== historyEntry)
|
|
1092
|
-
return false;
|
|
1093
|
-
}
|
|
1094
|
-
const current = await this.documentIdentity(handle, signal, checkCurrent, deadline, allowErrorDocument);
|
|
1095
|
-
if (acknowledgement?.frameId !== undefined && current.id !== acknowledgement.frameId) {
|
|
1096
|
-
throw new BrowserError('browser: navigation frame was superseded', 'BROWSER_NAVIGATION_SUPERSEDED');
|
|
1097
|
-
}
|
|
1098
|
-
const loader = acknowledgement?.loaderId ?? (acknowledgement === undefined ? undefined : before?.loaderId);
|
|
1099
|
-
if (loader !== undefined && current.loaderId !== loader) {
|
|
1100
|
-
if (current.loaderId === before?.loaderId)
|
|
1101
|
-
return false;
|
|
1102
|
-
throw new BrowserError('browser: navigation document was superseded', 'BROWSER_NAVIGATION_SUPERSEDED');
|
|
1103
|
-
}
|
|
1104
|
-
if (acknowledgement === undefined && current.loaderId === before?.loaderId)
|
|
1105
|
-
return false;
|
|
1106
|
-
return documentReady(handle, current, () => {
|
|
1107
|
-
signal?.throwIfAborted();
|
|
1108
|
-
checkCurrent?.();
|
|
1109
|
-
if (Date.now() >= deadline) {
|
|
1110
|
-
this.quarantine(handle);
|
|
1111
|
-
throw new BrowserError('browser: document readiness deadline expired', 'BROWSER_DOCUMENT_TIMEOUT');
|
|
1112
|
-
}
|
|
1113
|
-
});
|
|
1114
|
-
})(), remaining, signal, 'browser: document readiness timed out', timedOut => {
|
|
1115
|
-
try {
|
|
1116
|
-
checkCurrent?.();
|
|
1117
|
-
}
|
|
1118
|
-
catch {
|
|
1119
|
-
return;
|
|
1120
|
-
}
|
|
1121
|
-
this.interrupt(handle, timedOut);
|
|
1122
|
-
});
|
|
1123
|
-
signal?.throwIfAborted();
|
|
1124
|
-
checkCurrent?.();
|
|
1125
|
-
if (ready)
|
|
1126
|
-
return;
|
|
1127
|
-
await delay(Math.min(SETTLE_POLL_MS, Math.max(0, deadline - Date.now())), signal);
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
/**
|
|
1131
|
-
* Make sure the active tab's view can actually receive synthesized input.
|
|
1132
|
-
* Chromium drops `Input.*` events for a view with no display surface, so this
|
|
1133
|
-
* runs before click/type/key and fails loudly (BROWSER_VIEW_NOT_PRESENTED)
|
|
1134
|
-
* rather than reporting a success the page never saw.
|
|
1135
|
-
* @param s - the session whose active view must be presented.
|
|
1136
|
-
* @param signal - optional cancellation.
|
|
1137
|
-
* @returns the view the session's active tab has AFTER the presentation barrier.
|
|
1138
|
-
*/
|
|
1139
|
-
async present(s, signal) {
|
|
1140
|
-
const { handle } = this.activeTab(s);
|
|
1141
|
-
const present = this.host.presentView?.bind(this.host);
|
|
1142
|
-
if (present === undefined) {
|
|
1143
|
-
this.showActive(s);
|
|
1144
|
-
return this.activeTab(s).handle;
|
|
1145
|
-
}
|
|
1146
|
-
signal?.throwIfAborted();
|
|
1147
|
-
const timeoutMs = PROVIDER_TIMEOUTS.lookup;
|
|
1148
|
-
try {
|
|
1149
|
-
await withTimeout(present(handle, s.label, { quiet: this.isQuiet() }), timeoutMs, signal, `browser: presenting the page view timed out after ${timeoutMs}ms`);
|
|
1150
|
-
this.showActive(s);
|
|
1151
|
-
}
|
|
1152
|
-
catch (error) {
|
|
1153
|
-
throw new BrowserError(`browser: the page view is not presented, so synthesized input would be silently dropped (${String(error)})`, 'BROWSER_VIEW_NOT_PRESENTED', { cause: error });
|
|
1154
|
-
}
|
|
1155
|
-
// Read the active tab AGAIN. `present` is a round-trip that can take up to the budget
|
|
1156
|
-
// above, and the human is invited to drive the same window (a toolbar tab switch, a
|
|
1157
|
-
// closed window) while the agent waits. Chromium answers `Input.*` with success even
|
|
1158
|
-
// for a view that has no display surface, so dispatching to a handle that is no longer
|
|
1159
|
-
// the visible one does not fail — it silently lands nowhere, or on the wrong page.
|
|
1160
|
-
//
|
|
1161
|
-
// Returning the re-read handle was wrong, though: `handle` above is the one that was
|
|
1162
|
-
// actually presented, and if the active tab changed during the round trip then the
|
|
1163
|
-
// re-read one was never presented at all. Handing it back meant the caller dispatched
|
|
1164
|
-
// to a view with no display surface — the exact failure this method exists to prevent,
|
|
1165
|
-
// arrived at from the other side. Either the presented view is still the active one, or
|
|
1166
|
-
// the caller must be told rather than given something else to aim at.
|
|
1167
|
-
const live = this.activeTab(s).handle;
|
|
1168
|
-
if (live !== handle) {
|
|
1169
|
-
throw new BrowserError('browser: the active tab changed while the page view was being presented, so synthesized input would go to an unshown view — retry, and the new page will be presented instead', 'BROWSER_VIEW_CHANGED');
|
|
1170
|
-
}
|
|
1171
|
-
return handle;
|
|
1172
|
-
}
|
|
1173
|
-
/**
|
|
1174
|
-
* Refuse to send synthesized input to a view that is no longer the one it was located
|
|
1175
|
-
* against.
|
|
1176
|
-
*
|
|
1177
|
-
* `locateHandle` was captured before a page-side locate that can consume its whole
|
|
1178
|
-
* 10s budget; the session's active tab is re-read afterwards. If they differ, the human
|
|
1179
|
-
* switched tabs mid-flight (the product's whole point is that they can take over), and
|
|
1180
|
-
* the coordinates belong to one page while the dispatch would go to another. Comparing
|
|
1181
|
-
* the handles turns that into a loud, retryable error instead of input the caller
|
|
1182
|
-
* believes landed.
|
|
1183
|
-
* @param session - the session id, for the message.
|
|
1184
|
-
* @param locateHandle - the view the locate ran in.
|
|
1185
|
-
* @param liveHandle - the view that is active now.
|
|
1186
|
-
*/
|
|
1187
|
-
assertSameView(session, locateHandle, liveHandle) {
|
|
1188
|
-
if (locateHandle === liveHandle)
|
|
1189
|
-
return;
|
|
1190
|
-
throw new BrowserError(`browser: the session's active view changed while the element was being located (session ${session}); the operation was not dispatched — retry it`, 'BROWSER_VIEW_CHANGED');
|
|
1191
|
-
}
|
|
1192
|
-
/**
|
|
1193
|
-
* Give the view web focus before synthesizing keyboard input.
|
|
1194
|
-
*
|
|
1195
|
-
* A renderer only delivers key events to the view that holds web focus. A
|
|
1196
|
-
* view that was created but never clicked holds none — and `Input` events
|
|
1197
|
-
* injected over CDP do not grant it — so the FIRST `dsh_browser_key` of a fresh
|
|
1198
|
-
* session vanished inside the renderer while the command still answered
|
|
1199
|
-
* success. Hosts that cannot focus a view (a test double, a different shell
|
|
1200
|
-
* adapter) simply have no `focus`, and nothing changes for them.
|
|
1201
|
-
*/
|
|
1202
|
-
async focusView(handle) {
|
|
1203
|
-
if (handle.focus === undefined)
|
|
1204
|
-
return;
|
|
1205
|
-
const quiet = this.isQuiet();
|
|
1206
|
-
try {
|
|
1207
|
-
// Bounded, unlike the rest of this call: the child RPC has no timeout of its own,
|
|
1208
|
-
// and this runs before typing, so an unresponsive child would hang dsh_browser_key for
|
|
1209
|
-
// good. A timeout is caught below exactly like any other focus failure, so the
|
|
1210
|
-
// best-effort contract is unchanged.
|
|
1211
|
-
await withTimeout(handle.focus(quiet ? { quiet } : undefined), PROVIDER_TIMEOUTS.interaction, undefined, 'browser: focusing the view timed out');
|
|
1212
|
-
}
|
|
1213
|
-
catch (error) {
|
|
1214
|
-
if (quiet)
|
|
1215
|
-
throw error;
|
|
1216
|
-
// Best-effort: a view that refuses focus must not fail the caller's key
|
|
1217
|
-
// press; the dispatch below reports a real channel failure itself.
|
|
1218
|
-
}
|
|
1219
|
-
}
|
|
1220
|
-
/** Execute JS in the active tab's page context. */
|
|
1221
|
-
async execute(session, request, signal) {
|
|
1222
|
-
this.assertActionAllowed('execute');
|
|
1223
|
-
return this.evaluatePage(session, request, signal);
|
|
1224
|
-
}
|
|
1225
|
-
/** Run a fixed browser operation; the request cannot contain a script. */
|
|
1226
|
-
async pageOperation(session, request, signal) {
|
|
1227
|
-
const script = pageOperationScript(request);
|
|
1228
|
-
if (request.operation === 'drag') {
|
|
1229
|
-
return this.dispatchPointer(session, request.from, request.to, request.steps, signal);
|
|
1230
|
-
}
|
|
1231
|
-
if (request.operation === 'probe' && request.method === 'hoverAt') {
|
|
1232
|
-
const point = { x: Number(request.args?.[0]), y: Number(request.args?.[1]) };
|
|
1233
|
-
return this.dispatchPointer(session, point, undefined, 1, signal);
|
|
1234
|
-
}
|
|
1235
|
-
return this.evaluatePage(session, { script }, signal);
|
|
1236
|
-
}
|
|
1237
|
-
/** Send page pointer input through CDP while preserving presentation and cancellation policy. */
|
|
1238
|
-
async dispatchPointer(session, from, to, steps, signal) {
|
|
1239
|
-
const coordinates = [from.x, from.y, ...to === undefined ? [] : [to.x, to.y]];
|
|
1240
|
-
if (coordinates.some(value => !Number.isFinite(value) || value < 0)) {
|
|
1241
|
-
throw new BrowserError('browser: pointer coordinates must be finite nonnegative viewport pixels', 'BROWSER_POINTER_INVALID');
|
|
1242
|
-
}
|
|
1243
|
-
if (to !== undefined && this.settingsSource?.().vision.strategy === 'nonVisual') {
|
|
1244
|
-
throw new BrowserError('browser: coordinate dragging requires the visual strategy', 'BROWSER_NON_VISUAL_COORDINATES');
|
|
1245
|
-
}
|
|
1246
|
-
const s = this.session(session);
|
|
1247
|
-
const handle = await this.present(s, signal);
|
|
1248
|
-
const viewport = await withTimeout(handleSendEvaluate(handle, '({width:innerWidth,height:innerHeight})'), PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer viewport check timed out');
|
|
1249
|
-
if (!viewport.ok)
|
|
1250
|
-
throw new BrowserError('browser: could not read the pointer viewport', 'BROWSER_POINTER_INVALID');
|
|
1251
|
-
const size = viewport.value;
|
|
1252
|
-
if (from.x >= size.width || from.y >= size.height || (to !== undefined && (to.x >= size.width || to.y >= size.height))) {
|
|
1253
|
-
return { ok: true, value: JSON.stringify(to === undefined ? false : { ok: false, reason: 'drag points must be inside the current viewport' }) };
|
|
1254
|
-
}
|
|
1255
|
-
const send = async (params) => {
|
|
1256
|
-
signal?.throwIfAborted();
|
|
1257
|
-
this.assertSameView(session, handle, this.activeTab(s).handle);
|
|
1258
|
-
await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer input timed out');
|
|
1259
|
-
};
|
|
1260
|
-
await send({ type: 'mouseMoved', x: from.x, y: from.y, buttons: 0 });
|
|
1261
|
-
if (to === undefined)
|
|
1262
|
-
return { ok: true, value: 'true' };
|
|
1263
|
-
let at = from;
|
|
1264
|
-
let held = true;
|
|
1265
|
-
try {
|
|
1266
|
-
await send({ type: 'mousePressed', x: from.x, y: from.y, button: 'left', buttons: 1, clickCount: 1 });
|
|
1267
|
-
const count = Math.max(1, Math.min(Math.trunc(steps) || 12, 60));
|
|
1268
|
-
for (let step = 1; step <= count; step += 1) {
|
|
1269
|
-
const next = { x: from.x + (to.x - from.x) * step / count, y: from.y + (to.y - from.y) * step / count };
|
|
1270
|
-
await send({ type: 'mouseMoved', ...next, button: 'left', buttons: 1 });
|
|
1271
|
-
at = next;
|
|
1272
|
-
}
|
|
1273
|
-
// Native HTML drag targets need a final drag-over before releasing at the destination.
|
|
1274
|
-
await send({ type: 'mouseMoved', ...to, button: 'left', buttons: 1 });
|
|
1275
|
-
await send({ type: 'mouseReleased', ...to, button: 'left', buttons: 0, clickCount: 1 });
|
|
1276
|
-
held = false;
|
|
1277
|
-
return { ok: true, value: JSON.stringify({ ok: true, moved: count, at: to }) };
|
|
1278
|
-
}
|
|
1279
|
-
finally {
|
|
1280
|
-
if (held) {
|
|
1281
|
-
await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, button: 'left', buttons: 0, clickCount: 1 }), 1_000, undefined, 'browser: pointer release timed out').catch(() => { });
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
async evaluatePage(session, request, signal) {
|
|
1286
|
-
const s = this.session(session);
|
|
1287
|
-
const { handle } = this.activeTab(s);
|
|
1288
|
-
signal?.throwIfAborted();
|
|
1289
|
-
try {
|
|
1290
|
-
// Wrap the script in a Function so `return` statements are legal and
|
|
1291
|
-
// request.args arrive as `arguments[0..n]`. A bare script handed to CDP
|
|
1292
|
-
// Runtime.evaluate is an expression context — a leading `return` would
|
|
1293
|
-
// be a syntax error, and an object-literal script (`{...}`) would parse
|
|
1294
|
-
// as a block. So: if the script already starts with `return`, use it as
|
|
1295
|
-
// the body verbatim; otherwise wrap it as `return (expr)` so both
|
|
1296
|
-
// expression and object-literal forms evaluate to their value. Args are
|
|
1297
|
-
// embedded as a JSON array literal; unserializable members become null.
|
|
1298
|
-
const body = /^\s*return\b/.test(request.script)
|
|
1299
|
-
? request.script
|
|
1300
|
-
: `return (${request.script})`;
|
|
1301
|
-
const hasArgs = request.args !== undefined && request.args.length > 0;
|
|
1302
|
-
const expression = hasArgs
|
|
1303
|
-
? `(function(){ const __dshArgs = ${JSON.stringify(request.args)}; return Function(${JSON.stringify(body)}).apply(null, __dshArgs) })()`
|
|
1304
|
-
: `(function(){ return Function(${JSON.stringify(body)})() })()`;
|
|
1305
|
-
// CDP Runtime.evaluate can hang indefinitely on a not-yet-loaded page
|
|
1306
|
-
// (navigate returned but the renderer has not committed). Bound it so a
|
|
1307
|
-
// stuck call surfaces as BROWSER_EXECUTE_TIMEOUT instead of wedging the
|
|
1308
|
-
// whole tool call. The caller's signal wins when it fires first.
|
|
1309
|
-
const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
|
|
1310
|
-
const result = await withTimeout(handle.sendCommand(CDP_RUNTIME_EVALUATE, {
|
|
1311
|
-
expression,
|
|
1312
|
-
returnByValue: true,
|
|
1313
|
-
awaitPromise: true,
|
|
1314
|
-
}), timeoutMs, signal, `browser: execute timed out after ${timeoutMs}ms`,
|
|
1315
|
-
// Best-effort: kill the wedged page script so the renderer (and the
|
|
1316
|
-
// debugger queue) is not stuck behind a busy loop forever.
|
|
1317
|
-
timedOut => { this.interrupt(handle, timedOut); });
|
|
1318
|
-
if (result.exceptionDetails !== undefined) {
|
|
1319
|
-
const detail = result.exceptionDetails;
|
|
1320
|
-
const exception = detail.exception?.description ?? detail.text ?? 'unknown exception';
|
|
1321
|
-
this.record(s, 'execute', { script: request.script }, false, { error: exception });
|
|
1322
|
-
return { ok: false, exception };
|
|
1323
|
-
}
|
|
1324
|
-
const value = result.result?.value ?? null;
|
|
1325
|
-
this.record(s, 'execute', {
|
|
1326
|
-
script: request.script,
|
|
1327
|
-
...request.args !== undefined && request.args.length > 0 ? { args: request.args } : {},
|
|
1328
|
-
}, true, { result: typeof value === 'string' ? value.slice(0, 500) : JSON.stringify(value).slice(0, 500) });
|
|
1329
|
-
return { ok: true, value };
|
|
1330
|
-
}
|
|
1331
|
-
catch (error) {
|
|
1332
|
-
// A caller that aborted is not a failure of the page: report its own reason, or the
|
|
1333
|
-
// cancellation surfaces as "execute failed: AbortError" and — if the caller's reason
|
|
1334
|
-
// happens to be named TimeoutError — as "timed out after 30000ms", quoting a budget
|
|
1335
|
-
// that belongs to the caller rather than to this call.
|
|
1336
|
-
if (signal?.aborted)
|
|
1337
|
-
throw signal.reason;
|
|
1338
|
-
if (error instanceof Error && error.name === 'TimeoutError') {
|
|
1339
|
-
throw new BrowserError(`browser: execute timed out after ${request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS}ms`, 'BROWSER_EXECUTE_TIMEOUT', { cause: error });
|
|
1340
|
-
}
|
|
1341
|
-
throw new BrowserError(`browser: execute failed: ${String(error)}`, 'BROWSER_EXECUTE_FAILED', { cause: error });
|
|
1342
|
-
}
|
|
1343
|
-
}
|
|
1344
|
-
/**
|
|
1345
|
-
* Poll until the active tab's page is ready (and optional URL/selector
|
|
1346
|
-
* match), or the budget runs out. Returns a verdict instead of throwing on
|
|
1347
|
-
* timeout — the caller (model) decides what a miss means. Polling evaluates
|
|
1348
|
-
* in the CURRENT document, so after a navigation the old document may
|
|
1349
|
-
* briefly answer; pass the expected `url` to disambiguate.
|
|
1350
|
-
*/
|
|
1351
|
-
async waitFor(session, request, signal) {
|
|
1352
|
-
const tab = this.activeTab(this.session(session));
|
|
1353
|
-
signal?.throwIfAborted();
|
|
1354
|
-
const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
|
|
1355
|
-
const deadline = Date.now() + timeoutMs;
|
|
1356
|
-
const url = request.url ?? '';
|
|
1357
|
-
const selector = request.selector ?? '';
|
|
1358
|
-
const checkLoaded = request.loaded !== false;
|
|
1359
|
-
const expression = `(() => {
|
|
1360
|
-
const wantUrl = ${JSON.stringify(url)}
|
|
1361
|
-
const wantSelector = ${JSON.stringify(selector)}
|
|
1362
|
-
const inDoc = (doc, sel) => {
|
|
1363
|
-
if (doc.querySelector(sel)) return true
|
|
1364
|
-
for (const el of doc.querySelectorAll('iframe')) {
|
|
1365
|
-
try { const d = el.contentDocument; if (d && inDoc(d, sel)) return true } catch { /* cross-origin */ }
|
|
1366
|
-
}
|
|
1367
|
-
return false
|
|
1368
|
-
}
|
|
1369
|
-
const href = location.href
|
|
1370
|
-
// Exact match wins; otherwise prefix-match within the SAME origin only,
|
|
1371
|
-
// so wantUrl "https://a.com" never matches a cross-origin page whose
|
|
1372
|
-
// host merely starts with the same characters ("https://a.com.evil.com").
|
|
1373
|
-
let urlOk = wantUrl === '' || href === wantUrl
|
|
1374
|
-
if (!urlOk && wantUrl !== '') {
|
|
1375
|
-
try {
|
|
1376
|
-
const want = new URL(wantUrl)
|
|
1377
|
-
const got = new URL(href)
|
|
1378
|
-
urlOk = want.origin === got.origin && href.startsWith(wantUrl)
|
|
1379
|
-
} catch { urlOk = false }
|
|
1380
|
-
}
|
|
1381
|
-
const loadedOk = document.readyState === 'complete' || document.readyState === 'interactive'
|
|
1382
|
-
const foundOk = wantSelector === '' || inDoc(document, wantSelector)
|
|
1383
|
-
return { urlOk, loadedOk, foundOk }
|
|
1384
|
-
})()`;
|
|
1385
|
-
for (;;) {
|
|
1386
|
-
const result = await withTimeout(handleSendEvaluate(tab.handle, expression), Math.min(PROVIDER_TIMEOUTS.interaction, Math.max(250, deadline - Date.now())), signal, 'browser: wait poll timed out', timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
1387
|
-
if (!result.ok) {
|
|
1388
|
-
throw new BrowserError(`browser: wait failed: ${result.exception}`, 'BROWSER_WAIT_FAILED');
|
|
1389
|
-
}
|
|
1390
|
-
const state = result.value;
|
|
1391
|
-
const urlOk = url === '' || state.urlOk === true;
|
|
1392
|
-
const loadedOk = !checkLoaded || state.loadedOk === true;
|
|
1393
|
-
const foundOk = selector === '' || state.foundOk === true;
|
|
1394
|
-
if (urlOk && loadedOk && foundOk) {
|
|
1395
|
-
return { ready: true, reason: 'condition met' };
|
|
1396
|
-
}
|
|
1397
|
-
if (Date.now() >= deadline) {
|
|
1398
|
-
const misses = [];
|
|
1399
|
-
if (!urlOk)
|
|
1400
|
-
misses.push(`url not yet "${url}"`);
|
|
1401
|
-
if (!loadedOk)
|
|
1402
|
-
misses.push('page not loaded');
|
|
1403
|
-
if (!foundOk)
|
|
1404
|
-
misses.push(`selector "${selector}" not found`);
|
|
1405
|
-
return { ready: false, reason: misses.join('; ') };
|
|
1406
|
-
}
|
|
1407
|
-
// Sleep between polls, abortable by the caller.
|
|
1408
|
-
// Sleep between polls; delay() removes its abort listener on both paths, which the
|
|
1409
|
-
// hand-rolled version here did not — a 30s wait leaked about 150 of them.
|
|
1410
|
-
await delay(200, signal);
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
/** Produce an AI-friendly snapshot of the active tab. */
|
|
1414
|
-
async snapshot(session, signal) {
|
|
1415
|
-
const s = this.session(session);
|
|
1416
|
-
const tab = this.activeTab(s);
|
|
1417
|
-
signal?.throwIfAborted();
|
|
1418
|
-
// A tab that has never navigated is a blank, uncommitted view. The collector cannot answer in
|
|
1419
|
-
// it — there is no document to commit — so the call would sit out its whole budget before
|
|
1420
|
-
// saying anything. Answering the empty page immediately is both faster and more truthful.
|
|
1421
|
-
//
|
|
1422
|
-
// `about:blank` needs the same answer for a different reason: it HAS a document, so the collector
|
|
1423
|
-
// runs, finds nothing, and returns zero elements — indistinguishable from a real page with nothing
|
|
1424
|
-
// interactive. A caller then acts on it and receives success values, which is how a carrier swap
|
|
1425
|
-
// that started a fresh window looked like working tools operating on the wrong page (issue #37).
|
|
1426
|
-
const blankUrl = tab.url === '' || tab.url === 'about:blank';
|
|
1427
|
-
if (blankUrl) {
|
|
1428
|
-
return {
|
|
1429
|
-
url: tab.url,
|
|
1430
|
-
elements: [],
|
|
1431
|
-
truncated: false,
|
|
1432
|
-
blank: true,
|
|
1433
|
-
note: tab.url === ''
|
|
1434
|
-
? 'no page has been opened in this browser yet'
|
|
1435
|
-
: 'the page is about:blank — nothing has been opened in this browser, so there is nothing to read or drive',
|
|
1436
|
-
};
|
|
1437
|
-
}
|
|
1438
|
-
const script = `(() => {
|
|
1439
|
-
const cap = ${String(this.snapshotMaxElements)}
|
|
1440
|
-
const url = location.href
|
|
1441
|
-
const title = document.title || undefined
|
|
1442
|
-
// Collect interactive elements from the top document AND from shadow
|
|
1443
|
-
// roots and same-origin iframes (cross-origin iframes stay opaque — the
|
|
1444
|
-
// browser forbids reading them, and so does this snapshot). Elements
|
|
1445
|
-
// inside iframes carry a frame flag so the model knows DOM selectors
|
|
1446
|
-
// are frame-scoped; coordinates below are always top-document.
|
|
1447
|
-
const SELECTOR = 'input, textarea, select, button, a[href], [role="button"], [role="searchbox"], [contenteditable="true"]'
|
|
1448
|
-
const els = []
|
|
1449
|
-
const seen = new Set()
|
|
1450
|
-
const collect = (doc, inFrame) => {
|
|
1451
|
-
if (seen.has(doc)) return
|
|
1452
|
-
seen.add(doc)
|
|
1453
|
-
const hosts = []
|
|
1454
|
-
for (const el of doc.querySelectorAll('*')) {
|
|
1455
|
-
if (el.matches(SELECTOR)) els.push({ el, inFrame })
|
|
1456
|
-
if (el.shadowRoot) hosts.push({ doc: el.shadowRoot, inFrame })
|
|
1457
|
-
if (el.tagName === 'IFRAME') {
|
|
1458
|
-
try { const d = el.contentDocument; if (d) hosts.push({ doc: d, inFrame: true }) } catch { /* cross-origin */ }
|
|
1459
|
-
}
|
|
1460
|
-
}
|
|
1461
|
-
for (const h of hosts) collect(h.doc, h.inFrame)
|
|
1462
|
-
}
|
|
1463
|
-
collect(document, false)
|
|
1464
|
-
// Absolute viewport coordinates in the TOP document: iframe content is
|
|
1465
|
-
// offset by each ancestor iframe's rect, so coordinate clicks land on
|
|
1466
|
-
// the right element no matter which frame it lives in.
|
|
1467
|
-
const absRect = (el, doc) => {
|
|
1468
|
-
const r = el.getBoundingClientRect()
|
|
1469
|
-
let x = r.x, y = r.y
|
|
1470
|
-
let d = doc
|
|
1471
|
-
while (d && d.defaultView && d.defaultView.frameElement) {
|
|
1472
|
-
const fr = d.defaultView.frameElement.getBoundingClientRect()
|
|
1473
|
-
x += fr.x; y += fr.y
|
|
1474
|
-
d = d.defaultView.frameElement.ownerDocument
|
|
1475
|
-
}
|
|
1476
|
-
return { x, y, w: r.width, h: r.height }
|
|
1477
|
-
}
|
|
1478
|
-
const out = []
|
|
1479
|
-
for (const { el, inFrame } of els) {
|
|
1480
|
-
if (out.length >= cap) break
|
|
1481
|
-
const r = el.getBoundingClientRect()
|
|
1482
|
-
// Cheap layout check first; only force style recalc when it passes.
|
|
1483
|
-
if (r.width < 4 || r.height < 4) continue
|
|
1484
|
-
const cs = getComputedStyle(el)
|
|
1485
|
-
if (cs.visibility === 'hidden' || cs.display === 'none') continue
|
|
1486
|
-
const kind = el.tagName === 'INPUT' ? (el.type === 'checkbox' ? 'checkbox' : (el.type === 'submit' || el.type === 'button' ? 'button' : 'input'))
|
|
1487
|
-
: el.tagName === 'TEXTAREA' ? 'textarea'
|
|
1488
|
-
: el.tagName === 'SELECT' ? 'select'
|
|
1489
|
-
: el.tagName === 'BUTTON' ? 'button'
|
|
1490
|
-
: el.tagName === 'A' ? 'link' : 'other'
|
|
1491
|
-
// An anchor wrapping only an image has no text: 4399.com's 1608 game links are all
|
|
1492
|
-
// <a href><img alt="名字"></a>, so every label came out empty and the whole page read as
|
|
1493
|
-
// "no interactive elements" while it was full of them.
|
|
1494
|
-
const imageAlt = el.tagName === 'A' || el.tagName === 'BUTTON'
|
|
1495
|
-
? (el.querySelector('img[alt]')?.getAttribute('alt') ?? '')
|
|
1496
|
-
: ''
|
|
1497
|
-
const label = (el.getAttribute('aria-label') || el.placeholder || el.textContent || imageAlt
|
|
1498
|
-
|| el.value || el.name || el.id || '').toString().replace(/\\s+/g, ' ').trim().slice(0, ${String(SNAPSHOT_LABEL_MAX)})
|
|
1499
|
-
if (!label && kind !== 'link') continue
|
|
1500
|
-
const a = absRect(el, el.ownerDocument)
|
|
1501
|
-
out.push({
|
|
1502
|
-
ref: out.length + 1,
|
|
1503
|
-
kind,
|
|
1504
|
-
label,
|
|
1505
|
-
selector: el.id ? '#' + CSS.escape(el.id) : (el.name ? '[name=' + JSON.stringify(el.name) + ']' : ''),
|
|
1506
|
-
x: Math.round(a.x + a.w / 2),
|
|
1507
|
-
y: Math.round(a.y + a.h / 2),
|
|
1508
|
-
...inFrame ? { frame: true } : {},
|
|
1509
|
-
})
|
|
1510
|
-
}
|
|
1511
|
-
const challenge = ${CHALLENGE_DETECT_EXPRESSION}
|
|
1512
|
-
// The page's own URL is the authority on whether there is a document. The tracked tab.url is
|
|
1513
|
-
// a bookkeeping copy that can lag behind a navigation the browser performed itself, and a
|
|
1514
|
-
// stale copy made this check miss on a real about:blank tab.
|
|
1515
|
-
const blankPage = out.length === 0 && (url === '' || url === 'about:blank')
|
|
1516
|
-
// Independent of the element list: a page can mix DOM controls with a canvas that holds the
|
|
1517
|
-
// part the caller actually needs. Measured on sudoku.com — 60 links were collected and the
|
|
1518
|
-
// board, drawn on a canvas, was invisible in the same result.
|
|
1519
|
-
//
|
|
1520
|
-
// The thresholds keep a decorative canvas from claiming a page: at least 80x80 per canvas and
|
|
1521
|
-
// 10% of the viewport in total. Anything smaller is reported by nothing, which is right.
|
|
1522
|
-
let canvas
|
|
1523
|
-
if (blankPage !== true) {
|
|
1524
|
-
let area = 0
|
|
1525
|
-
let count = 0
|
|
1526
|
-
for (const c of document.querySelectorAll('canvas')) {
|
|
1527
|
-
const r = c.getBoundingClientRect()
|
|
1528
|
-
if (r.width < 80 || r.height < 80) continue
|
|
1529
|
-
count += 1
|
|
1530
|
-
area += r.width * r.height
|
|
1531
|
-
}
|
|
1532
|
-
const view = window.innerWidth * window.innerHeight
|
|
1533
|
-
if (count > 0 && view > 0 && area / view >= 0.1) canvas = true
|
|
1534
|
-
}
|
|
1535
|
-
return {
|
|
1536
|
-
url,
|
|
1537
|
-
title,
|
|
1538
|
-
elements: out,
|
|
1539
|
-
truncated: out.length >= cap,
|
|
1540
|
-
challenge,
|
|
1541
|
-
...blankPage === true
|
|
1542
|
-
? {
|
|
1543
|
-
blank: true,
|
|
1544
|
-
note: 'the page is about:blank — nothing has been opened in this browser, so there is nothing to read or drive',
|
|
1545
|
-
}
|
|
1546
|
-
: {},
|
|
1547
|
-
...canvas === true
|
|
1548
|
-
? {
|
|
1549
|
-
canvas: true,
|
|
1550
|
-
note: out.length === 0
|
|
1551
|
-
? 'this page draws its interface on a canvas, so there is no DOM content for a snapshot. '
|
|
1552
|
-
+ 'Use dsh_browser_screenshot to see it, and coordinates with dsh_browser_click to act on it.'
|
|
1553
|
-
: 'part of this page is drawn on a canvas, which no element list can describe. The elements '
|
|
1554
|
-
+ 'below are real; anything inside the canvas is only visible in dsh_browser_screenshot.',
|
|
1555
|
-
}
|
|
1556
|
-
: {},
|
|
1557
|
-
}
|
|
1558
|
-
})()`;
|
|
1559
|
-
// Same hang guard as execute: a renderer that has not committed after
|
|
1560
|
-
// navigate would otherwise block snapshot forever.
|
|
1561
|
-
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
1562
|
-
let result;
|
|
1563
|
-
try {
|
|
1564
|
-
result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: snapshot timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
1565
|
-
}
|
|
1566
|
-
catch (error) {
|
|
1567
|
-
if (error instanceof Error && error.name === 'TimeoutError') {
|
|
1568
|
-
this.quarantine(tab.handle);
|
|
1569
|
-
throw new BrowserError('browser: snapshot timed out; the guest is quarantined. Close this tab or explicitly reset the session.', 'BROWSER_SNAPSHOT_TIMEOUT', { cause: error });
|
|
1570
|
-
}
|
|
1571
|
-
throw error;
|
|
1572
|
-
}
|
|
1573
|
-
if (!result.ok)
|
|
1574
|
-
throw new BrowserError(`browser: snapshot evaluation failed: ${result.exception}`, 'BROWSER_SNAPSHOT_FAILED');
|
|
1575
|
-
const value = result.value;
|
|
1576
|
-
return value;
|
|
1577
|
-
}
|
|
1578
|
-
/**
|
|
1579
|
-
* Read the active tab's accessibility tree: semantic roles/names/states for
|
|
1580
|
-
* every interactive node (Chrome's `computedRole`/`computedName` when
|
|
1581
|
-
* available, tag/attribute inference otherwise). Pierces same-origin
|
|
1582
|
-
* iframes and shadow roots like the snapshot; cross-origin frames stay
|
|
1583
|
-
* opaque. Coordinates are top-document viewport-relative, so a node can
|
|
1584
|
-
* also be driven by click/type.
|
|
1585
|
-
*/
|
|
1586
|
-
async a11y(session, request, signal) {
|
|
1587
|
-
const s = this.session(session);
|
|
1588
|
-
const tab = this.activeTab(s);
|
|
1589
|
-
signal?.throwIfAborted();
|
|
1590
|
-
// Same short-circuit as `snapshot`: a tab that never navigated has no committed document, so
|
|
1591
|
-
// the tree cannot be read and the call would spend its whole budget discovering that.
|
|
1592
|
-
if (tab.url === '')
|
|
1593
|
-
return { url: '', title: undefined, count: 0, nodes: [], truncated: false };
|
|
1594
|
-
const includeHidden = request.includeHidden === true;
|
|
1595
|
-
// 150 rather than 500. The cap fills on any real page, and 500 nodes measured 38,953
|
|
1596
|
-
// characters — 10k-13k tokens for a single call. A caller that needs more asks for it.
|
|
1597
|
-
const maxNodes = Math.max(10, Math.min(5000, Math.floor(request.maxNodes ?? 150)));
|
|
1598
|
-
const script = `(() => {
|
|
1599
|
-
const includeHidden = ${String(includeHidden)}
|
|
1600
|
-
const maxNodes = ${String(maxNodes)}
|
|
1601
|
-
const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'HEAD', 'META', 'LINK', 'TITLE'])
|
|
1602
|
-
const ACTIONABLE = new Set(['button', 'link', 'textbox', 'searchbox', 'checkbox', 'radio', 'combobox', 'listbox', 'slider', 'spinbutton', 'tab', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'switch', 'option', 'summary', 'treeitem', 'scrollbar'])
|
|
1603
|
-
const CONTENT_NAMED = new Set(['button', 'link', 'heading', 'summary', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'tab', 'treeitem', 'option', 'listitem', 'switch', 'checkbox', 'radio', 'searchbox', 'textbox'])
|
|
1604
|
-
const out = []
|
|
1605
|
-
const seen = new Set()
|
|
1606
|
-
const ownText = (el) => Array.from(el.childNodes).filter(n => n.nodeType === Node.TEXT_NODE).map(n => n.textContent || '').join('').trim()
|
|
1607
|
-
const visible = (el) => {
|
|
1608
|
-
const r = el.getBoundingClientRect()
|
|
1609
|
-
const cs = getComputedStyle(el)
|
|
1610
|
-
return r.width >= 4 && r.height >= 4 && cs.visibility !== 'hidden' && cs.display !== 'none'
|
|
1611
|
-
}
|
|
1612
|
-
const roleOf = (el) => {
|
|
1613
|
-
const computed = el.computedRole
|
|
1614
|
-
if (typeof computed === 'string' && computed && computed !== 'none' && computed !== 'generic') return computed
|
|
1615
|
-
const tag = el.tagName.toLowerCase()
|
|
1616
|
-
if (el instanceof HTMLAnchorElement) return el.hasAttribute('href') ? 'link' : 'generic'
|
|
1617
|
-
if (tag === 'button') return 'button'
|
|
1618
|
-
if (tag === 'textarea') return 'textbox'
|
|
1619
|
-
if (tag === 'select') return el.hasAttribute('multiple') ? 'listbox' : 'combobox'
|
|
1620
|
-
if (tag === 'img') return el.getAttribute('alt') === '' ? 'presentation' : 'img'
|
|
1621
|
-
if (/^h[1-6]$/.test(tag)) return 'heading'
|
|
1622
|
-
if (tag === 'ul' || tag === 'ol') return 'list'
|
|
1623
|
-
if (tag === 'li') return 'listitem'
|
|
1624
|
-
if (tag === 'nav') return 'navigation'
|
|
1625
|
-
if (tag === 'main') return 'main'
|
|
1626
|
-
if (tag === 'form') return 'form'
|
|
1627
|
-
if (tag === 'table') return 'table'
|
|
1628
|
-
if (tag === 'tr') return 'row'
|
|
1629
|
-
if (tag === 'td') return 'cell'
|
|
1630
|
-
if (tag === 'th') return 'columnheader'
|
|
1631
|
-
if (tag === 'dialog') return 'dialog'
|
|
1632
|
-
if (tag === 'summary') return 'button'
|
|
1633
|
-
if (tag === 'input') {
|
|
1634
|
-
const t = el.type
|
|
1635
|
-
if (t === 'checkbox') return 'checkbox'
|
|
1636
|
-
if (t === 'radio') return 'radio'
|
|
1637
|
-
if (t === 'range') return 'slider'
|
|
1638
|
-
if (t === 'number') return 'spinbutton'
|
|
1639
|
-
if (t === 'button' || t === 'submit' || t === 'reset' || t === 'image') return 'button'
|
|
1640
|
-
if (t === 'hidden') return 'none'
|
|
1641
|
-
if (t === 'search') return 'searchbox'
|
|
1642
|
-
return 'textbox'
|
|
1643
|
-
}
|
|
1644
|
-
return 'generic'
|
|
1645
|
-
}
|
|
1646
|
-
const nameOf = (el, role) => {
|
|
1647
|
-
const computed = el.computedName
|
|
1648
|
-
if (typeof computed === 'string' && computed && computed.trim() !== '') return computed.trim()
|
|
1649
|
-
const aria = el.getAttribute('aria-label')
|
|
1650
|
-
if (aria) return aria
|
|
1651
|
-
const labelledby = el.getAttribute('aria-labelledby')
|
|
1652
|
-
if (labelledby) {
|
|
1653
|
-
const ref = document.getElementById(labelledby.split(/\\s+/)[0])
|
|
1654
|
-
if (ref) {
|
|
1655
|
-
const t = (ref.textContent || '').trim()
|
|
1656
|
-
if (t) return t
|
|
1657
|
-
}
|
|
1658
|
-
}
|
|
1659
|
-
if (el.hasAttribute('alt')) return el.getAttribute('alt')
|
|
1660
|
-
if (el.hasAttribute('title')) return el.getAttribute('title')
|
|
1661
|
-
if (el.placeholder) return el.placeholder
|
|
1662
|
-
if (CONTENT_NAMED.has(role)) {
|
|
1663
|
-
const t = ownText(el)
|
|
1664
|
-
if (t) return t
|
|
1665
|
-
}
|
|
1666
|
-
if (el.id) {
|
|
1667
|
-
const lbl = document.querySelector('label[for=' + JSON.stringify(el.id) + ']')
|
|
1668
|
-
if (lbl) {
|
|
1669
|
-
const t = (lbl.textContent || '').trim()
|
|
1670
|
-
if (t) return t
|
|
1671
|
-
}
|
|
1672
|
-
}
|
|
1673
|
-
return ''
|
|
1674
|
-
}
|
|
1675
|
-
const valueOf = (el) => {
|
|
1676
|
-
if (el instanceof HTMLInputElement) return el.type === 'checkbox' || el.type === 'radio' ? null : el.value
|
|
1677
|
-
if (el instanceof HTMLTextAreaElement) return el.value
|
|
1678
|
-
if (el instanceof HTMLSelectElement) {
|
|
1679
|
-
const o = el.options[el.selectedIndex]
|
|
1680
|
-
return o ? (o.textContent || '').trim() : null
|
|
1681
|
-
}
|
|
1682
|
-
if (el.isContentEditable) return (el.textContent || '').trim()
|
|
1683
|
-
return null
|
|
1684
|
-
}
|
|
1685
|
-
const statesOf = (el) => {
|
|
1686
|
-
const st = []
|
|
1687
|
-
if (!el.disabled) st.push('enabled'); else st.push('disabled')
|
|
1688
|
-
if (el.checked) st.push('checked'); else if (el.getAttribute('aria-checked') === 'false') st.push('unchecked')
|
|
1689
|
-
const expanded = el.getAttribute('aria-expanded')
|
|
1690
|
-
if (expanded === 'true') st.push('expanded')
|
|
1691
|
-
if (expanded === 'false') st.push('collapsed')
|
|
1692
|
-
if (el.required) st.push('required')
|
|
1693
|
-
if (el.readOnly) st.push('readonly')
|
|
1694
|
-
if (el.selected) st.push('selected')
|
|
1695
|
-
const pressed = el.getAttribute('aria-pressed')
|
|
1696
|
-
if (pressed === 'true') st.push('pressed')
|
|
1697
|
-
return st
|
|
1698
|
-
}
|
|
1699
|
-
const depthOf = (el) => {
|
|
1700
|
-
let d = 0
|
|
1701
|
-
let p = el.parentElement
|
|
1702
|
-
while (p) { d++; p = p.parentElement }
|
|
1703
|
-
return d
|
|
1704
|
-
}
|
|
1705
|
-
const absRect = (el, doc) => {
|
|
1706
|
-
const r = el.getBoundingClientRect()
|
|
1707
|
-
let x = r.x, y = r.y
|
|
1708
|
-
let d = doc
|
|
1709
|
-
while (d && d.defaultView && d.defaultView.frameElement) {
|
|
1710
|
-
const fr = d.defaultView.frameElement.getBoundingClientRect()
|
|
1711
|
-
x += fr.x; y += fr.y
|
|
1712
|
-
d = d.defaultView.frameElement.ownerDocument
|
|
1713
|
-
}
|
|
1714
|
-
return { x, y, w: r.width, h: r.height }
|
|
1715
|
-
}
|
|
1716
|
-
const walk = (doc, inFrame, baseDepth) => {
|
|
1717
|
-
if (seen.has(doc)) return
|
|
1718
|
-
seen.add(doc)
|
|
1719
|
-
for (const el of doc.querySelectorAll('*')) {
|
|
1720
|
-
if (out.length >= maxNodes) return
|
|
1721
|
-
if (SKIP.has(el.tagName)) continue
|
|
1722
|
-
if (el.shadowRoot) walk(el.shadowRoot, inFrame, baseDepth + 1)
|
|
1723
|
-
if (el.tagName === 'IFRAME') {
|
|
1724
|
-
try { const d = el.contentDocument; if (d) walk(d, true, baseDepth + 1) } catch { /* cross-origin */ }
|
|
1725
|
-
}
|
|
1726
|
-
const role = roleOf(el)
|
|
1727
|
-
if (role === 'none' || role === 'presentation' || role === 'generic') continue
|
|
1728
|
-
if (!includeHidden && !visible(el)) continue
|
|
1729
|
-
const name = nameOf(el, role)
|
|
1730
|
-
if (!name && !ACTIONABLE.has(role)) continue
|
|
1731
|
-
const a = absRect(el, el.ownerDocument)
|
|
1732
|
-
out.push({
|
|
1733
|
-
ref: out.length + 1,
|
|
1734
|
-
role,
|
|
1735
|
-
name: name.slice(0, 120),
|
|
1736
|
-
value: valueOf(el),
|
|
1737
|
-
states: statesOf(el),
|
|
1738
|
-
depth: baseDepth + depthOf(el),
|
|
1739
|
-
// Same derivation as the snapshot collector: an id or a name is what makes a node
|
|
1740
|
-
// something the caller can point at without guessing at its text. The tool-layer
|
|
1741
|
-
// schema declared this field before this line existed, so the schema was promising
|
|
1742
|
-
// a value the tool never sent.
|
|
1743
|
-
selector: el.id ? '#' + CSS.escape(el.id) : (el.name ? '[name=' + JSON.stringify(el.name) + ']' : ''),
|
|
1744
|
-
tag: el.tagName.toLowerCase(),
|
|
1745
|
-
x: Math.round(a.x + a.w / 2),
|
|
1746
|
-
y: Math.round(a.y + a.h / 2),
|
|
1747
|
-
...inFrame ? { frame: true } : {},
|
|
1748
|
-
})
|
|
1749
|
-
}
|
|
1750
|
-
}
|
|
1751
|
-
walk(document, false, 0)
|
|
1752
|
-
return { url: location.href, title: document.title || undefined, count: out.length, nodes: out, truncated: out.length >= maxNodes }
|
|
1753
|
-
})()`;
|
|
1754
|
-
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
1755
|
-
let result;
|
|
1756
|
-
try {
|
|
1757
|
-
result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: a11y timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
1758
|
-
}
|
|
1759
|
-
catch (error) {
|
|
1760
|
-
if (error instanceof Error && error.name === 'TimeoutError') {
|
|
1761
|
-
this.quarantine(tab.handle);
|
|
1762
|
-
throw new BrowserError('browser: a11y timed out; the guest is quarantined. Close this tab or explicitly reset the session.', 'BROWSER_A11Y_TIMEOUT', { cause: error });
|
|
1763
|
-
}
|
|
1764
|
-
throw error;
|
|
1765
|
-
}
|
|
1766
|
-
if (!result.ok)
|
|
1767
|
-
throw new BrowserError(`browser: a11y evaluation failed: ${result.exception}`, 'BROWSER_A11Y_FAILED');
|
|
1768
|
-
const value = result.value;
|
|
1769
|
-
this.record(s, 'a11y', { includeHidden, maxNodes }, true, { result: `${value.count} nodes` });
|
|
1770
|
-
return value;
|
|
1771
|
-
}
|
|
1772
|
-
/** Check whether a human-verification challenge is blocking the active tab. */
|
|
1773
|
-
async detectChallenge(session, signal) {
|
|
1774
|
-
const s = this.session(session);
|
|
1775
|
-
const tab = this.activeTab(s);
|
|
1776
|
-
signal?.throwIfAborted();
|
|
1777
|
-
const timeoutMs = PROVIDER_TIMEOUTS.action;
|
|
1778
|
-
const result = await withTimeout(handleSendEvaluate(tab.handle, CHALLENGE_DETECT_EXPRESSION), timeoutMs, signal, `browser: challenge detection timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
1779
|
-
if (!result.ok) {
|
|
1780
|
-
throw new BrowserError(`browser: challenge detection failed: ${result.exception}`, 'BROWSER_CHALLENGE_DETECT_FAILED');
|
|
1781
|
-
}
|
|
1782
|
-
const value = result.value;
|
|
1783
|
-
return { blocked: value.blocked === true, kind: value.kind, reason: value.reason };
|
|
1784
|
-
}
|
|
1785
|
-
/** Fetch page content in a requested format. */
|
|
1786
|
-
async content(session, request, signal) {
|
|
1787
|
-
const tab = this.activeTab(this.session(session));
|
|
1788
|
-
signal?.throwIfAborted();
|
|
1789
|
-
const selector = request.selector ?? '';
|
|
1790
|
-
const format = request.format;
|
|
1791
|
-
// Per-format caps. A full HTML document is enormous, but the same limit applied to
|
|
1792
|
-
// plain text is no limit at all (a whole page of text measured 25,882 characters).
|
|
1793
|
-
// This bounds the common case instead of letting one call spend 25k-33k tokens.
|
|
1794
|
-
//
|
|
1795
|
-
// The plugin config overrides the lot when it is set — see `contentMaxChars`. The caller's
|
|
1796
|
-
// own `maxChars` still outranks both: an explicit per-call bound is the most specific
|
|
1797
|
-
// statement of intent there is.
|
|
1798
|
-
const maxChars = request.maxChars
|
|
1799
|
-
?? this.contentMaxChars
|
|
1800
|
-
?? (format === 'html' || format === 'json' ? 50_000 : 20_000);
|
|
1801
|
-
const script = `(() => {
|
|
1802
|
-
const root = ${selector === '' ? 'document.body' : `document.querySelector(${JSON.stringify(selector)})`}
|
|
1803
|
-
if (!root) return { ok: false, reason: 'selector not found' }
|
|
1804
|
-
const fmt = ${JSON.stringify(format)}
|
|
1805
|
-
// Both walkers pierce shadow roots and same-origin iframes (cross-origin
|
|
1806
|
-
// iframes stay opaque — the browser forbids reading them).
|
|
1807
|
-
let content = ''
|
|
1808
|
-
if (fmt === 'txt') {
|
|
1809
|
-
// Prefer the browser's own rendered text.
|
|
1810
|
-
//
|
|
1811
|
-
// Walking text nodes and joining them is not equivalent: pages that wrap
|
|
1812
|
-
// every character in its own element — one-character spans for a
|
|
1813
|
-
// per-character animation, which is common — produce one text node per
|
|
1814
|
-
// letter, and joining those with spaces turns every word into a column of
|
|
1815
|
-
// letters. The rendered text reassembles them the way a reader sees them,
|
|
1816
|
-
// and it also honours visibility, so hidden text does not leak out.
|
|
1817
|
-
// (No backticks in this comment: it lives inside a template literal.)
|
|
1818
|
-
const rendered = typeof root.innerText === 'string' ? root.innerText : ''
|
|
1819
|
-
if (rendered.trim() !== '') {
|
|
1820
|
-
content = rendered
|
|
1821
|
-
} else {
|
|
1822
|
-
// Fallback for nodes without layout (a detached root, or a fragment):
|
|
1823
|
-
// collect text directly, still piercing shadow roots and same-origin
|
|
1824
|
-
// iframes, and join without inventing separators beyond what the markup
|
|
1825
|
-
// already implies.
|
|
1826
|
-
const parts = []
|
|
1827
|
-
const textWalk = (node) => {
|
|
1828
|
-
if (node.nodeType === Node.TEXT_NODE) { const t = (node.textContent || '').trim(); if (t) parts.push(t); return }
|
|
1829
|
-
if (node.nodeType !== Node.ELEMENT_NODE) return
|
|
1830
|
-
const tag = node.tagName.toLowerCase()
|
|
1831
|
-
if (tag === 'script' || tag === 'style' || tag === 'noscript') return
|
|
1832
|
-
if (tag === 'iframe') {
|
|
1833
|
-
try { const d = node.contentDocument; if (d && d.body) for (const c of d.body.childNodes) textWalk(c) } catch { /* cross-origin */ }
|
|
1834
|
-
return
|
|
1835
|
-
}
|
|
1836
|
-
if (node.shadowRoot) for (const c of node.shadowRoot.childNodes) textWalk(c)
|
|
1837
|
-
for (const child of node.childNodes) textWalk(child)
|
|
1838
|
-
}
|
|
1839
|
-
textWalk(root)
|
|
1840
|
-
content = parts.join(' ')
|
|
1841
|
-
}
|
|
1842
|
-
}
|
|
1843
|
-
else if (fmt === 'html') content = root.outerHTML || ''
|
|
1844
|
-
// A DOM element has no own enumerable properties — everything lives on the prototype
|
|
1845
|
-
// chain — so JSON.stringify(root) is always "{}". That is not a structured view of
|
|
1846
|
-
// the page, it is an empty object the caller will read as "no data here" and then
|
|
1847
|
-
// retry with other selectors. Serialise the markup instead, which is what a caller
|
|
1848
|
-
// asking for JSON of an element can actually use.
|
|
1849
|
-
else if (fmt === 'json') content = JSON.stringify({ html: root.outerHTML, tag: root.tagName.toLowerCase() })
|
|
1850
|
-
else {
|
|
1851
|
-
// markdown: headings, paragraphs, links, lists (best-effort)
|
|
1852
|
-
const parts = []
|
|
1853
|
-
const walk = (node) => {
|
|
1854
|
-
if (node.nodeType === Node.TEXT_NODE) { const t = (node.textContent || '').trim(); if (t) parts.push(t); return }
|
|
1855
|
-
if (node.nodeType !== Node.ELEMENT_NODE) return
|
|
1856
|
-
const tag = node.tagName.toLowerCase()
|
|
1857
|
-
if (tag === 'script' || tag === 'style' || tag === 'noscript') return
|
|
1858
|
-
if (tag === 'iframe') {
|
|
1859
|
-
try { const d = node.contentDocument; if (d && d.body) for (const c of d.body.childNodes) walk(c) } catch { /* cross-origin */ }
|
|
1860
|
-
return
|
|
1861
|
-
}
|
|
1862
|
-
if (node.shadowRoot) for (const c of node.shadowRoot.childNodes) walk(c)
|
|
1863
|
-
if (tag === 'h1' || tag === 'h2' || tag === 'h3' || tag === 'h4') parts.push('\\n' + '#'.repeat(Number(tag[1])) + ' ' + (node.textContent || '').trim() + '\\n')
|
|
1864
|
-
else if (tag === 'a') { const t = (node.textContent || '').trim(); if (t) parts.push('[' + t + '](' + (node.href || '') + ')') }
|
|
1865
|
-
else if (tag === 'li') parts.push(' - ' + (node.textContent || '').trim())
|
|
1866
|
-
else if (tag === 'p' || tag === 'div' || tag === 'section' || tag === 'article') { const t = (node.textContent || '').trim(); if (t) parts.push(t + '\\n') }
|
|
1867
|
-
else { for (const child of node.childNodes) walk(child) }
|
|
1868
|
-
}
|
|
1869
|
-
walk(root)
|
|
1870
|
-
// Join without a separator: each part already carries its own trailing
|
|
1871
|
-
// newline, so a space join would smear headings/links into run-on text.
|
|
1872
|
-
content = parts.join('')
|
|
1873
|
-
}
|
|
1874
|
-
const truncated = content.length > ${String(maxChars)}
|
|
1875
|
-
return { ok: true, content: content.slice(0, ${String(maxChars)}), truncated }
|
|
1876
|
-
})()`;
|
|
1877
|
-
// Honor a per-call timeout: content evaluation can hang on a heavy page,
|
|
1878
|
-
// so a caller-supplied budget bounds it. Unlike a bare signal entry check,
|
|
1879
|
-
// withTimeout also interrupts a call already in flight.
|
|
1880
|
-
const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
|
|
1881
|
-
const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: content timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
1882
|
-
if (!result.ok)
|
|
1883
|
-
throw new BrowserError(`browser: content evaluation failed: ${result.exception}`, 'BROWSER_CONTENT_FAILED');
|
|
1884
|
-
const value = result.value;
|
|
1885
|
-
if (!value.ok)
|
|
1886
|
-
throw new BrowserError(`browser: content fetch failed: ${value.reason ?? 'unknown'}`, 'BROWSER_CONTENT_FAILED');
|
|
1887
|
-
return { content: value.content ?? '', truncated: value.truncated ?? false };
|
|
1888
|
-
}
|
|
1889
|
-
/**
|
|
1890
|
-
* Click at viewport coordinates, or at a located element's center when a
|
|
1891
|
-
* `target` (css/text/xpath) is given. CDP mousePressed + mouseReleased.
|
|
1892
|
-
*/
|
|
1893
|
-
async click(session, request, signal) {
|
|
1894
|
-
const s = this.session(session);
|
|
1895
|
-
// The view the locate runs against. It can stop being the session's active view while
|
|
1896
|
-
// the locate waits (see prepareTarget), so every dispatch below re-reads the live one.
|
|
1897
|
-
const locateHandle = this.activeTab(s).handle;
|
|
1898
|
-
signal?.throwIfAborted();
|
|
1899
|
-
let x = 0;
|
|
1900
|
-
let y = 0;
|
|
1901
|
-
if ('target' in request) {
|
|
1902
|
-
// Semantic targeting (②): locate the element in-page, scroll it into
|
|
1903
|
-
// view, and click its center — no coordinate guessing needed.
|
|
1904
|
-
const locateMs = PROVIDER_TIMEOUTS.lookup;
|
|
1905
|
-
const body = `
|
|
1906
|
-
el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'center' })
|
|
1907
|
-
const r = el.getBoundingClientRect()
|
|
1908
|
-
return { ok: true, x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }
|
|
1909
|
-
`;
|
|
1910
|
-
const script = this.buildTargetScript(request.target, locateMs, body);
|
|
1911
|
-
const out = await this.runTargetScript(this.activeTab(s), script, locateMs, signal, 'BROWSER_CLICK_FAILED', 'browser: click');
|
|
1912
|
-
x = Number(out.x);
|
|
1913
|
-
y = Number(out.y);
|
|
1914
|
-
}
|
|
1915
|
-
else {
|
|
1916
|
-
// A coordinate only exists because somebody read a picture. Under the
|
|
1917
|
-
// non-visual strategy the plugin must not accept one: a model that cannot
|
|
1918
|
-
// see cannot have produced it, so the coordinates are either copied from an
|
|
1919
|
-
// earlier vision pass or invented, and honouring them turns a silent
|
|
1920
|
-
// mis-click into a mystery. Refusing here, with a message that says what to
|
|
1921
|
-
// do instead, converts that into a usable instruction.
|
|
1922
|
-
if (this.settingsSource !== undefined && this.settingsSource().vision.strategy === 'nonVisual') {
|
|
1923
|
-
throw new BrowserError('browser: the configured non-visual strategy refuses coordinate clicks — pass a semantic target instead, e.g. target { by: "text", value: "Sign in" }, which locates the element from the DOM and clicks its centre', 'BROWSER_NON_VISUAL_COORDINATES');
|
|
1924
|
-
}
|
|
1925
|
-
x = request.x;
|
|
1926
|
-
y = request.y;
|
|
1927
|
-
}
|
|
1928
|
-
// Input.* is only delivered to a view with a current display surface; the
|
|
1929
|
-
// barrier also re-presents after a navigation replaced the renderer. It returns the
|
|
1930
|
-
// handle that may still be receiving input when it settles.
|
|
1931
|
-
const handle = await this.present(s, signal);
|
|
1932
|
-
// The locate (up to 10s) and the present barrier both ran against the view captured
|
|
1933
|
-
// earlier; if the human switched tabs meanwhile, these coordinates belong to one page
|
|
1934
|
-
// and the dispatch would go to another — and Chromium answers success either way.
|
|
1935
|
-
if ('target' in request)
|
|
1936
|
-
this.assertSameView(session, locateHandle, handle);
|
|
1937
|
-
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
1938
|
-
const send = (params, label) => withTimeout(handle.sendCommand('Input.dispatchMouseEvent', params), timeoutMs, signal, `browser: click ${label} timed out after ${timeoutMs}ms`);
|
|
1939
|
-
// Chromium routes a synthesized `mousePressed` to the widget's *current*
|
|
1940
|
-
// hover target rather than hit-testing the coordinates, and a real pointer
|
|
1941
|
-
// click is always preceded by movement. A view that has never received a
|
|
1942
|
-
// mouse event has no hover target yet, so the press of the FIRST click on a
|
|
1943
|
-
// fresh tab went nowhere while CDP still answered success; the second click
|
|
1944
|
-
// landed because the first had quietly established the target. Move the
|
|
1945
|
-
// pointer first so a click is self-contained.
|
|
1946
|
-
try {
|
|
1947
|
-
await send({ type: 'mouseMoved', x, y, buttons: 0 }, 'move');
|
|
1948
|
-
}
|
|
1949
|
-
catch (error) {
|
|
1950
|
-
throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error });
|
|
1951
|
-
}
|
|
1952
|
-
// Paint before the press so the ripple is already on screen when the click
|
|
1953
|
-
// lands — the cursor exists to show the human WHERE the agent acts.
|
|
1954
|
-
// Name the operation in the overlay: the pointer is the "agent is driving this
|
|
1955
|
-
// tab" signal, so the bubble is what lets a human follow along without the log.
|
|
1956
|
-
this.showCursor(handle, x, y, 'click', 'click', true);
|
|
1957
|
-
const release = () => {
|
|
1958
|
-
// Back to the handle the PRESS may have landed on, deliberately not to the currently
|
|
1959
|
-
// active tab: this only runs after a failed press/release, and re-targeting a
|
|
1960
|
-
// compensating half of a click to a view the human just switched to would press a
|
|
1961
|
-
// button there. Best-effort either way.
|
|
1962
|
-
void handle
|
|
1963
|
-
.sendCommand('Input.dispatchMouseEvent', {
|
|
1964
|
-
type: 'mouseReleased',
|
|
1965
|
-
x,
|
|
1966
|
-
y,
|
|
1967
|
-
button: 'left',
|
|
1968
|
-
buttons: 0,
|
|
1969
|
-
clickCount: 1,
|
|
1970
|
-
})
|
|
1971
|
-
.catch(() => { });
|
|
1972
|
-
};
|
|
1973
|
-
try {
|
|
1974
|
-
await send({ type: 'mousePressed', x, y, button: 'left', buttons: 1, clickCount: 1 }, 'press');
|
|
1975
|
-
}
|
|
1976
|
-
catch (error) {
|
|
1977
|
-
// The press may still land late; release best-effort so the button is
|
|
1978
|
-
// never left in a stuck pressed state.
|
|
1979
|
-
release();
|
|
1980
|
-
throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error });
|
|
1981
|
-
}
|
|
1982
|
-
try {
|
|
1983
|
-
await send({ type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 }, 'release');
|
|
1984
|
-
}
|
|
1985
|
-
catch (error) {
|
|
1986
|
-
// The press already landed; retry the release so the button is not
|
|
1987
|
-
// left pressed before surfacing the failure.
|
|
1988
|
-
release();
|
|
1989
|
-
throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error });
|
|
1990
|
-
}
|
|
1991
|
-
this.record(s, 'click', 'target' in request ? { target: request.target } : { x, y }, true);
|
|
1992
|
-
}
|
|
1993
|
-
/**
|
|
1994
|
-
* Click many points in order, once.
|
|
1995
|
-
*
|
|
1996
|
-
* The same wire sequence as {@link click}, looped — only the round-trip count changes. Presenting
|
|
1997
|
-
* happens ONCE: the display-surface barrier is per view, not per press, and paying it for every
|
|
1998
|
-
* point is what made an 86-cell board expensive.
|
|
1999
|
-
*
|
|
2000
|
-
* Stops at the first point that fails and reports where: a run that pressed through a page which
|
|
2001
|
-
* had navigated or lost its surface would fill the wrong cells and still answer success.
|
|
2002
|
-
* @param session - the session to click in.
|
|
2003
|
-
* @param request - the points and the interval between them.
|
|
2004
|
-
* @param signal - cancellation between points.
|
|
2005
|
-
* @returns how many points landed, and where it stopped if it did not finish.
|
|
2006
|
-
*/
|
|
2007
|
-
async clickSequence(session, request, signal) {
|
|
2008
|
-
const s = this.session(session);
|
|
2009
|
-
const points = Array.isArray(request.points) ? request.points : [];
|
|
2010
|
-
if (points.length === 0)
|
|
2011
|
-
return { clicked: 0 };
|
|
2012
|
-
if (this.settingsSource !== undefined && this.settingsSource().vision.strategy === 'nonVisual') {
|
|
2013
|
-
throw new BrowserError('browser: the configured non-visual strategy refuses coordinate clicks — pass a semantic target instead.', 'BROWSER_NON_VISUAL_COORDINATES');
|
|
2014
|
-
}
|
|
2015
|
-
// One barrier for the whole run: cheap, and it is the view that needs a surface, not each press.
|
|
2016
|
-
const handle = await this.present(s, signal);
|
|
2017
|
-
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
2018
|
-
// 40 ms is above one frame at 30 fps, which is what keeps the page from reading two presses as a
|
|
2019
|
-
// double click. Faster runs were measured dropping presses outright.
|
|
2020
|
-
const gap = typeof request.intervalMs === 'number' && request.intervalMs >= 0 ? request.intervalMs : 40;
|
|
2021
|
-
const send = (params, label) => withTimeout(handle.sendCommand('Input.dispatchMouseEvent', params), timeoutMs, signal, `browser: click sequence ${label} timed out after ${timeoutMs}ms`);
|
|
2022
|
-
let clicked = 0;
|
|
2023
|
-
for (const [index, point] of points.entries()) {
|
|
2024
|
-
signal?.throwIfAborted();
|
|
2025
|
-
const x = Number(point?.x);
|
|
2026
|
-
const y = Number(point?.y);
|
|
2027
|
-
if (!Number.isFinite(x) || !Number.isFinite(y)) {
|
|
2028
|
-
return { clicked, failedAt: index, error: `point ${index} has no finite x/y` };
|
|
2029
|
-
}
|
|
2030
|
-
try {
|
|
2031
|
-
// The move is load-bearing: Chromium routes a synthesized press to the CURRENT hover target,
|
|
2032
|
-
// and a view that has never received a mouse event has none — the first press would go nowhere
|
|
2033
|
-
// while CDP still answered success.
|
|
2034
|
-
await send({ type: 'mouseMoved', x, y, buttons: 0 }, 'move');
|
|
2035
|
-
await send({ type: 'mousePressed', x, y, button: 'left', buttons: 1, clickCount: 1 }, 'press');
|
|
2036
|
-
await send({ type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 }, 'release');
|
|
2037
|
-
clicked += 1;
|
|
2038
|
-
}
|
|
2039
|
-
catch (error) {
|
|
2040
|
-
// Best-effort release so a failed press cannot leave the button stuck down.
|
|
2041
|
-
void handle
|
|
2042
|
-
.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 })
|
|
2043
|
-
.catch(() => { });
|
|
2044
|
-
return { clicked, failedAt: index, error: String(error instanceof Error ? error.message : error) };
|
|
2045
|
-
}
|
|
2046
|
-
if (index < points.length - 1 && gap > 0)
|
|
2047
|
-
await new Promise(resolve => setTimeout(resolve, gap));
|
|
2048
|
-
}
|
|
2049
|
-
return { clicked };
|
|
2050
|
-
}
|
|
2051
|
-
/**
|
|
2052
|
-
* Type into the focused element, or focus a located element (css/text/xpath)
|
|
2053
|
-
* first and then insert the text.
|
|
2054
|
-
*/
|
|
2055
|
-
async type(session, request, signal) {
|
|
2056
|
-
const s = this.session(session);
|
|
2057
|
-
// The view the locate runs against. It can stop being the session's active view while
|
|
2058
|
-
// the locate waits (the human is invited to drive the same window), so the input below
|
|
2059
|
-
// goes to the handle `present` reports instead of this one.
|
|
2060
|
-
const locateHandle = this.activeTab(s).handle;
|
|
2061
|
-
signal?.throwIfAborted();
|
|
2062
|
-
const hasTarget = 'target' in request;
|
|
2063
|
-
if (hasTarget) {
|
|
2064
|
-
const locateMs = PROVIDER_TIMEOUTS.lookup;
|
|
2065
|
-
const script = this.buildTargetScript(request.target, locateMs, `
|
|
2066
|
-
el.focus()
|
|
2067
|
-
return { ok: true }
|
|
2068
|
-
`);
|
|
2069
|
-
const locateTab = this.activeTab(s);
|
|
2070
|
-
const out = await this.runTargetScript(locateTab, script, locateMs, signal, 'BROWSER_TYPE_FAILED', 'browser: type');
|
|
2071
|
-
const cursorPoint = scriptPoint(out);
|
|
2072
|
-
if (cursorPoint !== undefined)
|
|
2073
|
-
this.showCursor(locateTab.handle, cursorPoint.x, cursorPoint.y, 'click', 'type', true);
|
|
2074
|
-
}
|
|
2075
|
-
const text = 'text' in request ? request.text : '';
|
|
2076
|
-
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
2077
|
-
// Input.insertText goes through the Input domain: same display-surface
|
|
2078
|
-
// requirement as click/key. It also reports which view is active once the barrier has
|
|
2079
|
-
// settled, which is what makes the tab-switch check below meaningful.
|
|
2080
|
-
const handle = await this.present(s, signal);
|
|
2081
|
-
// Focusing one page and inserting into another is exactly the silent mis-target this
|
|
2082
|
-
// refuses: the element was focused in the located view, and the text would have gone to
|
|
2083
|
-
// whichever page is now visible — possibly a password field there.
|
|
2084
|
-
if (hasTarget)
|
|
2085
|
-
this.assertSameView(session, locateHandle, handle);
|
|
2086
|
-
try {
|
|
2087
|
-
await withTimeout(handle.sendCommand('Input.insertText', { text }), timeoutMs, signal, `browser: type timed out after ${timeoutMs}ms`);
|
|
2088
|
-
}
|
|
2089
|
-
catch (error) {
|
|
2090
|
-
throw new BrowserError(`browser: type failed: ${String(error)}`, 'BROWSER_TYPE_FAILED', { cause: error });
|
|
2091
|
-
}
|
|
2092
|
-
// Store the full text so replay re-issues the same input; the history
|
|
2093
|
-
// tool truncates long values when rendering.
|
|
2094
|
-
this.record(s, 'type', { text, ...hasTarget ? { target: request.target } : {} }, true);
|
|
2095
|
-
}
|
|
2096
|
-
/** Scroll the page: by deltas, to a selector, or to top/bottom. */
|
|
2097
|
-
async scroll(session, request, signal) {
|
|
2098
|
-
const s = this.session(session);
|
|
2099
|
-
const tab = this.activeTab(s);
|
|
2100
|
-
signal?.throwIfAborted();
|
|
2101
|
-
const selector = request.selector ?? '';
|
|
2102
|
-
const script = `(() => {
|
|
2103
|
-
const sel = ${JSON.stringify(selector)}
|
|
2104
|
-
if (sel !== '') {
|
|
2105
|
-
const el = document.querySelector(sel)
|
|
2106
|
-
if (!el) return { ok: false, reason: 'selector not found' }
|
|
2107
|
-
el.scrollIntoView({ behavior: 'instant', block: 'center' })
|
|
2108
|
-
return { ok: true }
|
|
2109
|
-
}
|
|
2110
|
-
if (${request.toTop === true}) { window.scrollTo(0, 0); return { ok: true } }
|
|
2111
|
-
if (${request.toBottom === true}) { window.scrollTo(0, document.body.scrollHeight); return { ok: true } }
|
|
2112
|
-
window.scrollBy({ top: ${request.deltaY ?? 0}, left: ${request.deltaX ?? 0} })
|
|
2113
|
-
return { ok: true }
|
|
2114
|
-
})()`;
|
|
2115
|
-
const timeoutMs = PROVIDER_TIMEOUTS.action;
|
|
2116
|
-
const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: scroll timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
2117
|
-
if (!result.ok)
|
|
2118
|
-
throw new BrowserError(`browser: scroll failed: ${result.exception}`, 'BROWSER_SCROLL_FAILED');
|
|
2119
|
-
const value = result.value;
|
|
2120
|
-
if (value.ok !== true)
|
|
2121
|
-
throw new BrowserError(`browser: scroll failed: ${value.reason ?? 'unknown'}`, 'BROWSER_SCROLL_FAILED');
|
|
2122
|
-
this.record(s, 'scroll', { ...request }, true);
|
|
2123
|
-
}
|
|
2124
|
-
/** Go back (-1) or forward (+1) in the active tab's navigation history. */
|
|
2125
|
-
async historyStep(session, direction, signal) {
|
|
2126
|
-
const s = this.session(session);
|
|
2127
|
-
const tab = this.activeTab(s);
|
|
2128
|
-
const { handle } = tab;
|
|
2129
|
-
const transaction = this.beginNavigation(tab, signal);
|
|
2130
|
-
const { navigation } = transaction;
|
|
2131
|
-
signal = transaction.signal;
|
|
2132
|
-
signal?.throwIfAborted();
|
|
2133
|
-
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
2134
|
-
const deadline = Date.now() + timeoutMs;
|
|
2135
|
-
const hist = await withTimeout(handle.sendCommand('Page.getNavigationHistory'), timeoutMs, signal, `browser: history read timed out after ${timeoutMs}ms`);
|
|
2136
|
-
this.checkNavigation(tab, navigation);
|
|
2137
|
-
const entries = hist.entries ?? [];
|
|
2138
|
-
const currentIndex = hist.currentIndex ?? -1;
|
|
2139
|
-
const target = currentIndex + direction;
|
|
2140
|
-
if (target < 0 || target >= entries.length) {
|
|
2141
|
-
// Nothing to step to; treat it as a successful no-op so the agent can
|
|
2142
|
-
// proceed without an error dance.
|
|
2143
|
-
this.record(s, direction === -1 ? 'back' : 'forward', {}, true);
|
|
2144
|
-
return;
|
|
2145
|
-
}
|
|
2146
|
-
const entry = entries[target];
|
|
2147
|
-
if (entry?.id === undefined)
|
|
2148
|
-
throw new BrowserError('browser: history entry missing id', 'BROWSER_HISTORY_INVALID');
|
|
2149
|
-
// A history step is a navigation too: the classic A→B→A redirect would
|
|
2150
|
-
// otherwise read the outgoing document's identity (see settleDocument).
|
|
2151
|
-
const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation); }, deadline, true);
|
|
2152
|
-
const inPage = await withTimeout(handleSendEvaluate(handle, `(() => {
|
|
2153
|
-
if (typeof navigation === 'undefined') return false;
|
|
2154
|
-
const entry = navigation.entries().find(entry => entry.index === navigation.currentEntry.index + ${direction});
|
|
2155
|
-
return entry?.url === ${JSON.stringify(entry.url)} && entry.sameDocument === true;
|
|
2156
|
-
})()`), Math.max(1, deadline - Date.now()), signal, 'browser: history document identity timed out', timedOut => { this.interrupt(handle, timedOut); });
|
|
2157
|
-
this.checkNavigation(tab, navigation);
|
|
2158
|
-
signal?.throwIfAborted();
|
|
2159
|
-
await withTimeout(handle.sendCommand('Page.navigateToHistoryEntry', { entryId: entry.id }), Math.max(1, deadline - Date.now()), signal, `browser: history navigation timed out after ${timeoutMs}ms`, () => { if (tab.navigation === navigation)
|
|
2160
|
-
void handle.sendCommand('Page.stopLoading').catch(() => { }); });
|
|
2161
|
-
await this.settleDocument(handle, before, signal, inPage.ok && inPage.value === true ? { frameId: before.id, loaderId: before.loaderId } : undefined, () => { this.checkNavigation(tab, navigation); }, entry.id, deadline, true);
|
|
2162
|
-
this.record(s, direction === -1 ? 'back' : 'forward', {}, true);
|
|
2163
|
-
this.recordVisit(s, handle);
|
|
2164
|
-
this.showActive(s);
|
|
2165
|
-
}
|
|
2166
|
-
/** Go back in the active tab's history. */
|
|
2167
|
-
async back(session, signal) {
|
|
2168
|
-
return this.historyStep(session, -1, signal);
|
|
2169
|
-
}
|
|
2170
|
-
/** Go forward in the active tab's history. */
|
|
2171
|
-
async forward(session, signal) {
|
|
2172
|
-
return this.historyStep(session, 1, signal);
|
|
2173
|
-
}
|
|
2174
|
-
/** Reload the active tab. */
|
|
2175
|
-
async reload(session, signal) {
|
|
2176
|
-
const s = this.session(session);
|
|
2177
|
-
const tab = this.activeTab(s);
|
|
2178
|
-
const { handle } = tab;
|
|
2179
|
-
const transaction = this.beginNavigation(tab, signal);
|
|
2180
|
-
const { navigation } = transaction;
|
|
2181
|
-
signal = transaction.signal;
|
|
2182
|
-
signal?.throwIfAborted();
|
|
2183
|
-
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
2184
|
-
const deadline = Date.now() + timeoutMs;
|
|
2185
|
-
// Same-URL reload: only the per-load document identity can tell the new
|
|
2186
|
-
// document from the old one, so capture it before reloading.
|
|
2187
|
-
const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation); }, deadline, true);
|
|
2188
|
-
this.checkNavigation(tab, navigation);
|
|
2189
|
-
signal?.throwIfAborted();
|
|
2190
|
-
await withTimeout(handle.sendCommand('Page.reload', { ignoreCache: false }), Math.max(1, deadline - Date.now()), signal, `browser: reload timed out after ${timeoutMs}ms`,
|
|
2191
|
-
// Best-effort: cancel the reload if it wedges the debugger queue.
|
|
2192
|
-
() => { if (tab.navigation === navigation)
|
|
2193
|
-
void handle.sendCommand('Page.stopLoading').catch(() => { }); });
|
|
2194
|
-
await this.settleDocument(handle, before, signal, undefined, () => { this.checkNavigation(tab, navigation); }, undefined, deadline, true);
|
|
2195
|
-
this.record(s, 'reload', {}, true);
|
|
2196
|
-
this.recordVisit(s, handle);
|
|
2197
|
-
this.showActive(s);
|
|
2198
|
-
}
|
|
2199
|
-
/** Press one named key (Enter/Tab/arrows/…) via CDP key events. */
|
|
2200
|
-
async key(session, request, signal) {
|
|
2201
|
-
const s = this.session(session);
|
|
2202
|
-
signal?.throwIfAborted();
|
|
2203
|
-
const spec = KEY_SPECS[request.key];
|
|
2204
|
-
if (spec === undefined) {
|
|
2205
|
-
throw new BrowserError(`browser: unsupported key "${request.key}" (supported: ${BROWSER_KEY_NAMES.join(', ')})`, 'BROWSER_KEY_UNSUPPORTED');
|
|
2206
|
-
}
|
|
2207
|
-
const params = { key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.vk, nativeVirtualKeyCode: spec.vk, ...spec.text !== undefined ? { text: spec.text } : {} };
|
|
2208
|
-
const timeoutMs = PROVIDER_TIMEOUTS.action;
|
|
2209
|
-
// Input.dispatchKeyEvent is subject to the same display-surface rule. The handle comes
|
|
2210
|
-
// back from the presentation barrier rather than from a capture taken before it: this
|
|
2211
|
-
// session is shared with the human, who may switch tabs while the barrier round-trips,
|
|
2212
|
-
// and a key sent to the view they left is silently dropped (or lands on the new page).
|
|
2213
|
-
const handle = await this.present(s, signal);
|
|
2214
|
-
// Focus the SAME view the key is dispatched to; focusing the pre-switch handle would
|
|
2215
|
-
// grant web focus to a page that then receives nothing.
|
|
2216
|
-
await this.focusView(handle);
|
|
2217
|
-
const release = () => handle.sendCommand('Input.dispatchKeyEvent', { type: 'keyUp', ...params });
|
|
2218
|
-
try {
|
|
2219
|
-
await withTimeout(handle.sendCommand('Input.dispatchKeyEvent', { type: 'keyDown', ...params }), timeoutMs, signal, `browser: key press timed out after ${timeoutMs}ms`);
|
|
2220
|
-
}
|
|
2221
|
-
catch (error) {
|
|
2222
|
-
// The press may still land late; release best-effort so the key is
|
|
2223
|
-
// never left in a stuck pressed state.
|
|
2224
|
-
void release().catch(() => { });
|
|
2225
|
-
throw new BrowserError(`browser: key "${request.key}" failed: ${String(error)}`, 'BROWSER_KEY_FAILED', { cause: error });
|
|
2226
|
-
}
|
|
2227
|
-
try {
|
|
2228
|
-
await withTimeout(release(), timeoutMs, signal, `browser: key release timed out after ${timeoutMs}ms`);
|
|
2229
|
-
}
|
|
2230
|
-
catch (error) {
|
|
2231
|
-
// The press already landed; retry the release before surfacing.
|
|
2232
|
-
void release().catch(() => { });
|
|
2233
|
-
throw new BrowserError(`browser: key "${request.key}" failed: ${String(error)}`, 'BROWSER_KEY_FAILED', { cause: error });
|
|
2234
|
-
}
|
|
2235
|
-
this.record(s, 'key', { key: request.key }, true);
|
|
2236
|
-
}
|
|
2237
|
-
/**
|
|
2238
|
-
* Fill a form's fields in one batch. Runs one page-context script that
|
|
2239
|
-
* resolves each field (selector, or name/label/placeholder among visible
|
|
2240
|
-
* controls), sets its value with the native prototype setter (React/Vue
|
|
2241
|
-
* controlled inputs included) plus input/change events, handles
|
|
2242
|
-
* select/checkbox/radio/contenteditable, and optionally submits the form.
|
|
2243
|
-
*/
|
|
2244
|
-
async fillForm(session, request, signal) {
|
|
2245
|
-
const s = this.session(session);
|
|
2246
|
-
const tab = this.activeTab(s);
|
|
2247
|
-
signal?.throwIfAborted();
|
|
2248
|
-
const specs = JSON.stringify(request.fields.map(f => ({
|
|
2249
|
-
selector: f.selector ?? null,
|
|
2250
|
-
name: f.name ?? null,
|
|
2251
|
-
label: f.label ?? null,
|
|
2252
|
-
placeholder: f.placeholder ?? null,
|
|
2253
|
-
// A field with NO kind is a field with no kind FILTER: absent, not 'text'. Defaulting
|
|
2254
|
-
// it to 'text' here made `if (spec.kind)` above always true, so every unspecified
|
|
2255
|
-
// field was narrowed to an <input> — dsh_browser_fill on a <textarea> reported
|
|
2256
|
-
// `no "text" control matched`, and a contenteditable could not match any kind at all.
|
|
2257
|
-
// The value stays a string or null (never undefined): the in-page check tests truthiness,
|
|
2258
|
-
// and JSON drops an undefined member entirely, which is the same thing here.
|
|
2259
|
-
kind: f.kind ?? null,
|
|
2260
|
-
value: f.value,
|
|
2261
|
-
})));
|
|
2262
|
-
const submitFlag = request.submit === true;
|
|
2263
|
-
const script = `(() => {
|
|
2264
|
-
const specs = ${specs}
|
|
2265
|
-
const out = []
|
|
2266
|
-
const setNative = (el, proto, value) => {
|
|
2267
|
-
const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
|
|
2268
|
-
if (setter) setter.call(el, value)
|
|
2269
|
-
else el.value = value
|
|
2270
|
-
}
|
|
2271
|
-
const visible = (el) => {
|
|
2272
|
-
const r = el.getBoundingClientRect()
|
|
2273
|
-
const cs = getComputedStyle(el)
|
|
2274
|
-
return r.width >= 4 && r.height >= 4 && cs.visibility !== 'hidden' && cs.display !== 'none'
|
|
2275
|
-
}
|
|
2276
|
-
const describe = (spec) => spec.selector || spec.name || spec.label || spec.placeholder || '(unspecified)'
|
|
2277
|
-
const matches = (el, spec) => {
|
|
2278
|
-
if (spec.selector) { try { return el.matches(spec.selector) } catch { return false } }
|
|
2279
|
-
if (spec.name && el.name === spec.name) return true
|
|
2280
|
-
if (spec.placeholder && el.placeholder === spec.placeholder) return true
|
|
2281
|
-
if (spec.label) {
|
|
2282
|
-
if (el.getAttribute('aria-label') === spec.label) return true
|
|
2283
|
-
if (el.id) {
|
|
2284
|
-
const lbl = document.querySelector('label[for=' + JSON.stringify(el.id) + ']')
|
|
2285
|
-
if (lbl && (lbl.textContent || '').trim() === spec.label) return true
|
|
2286
|
-
}
|
|
2287
|
-
const wrap = el.closest('label')
|
|
2288
|
-
if (wrap && (wrap.textContent || '').trim() === spec.label) return true
|
|
2289
|
-
}
|
|
2290
|
-
return false
|
|
2291
|
-
}
|
|
2292
|
-
// Every root this page exposes: the top document plus its shadow trees (recursively)
|
|
2293
|
-
// and same-origin iframes. The snapshot and waitFor already walk all of them, so an
|
|
2294
|
-
// element inside one is shown to the model and can be waited for — resolving a click or
|
|
2295
|
-
// a fill used to look at the top document alone and answer "not found" for something
|
|
2296
|
-
// the model had just been handed a reference to. The two must agree about what exists.
|
|
2297
|
-
// (Kept in step with the collector in the snapshot script above.)
|
|
2298
|
-
const allRoots = () => {
|
|
2299
|
-
const roots = []
|
|
2300
|
-
const seen = new Set()
|
|
2301
|
-
const visit = doc => {
|
|
2302
|
-
if (seen.has(doc)) return
|
|
2303
|
-
seen.add(doc)
|
|
2304
|
-
roots.push(doc)
|
|
2305
|
-
for (const el of doc.querySelectorAll('*')) {
|
|
2306
|
-
if (el.shadowRoot) visit(el.shadowRoot)
|
|
2307
|
-
if (el.tagName === 'IFRAME') {
|
|
2308
|
-
try { const d = el.contentDocument; if (d) visit(d) } catch { /* cross-origin */ }
|
|
2309
|
-
}
|
|
2310
|
-
}
|
|
2311
|
-
}
|
|
2312
|
-
visit(document)
|
|
2313
|
-
return roots
|
|
2314
|
-
}
|
|
2315
|
-
const roots = allRoots()
|
|
2316
|
-
const candidates = (spec) => {
|
|
2317
|
-
const all = spec.selector
|
|
2318
|
-
? roots.flatMap(root => [...root.querySelectorAll(spec.selector)])
|
|
2319
|
-
: roots.flatMap(root => [...root.querySelectorAll('input, textarea, select, [contenteditable="true"]')]).filter(el => matches(el, spec))
|
|
2320
|
-
const vis = all.filter(visible)
|
|
2321
|
-
return vis.length > 0 ? vis : all
|
|
2322
|
-
}
|
|
2323
|
-
for (const spec of specs) {
|
|
2324
|
-
let els
|
|
2325
|
-
try {
|
|
2326
|
-
els = candidates(spec)
|
|
2327
|
-
} catch (e) {
|
|
2328
|
-
// A malformed selector must not abort the whole batch; report the
|
|
2329
|
-
// field as failed and continue with the rest.
|
|
2330
|
-
out.push({ ok: false, error: String(e), target: describe(spec) })
|
|
2331
|
-
continue
|
|
2332
|
-
}
|
|
2333
|
-
if (els.length === 0) { out.push({ ok: false, error: 'field not found', target: describe(spec) }); continue }
|
|
2334
|
-
let el = els[0]
|
|
2335
|
-
// The caller may name a kind. Honor it: the branches below read the element's own
|
|
2336
|
-
// tag/type, so without this a selector matching two different controls acted on
|
|
2337
|
-
// whichever came first — usually right, which is what hid the mistake. A field that
|
|
2338
|
-
// names NO kind gets no filter at all: the element's own tag then decides the
|
|
2339
|
-
// branch, which is what "kind defaults to text" was always trying to say.
|
|
2340
|
-
if (spec.kind) {
|
|
2341
|
-
const matchesKind = (node) => {
|
|
2342
|
-
const nodeTag = node.tagName
|
|
2343
|
-
const nodeType = (node.type || '').toLowerCase()
|
|
2344
|
-
if (spec.kind === 'select') return nodeTag === 'SELECT'
|
|
2345
|
-
if (spec.kind === 'textarea') return nodeTag === 'TEXTAREA'
|
|
2346
|
-
if (spec.kind === 'checkbox' || spec.kind === 'radio') return nodeType === spec.kind
|
|
2347
|
-
// 'text': the plain-value branch covers <input> AND <textarea>, and the batch
|
|
2348
|
-
// already collects [contenteditable="true"] as a settable control — so all three
|
|
2349
|
-
// must match. Requiring nodeTag === 'INPUT' here reported "no text control
|
|
2350
|
-
// matched" for a textarea and left the contenteditable branch below unreachable.
|
|
2351
|
-
if (nodeTag === 'TEXTAREA') return true
|
|
2352
|
-
if (node.isContentEditable === true) return true
|
|
2353
|
-
return nodeTag === 'INPUT' && nodeType !== 'checkbox' && nodeType !== 'radio' && nodeType !== 'file'
|
|
2354
|
-
}
|
|
2355
|
-
const wanted = els.find(matchesKind)
|
|
2356
|
-
if (wanted === undefined) {
|
|
2357
|
-
out.push({ ok: false, error: 'no "' + spec.kind + '" control matched', target: describe(spec) })
|
|
2358
|
-
continue
|
|
2359
|
-
}
|
|
2360
|
-
els.length = 0
|
|
2361
|
-
els.push(wanted)
|
|
2362
|
-
// el was bound before the filter narrowed els, so the branches below would still
|
|
2363
|
-
// read the first match — the very silent wrong-element behaviour this filter exists
|
|
2364
|
-
// to remove.
|
|
2365
|
-
el = els[0]
|
|
2366
|
-
}
|
|
2367
|
-
const tag = el.tagName
|
|
2368
|
-
const type = (el.type || '').toLowerCase()
|
|
2369
|
-
try {
|
|
2370
|
-
if (tag === 'SELECT') {
|
|
2371
|
-
const wanted = String(spec.value)
|
|
2372
|
-
if (el.multiple) {
|
|
2373
|
-
const wantedList = wanted.split(',').map(x => x.trim())
|
|
2374
|
-
let hit = false
|
|
2375
|
-
for (const o of [...el.options]) {
|
|
2376
|
-
o.selected = wantedList.includes(o.value) || wantedList.includes((o.textContent || '').trim())
|
|
2377
|
-
if (o.selected) hit = true
|
|
2378
|
-
}
|
|
2379
|
-
if (!hit) { out.push({ ok: false, error: 'option not found: ' + wanted, target: describe(spec) }); continue }
|
|
2380
|
-
} else {
|
|
2381
|
-
let opt = [...el.options].find(o => o.value === wanted)
|
|
2382
|
-
if (!opt) opt = [...el.options].find(o => (o.textContent || '').trim() === wanted)
|
|
2383
|
-
if (!opt) { out.push({ ok: false, error: 'option not found: ' + wanted, target: describe(spec) }); continue }
|
|
2384
|
-
setNative(el, HTMLSelectElement.prototype, opt.value)
|
|
2385
|
-
}
|
|
2386
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2387
|
-
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
2388
|
-
out.push({ ok: true, method: 'select', target: describe(spec) })
|
|
2389
|
-
} else if (type === 'file') {
|
|
2390
|
-
out.push({ ok: false, error: 'file inputs cannot be set from script; use dsh_browser_download or ask the human', target: describe(spec) })
|
|
2391
|
-
} else if (type === 'checkbox') {
|
|
2392
|
-
const want = spec.value === true || spec.value === 'true' || spec.value === 'on'
|
|
2393
|
-
if (el.checked !== want) el.click()
|
|
2394
|
-
out.push({ ok: true, method: 'checkbox', target: describe(spec) })
|
|
2395
|
-
} else if (type === 'radio') {
|
|
2396
|
-
const wanted = String(spec.value)
|
|
2397
|
-
const radio = [...document.querySelectorAll('input[type="radio"][name=' + JSON.stringify(el.name || '') + ']')]
|
|
2398
|
-
.find(r => r.value === wanted || (r === el && (spec.value === true || spec.value === 'true')))
|
|
2399
|
-
if (!radio) { out.push({ ok: false, error: 'radio option not found: ' + wanted, target: describe(spec) }); continue }
|
|
2400
|
-
if (!radio.checked) radio.click()
|
|
2401
|
-
out.push({ ok: true, method: 'radio', target: describe(spec) })
|
|
2402
|
-
} else if (el.isContentEditable) {
|
|
2403
|
-
el.textContent = String(spec.value)
|
|
2404
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2405
|
-
out.push({ ok: true, method: 'contenteditable', target: describe(spec) })
|
|
2406
|
-
} else if (tag === 'TEXTAREA') {
|
|
2407
|
-
setNative(el, HTMLTextAreaElement.prototype, String(spec.value))
|
|
2408
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2409
|
-
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
2410
|
-
out.push({ ok: true, method: 'textarea', target: describe(spec) })
|
|
2411
|
-
} else {
|
|
2412
|
-
setNative(el, HTMLInputElement.prototype, String(spec.value))
|
|
2413
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2414
|
-
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
2415
|
-
out.push({ ok: true, method: 'input', target: describe(spec) })
|
|
2416
|
-
}
|
|
2417
|
-
} catch (e) {
|
|
2418
|
-
out.push({ ok: false, error: String(e), target: describe(spec) })
|
|
2419
|
-
}
|
|
2420
|
-
}
|
|
2421
|
-
let submitted = false
|
|
2422
|
-
if (${submitFlag}) {
|
|
2423
|
-
let last = null
|
|
2424
|
-
for (const spec of specs) {
|
|
2425
|
-
try { const els = candidates(spec); if (els.length > 0) { last = els[0]; break } } catch { /* skip */ }
|
|
2426
|
-
}
|
|
2427
|
-
const form = last && (last.form || last.closest('form'))
|
|
2428
|
-
if (form) { form.requestSubmit(); submitted = true }
|
|
2429
|
-
}
|
|
2430
|
-
return { fields: out, submitted }
|
|
2431
|
-
})()`;
|
|
2432
|
-
const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
|
|
2433
|
-
const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: fillForm timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
2434
|
-
if (!result.ok) {
|
|
2435
|
-
throw new BrowserError(`browser: fillForm evaluation failed: ${result.exception}`, 'BROWSER_FILL_FAILED');
|
|
2436
|
-
}
|
|
2437
|
-
const value = result.value;
|
|
2438
|
-
const okCount = value.fields.filter(f => f.ok).length;
|
|
2439
|
-
this.record(s, 'fill', { fields: request.fields.length, submit: submitFlag }, okCount === value.fields.length, {
|
|
2440
|
-
result: `${okCount}/${value.fields.length} fields filled${value.submitted ? ', form submitted' : ''}`,
|
|
2441
|
-
});
|
|
2442
|
-
return { fields: value.fields, submitted: value.submitted === true };
|
|
2443
|
-
}
|
|
2444
|
-
/**
|
|
2445
|
-
* Build an in-page async IIFE that locates ONE element by css/text/xpath
|
|
2446
|
-
* (polling until it appears or the budget runs out) and then runs `body`
|
|
2447
|
-
* with `el` in scope. Shared by the target-based tools: click/type (②),
|
|
2448
|
-
* setValue/check/select/clear/getValue (③), and the scrape item wait.
|
|
2449
|
-
* A selector that fails to PARSE is reported immediately instead of being
|
|
2450
|
-
* polled until the budget expires — see the comment in `match`.
|
|
2451
|
-
*/
|
|
2452
|
-
buildTargetScript(spec, timeoutMs, body) {
|
|
2453
|
-
// `by` defaults to css in-page; report the strategy that WAS used, or a
|
|
2454
|
-
// miss says only `{"value":"Learn more"}` and the caller cannot tell that a
|
|
2455
|
-
// plain label was queried as a CSS selector.
|
|
2456
|
-
const resolvedSpec = { ...spec, by: spec.by ?? 'css' };
|
|
2457
|
-
return `(async () => {
|
|
2458
|
-
const spec = ${JSON.stringify(resolvedSpec)}
|
|
2459
|
-
const timeoutMs = ${String(timeoutMs)}
|
|
2460
|
-
const sleep = ms => new Promise(r => setTimeout(r, ms))
|
|
2461
|
-
const isVisible = el => el instanceof HTMLElement && (el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0)
|
|
2462
|
-
const ownText = el => Array.from(el.childNodes).filter(n => n.nodeType === Node.TEXT_NODE).map(n => n.textContent || '').join('').trim()
|
|
2463
|
-
const depth = el => { let d = 0; let p = el.parentElement; while (p) { d++; p = p.parentElement } return d }
|
|
2464
|
-
const match = () => {
|
|
2465
|
-
const by = typeof spec.by === 'string' ? spec.by : 'css'
|
|
2466
|
-
const value = String(spec.value ?? '')
|
|
2467
|
-
// Named matchIndex rather than index: this whole function is one host-side template
|
|
2468
|
-
// literal, so a bare name declared here can silently shadow a host binding of the
|
|
2469
|
-
// same name and turn an inner reference into a type error.
|
|
2470
|
-
const matchIndex = typeof spec.index === 'number' ? spec.index : 0
|
|
2471
|
-
// An index that cannot address an element can never match on a later poll, exactly
|
|
2472
|
-
// like a selector that fails to parse — so it must not look like a miss either. A
|
|
2473
|
-
// negative index, the common "last one" shorthand, otherwise burned the caller's
|
|
2474
|
-
// whole locate budget (10s) and then reported "element not found", which reads like a
|
|
2475
|
-
// slow page rather than a bad argument.
|
|
2476
|
-
// (No backticks in this comment: it lives inside a template literal.)
|
|
2477
|
-
if (!Number.isInteger(matchIndex) || matchIndex < 0) {
|
|
2478
|
-
throw new Error('target.index must be a non-negative integer, got ' + JSON.stringify(spec.index))
|
|
2479
|
-
}
|
|
2480
|
-
let els = []
|
|
2481
|
-
// Every root this page exposes: the top document plus its shadow trees (recursively)
|
|
2482
|
-
// and same-origin iframes. The snapshot and waitFor already walk all of them, so an
|
|
2483
|
-
// element inside one is shown to the model and can be waited for — resolving a click or
|
|
2484
|
-
// a fill used to look at the top document alone and answer "not found" for something
|
|
2485
|
-
// the model had just been handed a reference to. The two must agree about what exists.
|
|
2486
|
-
// (Kept in step with the collector in the snapshot script above.)
|
|
2487
|
-
const allRoots = () => {
|
|
2488
|
-
const roots = []
|
|
2489
|
-
const seen = new Set()
|
|
2490
|
-
const visit = doc => {
|
|
2491
|
-
if (seen.has(doc)) return
|
|
2492
|
-
seen.add(doc)
|
|
2493
|
-
roots.push(doc)
|
|
2494
|
-
for (const el of doc.querySelectorAll('*')) {
|
|
2495
|
-
if (el.shadowRoot) visit(el.shadowRoot)
|
|
2496
|
-
if (el.tagName === 'IFRAME') {
|
|
2497
|
-
try { const d = el.contentDocument; if (d) visit(d) } catch { /* cross-origin */ }
|
|
2498
|
-
}
|
|
155
|
+
process.stderr.write(`[dsh-browser] ${this.referenceScan.lastError}\n`);
|
|
156
|
+
try {
|
|
157
|
+
await this.evaluateInTab(tab, standaloneScript(noticeScript(hostMessages.zh.referenceFailed)), PROVIDER_TIMEOUTS.evaluation);
|
|
158
|
+
}
|
|
159
|
+
catch { /* The failure remains in host diagnostics when the guest disappears. */ }
|
|
2499
160
|
}
|
|
2500
|
-
|
|
2501
|
-
visit(document)
|
|
2502
|
-
return roots
|
|
161
|
+
return true;
|
|
2503
162
|
}
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
// not about which root holds the element.
|
|
2514
|
-
try { document.querySelectorAll(value) }
|
|
2515
|
-
catch (error) { throw new Error('invalid CSS selector ' + JSON.stringify(value) + ' (' + String((error && error.message) || error) + ')') }
|
|
2516
|
-
for (const root of roots) els.push(...root.querySelectorAll(value))
|
|
2517
|
-
} else if (by === 'xpath') {
|
|
2518
|
-
try {
|
|
2519
|
-
for (const root of roots) {
|
|
2520
|
-
const snap = document.evaluate(value, root, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
|
|
2521
|
-
for (let i = 0; i < snap.snapshotLength; i++) {
|
|
2522
|
-
const n = snap.snapshotItem(i)
|
|
2523
|
-
if (n instanceof Element) els.push(n)
|
|
2524
|
-
}
|
|
163
|
+
catch {
|
|
164
|
+
// A tab mid-navigation has no execution context yet; the next tick retries.
|
|
165
|
+
// A page that keeps failing backs off instead of being forgotten: the
|
|
166
|
+
// handle is the only way back to a page this host adopted, and dropping it
|
|
167
|
+
// made the bar stop delivering for the rest of the conversation.
|
|
168
|
+
tab.misses = (tab.misses ?? 0) + 1;
|
|
169
|
+
if (tab.misses >= DEAD_REFERENCE_TAB_MISSES) {
|
|
170
|
+
tab.misses = 0;
|
|
171
|
+
tab.retryAt = Date.now() + DEAD_REFERENCE_TAB_RETRY_MS;
|
|
2525
172
|
}
|
|
2526
|
-
|
|
2527
|
-
} else {
|
|
2528
|
-
// '*' rather than 'body *': a shadow root and an iframe document have no body of
|
|
2529
|
-
// their own to anchor to, and the visibility and own-text predicates below are what
|
|
2530
|
-
// actually decide whether an element counts.
|
|
2531
|
-
const all = roots.flatMap(root => [...root.querySelectorAll('*')])
|
|
2532
|
-
const exact = all.filter(el => isVisible(el) && ownText(el) === value)
|
|
2533
|
-
// Exact first, then contains; deepest element preferred (so a
|
|
2534
|
-
// button inside a card wins over the card itself).
|
|
2535
|
-
const pool = exact.length > 0 ? exact : all.filter(el => isVisible(el) && ownText(el).includes(value))
|
|
2536
|
-
els = pool.sort((a, b) => depth(b) - depth(a))
|
|
173
|
+
return true;
|
|
2537
174
|
}
|
|
2538
|
-
return els[matchIndex] ?? null
|
|
2539
|
-
}
|
|
2540
|
-
const deadline = Date.now() + timeoutMs
|
|
2541
|
-
let el = null
|
|
2542
|
-
for (;;) {
|
|
2543
|
-
// Only a parse error escapes the poll: see the comment in match() above.
|
|
2544
|
-
try { el = match() } catch (error) { return { ok: false, error: String((error && error.message) || error) } }
|
|
2545
|
-
if (el !== null) break
|
|
2546
|
-
if (Date.now() >= deadline) return { ok: false, error: 'element not found: ' + JSON.stringify(spec) + ' (looked for ' + timeoutMs + 'ms)' }
|
|
2547
|
-
await sleep(100)
|
|
2548
|
-
}
|
|
2549
|
-
const __result = await (async () => {
|
|
2550
|
-
${body}
|
|
2551
|
-
})()
|
|
2552
|
-
// Report the operated element's viewport center next to the script's own
|
|
2553
|
-
// verdict: the synthetic cursor (and any future feedback) needs the point,
|
|
2554
|
-
// and no individual body should have to compute it a second time. Kept
|
|
2555
|
-
// under a distinct key so a body that already returns x/y keeps them.
|
|
2556
|
-
const __rect = el.getBoundingClientRect()
|
|
2557
|
-
return {
|
|
2558
|
-
...(typeof __result === 'object' && __result !== null ? __result : { ok: true }),
|
|
2559
|
-
__point: { x: Math.round(__rect.x + __rect.width / 2), y: Math.round(__rect.y + __rect.height / 2) },
|
|
2560
|
-
}
|
|
2561
|
-
})()`;
|
|
2562
175
|
}
|
|
176
|
+
/** Forget one dead adopted tab; the conversation's next page starts a fresh session. */
|
|
2563
177
|
/**
|
|
2564
|
-
*
|
|
2565
|
-
*
|
|
2566
|
-
*
|
|
178
|
+
* What the sidebar reference entry is doing right now.
|
|
179
|
+
*
|
|
180
|
+
* Served on the reference route so "there is no selection bar on my page" has an
|
|
181
|
+
* answer that is not a guess: which conversation this process thinks it serves,
|
|
182
|
+
* whether a page was adopted, how many the shell reported, and the last refusal.
|
|
2567
183
|
*/
|
|
2568
|
-
|
|
2569
|
-
// The script polls for its whole `timeoutMs` and only then answers, so an
|
|
2570
|
-
// outer budget of the same size fires at the same instant and wins: the
|
|
2571
|
-
// caller saw `click timed out after 10000ms` while the page had already
|
|
2572
|
-
// decided WHY (selector not found / malformed). Give the answer a chance to
|
|
2573
|
-
// get back before the generic timeout replaces it.
|
|
2574
|
-
const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs + TARGET_SCRIPT_GRACE_MS, signal, `${errorLabel} timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
2575
|
-
if (!result.ok)
|
|
2576
|
-
throw new BrowserError(`${errorLabel} failed: ${result.exception}`, errorCode);
|
|
2577
|
-
const value = result.value;
|
|
2578
|
-
if (value?.ok !== true)
|
|
2579
|
-
throw new BrowserError(`${errorLabel} failed: ${value?.error ?? 'unknown'}`, errorCode);
|
|
2580
|
-
return value;
|
|
2581
|
-
}
|
|
2582
|
-
/** Set one element's value (native setter + input/change, React-friendly). */
|
|
2583
|
-
async setValue(session, request, signal) {
|
|
2584
|
-
const s = this.session(session);
|
|
2585
|
-
const tab = this.activeTab(s);
|
|
2586
|
-
signal?.throwIfAborted();
|
|
2587
|
-
const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
|
|
2588
|
-
const body = `
|
|
2589
|
-
const value = ${JSON.stringify(String(request.value))}
|
|
2590
|
-
const setNative = (el, proto, v) => {
|
|
2591
|
-
const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
|
|
2592
|
-
if (setter) setter.call(el, v)
|
|
2593
|
-
else el.value = v
|
|
2594
|
-
}
|
|
2595
|
-
const tag = el.tagName
|
|
2596
|
-
const type = (el.type || '').toLowerCase()
|
|
2597
|
-
if (tag === 'SELECT') {
|
|
2598
|
-
const wanted = value
|
|
2599
|
-
let opt = [...el.options].find(o => o.value === wanted)
|
|
2600
|
-
if (!opt) opt = [...el.options].find(o => (o.textContent || '').trim() === wanted)
|
|
2601
|
-
if (!opt) return { ok: false, error: 'option not found: ' + wanted }
|
|
2602
|
-
setNative(el, HTMLSelectElement.prototype, opt.value)
|
|
2603
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2604
|
-
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
2605
|
-
return { ok: true, method: 'select', value: opt.value }
|
|
2606
|
-
}
|
|
2607
|
-
if (el.isContentEditable) {
|
|
2608
|
-
el.textContent = value
|
|
2609
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2610
|
-
return { ok: true, method: 'contenteditable', value }
|
|
2611
|
-
}
|
|
2612
|
-
if (tag === 'TEXTAREA') {
|
|
2613
|
-
setNative(el, HTMLTextAreaElement.prototype, value)
|
|
2614
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2615
|
-
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
2616
|
-
return { ok: true, method: 'textarea', value }
|
|
2617
|
-
}
|
|
2618
|
-
setNative(el, HTMLInputElement.prototype, value)
|
|
2619
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2620
|
-
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
2621
|
-
return { ok: true, method: 'input', value }
|
|
2622
|
-
`;
|
|
2623
|
-
const script = this.buildTargetScript(request.target, timeoutMs, body);
|
|
2624
|
-
const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_SET_VALUE_FAILED', 'browser: setValue');
|
|
2625
|
-
const cursorPoint = scriptPoint(out);
|
|
2626
|
-
if (cursorPoint !== undefined)
|
|
2627
|
-
this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click');
|
|
2628
|
-
this.record(s, 'setValue', { target: request.target, value: String(request.value) }, true, { result: out.method });
|
|
2629
|
-
return { method: out.method, value: out.value };
|
|
2630
|
-
}
|
|
2631
|
-
/** Check or uncheck one checkbox/radio. */
|
|
2632
|
-
async check(session, request, signal) {
|
|
2633
|
-
const s = this.session(session);
|
|
2634
|
-
const tab = this.activeTab(s);
|
|
2635
|
-
signal?.throwIfAborted();
|
|
2636
|
-
const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
|
|
2637
|
-
const want = request.checked ?? true;
|
|
2638
|
-
const body = `
|
|
2639
|
-
const want = ${String(want)}
|
|
2640
|
-
const type = (el.type || '').toLowerCase()
|
|
2641
|
-
if (type === 'checkbox') {
|
|
2642
|
-
if (el.checked !== want) el.click()
|
|
2643
|
-
return { ok: true, checked: el.checked }
|
|
2644
|
-
}
|
|
2645
|
-
if (type === 'radio') {
|
|
2646
|
-
if (want && !el.checked) el.click()
|
|
2647
|
-
return { ok: true, checked: el.checked }
|
|
2648
|
-
}
|
|
2649
|
-
return { ok: false, error: 'element is not a checkbox or radio (' + el.tagName + ')' }
|
|
2650
|
-
`;
|
|
2651
|
-
const script = this.buildTargetScript(request.target, timeoutMs, body);
|
|
2652
|
-
const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_CHECK_FAILED', 'browser: check');
|
|
2653
|
-
const cursorPoint = scriptPoint(out);
|
|
2654
|
-
if (cursorPoint !== undefined)
|
|
2655
|
-
this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click');
|
|
2656
|
-
this.record(s, 'check', { target: request.target, checked: want }, true);
|
|
2657
|
-
return { checked: out.checked === true };
|
|
2658
|
-
}
|
|
2659
|
-
/** Select one option of a <select>, by value, visible text, or index. */
|
|
2660
|
-
async selectOption(session, request, signal) {
|
|
2661
|
-
const s = this.session(session);
|
|
2662
|
-
const tab = this.activeTab(s);
|
|
2663
|
-
signal?.throwIfAborted();
|
|
2664
|
-
const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
|
|
2665
|
-
const body = `
|
|
2666
|
-
if (el.tagName !== 'SELECT') return { ok: false, error: 'element is not a <select> (' + el.tagName + ')' }
|
|
2667
|
-
const optionValue = ${JSON.stringify(request.optionValue ?? null)}
|
|
2668
|
-
const optionText = ${JSON.stringify(request.optionText ?? null)}
|
|
2669
|
-
const optionIndex = ${String(request.optionIndex ?? -1)}
|
|
2670
|
-
let opt = null
|
|
2671
|
-
if (optionValue !== null) opt = [...el.options].find(o => o.value === optionValue)
|
|
2672
|
-
if (!opt && optionText !== null) opt = [...el.options].find(o => (o.textContent || '').trim() === optionText)
|
|
2673
|
-
if (!opt && optionIndex >= 0) opt = el.options[optionIndex] ?? null
|
|
2674
|
-
if (!opt) return { ok: false, error: 'option not found' }
|
|
2675
|
-
const setNative = (el, proto, v) => {
|
|
2676
|
-
const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
|
|
2677
|
-
if (setter) setter.call(el, v)
|
|
2678
|
-
else el.value = v
|
|
2679
|
-
}
|
|
2680
|
-
setNative(el, HTMLSelectElement.prototype, opt.value)
|
|
2681
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2682
|
-
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
2683
|
-
return { ok: true, value: opt.value, text: (opt.textContent || '').trim() }
|
|
2684
|
-
`;
|
|
2685
|
-
const script = this.buildTargetScript(request.target, timeoutMs, body);
|
|
2686
|
-
const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_SELECT_FAILED', 'browser: select');
|
|
2687
|
-
const cursorPoint = scriptPoint(out);
|
|
2688
|
-
if (cursorPoint !== undefined)
|
|
2689
|
-
this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click');
|
|
2690
|
-
this.record(s, 'select', { target: request.target, optionValue: request.optionValue ?? null, optionText: request.optionText ?? null, optionIndex: request.optionIndex ?? null }, true);
|
|
2691
|
-
return { value: out.value, text: out.text };
|
|
2692
|
-
}
|
|
2693
|
-
/** Clear one input/textarea/contenteditable (or uncheck a checkbox/radio). */
|
|
2694
|
-
async clearField(session, request, signal) {
|
|
2695
|
-
const s = this.session(session);
|
|
2696
|
-
const tab = this.activeTab(s);
|
|
2697
|
-
signal?.throwIfAborted();
|
|
2698
|
-
const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
|
|
2699
|
-
const body = `
|
|
2700
|
-
const setNative = (el, proto) => {
|
|
2701
|
-
const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
|
|
2702
|
-
if (setter) setter.call(el, '')
|
|
2703
|
-
else el.value = ''
|
|
2704
|
-
}
|
|
2705
|
-
if (el.isContentEditable) {
|
|
2706
|
-
el.textContent = ''
|
|
2707
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2708
|
-
} else if (el.tagName === 'TEXTAREA') {
|
|
2709
|
-
setNative(el, HTMLTextAreaElement.prototype)
|
|
2710
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2711
|
-
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
2712
|
-
} else if (el.tagName === 'INPUT' && (el.type === 'checkbox' || el.type === 'radio')) {
|
|
2713
|
-
if (el.checked) el.click()
|
|
2714
|
-
} else {
|
|
2715
|
-
setNative(el, HTMLInputElement.prototype)
|
|
2716
|
-
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
2717
|
-
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
2718
|
-
}
|
|
2719
|
-
return { ok: true }
|
|
2720
|
-
`;
|
|
2721
|
-
const script = this.buildTargetScript(request.target, timeoutMs, body);
|
|
2722
|
-
const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_CLEAR_FAILED', 'browser: clear');
|
|
2723
|
-
const cursorPoint = scriptPoint(out);
|
|
2724
|
-
if (cursorPoint !== undefined)
|
|
2725
|
-
this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click');
|
|
2726
|
-
this.record(s, 'clear', { target: request.target }, true);
|
|
2727
|
-
return { cleared: true };
|
|
2728
|
-
}
|
|
2729
|
-
/** Read one element's current value (for verification). */
|
|
2730
|
-
async getValue(session, request, signal) {
|
|
2731
|
-
const s = this.session(session);
|
|
2732
|
-
const tab = this.activeTab(s);
|
|
2733
|
-
signal?.throwIfAborted();
|
|
2734
|
-
const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
|
|
2735
|
-
const body = `
|
|
2736
|
-
const type = (el.type || '').toLowerCase()
|
|
2737
|
-
if (type === 'checkbox' || type === 'radio') return { ok: true, value: null, checked: el.checked }
|
|
2738
|
-
if (el.tagName === 'SELECT') {
|
|
2739
|
-
const o = el.options[el.selectedIndex]
|
|
2740
|
-
return { ok: true, value: el.value, selectedText: o ? (o.textContent || '').trim() : null }
|
|
2741
|
-
}
|
|
2742
|
-
const v = el.value !== undefined ? el.value : el.textContent
|
|
2743
|
-
return { ok: true, value: v === undefined || v === null ? null : String(v) }
|
|
2744
|
-
`;
|
|
2745
|
-
const script = this.buildTargetScript(request.target, timeoutMs, body);
|
|
2746
|
-
const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_GET_VALUE_FAILED', 'browser: getValue');
|
|
2747
|
-
this.record(s, 'getValue', { target: request.target }, true);
|
|
184
|
+
referenceStatus() {
|
|
2748
185
|
return {
|
|
2749
|
-
|
|
2750
|
-
...
|
|
2751
|
-
|
|
186
|
+
...this.referenceScan.label === undefined ? {} : { label: this.referenceScan.label },
|
|
187
|
+
...this.referenceSession === undefined ? {} : { session: this.referenceSession },
|
|
188
|
+
pages: this.referenceScan.pages,
|
|
189
|
+
...this.referenceScan.lastError === undefined ? {} : { lastError: this.referenceScan.lastError },
|
|
2752
190
|
};
|
|
2753
191
|
}
|
|
2754
192
|
/**
|
|
2755
|
-
*
|
|
2756
|
-
*
|
|
2757
|
-
* through the field selectors; `selector@attr` reads an attribute instead
|
|
2758
|
-
* of text (`a@href` yields an absolute URL).
|
|
2759
|
-
*/
|
|
2760
|
-
async scrape(session, request, signal) {
|
|
2761
|
-
const s = this.session(session);
|
|
2762
|
-
const tab = this.activeTab(s);
|
|
2763
|
-
signal?.throwIfAborted();
|
|
2764
|
-
const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
|
|
2765
|
-
const script = `(async () => {
|
|
2766
|
-
const itemSel = ${JSON.stringify(request.item)}
|
|
2767
|
-
const fields = ${JSON.stringify(request.fields)}
|
|
2768
|
-
const timeoutMs = ${String(timeoutMs)}
|
|
2769
|
-
const sleep = ms => new Promise(r => setTimeout(r, ms))
|
|
2770
|
-
const parseField = f => {
|
|
2771
|
-
const m = /^(.*)@([A-Za-z][A-Za-z0-9_-]*)$/.exec(f.selector.trim())
|
|
2772
|
-
if (m) return { base: m[1].trim(), attr: m[2] }
|
|
2773
|
-
return { base: f.selector, attr: null }
|
|
2774
|
-
}
|
|
2775
|
-
const deadline = Date.now() + timeoutMs
|
|
2776
|
-
let items = []
|
|
2777
|
-
for (;;) {
|
|
2778
|
-
// Immediate, like match() above: an unparseable selector can never match.
|
|
2779
|
-
try { items = Array.from(document.querySelectorAll(itemSel)) }
|
|
2780
|
-
catch (error) { return { ok: false, error: 'invalid CSS selector ' + JSON.stringify(itemSel) + ' (' + String((error && error.message) || error) + ')' } }
|
|
2781
|
-
if (items.length > 0) break
|
|
2782
|
-
if (Date.now() >= deadline) return { ok: false, error: 'no elements matched: ' + itemSel }
|
|
2783
|
-
await sleep(100)
|
|
2784
|
-
}
|
|
2785
|
-
const out = []
|
|
2786
|
-
for (const it of items) {
|
|
2787
|
-
const row = {}
|
|
2788
|
-
for (const f of fields) {
|
|
2789
|
-
const { base, attr } = parseField(f)
|
|
2790
|
-
let el = null
|
|
2791
|
-
try { el = base === '' ? it : it.querySelector(base) } catch { el = null }
|
|
2792
|
-
if (!el) { row[f.name] = null; continue }
|
|
2793
|
-
if (attr !== null) {
|
|
2794
|
-
const v = el.getAttribute(attr)
|
|
2795
|
-
row[f.name] = attr === 'href' && el.tagName === 'A' && v ? new URL(v, location.href).href : v
|
|
2796
|
-
continue
|
|
2797
|
-
}
|
|
2798
|
-
row[f.name] = (el.textContent || '').trim()
|
|
2799
|
-
}
|
|
2800
|
-
out.push(row)
|
|
2801
|
-
}
|
|
2802
|
-
return { ok: true, count: out.length, items: out }
|
|
2803
|
-
})()`;
|
|
2804
|
-
const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs + TARGET_SCRIPT_GRACE_MS, signal, `browser: scrape timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
2805
|
-
if (!result.ok)
|
|
2806
|
-
throw new BrowserError(`browser: scrape evaluation failed: ${result.exception}`, 'BROWSER_SCRAPE_FAILED');
|
|
2807
|
-
const value = result.value;
|
|
2808
|
-
if (value.ok !== true)
|
|
2809
|
-
throw new BrowserError(`browser: scrape failed: ${value.error ?? 'unknown'}`, 'BROWSER_SCRAPE_FAILED');
|
|
2810
|
-
const items = value.items ?? [];
|
|
2811
|
-
this.record(s, 'scrape', { item: request.item, fields: request.fields.map(f => f.name) }, true, { result: `${items.length} items` });
|
|
2812
|
-
return { count: items.length, items };
|
|
2813
|
-
}
|
|
2814
|
-
/**
|
|
2815
|
-
* Refuse an action the settings have switched off.
|
|
2816
|
-
*
|
|
2817
|
-
* These switches belong to the OPERATOR. The settings document is written through the
|
|
2818
|
-
* plugin's own panel and no tool can reach it, so — unlike `dsh_browser_restrict`, which the
|
|
2819
|
-
* model owns and can lift at will — a refusal here stands for as long as the setting does.
|
|
2820
|
-
* That is the point of them: a deployment can take page-script execution, downloads, or
|
|
2821
|
-
* login-state writes off the table without relying on the model's cooperation.
|
|
2822
|
-
*
|
|
2823
|
-
* Read through `settingsSource` on every call rather than captured at construction, so
|
|
2824
|
-
* flipping a switch applies to the next command instead of the next restart — the same
|
|
2825
|
-
* rule the credentials gate follows.
|
|
2826
|
-
* @param action - which switch to consult.
|
|
2827
|
-
* @throws BrowserError when that switch is off.
|
|
193
|
+
* Usable when the host says it can back views (the self-hosted host probes
|
|
194
|
+
* for a usable Electron binary; the desktop shell is assumed usable).
|
|
2828
195
|
*/
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
if (settings === undefined)
|
|
2832
|
-
return;
|
|
2833
|
-
if (action === 'execute' && !settings.actions.allowExecute) {
|
|
2834
|
-
throw new BrowserError('browser: running page scripts is switched off in settings (Browser → actions)', 'BROWSER_EXECUTE_DISABLED');
|
|
2835
|
-
}
|
|
2836
|
-
if (action === 'download' && !settings.actions.allowDownload) {
|
|
2837
|
-
throw new BrowserError('browser: downloads are switched off in settings (Browser → actions)', 'BROWSER_DOWNLOAD_DISABLED');
|
|
2838
|
-
}
|
|
2839
|
-
if (action === 'credentialWrite' && !settings.actions.allowCredentialWrite) {
|
|
2840
|
-
throw new BrowserError('browser: writing cookies is switched off in settings (Browser → actions)', 'BROWSER_AUTH_WRITE_DISABLED');
|
|
2841
|
-
}
|
|
196
|
+
available() {
|
|
197
|
+
return this.host.available?.() ?? true;
|
|
2842
198
|
}
|
|
2843
199
|
/**
|
|
2844
|
-
*
|
|
2845
|
-
*
|
|
2846
|
-
*
|
|
2847
|
-
*
|
|
2848
|
-
*
|
|
2849
|
-
*
|
|
2850
|
-
*
|
|
2851
|
-
* @param kind - the operation, used in the error code and message.
|
|
2852
|
-
* @returns the resolved absolute target path.
|
|
2853
|
-
* @throws BrowserError when the path is relative, outside the directory, or occupied.
|
|
200
|
+
* Open a NEW browser session with its own view. Every call mints a fresh
|
|
201
|
+
* session id and backing view; per-task reuse is owned by the caller (the
|
|
202
|
+
* tool layer caches one session per DSH task). Sessions are isolated from
|
|
203
|
+
* each other: each keeps its own tabs, active tab, and history, and only
|
|
204
|
+
* the active tab of a session is made visible.
|
|
205
|
+
* @param label - optional human-readable label (e.g. the DSH task id) shown
|
|
206
|
+
* in the window title so a human can tell which task's page is visible.
|
|
2854
207
|
*/
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
const
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
// that merely differed in case pass admission — a directory-confinement escape, and
|
|
2869
|
-
// one that mkdirSync below would then happily create.
|
|
2870
|
-
const fold = process.platform === 'win32' ? (value) => value.toLowerCase() : (value) => value;
|
|
2871
|
-
const dirKey = fold(dir);
|
|
2872
|
-
const fileKey = fold(file);
|
|
2873
|
-
// The directory ITSELF is refused, not accepted: a save path that IS downloadDir names
|
|
2874
|
-
// a directory, so there is no file to write — and mkdirSync would have created the
|
|
2875
|
-
// directory when it did not exist. Two paths are "inside" only when the file path is
|
|
2876
|
-
// strictly below the directory, which the separator check below already expresses.
|
|
2877
|
-
if (!fileKey.startsWith(dirKey + fold(sep))) {
|
|
2878
|
-
throw new BrowserError(`browser: ${kind} savePath must be inside downloadDir "${dir}"`, code);
|
|
2879
|
-
}
|
|
2880
|
-
// The check above is textual, and a symlink defeats it: resolve() normalizes `..`
|
|
2881
|
-
// but never follows a link, so `<downloadDir>/out/x.png` passed every test above
|
|
2882
|
-
// while `out` pointed at a directory outside the gate — and the write then landed
|
|
2883
|
-
// there. Resolve the REAL location of the deepest existing ancestor (which is what
|
|
2884
|
-
// decides where the bytes go) and require it to be inside the real directory too.
|
|
2885
|
-
// A legitimate path is unaffected: its ancestor resolves to the directory itself.
|
|
2886
|
-
//
|
|
2887
|
-
// The directory is created first so that it can be resolved at all — mkdirSync is a
|
|
2888
|
-
// no-op for one that already exists — and a directory that cannot be created or
|
|
2889
|
-
// resolved falls back to its textual form, leaving the real filesystem error to the
|
|
2890
|
-
// write instead of inventing one here.
|
|
2891
|
-
let realDir;
|
|
2892
|
-
try {
|
|
2893
|
-
mkdirSync(dir, { recursive: true });
|
|
2894
|
-
realDir = fold(realpathSync(dir));
|
|
2895
|
-
}
|
|
2896
|
-
catch {
|
|
2897
|
-
realDir = fold(dir);
|
|
2898
|
-
}
|
|
2899
|
-
const realAncestor = fold(realAncestorOf(file));
|
|
2900
|
-
if (realAncestor !== realDir && !realAncestor.startsWith(realDir + fold(sep))) {
|
|
2901
|
-
throw new BrowserError(`browser: ${kind} savePath resolves outside downloadDir "${dir}" (a symlink leaves it)`, code);
|
|
2902
|
-
}
|
|
2903
|
-
}
|
|
2904
|
-
// Never replace an existing file: its previous content is unrecoverable,
|
|
2905
|
-
// and the admitted directory may hold files the human put there. A new
|
|
2906
|
-
// name is one tool call away.
|
|
2907
|
-
//
|
|
2908
|
-
// Judged with lstat (see {@link entryExists}), not existsSync: existsSync FOLLOWS
|
|
2909
|
-
// links, so a DANGLING symlink read as "nothing here" and the write below created
|
|
2910
|
-
// its target — outside the directory whenever the link pointed out of it. It is the
|
|
2911
|
-
// directory entry that has to be free, whatever that entry points at.
|
|
2912
|
-
if (entryExists(file)) {
|
|
2913
|
-
throw new BrowserError(`browser: refusing to overwrite existing file "${file}" — use another name`, code);
|
|
2914
|
-
}
|
|
2915
|
-
return file;
|
|
208
|
+
open(label) {
|
|
209
|
+
// The label is the calling DSH task, and it is handed to the view as its owner: a host shared
|
|
210
|
+
// by several conversations (the desktop's) keeps one conversation's page out of another's on
|
|
211
|
+
// the strength of it, so it is not decoration.
|
|
212
|
+
const id = sessionWireId(browserSessionHandle(label || 'default', randomUUID()));
|
|
213
|
+
const tabId = tabWireId({ ...resolveSessionHandle(id), tab: randomUUID() });
|
|
214
|
+
const handle = this.host.createView(tabId);
|
|
215
|
+
// Group the session's views under its own window (one window per
|
|
216
|
+
// session), carrying the label for the window title. Hosts without
|
|
217
|
+
// groupView keep the shared-window behavior.
|
|
218
|
+
this.host.groupView?.(handle, id, label);
|
|
219
|
+
this.sessions.set(id, { id, label, tabs: [{ id: tabId, handle, url: '' }], activeIndex: 0, history: [], nextSeq: 1 });
|
|
220
|
+
return Promise.resolve(id);
|
|
2916
221
|
}
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
* with its own authenticated browser session. Both admitted paths and screenshots are confined
|
|
2921
|
-
* to `downloadDir`, so a prompt-injected agent cannot write arbitrary
|
|
2922
|
-
* machine paths.
|
|
2923
|
-
* @param session - the session whose cookies are used.
|
|
2924
|
-
* @param request - the URL plus the absolute target path.
|
|
2925
|
-
* @param signal - optional cancellation.
|
|
2926
|
-
* @returns the path the file was written to.
|
|
2927
|
-
*/
|
|
2928
|
-
async download(session, request, signal) {
|
|
2929
|
-
// Before admission, and before the session is even resolved: a switched-off action is
|
|
2930
|
-
// not a path problem, and the caller should hear the real reason.
|
|
2931
|
-
this.assertActionAllowed('download');
|
|
2932
|
-
const s = this.session(session);
|
|
2933
|
-
const { handle } = this.activeTab(s);
|
|
222
|
+
async prepareCarrier(signal, scope) {
|
|
223
|
+
if (this.host.prepare === undefined)
|
|
224
|
+
return;
|
|
2934
225
|
signal?.throwIfAborted();
|
|
2935
|
-
// URL admission: HTTP(S) only (mirrors the navigation guard). The seam
|
|
2936
|
-
// intentionally does not block private/localhost targets — a shared real
|
|
2937
|
-
// browser legitimately reaches local dev servers.
|
|
2938
|
-
let parsed;
|
|
2939
226
|
try {
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
catch {
|
|
2943
|
-
throw new BrowserError(`browser: refusing download of unparseable URL "${request.url}"`, 'BROWSER_DOWNLOAD_BLOCKED');
|
|
2944
|
-
}
|
|
2945
|
-
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
2946
|
-
throw new BrowserError(`browser: refusing download of non-HTTP(S) URL "${request.url}"`, 'BROWSER_DOWNLOAD_BLOCKED');
|
|
2947
|
-
}
|
|
2948
|
-
// savePath admission: the shared gate — absolute, inside `downloadDir`,
|
|
2949
|
-
// and never an existing file. Screenshots use the very same one.
|
|
2950
|
-
const savePath = this.admitSavePath(request.savePath, 'download');
|
|
2951
|
-
const downloadable = handle;
|
|
2952
|
-
if (typeof downloadable.download !== 'function') {
|
|
2953
|
-
throw new BrowserError('browser: the selected carrier does not provide file downloads', 'BROWSER_DOWNLOAD_UNSUPPORTED');
|
|
2954
|
-
}
|
|
2955
|
-
// The child fetches and writes the file; a slow/hung network can block
|
|
2956
|
-
// it well past the tool budget, so bound it. NOTE: unlike CDP calls,
|
|
2957
|
-
// there is no child-side abort mechanism for the RPC download — when the
|
|
2958
|
-
// parent's timeout fires the child continues writing. The parent's pending
|
|
2959
|
-
// entry is cleaned up (the promise settles) and the child's eventual
|
|
2960
|
-
// reply is harmlessly consumed by the RPC layer.
|
|
2961
|
-
const timeoutMs = PROVIDER_TIMEOUTS.download;
|
|
2962
|
-
await withTimeout(downloadable.download(request.url, savePath), timeoutMs, signal, `browser: download timed out after ${timeoutMs}ms`);
|
|
2963
|
-
this.record(s, 'download', { url: request.url, savePath }, true, { result: savePath });
|
|
2964
|
-
return { path: savePath };
|
|
2965
|
-
}
|
|
2966
|
-
/**
|
|
2967
|
-
* Export the session's cookies (login state) as serializable objects.
|
|
2968
|
-
* Self-hosted only; the desktop shell's embedded views use the real profile.
|
|
2969
|
-
*/
|
|
2970
|
-
async flushAuth(session) {
|
|
2971
|
-
// The settings panel offers "allow the agent to read cookies / export login state".
|
|
2972
|
-
// Until now nothing read that switch, so turning it off changed nothing at all —
|
|
2973
|
-
// the tool exported every cookie regardless.
|
|
2974
|
-
if (this.settingsSource?.().credentials.allowRead === false) {
|
|
2975
|
-
throw new BrowserError('browser: reading cookies is switched off in settings (Browser → credentials)', 'BROWSER_AUTH_DISABLED');
|
|
2976
|
-
}
|
|
2977
|
-
const s = this.session(session);
|
|
2978
|
-
const { handle } = this.activeTab(s);
|
|
2979
|
-
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
2980
|
-
// The self-hosted carrier has a native path (the child reads its own session), which
|
|
2981
|
-
// is worth preferring: it reports exactly what the browser persisted.
|
|
2982
|
-
const native = handle;
|
|
2983
|
-
if (typeof native.flushAuth === 'function') {
|
|
2984
|
-
const cookies = await withTimeout(native.flushAuth(), timeoutMs, undefined, `browser: auth export timed out after ${timeoutMs}ms`);
|
|
2985
|
-
this.record(s, 'flushAuth', {}, true, { result: `${cookies.length} cookies` });
|
|
2986
|
-
return cookies;
|
|
227
|
+
await withTimeout(this.host.prepare(scope), PROVIDER_TIMEOUTS.prepare, signal, 'browser: carrier launch timed out before navigating a guest');
|
|
228
|
+
this.carrierLaunchError = undefined;
|
|
2987
229
|
}
|
|
2988
|
-
|
|
2989
|
-
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
// window and every task drives the same browser, so signing in once works everywhere,
|
|
2993
|
-
// which is the whole point of "use your own browser". What must not be shared is the
|
|
2994
|
-
// HANDING OVER: an unfiltered read puts every domain every task has visited, plus
|
|
2995
|
-
// whatever the human is signed into, in front of one task's caller. Least exposure,
|
|
2996
|
-
// not isolation.
|
|
2997
|
-
//
|
|
2998
|
-
// Two corrections to the previous attempt. It called Storage.getCookies with a `urls`
|
|
2999
|
-
// parameter, but that method takes only browserContextId and ignores everything else, so
|
|
3000
|
-
// the filter did nothing and the whole jar was still exported; `urls` belongs to
|
|
3001
|
-
// Network.getCookies. And it silently fell back to an unfiltered read when the page URL
|
|
3002
|
-
// was unavailable — an error path that asked for MORE than the normal one. Both are
|
|
3003
|
-
// fixed: the method that honours the filter, and a failure that refuses instead of
|
|
3004
|
-
// widening.
|
|
3005
|
-
const cookiesUrl = await this.currentUrl(handle).catch(() => '');
|
|
3006
|
-
if (cookiesUrl === '') {
|
|
3007
|
-
throw new BrowserError('browser: cannot export cookies without knowing which page this session is on — the URL was unavailable, and reading the whole cookie jar would expose every other session\'s logins', 'BROWSER_AUTH_SCOPE_UNKNOWN');
|
|
230
|
+
catch (error) {
|
|
231
|
+
if (!signal?.aborted)
|
|
232
|
+
this.carrierLaunchError = error;
|
|
233
|
+
throw error;
|
|
3008
234
|
}
|
|
3009
|
-
const result = await withTimeout(handle.sendCommand('Network.getCookies', { urls: [cookiesUrl] }), timeoutMs, undefined, `browser: auth export timed out after ${timeoutMs}ms`);
|
|
3010
|
-
const cookies = toExportedCookies(result.cookies);
|
|
3011
|
-
this.record(s, 'flushAuth', {}, true, { result: `${cookies.length} cookies (CDP)` });
|
|
3012
|
-
return cookies;
|
|
3013
235
|
}
|
|
3014
|
-
|
|
3015
|
-
async restoreAuth(session, cookies) {
|
|
3016
|
-
// Restore WRITES cookies, so it answers to the write switch — not to
|
|
3017
|
-
// `credentials.allowRead`. It used to consult the read switch and report "reading
|
|
3018
|
-
// cookies is switched off", which is both the wrong gate and the wrong sentence: an
|
|
3019
|
-
// operator who allowed reading but wanted logins left alone had no switch at all,
|
|
3020
|
-
// and one who turned reading off lost the restore path for the wrong reason.
|
|
3021
|
-
this.assertActionAllowed('credentialWrite');
|
|
236
|
+
async bindPage(session, pageId) {
|
|
3022
237
|
const s = this.session(session);
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
}
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
//
|
|
3035
|
-
// toCdpCookie returns undefined for a cookie it cannot place (no usable domain), and
|
|
3036
|
-
// `cookies.map(...)` passed that undefined straight through: the array then held a
|
|
3037
|
-
// JSON `null`, CDP rejected the WHOLE call, and every valid cookie failed with an error
|
|
3038
|
-
// naming none of them. Filter the unusable ones out and say how many went.
|
|
3039
|
-
const mapped = cookies.map(toCdpCookie);
|
|
3040
|
-
const convertible = mapped.filter((cookie) => cookie !== undefined);
|
|
3041
|
-
const dropped = mapped.length - convertible.length;
|
|
3042
|
-
if (dropped > 0) {
|
|
3043
|
-
process.stderr.write(`[dsh-browser] restoreAuth: dropped ${dropped} of ${mapped.length} cookie(s) with no usable domain; the rest were still restored\n`);
|
|
3044
|
-
}
|
|
3045
|
-
await withTimeout(handle.sendCommand('Storage.setCookies', { cookies: convertible }), timeoutMs, undefined, `browser: auth restore timed out after ${timeoutMs}ms`);
|
|
3046
|
-
// Storage.setCookies returns nothing, so the count comes from what was actually sent.
|
|
3047
|
-
// An earlier version read result.cookies here; it was always undefined and rendered as
|
|
3048
|
-
// "Restored 0 cookies." even though the write had succeeded.
|
|
3049
|
-
const restored = convertible.length;
|
|
3050
|
-
this.record(s, 'restoreAuth', { count: cookies.length, dropped }, true, { result: `${restored} cookies (CDP)${dropped > 0 ? `; ${dropped} dropped` : ''}` });
|
|
3051
|
-
return restored;
|
|
238
|
+
if (this.host.adoptPage === undefined || !s.label)
|
|
239
|
+
throw new Error('sidebar page binding unsupported');
|
|
240
|
+
if (s.tabs.some(tab => tab.url !== ''))
|
|
241
|
+
throw new Error('source binding requires a fresh browser session');
|
|
242
|
+
const id = tabWireId(resolveTabHandle(resolveSessionHandle(s.id), pageId));
|
|
243
|
+
const handle = await this.host.adoptPage(id, this.carrierScope(s));
|
|
244
|
+
const previous = [...s.tabs];
|
|
245
|
+
s.tabs.splice(0, s.tabs.length, { id: this.carrierTab(s, id), handle, url: '' });
|
|
246
|
+
s.activeIndex = 0;
|
|
247
|
+
for (const tab of previous)
|
|
248
|
+
this.destroyTab(tab);
|
|
3052
249
|
}
|
|
3053
250
|
/**
|
|
3054
|
-
*
|
|
3055
|
-
*
|
|
3056
|
-
* `screenshot` calls `showActive()` before capturing, and that is right for a tool whose point is
|
|
3057
|
-
* that the human sees what the model just captured. It is also what makes that path unusable for a
|
|
3058
|
-
* live preview: presenting on every frame would move focus, switch tabs and expand windows on the
|
|
3059
|
-
* host's screen — exactly the side effects a viewer must not cause (issue #34).
|
|
251
|
+
* The most recent open request, for the Web sidebar.
|
|
3060
252
|
*
|
|
3061
|
-
*
|
|
3062
|
-
*
|
|
3063
|
-
*
|
|
3064
|
-
*
|
|
3065
|
-
* @
|
|
3066
|
-
* @returns the encoded image and its dimensions; throws BROWSER_PREVIEW_UNAVAILABLE when the page
|
|
3067
|
-
* is not painted, which the caller turns into a "paused" state rather than an error.
|
|
253
|
+
* On the desktop shell the host half tells the shell to place a tab (`__dshBuiltinBrowser.openPanel`)
|
|
254
|
+
* through the bridge. The Web shell has no such channel, so a tool-opened page lived only in the
|
|
255
|
+
* plugin's own browser while the panel stayed empty — and "open it in the sidebar" took several manual
|
|
256
|
+
* steps. The client polls this one slot and places the tab itself.
|
|
257
|
+
* @returns the last request and when it arrived, or undefined when nothing was opened yet.
|
|
3068
258
|
*/
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
const { handle } = this.activeTab(s);
|
|
3072
|
-
const timeoutMs = PREVIEW_CAPTURE_MS;
|
|
3073
|
-
const timeoutMessage = `browser: preview capture timed out after ${timeoutMs}ms`;
|
|
3074
|
-
// The self-hosted carrier encodes in the child from a NativeImage; it is the only path that can
|
|
3075
|
-
// produce JPEG under Electron 43, whose CDP JPEG encoder hangs.
|
|
3076
|
-
if (typeof handle.capture === 'function') {
|
|
3077
|
-
const shot = await withTimeout(handle.capture({
|
|
3078
|
-
format: 'jpeg',
|
|
3079
|
-
quality: PREVIEW_QUALITY,
|
|
3080
|
-
maxWidth: PREVIEW_MAX_WIDTH,
|
|
3081
|
-
maxHeight: PREVIEW_MAX_HEIGHT,
|
|
3082
|
-
}), timeoutMs, undefined, timeoutMessage);
|
|
3083
|
-
if (shot.base64 === '') {
|
|
3084
|
-
// A hidden or minimized window is not a failure to report as one: the design says the
|
|
3085
|
-
// viewer shows pause and does not open a window to fix it.
|
|
3086
|
-
throw new BrowserError('browser: preview unavailable (the page is not painted; the window may be hidden or minimized)', 'BROWSER_PREVIEW_UNAVAILABLE');
|
|
3087
|
-
}
|
|
3088
|
-
return {
|
|
3089
|
-
dataUrl: `data:${shot.mime};base64,${shot.base64}`,
|
|
3090
|
-
...shot.width !== undefined && shot.height !== undefined
|
|
3091
|
-
? { width: shot.width, height: shot.height }
|
|
3092
|
-
: {},
|
|
3093
|
-
};
|
|
3094
|
-
}
|
|
3095
|
-
// Real Chrome/Edge (and the sidebar): CDP. Viewport only — `captureBeyondViewport` would pull
|
|
3096
|
-
// the whole document, which is neither what a viewer shows nor bounded in size.
|
|
3097
|
-
//
|
|
3098
|
-
// `present: false` is load-bearing (issue #46): a preview is read-only, so it must not reach the
|
|
3099
|
-
// carrier's present path, which for the sidebar asks the shell to display this conversation —
|
|
3100
|
-
// the reported symptom was the sidebar browser panel jumping to the front when someone opened
|
|
3101
|
-
// the preview. A page that is not displayed now reads as "unavailable", which the route already
|
|
3102
|
-
// turns into the panel's paused state.
|
|
3103
|
-
const result = await withTimeout(handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, {
|
|
3104
|
-
format: 'jpeg',
|
|
3105
|
-
quality: PREVIEW_QUALITY,
|
|
3106
|
-
fromSurface: true,
|
|
3107
|
-
captureBeyondViewport: false,
|
|
3108
|
-
}, { present: false }), timeoutMs, undefined, timeoutMessage);
|
|
3109
|
-
const base64 = typeof result?.data === 'string' ? result.data : '';
|
|
3110
|
-
if (base64 === '') {
|
|
3111
|
-
throw new BrowserError('browser: preview unavailable (the carrier returned no image)', 'BROWSER_PREVIEW_UNAVAILABLE');
|
|
3112
|
-
}
|
|
3113
|
-
return { dataUrl: `data:image/jpeg;base64,${base64}` };
|
|
259
|
+
lastOpenRequest() {
|
|
260
|
+
return this.lastOpen;
|
|
3114
261
|
}
|
|
3115
|
-
/**
|
|
3116
|
-
|
|
3117
|
-
|
|
262
|
+
/**
|
|
263
|
+
* Make sure the active tab's view can actually receive synthesized input.
|
|
264
|
+
* Chromium drops `Input.*` events for a view with no display surface, so this
|
|
265
|
+
* runs before click/type/key and fails loudly (BROWSER_VIEW_NOT_PRESENTED)
|
|
266
|
+
* rather than reporting a success the page never saw.
|
|
267
|
+
* @param s - the session whose active view must be presented.
|
|
268
|
+
* @param signal - optional cancellation.
|
|
269
|
+
* @returns the view the session's active tab has AFTER the presentation barrier.
|
|
270
|
+
*/
|
|
271
|
+
async present(s, signal) {
|
|
3118
272
|
const { handle } = this.activeTab(s);
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
// in the window; capturePage is fast for visible views and resolves
|
|
3124
|
-
// immediately (empty) for hidden ones. JPEG and downscaling are encoded
|
|
3125
|
-
// in the child from the NativeImage, so this path is the only one that
|
|
3126
|
-
// can produce JPEG (CDP JPEG hangs on Electron 43).
|
|
3127
|
-
const capturable = handle;
|
|
3128
|
-
// A region capture must go through CDP: the native NativeImage path has no
|
|
3129
|
-
// clip and would present/activate the window (a quiet-mode violation).
|
|
3130
|
-
if (request?.clip === undefined && request?.fullPage !== true && typeof capturable.capture === 'function') {
|
|
3131
|
-
// Ensure the target view is the visible one before capturing — unless quiet mode is on.
|
|
3132
|
-
// There, presenting the view is exactly what the user asked to avoid (it restores and
|
|
3133
|
-
// raises the window); the host switches the visible tab inside the window and, if the
|
|
3134
|
-
// window has no surface to capture, falls through to CDP.
|
|
3135
|
-
if (!this.isQuiet())
|
|
3136
|
-
this.showActive(s);
|
|
3137
|
-
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
3138
|
-
const shot = await withTimeout(capturable.capture({
|
|
3139
|
-
...format === 'jpeg' ? { format, quality: request?.quality } : {},
|
|
3140
|
-
...request?.maxWidth !== undefined ? { maxWidth: request.maxWidth } : {},
|
|
3141
|
-
...request?.maxHeight !== undefined ? { maxHeight: request.maxHeight } : {},
|
|
3142
|
-
quiet: this.isQuiet(),
|
|
3143
|
-
}), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`);
|
|
3144
|
-
if (shot.base64 === '') {
|
|
3145
|
-
throw new BrowserError('browser: capture returned an empty image (view not painted); retry shortly', 'BROWSER_SCREENSHOT_FAILED');
|
|
3146
|
-
}
|
|
3147
|
-
return this.saveScreenshot(shot.base64, request?.savePath, shot.mime ?? 'image/png',
|
|
3148
|
-
// The child measured these after applying any downscale, and they describe the image
|
|
3149
|
-
// the caller receives. Without them this path — the default self-hosted one — could
|
|
3150
|
-
// never answer the width/height its own tool schema declares.
|
|
3151
|
-
shot.width !== undefined && shot.height !== undefined
|
|
3152
|
-
? { width: shot.width, height: shot.height }
|
|
3153
|
-
: undefined);
|
|
3154
|
-
}
|
|
3155
|
-
// Fallback: a handle without a native capture() (the sidebar, or an installed Chrome
|
|
3156
|
-
// or Edge) uses CDP; full-page needs `captureBeyondViewport`, which capturePage lacks.
|
|
3157
|
-
//
|
|
3158
|
-
// JPEG: Electron 43's CDP hangs on it, which is why the sidebar stays PNG. An
|
|
3159
|
-
// installed Chrome or Edge is the real browser and has no such defect, so it says so
|
|
3160
|
-
// through `supportsCdpJpeg` and gets the format it asked for, and the same for
|
|
3161
|
-
// downscaling, which CDP performs through a full-document clip.
|
|
3162
|
-
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
3163
|
-
const params = {};
|
|
3164
|
-
const region = request?.clip;
|
|
3165
|
-
if (region !== undefined) {
|
|
3166
|
-
const valid = [region.x, region.y, region.width, region.height].every(value => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 8192) && region.width > 0 && region.height > 0;
|
|
3167
|
-
if (!valid)
|
|
3168
|
-
throw new BrowserError('browser: screenshot region is out of range', 'BROWSER_SCREENSHOT_FAILED');
|
|
3169
|
-
params.clip = { x: region.x, y: region.y, width: region.width, height: region.height, scale: 1 };
|
|
3170
|
-
params.fromSurface = true;
|
|
3171
|
-
params.captureBeyondViewport = false;
|
|
3172
|
-
}
|
|
3173
|
-
if (region === undefined && request?.fullPage === true) {
|
|
3174
|
-
// `captureBeyondViewport` captures the full scrollable content; without
|
|
3175
|
-
// a clip this yields the full-page image (CDP default is the viewport).
|
|
3176
|
-
params.captureBeyondViewport = true;
|
|
3177
|
-
}
|
|
3178
|
-
const supportsJpeg = handle.supportsCdpJpeg === true;
|
|
3179
|
-
if (format === 'jpeg' && supportsJpeg) {
|
|
3180
|
-
params.format = 'jpeg';
|
|
3181
|
-
// CDP range is 0-100 and defaults to 80 when omitted.
|
|
3182
|
-
if (request?.quality !== undefined)
|
|
3183
|
-
params.quality = request.quality;
|
|
273
|
+
const present = this.host.presentView?.bind(this.host);
|
|
274
|
+
if (present === undefined) {
|
|
275
|
+
this.showActive(s);
|
|
276
|
+
return this.activeTab(s).handle;
|
|
3184
277
|
}
|
|
3185
|
-
|
|
3186
|
-
|
|
3187
|
-
|
|
3188
|
-
|
|
3189
|
-
|
|
3190
|
-
if (region === undefined && (request?.maxWidth !== undefined || request?.maxHeight !== undefined)) {
|
|
3191
|
-
const metrics = await withTimeout(handle.sendCommand('Page.getLayoutMetrics', {}), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`);
|
|
3192
|
-
const size = layoutSize(metrics);
|
|
3193
|
-
if (size !== undefined) {
|
|
3194
|
-
const height = request.fullPage === true ? size.height : size.viewportHeight;
|
|
3195
|
-
const byWidth = request.maxWidth !== undefined && size.width > 0 ? request.maxWidth / size.width : 1;
|
|
3196
|
-
const byHeight = request.maxHeight !== undefined && height > 0 ? request.maxHeight / height : 1;
|
|
3197
|
-
const scale = Math.min(1, byWidth, byHeight);
|
|
3198
|
-
// What the caller will actually receive. Recorded before the branch below, because the
|
|
3199
|
-
// size is worth reporting even when no scaling happened (scale 1).
|
|
3200
|
-
rendered = { width: Math.round(size.width * scale), height: Math.round(height * scale) };
|
|
3201
|
-
if (scale < 1) {
|
|
3202
|
-
params.clip = { x: 0, y: 0, width: size.width, height, scale };
|
|
3203
|
-
// The clip defines the captured area; captureBeyondViewport must not also apply.
|
|
3204
|
-
delete params.captureBeyondViewport;
|
|
3205
|
-
}
|
|
3206
|
-
}
|
|
278
|
+
signal?.throwIfAborted();
|
|
279
|
+
const timeoutMs = PROVIDER_TIMEOUTS.lookup;
|
|
280
|
+
try {
|
|
281
|
+
await withTimeout(present(handle, s.label, { quiet: this.isQuiet() }), timeoutMs, signal, `browser: presenting the page view timed out after ${timeoutMs}ms`);
|
|
282
|
+
this.showActive(s);
|
|
3207
283
|
}
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
const result = await withTimeout(region === undefined
|
|
3211
|
-
? handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params)
|
|
3212
|
-
: handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params, { present: false }), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`);
|
|
3213
|
-
const data = result.data;
|
|
3214
|
-
if (typeof data !== 'string') {
|
|
3215
|
-
throw new BrowserError('browser: screenshot returned no image data', 'BROWSER_SCREENSHOT_FAILED');
|
|
284
|
+
catch (error) {
|
|
285
|
+
throw new BrowserError(`browser: the page view is not presented, so synthesized input would be silently dropped (${String(error)})`, 'BROWSER_VIEW_NOT_PRESENTED', { cause: error });
|
|
3216
286
|
}
|
|
3217
|
-
//
|
|
3218
|
-
//
|
|
3219
|
-
//
|
|
3220
|
-
//
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
|
|
3228
|
-
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
if (savePath !== undefined) {
|
|
3233
|
-
// Admission failures propagate unchanged: they describe the caller's
|
|
3234
|
-
// path, not a disk problem.
|
|
3235
|
-
const target = this.admitSavePath(savePath, 'screenshot');
|
|
3236
|
-
try {
|
|
3237
|
-
writeFileNoReplace(target, Buffer.from(base64, 'base64'));
|
|
3238
|
-
return { dataUrl: `data:${mime};base64,${base64}`, path: target, ...rendered };
|
|
3239
|
-
}
|
|
3240
|
-
catch (error) {
|
|
3241
|
-
// Report the write problem but keep the capture usable.
|
|
3242
|
-
throw new BrowserError(`browser: screenshot save to "${target}" failed: ${String(error)}`, 'BROWSER_SCREENSHOT_SAVE_FAILED', { cause: error });
|
|
3243
|
-
}
|
|
287
|
+
// Read the active tab AGAIN. `present` is a round-trip that can take up to the budget
|
|
288
|
+
// above, and the human is invited to drive the same window (a toolbar tab switch, a
|
|
289
|
+
// closed window) while the agent waits. Chromium answers `Input.*` with success even
|
|
290
|
+
// for a view that has no display surface, so dispatching to a handle that is no longer
|
|
291
|
+
// the visible one does not fail — it silently lands nowhere, or on the wrong page.
|
|
292
|
+
//
|
|
293
|
+
// Returning the re-read handle was wrong, though: `handle` above is the one that was
|
|
294
|
+
// actually presented, and if the active tab changed during the round trip then the
|
|
295
|
+
// re-read one was never presented at all. Handing it back meant the caller dispatched
|
|
296
|
+
// to a view with no display surface — the exact failure this method exists to prevent,
|
|
297
|
+
// arrived at from the other side. Either the presented view is still the active one, or
|
|
298
|
+
// the caller must be told rather than given something else to aim at.
|
|
299
|
+
const live = this.activeTab(s).handle;
|
|
300
|
+
if (live !== handle) {
|
|
301
|
+
throw new BrowserError('browser: the active tab changed while the page view was being presented, so synthesized input would go to an unshown view — retry, and the new page will be presented instead', 'BROWSER_VIEW_CHANGED');
|
|
3244
302
|
}
|
|
3245
|
-
return
|
|
303
|
+
return handle;
|
|
3246
304
|
}
|
|
3247
305
|
/** Append one operation to the session's history. */
|
|
3248
306
|
record(s, action, params, ok, detail) {
|
|
@@ -3311,24 +369,6 @@ export class ElectronBrowserProvider {
|
|
|
3311
369
|
visited(options = {}) {
|
|
3312
370
|
return this.historyStore?.list(options) ?? [];
|
|
3313
371
|
}
|
|
3314
|
-
/**
|
|
3315
|
-
* Show the synthetic pointer on a view, unless the user switched it off. The
|
|
3316
|
-
* cursor is the "the agent has taken over this tab" signal, so it is painted
|
|
3317
|
-
* for every operation that has a landing point — including DOM-level ones that
|
|
3318
|
-
* move no real pointer.
|
|
3319
|
-
* @param handle - the view to paint into.
|
|
3320
|
-
* @param x - viewport x in CSS pixels.
|
|
3321
|
-
* @param y - viewport y in CSS pixels.
|
|
3322
|
-
* @param action - click pulses a ripple; move only relocates.
|
|
3323
|
-
* @param label - short description of the operation, shown beside the pointer.
|
|
3324
|
-
* @param force - paint even when the pointer is already there (a click ripple must
|
|
3325
|
-
* always play; a bare move need not repeat).
|
|
3326
|
-
*/
|
|
3327
|
-
showCursor(handle, x, y, action, label, force = false) {
|
|
3328
|
-
if (this.settingsSource !== undefined && !this.settingsSource().ui.virtualCursor)
|
|
3329
|
-
return;
|
|
3330
|
-
paintCursor(handle, x, y, action, (target, expression) => handleSendEvaluate(target, expression), label, force);
|
|
3331
|
-
}
|
|
3332
372
|
/**
|
|
3333
373
|
* Replay one recorded operation by sequence number. Navigate/click/type are
|
|
3334
374
|
* re-issued against the current page; execute re-runs its script. The
|
|
@@ -3426,52 +466,6 @@ export class ElectronBrowserProvider {
|
|
|
3426
466
|
}
|
|
3427
467
|
}
|
|
3428
468
|
}
|
|
3429
|
-
/** Look up a session or throw the unknown-session error. */
|
|
3430
|
-
session(session) {
|
|
3431
|
-
const existing = this.sessions.get(session);
|
|
3432
|
-
if (existing === undefined) {
|
|
3433
|
-
throw new BrowserError(`browser: session "${session}" is not open`, 'BROWSER_SESSION_UNKNOWN');
|
|
3434
|
-
}
|
|
3435
|
-
return existing;
|
|
3436
|
-
}
|
|
3437
|
-
/** The active tab of a session. */
|
|
3438
|
-
activeTab(s) {
|
|
3439
|
-
if (this.carrierLaunchError !== undefined)
|
|
3440
|
-
throw this.carrierLaunchError;
|
|
3441
|
-
const tab = s.tabs[s.activeIndex];
|
|
3442
|
-
if (tab === undefined)
|
|
3443
|
-
throw new BrowserError('browser: session has no active tab', 'BROWSER_TAB_UNKNOWN');
|
|
3444
|
-
if (tab.failure !== undefined)
|
|
3445
|
-
throw tab.failure;
|
|
3446
|
-
return tab;
|
|
3447
|
-
}
|
|
3448
|
-
/** Append a fresh tab and make it active. */
|
|
3449
|
-
newTab(s) {
|
|
3450
|
-
const id = tabWireId({ ...resolveSessionHandle(s.id), tab: randomUUID() });
|
|
3451
|
-
const handle = this.host.createView(id);
|
|
3452
|
-
// Same window as the session's other tabs.
|
|
3453
|
-
this.host.groupView?.(handle, s.id, s.label);
|
|
3454
|
-
s.tabs.push({ id, handle, url: '' });
|
|
3455
|
-
s.activeIndex = s.tabs.length - 1;
|
|
3456
|
-
this.showActive(s);
|
|
3457
|
-
}
|
|
3458
|
-
carrierScope(s) {
|
|
3459
|
-
return s.id;
|
|
3460
|
-
}
|
|
3461
|
-
carrierTab(s, id) {
|
|
3462
|
-
const scope = resolveSessionHandle(s.id);
|
|
3463
|
-
return tabWireId(resolveTabHandle(scope, id));
|
|
3464
|
-
}
|
|
3465
|
-
carrierId(s, id) {
|
|
3466
|
-
const tab = resolveTabHandle(resolveSessionHandle(s.id), id).tab;
|
|
3467
|
-
if (!tab.startsWith('page:') && this.host.closePage === undefined)
|
|
3468
|
-
return undefined;
|
|
3469
|
-
return id;
|
|
3470
|
-
}
|
|
3471
|
-
destroyTab(tab, options) {
|
|
3472
|
-
tab.navigationAbort?.abort(new BrowserError('browser: the navigation guest was closed', 'BROWSER_GUEST_CLOSED'));
|
|
3473
|
-
this.host.destroyView(tab.handle, options);
|
|
3474
|
-
}
|
|
3475
469
|
interrupt(handle, timedOut) {
|
|
3476
470
|
if (timedOut)
|
|
3477
471
|
this.quarantine(handle);
|
|
@@ -3487,18 +481,6 @@ export class ElectronBrowserProvider {
|
|
|
3487
481
|
terminatePage(handle);
|
|
3488
482
|
}
|
|
3489
483
|
}
|
|
3490
|
-
/** Find a session's tab by its backing view id (toolbar actions carry view ids). */
|
|
3491
|
-
tabByViewId(s, viewId) {
|
|
3492
|
-
return s.tabs.find(tab => tab.handle.id === viewId);
|
|
3493
|
-
}
|
|
3494
|
-
/**
|
|
3495
|
-
* Whether a session is still live. The human closing a window ends its session
|
|
3496
|
-
* (see {@link handleViewClosed}), so callers that cache ids must ask first.
|
|
3497
|
-
* @param session - the session id to test.
|
|
3498
|
-
*/
|
|
3499
|
-
exists(session) {
|
|
3500
|
-
return this.sessions.has(session);
|
|
3501
|
-
}
|
|
3502
484
|
/**
|
|
3503
485
|
* The sessions a viewer may watch, which is exactly the sessions that exist.
|
|
3504
486
|
*
|
|
@@ -3512,11 +494,15 @@ export class ElectronBrowserProvider {
|
|
|
3512
494
|
return [...this.sessions.keys()];
|
|
3513
495
|
}
|
|
3514
496
|
takeoverTargets(owner) {
|
|
3515
|
-
|
|
497
|
+
const reveal = this.host.revealQuietWindow?.bind(this.host);
|
|
498
|
+
const targets = [...this.sessions.values()].filter(s => (s.label ?? 'default').replace(/^session-/u, '') === owner).flatMap(s => {
|
|
3516
499
|
const tab = s.tabs[s.activeIndex];
|
|
3517
500
|
return tab && !tab.failure && /^https?:\/\//u.test(tab.url)
|
|
3518
|
-
? [{ session: s.id, owner: s.label ?? 'default', tabId: tab.id, pageId: tab.id, url: tab.url
|
|
501
|
+
? [{ session: s.id, owner: s.label ?? 'default', tabId: tab.id, pageId: tab.id, url: tab.url,
|
|
502
|
+
...reveal ? { reveal: (until) => reveal(tab.handle, until === undefined ? undefined : { until }) } : {} }] : [];
|
|
3519
503
|
});
|
|
504
|
+
const own = targets.filter(target => target.session !== this.referenceSession);
|
|
505
|
+
return own.length > 0 ? own : targets;
|
|
3520
506
|
}
|
|
3521
507
|
/**
|
|
3522
508
|
* The human closed a browser window: the session that window showed is over.
|
|
@@ -3580,7 +566,7 @@ export class ElectronBrowserProvider {
|
|
|
3580
566
|
case 'activateTab': {
|
|
3581
567
|
const tab = this.tabByViewId(s, action.viewId);
|
|
3582
568
|
if (tab !== undefined)
|
|
3583
|
-
await this.switchTab(s.id, tab.id);
|
|
569
|
+
await this.switchTab(s.id, tab.id, { user: true });
|
|
3584
570
|
return;
|
|
3585
571
|
}
|
|
3586
572
|
case 'closeTab': {
|
|
@@ -3657,11 +643,11 @@ export class ElectronBrowserProvider {
|
|
|
3657
643
|
* method did nothing at all on carriers without `collapse` (the self-hosted one),
|
|
3658
644
|
* silently desynchronising the two and failing every screenshot.
|
|
3659
645
|
*/
|
|
3660
|
-
showActive(s, select = false) {
|
|
646
|
+
showActive(s, select = false, user = false) {
|
|
3661
647
|
const quiet = this.isQuiet();
|
|
3662
648
|
const active = s.tabs[s.activeIndex];
|
|
3663
649
|
if (active !== undefined)
|
|
3664
|
-
this.host.showView?.(active.handle, s.label, { quiet, ...select ? { select: true } : {} });
|
|
650
|
+
this.host.showView?.(active.handle, s.label, { quiet, ...select ? { select: true } : {}, ...user ? { user: true } : {} });
|
|
3665
651
|
if (quiet || select)
|
|
3666
652
|
return;
|
|
3667
653
|
const autoExpand = this.settingsSource === undefined || this.settingsSource().ui.autoExpandOnce;
|
|
@@ -3670,141 +656,4 @@ export class ElectronBrowserProvider {
|
|
|
3670
656
|
// Best effort: a carrier that owns no presentation (self-hosted) simply has none.
|
|
3671
657
|
void this.host.collapse?.().catch(() => undefined);
|
|
3672
658
|
}
|
|
3673
|
-
/** Read the current URL of a view through CDP. */
|
|
3674
|
-
async currentUrl(handle) {
|
|
3675
|
-
// Bound the read: a wedged renderer would otherwise hang listTabs.
|
|
3676
|
-
const timeoutMs = PROVIDER_TIMEOUTS.lookup;
|
|
3677
|
-
const result = await withTimeout(handleSendEvaluate(handle, 'location.href'), timeoutMs, undefined, `browser: url read timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(handle, timedOut); });
|
|
3678
|
-
return result.ok && typeof result.value === 'string' ? result.value : '';
|
|
3679
|
-
}
|
|
3680
|
-
}
|
|
3681
|
-
/**
|
|
3682
|
-
* Bounds for one passive preview frame.
|
|
3683
|
-
*
|
|
3684
|
-
* The design's numbers (issue #34): viewport only, JPEG quality 70, fit inside 1280x720 without
|
|
3685
|
-
* enlarging, and a 2 s capture ceiling so a stuck frame ends the viewer's wait instead of piling up
|
|
3686
|
-
* behind the control queue. These are deliberately not configurable in v1 — one canonical spec per
|
|
3687
|
-
* target is what lets several viewers share a single capture.
|
|
3688
|
-
*/
|
|
3689
|
-
const PREVIEW_CAPTURE_MS = 2_000;
|
|
3690
|
-
const PREVIEW_QUALITY = 70;
|
|
3691
|
-
const PREVIEW_MAX_WIDTH = 1280;
|
|
3692
|
-
const PREVIEW_MAX_HEIGHT = 720;
|
|
3693
|
-
/** Poll interval for the document-settle loop. */
|
|
3694
|
-
const SETTLE_POLL_MS = 25;
|
|
3695
|
-
/**
|
|
3696
|
-
* Extra time the transport gets over an in-page locate script's own budget: the
|
|
3697
|
-
* script polls for `timeoutMs` and answers only afterwards, so the outer wait
|
|
3698
|
-
* must outlast it or its generic timeout hides the in-page reason.
|
|
3699
|
-
*/
|
|
3700
|
-
const TARGET_SCRIPT_GRACE_MS = 2_000;
|
|
3701
|
-
/** Abortable sleep used by the settle loop. */
|
|
3702
|
-
function delay(ms, signal) {
|
|
3703
|
-
return new Promise((resolve) => {
|
|
3704
|
-
const timer = setTimeout(() => {
|
|
3705
|
-
if (signal !== undefined)
|
|
3706
|
-
signal.removeEventListener('abort', onAbort);
|
|
3707
|
-
resolve();
|
|
3708
|
-
}, ms);
|
|
3709
|
-
const onAbort = () => { clearTimeout(timer); resolve(); };
|
|
3710
|
-
if (signal !== undefined)
|
|
3711
|
-
signal.addEventListener('abort', onAbort, { once: true });
|
|
3712
|
-
});
|
|
3713
|
-
}
|
|
3714
|
-
/**
|
|
3715
|
-
* Bound a promise so a wedged CDP call surfaces as an error instead of
|
|
3716
|
-
* hanging the tool call forever. The caller's signal, when provided, wins
|
|
3717
|
-
* over the timeout if it fires first.
|
|
3718
|
-
* @param promise - the operation to bound.
|
|
3719
|
-
* @param ms - the timeout budget.
|
|
3720
|
-
* @param signal - optional caller signal.
|
|
3721
|
-
* @param message - the timeout error message.
|
|
3722
|
-
* @returns the promise's value, or a rejected promise on timeout/abort.
|
|
3723
|
-
*/
|
|
3724
|
-
function withTimeout(promise, ms, signal, message, onCancel) {
|
|
3725
|
-
return new Promise((resolve, reject) => {
|
|
3726
|
-
let done = false;
|
|
3727
|
-
const timer = setTimeout(() => {
|
|
3728
|
-
if (done)
|
|
3729
|
-
return;
|
|
3730
|
-
done = true;
|
|
3731
|
-
// A fired timeout must also release the abort listener; { once: true }
|
|
3732
|
-
// only releases it on the next abort, which may never come.
|
|
3733
|
-
if (signal !== undefined)
|
|
3734
|
-
signal.removeEventListener('abort', onAbort);
|
|
3735
|
-
const error = new Error(message);
|
|
3736
|
-
error.name = 'TimeoutError';
|
|
3737
|
-
reject(error);
|
|
3738
|
-
// Best-effort interrupt of the underlying CDP call (see onCancel).
|
|
3739
|
-
onCancel?.(true);
|
|
3740
|
-
}, ms);
|
|
3741
|
-
const finish = (fn) => {
|
|
3742
|
-
if (done)
|
|
3743
|
-
return;
|
|
3744
|
-
done = true;
|
|
3745
|
-
clearTimeout(timer);
|
|
3746
|
-
if (signal !== undefined)
|
|
3747
|
-
signal.removeEventListener('abort', onAbort);
|
|
3748
|
-
fn();
|
|
3749
|
-
};
|
|
3750
|
-
const onAbort = () => {
|
|
3751
|
-
if (done)
|
|
3752
|
-
return;
|
|
3753
|
-
done = true;
|
|
3754
|
-
clearTimeout(timer);
|
|
3755
|
-
reject(signal?.reason instanceof Error ? signal.reason : new Error('aborted'));
|
|
3756
|
-
onCancel?.(false);
|
|
3757
|
-
};
|
|
3758
|
-
if (signal !== undefined)
|
|
3759
|
-
signal.addEventListener('abort', onAbort, { once: true });
|
|
3760
|
-
promise.then(value => finish(() => resolve(value)), error => finish(() => reject(error)));
|
|
3761
|
-
});
|
|
3762
|
-
}
|
|
3763
|
-
/**
|
|
3764
|
-
* Best-effort interrupt of a wedged page-script evaluation. `Runtime.evaluate`
|
|
3765
|
-
* with `awaitPromise` can hold the renderer (and the target's debugger queue)
|
|
3766
|
-
* behind a busy loop or a never-settling promise; terminating kills the
|
|
3767
|
-
* running script so subsequent commands are not stuck forever. Fire-and-forget:
|
|
3768
|
-
* if the interrupt itself hangs, it is ignored. Capped at
|
|
3769
|
-
* MAX_PENDING_TERMINATIONS per view to prevent unbounded pending entries
|
|
3770
|
-
* when the child is truly stuck.
|
|
3771
|
-
* @param handle - the view handle to terminate in.
|
|
3772
|
-
*/
|
|
3773
|
-
const pendingTerminations = new WeakMap();
|
|
3774
|
-
const MAX_PENDING_TERMINATIONS = 3;
|
|
3775
|
-
function terminatePage(handle) {
|
|
3776
|
-
const count = pendingTerminations.get(handle) ?? 0;
|
|
3777
|
-
if (count >= MAX_PENDING_TERMINATIONS)
|
|
3778
|
-
return;
|
|
3779
|
-
pendingTerminations.set(handle, count + 1);
|
|
3780
|
-
void handle.sendCommand('Runtime.terminateExecution', undefined, { present: false, initialize: false }).finally(() => {
|
|
3781
|
-
pendingTerminations.set(handle, Math.max(0, (pendingTerminations.get(handle) ?? 1) - 1));
|
|
3782
|
-
}).catch(() => { });
|
|
3783
|
-
}
|
|
3784
|
-
/**
|
|
3785
|
-
* Run a `Runtime.evaluate` through a view handle and normalize the result.
|
|
3786
|
-
* Shared by execute, snapshot, content, and internal URL reads.
|
|
3787
|
-
* @param handle - the view handle to evaluate in.
|
|
3788
|
-
* @param expression - the JS expression.
|
|
3789
|
-
* @param signal - optional abort signal; a fired signal rejects the call.
|
|
3790
|
-
*/
|
|
3791
|
-
/** Viewport point a target script reported, when it reported one. */
|
|
3792
|
-
function scriptPoint(out) {
|
|
3793
|
-
const point = out?.__point;
|
|
3794
|
-
const x = Number(point?.x);
|
|
3795
|
-
const y = Number(point?.y);
|
|
3796
|
-
return Number.isFinite(x) && Number.isFinite(y) ? { x, y } : undefined;
|
|
3797
|
-
}
|
|
3798
|
-
async function handleSendEvaluate(handle, expression, signal, options) {
|
|
3799
|
-
signal?.throwIfAborted();
|
|
3800
|
-
const result = await handle.sendCommand(CDP_RUNTIME_EVALUATE, {
|
|
3801
|
-
expression,
|
|
3802
|
-
returnByValue: true,
|
|
3803
|
-
awaitPromise: true,
|
|
3804
|
-
}, options);
|
|
3805
|
-
if (result.exceptionDetails !== undefined) {
|
|
3806
|
-
const detail = result.exceptionDetails;
|
|
3807
|
-
return { ok: false, exception: detail.exception?.description ?? detail.text ?? 'unknown exception' };
|
|
3808
|
-
}
|
|
3809
|
-
return { ok: true, value: result.result?.value ?? null };
|
|
3810
659
|
}
|