Skip to content

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

try js click before quads click

Nick Sweetinge7fb8aa376e4
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index ddd3a1c50..82473d642 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -1186,7 +1186,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# Look for common URL patterns
patterns = [
r'https?://[^\s<>"\']+', # Full URLs with http/https
- r'(?:www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(?:/[^\s<>"\']*)?', # Domain names with optional paths
+ r'(?:www\.)?[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}(?:/[^\s<>"\']*)?', # Domain names with subdomains and optional paths
]
for pattern in patterns:
@@ -1777,6 +1777,22 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# Force garbage collection
gc.collect()
+ # Debug: Log remaining threads and asyncio tasks
+ import threading
+ threads = threading.enumerate()
+ self.logger.debug(f'🧵 Remaining threads ({len(threads)}): {[t.name for t in threads]}')
+
+ # Get all asyncio tasks
+ tasks = asyncio.all_tasks(asyncio.get_event_loop())
+ # Filter out the current task (this close() coroutine)
+ other_tasks = [t for t in tasks if t != asyncio.current_task()]
+ if other_tasks:
+ self.logger.debug(f'⚡ Remaining asyncio tasks ({len(other_tasks)}):')
+ for task in other_tasks[:10]: # Limit to first 10 to avoid spam
+ self.logger.debug(f' - {task.get_name()}: {task}')
+ else:
+ self.logger.debug('⚡ No remaining asyncio tasks')
+
except Exception as e:
self.logger.error(f'Error during cleanup: {e}')
diff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.py
index 94b1b0ec7..d2139a074 100644
--- a/browser_use/browser/crash_watchdog.py
+++ b/browser_use/browser/crash_watchdog.py
@@ -171,7 +171,7 @@ class CrashWatchdog(BaseWatchdog):
cdp_client = self.browser_session.cdp_client
targets = await cdp_client.send.Target.getTargets()
target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)
- if target_info and target_info['targetId'] == self.browser_session.cdp_session.target_id:
+ if target_info and self.browser_session.cdp_session and target_info['targetId'] == self.browser_session.cdp_session.target_id:
self.browser_session.cdp_session.target_id = None # type: ignore
self.browser_session.cdp_session.session_id = None # type: ignore
self.logger.error(
diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.py
index 9e24167ba..5d6313eee 100644
--- a/browser_use/browser/default_action_watchdog.py
+++ b/browser_use/browser/default_action_watchdog.py
@@ -188,10 +188,38 @@ class DefaultActionWatchdog(BaseWatchdog):
Returns:
The download path if a download was triggered, None otherwise
"""
+ cdp_session = await self.browser_session.attach_cdp_session()
+
+ session_id = element_node.session_id
+ backend_node_id = element_node.backend_node_id
+
+ # do JS click first because quads click isnt good enough yet
+ try:
+ result = await cdp_session.cdp_client.send.DOM.resolveNode(
+ params={'backendNodeId': backend_node_id},
+ session_id=session_id,
+ )
+ assert 'object' in result and 'objectId' in result['object'], (
+ 'Failed to find DOM element based on backendNodeId, maybe page content changed?'
+ )
+ object_id = result['object']['objectId']
+
+ await cdp_session.cdp_client.send.Runtime.callFunctionOn(
+ params={
+ 'functionDeclaration': 'function() { this.click(); }',
+ 'objectId': object_id,
+ },
+ session_id=session_id,
+ )
+ await asyncio.sleep(0.5)
+ # Navigation is handled by NavigationWatchdog via events
+ return None
+ except Exception as js_e:
+ self.logger.error(f'CDP JavaScript click also failed: {js_e}')
+ raise Exception(f'Failed to click element: {js_e}')
try:
# Get CDP client
- cdp_session = await self.browser_session.attach_cdp_session()
# Get the correct session ID for the element's frame
# session_id = await self._get_session_id_for_element(element_node)
@@ -338,34 +366,34 @@ class DefaultActionWatchdog(BaseWatchdog):
# # Navigation is handled by NavigationWatchdog via events
# return download_path
- # raise Exception('Quad click isnt perfect yet especially for multi-action sequences where navigation dropdowns move around, additional JavaScript click is needed')
+ raise Exception('Quad click isnt perfect yet especially for multi-action sequences where navigation dropdowns move around, additional JavaScript click is needed')
except Exception as e:
self.logger.warning(f'CDP click failed: {type(e).__name__}: {e}')
# Fall back to JavaScript click via CDP
- try:
- result = await cdp_session.cdp_client.send.DOM.resolveNode(
- params={'backendNodeId': backend_node_id},
- session_id=session_id,
- )
- assert 'object' in result and 'objectId' in result['object'], (
- 'Failed to find DOM element based on backendNodeId, maybe page content changed?'
- )
- object_id = result['object']['objectId']
-
- await cdp_session.cdp_client.send.Runtime.callFunctionOn(
- params={
- 'functionDeclaration': 'function() { this.click(); }',
- 'objectId': object_id,
- },
- session_id=session_id,
- )
- await asyncio.sleep(0.5)
- # Navigation is handled by NavigationWatchdog via events
- return None
- except Exception as js_e:
- self.logger.error(f'CDP JavaScript click also failed: {js_e}')
- raise Exception(f'Failed to click element: {e}')
+ # try:
+ # result = await cdp_session.cdp_client.send.DOM.resolveNode(
+ # params={'backendNodeId': backend_node_id},
+ # session_id=session_id,
+ # )
+ # assert 'object' in result and 'objectId' in result['object'], (
+ # 'Failed to find DOM element based on backendNodeId, maybe page content changed?'
+ # )
+ # object_id = result['object']['objectId']
+
+ # await cdp_session.cdp_client.send.Runtime.callFunctionOn(
+ # params={
+ # 'functionDeclaration': 'function() { this.click(); }',
+ # 'objectId': object_id,
+ # },
+ # session_id=session_id,
+ # )
+ # await asyncio.sleep(0.5)
+ # # Navigation is handled by NavigationWatchdog via events
+ # return None
+ # except Exception as js_e:
+ # self.logger.error(f'CDP JavaScript click also failed: {js_e}')
+ raise Exception(f'Failed to click element: {e}')
except URLNotAllowedError as e:
raise e
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.py
index aa4f1ef09..bb975c90a 100644
--- a/browser_use/browser/downloads_watchdog.py
+++ b/browser_use/browser/downloads_watchdog.py
@@ -198,7 +198,7 @@ class DownloadsWatchdog(BaseWatchdog):
self.event_bus.dispatch(
FileDownloadedEvent(
url=str(path), # Use the file path as URL for local files
- file_path=str(path),
+ path=str(path),
file_name=path.name,
file_size=file_size,
)
@@ -208,7 +208,7 @@ class DownloadsWatchdog(BaseWatchdog):
except Exception as e:
self.logger.error(f'[DownloadsWatchdog] Error tracking download: {e}')
- async def _handle_cdp_download(self, event: dict, target_id: str, session_id: str) -> None:
+ async def _handle_cdp_download(self, event: dict, target_id: str, session_id: str | None) -> None:
"""Handle a CDP Page.downloadWillBegin event."""
try:
download_url = event.get('url', '')
@@ -271,7 +271,7 @@ class DownloadsWatchdog(BaseWatchdog):
'awaitPromise': True,
'returnByValue': True,
},
- session_id=session_id,
+ session_id=session_id if session_id else None,
)
download_result = result.get('result', {}).get('value')
diff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.py
index 6a4a73676..e18e8b526 100644
--- a/browser_use/browser/navigation_watchdog.py
+++ b/browser_use/browser/navigation_watchdog.py
@@ -64,8 +64,8 @@ class NavigationWatchdog(BaseWatchdog):
"""Clear agent focus when browser stops."""
# Clear target handlers
self._target_close_handlers.clear()
- assert self.browser_session.cdp_session is not None, 'No current target ID'
- self.browser_session.cdp_session.target_id = None
+ if self.browser_session.cdp_session:
+ self.browser_session.cdp_session.target_id = None
# ========== Tab Lifecycle Events ==========
@@ -525,9 +525,10 @@ class NavigationWatchdog(BaseWatchdog):
targets = await self.browser_session._cdp_get_all_pages()
if targets:
# Focus on the last target (most recently created)
- self.browser_session.cdp_session.target_id = targets[-1]['targetId']
+ if self.browser_session.cdp_session:
+ self.browser_session.cdp_session.target_id = targets[-1]['targetId']
await self._dispatch_focus_changed()
- target_url = await self._get_target_url(self.browser_session.cdp_session.target_id)
+ target_url = await self._get_target_url(self.browser_session.cdp_session.target_id if self.browser_session.cdp_session else None)
tab_index = await self._get_current_tab_index()
self.logger.info(f'[NavigationWatchdog] 👀 Agent focus moved to new tab {tab_index}: {target_url}')
@@ -535,9 +536,10 @@ class NavigationWatchdog(BaseWatchdog):
"""Switch agent focus to a specific tab index."""
targets = await self.browser_session._cdp_get_all_pages()
if 0 <= tab_index < len(targets):
- self.browser_session.cdp_session.target_id = targets[tab_index]['targetId']
+ if self.browser_session.cdp_session:
+ self.browser_session.cdp_session.target_id = targets[tab_index]['targetId']
await self._dispatch_focus_changed()
- target_url = await self._get_target_url(self.browser_session.cdp_session.target_id)
+ target_url = await self._get_target_url(self.browser_session.cdp_session.target_id if self.browser_session.cdp_session else None)
self.logger.info(f'[NavigationWatchdog] Agent focus switched to tab {tab_index}: {target_url}')
async def _find_new_agent_target(self) -> None:
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index a6a23535c..7d6862b8a 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -620,7 +620,8 @@ class BrowserSession(BaseModel):
async def get_tab_index(self, target_id: str) -> int:
"""Get tab index for a target ID."""
- target_ids = await self._cdp_get_all_pages()
+ targets = await self._cdp_get_all_pages()
+ target_ids = [t['targetId'] for t in targets]
if target_id in target_ids:
return target_ids.index(target_id)
return -1
diff --git a/browser_use/browser/storage_state_watchdog.py b/browser_use/browser/storage_state_watchdog.py
index 10de5d9d1..1b6112b87 100644
--- a/browser_use/browser/storage_state_watchdog.py
+++ b/browser_use/browser/storage_state_watchdog.py
@@ -7,6 +7,7 @@ from pathlib import Path
from typing import Any, ClassVar
from bubus import BaseEvent
+from cdp_use.cdp.network import Cookie
from pydantic import Field, PrivateAttr
from browser_use.browser.events import (
@@ -324,7 +325,9 @@ class StorageStateWatchdog(BaseWatchdog):
return []
try:
- return await self.browser_session._cdp_get_cookies()
+ cookies = await self.browser_session._cdp_get_cookies()
+ # Convert Cookie objects to dicts
+ return [cookie.model_dump() if hasattr(cookie, 'model_dump') else dict(cookie) for cookie in cookies]
except Exception as e:
self.logger.error(f'[StorageStateWatchdog] Failed to get cookies: {e}')
return []
@@ -336,8 +339,10 @@ class StorageStateWatchdog(BaseWatchdog):
return
try:
+ # Convert dicts to Cookie objects
+ cookie_objects = [Cookie(**cookie_dict) if isinstance(cookie_dict, dict) else cookie_dict for cookie_dict in cookies]
# Set cookies using CDP
- await self.browser_session._cdp_set_cookies(cookies)
+ await self.browser_session._cdp_set_cookies(cookie_objects)
self.logger.info(f'[StorageStateWatchdog] Added {len(cookies)} cookies')
except Exception as e:
self.logger.error(f'[StorageStateWatchdog] Failed to add cookies: {e}')
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index e96a1ed4b..ba2f525b3 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -212,6 +212,7 @@ class EnhancedDOMTreeNode:
"""
# frames
+ session_id: str
target_id: str
frame_id: str | None
content_document: 'EnhancedDOMTreeNode | None'
@@ -327,6 +328,7 @@ class EnhancedDOMTreeNode:
'node_value': self.node_value,
'attributes': self.attributes,
'is_scrollable': self.is_scrollable,
+ 'session_id': self.session_id,
'target_id': self.target_id,
'frame_id': self.frame_id,
'content_document': self.content_document.__json__() if self.content_document else None,
diff --git a/pyproject.toml b/pyproject.toml
index 804723283..60f2adc52 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -124,7 +124,7 @@ skip-magic-trailing-comma = false
[tool.pyright]
typeCheckingMode = "basic"
-exclude = ["tests/old/", ".venv/", ".git/", "__pycache__/", "./test_*.py", "./debug_*.py", "private_example/"]
+exclude = [".venv/", ".git/", "__pycache__/", "./test_*.py", "./debug_*.py", "private_example/", "debug/*", "tests/scripts/*", "tests/old/*"]
venvPath = "."
venv = ".venv"
@@ -140,6 +140,7 @@ include = [
"browser_use/py.typed",
"browser_use/dom/**/*.js",
"!tests/**/*.py",
+ "!debug/*",
]
[tool.pytest.ini_options]
diff --git a/tests/ci/test_watchdog.py b/tests/ci/test_watchdog.py
index 16a2494c4..041409457 100644
--- a/tests/ci/test_watchdog.py
+++ b/tests/ci/test_watchdog.py
@@ -96,9 +96,10 @@ async def test_watchdog_event_handler_registration():
session._storage_state_watchdog,
session._aboutblank_watchdog,
]:
- assert watchdog.event_bus is event_bus
- assert hasattr(watchdog, 'LISTENS_TO')
- assert hasattr(watchdog, 'EMITS')
+ if watchdog is not None:
+ assert watchdog.event_bus is event_bus
+ assert hasattr(watchdog, 'LISTENS_TO')
+ assert hasattr(watchdog, 'EMITS')
finally:
# Stop browser