dsh-builtin-browser 1.0.1 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +55 -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/tool-reference.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-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/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 -44
- 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 -36
- package/scripts/build-client.mjs +305 -0
- package/scripts/build.mjs +15 -12
- package/scripts/fix-exports.mjs +6 -16
- package/scripts/install-electron.mjs +55 -5
- package/scripts/pack.mjs +99 -0
- package/scripts/publish-manifest.mjs +56 -0
- package/scripts/verify-exports.mjs +26 -15
- package/skills/dsh-builtin-browser/SKILL.md +27 -2
- package/skills/dsh-builtin-browser/references/batch.md +15 -0
- package/src/browser/anti-bot.ts +251 -0
- package/src/browser/deep-dom.ts +40 -0
- package/src/browser/runtime.ts +18 -0
- package/src/browser/takeover-target.ts +16 -7
- package/src/browser/types.ts +56 -3
- package/src/browser-electron/authenticated-route.ts +29 -4
- package/src/browser-electron/automatic-maintenance.ts +23 -13
- package/src/browser-electron/bridge-connection.ts +11 -10
- package/src/browser-electron/bridge-install.ts +2 -1
- package/src/browser-electron/bridge-status.ts +61 -22
- package/src/browser-electron/desktop-bridge-host.ts +9 -7
- package/src/browser-electron/desktop-identity.ts +38 -5
- package/src/browser-electron/desktop-shell.ts +100 -0
- package/src/browser-electron/electron-provision.ts +104 -18
- package/src/browser-electron/entry.ts +1378 -1299
- package/src/browser-electron/extension-browser.ts +11 -4
- package/src/browser-electron/foreground-watch.ts +142 -0
- package/src/browser-electron/guest-cookie-jar.ts +3 -2
- package/src/browser-electron/guest-route.ts +180 -32
- package/src/browser-electron/guest-runtime.ts +61 -10
- package/src/browser-electron/guest-storage.ts +5 -2
- package/src/browser-electron/history-store.ts +3 -6
- package/src/browser-electron/host-main.ts +8 -4
- package/src/browser-electron/host-patch-maintenance.ts +18 -9
- package/src/browser-electron/maintenance-route.ts +2 -1
- package/src/browser-electron/missing-system-browser.ts +11 -10
- package/src/browser-electron/preferred-browser.ts +13 -3
- package/src/browser-electron/preview-route.ts +9 -12
- package/src/browser-electron/process-ownership.ts +9 -3
- package/src/browser-electron/profile-command.ts +2 -1
- package/src/browser-electron/profile-extension.ts +5 -0
- package/src/browser-electron/profile-lease.ts +131 -35
- package/src/browser-electron/provider-core.ts +1107 -0
- package/src/browser-electron/provider-interaction.ts +1034 -0
- package/src/browser-electron/provider-media.ts +589 -0
- package/src/browser-electron/provider-navigation.ts +323 -0
- package/src/browser-electron/provider-observation.ts +664 -0
- package/src/browser-electron/provider-tabs.ts +372 -0
- package/src/browser-electron/provider.ts +158 -4063
- package/src/browser-electron/reference-route.ts +598 -608
- package/src/browser-electron/remote-host.ts +118 -42
- package/src/browser-electron/runtime-status.ts +80 -13
- package/src/browser-electron/settings-store.ts +10 -6
- package/src/browser-electron/sidebar-only-host.ts +4 -2
- package/src/browser-electron/system-browser.ts +537 -184
- package/src/browser-electron/tauri-host.ts +194 -0
- package/src/browser-electron/virtual-cursor.ts +24 -14
- package/src/browser-reference/service.ts +38 -7
- package/src/browser-reference/web-sources.ts +4 -1
- package/src/client/apply-guard.ts +22 -0
- package/src/client/browser/BrowserController.ts +3 -3
- package/src/client/browser/IframeImpl.ts +182 -176
- package/src/client/browser/frame-history.ts +125 -0
- package/src/client/browser/frame-state.ts +27 -0
- package/src/client/browser/web-reference-source.ts +5 -1
- package/src/client/definition.tsx +36 -30
- package/src/client/electron/ElectronWebViewImpl.ts +20 -13
- package/src/client/electron/ElectronWebviewPresentation.ts +4 -2
- package/src/client/electron/NativeChildPresentation.ts +11 -3
- package/src/client/electron/NativeViewPage.ts +19 -5
- package/src/client/index.ts +333 -293
- package/src/client/locales.ts +9 -6
- package/src/client/reference/client/plugin.ts +21 -2
- package/src/client/reference/client/production/ReferenceCapsules.tsx +3 -3
- package/src/client/reference/client/production/assembly.ts +4 -28
- package/src/client/reference/client/production/availability.ts +0 -2
- package/src/client/reference/client/production/composer-attachments.ts +44 -0
- package/src/client/reference/client/production/draft-adapter.ts +4 -0
- package/src/client/reference/client/production/http-transport.ts +0 -5
- package/src/client/reference/client/production/production-submission.ts +50 -290
- package/src/client/reference/client/production/protocol.ts +7 -4
- package/src/client/reference/client/production/runtime.ts +41 -86
- package/src/client/reference/client/production/source-marker.ts +49 -13
- package/src/client/reference/client/production/user-text-rule.ts +10 -1
- package/src/client/reference/client/reveal.ts +3 -1
- package/src/client/reference/client/session-schedule.ts +36 -0
- package/src/client/settings/index.ts +8 -0
- package/src/client/settings/mount-guard.ts +31 -0
- package/src/client/settings/panel.ts +163 -52
- package/src/client/startpage/controller.ts +3 -6
- package/src/client/view/BrowserBody.tsx +2 -1
- package/src/client/view/IframePresentation.ts +37 -16
- package/src/client/view/StartPage.tsx +2 -1
- package/src/compat/host-features.ts +92 -0
- package/src/reference-source.ts +1 -1
- package/src/reference-text.ts +23 -1
- package/src/takeover-protocol.ts +11 -2
- package/src/tool-browser/block-recovery.ts +85 -0
- package/src/tool-browser/code-tool.ts +173 -19
- package/src/tool-browser/code-worker.ts +101 -15
- package/src/tool-browser/errors.ts +40 -0
- package/src/tool-browser/index.ts +66 -3534
- package/src/tool-browser/page-probe.ts +229 -28
- package/src/tool-browser/panel-page.ts +3 -1
- package/src/tool-browser/probe-client.ts +183 -0
- package/src/tool-browser/screenshot-annotations.ts +131 -0
- package/src/tool-browser/state.ts +375 -0
- package/src/tool-browser/takeover.ts +3 -2
- package/src/tool-browser/tools-debug.ts +806 -0
- package/src/tool-browser/tools-interaction.ts +956 -0
- package/src/tool-browser/tools-navigation.ts +786 -0
- package/src/tool-browser/tools-observation.ts +474 -0
- package/src/tool-browser/tools-reference.ts +294 -0
- package/src/web-guest.ts +35 -34
- package/dist/client.cjs +0 -43167
- package/dist/client.d.cts +0 -516
- package/dist/client.d.mts +0 -516
- package/dist/index.cjs +0 -92
- package/dist/index.d.mts +0 -2960
- package/dist/index.mjs +0 -24
- package/lib/browser-reference/submission-receipts.js +0 -139
- package/src/browser-reference/submission-receipts.ts +0 -122
|
@@ -0,0 +1,963 @@
|
|
|
1
|
+
import { DEFAULT_OPERATION_TIMEOUT_MS } from '../../assets/browser-policy.mjs';
|
|
2
|
+
import { pageOperationScript } from '../tool-browser/page-probe.js';
|
|
3
|
+
import { DEEP_DOM_SOURCE } from '../browser/deep-dom.js';
|
|
4
|
+
import { paintCursor } from './virtual-cursor.js';
|
|
5
|
+
import { BrowserError } from '../browser/types.js';
|
|
6
|
+
import { PROVIDER_TIMEOUTS, KEY_SPECS, BROWSER_KEY_NAMES, TARGET_SCRIPT_GRACE_MS, pagePollSlice, withTimeout, scriptPoint, handleSendEvaluate } from './provider-core.js';
|
|
7
|
+
import { ProviderObservation } from './provider-observation.js';
|
|
8
|
+
const FOCUSED_EDITABLE_SCRIPT = `(() => {
|
|
9
|
+
const NON_TEXT_INPUTS = ['button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit']
|
|
10
|
+
let doc = document
|
|
11
|
+
let el = doc.activeElement
|
|
12
|
+
for (;;) {
|
|
13
|
+
if (el && el.shadowRoot && el.shadowRoot.activeElement) { el = el.shadowRoot.activeElement; continue }
|
|
14
|
+
if (el && (el.tagName === 'IFRAME' || el.tagName === 'FRAME')) {
|
|
15
|
+
let inner = null
|
|
16
|
+
try { inner = el.contentDocument } catch {}
|
|
17
|
+
if (!inner) return { editable: true, active: el.tagName }
|
|
18
|
+
doc = inner
|
|
19
|
+
el = inner.activeElement
|
|
20
|
+
continue
|
|
21
|
+
}
|
|
22
|
+
break
|
|
23
|
+
}
|
|
24
|
+
const active = el ? el.tagName : 'nothing'
|
|
25
|
+
if (doc.designMode === 'on' || (el && el.isContentEditable)) return { editable: true, active }
|
|
26
|
+
if (el && el.tagName === 'TEXTAREA') return { editable: !el.readOnly && !el.disabled, active }
|
|
27
|
+
if (el && el.tagName === 'INPUT') return { editable: !el.readOnly && !el.disabled && !NON_TEXT_INPUTS.includes(String(el.type || '').toLowerCase()), active }
|
|
28
|
+
if (el && el.tagName.includes('-') && !el.shadowRoot) return { editable: true, active }
|
|
29
|
+
return { editable: false, active }
|
|
30
|
+
})()`;
|
|
31
|
+
export class ProviderInteraction extends ProviderObservation {
|
|
32
|
+
/** Run a fixed browser operation; the request cannot contain a script. */
|
|
33
|
+
async pageOperation(session, request, signal) {
|
|
34
|
+
const script = pageOperationScript(request);
|
|
35
|
+
if (request.operation === 'drag') {
|
|
36
|
+
return this.dispatchPointer(session, request.from, request.to, request.steps, signal);
|
|
37
|
+
}
|
|
38
|
+
if (request.operation === 'probe' && request.method === 'hoverAt') {
|
|
39
|
+
const point = { x: Number(request.args?.[0]), y: Number(request.args?.[1]) };
|
|
40
|
+
return this.dispatchPointer(session, point, undefined, 1, signal);
|
|
41
|
+
}
|
|
42
|
+
return this.evaluatePage(session, { script }, signal);
|
|
43
|
+
}
|
|
44
|
+
/** Send page pointer input through CDP while preserving presentation and cancellation policy. */
|
|
45
|
+
async dispatchPointer(session, from, to, steps, signal) {
|
|
46
|
+
const coordinates = [from.x, from.y, ...to === undefined ? [] : [to.x, to.y]];
|
|
47
|
+
if (coordinates.some(value => !Number.isFinite(value) || value < 0)) {
|
|
48
|
+
throw new BrowserError('browser: pointer coordinates must be finite nonnegative viewport pixels', 'BROWSER_POINTER_INVALID');
|
|
49
|
+
}
|
|
50
|
+
if (to !== undefined && this.settingsSource?.().vision.strategy === 'nonVisual') {
|
|
51
|
+
throw new BrowserError('browser: coordinate dragging requires the visual strategy', 'BROWSER_NON_VISUAL_COORDINATES');
|
|
52
|
+
}
|
|
53
|
+
const s = this.session(session);
|
|
54
|
+
const handle = await this.present(s, signal);
|
|
55
|
+
const viewport = await withTimeout(handleSendEvaluate(handle, '({width:innerWidth,height:innerHeight})'), PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer viewport check timed out');
|
|
56
|
+
if (!viewport.ok)
|
|
57
|
+
throw new BrowserError('browser: could not read the pointer viewport', 'BROWSER_POINTER_INVALID');
|
|
58
|
+
const size = viewport.value;
|
|
59
|
+
if (from.x >= size.width || from.y >= size.height || (to !== undefined && (to.x >= size.width || to.y >= size.height))) {
|
|
60
|
+
return { ok: true, value: JSON.stringify(to === undefined ? false : { ok: false, reason: 'drag points must be inside the current viewport' }) };
|
|
61
|
+
}
|
|
62
|
+
const send = async (params) => {
|
|
63
|
+
signal?.throwIfAborted();
|
|
64
|
+
this.assertSameView(session, handle, this.activeTab(s).handle);
|
|
65
|
+
await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer input timed out');
|
|
66
|
+
};
|
|
67
|
+
await send({ type: 'mouseMoved', x: from.x, y: from.y, buttons: 0 });
|
|
68
|
+
if (to === undefined)
|
|
69
|
+
return { ok: true, value: 'true' };
|
|
70
|
+
let at = from;
|
|
71
|
+
let held = true;
|
|
72
|
+
try {
|
|
73
|
+
await send({ type: 'mousePressed', x: from.x, y: from.y, button: 'left', buttons: 1, clickCount: 1 });
|
|
74
|
+
const count = Math.max(1, Math.min(Math.trunc(steps) || 12, 60));
|
|
75
|
+
for (let step = 1; step <= count; step += 1) {
|
|
76
|
+
const next = { x: from.x + (to.x - from.x) * step / count, y: from.y + (to.y - from.y) * step / count };
|
|
77
|
+
await send({ type: 'mouseMoved', ...next, button: 'left', buttons: 1 });
|
|
78
|
+
at = next;
|
|
79
|
+
}
|
|
80
|
+
// Native HTML drag targets need a final drag-over before releasing at the destination.
|
|
81
|
+
await send({ type: 'mouseMoved', ...to, button: 'left', buttons: 1 });
|
|
82
|
+
await send({ type: 'mouseReleased', ...to, button: 'left', buttons: 0, clickCount: 1 });
|
|
83
|
+
held = false;
|
|
84
|
+
return { ok: true, value: JSON.stringify({ ok: true, moved: count, at: to }) };
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
if (held) {
|
|
88
|
+
await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, button: 'left', buttons: 0, clickCount: 1 }), 1_000, undefined, 'browser: pointer release timed out').catch(() => { });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Click at viewport coordinates, or at a located element's center when a
|
|
94
|
+
* `target` (css/text/xpath) is given. CDP mousePressed + mouseReleased.
|
|
95
|
+
*/
|
|
96
|
+
async click(session, request, signal) {
|
|
97
|
+
const s = this.session(session);
|
|
98
|
+
// The view the locate runs against. It can stop being the session's active view while
|
|
99
|
+
// the locate waits (see prepareTarget), so every dispatch below re-reads the live one.
|
|
100
|
+
const locateHandle = this.activeTab(s).handle;
|
|
101
|
+
signal?.throwIfAborted();
|
|
102
|
+
let x = 0;
|
|
103
|
+
let y = 0;
|
|
104
|
+
if ('target' in request) {
|
|
105
|
+
// Semantic targeting (②): locate the element in-page, scroll it into
|
|
106
|
+
// view, wait for the compositor to commit any scroll offset so CDP
|
|
107
|
+
// hit-testing matches the scrolled layout, and return top-viewport center.
|
|
108
|
+
const locateMs = PROVIDER_TIMEOUTS.lookup;
|
|
109
|
+
const body = `
|
|
110
|
+
const absRect = node => {
|
|
111
|
+
const r = node.getBoundingClientRect()
|
|
112
|
+
let ax = r.x, ay = r.y
|
|
113
|
+
let d = node.ownerDocument
|
|
114
|
+
while (d && d.defaultView && d.defaultView.frameElement) {
|
|
115
|
+
const fr = d.defaultView.frameElement.getBoundingClientRect()
|
|
116
|
+
ax += fr.x; ay += fr.y
|
|
117
|
+
d = d.defaultView.frameElement.ownerDocument
|
|
118
|
+
}
|
|
119
|
+
return { x: ax, y: ay, width: r.width, height: r.height }
|
|
120
|
+
}
|
|
121
|
+
const before = absRect(el)
|
|
122
|
+
el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'center' })
|
|
123
|
+
const moved = absRect(el)
|
|
124
|
+
const needsFrame = Math.abs(moved.x - before.x) > 0.5 || Math.abs(moved.y - before.y) > 0.5
|
|
125
|
+
|| before.y < 0 || before.y + before.height > innerHeight
|
|
126
|
+
|| before.x < 0 || before.x + before.width > innerWidth
|
|
127
|
+
if (needsFrame) {
|
|
128
|
+
const nextFrame = () => new Promise(resolve => {
|
|
129
|
+
if (typeof requestAnimationFrame !== 'function') { setTimeout(resolve, 16); return }
|
|
130
|
+
let done = false
|
|
131
|
+
const finish = () => { if (!done) { done = true; resolve() } }
|
|
132
|
+
const timer = setTimeout(finish, 50)
|
|
133
|
+
requestAnimationFrame(() => { clearTimeout(timer); finish() })
|
|
134
|
+
})
|
|
135
|
+
await nextFrame()
|
|
136
|
+
await nextFrame()
|
|
137
|
+
}
|
|
138
|
+
const r = absRect(el)
|
|
139
|
+
return { ok: true, x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }
|
|
140
|
+
`;
|
|
141
|
+
const script = this.buildTargetScript(request.target, locateMs, body);
|
|
142
|
+
const out = await this.runTargetScript(this.activeTab(s), script, locateMs, signal, 'BROWSER_CLICK_FAILED', 'browser: click');
|
|
143
|
+
x = Number(out.x);
|
|
144
|
+
y = Number(out.y);
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
// A coordinate only exists because somebody read a picture. Under the
|
|
148
|
+
// non-visual strategy the plugin must not accept one: a model that cannot
|
|
149
|
+
// see cannot have produced it, so the coordinates are either copied from an
|
|
150
|
+
// earlier vision pass or invented, and honouring them turns a silent
|
|
151
|
+
// mis-click into a mystery. Refusing here, with a message that says what to
|
|
152
|
+
// do instead, converts that into a usable instruction.
|
|
153
|
+
if (this.settingsSource !== undefined && this.settingsSource().vision.strategy === 'nonVisual') {
|
|
154
|
+
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');
|
|
155
|
+
}
|
|
156
|
+
x = request.x;
|
|
157
|
+
y = request.y;
|
|
158
|
+
}
|
|
159
|
+
// Input.* is only delivered to a view with a current display surface; the
|
|
160
|
+
// barrier also re-presents after a navigation replaced the renderer. It returns the
|
|
161
|
+
// handle that may still be receiving input when it settles.
|
|
162
|
+
const handle = await this.present(s, signal);
|
|
163
|
+
// The locate (up to 10s) and the present barrier both ran against the view captured
|
|
164
|
+
// earlier; if the human switched tabs meanwhile, these coordinates belong to one page
|
|
165
|
+
// and the dispatch would go to another — and Chromium answers success either way.
|
|
166
|
+
if ('target' in request)
|
|
167
|
+
this.assertSameView(session, locateHandle, handle);
|
|
168
|
+
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
169
|
+
const send = (params, label) => withTimeout(handle.sendCommand('Input.dispatchMouseEvent', params), timeoutMs, signal, `browser: click ${label} timed out after ${timeoutMs}ms`);
|
|
170
|
+
// Paint the synthetic pointer before dispatching the mouse sequence so the
|
|
171
|
+
// overlay evaluation never interleaves between mouseMoved, mousePressed, and
|
|
172
|
+
// mouseReleased or races a form-submit navigation triggered by the click.
|
|
173
|
+
await this.showCursorSettled(handle, x, y, 'click', 'click', true);
|
|
174
|
+
// Chromium routes a synthesized `mousePressed` to the widget's *current*
|
|
175
|
+
// hover target rather than hit-testing the coordinates, and a real pointer
|
|
176
|
+
// click is always preceded by movement. A view that has never received a
|
|
177
|
+
// mouse event has no hover target yet, so the press of the FIRST click on a
|
|
178
|
+
// fresh tab went nowhere while CDP still answered success; the second click
|
|
179
|
+
// landed because the first had quietly established the target. Move the
|
|
180
|
+
// pointer first so a click is self-contained.
|
|
181
|
+
try {
|
|
182
|
+
await send({ type: 'mouseMoved', x, y, buttons: 0 }, 'move');
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error });
|
|
186
|
+
}
|
|
187
|
+
const release = () => {
|
|
188
|
+
// Back to the handle the PRESS may have landed on, deliberately not to the currently
|
|
189
|
+
// active tab: this only runs after a failed press/release, and re-targeting a
|
|
190
|
+
// compensating half of a click to a view the human just switched to would press a
|
|
191
|
+
// button there. Best-effort either way.
|
|
192
|
+
void handle
|
|
193
|
+
.sendCommand('Input.dispatchMouseEvent', {
|
|
194
|
+
type: 'mouseReleased',
|
|
195
|
+
x,
|
|
196
|
+
y,
|
|
197
|
+
button: 'left',
|
|
198
|
+
buttons: 0,
|
|
199
|
+
clickCount: 1,
|
|
200
|
+
})
|
|
201
|
+
.catch(() => { });
|
|
202
|
+
};
|
|
203
|
+
try {
|
|
204
|
+
await send({ type: 'mousePressed', x, y, button: 'left', buttons: 1, clickCount: 1 }, 'press');
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
// The press may still land late; release best-effort so the button is
|
|
208
|
+
// never left in a stuck pressed state.
|
|
209
|
+
release();
|
|
210
|
+
throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error });
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
await send({ type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 }, 'release');
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
// The press already landed; retry the release so the button is not
|
|
217
|
+
// left pressed before surfacing the failure.
|
|
218
|
+
release();
|
|
219
|
+
throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error });
|
|
220
|
+
}
|
|
221
|
+
this.record(s, 'click', 'target' in request ? { target: request.target } : { x, y }, true);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Click many points in order, once.
|
|
225
|
+
*
|
|
226
|
+
* The same wire sequence as {@link click}, looped — only the round-trip count changes. Presenting
|
|
227
|
+
* happens ONCE: the display-surface barrier is per view, not per press, and paying it for every
|
|
228
|
+
* point is what made an 86-cell board expensive.
|
|
229
|
+
*
|
|
230
|
+
* Stops at the first point that fails and reports where: a run that pressed through a page which
|
|
231
|
+
* had navigated or lost its surface would fill the wrong cells and still answer success.
|
|
232
|
+
* @param session - the session to click in.
|
|
233
|
+
* @param request - the points and the interval between them.
|
|
234
|
+
* @param signal - cancellation between points.
|
|
235
|
+
* @returns how many points landed, and where it stopped if it did not finish.
|
|
236
|
+
*/
|
|
237
|
+
async clickSequence(session, request, signal) {
|
|
238
|
+
const s = this.session(session);
|
|
239
|
+
const points = Array.isArray(request.points) ? request.points : [];
|
|
240
|
+
if (points.length === 0)
|
|
241
|
+
return { clicked: 0 };
|
|
242
|
+
if (this.settingsSource !== undefined && this.settingsSource().vision.strategy === 'nonVisual') {
|
|
243
|
+
throw new BrowserError('browser: the configured non-visual strategy refuses coordinate clicks — pass a semantic target instead.', 'BROWSER_NON_VISUAL_COORDINATES');
|
|
244
|
+
}
|
|
245
|
+
// One barrier for the whole run: cheap, and it is the view that needs a surface, not each press.
|
|
246
|
+
const handle = await this.present(s, signal);
|
|
247
|
+
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
248
|
+
// 40 ms is above one frame at 30 fps, which is what keeps the page from reading two presses as a
|
|
249
|
+
// double click. Faster runs were measured dropping presses outright.
|
|
250
|
+
const gap = typeof request.intervalMs === 'number' && request.intervalMs >= 0 ? request.intervalMs : 40;
|
|
251
|
+
const send = (params, label) => withTimeout(handle.sendCommand('Input.dispatchMouseEvent', params), timeoutMs, signal, `browser: click sequence ${label} timed out after ${timeoutMs}ms`);
|
|
252
|
+
let clicked = 0;
|
|
253
|
+
for (const [index, point] of points.entries()) {
|
|
254
|
+
signal?.throwIfAborted();
|
|
255
|
+
const x = Number(point?.x);
|
|
256
|
+
const y = Number(point?.y);
|
|
257
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) {
|
|
258
|
+
return { clicked, failedAt: index, error: `point ${index} has no finite x/y` };
|
|
259
|
+
}
|
|
260
|
+
try {
|
|
261
|
+
// The move is load-bearing: Chromium routes a synthesized press to the CURRENT hover target,
|
|
262
|
+
// and a view that has never received a mouse event has none — the first press would go nowhere
|
|
263
|
+
// while CDP still answered success.
|
|
264
|
+
await send({ type: 'mouseMoved', x, y, buttons: 0 }, 'move');
|
|
265
|
+
await send({ type: 'mousePressed', x, y, button: 'left', buttons: 1, clickCount: 1 }, 'press');
|
|
266
|
+
await send({ type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 }, 'release');
|
|
267
|
+
clicked += 1;
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
// Best-effort release so a failed press cannot leave the button stuck down.
|
|
271
|
+
void handle
|
|
272
|
+
.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 })
|
|
273
|
+
.catch(() => { });
|
|
274
|
+
return { clicked, failedAt: index, error: String(error instanceof Error ? error.message : error) };
|
|
275
|
+
}
|
|
276
|
+
if (index < points.length - 1 && gap > 0)
|
|
277
|
+
await new Promise(resolve => setTimeout(resolve, gap));
|
|
278
|
+
}
|
|
279
|
+
return { clicked };
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Type into the focused element, or focus a located element (css/text/xpath)
|
|
283
|
+
* first and then insert the text.
|
|
284
|
+
*/
|
|
285
|
+
async type(session, request, signal) {
|
|
286
|
+
const s = this.session(session);
|
|
287
|
+
// The view the locate runs against. It can stop being the session's active view while
|
|
288
|
+
// the locate waits (the human is invited to drive the same window), so the input below
|
|
289
|
+
// goes to the handle `present` reports instead of this one.
|
|
290
|
+
const locateHandle = this.activeTab(s).handle;
|
|
291
|
+
signal?.throwIfAborted();
|
|
292
|
+
const hasTarget = 'target' in request;
|
|
293
|
+
if (hasTarget) {
|
|
294
|
+
const locateMs = PROVIDER_TIMEOUTS.lookup;
|
|
295
|
+
const script = this.buildTargetScript(request.target, locateMs, `
|
|
296
|
+
el.focus()
|
|
297
|
+
return { ok: true }
|
|
298
|
+
`);
|
|
299
|
+
const locateTab = this.activeTab(s);
|
|
300
|
+
const out = await this.runTargetScript(locateTab, script, locateMs, signal, 'BROWSER_TYPE_FAILED', 'browser: type');
|
|
301
|
+
const cursorPoint = scriptPoint(out);
|
|
302
|
+
if (cursorPoint !== undefined)
|
|
303
|
+
this.showCursor(locateTab.handle, cursorPoint.x, cursorPoint.y, 'click', 'type', true);
|
|
304
|
+
}
|
|
305
|
+
const text = 'text' in request ? request.text : '';
|
|
306
|
+
const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
|
|
307
|
+
// Input.insertText goes through the Input domain: same display-surface
|
|
308
|
+
// requirement as click/key. It also reports which view is active once the barrier has
|
|
309
|
+
// settled, which is what makes the tab-switch check below meaningful.
|
|
310
|
+
const handle = await this.present(s, signal);
|
|
311
|
+
// Focusing one page and inserting into another is exactly the silent mis-target this
|
|
312
|
+
// refuses: the element was focused in the located view, and the text would have gone to
|
|
313
|
+
// whichever page is now visible — possibly a password field there.
|
|
314
|
+
if (hasTarget)
|
|
315
|
+
this.assertSameView(session, locateHandle, handle);
|
|
316
|
+
// Electron guests (DSH Desktop and Tauri sidebar) crash their renderer when text is inserted
|
|
317
|
+
// with no editable element focused, and nothing would have been typed in any browser.
|
|
318
|
+
const focus = await withTimeout(handleSendEvaluate(handle, FOCUSED_EDITABLE_SCRIPT, signal), PROVIDER_TIMEOUTS.lookup, signal, `browser: type focus check timed out after ${PROVIDER_TIMEOUTS.lookup}ms`);
|
|
319
|
+
if (!focus.ok)
|
|
320
|
+
throw new BrowserError(`browser: type failed: ${focus.exception}`, 'BROWSER_TYPE_FAILED');
|
|
321
|
+
const focused = focus.value;
|
|
322
|
+
if (focused?.editable !== true) {
|
|
323
|
+
const active = typeof focused?.active === 'string' ? `focus is on ${focused.active}` : 'nothing has focus';
|
|
324
|
+
throw new BrowserError(`browser: type needs a focused text field, and ${active}; pass a target, or tap the field first`, 'BROWSER_TYPE_NO_FOCUS');
|
|
325
|
+
}
|
|
326
|
+
try {
|
|
327
|
+
await withTimeout(handle.sendCommand('Input.insertText', { text }), timeoutMs, signal, `browser: type timed out after ${timeoutMs}ms`);
|
|
328
|
+
}
|
|
329
|
+
catch (error) {
|
|
330
|
+
throw new BrowserError(`browser: type failed: ${String(error)}`, 'BROWSER_TYPE_FAILED', { cause: error });
|
|
331
|
+
}
|
|
332
|
+
// Store the full text so replay re-issues the same input; the history
|
|
333
|
+
// tool truncates long values when rendering.
|
|
334
|
+
this.record(s, 'type', { text, ...hasTarget ? { target: request.target } : {} }, true);
|
|
335
|
+
}
|
|
336
|
+
/** Scroll the page: by deltas, to a selector, or to top/bottom. */
|
|
337
|
+
async scroll(session, request, signal) {
|
|
338
|
+
const s = this.session(session);
|
|
339
|
+
const tab = this.activeTab(s);
|
|
340
|
+
signal?.throwIfAborted();
|
|
341
|
+
const selector = request.selector ?? '';
|
|
342
|
+
const script = `(() => {${DEEP_DOM_SOURCE}
|
|
343
|
+
const sel = ${JSON.stringify(selector)}
|
|
344
|
+
if (sel !== '') {
|
|
345
|
+
const el = __dshQuery(sel)
|
|
346
|
+
if (!el) return { ok: false, reason: 'selector not found' }
|
|
347
|
+
el.scrollIntoView({ behavior: 'instant', block: 'center' })
|
|
348
|
+
return { ok: true }
|
|
349
|
+
}
|
|
350
|
+
if (${request.toTop === true}) { window.scrollTo(0, 0); return { ok: true } }
|
|
351
|
+
if (${request.toBottom === true}) { window.scrollTo(0, document.body.scrollHeight); return { ok: true } }
|
|
352
|
+
window.scrollBy({ top: ${request.deltaY ?? 0}, left: ${request.deltaX ?? 0} })
|
|
353
|
+
return { ok: true }
|
|
354
|
+
})()`;
|
|
355
|
+
const timeoutMs = PROVIDER_TIMEOUTS.action;
|
|
356
|
+
const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: scroll timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
357
|
+
if (!result.ok)
|
|
358
|
+
throw new BrowserError(`browser: scroll failed: ${result.exception}`, 'BROWSER_SCROLL_FAILED');
|
|
359
|
+
const value = result.value;
|
|
360
|
+
if (value.ok !== true)
|
|
361
|
+
throw new BrowserError(`browser: scroll failed: ${value.reason ?? 'unknown'}`, 'BROWSER_SCROLL_FAILED');
|
|
362
|
+
this.record(s, 'scroll', { ...request }, true);
|
|
363
|
+
}
|
|
364
|
+
/** Press one named key (Enter/Tab/arrows/…) via CDP key events. */
|
|
365
|
+
async key(session, request, signal) {
|
|
366
|
+
const s = this.session(session);
|
|
367
|
+
signal?.throwIfAborted();
|
|
368
|
+
const spec = KEY_SPECS[request.key];
|
|
369
|
+
if (spec === undefined) {
|
|
370
|
+
throw new BrowserError(`browser: unsupported key "${request.key}" (supported: ${BROWSER_KEY_NAMES.join(', ')})`, 'BROWSER_KEY_UNSUPPORTED');
|
|
371
|
+
}
|
|
372
|
+
const params = { key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.vk, nativeVirtualKeyCode: spec.vk, ...spec.text !== undefined ? { text: spec.text } : {} };
|
|
373
|
+
const timeoutMs = PROVIDER_TIMEOUTS.action;
|
|
374
|
+
// Input.dispatchKeyEvent is subject to the same display-surface rule. The handle comes
|
|
375
|
+
// back from the presentation barrier rather than from a capture taken before it: this
|
|
376
|
+
// session is shared with the human, who may switch tabs while the barrier round-trips,
|
|
377
|
+
// and a key sent to the view they left is silently dropped (or lands on the new page).
|
|
378
|
+
const handle = await this.present(s, signal);
|
|
379
|
+
// Focus the SAME view the key is dispatched to; focusing the pre-switch handle would
|
|
380
|
+
// grant web focus to a page that then receives nothing.
|
|
381
|
+
await this.focusView(handle);
|
|
382
|
+
const release = () => handle.sendCommand('Input.dispatchKeyEvent', { type: 'keyUp', ...params });
|
|
383
|
+
try {
|
|
384
|
+
await withTimeout(handle.sendCommand('Input.dispatchKeyEvent', { type: 'keyDown', ...params }), timeoutMs, signal, `browser: key press timed out after ${timeoutMs}ms`);
|
|
385
|
+
}
|
|
386
|
+
catch (error) {
|
|
387
|
+
// The press may still land late; release best-effort so the key is
|
|
388
|
+
// never left in a stuck pressed state.
|
|
389
|
+
void release().catch(() => { });
|
|
390
|
+
throw new BrowserError(`browser: key "${request.key}" failed: ${String(error)}`, 'BROWSER_KEY_FAILED', { cause: error });
|
|
391
|
+
}
|
|
392
|
+
try {
|
|
393
|
+
await withTimeout(release(), timeoutMs, signal, `browser: key release timed out after ${timeoutMs}ms`);
|
|
394
|
+
}
|
|
395
|
+
catch (error) {
|
|
396
|
+
// The press already landed; retry the release before surfacing.
|
|
397
|
+
void release().catch(() => { });
|
|
398
|
+
throw new BrowserError(`browser: key "${request.key}" failed: ${String(error)}`, 'BROWSER_KEY_FAILED', { cause: error });
|
|
399
|
+
}
|
|
400
|
+
this.record(s, 'key', { key: request.key }, true);
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Fill a form's fields in one batch. Runs one page-context script that
|
|
404
|
+
* resolves each field (selector, or name/label/placeholder among visible
|
|
405
|
+
* controls), sets its value with the native prototype setter (React/Vue
|
|
406
|
+
* controlled inputs included) plus input/change events, handles
|
|
407
|
+
* select/checkbox/radio/contenteditable, and optionally submits the form.
|
|
408
|
+
*/
|
|
409
|
+
async fillForm(session, request, signal) {
|
|
410
|
+
const s = this.session(session);
|
|
411
|
+
const tab = this.activeTab(s);
|
|
412
|
+
signal?.throwIfAborted();
|
|
413
|
+
const specs = JSON.stringify(request.fields.map(f => ({
|
|
414
|
+
selector: f.selector ?? null,
|
|
415
|
+
name: f.name ?? null,
|
|
416
|
+
label: f.label ?? null,
|
|
417
|
+
placeholder: f.placeholder ?? null,
|
|
418
|
+
// A field with NO kind is a field with no kind FILTER: absent, not 'text'. Defaulting
|
|
419
|
+
// it to 'text' here made `if (spec.kind)` above always true, so every unspecified
|
|
420
|
+
// field was narrowed to an <input> — dsh_browser_fill on a <textarea> reported
|
|
421
|
+
// `no "text" control matched`, and a contenteditable could not match any kind at all.
|
|
422
|
+
// The value stays a string or null (never undefined): the in-page check tests truthiness,
|
|
423
|
+
// and JSON drops an undefined member entirely, which is the same thing here.
|
|
424
|
+
kind: f.kind ?? null,
|
|
425
|
+
value: f.value,
|
|
426
|
+
})));
|
|
427
|
+
const submitFlag = request.submit === true;
|
|
428
|
+
const script = `(() => {
|
|
429
|
+
const specs = ${specs}
|
|
430
|
+
const out = []
|
|
431
|
+
const setNative = (el, proto, value) => {
|
|
432
|
+
const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
|
|
433
|
+
if (setter) setter.call(el, value)
|
|
434
|
+
else el.value = value
|
|
435
|
+
}
|
|
436
|
+
const visible = (el) => {
|
|
437
|
+
const r = el.getBoundingClientRect()
|
|
438
|
+
const cs = getComputedStyle(el)
|
|
439
|
+
return r.width >= 4 && r.height >= 4 && cs.visibility !== 'hidden' && cs.display !== 'none'
|
|
440
|
+
}
|
|
441
|
+
const describe = (spec) => spec.selector || spec.name || spec.label || spec.placeholder || '(unspecified)'
|
|
442
|
+
const matches = (el, spec) => {
|
|
443
|
+
if (spec.selector) { try { return el.matches(spec.selector) } catch { return false } }
|
|
444
|
+
if (spec.name && el.name === spec.name) return true
|
|
445
|
+
if (spec.placeholder && el.placeholder === spec.placeholder) return true
|
|
446
|
+
if (spec.label) {
|
|
447
|
+
if (el.getAttribute('aria-label') === spec.label) return true
|
|
448
|
+
if (el.id) {
|
|
449
|
+
const lbl = (el.getRootNode().querySelector ? el.getRootNode() : document).querySelector('label[for=' + JSON.stringify(el.id) + ']')
|
|
450
|
+
if (lbl && (lbl.textContent || '').trim() === spec.label) return true
|
|
451
|
+
}
|
|
452
|
+
const wrap = el.closest('label')
|
|
453
|
+
if (wrap && (wrap.textContent || '').trim() === spec.label) return true
|
|
454
|
+
}
|
|
455
|
+
return false
|
|
456
|
+
}
|
|
457
|
+
// Every root this page exposes: the top document plus its shadow trees (recursively)
|
|
458
|
+
// and same-origin iframes. The snapshot and waitFor already walk all of them, so an
|
|
459
|
+
// element inside one is shown to the model and can be waited for — resolving a click or
|
|
460
|
+
// a fill used to look at the top document alone and answer "not found" for something
|
|
461
|
+
// the model had just been handed a reference to. The two must agree about what exists.
|
|
462
|
+
// (Kept in step with the collector in the snapshot script above.)
|
|
463
|
+
const allRoots = () => {
|
|
464
|
+
const roots = []
|
|
465
|
+
const seen = new Set()
|
|
466
|
+
const visit = doc => {
|
|
467
|
+
if (seen.has(doc)) return
|
|
468
|
+
seen.add(doc)
|
|
469
|
+
roots.push(doc)
|
|
470
|
+
for (const el of doc.querySelectorAll('*')) {
|
|
471
|
+
if (el.shadowRoot) visit(el.shadowRoot)
|
|
472
|
+
if (el.tagName === 'IFRAME') {
|
|
473
|
+
try { const d = el.contentDocument; if (d) visit(d) } catch { /* cross-origin */ }
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
visit(document)
|
|
478
|
+
return roots
|
|
479
|
+
}
|
|
480
|
+
const roots = allRoots()
|
|
481
|
+
const candidates = (spec) => {
|
|
482
|
+
const all = spec.selector
|
|
483
|
+
? roots.flatMap(root => [...root.querySelectorAll(spec.selector)])
|
|
484
|
+
: roots.flatMap(root => [...root.querySelectorAll('input, textarea, select, [contenteditable="true"]')]).filter(el => matches(el, spec))
|
|
485
|
+
const vis = all.filter(visible)
|
|
486
|
+
return vis.length > 0 ? vis : all
|
|
487
|
+
}
|
|
488
|
+
for (const spec of specs) {
|
|
489
|
+
let els
|
|
490
|
+
try {
|
|
491
|
+
els = candidates(spec)
|
|
492
|
+
} catch (e) {
|
|
493
|
+
// A malformed selector must not abort the whole batch; report the
|
|
494
|
+
// field as failed and continue with the rest.
|
|
495
|
+
out.push({ ok: false, error: String(e), target: describe(spec) })
|
|
496
|
+
continue
|
|
497
|
+
}
|
|
498
|
+
if (els.length === 0) { out.push({ ok: false, error: 'field not found', target: describe(spec) }); continue }
|
|
499
|
+
let el = els[0]
|
|
500
|
+
// The caller may name a kind. Honor it: the branches below read the element's own
|
|
501
|
+
// tag/type, so without this a selector matching two different controls acted on
|
|
502
|
+
// whichever came first — usually right, which is what hid the mistake. A field that
|
|
503
|
+
// names NO kind gets no filter at all: the element's own tag then decides the
|
|
504
|
+
// branch, which is what "kind defaults to text" was always trying to say.
|
|
505
|
+
if (spec.kind) {
|
|
506
|
+
const matchesKind = (node) => {
|
|
507
|
+
const nodeTag = node.tagName
|
|
508
|
+
const nodeType = (node.type || '').toLowerCase()
|
|
509
|
+
if (spec.kind === 'select') return nodeTag === 'SELECT'
|
|
510
|
+
if (spec.kind === 'textarea') return nodeTag === 'TEXTAREA'
|
|
511
|
+
if (spec.kind === 'checkbox' || spec.kind === 'radio') return nodeType === spec.kind
|
|
512
|
+
// 'text': the plain-value branch covers <input> AND <textarea>, and the batch
|
|
513
|
+
// already collects [contenteditable="true"] as a settable control — so all three
|
|
514
|
+
// must match. Requiring nodeTag === 'INPUT' here reported "no text control
|
|
515
|
+
// matched" for a textarea and left the contenteditable branch below unreachable.
|
|
516
|
+
if (nodeTag === 'TEXTAREA') return true
|
|
517
|
+
if (node.isContentEditable === true) return true
|
|
518
|
+
return nodeTag === 'INPUT' && nodeType !== 'checkbox' && nodeType !== 'radio' && nodeType !== 'file'
|
|
519
|
+
}
|
|
520
|
+
const wanted = els.find(matchesKind)
|
|
521
|
+
if (wanted === undefined) {
|
|
522
|
+
out.push({ ok: false, error: 'no "' + spec.kind + '" control matched', target: describe(spec) })
|
|
523
|
+
continue
|
|
524
|
+
}
|
|
525
|
+
els.length = 0
|
|
526
|
+
els.push(wanted)
|
|
527
|
+
// el was bound before the filter narrowed els, so the branches below would still
|
|
528
|
+
// read the first match — the very silent wrong-element behaviour this filter exists
|
|
529
|
+
// to remove.
|
|
530
|
+
el = els[0]
|
|
531
|
+
}
|
|
532
|
+
const tag = el.tagName
|
|
533
|
+
const type = (el.type || '').toLowerCase()
|
|
534
|
+
try {
|
|
535
|
+
if (tag === 'SELECT') {
|
|
536
|
+
const wanted = String(spec.value)
|
|
537
|
+
if (el.multiple) {
|
|
538
|
+
const wantedList = wanted.split(',').map(x => x.trim())
|
|
539
|
+
let hit = false
|
|
540
|
+
for (const o of [...el.options]) {
|
|
541
|
+
o.selected = wantedList.includes(o.value) || wantedList.includes((o.textContent || '').trim())
|
|
542
|
+
if (o.selected) hit = true
|
|
543
|
+
}
|
|
544
|
+
if (!hit) { out.push({ ok: false, error: 'option not found: ' + wanted, target: describe(spec) }); continue }
|
|
545
|
+
} else {
|
|
546
|
+
let opt = [...el.options].find(o => o.value === wanted)
|
|
547
|
+
if (!opt) opt = [...el.options].find(o => (o.textContent || '').trim() === wanted)
|
|
548
|
+
if (!opt) { out.push({ ok: false, error: 'option not found: ' + wanted, target: describe(spec) }); continue }
|
|
549
|
+
setNative(el, HTMLSelectElement.prototype, opt.value)
|
|
550
|
+
}
|
|
551
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
552
|
+
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
553
|
+
out.push({ ok: true, method: 'select', target: describe(spec) })
|
|
554
|
+
} else if (type === 'file') {
|
|
555
|
+
out.push({ ok: false, error: 'file inputs cannot be set from script; use dsh_browser_download or ask the human', target: describe(spec) })
|
|
556
|
+
} else if (type === 'checkbox') {
|
|
557
|
+
const want = spec.value === true || spec.value === 'true' || spec.value === 'on'
|
|
558
|
+
if (el.checked !== want) el.click()
|
|
559
|
+
out.push({ ok: true, method: 'checkbox', target: describe(spec) })
|
|
560
|
+
} else if (type === 'radio') {
|
|
561
|
+
const wanted = String(spec.value)
|
|
562
|
+
const radio = [...(el.getRootNode().querySelectorAll ? el.getRootNode() : document).querySelectorAll('input[type="radio"][name=' + JSON.stringify(el.name || '') + ']')]
|
|
563
|
+
.filter(r => r.form === el.form)
|
|
564
|
+
.find(r => r.value === wanted || (r === el && (spec.value === true || spec.value === 'true')))
|
|
565
|
+
if (!radio) { out.push({ ok: false, error: 'radio option not found: ' + wanted, target: describe(spec) }); continue }
|
|
566
|
+
if (!radio.checked) radio.click()
|
|
567
|
+
out.push({ ok: true, method: 'radio', target: describe(spec) })
|
|
568
|
+
} else if (el.isContentEditable) {
|
|
569
|
+
el.textContent = String(spec.value)
|
|
570
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
571
|
+
out.push({ ok: true, method: 'contenteditable', target: describe(spec) })
|
|
572
|
+
} else if (tag === 'TEXTAREA') {
|
|
573
|
+
setNative(el, HTMLTextAreaElement.prototype, String(spec.value))
|
|
574
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
575
|
+
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
576
|
+
out.push({ ok: true, method: 'textarea', target: describe(spec) })
|
|
577
|
+
} else {
|
|
578
|
+
setNative(el, HTMLInputElement.prototype, String(spec.value))
|
|
579
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
580
|
+
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
581
|
+
out.push({ ok: true, method: 'input', target: describe(spec) })
|
|
582
|
+
}
|
|
583
|
+
} catch (e) {
|
|
584
|
+
out.push({ ok: false, error: String(e), target: describe(spec) })
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
let submitted = false
|
|
588
|
+
if (${submitFlag}) {
|
|
589
|
+
let last = null
|
|
590
|
+
for (const spec of specs) {
|
|
591
|
+
try { const els = candidates(spec); if (els.length > 0) { last = els[0]; break } } catch { /* skip */ }
|
|
592
|
+
}
|
|
593
|
+
const form = last && (last.form || last.closest('form'))
|
|
594
|
+
if (form) { form.requestSubmit(); submitted = true }
|
|
595
|
+
}
|
|
596
|
+
return { fields: out, submitted }
|
|
597
|
+
})()`;
|
|
598
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
|
|
599
|
+
const result = await withTimeout(handleSendEvaluate(tab.handle, script), timeoutMs, signal, `browser: fillForm timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
600
|
+
if (!result.ok) {
|
|
601
|
+
throw new BrowserError(`browser: fillForm evaluation failed: ${result.exception}`, 'BROWSER_FILL_FAILED');
|
|
602
|
+
}
|
|
603
|
+
const value = result.value;
|
|
604
|
+
const okCount = value.fields.filter(f => f.ok).length;
|
|
605
|
+
this.record(s, 'fill', { fields: request.fields.length, submit: submitFlag }, okCount === value.fields.length, {
|
|
606
|
+
result: `${okCount}/${value.fields.length} fields filled${value.submitted ? ', form submitted' : ''}`,
|
|
607
|
+
});
|
|
608
|
+
return { fields: value.fields, submitted: value.submitted === true };
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Build an in-page async IIFE that locates ONE element by css/text/xpath
|
|
612
|
+
* (polling until it appears or the budget runs out) and then runs `body`
|
|
613
|
+
* with `el` in scope. Shared by the target-based tools: click/type (②),
|
|
614
|
+
* setValue/check/select/clear/getValue (③), and the scrape item wait.
|
|
615
|
+
* A selector that fails to PARSE is reported immediately instead of being
|
|
616
|
+
* polled until the budget expires — see the comment in `match`.
|
|
617
|
+
*/
|
|
618
|
+
buildTargetScript(spec, timeoutMs, body) {
|
|
619
|
+
// `by` defaults to css in-page; report the strategy that WAS used, or a
|
|
620
|
+
// miss says only `{"value":"Learn more"}` and the caller cannot tell that a
|
|
621
|
+
// plain label was queried as a CSS selector.
|
|
622
|
+
const resolvedSpec = { ...spec, by: spec.by ?? 'css' };
|
|
623
|
+
return (sliceMs, last) => `(async () => {
|
|
624
|
+
const spec = ${JSON.stringify(resolvedSpec)}
|
|
625
|
+
const timeoutMs = ${String(timeoutMs)}
|
|
626
|
+
const sliceMs = ${String(sliceMs)}
|
|
627
|
+
const last = ${String(last)}
|
|
628
|
+
const sleep = ms => new Promise(r => setTimeout(r, ms))
|
|
629
|
+
const isVisible = el => el instanceof HTMLElement && (el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0)
|
|
630
|
+
const ownText = el => Array.from(el.childNodes).filter(n => n.nodeType === Node.TEXT_NODE).map(n => n.textContent || '').join('').trim()
|
|
631
|
+
const depth = el => { let d = 0; let p = el.parentElement; while (p) { d++; p = p.parentElement } return d }
|
|
632
|
+
const match = () => {
|
|
633
|
+
const by = typeof spec.by === 'string' ? spec.by : 'css'
|
|
634
|
+
const value = String(spec.value ?? '')
|
|
635
|
+
// Named matchIndex rather than index: this whole function is one host-side template
|
|
636
|
+
// literal, so a bare name declared here can silently shadow a host binding of the
|
|
637
|
+
// same name and turn an inner reference into a type error.
|
|
638
|
+
const matchIndex = typeof spec.index === 'number' ? spec.index : 0
|
|
639
|
+
// An index that cannot address an element can never match on a later poll, exactly
|
|
640
|
+
// like a selector that fails to parse — so it must not look like a miss either. A
|
|
641
|
+
// negative index, the common "last one" shorthand, otherwise burned the caller's
|
|
642
|
+
// whole locate budget (10s) and then reported "element not found", which reads like a
|
|
643
|
+
// slow page rather than a bad argument.
|
|
644
|
+
// (No backticks in this comment: it lives inside a template literal.)
|
|
645
|
+
if (!Number.isInteger(matchIndex) || matchIndex < 0) {
|
|
646
|
+
throw new Error('target.index must be a non-negative integer, got ' + JSON.stringify(spec.index))
|
|
647
|
+
}
|
|
648
|
+
let els = []
|
|
649
|
+
// Every root this page exposes: the top document plus its shadow trees (recursively)
|
|
650
|
+
// and same-origin iframes. The snapshot and waitFor already walk all of them, so an
|
|
651
|
+
// element inside one is shown to the model and can be waited for — resolving a click or
|
|
652
|
+
// a fill used to look at the top document alone and answer "not found" for something
|
|
653
|
+
// the model had just been handed a reference to. The two must agree about what exists.
|
|
654
|
+
// (Kept in step with the collector in the snapshot script above.)
|
|
655
|
+
const allRoots = () => {
|
|
656
|
+
const roots = []
|
|
657
|
+
const seen = new Set()
|
|
658
|
+
const visit = doc => {
|
|
659
|
+
if (seen.has(doc)) return
|
|
660
|
+
seen.add(doc)
|
|
661
|
+
roots.push(doc)
|
|
662
|
+
for (const el of doc.querySelectorAll('*')) {
|
|
663
|
+
if (el.shadowRoot) visit(el.shadowRoot)
|
|
664
|
+
if (el.tagName === 'IFRAME') {
|
|
665
|
+
try { const d = el.contentDocument; if (d) visit(d) } catch { /* cross-origin */ }
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
visit(document)
|
|
670
|
+
return roots
|
|
671
|
+
}
|
|
672
|
+
const roots = allRoots()
|
|
673
|
+
if (by === 'css') {
|
|
674
|
+
// A selector that does not PARSE can never match on a later poll, so
|
|
675
|
+
// it must not look like a miss: the old "return null" kept the caller
|
|
676
|
+
// polling until the whole budget was gone, and "element not found
|
|
677
|
+
// after 10s" reads like a slow page while the real cause is a
|
|
678
|
+
// malformed selector (a label or plain text passed where one belongs).
|
|
679
|
+
// Parse on the top document first: a selector that does not PARSE must still be
|
|
680
|
+
// reported as a bad argument rather than as a miss, and that check is about syntax,
|
|
681
|
+
// not about which root holds the element.
|
|
682
|
+
try { document.querySelectorAll(value) }
|
|
683
|
+
catch (error) { throw new Error('invalid CSS selector ' + JSON.stringify(value) + ' (' + String((error && error.message) || error) + ')') }
|
|
684
|
+
for (const root of roots) els.push(...root.querySelectorAll(value))
|
|
685
|
+
} else if (by === 'xpath') {
|
|
686
|
+
try {
|
|
687
|
+
for (const root of roots) {
|
|
688
|
+
const snap = document.evaluate(value, root, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
|
|
689
|
+
for (let i = 0; i < snap.snapshotLength; i++) {
|
|
690
|
+
const n = snap.snapshotItem(i)
|
|
691
|
+
if (n instanceof Element) els.push(n)
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
} catch (error) { throw new Error('invalid XPath ' + JSON.stringify(value) + ' (' + String((error && error.message) || error) + ')') }
|
|
695
|
+
} else {
|
|
696
|
+
// '*' rather than 'body *': a shadow root and an iframe document have no body of
|
|
697
|
+
// their own to anchor to, and the visibility and own-text predicates below are what
|
|
698
|
+
// actually decide whether an element counts.
|
|
699
|
+
const all = roots.flatMap(root => [...root.querySelectorAll('*')])
|
|
700
|
+
const exact = all.filter(el => isVisible(el) && ownText(el) === value)
|
|
701
|
+
// Exact first, then contains; deepest element preferred (so a
|
|
702
|
+
// button inside a card wins over the card itself).
|
|
703
|
+
const pool = exact.length > 0 ? exact : all.filter(el => isVisible(el) && ownText(el).includes(value))
|
|
704
|
+
els = pool.sort((a, b) => depth(b) - depth(a))
|
|
705
|
+
}
|
|
706
|
+
return els[matchIndex] ?? null
|
|
707
|
+
}
|
|
708
|
+
const deadline = Date.now() + sliceMs
|
|
709
|
+
let el = null
|
|
710
|
+
for (;;) {
|
|
711
|
+
// Only a parse error escapes the poll: see the comment in match() above.
|
|
712
|
+
try { el = match() } catch (error) { return { ok: false, error: String((error && error.message) || error) } }
|
|
713
|
+
if (el !== null) break
|
|
714
|
+
if (Date.now() >= deadline && !last) return { pending: true }
|
|
715
|
+
if (Date.now() >= deadline) return { ok: false, error: 'element not found: ' + JSON.stringify(spec) + ' (looked for ' + timeoutMs + 'ms)' }
|
|
716
|
+
await sleep(100)
|
|
717
|
+
}
|
|
718
|
+
const __result = await (async () => {
|
|
719
|
+
${body}
|
|
720
|
+
})()
|
|
721
|
+
// Report the operated element's viewport center next to the script's own
|
|
722
|
+
// verdict: the synthetic cursor (and any future feedback) needs the point,
|
|
723
|
+
// and no individual body should have to compute it a second time. Kept
|
|
724
|
+
// under a distinct key so a body that already returns x/y keeps them.
|
|
725
|
+
const __rect = el.getBoundingClientRect()
|
|
726
|
+
return {
|
|
727
|
+
...(typeof __result === 'object' && __result !== null ? __result : { ok: true }),
|
|
728
|
+
__point: { x: Math.round(__rect.x + __rect.width / 2), y: Math.round(__rect.y + __rect.height / 2) },
|
|
729
|
+
}
|
|
730
|
+
})()`;
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* Shared evaluate wrapper for the target-based tools. Runs the in-page
|
|
734
|
+
* script and returns its result object; throws a typed BrowserError on
|
|
735
|
+
* evaluation failure or an in-page `{ ok: false, error }` verdict.
|
|
736
|
+
*/
|
|
737
|
+
async runTargetScript(tab, script, timeoutMs, signal, errorCode, errorLabel) {
|
|
738
|
+
// Each slice polls in-page and answers only afterwards, so its outer budget must outlast it or
|
|
739
|
+
// the generic timeout hides the in-page reason (selector not found / malformed).
|
|
740
|
+
const deadline = Date.now() + timeoutMs;
|
|
741
|
+
let value;
|
|
742
|
+
do {
|
|
743
|
+
const { sliceMs, last } = pagePollSlice(deadline);
|
|
744
|
+
const result = await withTimeout(handleSendEvaluate(tab.handle, script(sliceMs, last)), Math.max(sliceMs, deadline - Date.now()) + TARGET_SCRIPT_GRACE_MS, signal, `${errorLabel} timed out after ${timeoutMs}ms`, timedOut => { this.interrupt(tab.handle, timedOut); });
|
|
745
|
+
if (!result.ok)
|
|
746
|
+
throw new BrowserError(`${errorLabel} failed: ${result.exception}`, errorCode);
|
|
747
|
+
value = result.value;
|
|
748
|
+
} while (value?.pending === true);
|
|
749
|
+
if (value?.ok !== true)
|
|
750
|
+
throw new BrowserError(`${errorLabel} failed: ${value?.error ?? 'unknown'}`, errorCode);
|
|
751
|
+
return value;
|
|
752
|
+
}
|
|
753
|
+
/** Set one element's value (native setter + input/change, React-friendly). */
|
|
754
|
+
async setValue(session, request, signal) {
|
|
755
|
+
const s = this.session(session);
|
|
756
|
+
const tab = this.activeTab(s);
|
|
757
|
+
signal?.throwIfAborted();
|
|
758
|
+
const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
|
|
759
|
+
const body = `
|
|
760
|
+
const value = ${JSON.stringify(String(request.value))}
|
|
761
|
+
const setNative = (el, proto, v) => {
|
|
762
|
+
const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
|
|
763
|
+
if (setter) setter.call(el, v)
|
|
764
|
+
else el.value = v
|
|
765
|
+
}
|
|
766
|
+
const tag = el.tagName
|
|
767
|
+
const type = (el.type || '').toLowerCase()
|
|
768
|
+
if (tag === 'SELECT') {
|
|
769
|
+
const wanted = value
|
|
770
|
+
let opt = [...el.options].find(o => o.value === wanted)
|
|
771
|
+
if (!opt) opt = [...el.options].find(o => (o.textContent || '').trim() === wanted)
|
|
772
|
+
if (!opt) return { ok: false, error: 'option not found: ' + wanted }
|
|
773
|
+
setNative(el, HTMLSelectElement.prototype, opt.value)
|
|
774
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
775
|
+
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
776
|
+
return { ok: true, method: 'select', value: opt.value }
|
|
777
|
+
}
|
|
778
|
+
if (el.isContentEditable) {
|
|
779
|
+
el.textContent = value
|
|
780
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
781
|
+
return { ok: true, method: 'contenteditable', value }
|
|
782
|
+
}
|
|
783
|
+
if (tag === 'TEXTAREA') {
|
|
784
|
+
setNative(el, HTMLTextAreaElement.prototype, value)
|
|
785
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
786
|
+
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
787
|
+
return { ok: true, method: 'textarea', value }
|
|
788
|
+
}
|
|
789
|
+
setNative(el, HTMLInputElement.prototype, value)
|
|
790
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
791
|
+
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
792
|
+
return { ok: true, method: 'input', value }
|
|
793
|
+
`;
|
|
794
|
+
const script = this.buildTargetScript(request.target, timeoutMs, body);
|
|
795
|
+
const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_SET_VALUE_FAILED', 'browser: setValue');
|
|
796
|
+
const cursorPoint = scriptPoint(out);
|
|
797
|
+
if (cursorPoint !== undefined)
|
|
798
|
+
this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click');
|
|
799
|
+
this.record(s, 'setValue', { target: request.target, value: String(request.value) }, true, { result: out.method });
|
|
800
|
+
return { method: out.method, value: out.value };
|
|
801
|
+
}
|
|
802
|
+
/** Check or uncheck one checkbox/radio. */
|
|
803
|
+
async check(session, request, signal) {
|
|
804
|
+
const s = this.session(session);
|
|
805
|
+
const tab = this.activeTab(s);
|
|
806
|
+
signal?.throwIfAborted();
|
|
807
|
+
const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
|
|
808
|
+
const want = request.checked ?? true;
|
|
809
|
+
const body = `
|
|
810
|
+
const want = ${String(want)}
|
|
811
|
+
const type = (el.type || '').toLowerCase()
|
|
812
|
+
if (type === 'checkbox') {
|
|
813
|
+
if (el.checked !== want) el.click()
|
|
814
|
+
return { ok: true, checked: el.checked }
|
|
815
|
+
}
|
|
816
|
+
if (type === 'radio') {
|
|
817
|
+
if (want && !el.checked) el.click()
|
|
818
|
+
return { ok: true, checked: el.checked }
|
|
819
|
+
}
|
|
820
|
+
return { ok: false, error: 'element is not a checkbox or radio (' + el.tagName + ')' }
|
|
821
|
+
`;
|
|
822
|
+
const script = this.buildTargetScript(request.target, timeoutMs, body);
|
|
823
|
+
const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_CHECK_FAILED', 'browser: check');
|
|
824
|
+
const cursorPoint = scriptPoint(out);
|
|
825
|
+
if (cursorPoint !== undefined)
|
|
826
|
+
this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click');
|
|
827
|
+
this.record(s, 'check', { target: request.target, checked: want }, true);
|
|
828
|
+
return { checked: out.checked === true };
|
|
829
|
+
}
|
|
830
|
+
/** Select one option of a <select>, by value, visible text, or index. */
|
|
831
|
+
async selectOption(session, request, signal) {
|
|
832
|
+
const s = this.session(session);
|
|
833
|
+
const tab = this.activeTab(s);
|
|
834
|
+
signal?.throwIfAborted();
|
|
835
|
+
const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
|
|
836
|
+
const body = `
|
|
837
|
+
if (el.tagName !== 'SELECT') return { ok: false, error: 'element is not a <select> (' + el.tagName + ')' }
|
|
838
|
+
const optionValue = ${JSON.stringify(request.optionValue ?? null)}
|
|
839
|
+
const optionText = ${JSON.stringify(request.optionText ?? null)}
|
|
840
|
+
const optionIndex = ${String(request.optionIndex ?? -1)}
|
|
841
|
+
let opt = null
|
|
842
|
+
if (optionValue !== null) opt = [...el.options].find(o => o.value === optionValue)
|
|
843
|
+
if (!opt && optionText !== null) opt = [...el.options].find(o => (o.textContent || '').trim() === optionText)
|
|
844
|
+
if (!opt && optionIndex >= 0) opt = el.options[optionIndex] ?? null
|
|
845
|
+
if (!opt) return { ok: false, error: 'option not found' }
|
|
846
|
+
const setNative = (el, proto, v) => {
|
|
847
|
+
const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
|
|
848
|
+
if (setter) setter.call(el, v)
|
|
849
|
+
else el.value = v
|
|
850
|
+
}
|
|
851
|
+
setNative(el, HTMLSelectElement.prototype, opt.value)
|
|
852
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
853
|
+
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
854
|
+
return { ok: true, value: opt.value, text: (opt.textContent || '').trim() }
|
|
855
|
+
`;
|
|
856
|
+
const script = this.buildTargetScript(request.target, timeoutMs, body);
|
|
857
|
+
const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_SELECT_FAILED', 'browser: select');
|
|
858
|
+
const cursorPoint = scriptPoint(out);
|
|
859
|
+
if (cursorPoint !== undefined)
|
|
860
|
+
this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click');
|
|
861
|
+
this.record(s, 'select', { target: request.target, optionValue: request.optionValue ?? null, optionText: request.optionText ?? null, optionIndex: request.optionIndex ?? null }, true);
|
|
862
|
+
return { value: out.value, text: out.text };
|
|
863
|
+
}
|
|
864
|
+
/** Clear one input/textarea/contenteditable (or uncheck a checkbox/radio). */
|
|
865
|
+
async clearField(session, request, signal) {
|
|
866
|
+
const s = this.session(session);
|
|
867
|
+
const tab = this.activeTab(s);
|
|
868
|
+
signal?.throwIfAborted();
|
|
869
|
+
const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
|
|
870
|
+
const body = `
|
|
871
|
+
const setNative = (el, proto) => {
|
|
872
|
+
const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
|
|
873
|
+
if (setter) setter.call(el, '')
|
|
874
|
+
else el.value = ''
|
|
875
|
+
}
|
|
876
|
+
if (el.isContentEditable) {
|
|
877
|
+
el.textContent = ''
|
|
878
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
879
|
+
} else if (el.tagName === 'TEXTAREA') {
|
|
880
|
+
setNative(el, HTMLTextAreaElement.prototype)
|
|
881
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
882
|
+
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
883
|
+
} else if (el.tagName === 'INPUT' && (el.type === 'checkbox' || el.type === 'radio')) {
|
|
884
|
+
if (el.checked) el.click()
|
|
885
|
+
} else {
|
|
886
|
+
setNative(el, HTMLInputElement.prototype)
|
|
887
|
+
el.dispatchEvent(new Event('input', { bubbles: true }))
|
|
888
|
+
el.dispatchEvent(new Event('change', { bubbles: true }))
|
|
889
|
+
}
|
|
890
|
+
return { ok: true }
|
|
891
|
+
`;
|
|
892
|
+
const script = this.buildTargetScript(request.target, timeoutMs, body);
|
|
893
|
+
const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_CLEAR_FAILED', 'browser: clear');
|
|
894
|
+
const cursorPoint = scriptPoint(out);
|
|
895
|
+
if (cursorPoint !== undefined)
|
|
896
|
+
this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click');
|
|
897
|
+
this.record(s, 'clear', { target: request.target }, true);
|
|
898
|
+
return { cleared: true };
|
|
899
|
+
}
|
|
900
|
+
/** Read one element's current value (for verification). */
|
|
901
|
+
async getValue(session, request, signal) {
|
|
902
|
+
const s = this.session(session);
|
|
903
|
+
const tab = this.activeTab(s);
|
|
904
|
+
signal?.throwIfAborted();
|
|
905
|
+
const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction;
|
|
906
|
+
const body = `
|
|
907
|
+
const type = (el.type || '').toLowerCase()
|
|
908
|
+
if (type === 'checkbox' || type === 'radio') return { ok: true, value: null, checked: el.checked }
|
|
909
|
+
if (el.tagName === 'SELECT') {
|
|
910
|
+
const o = el.options[el.selectedIndex]
|
|
911
|
+
return { ok: true, value: el.value, selectedText: o ? (o.textContent || '').trim() : null }
|
|
912
|
+
}
|
|
913
|
+
const v = el.value !== undefined ? el.value : el.textContent
|
|
914
|
+
return { ok: true, value: v === undefined || v === null ? null : String(v) }
|
|
915
|
+
`;
|
|
916
|
+
const script = this.buildTargetScript(request.target, timeoutMs, body);
|
|
917
|
+
const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_GET_VALUE_FAILED', 'browser: getValue');
|
|
918
|
+
this.record(s, 'getValue', { target: request.target }, true);
|
|
919
|
+
return {
|
|
920
|
+
value: out.value === null || out.value === undefined ? null : String(out.value),
|
|
921
|
+
...out.checked !== undefined ? { checked: out.checked === true } : {},
|
|
922
|
+
...out.selectedText !== undefined && out.selectedText !== null ? { selectedText: String(out.selectedText) } : {},
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* Show the synthetic pointer on a view, unless the user switched it off. The
|
|
927
|
+
* cursor is the "the agent has taken over this tab" signal, so it is painted
|
|
928
|
+
* for every operation that has a landing point — including DOM-level ones that
|
|
929
|
+
* move no real pointer.
|
|
930
|
+
* @param handle - the view to paint into.
|
|
931
|
+
* @param x - viewport x in CSS pixels.
|
|
932
|
+
* @param y - viewport y in CSS pixels.
|
|
933
|
+
* @param action - click pulses a ripple; move only relocates.
|
|
934
|
+
* @param label - short description of the operation, shown beside the pointer.
|
|
935
|
+
* @param force - paint even when the pointer is already there (a click ripple must
|
|
936
|
+
* always play; a bare move need not repeat).
|
|
937
|
+
*/
|
|
938
|
+
showCursor(handle, x, y, action, label, force = false) {
|
|
939
|
+
if (this.settingsSource !== undefined && !this.settingsSource().ui.virtualCursor)
|
|
940
|
+
return Promise.resolve();
|
|
941
|
+
return paintCursor(handle, x, y, action, (target, expression) => handleSendEvaluate(target, expression), label, force);
|
|
942
|
+
}
|
|
943
|
+
/** Best-effort bounded wait for the click cursor paint before pointer dispatch. */
|
|
944
|
+
async showCursorSettled(handle, x, y, action, label, force = false) {
|
|
945
|
+
if (this.settingsSource !== undefined && !this.settingsSource().ui.virtualCursor)
|
|
946
|
+
return;
|
|
947
|
+
const pending = this.showCursor(handle, x, y, action, label, force);
|
|
948
|
+
let timer;
|
|
949
|
+
try {
|
|
950
|
+
await Promise.race([
|
|
951
|
+
pending,
|
|
952
|
+
new Promise(resolve => {
|
|
953
|
+
timer = setTimeout(resolve, 250);
|
|
954
|
+
timer.unref?.();
|
|
955
|
+
}),
|
|
956
|
+
]);
|
|
957
|
+
}
|
|
958
|
+
finally {
|
|
959
|
+
if (timer !== undefined)
|
|
960
|
+
clearTimeout(timer);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
}
|