'use strict' const crypto = require('node:crypto') const { EVENT_TYPES } = require('../events/event-types.cjs') const browserIO = require('../network/browser-io.cjs') const { PAGE_CHANGED_CLEAR_REASONS } = require('../session/operations.cjs') const VISUAL_EVIDENCE_TTL_MS = 2 * 60 * 1000 class ClickOperations { async _elementForAction(entry, index, decisionToken = null, action = 'element') { const numeric = Number(index) if (!Number.isFinite(numeric)) throw new Error('index is required') if (decisionToken && typeof decisionToken === 'object') { this._assertDecisionToken( this._sessionIdForEntry(entry), { _fanDecisionToken: decisionToken, index: numeric }, action ) } if (!entry.selectorMap.get(numeric)) { // A tokenized model action may use only the exact map the model saw. The // legacy auto-observe path below is intentionally forbidden here: a new // page can reuse the same integer for an unrelated destructive control. if (decisionToken && typeof decisionToken === 'object') { const error = new Error( `Element index ${numeric} does not exist in the browser snapshot used for this decision. ` + 'The action was not executed; observe again and choose a fresh index.' ) error.code = 'ELEMENT_NOT_FOUND' error.details = { retryable: true, replanRequired: true, action: String(action || ''), index: numeric, current: this._browserDecisionToken(this._sessionIdForEntry(entry)) } throw error } // If the map was emptied because the PAGE changed (navigation/document // swap), the caller's index was minted against the previous page — // auto-re-observing here would silently re-mint indices on the NEW page // and act on the wrong element. Fail with a model-actionable error // instead. Maps emptied by same-page action clears (click/type/scroll) // keep the auto-observe convenience. if (entry.selectorMap.size === 0 && PAGE_CHANGED_CLEAR_REASONS.has(entry.selectorMap.reason)) { throw this._staleElementError( numeric, `Element index ${numeric} is stale: the page changed since the last observation ` + `(${entry.selectorMap.reason}). Observe again and use fresh element indices.`, action, { reason: entry.selectorMap.reason } ) } await this.observe(entry.id) } const element = entry.selectorMap.get(numeric) if (!element) { const error = new Error(`Element index ${numeric} is not available`) error.code = 'ELEMENT_NOT_FOUND' error.details = { retryable: true, replanRequired: true, action: String(action || ''), index: numeric } throw error } if (element.disabled) { const error = new Error(`Element index ${numeric} is disabled`) error.code = 'ELEMENT_DISABLED' error.details = { retryable: false, action: String(action || ''), index: numeric } throw error } return element } _staleElementError(index, message, action = 'element', details = {}) { const error = new Error(String(message || `Element index ${index} is stale`)) error.code = 'STALE_ELEMENT_REFERENCE' error.details = { retryable: true, replanRequired: true, action: String(action || ''), index: Number(index), ...details } return error } _isBrowserReplanError(error) { if (error?.details?.replanRequired === true) return true return new Set([ 'STALE_ELEMENT_REFERENCE', 'ELEMENT_NOT_FOUND', 'BROWSER_STATE_CHANGED', 'BROWSER_SESSION_MISMATCH' ]).has(String(error?.code || '')) } _failClosedClickError(element = {}, reason = 'unsafe-click', cause = null, provenance = {}) { const error = new Error( `Submit element index ${element.index} was not clicked because the native click path was unsafe (${reason}).` ) const hasBeforeDispatch = Object.prototype.hasOwnProperty.call(provenance, 'beforeDispatch') const hasDispatchAttempted = Object.prototype.hasOwnProperty.call(provenance, 'dispatchAttempted') error.code = 'FORM_SUBMIT_CLICK_UNSAFE' error.details = { retryable: true, replanRequired: true, dispatchAttempted: hasDispatchAttempted ? Boolean(provenance.dispatchAttempted) : false, action: 'formSubmit', reason: String(reason || 'unsafe-click'), index: Number(element.index) } const beforeDispatch = hasBeforeDispatch ? provenance.beforeDispatch : true if (beforeDispatch !== undefined) error.details.beforeDispatch = beforeDispatch if (cause) error.cause = cause return error } _elementFailureLooksStale(error) { const message = String(error?.message || error || '').toLowerCase() return [ 'element not found', 'element is detached', 'failed to resolve element', 'failed to resolve backend node', 'no node with given id', 'could not find node', 'cannot find context', 'execution context was destroyed' ].some(fragment => message.includes(fragment)) } _browserIndexTraceError(error) { const details = error?.details && typeof error.details === 'object' ? error.details : {} return { errorCode: error?.code == null ? null : String(error.code), errorMessage: String(error?.message || error || '').replace(/\s+/g, ' ').slice(0, 300), retryable: typeof details.retryable === 'boolean' ? details.retryable : null, replanRequired: typeof details.replanRequired === 'boolean' ? details.replanRequired : null } } _browserIndexTraceElement(element) { if (!element || typeof element !== 'object') return null return { index: Number.isFinite(Number(element.index)) ? Number(element.index) : null, backendNodeId: Number.isFinite(Number(element.backendNodeId)) ? Number(element.backendNodeId) : null, selectorIndex: Number.isFinite(Number(element.selectorIndex)) ? Number(element.selectorIndex) : null, hasSelector: Boolean(element.selector), frameSessionId: element.sessionId == null ? null : String(element.sessionId), source: element.source == null ? null : String(element.source), tag: element.tag == null ? null : String(element.tag), role: element.role == null ? null : String(element.role) } } _logBrowserIndexTrace(phase, entry, params = {}, element = null, extra = {}) { try { const sessionId = this._sessionIdForEntry(entry) const currentToken = this._browserDecisionToken(sessionId) const observed = entry?.lastObservationTrace || null const mutation = entry?.domMutationTrace || {} const currentMutationRevision = Math.max(0, Number(mutation.revision) || 0) const observedMutationRevision = Math.max(0, Number(observed?.mutationRevision) || 0) const documentState = this._documentStateSnapshot(entry) this.log( `[browser-index-trace] ${JSON.stringify({ phase: String(phase || 'unknown'), actionId: params?._fanActionTraceId == null ? null : String(params._fanActionTraceId), requestedIndex: Number.isFinite(Number(params?.index)) ? Number(params.index) : null, tabId: String(entry?.id || ''), target: this._browserIndexTraceElement(element), observation: observed, current: currentToken, currentDocument: { revision: Number(documentState.revision) || 0, frameId: String(documentState.frameId || ''), loaderId: String(documentState.loaderId || '') }, domMutations: { observedRevision: observedMutationRevision, currentRevision: currentMutationRevision, sinceObservation: Math.max(0, currentMutationRevision - observedMutationRevision), lastMethod: String(mutation.lastMethod || ''), lastAt: Number(mutation.lastAt) || 0, frameSessionId: mutation.sessionId == null ? null : String(mutation.sessionId) }, ...extra })}` ) } catch { // Diagnostic logging must never alter click behaviour. } } _viewportFromLayoutMetrics(metrics = {}) { const viewport = metrics.layoutViewport || metrics.visualViewport || {} const width = Number(viewport.clientWidth ?? viewport.width) const height = Number(viewport.clientHeight ?? viewport.height) return { width: Number.isFinite(width) && width > 0 ? width : 100000, height: Number.isFinite(height) && height > 0 ? height : 100000 } } _boundsFromQuad(quad) { if (!Array.isArray(quad) || quad.length < 8) return null const xs = [quad[0], quad[2], quad[4], quad[6]].map(Number) const ys = [quad[1], quad[3], quad[5], quad[7]].map(Number) if (xs.some(value => !Number.isFinite(value)) || ys.some(value => !Number.isFinite(value))) return null const left = Math.min(...xs) const right = Math.max(...xs) const top = Math.min(...ys) const bottom = Math.max(...ys) // CLK-1:四点质心(对齐 的 sum/4),用作点击落点。轴对齐矩形/平行四边形下 // 质心== bbox 中心(逐字节同),仅当 content-quad 因 3D/perspective 退化成非中心对称四边形时 // 才与 bbox 中心分歧——此时质心更稳(bbox 中心可能落在元素外/相邻元素上致遮挡误判)。 const cx = (xs[0] + xs[1] + xs[2] + xs[3]) / 4 const cy = (ys[0] + ys[1] + ys[2] + ys[3]) / 4 return { left, top, right, bottom, width: right - left, height: bottom - top, cx, cy } } _clickGeometryFromQuads(quads = [], viewport = this._viewportFromLayoutMetrics(), source = 'quad') { const candidates = quads .map(quad => this._boundsFromQuad(quad)) .filter(bounds => bounds && bounds.width > 0 && bounds.height > 0) if (!candidates.length) return null let best = candidates[0] let bestArea = -1 for (const bounds of candidates) { const visibleWidth = Math.max(0, Math.min(viewport.width, bounds.right) - Math.max(0, bounds.left)) const visibleHeight = Math.max(0, Math.min(viewport.height, bounds.bottom) - Math.max(0, bounds.top)) const visibleArea = visibleWidth * visibleHeight if (visibleArea > bestArea) { best = bounds bestArea = visibleArea } } // CLK-1:落点用四点质心(best.cx/cy),保留 viewport clamp;rect 仍用轴对齐 bbox(截图 clip 用) const x = Math.max(0, Math.min(viewport.width - 1, best.cx != null ? best.cx : (best.left + best.right) / 2)) const y = Math.max(0, Math.min(viewport.height - 1, best.cy != null ? best.cy : (best.top + best.bottom) / 2)) return { x, y, rect: { left: best.left, top: best.top, width: best.width, height: best.height }, source } } // CLK-7:统一的点击派发序列。mouseMoved 后等 50ms、mousePressed 后等 80ms // default_action_watchdog.py:914/932 的 sleep0.05/0.08),给出真实的 mousedown 持续时间—— // 个别按 mousedown 时长判 click/长按的控件需要它。抽成 helper 避免三/四处复制漂移(参考 // INPUT/DD 双路径漂移教训)。 async _dispatchClickSequence( entry, x, y, sessionId, decisionGuard = null, beforeClick = null, expectedInputEvent = false ) { if (decisionGuard) decisionGuard() await this._humanMouseTrajectory(entry, x, y, sessionId, undefined, decisionGuard) if (decisionGuard) decisionGuard() await entry.client.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y }, sessionId) await this._sleep(50) if (decisionGuard) decisionGuard() await this._markActingOn(entry.client, sessionId) if (decisionGuard) decisionGuard() if (typeof beforeClick === 'function') { await beforeClick({ x, y, sessionId }) if (decisionGuard) decisionGuard() } await entry.client.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 }, sessionId) await this._sleep(80) // Once mousePressed has been sent, always pair it with mouseReleased. A // mousedown handler may itself navigate, and abandoning the release would // leave Chromium's input state stuck. The lease is checked immediately // before the press, which is the irreversible action boundary. await entry.client.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1, ...(expectedInputEvent ? { _fanExpectedInputEvent: true } : {}) }, sessionId) } // 稳定性沉降:在页面内用 requestAnimationFrame 反复采样目标 bbox,直到连续两帧完全一致(动画已停), // 或到 clickStabilityMaxMs 超时。对齐 Playwright 'stable' / Cypress 动画结束检测——避免在动画中(滑入弹窗、 // 展开菜单)取坐标后元素移位导致点偏。静态元素 ~2 帧即返回(比固定 50ms 死等更快),动画元素才多等。 // 永不抛错;解析/执行失败 → 直接返回(退回原有时序,不打断点击)。 async _waitElementStable(entry, backendNodeId, sessionId) { const maxMs = Number(this.clickStabilityMaxMs) || 0 if (maxMs <= 0) return false try { const r = await this._usingResolvedBackendNode(entry, backendNodeId, sessionId, objectId => ( entry.client.send('Runtime.callFunctionOn', { objectId, functionDeclaration: `function(maxMs) { return new Promise((resolve) => { const el = this; const clock = () => (typeof performance !== 'undefined' ? performance.now() : Date.now()); const t0 = clock(); let done = false; const finish = (v) => { if (!done) { done = true; resolve(v); } }; // 硬超时:不依赖 rAF——后台/隐藏标签会把 rAF 节流甚至暂停,此 setTimeout 保证最迟 maxMs 返回。 setTimeout(() => finish({ stable: false, waitedMs: clock() - t0, timedOut: true }), maxMs); let prev = null; const sample = () => { if (done) return; const rc = el.getBoundingClientRect(); const cur = rc.left + ',' + rc.top + ',' + rc.width + ',' + rc.height; if (prev !== null && cur === prev) { finish({ stable: true, waitedMs: clock() - t0 }); return; } prev = cur; requestAnimationFrame(sample); }; requestAnimationFrame(sample); }); }`, arguments: [{ value: maxMs }], awaitPromise: true, returnByValue: true }, sessionId).catch(() => null) )) return Boolean(r?.result?.value?.stable) } catch (e) { void e return false } } async _backendNodeClickGeometry(entry, element = {}, sessionId = undefined) { const backendNodeId = Number(element.backendNodeId) if (!Number.isFinite(backendNodeId)) return null await entry.client.send('DOM.scrollIntoViewIfNeeded', { backendNodeId }, sessionId).catch(() => undefined) // 等动画沉降(连续两帧 bbox 一致)再取坐标,取代固定 50ms 死等。 await this._waitElementStable(entry, backendNodeId, sessionId) const metrics = await entry.client.send('Page.getLayoutMetrics', {}, sessionId).catch(() => ({})) const viewport = this._viewportFromLayoutMetrics(metrics) const contentQuads = await entry.client .send('DOM.getContentQuads', { backendNodeId }, sessionId) .catch(() => null) const contentGeometry = this._clickGeometryFromQuads(contentQuads?.quads || [], viewport, 'contentQuads') if (contentGeometry) return contentGeometry const boxModel = await entry.client.send('DOM.getBoxModel', { backendNodeId }, sessionId).catch(() => null) const contentBox = boxModel?.model?.content const boxGeometry = this._clickGeometryFromQuads(contentBox ? [contentBox] : [], viewport, 'boxModel') if (boxGeometry) return boxGeometry const rectResult = await this._usingResolvedBackendNode(entry, backendNodeId, sessionId, objectId => ( entry.client.send('Runtime.callFunctionOn', { objectId, functionDeclaration: `function() { let rect = this.getBoundingClientRect(); // Fix B:元素自身无盒模型(0 尺寸——刚出现/动画中的图标按钮