Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

removed PERF_METRICS for nicer code view

Gregor Žunič3a50681e26d7
diff --git a/browser_use/dom/buildDomTree.js b/browser_use/dom/buildDomTree.js
index a1b63833f..8a7af4941 100644
--- a/browser_use/dom/buildDomTree.js
+++ b/browser_use/dom/buildDomTree.js
@@ -9,98 +9,6 @@
const { doHighlightElements, focusHighlightIndex, viewportExpansion, debugMode } = args;
let highlightIndex = 0; // Reset highlight index
- // Add timing stack to handle recursion
- const TIMING_STACK = {
- nodeProcessing: [],
- treeTraversal: [],
- highlighting: [],
- current: null
- };
-
- function pushTiming(type) {
- TIMING_STACK[type] = TIMING_STACK[type] || [];
- TIMING_STACK[type].push(performance.now());
- }
-
- function popTiming(type) {
- const start = TIMING_STACK[type].pop();
- const duration = performance.now() - start;
- return duration;
- }
-
- // Only initialize performance tracking if in debug mode
- const PERF_METRICS = debugMode ? {
- buildDomTreeCalls: 0,
- timings: {
- buildDomTree: 0,
- highlightElement: 0,
- isInteractiveElement: 0,
- isElementVisible: 0,
- isTopElement: 0,
- isInExpandedViewport: 0,
- isTextNodeVisible: 0,
- getEffectiveScroll: 0,
- },
- cacheMetrics: {
- boundingRectCacheHits: 0,
- boundingRectCacheMisses: 0,
- computedStyleCacheHits: 0,
- computedStyleCacheMisses: 0,
- getBoundingClientRectTime: 0,
- getComputedStyleTime: 0,
- boundingRectHitRate: 0,
- computedStyleHitRate: 0,
- overallHitRate: 0,
- clientRectsCacheHits: 0,
- clientRectsCacheMisses: 0,
- },
- nodeMetrics: {
- totalNodes: 0,
- processedNodes: 0,
- skippedNodes: 0,
- },
- buildDomTreeBreakdown: {
- totalTime: 0,
- totalSelfTime: 0,
- buildDomTreeCalls: 0,
- domOperations: {
- getBoundingClientRect: 0,
- getComputedStyle: 0,
- },
- domOperationCounts: {
- getBoundingClientRect: 0,
- getComputedStyle: 0,
- }
- }
- } : null;
-
- // Simple timing helper that only runs in debug mode
- function measureTime(fn) {
- if (!debugMode) return fn;
- return function (...args) {
- const start = performance.now();
- const result = fn.apply(this, args);
- const duration = performance.now() - start;
- return result;
- };
- }
-
- // Helper to measure DOM operations
- function measureDomOperation(operation, name) {
- if (!debugMode) return operation();
-
- const start = performance.now();
- const result = operation();
- const duration = performance.now() - start;
-
- if (PERF_METRICS && name in PERF_METRICS.buildDomTreeBreakdown.domOperations) {
- PERF_METRICS.buildDomTreeBreakdown.domOperations[name] += duration;
- PERF_METRICS.buildDomTreeBreakdown.domOperationCounts[name]++;
- }
-
- return result;
- }
-
// Add caching mechanisms at the top level
const DOM_CACHE = {
boundingRects: new WeakMap(),
@@ -118,28 +26,10 @@
if (!element) return null;
if (DOM_CACHE.boundingRects.has(element)) {
- if (debugMode && PERF_METRICS) {
- PERF_METRICS.cacheMetrics.boundingRectCacheHits++;
- }
return DOM_CACHE.boundingRects.get(element);
}
- if (debugMode && PERF_METRICS) {
- PERF_METRICS.cacheMetrics.boundingRectCacheMisses++;
- }
-
- let rect;
- if (debugMode) {
- const start = performance.now();
- rect = element.getBoundingClientRect();
- const duration = performance.now() - start;
- if (PERF_METRICS) {
- PERF_METRICS.buildDomTreeBreakdown.domOperations.getBoundingClientRect += duration;
- PERF_METRICS.buildDomTreeBreakdown.domOperationCounts.getBoundingClientRect++;
- }
- } else {
- rect = element.getBoundingClientRect();
- }
+ const rect = element.getBoundingClientRect();
if (rect) {
DOM_CACHE.boundingRects.set(element, rect);
@@ -151,28 +41,10 @@
if (!element) return null;
if (DOM_CACHE.computedStyles.has(element)) {
- if (debugMode && PERF_METRICS) {
- PERF_METRICS.cacheMetrics.computedStyleCacheHits++;
- }
return DOM_CACHE.computedStyles.get(element);
}
- if (debugMode && PERF_METRICS) {
- PERF_METRICS.cacheMetrics.computedStyleCacheMisses++;
- }
-
- let style;
- if (debugMode) {
- const start = performance.now();
- style = window.getComputedStyle(element);
- const duration = performance.now() - start;
- if (PERF_METRICS) {
- PERF_METRICS.buildDomTreeBreakdown.domOperations.getComputedStyle += duration;
- PERF_METRICS.buildDomTreeBreakdown.domOperationCounts.getComputedStyle++;
- }
- } else {
- style = window.getComputedStyle(element);
- }
+ const style = window.getComputedStyle(element);
if (style) {
DOM_CACHE.computedStyles.set(element, style);
@@ -183,20 +55,13 @@
// Add a new function to get cached client rects
function getCachedClientRects(element) {
if (!element) return null;
-
+
if (DOM_CACHE.clientRects.has(element)) {
- if (debugMode && PERF_METRICS) {
- PERF_METRICS.cacheMetrics.clientRectsCacheHits++;
- }
return DOM_CACHE.clientRects.get(element);
}
-
- if (debugMode && PERF_METRICS) {
- PERF_METRICS.cacheMetrics.clientRectsCacheMisses++;
- }
-
+
const rects = element.getClientRects();
-
+
if (rects) {
DOM_CACHE.clientRects.set(element, rects);
}
@@ -231,8 +96,6 @@
* Highlights an element in the DOM and returns the index of the next element.
*/
function highlightElement(element, index, parentIframe = null) {
- pushTiming('highlighting');
-
if (!element) return index;
// Store overlays and the single label for updating
@@ -432,7 +295,7 @@
const throttledUpdatePositions = throttleFunction(updatePositions, 16); // ~60fps
window.addEventListener('scroll', throttledUpdatePositions, true);
window.addEventListener('resize', throttledUpdatePositions);
-
+
// Add cleanup function
cleanupFn = () => {
window.removeEventListener('scroll', throttledUpdatePositions, true);
@@ -441,13 +304,12 @@
overlays.forEach(overlay => overlay.element.remove());
if (label) label.remove();
};
-
+
// Then add fragment to container in one operation
container.appendChild(fragment);
-
+
return index + 1;
} finally {
- popTiming('highlighting');
// Store cleanup function for later use
if (cleanupFn) {
// Keep a reference to cleanup functions in a global array
@@ -462,7 +324,7 @@
window._highlightCleanupFunctions.forEach(fn => fn());
window._highlightCleanupFunctions = [];
}
-
+
// Also remove the container
const container = document.getElementById(HIGHLIGHT_CONTAINER_ID);
if (container) container.remove();
@@ -472,16 +334,16 @@
if (!currentElement.parentElement) {
return 0; // No parent means no siblings
}
-
+
const tagName = currentElement.nodeName.toLowerCase();
-
+
const siblings = Array.from(currentElement.parentElement.children)
.filter((sib) => sib.nodeName.toLowerCase() === tagName);
-
+
if (siblings.length === 1) {
return 0; // Only element of its type
}
-
+
const index = siblings.indexOf(currentElement) + 1; // 1-based index
return index;
}
@@ -491,7 +353,7 @@
*/
function getXPathTree(element, stopAtBoundary = true) {
if (xpathCache.has(element)) return xpathCache.get(element);
-
+
const segments = [];
let currentElement = element;
@@ -542,7 +404,7 @@
style.opacity !== '0';
}
}
-
+
const range = document.createRange();
range.selectNodeContents(textNode);
const rects = range.getClientRects(); // Use getClientRects for Range
@@ -784,7 +646,7 @@
if (element.getAttribute("contenteditable") === "true" || element.isContentEditable) {
return true;
}
-
+
// Added enhancement to capture dropdown interactive elements
if (element.classList && (
element.classList.contains("button") ||
@@ -839,22 +701,22 @@
const getEventListenersForNode = element?.ownerDocument?.defaultView?.getEventListenersForNode || window.getEventListenersForNode;
if (typeof getEventListenersForNode === 'function') {
const listeners = getEventListenersForNode(element);
- const interactionEvents = ['click', 'mousedown', 'mouseup', 'keydown', 'keyup', 'submit', 'change', 'input', 'focus', 'blur'];
- for (const eventType of interactionEvents) {
- for (const listener of listeners) {
- if (listener.type === eventType) {
- return true; // Found a common interaction listener
- }
+ const interactionEvents = ['click', 'mousedown', 'mouseup', 'keydown', 'keyup', 'submit', 'change', 'input', 'focus', 'blur'];
+ for (const eventType of interactionEvents) {
+ for (const listener of listeners) {
+ if (listener.type === eventType) {
+ return true; // Found a common interaction listener
}
}
+ }
}
// Fallback: Check common event attributes if getEventListeners is not available (getEventListeners doesn't work in page.evaluate context)
- const commonMouseAttrs = ['onclick', 'onmousedown', 'onmouseup', 'ondblclick'];
- for (const attr of commonMouseAttrs) {
- if (element.hasAttribute(attr) || typeof element[attr] === 'function') {
- return true;
- }
+ const commonMouseAttrs = ['onclick', 'onmousedown', 'onmouseup', 'ondblclick'];
+ for (const attr of commonMouseAttrs) {
+ if (element.hasAttribute(attr) || typeof element[attr] === 'function') {
+ return true;
}
+ }
} catch (e) {
// console.warn(`Could not check event listeners for ${element.tagName}:`, e);
// If checking listeners fails, rely on other checks
@@ -872,7 +734,7 @@
if (viewportExpansion === -1) {
return true;
}
-
+
const rects = getCachedClientRects(element); // Replace element.getClientRects()
if (!rects || rects.length === 0) {
@@ -913,10 +775,7 @@
const centerY = rects[Math.floor(rects.length / 2)].top + rects[Math.floor(rects.length / 2)].height / 2;
try {
- const topEl = measureDomOperation(
- () => shadowRoot.elementFromPoint(centerX, centerY),
- 'elementFromPoint'
- );
+ const topEl = shadowRoot.elementFromPoint(centerX, centerY);
if (!topEl) return false;
let current = topEl;
@@ -997,20 +856,18 @@
let scrollX = 0;
let scrollY = 0;
- return measureDomOperation(() => {
- while (currentEl && currentEl !== document.documentElement) {
- if (currentEl.scrollLeft || currentEl.scrollTop) {
- scrollX += currentEl.scrollLeft;
- scrollY += currentEl.scrollTop;
- }
- currentEl = currentEl.parentElement;
+ while (currentEl && currentEl !== document.documentElement) {
+ if (currentEl.scrollLeft || currentEl.scrollTop) {
+ scrollX += currentEl.scrollLeft;
+ scrollY += currentEl.scrollTop;
}
+ currentEl = currentEl.parentElement;
+ }
- scrollX += window.scrollX;
- scrollY += window.scrollY;
+ scrollX += window.scrollX;
+ scrollY += window.scrollY;
- return { scrollX, scrollY };
- }, 'scrollOperations');
+ return { scrollX, scrollY };
}
// Add these helper functions at the top level
@@ -1126,7 +983,7 @@
if (element.hasAttribute('onclick') || typeof element.onclick === 'function') {
return true;
}
-
+
// Check for other common interaction event listeners
try {
const getEventListenersForNode = element?.ownerDocument?.defaultView?.getEventListenersForNode || window.getEventListenersForNode;
@@ -1136,16 +993,16 @@
for (const eventType of interactionEvents) {
for (const listener of listeners) {
if (listener.type === eventType) {
- return true; // Found a common interaction listener
+ return true; // Found a common interaction listener
}
}
}
}
// Fallback: Check common event attributes if getEventListeners is not available (getEventListenersForNode doesn't work in page.evaluate context)
- const commonEventAttrs = ['onmousedown', 'onmouseup', 'onkeydown', 'onkeyup', 'onsubmit', 'onchange', 'oninput', 'onfocus', 'onblur'];
- if (commonEventAttrs.some(attr => element.hasAttribute(attr))) {
- return true;
- }
+ const commonEventAttrs = ['onmousedown', 'onmouseup', 'onkeydown', 'onkeyup', 'onsubmit', 'onchange', 'oninput', 'onfocus', 'onblur'];
+ if (commonEventAttrs.some(attr => element.hasAttribute(attr))) {
+ return true;
+ }
} catch (e) {
// console.warn(`Could not check event listeners for ${element.tagName}:`, e);
// If checking listeners fails, rely on other checks
@@ -1185,7 +1042,7 @@
if (shouldHighlight) {
// Check viewport status before assigning index and highlighting
nodeData.isInViewport = isInExpandedViewport(node, viewportExpansion);
-
+
// When viewportExpansion is -1, all interactive elements should get a highlight index
// regardless of viewport status
if (nodeData.isInViewport || viewportExpansion === -1) {
@@ -1214,16 +1071,12 @@
*/
function buildDomTree(node, parentIframe = null, isParentHighlighted = false) {
// Fast rejection checks first
- if (!node || node.id === HIGHLIGHT_CONTAINER_ID ||
- (node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE)) {
- if (debugMode) PERF_METRICS.nodeMetrics.skippedNodes++;
+ if (!node || node.id === HIGHLIGHT_CONTAINER_ID ||
+ (node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE)) {
return null;
}
- if (debugMode) PERF_METRICS.nodeMetrics.totalNodes++;
-
if (!node || node.id === HIGHLIGHT_CONTAINER_ID) {
- if (debugMode) PERF_METRICS.nodeMetrics.skippedNodes++;
return null;
}
@@ -1244,13 +1097,11 @@
const id = `${ID.current++}`;
DOM_HASH_MAP[id] = nodeData;
- if (debugMode) PERF_METRICS.nodeMetrics.processedNodes++;
return id;
}
// Early bailout for non-element nodes except text
if (node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE) {
- if (debugMode) PERF_METRICS.nodeMetrics.skippedNodes++;
return null;
}
@@ -1258,14 +1109,12 @@
if (node.nodeType === Node.TEXT_NODE) {
const textContent = node.textContent.trim();
if (!textContent) {
- if (debugMode) PERF_METRICS.nodeMetrics.skippedNodes++;
return null;
}
// Only check visibility for text nodes that might be visible
const parentElement = node.parentElement;
if (!parentElement || parentElement.tagName.toLowerCase() === 'script') {
- if (debugMode) PERF_METRICS.nodeMetrics.skippedNodes++;
return null;
}
@@ -1275,13 +1124,11 @@
text: textContent,
isVisible: isTextNodeVisible(node),
};
- if (debugMode) PERF_METRICS.nodeMetrics.processedNodes++;
return id;
}
// Quick checks for element nodes
if (node.nodeType === Node.ELEMENT_NODE && !isElementAccepted(node)) {
- if (debugMode) PERF_METRICS.nodeMetrics.skippedNodes++;
return null;
}
@@ -1305,7 +1152,6 @@
rect.left > window.innerWidth + viewportExpansion
))) {
// console.log("Skipping node outside viewport (quick check):", node.tagName, rect);
- if (debugMode) PERF_METRICS.nodeMetrics.skippedNodes++;
return null;
}
}
@@ -1396,85 +1242,21 @@
// Check if the anchor has actual dimensions
const rect = getCachedBoundingRect(node);
const hasSize = (rect && rect.width > 0 && rect.height > 0) || (node.offsetWidth > 0 || node.offsetHeight > 0);
-
+
if (!hasSize) {
- if (debugMode) PERF_METRICS.nodeMetrics.skippedNodes++;
return null;
}
}
const id = `${ID.current++}`;
DOM_HASH_MAP[id] = nodeData;
- if (debugMode) PERF_METRICS.nodeMetrics.processedNodes++;
return id;
}
- // After all functions are defined, wrap them with performance measurement
- // Remove buildDomTree from here as we measure it separately
- highlightElement = measureTime(highlightElement);
- isInteractiveElement = measureTime(isInteractiveElement);
- isElementVisible = measureTime(isElementVisible);
- isTopElement = measureTime(isTopElement);
- isInExpandedViewport = measureTime(isInExpandedViewport);
- isTextNodeVisible = measureTime(isTextNodeVisible);
- getEffectiveScroll = measureTime(getEffectiveScroll);
-
const rootId = buildDomTree(document.body);
// Clear the cache before starting
DOM_CACHE.clearCache();
- // Only process metrics in debug mode
- if (debugMode && PERF_METRICS) {
- // Convert timings to seconds and add useful derived metrics
- Object.keys(PERF_METRICS.timings).forEach(key => {
- PERF_METRICS.timings[key] = PERF_METRICS.timings[key] / 1000;
- });
-
- Object.keys(PERF_METRICS.buildDomTreeBreakdown).forEach(key => {
- if (typeof PERF_METRICS.buildDomTreeBreakdown[key] === 'number') {
- PERF_METRICS.buildDomTreeBreakdown[key] = PERF_METRICS.buildDomTreeBreakdown[key] / 1000;
- }
- });
-
- // Add some useful derived metrics
- if (PERF_METRICS.buildDomTreeBreakdown.buildDomTreeCalls > 0) {
- PERF_METRICS.buildDomTreeBreakdown.averageTimePerNode =
- PERF_METRICS.buildDomTreeBreakdown.totalTime / PERF_METRICS.buildDomTreeBreakdown.buildDomTreeCalls;
- }
-
- PERF_METRICS.buildDomTreeBreakdown.timeInChildCalls =
- PERF_METRICS.buildDomTreeBreakdown.totalTime - PERF_METRICS.buildDomTreeBreakdown.totalSelfTime;
-
- // Add average time per operation to the metrics
- Object.keys(PERF_METRICS.buildDomTreeBreakdown.domOperations).forEach(op => {
- const time = PERF_METRICS.buildDomTreeBreakdown.domOperations[op];
- const count = PERF_METRICS.buildDomTreeBreakdown.domOperationCounts[op];
- if (count > 0) {
- PERF_METRICS.buildDomTreeBreakdown.domOperations[`${op}Average`] = time / count;
- }
- });
-
- // Calculate cache hit rates
- const boundingRectTotal = PERF_METRICS.cacheMetrics.boundingRectCacheHits + PERF_METRICS.cacheMetrics.boundingRectCacheMisses;
- const computedStyleTotal = PERF_METRICS.cacheMetrics.computedStyleCacheHits + PERF_METRICS.cacheMetrics.computedStyleCacheMisses;
-
- if (boundingRectTotal > 0) {
- PERF_METRICS.cacheMetrics.boundingRectHitRate = PERF_METRICS.cacheMetrics.boundingRectCacheHits / boundingRectTotal;
- }
-
- if (computedStyleTotal > 0) {
- PERF_METRICS.cacheMetrics.computedStyleHitRate = PERF_METRICS.cacheMetrics.computedStyleCacheHits / computedStyleTotal;
- }
-
- if ((boundingRectTotal + computedStyleTotal) > 0) {
- PERF_METRICS.cacheMetrics.overallHitRate =
- (PERF_METRICS.cacheMetrics.boundingRectCacheHits + PERF_METRICS.cacheMetrics.computedStyleCacheHits) /
- (boundingRectTotal + computedStyleTotal);
- }
- }
-
- return debugMode ?
- { rootId, map: DOM_HASH_MAP, perfMetrics: PERF_METRICS } :
- { rootId, map: DOM_HASH_MAP };
+ return { rootId, map: DOM_HASH_MAP };
};
diff --git a/tests/old/extraction_test.py b/tests/old/extraction_test.py
index 59f8fc332..e2f61cf51 100644
--- a/tests/old/extraction_test.py
+++ b/tests/old/extraction_test.py
@@ -31,12 +31,13 @@ async def test_focus_vs_all_elements():
# executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
disable_security=True,
wait_for_network_idle_page_load_time=1,
- headless=True,
+ headless=False,
)
)
websites = [
- 'https://demos.telerik.com/kendo-react-ui/treeview/overview/basic/func?theme=default-ocean-blue-a11y',
+ # 'https://demos.telerik.com/kendo-react-ui/treeview/overview/basic/func?theme=default-ocean-blue-a11y',
+ 'https://google.com',
'https://www.ycombinator.com/companies',
'https://kayak.com/flights',
# 'https://en.wikipedia.org/wiki/Humanist_Party_of_Ontario',
@@ -50,7 +51,6 @@ async def test_focus_vs_all_elements():
'https://reddit.com',
'https://codepen.io/geheimschriftstift/pen/mPLvQz',
'https://www.google.com/search?q=google+hi&oq=google+hi&gs_lcrp=EgZjaHJvbWUyBggAEEUYOTIGCAEQRRhA0gEIMjI2NmowajSoAgCwAgE&sourceid=chrome&ie=UTF-8',
- 'https://google.com',
'https://amazon.com',
'https://github.com',
]
@@ -80,7 +80,7 @@ async def test_focus_vs_all_elements():
# print(all_elements_state.element_tree.clickable_elements_to_string())
prompt = AgentMessagePrompt(
browser_state_summary=all_elements_state,
- file_system=FileSystem(dir_path='./tmp'),
+ file_system=FileSystem(base_dir='./tmp'),
include_attributes=DEFAULT_INCLUDE_ATTRIBUTES,
step_info=None,
)