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
|
@@ -27,9 +27,10 @@
|
|
|
27
27
|
*/
|
|
28
28
|
|
|
29
29
|
import type { BrowserPageOperationRequest, BrowserProbeMethod } from '../browser/types.ts'
|
|
30
|
+
import { DEEP_DOM_SOURCE } from '../browser/deep-dom.ts'
|
|
30
31
|
|
|
31
32
|
/** Bumped when the probe's shape changes; an older probe is replaced rather than trusted. */
|
|
32
|
-
export const PROBE_VERSION =
|
|
33
|
+
export const PROBE_VERSION = 10
|
|
33
34
|
|
|
34
35
|
/** Where the probe keeps itself, and the only global it adds. */
|
|
35
36
|
const PROBE_KEY = '__dshProbe'
|
|
@@ -40,7 +41,19 @@ const PROBE_KEY = '__dshProbe'
|
|
|
40
41
|
* Written as a string because it runs in the page, not here. Keep it dependency-free and ES5-safe:
|
|
41
42
|
* a page may be older than the harness.
|
|
42
43
|
*/
|
|
43
|
-
export const PROBE_INSTALL_SCRIPT = `(() => {
|
|
44
|
+
export const PROBE_INSTALL_SCRIPT = `(() => {${DEEP_DOM_SOURCE}
|
|
45
|
+
const frameOffset = (node) => {
|
|
46
|
+
let x = 0, y = 0
|
|
47
|
+
let doc = node && node.ownerDocument
|
|
48
|
+
while (doc && doc.defaultView && doc.defaultView.frameElement) {
|
|
49
|
+
const frame = doc.defaultView.frameElement
|
|
50
|
+
const r = frame.getBoundingClientRect()
|
|
51
|
+
x += r.left + (Number(frame.clientLeft) || 0)
|
|
52
|
+
y += r.top + (Number(frame.clientTop) || 0)
|
|
53
|
+
doc = frame.ownerDocument
|
|
54
|
+
}
|
|
55
|
+
return { x: x, y: y }
|
|
56
|
+
}
|
|
44
57
|
const KEY = ${JSON.stringify(PROBE_KEY)}
|
|
45
58
|
const VERSION = ${PROBE_VERSION}
|
|
46
59
|
const previous = globalThis[KEY]
|
|
@@ -93,12 +106,12 @@ export const PROBE_INSTALL_SCRIPT = `(() => {
|
|
|
93
106
|
const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase()
|
|
94
107
|
const started = Date.now()
|
|
95
108
|
state.pending += 1
|
|
96
|
-
const settle = (status) => {
|
|
109
|
+
const settle = (status, type) => {
|
|
97
110
|
state.pending = Math.max(0, state.pending - 1)
|
|
98
|
-
note({ at: started, kind: 'fetch', method: method, url: short(url, 300), status: status, ms: Date.now() - started })
|
|
111
|
+
note({ at: started, kind: 'fetch', method: method, url: short(url, 300), status: status, type: short(type || '', 80), ms: Date.now() - started })
|
|
99
112
|
}
|
|
100
113
|
return nativeFetch.apply(this, arguments).then(
|
|
101
|
-
(response) => { settle(response.status); return response },
|
|
114
|
+
(response) => { let type = ''; try { type = response.headers.get('content-type') || '' } catch (error) { /* opaque */ } settle(response.status, type); return response },
|
|
102
115
|
(error) => { settle(0); throw error },
|
|
103
116
|
)
|
|
104
117
|
})
|
|
@@ -117,7 +130,9 @@ export const PROBE_INSTALL_SCRIPT = `(() => {
|
|
|
117
130
|
state.pending += 1
|
|
118
131
|
const done = () => {
|
|
119
132
|
state.pending = Math.max(0, state.pending - 1)
|
|
120
|
-
|
|
133
|
+
let type = ''
|
|
134
|
+
try { type = this.getResponseHeader('content-type') || '' } catch (error) { /* not readable */ }
|
|
135
|
+
note({ at: meta.at, kind: 'xhr', method: meta.method, url: short(meta.url, 300), status: this.status || 0, type: short(type, 80), ms: Date.now() - meta.at })
|
|
121
136
|
this.removeEventListener('loadend', done)
|
|
122
137
|
}
|
|
123
138
|
this.addEventListener('loadend', done)
|
|
@@ -181,11 +196,11 @@ export const PROBE_INSTALL_SCRIPT = `(() => {
|
|
|
181
196
|
if (!target) return null
|
|
182
197
|
let node = null
|
|
183
198
|
try {
|
|
184
|
-
if (target.css) node =
|
|
199
|
+
if (target.css) node = __dshQuery(String(target.css))
|
|
185
200
|
else if (target.xpath) node = document.evaluate(String(target.xpath), document, null, 9, null).singleNodeValue
|
|
186
201
|
else if (target.text) {
|
|
187
202
|
const wanted = String(target.text).trim().toLowerCase()
|
|
188
|
-
const nodes =
|
|
203
|
+
const nodes = __dshQueryAll('button, a, [role=button], input, label, [role=tab], [role=option], [role=link]')
|
|
189
204
|
for (let i = 0; i < nodes.length; i += 1) {
|
|
190
205
|
const value = ((nodes[i].innerText || nodes[i].getAttribute('aria-label') || nodes[i].value || '') + '').trim().toLowerCase()
|
|
191
206
|
if (value && value.indexOf(wanted) !== -1) { node = nodes[i]; break }
|
|
@@ -195,32 +210,91 @@ export const PROBE_INSTALL_SCRIPT = `(() => {
|
|
|
195
210
|
if (!node) return null
|
|
196
211
|
if (scroll === true && typeof node.scrollIntoView === 'function') node.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' })
|
|
197
212
|
const rect = node.getBoundingClientRect()
|
|
198
|
-
|
|
213
|
+
const offset = frameOffset(node)
|
|
214
|
+
state.lastFound = node
|
|
215
|
+
return { x: Math.round(offset.x + rect.left + rect.width / 2), y: Math.round(offset.y + rect.top + rect.height / 2), w: Math.round(rect.width), h: Math.round(rect.height), described: describe(node) }
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const composedParent = (node) => {
|
|
219
|
+
if (node.parentElement) return node.parentElement
|
|
220
|
+
if (node.parentNode && node.parentNode.host) return node.parentNode.host
|
|
221
|
+
const doc = node.ownerDocument
|
|
222
|
+
if (doc && (node === doc.documentElement || node.parentNode === doc)) {
|
|
223
|
+
const frame = doc.defaultView && doc.defaultView.frameElement
|
|
224
|
+
if (frame && frame !== node) return frame
|
|
225
|
+
}
|
|
226
|
+
return null
|
|
227
|
+
}
|
|
228
|
+
const deepHit = (x, y) => {
|
|
229
|
+
let cx = x, cy = y
|
|
230
|
+
let node = document.elementFromPoint(cx, cy)
|
|
231
|
+
for (let i = 0; node && i < 16; i += 1) {
|
|
232
|
+
if (node.shadowRoot && typeof node.shadowRoot.elementFromPoint === 'function') {
|
|
233
|
+
const inner = node.shadowRoot.elementFromPoint(cx, cy)
|
|
234
|
+
if (!inner || inner === node) break
|
|
235
|
+
node = inner
|
|
236
|
+
continue
|
|
237
|
+
}
|
|
238
|
+
if (node.tagName === 'IFRAME' || node.tagName === 'FRAME') {
|
|
239
|
+
let doc = null
|
|
240
|
+
try { doc = node.contentDocument } catch (error) { doc = null }
|
|
241
|
+
if (!doc || typeof doc.elementFromPoint !== 'function') break
|
|
242
|
+
const r = node.getBoundingClientRect()
|
|
243
|
+
cx = cx - r.left - (Number(node.clientLeft) || 0)
|
|
244
|
+
cy = cy - r.top - (Number(node.clientTop) || 0)
|
|
245
|
+
const inner = doc.elementFromPoint(cx, cy)
|
|
246
|
+
if (!inner || inner === node) break
|
|
247
|
+
node = inner
|
|
248
|
+
continue
|
|
249
|
+
}
|
|
250
|
+
break
|
|
251
|
+
}
|
|
252
|
+
return node
|
|
253
|
+
}
|
|
254
|
+
const computedStyle = (node) => {
|
|
255
|
+
try {
|
|
256
|
+
const win = node && node.ownerDocument && node.ownerDocument.defaultView
|
|
257
|
+
return (win && typeof win.getComputedStyle === 'function' ? win.getComputedStyle : getComputedStyle)(node)
|
|
258
|
+
} catch (error) { return null }
|
|
259
|
+
}
|
|
260
|
+
const floats = (node) => {
|
|
261
|
+
const style = computedStyle(node)
|
|
262
|
+
return !!style && (style.position === 'fixed' || style.position === 'sticky' || Number(style.zIndex) >= 100)
|
|
263
|
+
}
|
|
264
|
+
// A click at the point lands on the target when what is there is the target or inside it (an icon or label in a
|
|
265
|
+
// button, including inside open shadow roots and same-origin iframes), unless a floating layer between them
|
|
266
|
+
// (a modal inside the target) is what takes the click.
|
|
267
|
+
const lands = (target, hit) => {
|
|
268
|
+
for (let node = hit, depth = 0; node && depth < 64; node = composedParent(node), depth += 1) {
|
|
269
|
+
if (node === target) return true
|
|
270
|
+
if (floats(node)) return false
|
|
271
|
+
}
|
|
272
|
+
return false
|
|
199
273
|
}
|
|
200
274
|
|
|
201
275
|
const DISMISS = /(accept|agree|allow|continue|close|got it|dismiss|ok|agree|同意|接受|允许|继续|关闭|知道了|我知道了|我同意)/i
|
|
202
276
|
|
|
203
277
|
state.overlayAt = function (x, y) {
|
|
204
|
-
const
|
|
278
|
+
const px = Number(x), py = Number(y)
|
|
279
|
+
const top = deepHit(px, py)
|
|
205
280
|
if (!top) return { covers: null, dismiss: null }
|
|
281
|
+
if (state.lastFound && lands(state.lastFound, top)) return { covers: null, dismiss: null }
|
|
206
282
|
let node = top
|
|
207
283
|
let depth = 0
|
|
208
|
-
while (node && depth <
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
const floating = style && (style.position === 'fixed' || style.position === 'sticky' || Number(style.zIndex) >= 100)
|
|
212
|
-
if (floating) {
|
|
213
|
-
const buttons = node.querySelectorAll('button, [role=button], a')
|
|
284
|
+
while (node && depth < 16) {
|
|
285
|
+
if (floats(node)) {
|
|
286
|
+
const buttons = node.querySelectorAll ? node.querySelectorAll('button, [role=button], a') : []
|
|
214
287
|
for (let i = 0; i < buttons.length && i < 60; i += 1) {
|
|
215
288
|
const label = ((buttons[i].innerText || '') + ' ' + (buttons[i].getAttribute('aria-label') || '')).trim()
|
|
216
289
|
if (DISMISS.test(label)) {
|
|
217
290
|
const rect = buttons[i].getBoundingClientRect()
|
|
218
|
-
|
|
291
|
+
const offset = frameOffset(buttons[i])
|
|
292
|
+
return { covers: describe(top), dismiss: { label: short(label, 40), x: Math.round(offset.x + rect.left + rect.width / 2), y: Math.round(offset.y + rect.top + rect.height / 2) } }
|
|
219
293
|
}
|
|
220
294
|
}
|
|
221
295
|
return { covers: describe(top), dismiss: null }
|
|
222
296
|
}
|
|
223
|
-
node = node
|
|
297
|
+
node = composedParent(node)
|
|
224
298
|
depth += 1
|
|
225
299
|
}
|
|
226
300
|
return { covers: describe(top), dismiss: null }
|
|
@@ -268,22 +342,28 @@ export const PROBE_INSTALL_SCRIPT = `(() => {
|
|
|
268
342
|
const out = []
|
|
269
343
|
if (needle === '') return out
|
|
270
344
|
const wanted = needle.toLowerCase()
|
|
271
|
-
const
|
|
272
|
-
|
|
273
|
-
const
|
|
345
|
+
const roots = __dshRoots()
|
|
346
|
+
for (let r = 0; r < roots.length; r += 1) {
|
|
347
|
+
const scope = roots[r]
|
|
348
|
+
const owner = scope.ownerDocument || scope
|
|
349
|
+
const root = scope.nodeType === 9 ? (scope.body || scope.documentElement) : scope
|
|
350
|
+
if (!root || typeof owner.createTreeWalker !== 'function') continue
|
|
351
|
+
const walker = owner.createTreeWalker(root, 4, null) // 4 = SHOW_TEXT
|
|
274
352
|
let node = walker.nextNode()
|
|
275
353
|
while (node) {
|
|
276
|
-
const
|
|
354
|
+
const parent = node.parentElement
|
|
355
|
+
const value = parent && /^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(parent.tagName) ? '' : node.nodeValue || ''
|
|
277
356
|
let at = value.toLowerCase().indexOf(wanted)
|
|
278
357
|
while (at !== -1) {
|
|
279
|
-
const range =
|
|
358
|
+
const range = owner.createRange()
|
|
280
359
|
range.setStart(node, at)
|
|
281
360
|
range.setEnd(node, at + needle.length)
|
|
282
361
|
const rect = range.getBoundingClientRect()
|
|
362
|
+
const offset = frameOffset(node)
|
|
283
363
|
out.push({
|
|
284
364
|
text: short(value.slice(Math.max(0, at - 20), at + needle.length + 20).replace(/\\s+/g, ' ').trim(), 80),
|
|
285
|
-
x: Math.round(rect.left + rect.width / 2),
|
|
286
|
-
y: Math.round(rect.top + rect.height / 2),
|
|
365
|
+
x: Math.round(offset.x + rect.left + rect.width / 2),
|
|
366
|
+
y: Math.round(offset.y + rect.top + rect.height / 2),
|
|
287
367
|
host: node.parentElement ? describe(node.parentElement) : 'text',
|
|
288
368
|
})
|
|
289
369
|
if (out.length >= (all ? 50 : 5)) return out
|
|
@@ -291,6 +371,7 @@ export const PROBE_INSTALL_SCRIPT = `(() => {
|
|
|
291
371
|
}
|
|
292
372
|
node = walker.nextNode()
|
|
293
373
|
}
|
|
374
|
+
}
|
|
294
375
|
return out
|
|
295
376
|
}
|
|
296
377
|
|
|
@@ -330,10 +411,98 @@ export const PROBE_INSTALL_SCRIPT = `(() => {
|
|
|
330
411
|
links: query('a[href]'),
|
|
331
412
|
scrollX: Math.round(globalThis.scrollX || 0),
|
|
332
413
|
scrollY: Math.round(globalThis.scrollY || 0),
|
|
414
|
+
// The page's own geometry (issue #140): a screenshot that disagrees with these numbers was
|
|
415
|
+
// captured from a different surface, which is a fact only the page can prove.
|
|
416
|
+
vpWidth: Math.round(globalThis.innerWidth || 0),
|
|
417
|
+
vpHeight: Math.round(globalThis.innerHeight || 0),
|
|
418
|
+
dpr: Number(globalThis.devicePixelRatio || 1),
|
|
419
|
+
winWidth: Math.round(globalThis.outerWidth || 0),
|
|
420
|
+
winHeight: Math.round(globalThis.outerHeight || 0),
|
|
333
421
|
selection: short(globalThis.getSelection ? String(globalThis.getSelection()) : '', 120),
|
|
334
422
|
text: short(String(body || '').replace(/\\s+/g, ' ').trim(), 400),
|
|
335
423
|
}
|
|
336
424
|
}
|
|
425
|
+
// Where a page keeps its data before it becomes DOM: embedded state, the JSON APIs it called,
|
|
426
|
+
// resources it fetched before the probe existed, and endpoints it declares. Shapes only, never
|
|
427
|
+
// bodies, so the answer stays around 1-2 KB.
|
|
428
|
+
state.dataSources = function () {
|
|
429
|
+
const DATA_URL = /[.]json([?#]|$)|[/]api[/]|graphql|[/](locations?|stores?|search|query|products?|items?|listings?)([/?#.]|$)/i
|
|
430
|
+
const bytes = (text) => { try { return new Blob([text]).size } catch (error) { return String(text).length } }
|
|
431
|
+
const shape = (value) => {
|
|
432
|
+
const keys = value && typeof value === 'object' && !Array.isArray(value) ? Object.keys(value).slice(0, 12) : []
|
|
433
|
+
const arrays = []
|
|
434
|
+
const seen = new Set()
|
|
435
|
+
const walk = (node, path, depth) => {
|
|
436
|
+
if (!node || typeof node !== 'object' || seen.has(node) || depth > 6 || seen.size > 2000) return
|
|
437
|
+
seen.add(node)
|
|
438
|
+
if (Array.isArray(node)) {
|
|
439
|
+
if (node.length >= 3) arrays.push({ path: path || '(root)', length: node.length })
|
|
440
|
+
walk(node[0], path + '[0]', depth + 1)
|
|
441
|
+
return
|
|
442
|
+
}
|
|
443
|
+
for (const key of Object.keys(node).slice(0, 60)) walk(node[key], path ? path + '.' + key : key, depth + 1)
|
|
444
|
+
}
|
|
445
|
+
walk(value, '', 0)
|
|
446
|
+
arrays.sort((a, b) => b.length - a.length)
|
|
447
|
+
return { keys: keys, arrays: arrays.slice(0, 5) }
|
|
448
|
+
}
|
|
449
|
+
const embedded = []
|
|
450
|
+
const counts = {}
|
|
451
|
+
const scripts = Array.from(document.querySelectorAll('script#__NEXT_DATA__, script#__NUXT_DATA__, script[type="application/json"], script[type="application/ld+json"]'))
|
|
452
|
+
for (const node of scripts) {
|
|
453
|
+
const type = node.type || 'text/javascript'
|
|
454
|
+
const index = counts[type] = (counts[type] === undefined ? 0 : counts[type] + 1)
|
|
455
|
+
const text = node.textContent || ''
|
|
456
|
+
if (text.trim().length < 2 || embedded.length >= 8) continue
|
|
457
|
+
let parsed
|
|
458
|
+
try { parsed = JSON.parse(text) } catch (error) { parsed = undefined }
|
|
459
|
+
const name = node.id ? '#' + node.id : 'script[type="' + type + '"][' + index + ']'
|
|
460
|
+
embedded.push(Object.assign({ name: short(name, 80), bytes: bytes(text) }, parsed === undefined ? { parsed: false } : shape(parsed)))
|
|
461
|
+
}
|
|
462
|
+
for (const key of ['__NEXT_DATA__', '__NUXT__', '__INITIAL_STATE__', '__PRELOADED_STATE__', '__APOLLO_STATE__', '__remixContext']) {
|
|
463
|
+
let value
|
|
464
|
+
try { value = globalThis[key] } catch (error) { value = undefined }
|
|
465
|
+
if (value === undefined || value === null || typeof value !== 'object' || embedded.length >= 10) continue
|
|
466
|
+
let size = 0
|
|
467
|
+
try { size = bytes(JSON.stringify(value)) } catch (error) { size = 0 }
|
|
468
|
+
embedded.push(Object.assign({ name: 'window.' + key, bytes: size }, shape(value)))
|
|
469
|
+
}
|
|
470
|
+
const apis = []
|
|
471
|
+
const called = new Map()
|
|
472
|
+
for (const row of state.network) {
|
|
473
|
+
if ((row.kind !== 'fetch' && row.kind !== 'xhr') || !(row.status > 0)) continue
|
|
474
|
+
const id = row.method + ' ' + String(row.url).split('?')[0]
|
|
475
|
+
const json = /json/i.test(String(row.type || ''))
|
|
476
|
+
const hit = called.get(id)
|
|
477
|
+
if (hit) { hit.calls += 1; hit.url = row.url; hit.status = row.status; continue }
|
|
478
|
+
const entry = { method: row.method, url: row.url, status: row.status, type: short(String(row.type || '').split(';')[0], 40), calls: 1, json: json }
|
|
479
|
+
called.set(id, entry)
|
|
480
|
+
apis.push(entry)
|
|
481
|
+
}
|
|
482
|
+
apis.sort((a, b) => Number(b.json) - Number(a.json) || Number(DATA_URL.test(b.url)) - Number(DATA_URL.test(a.url)))
|
|
483
|
+
const known = new Set(apis.map(entry => String(entry.url).split('?')[0]))
|
|
484
|
+
const resources = []
|
|
485
|
+
let timings = []
|
|
486
|
+
try { timings = performance.getEntriesByType('resource') } catch (error) { timings = [] }
|
|
487
|
+
for (const entry of timings) {
|
|
488
|
+
const url = String(entry.name || '')
|
|
489
|
+
const initiator = String(entry.initiatorType || '')
|
|
490
|
+
if (initiator !== 'fetch' && initiator !== 'xmlhttprequest' && !DATA_URL.test(url)) continue
|
|
491
|
+
if (/^(script|css|img|link|image)$/.test(initiator) && !/[.]json([?#]|$)/i.test(url)) continue
|
|
492
|
+
const base = url.split('?')[0]
|
|
493
|
+
if (url.length > 2048 || known.has(base)) continue
|
|
494
|
+
known.add(base)
|
|
495
|
+
resources.push({ url: url, initiator: initiator, bytes: entry.transferSize || entry.encodedBodySize || 0 })
|
|
496
|
+
if (resources.length >= 12) break
|
|
497
|
+
}
|
|
498
|
+
const declared = []
|
|
499
|
+
const declare = (from, url) => { if (url && url.length <= 2048 && declared.length < 10 && !declared.some(entry => entry.url === url)) declared.push({ from: from, url: url }) }
|
|
500
|
+
try {
|
|
501
|
+
for (const link of Array.from(document.querySelectorAll('link[rel~="preload"][as="fetch"], link[rel~="prefetch"][as="fetch"]'))) declare('link[rel=' + link.rel + ']', link.href)
|
|
502
|
+
for (const node of Array.from(document.querySelectorAll('[data-api], [data-endpoint]')).slice(0, 20)) declare(node.hasAttribute('data-api') ? 'data-api' : 'data-endpoint', String(node.getAttribute('data-api') || node.getAttribute('data-endpoint') || ''))
|
|
503
|
+
} catch (error) { /* a document without these still answers the rest */ }
|
|
504
|
+
return { url: String(location.href), embedded: embedded, apis: apis.slice(0, 12), resources: resources, declared: declared }
|
|
505
|
+
}
|
|
337
506
|
globalThis[KEY] = state
|
|
338
507
|
return VERSION
|
|
339
508
|
})()`
|
|
@@ -426,13 +595,13 @@ export function uploadScript(
|
|
|
426
595
|
file: { readonly name: string; readonly mime: string; readonly base64: string },
|
|
427
596
|
): string {
|
|
428
597
|
const spec = JSON.stringify({ target, file })
|
|
429
|
-
return `(() => {
|
|
598
|
+
return `(() => {${DEEP_DOM_SOURCE}
|
|
430
599
|
const spec = ${spec}
|
|
431
600
|
const probe = globalThis[${JSON.stringify(PROBE_KEY)}]
|
|
432
601
|
const where = probe ? probe.find(spec.target) : null
|
|
433
602
|
let node = null
|
|
434
603
|
try {
|
|
435
|
-
if (spec.target.by === 'css') node =
|
|
604
|
+
if (spec.target.by === 'css') node = __dshQuery(spec.target.value)
|
|
436
605
|
else if (spec.target.by === 'xpath') node = document.evaluate(spec.target.value, document, null, 9, null).singleNodeValue
|
|
437
606
|
else if (where) node = document.elementFromPoint(where.x, where.y)
|
|
438
607
|
} catch (error) { node = null }
|
|
@@ -455,17 +624,49 @@ export function uploadScript(
|
|
|
455
624
|
return JSON.stringify({ ok: true, name: blob.name, size: blob.size, files: node.files ? node.files.length : 0 })
|
|
456
625
|
})()`
|
|
457
626
|
}
|
|
627
|
+
/**
|
|
628
|
+
* What an action changed on the page that the URL does not show: the title, visible alert regions
|
|
629
|
+
* and the dialogs the probe answered. Read before and after each action for the post-action line.
|
|
630
|
+
* It never installs the probe, so observing an action leaves the page as it was.
|
|
631
|
+
*/
|
|
632
|
+
const PULSE_SCRIPT = `(() => {
|
|
633
|
+
const probe = globalThis[${JSON.stringify(PROBE_KEY)}]
|
|
634
|
+
const alerts = []
|
|
635
|
+
try {
|
|
636
|
+
for (const node of Array.from(document.querySelectorAll('[role=alert], [role=alertdialog], [aria-live=assertive]')).slice(0, 20)) {
|
|
637
|
+
const text = String(node.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 160)
|
|
638
|
+
if (text !== '' && node.getClientRects().length > 0 && alerts.indexOf(text) === -1) alerts.push(text)
|
|
639
|
+
if (alerts.length >= 5) break
|
|
640
|
+
}
|
|
641
|
+
} catch (error) { /* a document without a body still has a title */ }
|
|
642
|
+
const dialogs = probe && Array.isArray(probe.dialogs)
|
|
643
|
+
? probe.dialogs.slice(-5).map(entry => ({ at: entry.at, kind: entry.kind, message: String(entry.message).slice(0, 160), answered: entry.answered }))
|
|
644
|
+
: []
|
|
645
|
+
return JSON.stringify({ title: String(document.title || ''), alerts: alerts, dialogs: dialogs, probe: probe ? Number(probe.startedAt) || 0 : 0 })
|
|
646
|
+
})()`
|
|
647
|
+
|
|
648
|
+
/** A fetch from the page, so it carries the page's same-origin cookies. The body comes back as text. */
|
|
649
|
+
function fetchScript(url: string, init: { readonly method?: string; readonly headers?: Readonly<Record<string, string>>; readonly body?: string }): string {
|
|
650
|
+
return `(async () => {
|
|
651
|
+
const response = await fetch(new URL(${JSON.stringify(url)}, document.baseURI).href, Object.assign({ credentials: 'same-origin' }, ${JSON.stringify(init)}))
|
|
652
|
+
const body = await response.text()
|
|
653
|
+
return JSON.stringify({ ok: response.ok, status: response.status, statusText: response.statusText, url: response.url, type: response.headers.get('content-type') || '', body: body })
|
|
654
|
+
})()`
|
|
655
|
+
}
|
|
656
|
+
|
|
458
657
|
/** Build a fixed page operation, rejecting unknown operations before any code runs. */
|
|
459
658
|
export function pageOperationScript(request: BrowserPageOperationRequest): string {
|
|
460
659
|
switch (request.operation) {
|
|
461
660
|
case 'install': return PROBE_INSTALL_SCRIPT
|
|
462
661
|
case 'url': return 'JSON.stringify(location.href)'
|
|
662
|
+
case 'pulse': return PULSE_SCRIPT
|
|
663
|
+
case 'fetch': return fetchScript(request.url, request.init)
|
|
463
664
|
case 'text': return 'JSON.stringify((document.body ? document.body.innerText : "").indexOf(' + JSON.stringify(request.text) + ') !== -1)'
|
|
464
665
|
case 'drag': return dragScript(request.from, request.to, request.steps)
|
|
465
666
|
case 'upload': return uploadScript(request.target, request.file)
|
|
466
667
|
case 'probe': {
|
|
467
668
|
const methods: readonly BrowserProbeMethod[] = ['read', 'clear', 'settle', 'find', 'overlayAt', 'summary',
|
|
468
|
-
'findText', 'hoverAt', 'setDialogPolicy', 'dialogStatus', 'networkCursor']
|
|
669
|
+
'findText', 'hoverAt', 'setDialogPolicy', 'dialogStatus', 'networkCursor', 'dataSources']
|
|
469
670
|
if (!methods.includes(request.method)) throw new Error('browser: unsupported fixed page operation')
|
|
470
671
|
return probeCallScript(request.method, request.args)
|
|
471
672
|
}
|
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
* @module dsh-builtin-browser/tool-browser/panel-page
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
+
import { GUEST_ROUTE } from '../../assets/browser-policy.mjs'
|
|
18
|
+
|
|
17
19
|
/** One interactive node found in the proxied document. */
|
|
18
20
|
export interface PanelElement {
|
|
19
21
|
readonly index: number
|
|
@@ -76,7 +78,7 @@ export async function readPanelPage(
|
|
|
76
78
|
options: { readonly limit?: number; readonly signal?: AbortSignal } = {},
|
|
77
79
|
): Promise<PanelPage> {
|
|
78
80
|
const limit = options.limit ?? 120
|
|
79
|
-
const proxied = `${origin}
|
|
81
|
+
const proxied = `${origin}${GUEST_ROUTE}?u=${encodeURIComponent(pageUrl)}`
|
|
80
82
|
const response = await fetch(proxied, {
|
|
81
83
|
headers: {
|
|
82
84
|
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Page-side probe client: fingerprints, observed effects, the installed probe, polling, and checks.
|
|
3
|
+
* @module dsh-browser/tool-browser/probe-client
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
7
|
+
import { pageOperationScript } from './page-probe.ts'
|
|
8
|
+
import { CURSOR_ID } from '../browser-electron/virtual-cursor.ts'
|
|
9
|
+
import type { BrowserSessionId, BrowserPageOperationRequest, BrowserProbeMethod } from '../browser/types.ts'
|
|
10
|
+
|
|
11
|
+
export const effectProperties = {
|
|
12
|
+
verified: { type: 'boolean' as const, description: 'Whether a visible change was observed. Absent when it could not be checked.' },
|
|
13
|
+
note: { type: 'string' as const, description: 'Why the effect is uncertain.' },
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function pageFingerprint(browser: NonNullable<Context['browser']>, session: BrowserSessionId): Promise<string | undefined> {
|
|
17
|
+
try {
|
|
18
|
+
const result = await browser.execute(session, {
|
|
19
|
+
script: `(() => {
|
|
20
|
+
const a = document.activeElement
|
|
21
|
+
const b = document.body
|
|
22
|
+
const c = typeof document.getElementById === 'function' ? document.getElementById(${JSON.stringify(CURSOR_ID)}) : null
|
|
23
|
+
const own = b && c && c.parentNode === b ? c : null
|
|
24
|
+
return JSON.stringify([
|
|
25
|
+
location.href, document.title,
|
|
26
|
+
a ? [a.tagName, a.id || a.getAttribute('name') || a.className || '',
|
|
27
|
+
typeof a.value === 'string' ? a.value.length : null, a.checked, a.selectedIndex,
|
|
28
|
+
a.selectionStart, a.selectionEnd, a.scrollLeft, a.scrollTop] : null,
|
|
29
|
+
window.scrollX, window.scrollY,
|
|
30
|
+
b ? b.childElementCount - (own ? 1 : 0) : 0,
|
|
31
|
+
b ? b.innerHTML.length - (own ? own.outerHTML.length : 0) : 0,
|
|
32
|
+
])
|
|
33
|
+
})()`,
|
|
34
|
+
})
|
|
35
|
+
return result.ok && typeof result.value === 'string' ? result.value : undefined
|
|
36
|
+
} catch {
|
|
37
|
+
return undefined
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function observedEffect(browser: NonNullable<Context['browser']>, session: BrowserSessionId, before: string | undefined): Promise<{ verified?: boolean; note?: string }> {
|
|
42
|
+
const after = await pageFingerprint(browser, session)
|
|
43
|
+
if (before === undefined || after === undefined) return { note: 'The effect could not be checked.' }
|
|
44
|
+
return before !== after
|
|
45
|
+
? { verified: true }
|
|
46
|
+
: { verified: false, note: 'No visible change observed; the effect is uncertain.' }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function effectText(value: { verified?: boolean; note?: string }): string {
|
|
50
|
+
return value.verified === true ? ' Visible change observed.' : ` ${value.note ?? 'The effect could not be checked.'}`
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Run a script in the page and return its value as text. */
|
|
54
|
+
export async function pageValue(browser: NonNullable<Context['browser']>, session: BrowserSessionId, script: string, signal?: AbortSignal): Promise<string> {
|
|
55
|
+
const result = await browser.execute(session, { script }, signal)
|
|
56
|
+
if (!result.ok) throw new Error(`page script failed: ${result.exception}`)
|
|
57
|
+
const raw = result.value
|
|
58
|
+
return typeof raw === 'string' ? raw : JSON.stringify(raw ?? null)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Fixed operations keep their inputs as data and preserve arbitrary-script permissions. */
|
|
62
|
+
export async function pageOperationValue(browser: NonNullable<Context['browser']>, session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<string> {
|
|
63
|
+
const result = typeof browser.pageOperation === 'function'
|
|
64
|
+
? await browser.pageOperation(session, request, signal)
|
|
65
|
+
: await browser.execute(session, { script: pageOperationScript(request) }, signal)
|
|
66
|
+
if (!result.ok) throw new Error('page operation failed: ' + result.exception)
|
|
67
|
+
return typeof result.value === 'string' ? result.value : JSON.stringify(result.value ?? null)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Install the fixed probe and report page failures immediately. */
|
|
71
|
+
export async function installProbe(browser: NonNullable<Context['browser']>, session: BrowserSessionId, signal?: AbortSignal): Promise<void> {
|
|
72
|
+
await pageOperationValue(browser, session, { operation: 'install' }, signal)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** One probe call, parsed. Throws when the probe is absent or the call failed. */
|
|
76
|
+
export async function probe<T = unknown>(
|
|
77
|
+
browser: NonNullable<Context['browser']>,
|
|
78
|
+
session: BrowserSessionId,
|
|
79
|
+
method: BrowserProbeMethod,
|
|
80
|
+
args: readonly unknown[] = [],
|
|
81
|
+
signal?: AbortSignal,
|
|
82
|
+
): Promise<T> {
|
|
83
|
+
const text = await pageOperationValue(browser, session, { operation: 'probe', method, args }, signal)
|
|
84
|
+
let parsed: unknown
|
|
85
|
+
try { parsed = JSON.parse(text) } catch { throw new Error(`page probe returned unreadable JSON: ${text.slice(0, 120)}`) }
|
|
86
|
+
if (parsed !== null && typeof parsed === 'object' && 'error' in (parsed as Record<string, unknown>)) {
|
|
87
|
+
throw new Error(`page probe: ${String((parsed as Record<string, unknown>).error)}`)
|
|
88
|
+
}
|
|
89
|
+
return parsed as T
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A probe call that survives a navigation inside a batch.
|
|
94
|
+
*
|
|
95
|
+
* Submitting a form replaces the document, and the probe with it, so a later step in the same
|
|
96
|
+
* batch would fail with `probe-not-installed` — measured on the first real benchmark run. One
|
|
97
|
+
* reinstall and one retry is enough: a second failure is a real absence, not a stale context.
|
|
98
|
+
*/
|
|
99
|
+
export async function probeLive<T = unknown>(
|
|
100
|
+
browser: NonNullable<Context['browser']>,
|
|
101
|
+
session: BrowserSessionId,
|
|
102
|
+
method: BrowserProbeMethod,
|
|
103
|
+
args: readonly unknown[] = [],
|
|
104
|
+
signal?: AbortSignal,
|
|
105
|
+
): Promise<T> {
|
|
106
|
+
try {
|
|
107
|
+
return await probe<T>(browser, session, method, args, signal)
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (!/probe-not-installed|probe-method-missing/.test(String(error))) throw error
|
|
110
|
+
await installProbe(browser, session, signal)
|
|
111
|
+
return await probe<T>(browser, session, method, args, signal)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Sleep. Long waits are capped by the caller, and the tool timeout still applies. */
|
|
116
|
+
export async function pause(ms: number): Promise<void> {
|
|
117
|
+
await new Promise<void>(resolve => { setTimeout(resolve, ms) })
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Poll until the callback returns something, or the budget runs out. */
|
|
121
|
+
export async function poll<T>(check: () => Promise<T | undefined>, budgetMs: number, intervalMs = 200): Promise<T | undefined> {
|
|
122
|
+
const deadline = Date.now() + budgetMs
|
|
123
|
+
for (;;) {
|
|
124
|
+
const value = await check()
|
|
125
|
+
if (value !== undefined) return value
|
|
126
|
+
const left = deadline - Date.now()
|
|
127
|
+
if (left <= 0) return undefined
|
|
128
|
+
// Timers may fire a millisecond before `Date.now()` reaches the deadline; the pause that
|
|
129
|
+
// reaches it is the last one, so it is followed by exactly one final check.
|
|
130
|
+
if (left <= intervalMs) {
|
|
131
|
+
await pause(left)
|
|
132
|
+
return await check()
|
|
133
|
+
}
|
|
134
|
+
await pause(intervalMs)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* One flat probe row: what a page can hand back through JSON.
|
|
140
|
+
*
|
|
141
|
+
* Concrete rather than `Record<string, unknown>`, because the tool output schema is a JSON value
|
|
142
|
+
* and the compiler (rightly) refuses to promise that an `unknown` is one.
|
|
143
|
+
*/
|
|
144
|
+
export type ProbeRow = Record<string, string | number | boolean | null>
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Run one `dsh_browser_check` specification against the page.
|
|
148
|
+
*
|
|
149
|
+
* Shared by the `check` tool and by the `{check: …}` step of `dsh_browser_do`, so a batch asserts
|
|
150
|
+
* exactly what a standalone call asserts.
|
|
151
|
+
*/
|
|
152
|
+
export async function runChecks(
|
|
153
|
+
browser: NonNullable<Context['browser']>,
|
|
154
|
+
session: BrowserSessionId,
|
|
155
|
+
spec: { readonly selector?: string; readonly text?: string; readonly url?: string; readonly js?: string },
|
|
156
|
+
signal?: AbortSignal,
|
|
157
|
+
): Promise<{ pass: boolean; checks: Array<{ kind: string; expected: string; actual: string; pass: boolean }> }> {
|
|
158
|
+
const checks: Array<{ kind: string; expected: string; actual: string; pass: boolean }> = []
|
|
159
|
+
if (spec.selector !== undefined) {
|
|
160
|
+
const found = await probeLive<{ described?: string } | null>(browser, session, 'find', [{ css: spec.selector }], signal)
|
|
161
|
+
checks.push({ kind: 'selector', expected: spec.selector, actual: found === null ? 'not found' : String(found.described ?? 'found'), pass: found !== null })
|
|
162
|
+
}
|
|
163
|
+
if (spec.text !== undefined) {
|
|
164
|
+
const present = await pageOperationValue(browser, session, { operation: 'text', text: spec.text }, signal)
|
|
165
|
+
const ok = present === 'true'
|
|
166
|
+
checks.push({ kind: 'text', expected: spec.text, actual: ok ? 'present' : 'absent', pass: ok })
|
|
167
|
+
}
|
|
168
|
+
if (spec.url !== undefined) {
|
|
169
|
+
const href = await pageOperationValue(browser, session, { operation: 'url' }, signal).then(text => text.replace(/^"|"$/g, ''))
|
|
170
|
+
const ok = href.includes(spec.url)
|
|
171
|
+
checks.push({ kind: 'url', expected: spec.url, actual: href, pass: ok })
|
|
172
|
+
}
|
|
173
|
+
if (spec.js !== undefined) {
|
|
174
|
+
try {
|
|
175
|
+
const value = await pageValue(browser, session, `(() => { try { return JSON.stringify({ ok: !!(${spec.js}) }) } catch (error) { return JSON.stringify({ ok: false, error: String(error) }) } })()`, signal)
|
|
176
|
+
const parsed = JSON.parse(value) as { ok?: boolean; error?: string }
|
|
177
|
+
checks.push({ kind: 'js', expected: spec.js, actual: parsed.ok === true ? 'truthy' : (parsed.error ?? 'falsy'), pass: parsed.ok === true })
|
|
178
|
+
} catch (error) {
|
|
179
|
+
checks.push({ kind: 'js', expected: spec.js, actual: String(error), pass: false })
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return { pass: checks.length > 0 && checks.every(check => check.pass), checks }
|
|
183
|
+
}
|