Skip to content

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

Merge remote-tracking branch 'origin/main' into extraction-magnus-revert-with-main

Magnus Müller061e24b97695
diff --cc browser_use/agent/prompts.py
index 264555f15,2b8a8bbdb..4003da389
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@@ -127,9 -134,9 +134,9 @@@ class AgentMessagePrompt
return unique_screenshots
- @observe_debug(name='_get_browser_state_description')
+ @observe_debug(ignore_input=True, ignore_output=True, name='_get_browser_state_description')
def _get_browser_state_description(self) -> str:
- elements_text = self.browser_state.element_tree.clickable_elements_to_string(include_attributes=self.include_attributes)
+ elements_text = self.browser_state.dom_state.llm_representation(include_attributes=self.include_attributes)
if len(elements_text) > self.max_clickable_elements_length:
elements_text = elements_text[: self.max_clickable_elements_length]
diff --cc browser_use/agent/service.py
index 2dc90ad69,ba59ed171..7db2f468f
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@@ -21,6 -21,8 +21,7 @@@ from browser_use.agent.cloud_events imp
CreateAgentTaskEvent,
UpdateAgentTaskEvent,
)
+ from browser_use.agent.message_manager.utils import save_conversation
-from browser_use.dom.views import DEFAULT_INCLUDE_ATTRIBUTES
from browser_use.llm.base import BaseChatModel
from browser_use.llm.messages import BaseMessage, UserMessage
from browser_use.tokens.service import TokenCost
@@@ -59,8 -58,10 +57,7 @@@ from browser_use.browser.views import B
from browser_use.config import CONFIG
from browser_use.controller.registry.views import ActionModel
from browser_use.controller.service import Controller
-from browser_use.dom.history_tree_processor.service import (
- DOMHistoryElement,
- HistoryTreeProcessor,
-)
+from browser_use.dom.views import DOMInteractedElement
- from browser_use.exceptions import LLMException
from browser_use.filesystem.file_system import FileSystem
from browser_use.observability import observe, observe_debug
from browser_use.sync import CloudSync
@@@ -149,9 -162,10 +158,10 @@@ class Agent(Generic[Context, AgentStruc
message_context: str | None = None,
generate_gif: bool | str = False,
available_file_paths: list[str] | None = None,
- include_attributes: list[str] = DEFAULT_INCLUDE_ATTRIBUTES,
+ include_attributes: list[str] | None = None,
max_actions_per_step: int = 10,
use_thinking: bool = True,
+ flash_mode: bool = False,
max_history_items: int = 40,
images_per_step: int = 1,
page_extraction_llm: BaseChatModel | None = None,
@@@ -170,6 -184,16 +180,21 @@@
include_tool_call_examples: bool = False,
**kwargs,
):
+ # Check for deprecated planner parameters
- planner_params = [planner_llm, use_vision_for_planner, is_planner_reasoning, extend_planner_system_message]
++ planner_params = [
++ planner_llm,
++ use_vision_for_planner,
++ is_planner_reasoning,
++ extend_planner_system_message,
++ ]
+ if any(param is not None and param is not False for param in planner_params) or planner_interval != 1:
+ logger.warning(
+ '⚠️ Planner functionality has been removed in browser-use v0.3.3+. '
+ 'The planner_llm, use_vision_for_planner, planner_interval, is_planner_reasoning, '
+ 'and extend_planner_system_message parameters are deprecated and will be ignored. '
+ 'Please remove these parameters from your Agent() initialization.'
+ )
+
# Check for deprecated memory parameters
if kwargs.get('enable_memory', False) or kwargs.get('memory_config') is not None:
logger.warning(
@@@ -885,7 -832,115 +833,134 @@@
else:
self.logger.error(f'{prefix}{error_msg}')
- return [ActionResult(error=error_msg, include_in_memory=True)]
+ self.state.last_result = [ActionResult(error=error_msg)]
+ return None
+
+ async def _finalize(self, browser_state_summary: BrowserStateSummary | None) -> None:
+ """Finalize the step with history, logging, and events"""
+ step_end_time = time.time()
+ if not self.state.last_result:
+ return
+
+ if browser_state_summary:
+ metadata = StepMetadata(
+ step_number=self.state.n_steps,
+ step_start_time=self.step_start_time,
+ step_end_time=step_end_time,
+ )
+
+ # Use _make_history_item like main branch
- self._make_history_item(self.state.last_model_output, browser_state_summary, self.state.last_result, metadata)
++ self._make_history_item(
++ self.state.last_model_output,
++ browser_state_summary,
++ self.state.last_result,
++ metadata,
++ )
+
+ # Log step completion summary
+ self._log_step_completion_summary(self.step_start_time, self.state.last_result)
+
+ # Save file system state after step completion
+ self.save_file_system_state()
+
+ # Emit both step created and executed events
+ if browser_state_summary and self.state.last_model_output:
+ # Extract key step data for the event
+ actions_data = []
+ if self.state.last_model_output.action:
+ for action in self.state.last_model_output.action:
+ action_dict = action.model_dump() if hasattr(action, 'model_dump') else {}
+ actions_data.append(action_dict)
+
+ # Emit CreateAgentStepEvent
+ step_event = CreateAgentStepEvent.from_agent_step(
- self, self.state.last_model_output, self.state.last_result, actions_data, browser_state_summary
++ self,
++ self.state.last_model_output,
++ self.state.last_result,
++ actions_data,
++ browser_state_summary,
+ )
+ self.eventbus.dispatch(step_event)
+
+ async def _handle_final_step(self, step_info: AgentStepInfo | None = None) -> None:
+ """Handle special processing for the last step"""
+ if step_info and step_info.is_last_step():
+ # Add last step warning if needed
+ msg = 'Now comes your last step. Use only the "done" action now. No other actions - so here your action sequence must have length 1.'
+ msg += '\nIf the task is not yet fully finished as requested by the user, set success in "done" to false! E.g. if not all steps are fully completed.'
+ msg += '\nIf the task is fully finished, set success in "done" to true.'
+ msg += '\nInclude everything you found out for the ultimate task in the done text.'
+ self.logger.info('Last step finishing up')
+ self._message_manager._add_message_with_type(UserMessage(content=msg), 'consistent')
+ self.AgentOutput = self.DoneAgentOutput
+
+ async def _get_model_output_with_retry(self, input_messages: list[BaseMessage]) -> AgentOutput:
+ """Get model output with retry logic for empty actions"""
+ model_output = await self.get_model_output(input_messages)
+ self.logger.debug(
+ f'✅ Step {self.state.n_steps + 1}: Got LLM response with {len(model_output.action) if model_output.action else 0} actions'
+ )
+
+ if (
+ not model_output.action
+ or not isinstance(model_output.action, list)
+ or all(action.model_dump() == {} for action in model_output.action)
+ ):
+ self.logger.warning('Model returned empty action. Retrying...')
+
+ clarification_message = UserMessage(
+ content='You forgot to return an action. Please respond only with a valid JSON action according to the expected format.'
+ )
+
+ retry_messages = input_messages + [clarification_message]
+ model_output = await self.get_model_output(retry_messages)
+
+ if not model_output.action or all(action.model_dump() == {} for action in model_output.action):
+ self.logger.warning('Model still returned empty after retry. Inserting safe noop action.')
+ action_instance = self.ActionModel()
+ setattr(
+ action_instance,
+ 'done',
+ {
+ 'success': False,
+ 'text': 'No next action returned by LLM!',
+ },
+ )
+ model_output.action = [action_instance]
+
+ return model_output
+
+ async def _handle_post_llm_processing(
- self, browser_state_summary: BrowserStateSummary, input_messages: list[BaseMessage]
++ self,
++ browser_state_summary: BrowserStateSummary,
++ input_messages: list[BaseMessage],
+ ) -> None:
+ """Handle callbacks and conversation saving after LLM interaction"""
+ if self.register_new_step_callback and self.state.last_model_output:
+ if inspect.iscoroutinefunction(self.register_new_step_callback):
- await self.register_new_step_callback(browser_state_summary, self.state.last_model_output, self.state.n_steps)
++ await self.register_new_step_callback(
++ browser_state_summary,
++ self.state.last_model_output,
++ self.state.n_steps,
++ )
+ else:
- self.register_new_step_callback(browser_state_summary, self.state.last_model_output, self.state.n_steps)
++ self.register_new_step_callback(
++ browser_state_summary,
++ self.state.last_model_output,
++ self.state.n_steps,
++ )
+
+ if self.settings.save_conversation_path and self.state.last_model_output:
+ # Treat save_conversation_path as a directory (consistent with other recording paths)
+ conversation_dir = Path(self.settings.save_conversation_path)
+ conversation_filename = f'conversation_{self.id}_{self.state.n_steps}.txt'
+ target = conversation_dir / conversation_filename
+ await save_conversation(
+ input_messages,
+ self.state.last_model_output,
+ target,
+ self.settings.save_conversation_path_encoding,
+ )
def _make_history_item(
self,
@@@ -946,7 -1000,7 +1020,7 @@@
self._log_next_action_summary(parsed)
return parsed
-- except ValidationError as e:
++ except ValidationError:
# Just re-raise - Pydantic's validation errors are already descriptive
raise
@@@ -956,12 -1010,12 +1030,12 @@@
self.logger.debug(f'🤖 Browser-Use Library Version {self.version} ({self.source})')
- def _log_step_context(self, current_page, browser_state_summary) -> None:
+ def _log_step_context(self, current_page: Page, browser_state_summary: BrowserStateSummary) -> None:
"""Log step context information"""
url_short = current_page.url[:50] + '...' if len(current_page.url) > 50 else current_page.url
- interactive_count = len(browser_state_summary.selector_map) if browser_state_summary else 0
+ interactive_count = len(browser_state_summary.dom_state.selector_map) if browser_state_summary else 0
self.logger.info(
- f'📍 Step {self.state.n_steps}: Evaluating page with {interactive_count} interactive elements on: {url_short}'
+ f'📍 Step {self.state.n_steps + 1}: Evaluating page with {interactive_count} interactive elements on: {url_short}'
)
def _log_next_action_summary(self, parsed: 'AgentOutput') -> None:
diff --cc browser_use/agent/views.py
index d1f7f1e03,0eb3079cc..e0f1fbf25
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@@ -39,12 -37,23 +39,12 @@@ class AgentSettings(BaseModel)
validate_output: bool = False
message_context: str | None = None
generate_gif: bool | str = False
- available_file_paths: list[str] | None = None
override_system_message: str | None = None
extend_system_message: str | None = None
- include_attributes: list[str] = [
- 'title',
- 'type',
- 'name',
- 'role',
- 'tabindex',
- 'aria-label',
- 'placeholder',
- 'value',
- 'alt',
- 'aria-expanded',
- ]
+ include_attributes: list[str] | None = DEFAULT_INCLUDE_ATTRIBUTES
max_actions_per_step: int = 10
use_thinking: bool = True
+ flash_mode: bool = False # If enabled, disables evaluation_previous_goal and next_goal, and sets use_thinking = False
max_history_items: int = 40
images_per_step: int = 1
diff --cc browser_use/browser/session.py
index 4792aded6,1d5589c93..332dc8897
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@@ -16,10 -15,10 +15,20 @@@ from pathlib import Pat
from typing import Any, Self
from urllib.parse import urlparse
+ import anyio
+ from typing_extensions import deprecated
+
from browser_use.config import CONFIG
- from browser_use.dom.debug.highlights import inject_highlighting_script, remove_highlighting_script
++from browser_use.dom.debug.highlights import (
++ inject_highlighting_script,
++ remove_highlighting_script,
++)
+from browser_use.dom.service import DomService
- from browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode, SerializedDOMState
++from browser_use.dom.views import (
++ DOMSelectorMap,
++ EnhancedDOMTreeNode,
++ SerializedDOMState,
++)
from browser_use.observability import observe_debug
from browser_use.utils import _log_pretty_path, _log_pretty_url
@@@ -30,11 -29,10 +39,22 @@@ os.environ['PW_TEST_SCREENSHOT_NO_FONTS
import psutil
from bubus.helpers import retry
from playwright._impl._api_structures import ViewportSize
--from pydantic import AliasChoices, BaseModel, ConfigDict, Field, InstanceOf, PrivateAttr, model_validator
++from pydantic import (
++ AliasChoices,
++ BaseModel,
++ ConfigDict,
++ Field,
++ InstanceOf,
++ PrivateAttr,
++ model_validator,
++)
from uuid_extensions import uuid7str
--from browser_use.browser.profile import BROWSERUSE_DEFAULT_CHANNEL, BrowserChannel, BrowserProfile
++from browser_use.browser.profile import (
++ BROWSERUSE_DEFAULT_CHANNEL,
++ BrowserChannel,
++ BrowserProfile,
++)
from browser_use.browser.types import (
Browser,
BrowserContext,
@@@ -88,47 -85,105 +108,106 @@@ def _log_glob_warning(domain: str, glob
_GLOB_WARNING_SHOWN = True
- def require_initialization(func):
- """decorator for BrowserSession methods to require the BrowserSession be already active"""
+ def require_healthy_browser(usable_page=True, reopen_page=True):
+ """Decorator for BrowserSession methods to ensure browser/page is healthy before execution.
- assert asyncio.iscoroutinefunction(func), '@require_initialization only supports decorating async methods on BrowserSession'
+ This ridiculous overengineered logic is necessary to work around playwright's completely broken handling of crashed pages.
+ - When a page is loading, playwright calls will hang indefinitely.
+ - When a page is blocked by a JS while(true){}, playwright calls will hang indefinitely.
+ - When a page is unresponsive because the system is out of CPU or Memory, playwright calls will hang indefinitely.
+ asyncio.wait(...) is the most extreme method available to try and terminate asyncio tasks in python, but even this does not work
+ because it's likely the underlying playwright node.js process that's crashing and synchronously blocking the python side.
+ This is why we must use CDP directly and skip playwright eventually.
- @wraps(func)
- async def wrapper(self, *args, **kwargs):
- try:
- if not self.initialized or not self.browser_context:
- # raise RuntimeError('BrowserSession(...).start() must be called first to launch or connect to the browser')
- await self.start() # just start it automatically if not already started
+ Args:
- usable_page: If True, check that the agent_current_page is valid and responsive before executing the method, if invalid log it but continue anyway
- reopen_page: If True, attempt to reopen the page if it's crashed, invalid, or unresponsive (only applies if usable_page=True)
++ usable_page: If True, check that the agent_current_page is valid and responsive before executing the method, if invalid log it but continue anyway
++ reopen_page: If True, attempt to reopen the page if it's crashed, invalid, or unresponsive (only applies if usable_page=True)
+ """
- if not self.agent_current_page or self.agent_current_page.is_closed():
- self.agent_current_page = (
- self.browser_context.pages[0] if (self.browser_context and len(self.browser_context.pages) > 0) else None
- )
+ def decorator(func):
+ assert asyncio.iscoroutinefunction(func), '@require_healthy_browser only supports async methods'
- if not self.agent_current_page or self.agent_current_page.is_closed():
- await self.create_new_tab()
+ @wraps(func)
+ async def wrapper(self: BrowserSession, *args, **kwargs):
+ try:
+ if not self.initialized or not self.browser_context:
+ # raise RuntimeError('BrowserSession(...).start() must be called first to launch or connect to the browser')
+ await self.start() # just start it automatically if not already started
- assert self.agent_current_page and not self.agent_current_page.is_closed()
+ if not self.agent_current_page or self.agent_current_page.is_closed():
+ self.agent_current_page = (
+ self.browser_context.pages[0] if (self.browser_context and len(self.browser_context.pages) > 0) else None
+ )
- if not hasattr(self, '_cached_browser_state_summary'):
- raise RuntimeError('BrowserSession(...).start() must be called first to initialize the browser session')
+ # always require at least one tab to be open for the context to be considered usable, dont check responsiveness unless usable_page=True
+ if not self.agent_current_page or self.agent_current_page.is_closed():
+ # Create new page directly to avoid circular dependency
+ assert self.browser_context is not None, 'Browser context is not set'
+ new_page = await self.browser_context.new_page()
+ self.agent_current_page = new_page
+ if (not self.human_current_page) or self.human_current_page.is_closed():
+ self.human_current_page = new_page
+ if self.browser_profile.viewport:
+ await new_page.set_viewport_size(self.browser_profile.viewport)
+
+ assert self.agent_current_page and not self.agent_current_page.is_closed()
+
+ if not hasattr(self, '_cached_browser_state_summary'):
+ raise RuntimeError('BrowserSession(...).start() must be called first to initialize the browser session')
+
+ # Check page responsiveness if usable_page=True
+ if usable_page:
+ # Skip if already in recovery to prevent infinite recursion
+ if hasattr(self, '_in_recovery') and self._in_recovery:
+ # self.logger.debug('Already in recovery, skipping responsiveness check')
+ return await func(self, *args, **kwargs)
+
+ # Skip responsiveness check for about:blank pages - they're always responsive (I hope, otherwise something is very wrong)
+ if self.agent_current_page and is_new_tab_page(self.agent_current_page.url):
+ # self.logger.debug('Skipping responsiveness check for about:blank page')
+ return await func(self, *args, **kwargs)
+
+ # Check if page is responsive
+ # self.logger.debug(f'Checking page responsiveness for {func.__name__}...')
+ if await self._is_page_responsive(self.agent_current_page):
+ # self.logger.debug('✅ Confirmed page is responsive')
+ pass
+ else:
+ # Page is unresponsive - handle recovery
+ if not reopen_page:
+ self.logger.warning(
+ '⚠️ Page unresponsive but @require_healthy_browser(reopen_page=False), attempting to continue anyway...'
+ )
+ else:
+ try:
+ await self._recover_unresponsive_page(
- func.__name__, timeout_ms=int(self.browser_profile.default_navigation_timeout or 5000) + 5_000
++ func.__name__,
++ timeout_ms=int(self.browser_profile.default_navigation_timeout or 5000) + 5_000,
+ )
+ self.logger.debug(
+ f'🤕 Crashed page recovery finished, attempting to continue with {func.__name__}() on {_log_pretty_url(self.agent_current_page.url)}...'
+ )
- except Exception as e:
++ except Exception:
+ self.logger.warning(
+ f'❌ Crashed page recovery failed, could not run {func.__name__}(), page is stuck unresponsive on {_log_pretty_url(self.agent_current_page.url)}...'
+ )
+ raise # Re-raise to let retry decorator / callsite handle it
- return await func(self, *args, **kwargs)
+ return await func(self, *args, **kwargs)
- except Exception as e:
- # Check if this is a TargetClosedError or similar connection error
- if 'TargetClosedError' in str(type(e)) or 'context or browser has been closed' in str(e):
- self.logger.warning(
- f'✂️ Browser {self._connection_str} disconnected before BrowserSession.{func.__name__} could run...'
- )
- self._reset_connection_state()
- # Re-raise the error so the caller can handle it appropriately
- raise
- else:
- # Re-raise other exceptions unchanged
+ except Exception as e:
+ # Check if this is a TargetClosedError or similar connection error
+ if 'TargetClosedError' in str(type(e)) or 'browser has been closed' in str(e):
+ self.logger.warning(
+ f'✂️ Browser {self._connection_str} disconnected before BrowserSession.{func.__name__}() could run... (error: {type(e).__name__}: {e})'
+ )
+ self._reset_connection_state()
+ # Re-raise all hard errors so the caller can handle them appropriately
raise
- return wrapper
+ return wrapper
+
+ return decorator
DEFAULT_BROWSER_PROFILE = BrowserProfile()
@@@ -283,13 -347,13 +371,13 @@@ class BrowserSession(BaseModel)
"""
Starts the browser session by either connecting to an existing browser or launching a new one.
Precedence order for launching/connecting:
-- 1. page=Page playwright object, will use its page.context as browser_context
-- 2. browser_context=PlaywrightBrowserContext object, will use its browser
-- 3. browser=PlaywrightBrowser object, will use its first available context
-- 4. browser_pid=int, will connect to a local chromium-based browser via pid
-- 5. wss_url=str, will connect to a remote playwright browser server via WSS
-- 6. cdp_url=str, will connect to a remote chromium-based browser via CDP
-- 7. playwright=Playwright object, will use its chromium instance to launch a new browser
++ 1. page=Page playwright object, will use its page.context as browser_context
++ 2. browser_context=PlaywrightBrowserContext object, will use its browser
++ 3. browser=PlaywrightBrowser object, will use its first available context
++ 4. browser_pid=int, will connect to a local chromium-based browser via pid
++ 5. wss_url=str, will connect to a remote playwright browser server via WSS
++ 6. cdp_url=str, will connect to a remote chromium-based browser via CDP
++ 7. playwright=Playwright object, will use its chromium instance to launch a new browser
"""
# if we're already initialized and the connection is still valid, return the existing session state and start from scratch
@@@ -553,10 -618,10 +642,12 @@@
except psutil.NoSuchProcess:
pass
except Exception as e:
- self.logger.warning(f'Error force-killing browser in BrowserSession.__del__: {type(e).__name__}: {e}')
+ self.logger.warning(f'⚠️ Error force-killing browser in BrowserSession.__del__: {type(e).__name__}: {e}')
@staticmethod
-- async def _start_global_playwright_subprocess(is_stealth: bool) -> PlaywrightOrPatchright:
++ async def _start_global_playwright_subprocess(
++ is_stealth: bool,
++ ) -> PlaywrightOrPatchright:
"""Create and return a new playwright or patchright node.js subprocess / API connector"""
global GLOBAL_PLAYWRIGHT_API_OBJECT, GLOBAL_PATCHRIGHT_API_OBJECT
global GLOBAL_PLAYWRIGHT_EVENT_LOOP, GLOBAL_PATCHRIGHT_EVENT_LOOP
@@@ -617,7 -682,7 +708,14 @@@
# Create new playwright object
return await self._start_global_playwright_subprocess(is_stealth=is_stealth)
-- @retry(wait=1, retries=2, timeout=45, semaphore_limit=1, semaphore_scope='self', semaphore_lax=False)
++ @retry(
++ wait=1,
++ retries=2,
++ timeout=45,
++ semaphore_limit=1,
++ semaphore_scope='self',
++ semaphore_lax=False,
++ )
async def _close_browser_context(self) -> None:
"""Close browser context with retry logic."""
await self._unsafe_close_browser_context()
@@@ -628,7 -693,7 +726,14 @@@
await self.browser_context.close()
self.browser_context = None
-- @retry(wait=1, retries=2, timeout=10, semaphore_limit=1, semaphore_scope='self', semaphore_lax=False)
++ @retry(
++ wait=1,
++ retries=2,
++ timeout=10,
++ semaphore_limit=1,
++ semaphore_scope='self',
++ semaphore_lax=False,
++ )
async def _close_browser(self) -> None:
"""Close browser instance with retry logic."""
await self._unsafe_close_browser()
@@@ -646,7 -711,7 +751,10 @@@
semaphore_limit=1,
semaphore_scope='self',
semaphore_lax=True,
-- retry_on=(TimeoutError, psutil.TimeoutExpired), # Only retry on timeouts, not NoSuchProcess
++ retry_on=(
++ TimeoutError,
++ psutil.TimeoutExpired,
++ ), # Only retry on timeouts, not NoSuchProcess
)
async def _terminate_browser_process(self, _hint: str = '') -> None:
"""Terminate browser process with retry logic."""
@@@ -671,7 -736,7 +779,14 @@@
finally:
self.browser_pid = None
-- @retry(wait=0.5, retries=2, timeout=30, semaphore_limit=1, semaphore_scope='self', semaphore_lax=True)
++ @retry(
++ wait=0.5,
++ retries=2,
++ timeout=30,
++ semaphore_limit=1,
++ semaphore_scope='self',
++ semaphore_lax=True,
++ )
async def _save_trace_recording(self) -> None:
"""Save browser trace recording."""
if self.browser_profile.traces_dir and self.browser_context is not None:
@@@ -1026,7 -1044,7 +1094,14 @@@
)
self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end
-- @retry(wait=1, retries=2, timeout=45, semaphore_limit=1, semaphore_scope='self', semaphore_lax=False)
++ @retry(
++ wait=1,
++ retries=2,
++ timeout=45,
++ semaphore_limit=1,
++ semaphore_scope='self',
++ semaphore_lax=False,
++ )
async def setup_new_browser_context(self) -> None:
"""Launch a new browser and browser_context"""
# Double-check after semaphore acquisition to prevent duplicate browser launches
@@@ -1383,7 -1422,7 +1479,11 @@@
# self.browser_profile.user_data_dir = fork_path
# self.browser_profile.prepare_user_data_dir()
- @observe_debug(name='setup_current_page_change_listeners')
- @observe_debug(ignore_input=True, ignore_output=True, name='setup_current_page_change_listeners')
++ @observe_debug(
++ ignore_input=True,
++ ignore_output=True,
++ name='setup_current_page_change_listeners',
++ )
async def _setup_current_page_change_listeners(self) -> None:
# Uses a combination of:
# - visibilitychange events
@@@ -1508,7 -1547,9 +1608,12 @@@
f'⚠️ Failed to add visibility listener to existing tab, is it crashed or ignoring CDP commands?: [{page_idx}]{page.url}: {type(e).__name__}: {e}'
)
- @observe_debug(name='setup_viewports', metadata={'browser_profile': '{{browser_profile}}'})
+ @observe_debug(
- ignore_input=True, ignore_output=True, name='setup_viewports', metadata={'browser_profile': '{{browser_profile}}'}
++ ignore_input=True,
++ ignore_output=True,
++ name='setup_viewports',
++ metadata={'browser_profile': '{{browser_profile}}'},
+ )
async def _setup_viewports(self) -> None:
"""Resize any existing page viewports to match the configured size, set up storage_state, permissions, geolocation, etc."""
@@@ -1617,7 -1665,7 +1729,10 @@@
# fallback to javascript resize if cdp setWindowBounds fails
await page.evaluate(
"""(width, height) => {window.resizeTo(width, height)}""",
-- [self.browser_profile.window_size['width'], self.browser_profile.window_size['height']],
++ [
++ self.browser_profile.window_size['width'],
++ self.browser_profile.window_size['height'],
++ ],
)
return
except Exception:
@@@ -1643,8 -1691,8 +1758,8 @@@
- Browser_context itself is closed/unusable
Args:
-- restart: If True, will attempt to create a new tab if no pages exist (valid contexts must always have at least one page open).
-- If False, will only check connection status without side effects.
++ restart: If True, will attempt to create a new tab if no pages exist (valid contexts must always have at least one page open).
++ If False, will only check connection status without side effects.
"""
if not self.browser_context:
return False
@@@ -1710,7 -1762,7 +1829,10 @@@
# if we have a self.browser_pid, check if it's still alive and serving a remote debugging port
# if so, don't clear it because there's a chance we can re-use it by just reconnecting to the same pid's port
proc = psutil.Process(self.browser_pid)
-- proc_is_alive = proc.status() not in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD)
++ proc_is_alive = proc.status() not in (
++ psutil.STATUS_ZOMBIE,
++ psutil.STATUS_DEAD,
++ )
assert proc_is_alive and '--remote-debugging-port' in ' '.join(proc.cmdline())
except Exception:
self.logger.info(f' ↳ Browser browser_pid={self.browser_pid} process is no longer running')
@@@ -1724,7 -1776,7 +1846,7 @@@
"""Check if the user data directory has a conflicting browser process.
Returns:
-- True if there's a conflict (active process using this profile), False otherwise
++ True if there's a conflict (active process using this profile), False otherwise
"""
if not self.browser_profile.user_data_dir:
return False
@@@ -1783,7 -1835,7 +1905,7 @@@
"""Fallback to a temporary profile directory when the current one is locked.
Args:
-- reason: Human-readable reason for the fallback
++ reason: Human-readable reason for the fallback
"""
old_dir = self.browser_profile.user_data_dir
self.browser_profile.user_data_dir = Path(tempfile.mkdtemp(prefix='browseruse-tmp-singleton-'))
@@@ -1797,7 -1849,7 +1919,7 @@@
"""Create and prepare the user data dir, handling conflicts if needed.
Args:
-- check_conflicts: Whether to check for and handle singleton lock conflicts
++ check_conflicts: Whether to check for and handle singleton lock conflicts
"""
if self.browser_profile.user_data_dir:
try:
@@@ -1880,7 -1932,7 +2002,11 @@@
try:
path_obj = Path(path_value).expanduser().resolve()
path_obj.mkdir(parents=True, exist_ok=True)
-- setattr(self.browser_profile, path_name, str(path_obj) if path_name == 'traces_dir' else path_obj)
++ setattr(
++ self.browser_profile,
++ path_name,
++ str(path_obj) if path_name == 'traces_dir' else path_obj,
++ )
except Exception as e:
self.logger.error(f'❌ Failed to create {path_name} directory {path_value}: {e}')
@@@ -1964,36 -2014,49 +2088,34 @@@
page = await self.get_current_page()
await page.wait_for_selector(selector, state='visible', timeout=timeout)
+ @observe_debug(name='inject_highlights', ignore_output=True, ignore_input=True)
- @require_initialization
+ @time_execution_async('--inject_highlights')
+ @retry(timeout=10, retries=0)
+ async def inject_highlights(self, dom_service: DomService, selector_map: DOMSelectorMap):
+ """Inject highlights into the page."""
+ await inject_highlighting_script(dom_service, selector_map)
+
@observe_debug(name='remove_highlights', ignore_output=True, ignore_input=True)
- @require_initialization
+ @require_healthy_browser(usable_page=True, reopen_page=True)
@time_execution_async('--remove_highlights')
- @retry(timeout=2, retries=0)
- async def remove_highlights(self):
+ @retry(timeout=10, retries=0)
+ async def remove_highlights(self, dom_service: DomService):
"""
+ DEPRECATED
+
Removes all highlight overlays and labels created by the highlightElement function.
Handles cases where the page might be closed or inaccessible.
"""
- page = await self.get_current_page()
- try:
- await page.evaluate(
- """
- try {
- // Remove the highlight container and all its contents
- const container = document.getElementById('playwright-highlight-container');
- if (container) {
- container.remove();
- }
-
- // Remove highlight attributes from elements
- const highlightedElements = document.querySelectorAll('[browser-user-highlight-id^="playwright-highlight-"]');
- highlightedElements.forEach(el => {
- el.removeAttribute('browser-user-highlight-id');
- });
- } catch (e) {
- console.error('Failed to remove highlights:', e);
- }
- """
- )
- except Exception as e:
- self.logger.debug(f'⚠️ Failed to remove highlights (this is usually ok): {type(e).__name__}: {e}')
- # Don't raise the error since this is not critical functionality
+ await remove_highlighting_script(dom_service)
- @require_initialization
- @require_healthy_browser(usable_page=True, reopen_page=True)
- async def get_dom_element_by_index(self, index: int) -> DOMElementNode | None:
+ async def get_dom_element_by_index(self, index: int) -> EnhancedDOMTreeNode | None:
"""Get DOM element by index."""
selector_map = await self.get_selector_map()
return selector_map.get(index)
- @require_initialization
+ @require_healthy_browser(usable_page=True, reopen_page=True)
@time_execution_async('--click_element_node')
- async def _click_element_node(self, element_node: DOMElementNode) -> str | None:
+ async def _click_element_node(self, element_node: EnhancedDOMTreeNode) -> str | None:
"""
Optimized method to click an element using xpath.
"""
@@@ -2079,15 -2142,13 +2201,15 @@@
raise e
except Exception as e:
# Final fallback - try clicking by coordinates if available
- if element_node.viewport_coordinates and element_node.viewport_coordinates.center:
+ if element_node.snapshot_node and element_node.snapshot_node.bounds:
try:
+ # TODO: instead of using the cached center, we should use the actual center of the element (easy, just get it by nodeBackendId)
self.logger.warning(
- f'⚠️ Element click failed, falling back to coordinate click at ({element_node.snapshot_node.bounds.center.x}, {element_node.snapshot_node.bounds.center.y})'
- f'⚠️ Element click failed, falling back to coordinate click at ({element_node.viewport_coordinates.center.x}, {element_node.viewport_coordinates.center.y})'
++ f'⚠️ Element click failed, falling back to coordinate click at ({element_node.snapshot_node.bounds.x}, {element_node.snapshot_node.bounds.y})'
)
await page.mouse.click(
- element_node.snapshot_node.bounds.center.x,
- element_node.snapshot_node.bounds.center.y,
- element_node.viewport_coordinates.center.x, element_node.viewport_coordinates.center.y
++ element_node.snapshot_node.bounds.x,
++ element_node.snapshot_node.bounds.y,
)
try:
await page.wait_for_load_state()
@@@ -2112,13 -2174,33 +2235,37 @@@
tabs_info = []
for page_id, page in enumerate(self.browser_context.pages):
try:
- title = await self._get_page_title(page)
+ title = await asyncio.wait_for(page.title(), timeout=3.0)
tab_info = TabInfo(page_id=page_id, url=page.url, title=title)
except Exception:
- # page.title() can hang forever on tabs that are crashed/disappeared/new tab pages
- # we dont want to try automating those tabs because they will hang the whole script
- self.logger.debug(f'⚠️ Failed to get tab info for tab #{page_id}: {_log_pretty_url(page.url)} (ignoring)')
- tab_info = TabInfo(page_id=page_id, url='about:blank', title='ignore this tab and do not use it')
+ # page.title() can hang forever on tabs that are crashed/disappeared/about:blank
+ # but we should preserve the real URL and not mislead the LLM about tab availability
+ self.logger.debug(
+ f'⚠️ Failed to get tab info for tab #{page_id}: {_log_pretty_url(page.url)} (using fallback title)'
+ )
+
+ # Only mark as unusable if it's actually about:blank, otherwise preserve the real URL
+ if page.url == 'about:blank':
- tab_info = TabInfo(page_id=page_id, url='about:blank', title='ignore this tab and do not use it')
++ tab_info = TabInfo(
++ page_id=page_id,
++ url='about:blank',
++ title='ignore this tab and do not use it',
++ )
+ else:
+ # Preserve the real URL and use a descriptive fallback title
+ # fallback_title = '(title unavailable, page possibly crashed / unresponsive)'
+ # tab_info = TabInfo(page_id=page_id, url=page.url, title=fallback_title)
+
+ # harsh but good, just close the page here because if we cant get the title then we certainly cant do anything else useful with it, no point keeping it open
+ try:
+ await page.close()
+ self.logger.debug(
+ f'🪓 Force-closed 🅟 {str(id(page))[-2:]} because its JS engine is unresponsive via CDP: {_log_pretty_url(page.url)}'
+ )
+ except Exception:
+ pass
+ continue
+
tabs_info.append(tab_info)
return tabs_info
@@@ -2158,28 -2235,126 +2300,142 @@@
await self.get_current_page()
# --- Page navigation ---
- @require_initialization
- async def navigate(self, url: str) -> None:
- # Add https:// if there's no protocol
+ @observe_debug(ignore_input=True, ignore_output=True)
- @retry(retries=0, timeout=30, wait=1, semaphore_timeout=10, semaphore_limit=1, semaphore_scope='self', semaphore_lax=True)
++ @retry(
++ retries=0,
++ timeout=30,
++ wait=1,
++ semaphore_timeout=10,
++ semaphore_limit=1,
++ semaphore_scope='self',
++ semaphore_lax=True,
++ )
+ @require_healthy_browser(usable_page=False, reopen_page=False)
- async def navigate(self, url: str = 'about:blank', new_tab: bool = False, timeout_ms: int | None = None) -> Page:
++ async def navigate(
++ self,
++ url: str = 'about:blank',
++ new_tab: bool = False,
++ timeout_ms: int | None = None,
++ ) -> Page:
+ """
+ Universal navigation method that handles all navigation scenarios.
+
+ Args:
- url: URL to navigate to (defaults to 'about:blank')
- new_tab: If True, creates a new tab for navigation
++ url: URL to navigate to (defaults to 'about:blank')
++ new_tab: If True, creates a new tab for navigation
+ Returns:
- Page: The page that was navigated
++ Page: The page that was navigated
+ """
+ # Normalize the URL
normalized_url = normalize_url(url)
+ # Check if URL is allowed
+ if not self._is_url_allowed(normalized_url):
+ raise BrowserError(f'⛔️ Navigation to non-allowed URL: {normalized_url}')
+
- timeout_ms = min(3000, int(timeout_ms or self.browser_profile.default_navigation_timeout or 12000))
++ timeout_ms = min(
++ 3000,
++ int(timeout_ms or self.browser_profile.default_navigation_timeout or 12000),
++ )
+
+ # Handle new tab creation
+ if new_tab:
+ # Create new tab
+ assert self.browser_context is not None, 'Browser context is not set'
+ self.agent_current_page = await self.browser_context.new_page()
+
+ # Update human tab reference if there is no human tab yet
+ if (not self.human_current_page) or self.human_current_page.is_closed():
+ self.human_current_page = self.agent_current_page
+
+ # Set viewport for new tab
+ if self.browser_profile.viewport:
+ await self.agent_current_page.set_viewport_size(self.browser_profile.viewport)
+
+ page = self.agent_current_page
+ else:
+ # Use existing page
+ page = await self.get_current_page()
+
+ # Navigate to URL
try:
- if self.agent_current_page:
- await self.agent_current_page.goto(normalized_url, wait_until='domcontentloaded')
- else:
- await self.create_new_tab(normalized_url)
- except Exception as e:
- if 'timeout' in str(e).lower():
+ # Use asyncio.wait to prevent hanging on slow page loads
+ # Don't cap the timeout - respect what was requested
+ self.logger.debug(f'🧭 Starting navigation to {_log_pretty_url(normalized_url)} with timeout {timeout_ms}ms')
+ nav_task = asyncio.create_task(page.goto(normalized_url, wait_until='load', timeout=timeout_ms))
+ done, pending = await asyncio.wait([nav_task], timeout=(timeout_ms + 500) / 1000)
+
+ if nav_task in pending:
+ # Navigation timed out
self.logger.warning(
- f"⚠️ Loading {_log_pretty_url(normalized_url)} didn't finish after {(self.browser_profile.default_navigation_timeout or 30_000) / 1000}s, continuing anyway..."
+ f"⚠️ Loading {_log_pretty_url(normalized_url)} didn't finish after {timeout_ms / 1000}s, continuing anyway..."
)
- # Don't re-raise timeout errors - the page is likely still usable and will continue to load in the background
+ nav_task.cancel()
+ try:
+ await nav_task
+ except asyncio.CancelledError:
+ pass
+
+ # Check if page is still usable after timeout
+ if page and not page.is_closed():
+ current_url = page.url
+ # self.logger.debug(f'🤌 Checking responsiveness after navigation timeout (current URL: {current_url})')
+ is_responsive = await self._is_page_responsive(page, timeout=3.0)
+ if is_responsive:
+ self.logger.debug(
+ f'✅ Page is responsive and usable despite navigation loading timeout on: {_log_pretty_url(current_url)})'
+ )
+ else:
+ self.logger.error(
+ f'❌ Page is unresponsive after navigation stalled on: {_log_pretty_url(current_url)} WARNING! Subsequent operations will likely fail on this page, it must be reset...'
+ )
+ # Don't try complex recovery during navigate - just raise the error
+ # The retry decorator will handle retries, and other methods with
+ # @require_healthy_browser(reopen_page=True) will trigger proper recovery
+ raise RuntimeError(
+ f'Page JS engine is unresponsive after navigation / loading issue on: {_log_pretty_url(current_url)}). Agent cannot proceed with this page because its JS event loop is unresponsive.'
+ )
+ elif nav_task in done:
+ # Navigation completed, check if it succeeded
+ await nav_task # This will raise if navigation failed
+ except Exception as e:
+ if 'timeout' in str(e).lower():
+ # self.logger.warning(
+ # f"⚠️ Loading {_log_pretty_url(normalized_url)} didn't finish and further operations may fail on this page..."
+ # )
+ pass # allow agent to attempt to continue without raising hard error, it can use tools to work around it
else:
- # Re-raise non-timeout errors
raise
- @require_initialization
+ # Show DVD animation on new tab pages if no URL specified
+ if new_tab and is_new_tab_page(page.url):
+ # Navigate to about:blank if we're on chrome://new-tab-page to avoid security restrictions
+ if page.url.startswith('chrome://new-tab-page'):
+ try:
+ await page.goto('about:blank', wait_until='load', timeout=timeout_ms)
+ except Exception:
+ pass
+ await self._show_dvd_screensaver_loading_animation(page)
+
+ return page
+
+ @deprecated('Use BrowserSession.navigate(url) instead of .navigate_to(url)')
+ async def navigate_to(self, url: str) -> Page:
+ """Backward compatibility alias for navigate()"""
+ return await self.navigate(url=url, new_tab=False)
+
+ @deprecated('Use BrowserSession.navigate(url=url, new_tab=True) instead of .create_new_tab(url)')
+ async def create_new_tab(self, url: str | None = None) -> Page:
+ """Backward compatibility alias for navigate()"""
+ return await self.navigate(url=url or 'about:blank', new_tab=True)
+
+ @deprecated('Use BrowserSession.navigate(url=url, new_tab=True) instead of .new_tab(url)')
+ async def new_tab(self, url: str | None = None) -> Page:
+ """Backward compatibility alias for navigate()"""
+ return await self.navigate(url=url or 'about:blank', new_tab=True)
+
+ @require_healthy_browser(usable_page=True, reopen_page=True)
async def refresh(self) -> None:
if self.agent_current_page and not self.agent_current_page.is_closed():
await self.agent_current_page.reload()
@@@ -2620,7 -2820,7 +2901,10 @@@
# Calculate remaining time to meet minimum WAIT_TIME
elapsed = time.time() - start_time
-- remaining = max((timeout_overwrite or self.browser_profile.minimum_wait_page_load_time) - elapsed, 0)
++ remaining = max(
++ (timeout_overwrite or self.browser_profile.minimum_wait_page_load_time) - elapsed,
++ 0,
++ )
# Skip expensive performance API logging - can cause significant delays on complex pages
bytes_used = None
@@@ -2933,31 -3158,50 +3210,39 @@@
try:
self.logger.debug('🧹 Removing highlights...')
- try:
- await self.remove_highlights()
- except TimeoutError:
- self.logger.debug('Timeout to remove highlights')
-
+ # Check for PDF and auto-download if needed
+ try:
+ pdf_path = await self._auto_download_pdf_if_needed(page)
+ if pdf_path:
+ self.logger.info(f'📄 PDF auto-downloaded: {pdf_path}')
+ except Exception as e:
+ self.logger.debug(f'PDF auto-download check failed: {type(e).__name__}: {e}')
+
self.logger.debug('🌳 Starting DOM processing...')
- dom_service = DomService(page, logger=self.logger)
- try:
- content = await asyncio.wait_for(
- dom_service.get_clickable_elements(
- focus_element=focus_element,
- viewport_expansion=self.browser_profile.viewport_expansion,
- highlight_elements=self.browser_profile.highlight_elements,
- ),
- timeout=45.0, # 45 second timeout for DOM processing - generous for complex pages
- )
- self.logger.debug('✅ DOM processing completed')
- except TimeoutError:
- self.logger.warning(f'DOM processing timed out after 45 seconds for {page.url}')
- self.logger.warning('🔄 Falling back to minimal DOM state to allow basic navigation...')
-
- # Create minimal DOM state for basic navigation
- from browser_use.dom.views import DOMElementNode
-
- minimal_element_tree = DOMElementNode(
- tag_name='body',
- xpath='/body',
- attributes={},
- children=[],
- is_visible=True,
- parent=None,
- )
+ async with DomService(self, page) as dom_service:
+ await self.remove_highlights(dom_service)
+ try:
+ dom_state, timing_info = await asyncio.wait_for(
+ dom_service.get_serialized_dom_tree(
+ previous_cached_state=self._cached_browser_state_summary.dom_state
+ if self._cached_browser_state_summary
+ else None,
+ ),
+ timeout=45.0, # 45 second timeout for DOM processing - generous for complex pages
+ )
- from browser_use.dom.views import DOMState
+ await self.inject_highlights(dom_service, dom_state.selector_map)
- content = DOMState(element_tree=minimal_element_tree, selector_map={})
+ self.logger.debug('✅ DOM processing completed')
+ except TimeoutError:
+ self.logger.warning(f'DOM processing timed out after 45 seconds for {page.url}')
+ self.logger.warning('🔄 Falling back to minimal DOM state to allow basic navigation...')
+
+ # Create minimal DOM state for basic navigation
+
+ from browser_use.dom.views import SerializedDOMState
+
+ dom_state = SerializedDOMState(_root=None, selector_map={})
self.logger.debug('📋 Getting tabs info...')
tabs_info = await self.get_tabs_info()
@@@ -3035,53 -3280,341 +3320,349 @@@
if hasattr(self, 'browser_state_summary'):
return self.browser_state_summary
raise
+ finally:
+ await self.remove_highlights(dom_service)
+ # region - Page Health Check Helpers
+ @observe_debug(ignore_input=True)
+ async def _is_page_responsive(self, page: Page, timeout: float = 5.0) -> bool:
+ """Check if a page is responsive by trying to evaluate simple JavaScript."""
+ eval_task = None
+ try:
+ eval_task = asyncio.create_task(page.evaluate('1'))
+ done, pending = await asyncio.wait([eval_task], timeout=timeout)
+
+ if eval_task in done:
+ try:
+ await eval_task # This will raise if the evaluation failed
+ return True
+ except Exception:
+ return False
+ else:
+ # Timeout - the page is unresponsive
+ return False
+ except Exception:
+ return False
+ finally:
+ # Always clean up the eval task
+ if eval_task and not eval_task.done():
+ eval_task.cancel()
+ try:
+ await eval_task
+ except (asyncio.CancelledError, Exception):
+ pass
+
+ async def _force_close_page_via_cdp(self, page_url: str) -> bool:
+ """Force close a crashed page using CDP from a clean temporary page."""
+ try:
+ # self.logger.info('🔨 Creating temporary page for CDP force-close...')
+
+ # Create a clean page for CDP operations
+ assert self.browser_context, 'Browser context is not set up yet'
+ temp_page = await asyncio.wait_for(self.browser_context.new_page(), timeout=5.0)
+ await asyncio.wait_for(temp_page.goto('about:blank'), timeout=2.0)
+
+ # Create CDP session from the clean page
+ cdp_session = await asyncio.wait_for(self.browser_context.new_cdp_session(temp_page), timeout=5.0) # type: ignore
+
+ try:
+ # Get all browser targets
+ targets = await asyncio.wait_for(cdp_session.send('Target.getTargets'), timeout=2.0)
+
+ # Find the crashed page target
+ blocked_target_id = None
+ for target in targets.get('targetInfos', []):
+ if target.get('type') == 'page' and target.get('url') == page_url:
+ blocked_target_id = target.get('targetId')
+ # self.logger.debug(f'Found target to close: {page_url}')
+ break
+
+ if blocked_target_id:
+ # Force close the target
+ self.logger.warning(
+ f'🪓 Force-closing crashed page target_id={blocked_target_id} via CDP: {_log_pretty_url(page_url)}...'
+ )
- await asyncio.wait_for(cdp_session.send('Target.closeTarget', {'targetId': blocked_target_id}), timeout=2.0)
++ await asyncio.wait_for(
++ cdp_session.send('Target.closeTarget', {'targetId': blocked_target_id}),
++ timeout=2.0,
++ )
+ # self.logger.debug(f'☠️ Successfully force-closed crashed page target_id={blocked_target_id} via CDP: {_log_pretty_url(page_url)}')
+ return True
+ else:
+ self.logger.debug(
+ f'❌ Could not find CDP page target_id to force-close: {_log_pretty_url(page_url)} (concurrency issues?)'
+ )
+ return False
+
+ finally:
+ # Clean up
+ try:
+ await asyncio.wait_for(cdp_session.detach(), timeout=1.0)
+ except Exception:
+ pass
+ await temp_page.close()
+
+ except Exception as e:
+ self.logger.error(f'❌ Using raw CDP to force-close crashed page failed: {type(e).__name__}: {e}')
+ return False
+
+ async def _try_reopen_url(self, url: str, timeout_ms: int | None = None) -> bool:
+ """Try to reopen a URL in a new page and check if it's responsive."""
+ if not url or is_new_tab_page(url):
+ return False
+
+ timeout_ms = int(timeout_ms or self.browser_profile.default_navigation_timeout or 6000)
+
+ try:
+ self.logger.debug(f'🔄 Attempting to reload URL that crashed: {_log_pretty_url(url)}')
+
+ # Create new page directly to avoid circular dependency
+ assert self.browser_context is not None, 'Browser context is not set'
+ new_page = await self.browser_context.new_page()
+ self.agent_current_page = new_page
+
+ # Update human tab reference if there is no human tab yet
+ if (not self.human_current_page) or self.human_current_page.is_closed():
+ self.human_current_page = new_page
+
+ # Set viewport for new tab
+ if self.browser_profile.viewport:
+ await new_page.set_viewport_size(self.browser_profile.viewport)
+
+ # Navigate with timeout using asyncio.wait
+ nav_task = asyncio.create_task(new_page.goto(url, wait_until='load', timeout=timeout_ms))
+ done, pending = await asyncio.wait([nav_task], timeout=(timeout_ms + 500) / 1000)
+
+ if nav_task in pending:
+ # Navigation timed out
+ self.logger.debug(
+ f'⚠️ Attempting to reload previously crashed URL {_log_pretty_url(url)} failed again, timed out again after {timeout_ms / 1000}s'
+ )
+ nav_task.cancel()
+ try:
+ await nav_task
+ except asyncio.CancelledError:
+ pass
+ elif nav_task in done:
+ try:
+ await nav_task # This will raise if navigation failed
+ except Exception as e:
+ self.logger.debug(
+ f'⚠️ Attempting to reload previously crashed URL {_log_pretty_url(url)} failed again: {type(e).__name__}'
+ )
+
+ # Wait a bit for any transient blocking to resolve
+ await asyncio.sleep(1.0)
+
+ # Check if the reopened page is responsive
+ # self.logger.debug('Checking if reopened page is responsive...')
+ is_responsive = await self._is_page_responsive(new_page, timeout=2.0)
+
+ if is_responsive:
+ self.logger.info(f'✅ Page recovered and is now responsive after reopening on: {_log_pretty_url(url)}')
+ return True
+ else:
+ self.logger.warning(f'⚠️ Reopened page {_log_pretty_url(url)} is still unresponsive')
+ # Close the unresponsive page before returning
+ # This is critical to prevent the recovery flow from hanging
+ try:
+ await self._force_close_page_via_cdp(new_page.url)
+ except Exception as e:
+ self.logger.error(
+ f'❌ Failed to close crashed page {_log_pretty_url(url)} via CDP: {type(e).__name__}: {e} (something is very wrong or system is extremely overloaded)'
+ )
+ self.agent_current_page = None # Clear reference to closed page
+ return False
+
+ except Exception as e:
+ self.logger.error(f'❌ Retrying crashed page {_log_pretty_url(url)} failed: {type(e).__name__}: {e}')
+ return False
+
+ async def _create_blank_fallback_page(self, url: str) -> None:
+ """Create a new blank page as a fallback when recovery fails."""
+ self.logger.warning(
+ f'⚠️ Resetting to about:blank as fallback because browser is unable to load the original URL without crashing: {_log_pretty_url(url)}'
+ )
+ # self.logger.debug(f'Current agent_current_page: {self.agent_current_page}')
+
+ # Close any existing broken page
+ if self.agent_current_page and not self.agent_current_page.is_closed():
+ try:
+ await self.agent_current_page.close()
+ except Exception:
+ pass
+
+ # Create fresh page directly (avoid decorated methods to prevent circular dependency)
+ assert self.browser_context is not None, 'Browser context is not set'
+ new_page = await self.browser_context.new_page()
+ self.agent_current_page = new_page
+
+ # Update human tab reference if there is no human tab yet
+ if (not self.human_current_page) or self.human_current_page.is_closed():
+ self.human_current_page = new_page
+
+ # Set viewport for new tab
+ if self.browser_profile.viewport:
+ await new_page.set_viewport_size(self.browser_profile.viewport)
+
+ # Navigate to blank
+ try:
+ await new_page.goto('about:blank', wait_until='load', timeout=5000)
+ except Exception as e:
+ self.logger.error(
+ f'❌ Failed to navigate to about:blank: {type(e).__name__}: {e} (something is very wrong or system is extremely overloaded)'
+ )
+ raise
+
+ # Verify it's responsive
+ if not await self._is_page_responsive(new_page, timeout=1.0):
+ raise BrowserError(
+ 'Browser is unable to load any new about:blank pages (something is very wrong or browser is extremely overloaded)'
+ )
+
+ async def _recover_unresponsive_page(self, calling_method: str, timeout_ms: int | None = None) -> None:
+ """Recover from an unresponsive page by closing and reopening it."""
+ self.logger.warning(f'⚠️ Page JS engine became unresponsive in {calling_method}(), attempting recovery...')
- timeout_ms = min(3000, int(timeout_ms or self.browser_profile.default_navigation_timeout or 5000))
++ timeout_ms = min(
++ 3000,
++ int(timeout_ms or self.browser_profile.default_navigation_timeout or 5000),
++ )
+
+ # Prevent re-entrance
+ self._in_recovery = True
+ try:
+ # Get current URL before recovery
+ assert self.agent_current_page, 'Agent current page is not set'
+ current_url = self.agent_current_page.url
+ # self.logger.debug(f'Current URL: {current_url}')
+
+ # Clear page references
+ blocked_page = self.agent_current_page
+ self.agent_current_page = None
+ if blocked_page == self.human_current_page:
+ self.human_current_page = None
+
+ # Force-close the crashed page via CDP
+ self.logger.debug('🪓 Page Recovery Step 1/3: Force-closing crashed page via CDP...')
+ await self._force_close_page_via_cdp(current_url)
+
+ # Remove the closed page from browser_context.pages by forcing a refresh
+ # This prevents TargetClosedError when iterating through pages later
+ if self.browser_context and self.browser_context.pages:
+ # Additional cleanup: close any page objects that have the same url as the crashed page
+ # (could close too many pages by accident if we have a few different tabs on the same URL)
+ # Sometimes playwright doesn't immediately remove force-closed pages from the list
+ for page in self.browser_context.pages[:]: # Use slice to avoid modifying list during iteration
+ if page.url == current_url and not page.is_closed() and not is_new_tab_page(page.url):
+ try:
+ # Try to close it via playwright as well
+ await page.close()
+ self.logger.debug(
+ f'🪓 Closed 🅟 {str(id(page))[-2:]} because it has a known crash-causing URL: {_log_pretty_url(page.url)}'
+ )
+ except Exception:
+ pass # Page might already be closed via CDP
+
+ # Try to reopen the URL (in case blocking was transient)
+ self.logger.debug('🍼 Page Recovery Step 2/3: Trying to reopen the URL again...')
+ if await self._try_reopen_url(current_url, timeout_ms=timeout_ms):
+ self.logger.debug('✅ Page Recovery Step 3/3: Page loading succeeded after 2nd attempt!')
+ return # Success!
+
+ # If that failed, fall back to blank page
+ self.logger.debug(
+ '❌ Page Recovery Step 3/3: Loading the page a 2nd time failed as well, browser seems unable to load this URL without getting stuck, retreating to a safe page...'
+ )
+ await self._create_blank_fallback_page(current_url)
+
+ finally:
+ # Always clear recovery flag
+ self._in_recovery = False
+
# region - Browser Actions
- @observe_debug(name='take_screenshot')
- @require_initialization
+ @observe_debug(name='take_screenshot', ignore_output=True)
+ @retry(
+ retries=1, # try up to 1 time to take the screenshot (2 total attempts)
+ timeout=30, # allow up to 30s for each attempt (includes recovery time)
+ wait=1, # wait 1s between each attempt
+ semaphore_limit=2, # Allow 2 screenshots at a time to better utilize resources
+ semaphore_name='screenshot_global',
+ semaphore_scope='multiprocess',
+ semaphore_lax=True, # Continue without semaphore if it can't be acquired
+ semaphore_timeout=15, # Wait up to 15s for semaphore acquisition
+ )
+ @require_healthy_browser(usable_page=True, reopen_page=True)
@time_execution_async('--take_screenshot')
- async def take_screenshot(self, full_page: bool = False) -> str:
+ async def take_screenshot(self, full_page: bool = False) -> str | None:
"""
- Returns a base64 encoded screenshot of the current page.
+ Returns a base64 encoded screenshot of the current page using CDP.
+
+ The decorator order ensures:
+ 1. @retry runs first (outer decorator)
+ 2. @require_healthy_browser runs on each retry attempt
+ 3. Page responsiveness is checked before each screenshot attempt
+ 4. If page is unresponsive, it's recovered and the method is retried
"""
assert self.agent_current_page is not None, 'Agent current page is not set'
+ assert self.browser_context, 'Browser context is not set'
+ page = self.agent_current_page
+
+ if is_new_tab_page(page.url):
+ self.logger.warning(
+ f'▫️ Sending LLM 1px placeholder instead of real screenshot of: {_log_pretty_url(page.url)} (page empty)'
+ )
+ # not an exception because there's no point in retrying if we hit this, its always pointless to screenshot about:blank
+ # raise ValueError('Refusing to take unneeded screenshot of empty new tab page')
+ # return a 1px*1px white png to avoid wasting tokens
+ return 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII='
+
+ # Always bring page to front before rendering, otherwise it crashes in some cases, not sure why
try:
- # Take screenshot with comprehensive crash detection
- return await self._take_screenshot_hybrid()
- except Exception as e:
- # Check for specific crash-related errors
- error_str = str(e).lower()
- if any(
- crash_indicator in error_str
- for crash_indicator in [
- 'target crashed',
- 'target closed',
- 'context has been closed',
- 'page has been closed',
- 'crashed target',
- 'page is closed',
- 'timeout', # Add timeout to trigger reconnection with fresh page
- ]
- ):
- self.logger.warning(f'🚨 Detected crashed target during screenshot: {type(e).__name__}: {e}')
- self.logger.warning('🔄 Attempting browser restart...')
- try:
- self._reset_connection_state()
- await self.start()
- result = await self._take_screenshot_hybrid()
- self.logger.info('✅ Screenshot successful after browser restart')
- return result
- except Exception as restart_error:
- self.logger.error(
- f'❌ Failed to restart browser after crash: {type(restart_error).__name__}: {restart_error}'
- )
- raise Exception(f'Browser crashed and restart failed: {restart_error}')
+ await page.bring_to_front()
+ except Exception:
+ pass
+
+ # Take screenshot using CDP to get around playwright's unnecessary slowness and weird behavior
+ cdp_session = None
+ try:
+ # Create CDP session for the screenshot
+ self.logger.debug(
+ f'📸 Taking viewport-only PNG screenshot of page via fresh CDP session: {_log_pretty_url(page.url)}'
+ )
+ cdp_session = await self.browser_context.new_cdp_session(page) # type: ignore
+
+ # Capture screenshot via CDP
+ screenshot_response = await cdp_session.send(
+ 'Page.captureScreenshot',
+ {
+ 'captureBeyondViewport': False,
+ 'fromSurface': True,
+ 'format': 'png',
+ },
+ )
+
+ screenshot_b64 = screenshot_response.get('data')
+ if not screenshot_b64:
+ raise Exception(
+ f'CDP returned empty screenshot data for page {_log_pretty_url(page.url)}? (expected png base64)'
+ ) # have never seen this happen in practice
+
+ return screenshot_b64
+
+ except Exception as err:
+ error_str = f'{type(err).__name__}: {err}'
+ if 'timeout' in error_str.lower():
+ self.logger.warning(f'⏱️ Screenshot timed out on page {_log_pretty_url(page.url)} (possibly crashed): {error_str}')
else:
- self.logger.error(f'❌ Failed to take screenshot: {type(e).__name__}: {e}')
- raise
+ self.logger.error(f'❌ Screenshot failed on page {_log_pretty_url(page.url)} (possibly crashed): {error_str}')
+ raise
+ finally:
+ if cdp_session:
+ try:
+ await asyncio.wait_for(cdp_session.detach(), timeout=1.0)
+ except Exception:
+ pass
# region - User Actions
@@@ -3174,10 -3707,10 +3755,10 @@@
Creates a CSS selector for a DOM element, handling various edge cases and special characters.
Args:
-- element: The DOM element to create a selector for
++ element: The DOM element to create a selector for
Returns:
-- A valid CSS selector string
++ A valid CSS selector string
"""
try:
# Get base selector from XPath
@@@ -3273,10 -3806,11 +3854,10 @@@
return css_selector
except Exception:
- # Fallback to a more basic selector if something goes wrong
- tag_name = element.tag_name or '*'
- return f"{tag_name}[highlight_index='{element.highlight_index}']"
+ # Fallback: use XPath as a CSS selector (via Playwright's "xpath=" pseudo-selector)
+ return f'xpath={element.xpath or "//" + (element.tag_name or "*")}'
- @require_initialization
+ @require_healthy_browser(usable_page=True, reopen_page=True)
@time_execution_async('--is_visible')
async def _is_visible(self, element: ElementHandle) -> bool:
"""
@@@ -3292,9 -3826,9 +3873,9 @@@
return not is_hidden and bbox is not None and bbox['width'] > 0 and bbox['height'] > 0
- @require_initialization
+ @require_healthy_browser(usable_page=True, reopen_page=True)
@time_execution_async('--get_locate_element')
- async def get_locate_element(self, element: DOMElementNode) -> ElementHandle | None:
+ async def get_locate_element(self, element: EnhancedDOMTreeNode) -> ElementHandle | None:
page = await self.get_current_page()
current_frame = page
@@@ -3324,7 -3858,7 +3905,8 @@@
current_frame = current_frame.frame_locator(f'xpath={parent.xpath}')
css_selector = self._enhanced_css_selector_for_element(
-- element, include_dynamic_attributes=self.browser_profile.include_dynamic_attributes
++ element,
++ include_dynamic_attributes=self.browser_profile.include_dynamic_attributes,
)
try:
@@@ -3463,9 -3997,9 +4045,9 @@@
)
return None
- @require_initialization
+ @require_healthy_browser(usable_page=True, reopen_page=True)
@time_execution_async('--input_text_element_node')
- async def _input_text_element_node(self, element_node: DOMElementNode, text: str):
+ async def _input_text_element_node(self, element_node: EnhancedDOMTreeNode, text: str):
"""
Input text into an element with proper error handling and state management.
Handles different types of input fields and ensures proper element state before input.
@@@ -3528,9 -4062,9 +4110,9 @@@
self.logger.debug(
f'❌ Failed to input text into element: {repr(element_node)} on page {page_url}: {type(e).__name__}: {e}'
)
- raise BrowserError(f'Failed to input text into index {element_node.highlight_index}')
+ raise BrowserError(f'Failed to input text into element: {repr(element_node)}')
- @require_initialization
+ @require_healthy_browser(usable_page=True, reopen_page=True)
@time_execution_async('--switch_to_tab')
async def switch_to_tab(self, page_id: int) -> Page:
"""Switch to a specific tab by its page_id (aka tab index exposed to LLM)"""
@@@ -3576,112 -4110,16 +4158,17 @@@
return page
- @observe_debug(name='create_new_tab')
- @time_execution_async('--create_new_tab')
- async def create_new_tab(self, url: str | None = None) -> Page:
- """Create a new tab and optionally navigate to a URL"""
-
- # Add https:// if there's no protocol
- normalized_url = url
- if url:
- normalized_url = normalize_url(url)
-
- if not self._is_url_allowed(normalized_url):
- raise BrowserError(f'Cannot create new tab with non-allowed URL: {normalized_url}')
-
- try:
- assert self.browser_context is not None, 'Browser context is not set'
- new_page = await self.browser_context.new_page()
- except Exception:
- self.initialized = False
- self.browser_context = None # Clear the closed context
-
- if not self.initialized or not self.browser_context:
- # If we were initialized but lost connection, reset state first to avoid infinite loops
- if self.initialized and not self.browser_context:
- self.logger.warning(
- f'💔 Browser {self._connection_str} disconnected while trying to create a new tab, reconnecting...'
- )
- self._reset_connection_state()
- await self.start()
- assert self.browser_context, 'Browser context is not set'
- new_page = await self.browser_context.new_page()
-
- # Update agent tab reference
- self.agent_current_page = new_page
-
- # Update human tab reference if there is no human tab yet
- if (not self.human_current_page) or self.human_current_page.is_closed():
- self.human_current_page = new_page
-
- tab_idx = self.tabs.index(new_page)
- try:
- await new_page.wait_for_load_state()
- except Exception as e:
- self.logger.warning(
- f'⚠️ New page [{tab_idx}]{_log_pretty_url(new_page.url)} failed to fully load: {type(e).__name__}: {e}'
- )
-
- # Show DVD animation on new tab pages (after navigating to about:blank if needed)
- if not normalized_url and is_new_tab_page(new_page.url):
- # Navigate to about:blank if we're on chrome://new-tab-page to avoid security restrictions
- if new_page.url.startswith('chrome://new-tab-page'):
- await new_page.goto('about:blank')
- await self._show_dvd_screensaver_loading_animation(new_page)
-
- # Set the viewport size for the new tab
- if self.browser_profile.viewport:
- await new_page.set_viewport_size(self.browser_profile.viewport)
-
- if normalized_url:
- try:
- await new_page.goto(normalized_url, wait_until='domcontentloaded')
- await self._wait_for_page_and_frames_load(timeout_overwrite=1)
- except Exception as e:
- self.logger.error(f'❌ Error navigating to {normalized_url}: {type(e).__name__}: {e} (proceeding anyway...)')
-
- assert self.human_current_page is not None
- assert self.agent_current_page is not None
- # if url: # sometimes this does not pass because JS or HTTP redirects the page really fast
- # assert self.agent_current_page.url == url
- # else:
- # assert self.agent_current_page.url == 'about:blank'
-
- # if there are any unused new tab pages after we open a new tab, close them to clean up unused tabs
- assert self.browser_context is not None, 'Browser context is not set'
- # hacky way to be sure we only close our own tabs, check the title of the tab for our BrowserSession name
- title_of_our_setup_tab = (
- f'Starting agent {str(self.id)[-4:]}...' # set up by self._show_dvd_screensaver_loading_animation()
- )
- for page in self.browser_context.pages:
- try:
- # sometimes this fails, because the page is not accessible
- page_title = await self._get_page_title(page)
- except Exception:
- page_title = 'Title unavailable'
-
- if is_new_tab_page(page.url) and page != self.agent_current_page and page_title == title_of_our_setup_tab:
- await page.close()
- self.human_current_page = ( # in case we just closed the human's tab, fix the refs
- self.human_current_page if not self.human_current_page.is_closed() else self.agent_current_page
- )
- break # only close a maximum of one unused new tab page,
- # if multiple parallel agents share one BrowserSession
- # closing every new_page() tab (which start on new tab pages) causes lots of problems
- # (the title check is not enough when they share a single BrowserSession)
-
- return new_page
-
# region - Helper methods for easier access to the DOM
- @observe_debug(name='get_selector_map')
- @require_initialization
++
+ @observe_debug(name='get_selector_map', ignore_output=True, ignore_input=True)
+ @require_healthy_browser(usable_page=True, reopen_page=True)
- async def get_selector_map(self) -> SelectorMap:
+ async def get_selector_map(self) -> DOMSelectorMap:
if self._cached_browser_state_summary is None:
return {}
- return self._cached_browser_state_summary.selector_map
+ return self._cached_browser_state_summary.dom_state.selector_map
- @observe_debug(name='get_element_by_index')
- @require_initialization
+ @observe_debug(ignore_input=True, ignore_output=True, name='get_element_by_index')
+ @require_healthy_browser(usable_page=True, reopen_page=True)
async def get_element_by_index(self, index: int) -> ElementHandle | None:
selector_map = await self.get_selector_map()
element_handle = await self.get_locate_element(selector_map[index])
@@@ -3698,13 -4136,17 +4185,13 @@@
return False
@staticmethod
- def is_file_input(node: DOMElementNode) -> bool:
- return (
- isinstance(node, DOMElementNode)
- and getattr(node, 'tag_name', '').lower() == 'input'
- and node.attributes.get('type', '').lower() == 'file'
- )
+ def is_file_input(node: EnhancedDOMTreeNode) -> bool:
+ return node.tag_name == 'input' and node.attributes.get('type', '').lower() == 'file'
- @require_initialization
+ @require_healthy_browser(usable_page=True, reopen_page=True)
async def find_file_upload_element_by_index(
self, index: int, max_height: int = 3, max_descendant_depth: int = 3
- ) -> DOMElementNode | None:
+ ) -> EnhancedDOMTreeNode | None:
"""
Find the closest file input to the selected element by traversing the DOM bottom-up.
At each level (up to max_height ancestors):
@@@ -3829,11 -4271,67 +4316,67 @@@
return page_info
- @require_initialization
+ async def _scroll_with_cdp_gesture(self, page: Page, pixels: int) -> bool:
+ """
+ Scroll using CDP Input.synthesizeScrollGesture for universal compatibility.
+
+ Args:
- page: The page to scroll
- pixels: Number of pixels to scroll (positive = up, negative = down)
++ page: The page to scroll
++ pixels: Number of pixels to scroll (positive = up, negative = down)
+
+ Returns:
- True if successful, False if failed
++ True if successful, False if failed
+ """
+ try:
+ # Use CDP to synthesize scroll gesture - works in all contexts including PDFs
+ cdp_session = await page.context.new_cdp_session(page) # type: ignore
+
+ # Get viewport center for scroll origin
+ viewport = await page.evaluate("""
+ () => ({
+ width: window.innerWidth,
+ height: window.innerHeight
+ })
+ """)
+
+ center_x = viewport['width'] // 2
+ center_y = viewport['height'] // 2
+
+ await cdp_session.send(
+ 'Input.synthesizeScrollGesture',
+ {
+ 'x': center_x,
+ 'y': center_y,
+ 'xDistance': 0,
+ 'yDistance': -pixels, # Negative = scroll down, Positive = scroll up
+ 'gestureSourceType': 'mouse', # Use mouse gestures for better compatibility
+ 'speed': 3000, # Pixels per second
+ },
+ )
+
+ try:
+ await asyncio.wait_for(cdp_session.detach(), timeout=1.0)
+ except (TimeoutError, Exception):
+ pass
+ self.logger.debug(f'📄 Scrolled via CDP Input.synthesizeScrollGesture: {pixels}px')
+ return True
+
+ except Exception as e:
+ self.logger.warning(f'❌ Scrolling via CDP Input.synthesizeScrollGesture failed: {type(e).__name__}: {e}')
+ return False
+
+ @require_healthy_browser(usable_page=True, reopen_page=True)
async def _scroll_container(self, pixels: int) -> None:
- """Scroll the element that truly owns vertical scroll.Starts at the focused node ➜ climbs to the first big, scroll-enabled ancestor otherwise picks the first scrollable element or the root, then calls `element.scrollBy` (or `window.scrollBy` for the root) by the supplied pixel value."""
+ """Scroll using CDP gesture synthesis with JavaScript fallback."""
+
+ page = await self.get_current_page()
+
+ # Try CDP scroll gesture first (works universally including PDFs)
+ if await self._scroll_with_cdp_gesture(page, pixels):
+ return
- # An element can *really* scroll if: overflow-y is auto|scroll|overlay, it has more content than fits, its own viewport is not a postage stamp (more than 50 % of window).
+ # Fallback to JavaScript for older browsers or when CDP fails
+ self.logger.debug('Falling back to JavaScript scrolling')
SMART_SCROLL_JS = """(dy) => {
const bigEnough = el => el.clientHeight >= window.innerHeight * 0.5;
const canScroll = el =>
@@@ -3877,96 -4374,262 +4419,262 @@@
# all in one JS function for speed, we want as few roundtrip CDP calls as possible
# between opening the tab and showing the animation
- await page.evaluate(
- """(browser_session_label) => {
- const animated_title = `Starting agent ${browser_session_label}...`;
- if (document.title === animated_title) {
- return; // already run on this tab, dont run again
- }
- document.title = animated_title;
-
- // Create the main overlay
- const loadingOverlay = document.createElement('div');
- loadingOverlay.id = 'pretty-loading-animation';
- loadingOverlay.style.position = 'fixed';
- loadingOverlay.style.top = '0';
- loadingOverlay.style.left = '0';
- loadingOverlay.style.width = '100vw';
- loadingOverlay.style.height = '100vh';
- loadingOverlay.style.background = '#000';
- loadingOverlay.style.zIndex = '99999';
- loadingOverlay.style.overflow = 'hidden';
-
- // Create the image element
- const img = document.createElement('img');
- img.src = 'https://cf.browser-use.com/logo.svg';
- img.alt = 'Browser-Use';
- img.style.width = '200px';
- img.style.height = 'auto';
- img.style.position = 'absolute';
- img.style.left = '0px';
- img.style.top = '0px';
- img.style.zIndex = '2';
- img.style.opacity = '0.8';
-
- loadingOverlay.appendChild(img);
- document.body.appendChild(loadingOverlay);
-
- // DVD screensaver bounce logic
- let x = Math.random() * (window.innerWidth - 300);
- let y = Math.random() * (window.innerHeight - 300);
- let dx = 1.2 + Math.random() * 0.4; // px per frame
- let dy = 1.2 + Math.random() * 0.4;
- // Randomize direction
- if (Math.random() > 0.5) dx = -dx;
- if (Math.random() > 0.5) dy = -dy;
-
- function animate() {
- const imgWidth = img.offsetWidth || 300;
- const imgHeight = img.offsetHeight || 300;
- x += dx;
- y += dy;
-
- if (x <= 0) {
- x = 0;
- dx = Math.abs(dx);
- } else if (x + imgWidth >= window.innerWidth) {
- x = window.innerWidth - imgWidth;
- dx = -Math.abs(dx);
+ try:
+ await page.evaluate(
+ """(browser_session_label) => {
+ const animated_title = `Starting agent ${browser_session_label}...`;
+ if (document.title === animated_title) {
+ return; // already run on this tab, dont run again
}
- if (y <= 0) {
- y = 0;
- dy = Math.abs(dy);
- } else if (y + imgHeight >= window.innerHeight) {
- y = window.innerHeight - imgHeight;
- dy = -Math.abs(dy);
+ document.title = animated_title;
+
+ // Create the main overlay
+ const loadingOverlay = document.createElement('div');
+ loadingOverlay.id = 'pretty-loading-animation';
+ loadingOverlay.style.position = 'fixed';
+ loadingOverlay.style.top = '0';
+ loadingOverlay.style.left = '0';
+ loadingOverlay.style.width = '100vw';
+ loadingOverlay.style.height = '100vh';
+ loadingOverlay.style.background = '#000';
+ loadingOverlay.style.zIndex = '99999';
+ loadingOverlay.style.overflow = 'hidden';
+
+ // Create the image element
+ const img = document.createElement('img');
+ img.src = 'https://cf.browser-use.com/logo.svg';
+ img.alt = 'Browser-Use';
+ img.style.width = '200px';
+ img.style.height = 'auto';
+ img.style.position = 'absolute';
+ img.style.left = '0px';
+ img.style.top = '0px';
+ img.style.zIndex = '2';
+ img.style.opacity = '0.8';
+
+ loadingOverlay.appendChild(img);
+ document.body.appendChild(loadingOverlay);
+
+ // DVD screensaver bounce logic
+ let x = Math.random() * (window.innerWidth - 300);
+ let y = Math.random() * (window.innerHeight - 300);
+ let dx = 1.2 + Math.random() * 0.4; // px per frame
+ let dy = 1.2 + Math.random() * 0.4;
+ // Randomize direction
+ if (Math.random() > 0.5) dx = -dx;
+ if (Math.random() > 0.5) dy = -dy;
+
+ function animate() {
+ const imgWidth = img.offsetWidth || 300;
+ const imgHeight = img.offsetHeight || 300;
+ x += dx;
+ y += dy;
+
+ if (x <= 0) {
+ x = 0;
+ dx = Math.abs(dx);
+ } else if (x + imgWidth >= window.innerWidth) {
+ x = window.innerWidth - imgWidth;
+ dx = -Math.abs(dx);
+ }
+ if (y <= 0) {
+ y = 0;
+ dy = Math.abs(dy);
+ } else if (y + imgHeight >= window.innerHeight) {
+ y = window.innerHeight - imgHeight;
+ dy = -Math.abs(dy);
+ }
+
+ img.style.left = `${x}px`;
+ img.style.top = `${y}px`;
+
+ requestAnimationFrame(animate);
}
+ animate();
+
+ // Responsive: update bounds on resize
+ window.addEventListener('resize', () => {
+ x = Math.min(x, window.innerWidth - img.offsetWidth);
+ y = Math.min(y, window.innerHeight - img.offsetHeight);
+ });
+
+ // Add a little CSS for smoothness
+ const style = document.createElement('style');
+ style.textContent = `
+ #pretty-loading-animation {
+ /*backdrop-filter: blur(2px) brightness(0.9);*/
+ }
+ #pretty-loading-animation img {
+ user-select: none;
+ pointer-events: none;
+ }
+ `;
+ document.head.appendChild(style);
+ }""",
+ str(self.id)[-4:],
+ )
+ except Exception as e:
+ self.logger.debug(f'❌ Failed to show 📀 DVD loading animation: {type(e).__name__}: {e}')
- img.style.left = `${x}px`;
- img.style.top = `${y}px`;
+ @observe_debug(ignore_input=True, ignore_output=True, name='get_state_summary_with_fallback')
+ @require_healthy_browser(usable_page=True, reopen_page=True)
+ @time_execution_async('--get_state_summary_with_fallback')
+ async def get_state_summary_with_fallback(self, cache_clickable_elements_hashes: bool = True) -> BrowserStateSummary:
+ """Get browser state with fallback to minimal state on errors
- requestAnimationFrame(animate);
- }
- animate();
+ This method first tries to get a full state summary. If that fails,
+ it falls back to a minimal state summary to allow basic navigation.
- // Responsive: update bounds on resize
- window.addEventListener('resize', () => {
- x = Math.min(x, window.innerWidth - img.offsetWidth);
- y = Math.min(y, window.innerHeight - img.offsetHeight);
- });
+ Parameters:
+ -----------
+ cache_clickable_elements_hashes: bool
- If True, cache the clickable elements hashes for the current state.
++ If True, cache the clickable elements hashes for the current state.
- // Add a little CSS for smoothness
- const style = document.createElement('style');
- style.textContent = `
- #pretty-loading-animation {
- /*backdrop-filter: blur(2px) brightness(0.9);*/
- }
- #pretty-loading-animation img {
- user-select: none;
- pointer-events: none;
+ Returns:
+ --------
+ BrowserStateSummary: Either full state or minimal fallback state
+ """
+ # Try 1: Full state summary (current implementation)
+ try:
+ return await self.get_state_summary(cache_clickable_elements_hashes)
+ except Exception as e:
+ self.logger.warning(f'Full state retrieval failed: {type(e).__name__}: {e}')
+ self.logger.warning('🔄 Falling back to minimal state summary')
+
+ # Try 2: Minimal state summary as fallback
+ return await self.get_minimal_state_summary()
+
+ async def _is_pdf_viewer(self, page: Page) -> bool:
+ """
+ Check if the current page is displaying a PDF in Chrome's PDF viewer.
+ Returns True if PDF is detected, False otherwise.
+ """
+ try:
+ is_pdf_viewer = await page.evaluate("""
+ () => {
+ // Check for Chrome's built-in PDF viewer (updated selector)
+ const pdfEmbed = document.querySelector('embed[type="application/x-google-chrome-pdf"]') ||
+ document.querySelector('embed[type="application/pdf"]');
+ const isPdfViewer = !!pdfEmbed;
+
+ // Also check if the URL ends with .pdf or has PDF content-type
+ const url = window.location.href;
+ const isPdfUrl = url.toLowerCase().includes('.pdf') ||
+ document.contentType === 'application/pdf';
+
+ return isPdfViewer || isPdfUrl;
}
- `;
- document.head.appendChild(style);
- }""",
- str(self.id)[-4:],
- )
+ """)
+ return is_pdf_viewer
+ except Exception as e:
+ self.logger.debug(f'Error checking PDF viewer: {type(e).__name__}: {e}')
+ return False
+
+ async def _auto_download_pdf_if_needed(self, page: Page) -> str | None:
+ """
+ Check if the current page is a PDF viewer and automatically download the PDF if so.
+ Returns the download path if a PDF was downloaded, None otherwise.
+ """
+ if not self.browser_profile.downloads_path or not self._auto_download_pdfs:
+ return None
+
+ try:
+ # Check if we're in a PDF viewer
+ is_pdf_viewer = await self._is_pdf_viewer(page)
+ self.logger.debug(f'is_pdf_viewer: {is_pdf_viewer}')
+
+ if not is_pdf_viewer:
+ return None
+
+ # Get the PDF URL
+ pdf_url = page.url
+
+ # Check if we've already downloaded this PDF
+ pdf_filename = os.path.basename(pdf_url.split('?')[0]) # Remove query params
+ if not pdf_filename or not pdf_filename.endswith('.pdf'):
+ # Generate filename from URL
+ from urllib.parse import urlparse
+
+ parsed = urlparse(pdf_url)
+ pdf_filename = os.path.basename(parsed.path) or 'document.pdf'
+ if not pdf_filename.endswith('.pdf'):
+ pdf_filename += '.pdf'
+
+ # Check if already downloaded
+ expected_path = os.path.join(self.browser_profile.downloads_path, pdf_filename)
+ if any(os.path.basename(downloaded) == pdf_filename for downloaded in self._downloaded_files):
+ self.logger.debug(f'📄 PDF already downloaded: {pdf_filename}')
+ return None
+
+ self.logger.info(f'📄 Auto-downloading PDF from: {pdf_url}')
+
+ # Download the actual PDF file using JavaScript fetch
+ # Note: This should hit the browser cache since Chrome already downloaded the PDF to display it
+ try:
+ self.logger.debug(f'Downloading PDF from URL: {pdf_url}')
+
+ # Properly escape the URL to prevent JavaScript injection
+ escaped_pdf_url = json.dumps(pdf_url)
+
+ download_result = await page.evaluate(f"""
+ async () => {{
+ try {{
+ // Use fetch with cache: 'force-cache' to prioritize cached version
+ const response = await fetch({escaped_pdf_url}, {{
+ cache: 'force-cache'
+ }});
+ if (!response.ok) {{
+ throw new Error(`HTTP error! status: ${{response.status}}`);
+ }}
+ const blob = await response.blob();
+ const arrayBuffer = await blob.arrayBuffer();
+ const uint8Array = new Uint8Array(arrayBuffer);
+
+ // Log whether this was served from cache
+ const fromCache = response.headers.has('age') ||
+ !response.headers.has('date') ||
+ performance.getEntriesByName({escaped_pdf_url}).some(entry =>
+ entry.transferSize === 0 || entry.transferSize < entry.encodedBodySize
+ );
+
+ return {{
+ data: Array.from(uint8Array),
+ fromCache: fromCache,
+ responseSize: uint8Array.length,
+ transferSize: response.headers.get('content-length') || 'unknown'
+ }};
+ }} catch (error) {{
+ throw new Error(`Fetch failed: ${{error.message}}`);
+ }}
+ }}
+ """)
+
+ if download_result and download_result.get('data') and len(download_result['data']) > 0:
+ # Ensure unique filename
+ unique_filename = await self._get_unique_filename(self.browser_profile.downloads_path, pdf_filename)
+ download_path = os.path.join(self.browser_profile.downloads_path, unique_filename)
+
+ # Save the PDF asynchronously
+ async with await anyio.open_file(download_path, 'wb') as f:
+ await f.write(bytes(download_result['data']))
+
+ # Track the downloaded file
+ self._downloaded_files.append(download_path)
+
+ # Log cache information
+ cache_status = 'from cache' if download_result.get('fromCache') else 'from network'
+ response_size = download_result.get('responseSize', 0)
+ self.logger.info(f'📄 Auto-downloaded PDF ({cache_status}, {response_size:,} bytes): {download_path}')
+
+ return download_path
+ else:
+ self.logger.warning(f'⚠️ No data received when downloading PDF from {pdf_url}')
+ return None
+
+ except Exception as e:
+ self.logger.warning(f'⚠️ Failed to auto-download PDF from {pdf_url}: {type(e).__name__}: {e}')
+ return None
+
+ except Exception as e:
+ self.logger.warning(f'⚠️ Error in PDF auto-download check: {type(e).__name__}: {e}')
+ return None
diff --cc pyproject.toml
index 5a233d392,fee168db4..8ec92290f
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -41,7 -41,7 +41,8 @@@ dependencies =
"google-auth-oauthlib>=1.2.2",
"mcp>=1.10.1",
"pypdf>=5.7.0",
+ "cdp-use>=1.3.2",
+ "markdown-pdf>=1.7",
]
# google-api-core: only used for Google LLM APIs
# pyperclip: only used for examples that use copy/paste