Skip to content

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

refactor to use new BrowserSession model

Nick Sweeting90dad4a39a79
diff --git a/.github/ISSUE_TEMPLATE/1_element_detection_bug.yml b/.github/ISSUE_TEMPLATE/1_element_detection_bug.yml
index 4af84f40b..b893e15b0 100644
--- a/.github/ISSUE_TEMPLATE/1_element_detection_bug.yml
+++ b/.github/ISSUE_TEMPLATE/1_element_detection_bug.yml
@@ -91,12 +91,12 @@ body:
placeholder: |
from dotenv import load_dotenv
load_dotenv()
- from browser_use import Agent, Browser, Controller
+ from browser_use import Agent, BrowserSession, Controller
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o")
- browser = Browser(chrome_binary_path='/usr/bin/google-chrome')
- agent = Agent(llm=llm, browser=browser))
+ browser_session = BrowserSession(executable_path='/usr/bin/google-chrome')
+ agent = Agent(llm=llm, browser_session=browser_session))
...
- type: textarea
diff --git a/.github/ISSUE_TEMPLATE/2_bug_report.yml b/.github/ISSUE_TEMPLATE/2_bug_report.yml
index aaf173559..13e427e57 100644
--- a/.github/ISSUE_TEMPLATE/2_bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/2_bug_report.yml
@@ -38,12 +38,12 @@ body:
placeholder: |
from dotenv import load_dotenv
load_dotenv()
- from browser_use import Agent, Browser, Controller
+ from browser_use import Agent, BrowserSession, Controller
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o")
- browser = Browser(chrome_binary_path='/usr/bin/google-chrome')
- agent = Agent(llm=llm, browser=browser))
+ browser_session = BrowserSession(executable_path='/usr/bin/google-chrome')
+ agent = Agent(llm=llm, browser_session=browser_session))
...
- type: dropdown
diff --git a/browser_use/__init__.py b/browser_use/__init__.py
index 06b3d3917..87ec8ad42 100644
--- a/browser_use/__init__.py
+++ b/browser_use/__init__.py
@@ -10,26 +10,26 @@ from browser_use.logging_config import setup_logging
setup_logging()
-from browser_use.agent.prompts import SystemPrompt as SystemPrompt
-from browser_use.agent.service import Agent as Agent
-from browser_use.agent.views import ActionModel as ActionModel
-from browser_use.agent.views import ActionResult as ActionResult
-from browser_use.agent.views import AgentHistoryList as AgentHistoryList
-from browser_use.browser.browser import Browser as Browser
-from browser_use.browser.browser import BrowserConfig as BrowserConfig
-from browser_use.browser.context import BrowserContextConfig
-from browser_use.controller.service import Controller as Controller
-from browser_use.dom.service import DomService as DomService
+from browser_use.agent.prompts import SystemPrompt
+from browser_use.agent.service import Agent
+from browser_use.agent.views import ActionModel, ActionResult, AgentHistoryList
+from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.browser.compat import Browser, BrowserConfig, BrowserContext, BrowserContextConfig
+from browser_use.controller.service import Controller
+from browser_use.dom.service import DomService
__all__ = [
'Agent',
'Browser',
'BrowserConfig',
+ 'BrowserSession',
+ 'BrowserProfile',
'Controller',
'DomService',
'SystemPrompt',
'ActionResult',
'ActionModel',
'AgentHistoryList',
+ 'BrowserContext',
'BrowserContextConfig',
]
diff --git a/browser_use/agent/memory/service.py b/browser_use/agent/memory/service.py
index cb5d41dc2..f5ea3d1d2 100644
--- a/browser_use/agent/memory/service.py
+++ b/browser_use/agent/memory/service.py
@@ -57,7 +57,7 @@ class Memory:
self.config.embedder_dims = 512
else:
# Ensure LLM instance is set in the config
- self.config = MemoryConfig(config) # re-validate user-provided config
+ self.config = MemoryConfig(**config.model_dump()) # re-validate untrusted user-provided config
self.config.llm_instance = llm
# Check for required packages
diff --git a/browser_use/agent/message_manager/__init__.py b/browser_use/agent/message_manager/__init__.py
new file mode 100644
index 000000000..072c3dd81
--- /dev/null
+++ b/browser_use/agent/message_manager/__init__.py
@@ -0,0 +1,4 @@
+"""
+Message Manager for Browser Use Agent.
+"""
+# Fix circular import by only importing names in functions where needed
diff --git a/browser_use/agent/playwright_script_generator.py b/browser_use/agent/playwright_script_generator.py
index d158a79e9..01e658a61 100644
--- a/browser_use/agent/playwright_script_generator.py
+++ b/browser_use/agent/playwright_script_generator.py
@@ -1,722 +1,721 @@
-import json
-import logging
-from pathlib import Path
-from typing import Any
-
-from browser_use.browser.browser import BrowserConfig
-from browser_use.browser.context import BrowserContextConfig
-
-logger = logging.getLogger(__name__)
-
-
-class PlaywrightScriptGenerator:
- """Generates a Playwright script from AgentHistoryList."""
-
- def __init__(
- self,
- history_list: list[dict[str, Any]],
- sensitive_data_keys: list[str] | None = None,
- browser_config: BrowserConfig | None = None,
- context_config: BrowserContextConfig | None = None,
- ):
- """
- Initializes the script generator.
-
- Args:
- history_list: A list of dictionaries, where each dictionary represents an AgentHistory item.
- Expected to be raw dictionaries from `AgentHistoryList.model_dump()`.
- sensitive_data_keys: A list of keys used as placeholders for sensitive data.
- browser_config: Configuration from the original Browser instance.
- context_config: Configuration from the original BrowserContext instance.
- """
- self.history = history_list
- self.sensitive_data_keys = sensitive_data_keys or []
- self.browser_config = browser_config
- self.context_config = context_config
- self._imports_helpers_added = False
- self._page_counter = 0 # Track pages for tab management
-
- # Dictionary mapping action types to handler methods
- self._action_handlers = {
- 'go_to_url': self._map_go_to_url,
- 'wait': self._map_wait,
- 'input_text': self._map_input_text,
- 'click_element': self._map_click_element,
- 'click_element_by_index': self._map_click_element, # Map legacy action
- 'scroll_down': self._map_scroll_down,
- 'scroll_up': self._map_scroll_up,
- 'send_keys': self._map_send_keys,
- 'go_back': self._map_go_back,
- 'open_tab': self._map_open_tab,
- 'close_tab': self._map_close_tab,
- 'switch_tab': self._map_switch_tab,
- 'search_google': self._map_search_google,
- 'drag_drop': self._map_drag_drop,
- 'extract_content': self._map_extract_content,
- 'click_download_button': self._map_click_download_button,
- 'done': self._map_done,
- }
-
- def _generate_browser_launch_args(self) -> str:
- """Generates the arguments string for browser launch based on BrowserConfig."""
- if not self.browser_config:
- # Default launch if no config provided
- return 'headless=False'
-
- args_dict = {
- 'headless': self.browser_config.headless,
- # Add other relevant launch options here based on self.browser_config
- # Example: 'proxy': self.browser_config.proxy.model_dump() if self.browser_config.proxy else None
- # Example: 'args': self.browser_config.extra_browser_args # Be careful inheriting args
- }
- if self.browser_config.proxy:
- args_dict['proxy'] = self.browser_config.proxy.model_dump()
-
- # Filter out None values
- args_dict = {k: v for k, v in args_dict.items() if v is not None}
-
- # Format as keyword arguments string
- args_str = ', '.join(f'{key}={repr(value)}' for key, value in args_dict.items())
- return args_str
-
- def _generate_context_options(self) -> str:
- """Generates the options string for context creation based on BrowserContextConfig."""
- if not self.context_config:
- return '' # Default context
-
- options_dict = {}
-
- # Map relevant BrowserContextConfig fields to Playwright context options
- if self.context_config.user_agent:
- options_dict['user_agent'] = self.context_config.user_agent
- if self.context_config.locale:
- options_dict['locale'] = self.context_config.locale
- if self.context_config.permissions:
- options_dict['permissions'] = self.context_config.permissions
- if self.context_config.geolocation:
- options_dict['geolocation'] = self.context_config.geolocation
- if self.context_config.timezone_id:
- options_dict['timezone_id'] = self.context_config.timezone_id
- if self.context_config.http_credentials:
- options_dict['http_credentials'] = self.context_config.http_credentials
- if self.context_config.is_mobile is not None:
- options_dict['is_mobile'] = self.context_config.is_mobile
- if self.context_config.has_touch is not None:
- options_dict['has_touch'] = self.context_config.has_touch
- if self.context_config.save_recording_path:
- options_dict['record_video_dir'] = self.context_config.save_recording_path
- if self.context_config.save_har_path:
- options_dict['record_har_path'] = self.context_config.save_har_path
-
- # Handle viewport/window size
- if self.context_config.no_viewport:
- options_dict['no_viewport'] = True
- elif hasattr(self.context_config, 'window_width') and hasattr(self.context_config, 'window_height'):
- options_dict['viewport'] = {
- 'width': self.context_config.window_width,
- 'height': self.context_config.window_height,
- }
-
- # Note: cookies_file and save_downloads_path are handled separately
-
- # Filter out None values
- options_dict = {k: v for k, v in options_dict.items() if v is not None}
-
- # Format as keyword arguments string
- options_str = ', '.join(f'{key}={repr(value)}' for key, value in options_dict.items())
- return options_str
-
- def _get_imports_and_helpers(self) -> list[str]:
- """Generates necessary import statements (excluding helper functions)."""
- # Return only the standard imports needed by the main script body
- return [
- 'import asyncio',
- 'import json',
- 'import os',
- 'import sys',
- 'from pathlib import Path', # Added Path import
- 'import urllib.parse', # Needed for search_google
- 'from playwright.async_api import async_playwright, Page, BrowserContext', # Added BrowserContext
- 'from dotenv import load_dotenv',
- '',
- '# Load environment variables',
- 'load_dotenv(override=True)',
- '',
- # Helper function definitions are no longer here
- ]
-
- def _get_sensitive_data_definitions(self) -> list[str]:
- """Generates the SENSITIVE_DATA dictionary definition."""
- if not self.sensitive_data_keys:
- return ['SENSITIVE_DATA = {}', '']
-
- lines = ['# Sensitive data placeholders mapped to environment variables']
- lines.append('SENSITIVE_DATA = {')
- for key in self.sensitive_data_keys:
- env_var_name = key.upper()
- default_value_placeholder = f'YOUR_{env_var_name}'
- lines.append(f' "{key}": os.getenv("{env_var_name}", {json.dumps(default_value_placeholder)}),')
- lines.append('}')
- lines.append('')
- return lines
-
- def _get_selector_for_action(self, history_item: dict, action_index_in_step: int) -> str | None:
- """
- Gets the selector (preferring XPath) for a given action index within a history step.
- Formats the XPath correctly for Playwright.
- """
- state = history_item.get('state')
- if not isinstance(state, dict):
- return None
- interacted_elements = state.get('interacted_element')
- if not isinstance(interacted_elements, list):
- return None
- if action_index_in_step >= len(interacted_elements):
- return None
- element_data = interacted_elements[action_index_in_step]
- if not isinstance(element_data, dict):
- return None
-
- # Prioritize XPath
- xpath = element_data.get('xpath')
- if isinstance(xpath, str) and xpath.strip():
- if not xpath.startswith('xpath=') and not xpath.startswith('/') and not xpath.startswith('//'):
- xpath_selector = f'xpath=//{xpath}' # Make relative if not already
- elif not xpath.startswith('xpath='):
- xpath_selector = f'xpath={xpath}' # Add prefix if missing
- else:
- xpath_selector = xpath
- return xpath_selector
-
- # Fallback to CSS selector if XPath is missing
- css_selector = element_data.get('css_selector')
- if isinstance(css_selector, str) and css_selector.strip():
- return css_selector # Use CSS selector as is
-
- logger.warning(
- f'Could not find a usable XPath or CSS selector for action index {action_index_in_step} (element index {element_data.get("highlight_index", "N/A")}).'
- )
- return None
-
- def _get_goto_timeout(self) -> int:
- """Gets the page navigation timeout in milliseconds."""
- default_timeout = 90000 # Default 90 seconds
- if self.context_config and self.context_config.maximum_wait_page_load_time:
- # Convert seconds to milliseconds
- return int(self.context_config.maximum_wait_page_load_time * 1000)
- return default_timeout
-
- # --- Action Mapping Methods ---
- def _map_go_to_url(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- url = params.get('url')
- goto_timeout = self._get_goto_timeout()
- script_lines = []
- if url and isinstance(url, str):
- escaped_url = json.dumps(url)
- script_lines.append(f' print(f"Navigating to: {url} ({step_info_str})")')
- script_lines.append(f' await page.goto({escaped_url}, timeout={goto_timeout})')
- script_lines.append(f" await page.wait_for_load_state('load', timeout={goto_timeout})")
- script_lines.append(' await page.wait_for_timeout(1000)') # Short pause
- else:
- script_lines.append(f' # Skipping go_to_url ({step_info_str}): missing or invalid url')
- return script_lines
-
- def _map_wait(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- seconds = params.get('seconds', 3)
- try:
- wait_seconds = int(seconds)
- except (ValueError, TypeError):
- wait_seconds = 3
- return [
- f' print(f"Waiting for {wait_seconds} seconds... ({step_info_str})")',
- f' await asyncio.sleep({wait_seconds})',
- ]
-
- def _map_input_text(
- self, params: dict, history_item: dict, action_index_in_step: int, step_info_str: str, **kwargs
- ) -> list[str]:
- index = params.get('index')
- text = params.get('text', '')
- selector = self._get_selector_for_action(history_item, action_index_in_step)
- script_lines = []
- if selector and index is not None:
- clean_text_expression = f'replace_sensitive_data({json.dumps(str(text))}, SENSITIVE_DATA)'
- escaped_selector = json.dumps(selector)
- escaped_step_info = json.dumps(step_info_str)
- script_lines.append(
- f' await _try_locate_and_act(page, {escaped_selector}, "fill", text={clean_text_expression}, step_info={escaped_step_info})'
- )
- else:
- script_lines.append(
- f' # Skipping input_text ({step_info_str}): missing index ({index}) or selector ({selector})'
- )
- return script_lines
-
- def _map_click_element(
- self, params: dict, history_item: dict, action_index_in_step: int, step_info_str: str, action_type: str, **kwargs
- ) -> list[str]:
- if action_type == 'click_element_by_index':
- logger.warning(f"Mapping legacy 'click_element_by_index' to 'click_element' ({step_info_str})")
- index = params.get('index')
- selector = self._get_selector_for_action(history_item, action_index_in_step)
- script_lines = []
- if selector and index is not None:
- escaped_selector = json.dumps(selector)
- escaped_step_info = json.dumps(step_info_str)
- script_lines.append(
- f' await _try_locate_and_act(page, {escaped_selector}, "click", step_info={escaped_step_info})'
- )
- else:
- script_lines.append(
- f' # Skipping {action_type} ({step_info_str}): missing index ({index}) or selector ({selector})'
- )
- return script_lines
-
- def _map_scroll_down(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- amount = params.get('amount')
- script_lines = []
- if amount and isinstance(amount, int):
- script_lines.append(f' print(f"Scrolling down by {amount} pixels ({step_info_str})")')
- script_lines.append(f" await page.evaluate('window.scrollBy(0, {amount})')")
- else:
- script_lines.append(f' print(f"Scrolling down by one page height ({step_info_str})")')
- script_lines.append(" await page.evaluate('window.scrollBy(0, window.innerHeight)')")
- script_lines.append(' await page.wait_for_timeout(500)')
- return script_lines
-
- def _map_scroll_up(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- amount = params.get('amount')
- script_lines = []
- if amount and isinstance(amount, int):
- script_lines.append(f' print(f"Scrolling up by {amount} pixels ({step_info_str})")')
- script_lines.append(f" await page.evaluate('window.scrollBy(0, -{amount})')")
- else:
- script_lines.append(f' print(f"Scrolling up by one page height ({step_info_str})")')
- script_lines.append(" await page.evaluate('window.scrollBy(0, -window.innerHeight)')")
- script_lines.append(' await page.wait_for_timeout(500)')
- return script_lines
-
- def _map_send_keys(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- keys = params.get('keys')
- script_lines = []
- if keys and isinstance(keys, str):
- escaped_keys = json.dumps(keys)
- script_lines.append(f' print(f"Sending keys: {keys} ({step_info_str})")')
- script_lines.append(f' await page.keyboard.press({escaped_keys})')
- script_lines.append(' await page.wait_for_timeout(500)')
- else:
- script_lines.append(f' # Skipping send_keys ({step_info_str}): missing or invalid keys')
- return script_lines
-
- def _map_go_back(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- goto_timeout = self._get_goto_timeout()
- return [
- ' await asyncio.sleep(60) # Wait 1 minute (important) before going back',
- f' print(f"Navigating back using browser history ({step_info_str})")',
- f' await page.go_back(timeout={goto_timeout})',
- f" await page.wait_for_load_state('load', timeout={goto_timeout})",
- ' await page.wait_for_timeout(1000)',
- ]
-
- def _map_open_tab(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- url = params.get('url')
- goto_timeout = self._get_goto_timeout()
- script_lines = []
- if url and isinstance(url, str):
- escaped_url = json.dumps(url)
- script_lines.append(f' print(f"Opening new tab and navigating to: {url} ({step_info_str})")')
- script_lines.append(' page = await context.new_page()')
- script_lines.append(f' await page.goto({escaped_url}, timeout={goto_timeout})')
- script_lines.append(f" await page.wait_for_load_state('load', timeout={goto_timeout})")
- script_lines.append(' await page.wait_for_timeout(1000)')
- self._page_counter += 1 # Increment page counter
- else:
- script_lines.append(f' # Skipping open_tab ({step_info_str}): missing or invalid url')
- return script_lines
-
- def _map_close_tab(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- page_id = params.get('page_id')
- script_lines = []
- if page_id is not None:
- script_lines.extend(
- [
- f' print(f"Attempting to close tab with page_id {page_id} ({step_info_str})")',
- f' if {page_id} < len(context.pages):',
- f' target_page = context.pages[{page_id}]',
- ' await target_page.close()',
- ' await page.wait_for_timeout(500)',
- ' if context.pages: page = context.pages[-1]', # Switch to last page
- ' else:',
- " print(' Warning: No pages left after closing tab. Cannot switch.', file=sys.stderr)",
- ' # Optionally, create a new page here if needed: page = await context.new_page()',
- ' if page: await page.bring_to_front()', # Bring to front if page exists
- ' else:',
- f' print(f" Warning: Tab with page_id {page_id} not found to close ({step_info_str})", file=sys.stderr)',
- ]
- )
- else:
- script_lines.append(f' # Skipping close_tab ({step_info_str}): missing page_id')
- return script_lines
-
- def _map_switch_tab(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- page_id = params.get('page_id')
- script_lines = []
- if page_id is not None:
- script_lines.extend(
- [
- f' print(f"Switching to tab with page_id {page_id} ({step_info_str})")',
- f' if {page_id} < len(context.pages):',
- f' page = context.pages[{page_id}]',
- ' await page.bring_to_front()',
- " await page.wait_for_load_state('load', timeout=15000)",
- ' await page.wait_for_timeout(500)',
- ' else:',
- f' print(f" Warning: Tab with page_id {page_id} not found to switch ({step_info_str})", file=sys.stderr)',
- ]
- )
- else:
- script_lines.append(f' # Skipping switch_tab ({step_info_str}): missing page_id')
- return script_lines
-
- def _map_search_google(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- query = params.get('query')
- goto_timeout = self._get_goto_timeout()
- script_lines = []
- if query and isinstance(query, str):
- clean_query = f'replace_sensitive_data({json.dumps(query)}, SENSITIVE_DATA)'
- search_url_expression = f'f"https://www.google.com/search?q={{ urllib.parse.quote_plus({clean_query}) }}&udm=14"'
- script_lines.extend(
- [
- f' search_url = {search_url_expression}',
- f' print(f"Searching Google for query related to: {{ {clean_query} }} ({step_info_str})")',
- f' await page.goto(search_url, timeout={goto_timeout})',
- f" await page.wait_for_load_state('load', timeout={goto_timeout})",
- ' await page.wait_for_timeout(1000)',
- ]
- )
- else:
- script_lines.append(f' # Skipping search_google ({step_info_str}): missing or invalid query')
- return script_lines
-
- def _map_drag_drop(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- source_sel = params.get('element_source')
- target_sel = params.get('element_target')
- source_coords = (params.get('coord_source_x'), params.get('coord_source_y'))
- target_coords = (params.get('coord_target_x'), params.get('coord_target_y'))
- script_lines = [f' print(f"Attempting drag and drop ({step_info_str})")']
- if source_sel and target_sel:
- escaped_source = json.dumps(source_sel)
- escaped_target = json.dumps(target_sel)
- script_lines.append(f' await page.drag_and_drop({escaped_source}, {escaped_target})')
- script_lines.append(f" print(f' Dragged element {escaped_source} to {escaped_target}')")
- elif all(c is not None for c in source_coords) and all(c is not None for c in target_coords):
- sx, sy = source_coords
- tx, ty = target_coords
- script_lines.extend(
- [
- f' await page.mouse.move({sx}, {sy})',
- ' await page.mouse.down()',
- f' await page.mouse.move({tx}, {ty})',
- ' await page.mouse.up()',
- f" print(f' Dragged from ({sx},{sy}) to ({tx},{ty})')",
- ]
- )
- else:
- script_lines.append(
- f' # Skipping drag_drop ({step_info_str}): requires either element selectors or full coordinates'
- )
- script_lines.append(' await page.wait_for_timeout(500)')
- return script_lines
-
- def _map_extract_content(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- goal = params.get('goal', 'content')
- logger.warning(f"Action 'extract_content' ({step_info_str}) cannot be directly translated to Playwright script.")
- return [f' # Action: extract_content (Goal: {goal}) - Skipped in Playwright script ({step_info_str})']
-
- def _map_click_download_button(
- self, params: dict, history_item: dict, action_index_in_step: int, step_info_str: str, **kwargs
- ) -> list[str]:
- index = params.get('index')
- selector = self._get_selector_for_action(history_item, action_index_in_step)
- download_dir_in_script = "'./files'" # Default
- if self.context_config and self.context_config.save_downloads_path:
- download_dir_in_script = repr(self.context_config.save_downloads_path)
-
- script_lines = []
- if selector and index is not None:
- script_lines.append(
- f' print(f"Attempting to download file by clicking element ({selector}) ({step_info_str})")'
- )
- script_lines.append(' try:')
- script_lines.append(
- ' async with page.expect_download(timeout=120000) as download_info:'
- ) # 2 min timeout
- step_info_for_download = f'{step_info_str} (triggering download)'
- script_lines.append(
- f' await _try_locate_and_act(page, {json.dumps(selector)}, "click", step_info={json.dumps(step_info_for_download)})'
- )
- script_lines.append(' download = await download_info.value')
- script_lines.append(f' configured_download_dir = {download_dir_in_script}')
- script_lines.append(' download_dir_path = Path(configured_download_dir).resolve()')
- script_lines.append(' download_dir_path.mkdir(parents=True, exist_ok=True)')
- script_lines.append(
- " base, ext = os.path.splitext(download.suggested_filename or f'download_{{len(list(download_dir_path.iterdir())) + 1}}.tmp')"
- )
- script_lines.append(' counter = 1')
- script_lines.append(" download_path_obj = download_dir_path / f'{base}{ext}'")
- script_lines.append(' while download_path_obj.exists():')
- script_lines.append(" download_path_obj = download_dir_path / f'{base}({{counter}}){ext}'")
- script_lines.append(' counter += 1')
- script_lines.append(' await download.save_as(str(download_path_obj))')
- script_lines.append(" print(f' File downloaded successfully to: {str(download_path_obj)}')")
- script_lines.append(' except PlaywrightActionError as pae:')
- script_lines.append(' raise pae') # Re-raise to stop script
- script_lines.append(' except Exception as download_err:')
- script_lines.append(
- f" raise PlaywrightActionError(f'Download failed for {step_info_str}: {{download_err}}') from download_err"
- )
- else:
- script_lines.append(
- f' # Skipping click_download_button ({step_info_str}): missing index ({index}) or selector ({selector})'
- )
- return script_lines
-
- def _map_done(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
- script_lines = []
- if isinstance(params, dict):
- final_text = params.get('text', '')
- success_status = params.get('success', False)
- escaped_final_text_with_placeholders = json.dumps(str(final_text))
- script_lines.append(f' print("\\n--- Task marked as Done by agent ({step_info_str}) ---")')
- script_lines.append(f' print(f"Agent reported success: {success_status}")')
- script_lines.append(' # Final Message from agent (may contain placeholders):')
- script_lines.append(
- f' final_message = replace_sensitive_data({escaped_final_text_with_placeholders}, SENSITIVE_DATA)'
- )
- script_lines.append(' print(final_message)')
- else:
- script_lines.append(f' print("\\n--- Task marked as Done by agent ({step_info_str}) ---")')
- script_lines.append(' print("Success: N/A (invalid params)")')
- script_lines.append(' print("Final Message: N/A (invalid params)")')
- return script_lines
-
- def _map_action_to_playwright(
- self,
- action_dict: dict,
- history_item: dict,
- previous_history_item: dict | None,
- action_index_in_step: int,
- step_info_str: str,
- ) -> list[str]:
- """
- Translates a single action dictionary into Playwright script lines using dictionary dispatch.
- """
- if not isinstance(action_dict, dict) or not action_dict:
- return [f' # Invalid action format: {action_dict} ({step_info_str})']
-
- action_type = next(iter(action_dict.keys()), None)
- params = action_dict.get(action_type)
-
- if not action_type or params is None:
- if action_dict == {}:
- return [f' # Empty action dictionary found ({step_info_str})']
- return [f' # Could not determine action type or params: {action_dict} ({step_info_str})']
-
- # Get the handler function from the dictionary
- handler = self._action_handlers.get(action_type)
-
- if handler:
- # Call the specific handler method
- return handler(
- params=params,
- history_item=history_item,
- action_index_in_step=action_index_in_step,
- step_info_str=step_info_str,
- action_type=action_type, # Pass action_type for legacy handling etc.
- previous_history_item=previous_history_item,
- )
- else:
- # Handle unsupported actions
- logger.warning(f'Unsupported action type encountered: {action_type} ({step_info_str})')
- return [f' # Unsupported action type: {action_type} ({step_info_str})']
-
- def generate_script_content(self) -> str:
- """Generates the full Playwright script content as a string."""
- script_lines = []
- self._page_counter = 0 # Reset page counter for new script generation
-
- if not self._imports_helpers_added:
- script_lines.extend(self._get_imports_and_helpers())
- self._imports_helpers_added = True
-
- # Read helper script content
- helper_script_path = Path(__file__).parent / 'playwright_script_helpers.py'
- try:
- with open(helper_script_path, encoding='utf-8') as f_helper:
- helper_script_content = f_helper.read()
- except FileNotFoundError:
- logger.error(f'Helper script not found at {helper_script_path}. Cannot generate script.')
- return '# Error: Helper script file missing.'
- except Exception as e:
- logger.error(f'Error reading helper script {helper_script_path}: {e}')
- return f'# Error: Could not read helper script: {e}'
-
- script_lines.extend(self._get_sensitive_data_definitions())
-
- # Add the helper script content after imports and sensitive data
- script_lines.append('\n# --- Helper Functions (from playwright_script_helpers.py) ---')
- script_lines.append(helper_script_content)
- script_lines.append('# --- End Helper Functions ---')
-
- # Generate browser launch and context creation code
- browser_launch_args = self._generate_browser_launch_args()
- context_options = self._generate_context_options()
- # Determine browser type (defaulting to chromium)
- browser_type = 'chromium'
- if self.browser_config and self.browser_config.browser_class in ['firefox', 'webkit']:
- browser_type = self.browser_config.browser_class
-
- script_lines.extend(
- [
- 'async def run_generated_script():',
- ' global SENSITIVE_DATA', # Ensure sensitive data is accessible
- ' async with async_playwright() as p:',
- ' browser = None',
- ' context = None',
- ' page = None',
- ' exit_code = 0 # Default success exit code',
- ' try:',
- f" print('Launching {browser_type} browser...')",
- # Use generated launch args, remove slow_mo
- f' browser = await p.{browser_type}.launch({browser_launch_args})',
- # Use generated context options
- f' context = await browser.new_context({context_options})',
- " print('Browser context created.')",
- ]
- )
-
- # Add cookie loading logic if cookies_file is specified
- if self.context_config and self.context_config.cookies_file:
- cookies_file_path = repr(self.context_config.cookies_file)
- script_lines.extend(
- [
- ' # Load cookies if specified',
- f' cookies_path = {cookies_file_path}',
- ' if cookies_path and os.path.exists(cookies_path):',
- ' try:',
- " with open(cookies_path, 'r', encoding='utf-8') as f_cookies:",
- ' cookies = json.load(f_cookies)',
- ' # Validate sameSite attribute',
- " valid_same_site = ['Strict', 'Lax', 'None']",
- ' for cookie in cookies:',
- " if 'sameSite' in cookie and cookie['sameSite'] not in valid_same_site:",
- ' print(f\' Warning: Fixing invalid sameSite value "{{cookie["sameSite"]}}" to None for cookie {{cookie.get("name")}}\', file=sys.stderr)',
- " cookie['sameSite'] = 'None'",
- ' await context.add_cookies(cookies)',
- " print(f' Successfully loaded {{len(cookies)}} cookies from {{cookies_path}}')",
- ' except Exception as cookie_err:',
- " print(f' Warning: Failed to load or add cookies from {{cookies_path}}: {{cookie_err}}', file=sys.stderr)",
- ' else:',
- ' if cookies_path:', # Only print if a path was specified but not found
- " print(f' Cookie file not found at: {cookies_path}')",
- '',
- ]
- )
-
- script_lines.extend(
- [
- ' # Initial page handling',
- ' if context.pages:',
- ' page = context.pages[0]',
- " print('Using initial page provided by context.')",
- ' else:',
- ' page = await context.new_page()',
- " print('Created a new page as none existed.')",
- " print('\\n--- Starting Generated Script Execution ---')",
- ]
- )
-
- action_counter = 0
- stop_processing_steps = False
- previous_item_dict = None
-
- for step_index, item_dict in enumerate(self.history):
- if stop_processing_steps:
- break
-
- if not isinstance(item_dict, dict):
- logger.warning(f'Skipping step {step_index + 1}: Item is not a dictionary ({type(item_dict)})')
- script_lines.append(f'\n # --- Step {step_index + 1}: Skipped (Invalid Format) ---')
- previous_item_dict = item_dict
- continue
-
- script_lines.append(f'\n # --- Step {step_index + 1} ---')
- model_output = item_dict.get('model_output')
-
- if not isinstance(model_output, dict) or 'action' not in model_output:
- script_lines.append(' # No valid model_output or action found for this step')
- previous_item_dict = item_dict
- continue
-
- actions = model_output.get('action')
- if not isinstance(actions, list):
- script_lines.append(f' # Actions format is not a list: {type(actions)}')
- previous_item_dict = item_dict
- continue
-
- for action_index_in_step, action_detail in enumerate(actions):
- action_counter += 1
- script_lines.append(f' # Action {action_counter}')
-
- step_info_str = f'Step {step_index + 1}, Action {action_index_in_step + 1}'
- action_lines = self._map_action_to_playwright(
- action_dict=action_detail,
- history_item=item_dict,
- previous_history_item=previous_item_dict,
- action_index_in_step=action_index_in_step,
- step_info_str=step_info_str,
- )
- script_lines.extend(action_lines)
-
- action_type = next(iter(action_detail.keys()), None) if isinstance(action_detail, dict) else None
- if action_type == 'done':
- stop_processing_steps = True
- break
-
- previous_item_dict = item_dict
-
- # Updated final block to include sys.exit
- script_lines.extend(
- [
- ' except PlaywrightActionError as pae:', # Catch specific action errors
- " print(f'\\n--- Playwright Action Error: {pae} ---', file=sys.stderr)",
- ' exit_code = 1', # Set exit code to failure
- ' except Exception as e:',
- " print(f'\\n--- An unexpected error occurred: {e} ---', file=sys.stderr)",
- ' import traceback',
- ' traceback.print_exc()',
- ' exit_code = 1', # Set exit code to failure
- ' finally:',
- " print('\\n--- Generated Script Execution Finished ---')",
- " print('Closing browser/context...')",
- ' if context:',
- ' try: await context.close()',
- " except Exception as ctx_close_err: print(f' Warning: could not close context: {ctx_close_err}', file=sys.stderr)",
- ' if browser:',
- ' try: await browser.close()',
- " except Exception as browser_close_err: print(f' Warning: could not close browser: {browser_close_err}', file=sys.stderr)",
- " print('Browser/context closed.')",
- ' # Exit with the determined exit code',
- ' if exit_code != 0:',
- " print(f'Script finished with errors (exit code {exit_code}).', file=sys.stderr)",
- ' sys.exit(exit_code)', # Exit with non-zero code on error
- '',
- '# --- Script Entry Point ---',
- "if __name__ == '__main__':",
- " if os.name == 'nt':",
- ' asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())',
- ' asyncio.run(run_generated_script())',
- ]
- )
-
- return '\n'.join(script_lines)
+# import json
+# import logging
+# from pathlib import Path
+# from typing import Any
+
+# from browser_use.browser import BrowserConfig, BrowserContextConfig
+
+# logger = logging.getLogger(__name__)
+
+
+# class PlaywrightScriptGenerator:
+# """Generates a Playwright script from AgentHistoryList."""
+
+# def __init__(
+# self,
+# history_list: list[dict[str, Any]],
+# sensitive_data_keys: list[str] | None = None,
+# browser_config: BrowserConfig | None = None,
+# context_config: BrowserContextConfig | None = None,
+# ):
+# """
+# Initializes the script generator.
+
+# Args:
+# history_list: A list of dictionaries, where each dictionary represents an AgentHistory item.
+# Expected to be raw dictionaries from `AgentHistoryList.model_dump()`.
+# sensitive_data_keys: A list of keys used as placeholders for sensitive data.
+# browser_config: Configuration from the original Browser instance (deprecated, use BrowserProfile).
+# context_config: Configuration from the original BrowserContext instance (deprecated, use BrowserProfile).
+# """
+# self.history = history_list
+# self.sensitive_data_keys = sensitive_data_keys or []
+# self.browser_config = browser_config
+# self.context_config = context_config
+# self._imports_helpers_added = False
+# self._page_counter = 0 # Track pages for tab management
+
+# # Dictionary mapping action types to handler methods
+# self._action_handlers = {
+# 'go_to_url': self._map_go_to_url,
+# 'wait': self._map_wait,
+# 'input_text': self._map_input_text,
+# 'click_element': self._map_click_element,
+# 'click_element_by_index': self._map_click_element, # Map legacy action
+# 'scroll_down': self._map_scroll_down,
+# 'scroll_up': self._map_scroll_up,
+# 'send_keys': self._map_send_keys,
+# 'go_back': self._map_go_back,
+# 'open_tab': self._map_open_tab,
+# 'close_tab': self._map_close_tab,
+# 'switch_tab': self._map_switch_tab,
+# 'search_google': self._map_search_google,
+# 'drag_drop': self._map_drag_drop,
+# 'extract_content': self._map_extract_content,
+# 'click_download_button': self._map_click_download_button,
+# 'done': self._map_done,
+# }
+
+# def _generate_browser_launch_args(self) -> str:
+# """Generates the arguments string for browser launch based on BrowserConfig."""
+# if not self.browser_config:
+# # Default launch if no config provided
+# return 'headless=False'
+
+# args_dict = {
+# 'headless': self.browser_config.headless,
+# # Add other relevant launch options here based on self.browser_config
+# # Example: 'proxy': self.browser_config.proxy.model_dump() if self.browser_config.proxy else None
+# # Example: 'args': self.browser_config.extra_browser_args # Be careful inheriting args
+# }
+# if self.browser_config.proxy:
+# args_dict['proxy'] = self.browser_config.proxy.model_dump()
+
+# # Filter out None values
+# args_dict = {k: v for k, v in args_dict.items() if v is not None}
+
+# # Format as keyword arguments string
+# args_str = ', '.join(f'{key}={repr(value)}' for key, value in args_dict.items())
+# return args_str
+
+# def _generate_context_options(self) -> str:
+# """Generates the options string for context creation based on BrowserContextConfig."""
+# if not self.context_config:
+# return '' # Default context
+
+# options_dict = {}
+
+# # Map relevant BrowserContextConfig fields to Playwright context options
+# if self.context_config.user_agent:
+# options_dict['user_agent'] = self.context_config.user_agent
+# if self.context_config.locale:
+# options_dict['locale'] = self.context_config.locale
+# if self.context_config.permissions:
+# options_dict['permissions'] = self.context_config.permissions
+# if self.context_config.geolocation:
+# options_dict['geolocation'] = self.context_config.geolocation
+# if self.context_config.timezone_id:
+# options_dict['timezone_id'] = self.context_config.timezone_id
+# if self.context_config.http_credentials:
+# options_dict['http_credentials'] = self.context_config.http_credentials
+# if self.context_config.is_mobile is not None:
+# options_dict['is_mobile'] = self.context_config.is_mobile
+# if self.context_config.has_touch is not None:
+# options_dict['has_touch'] = self.context_config.has_touch
+# if self.context_config.save_recording_path:
+# options_dict['record_video_dir'] = self.context_config.save_recording_path
+# if self.context_config.save_har_path:
+# options_dict['record_har_path'] = self.context_config.save_har_path
+
+# # Handle viewport/window size
+# if self.context_config.no_viewport:
+# options_dict['no_viewport'] = True
+# elif hasattr(self.context_config, 'window_width') and hasattr(self.context_config, 'window_height'):
+# options_dict['viewport'] = {
+# 'width': self.context_config.window_width,
+# 'height': self.context_config.window_height,
+# }
+
+# # Note: cookies_file and save_downloads_path are handled separately
+
+# # Filter out None values
+# options_dict = {k: v for k, v in options_dict.items() if v is not None}
+
+# # Format as keyword arguments string
+# options_str = ', '.join(f'{key}={repr(value)}' for key, value in options_dict.items())
+# return options_str
+
+# def _get_imports_and_helpers(self) -> list[str]:
+# """Generates necessary import statements (excluding helper functions)."""
+# # Return only the standard imports needed by the main script body
+# return [
+# 'import asyncio',
+# 'import json',
+# 'import os',
+# 'import sys',
+# 'from pathlib import Path', # Added Path import
+# 'import urllib.parse', # Needed for search_google
+# 'from playwright.async_api import async_playwright, Page, BrowserContext', # Added BrowserContext
+# 'from dotenv import load_dotenv',
+# '',
+# '# Load environment variables',
+# 'load_dotenv(override=True)',
+# '',
+# # Helper function definitions are no longer here
+# ]
+
+# def _get_sensitive_data_definitions(self) -> list[str]:
+# """Generates the SENSITIVE_DATA dictionary definition."""
+# if not self.sensitive_data_keys:
+# return ['SENSITIVE_DATA = {}', '']
+
+# lines = ['# Sensitive data placeholders mapped to environment variables']
+# lines.append('SENSITIVE_DATA = {')
+# for key in self.sensitive_data_keys:
+# env_var_name = key.upper()
+# default_value_placeholder = f'YOUR_{env_var_name}'
+# lines.append(f' "{key}": os.getenv("{env_var_name}", {json.dumps(default_value_placeholder)}),')
+# lines.append('}')
+# lines.append('')
+# return lines
+
+# def _get_selector_for_action(self, history_item: dict, action_index_in_step: int) -> str | None:
+# """
+# Gets the selector (preferring XPath) for a given action index within a history step.
+# Formats the XPath correctly for Playwright.
+# """
+# state = history_item.get('state')
+# if not isinstance(state, dict):
+# return None
+# interacted_elements = state.get('interacted_element')
+# if not isinstance(interacted_elements, list):
+# return None
+# if action_index_in_step >= len(interacted_elements):
+# return None
+# element_data = interacted_elements[action_index_in_step]
+# if not isinstance(element_data, dict):
+# return None
+
+# # Prioritize XPath
+# xpath = element_data.get('xpath')
+# if isinstance(xpath, str) and xpath.strip():
+# if not xpath.startswith('xpath=') and not xpath.startswith('/') and not xpath.startswith('//'):
+# xpath_selector = f'xpath=//{xpath}' # Make relative if not already
+# elif not xpath.startswith('xpath='):
+# xpath_selector = f'xpath={xpath}' # Add prefix if missing
+# else:
+# xpath_selector = xpath
+# return xpath_selector
+
+# # Fallback to CSS selector if XPath is missing
+# css_selector = element_data.get('css_selector')
+# if isinstance(css_selector, str) and css_selector.strip():
+# return css_selector # Use CSS selector as is
+
+# logger.warning(
+# f'Could not find a usable XPath or CSS selector for action index {action_index_in_step} (element index {element_data.get("highlight_index", "N/A")}).'
+# )
+# return None
+
+# def _get_goto_timeout(self) -> int:
+# """Gets the page navigation timeout in milliseconds."""
+# default_timeout = 90000 # Default 90 seconds
+# if self.context_config and self.context_config.maximum_wait_page_load_time:
+# # Convert seconds to milliseconds
+# return int(self.context_config.maximum_wait_page_load_time * 1000)
+# return default_timeout
+
+# # --- Action Mapping Methods ---
+# def _map_go_to_url(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# url = params.get('url')
+# goto_timeout = self._get_goto_timeout()
+# script_lines = []
+# if url and isinstance(url, str):
+# escaped_url = json.dumps(url)
+# script_lines.append(f' print(f"Navigating to: {url} ({step_info_str})")')
+# script_lines.append(f' await page.goto({escaped_url}, timeout={goto_timeout})')
+# script_lines.append(f" await page.wait_for_load_state('load', timeout={goto_timeout})")
+# script_lines.append(' await page.wait_for_timeout(1000)') # Short pause
+# else:
+# script_lines.append(f' # Skipping go_to_url ({step_info_str}): missing or invalid url')
+# return script_lines
+
+# def _map_wait(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# seconds = params.get('seconds', 3)
+# try:
+# wait_seconds = int(seconds)
+# except (ValueError, TypeError):
+# wait_seconds = 3
+# return [
+# f' print(f"Waiting for {wait_seconds} seconds... ({step_info_str})")',
+# f' await asyncio.sleep({wait_seconds})',
+# ]
+
+# def _map_input_text(
+# self, params: dict, history_item: dict, action_index_in_step: int, step_info_str: str, **kwargs
+# ) -> list[str]:
+# index = params.get('index')
+# text = params.get('text', '')
+# selector = self._get_selector_for_action(history_item, action_index_in_step)
+# script_lines = []
+# if selector and index is not None:
+# clean_text_expression = f'replace_sensitive_data({json.dumps(str(text))}, SENSITIVE_DATA)'
+# escaped_selector = json.dumps(selector)
+# escaped_step_info = json.dumps(step_info_str)
+# script_lines.append(
+# f' await _try_locate_and_act(page, {escaped_selector}, "fill", text={clean_text_expression}, step_info={escaped_step_info})'
+# )
+# else:
+# script_lines.append(
+# f' # Skipping input_text ({step_info_str}): missing index ({index}) or selector ({selector})'
+# )
+# return script_lines
+
+# def _map_click_element(
+# self, params: dict, history_item: dict, action_index_in_step: int, step_info_str: str, action_type: str, **kwargs
+# ) -> list[str]:
+# if action_type == 'click_element_by_index':
+# logger.warning(f"Mapping legacy 'click_element_by_index' to 'click_element' ({step_info_str})")
+# index = params.get('index')
+# selector = self._get_selector_for_action(history_item, action_index_in_step)
+# script_lines = []
+# if selector and index is not None:
+# escaped_selector = json.dumps(selector)
+# escaped_step_info = json.dumps(step_info_str)
+# script_lines.append(
+# f' await _try_locate_and_act(page, {escaped_selector}, "click", step_info={escaped_step_info})'
+# )
+# else:
+# script_lines.append(
+# f' # Skipping {action_type} ({step_info_str}): missing index ({index}) or selector ({selector})'
+# )
+# return script_lines
+
+# def _map_scroll_down(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# amount = params.get('amount')
+# script_lines = []
+# if amount and isinstance(amount, int):
+# script_lines.append(f' print(f"Scrolling down by {amount} pixels ({step_info_str})")')
+# script_lines.append(f" await page.evaluate('window.scrollBy(0, {amount})')")
+# else:
+# script_lines.append(f' print(f"Scrolling down by one page height ({step_info_str})")')
+# script_lines.append(" await page.evaluate('window.scrollBy(0, window.innerHeight)')")
+# script_lines.append(' await page.wait_for_timeout(500)')
+# return script_lines
+
+# def _map_scroll_up(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# amount = params.get('amount')
+# script_lines = []
+# if amount and isinstance(amount, int):
+# script_lines.append(f' print(f"Scrolling up by {amount} pixels ({step_info_str})")')
+# script_lines.append(f" await page.evaluate('window.scrollBy(0, -{amount})')")
+# else:
+# script_lines.append(f' print(f"Scrolling up by one page height ({step_info_str})")')
+# script_lines.append(" await page.evaluate('window.scrollBy(0, -window.innerHeight)')")
+# script_lines.append(' await page.wait_for_timeout(500)')
+# return script_lines
+
+# def _map_send_keys(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# keys = params.get('keys')
+# script_lines = []
+# if keys and isinstance(keys, str):
+# escaped_keys = json.dumps(keys)
+# script_lines.append(f' print(f"Sending keys: {keys} ({step_info_str})")')
+# script_lines.append(f' await page.keyboard.press({escaped_keys})')
+# script_lines.append(' await page.wait_for_timeout(500)')
+# else:
+# script_lines.append(f' # Skipping send_keys ({step_info_str}): missing or invalid keys')
+# return script_lines
+
+# def _map_go_back(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# goto_timeout = self._get_goto_timeout()
+# return [
+# ' await asyncio.sleep(60) # Wait 1 minute (important) before going back',
+# f' print(f"Navigating back using browser history ({step_info_str})")',
+# f' await page.go_back(timeout={goto_timeout})',
+# f" await page.wait_for_load_state('load', timeout={goto_timeout})",
+# ' await page.wait_for_timeout(1000)',
+# ]
+
+# def _map_open_tab(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# url = params.get('url')
+# goto_timeout = self._get_goto_timeout()
+# script_lines = []
+# if url and isinstance(url, str):
+# escaped_url = json.dumps(url)
+# script_lines.append(f' print(f"Opening new tab and navigating to: {url} ({step_info_str})")')
+# script_lines.append(' page = await context.new_page()')
+# script_lines.append(f' await page.goto({escaped_url}, timeout={goto_timeout})')
+# script_lines.append(f" await page.wait_for_load_state('load', timeout={goto_timeout})")
+# script_lines.append(' await page.wait_for_timeout(1000)')
+# self._page_counter += 1 # Increment page counter
+# else:
+# script_lines.append(f' # Skipping open_tab ({step_info_str}): missing or invalid url')
+# return script_lines
+
+# def _map_close_tab(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# page_id = params.get('page_id')
+# script_lines = []
+# if page_id is not None:
+# script_lines.extend(
+# [
+# f' print(f"Attempting to close tab with page_id {page_id} ({step_info_str})")',
+# f' if {page_id} < len(context.pages):',
+# f' target_page = context.pages[{page_id}]',
+# ' await target_page.close()',
+# ' await page.wait_for_timeout(500)',
+# ' if context.pages: page = context.pages[-1]', # Switch to last page
+# ' else:',
+# " print(' Warning: No pages left after closing tab. Cannot switch.', file=sys.stderr)",
+# ' # Optionally, create a new page here if needed: page = await context.new_page()',
+# ' if page: await page.bring_to_front()', # Bring to front if page exists
+# ' else:',
+# f' print(f" Warning: Tab with page_id {page_id} not found to close ({step_info_str})", file=sys.stderr)',
+# ]
+# )
+# else:
+# script_lines.append(f' # Skipping close_tab ({step_info_str}): missing page_id')
+# return script_lines
+
+# def _map_switch_tab(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# page_id = params.get('page_id')
+# script_lines = []
+# if page_id is not None:
+# script_lines.extend(
+# [
+# f' print(f"Switching to tab with page_id {page_id} ({step_info_str})")',
+# f' if {page_id} < len(context.pages):',
+# f' page = context.pages[{page_id}]',
+# ' await page.bring_to_front()',
+# " await page.wait_for_load_state('load', timeout=15000)",
+# ' await page.wait_for_timeout(500)',
+# ' else:',
+# f' print(f" Warning: Tab with page_id {page_id} not found to switch ({step_info_str})", file=sys.stderr)',
+# ]
+# )
+# else:
+# script_lines.append(f' # Skipping switch_tab ({step_info_str}): missing page_id')
+# return script_lines
+
+# def _map_search_google(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# query = params.get('query')
+# goto_timeout = self._get_goto_timeout()
+# script_lines = []
+# if query and isinstance(query, str):
+# clean_query = f'replace_sensitive_data({json.dumps(query)}, SENSITIVE_DATA)'
+# search_url_expression = f'f"https://www.google.com/search?q={{ urllib.parse.quote_plus({clean_query}) }}&udm=14"'
+# script_lines.extend(
+# [
+# f' search_url = {search_url_expression}',
+# f' print(f"Searching Google for query related to: {{ {clean_query} }} ({step_info_str})")',
+# f' await page.goto(search_url, timeout={goto_timeout})',
+# f" await page.wait_for_load_state('load', timeout={goto_timeout})",
+# ' await page.wait_for_timeout(1000)',
+# ]
+# )
+# else:
+# script_lines.append(f' # Skipping search_google ({step_info_str}): missing or invalid query')
+# return script_lines
+
+# def _map_drag_drop(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# source_sel = params.get('element_source')
+# target_sel = params.get('element_target')
+# source_coords = (params.get('coord_source_x'), params.get('coord_source_y'))
+# target_coords = (params.get('coord_target_x'), params.get('coord_target_y'))
+# script_lines = [f' print(f"Attempting drag and drop ({step_info_str})")']
+# if source_sel and target_sel:
+# escaped_source = json.dumps(source_sel)
+# escaped_target = json.dumps(target_sel)
+# script_lines.append(f' await page.drag_and_drop({escaped_source}, {escaped_target})')
+# script_lines.append(f" print(f' Dragged element {escaped_source} to {escaped_target}')")
+# elif all(c is not None for c in source_coords) and all(c is not None for c in target_coords):
+# sx, sy = source_coords
+# tx, ty = target_coords
+# script_lines.extend(
+# [
+# f' await page.mouse.move({sx}, {sy})',
+# ' await page.mouse.down()',
+# f' await page.mouse.move({tx}, {ty})',
+# ' await page.mouse.up()',
+# f" print(f' Dragged from ({sx},{sy}) to ({tx},{ty})')",
+# ]
+# )
+# else:
+# script_lines.append(
+# f' # Skipping drag_drop ({step_info_str}): requires either element selectors or full coordinates'
+# )
+# script_lines.append(' await page.wait_for_timeout(500)')
+# return script_lines
+
+# def _map_extract_content(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# goal = params.get('goal', 'content')
+# logger.warning(f"Action 'extract_content' ({step_info_str}) cannot be directly translated to Playwright script.")
+# return [f' # Action: extract_content (Goal: {goal}) - Skipped in Playwright script ({step_info_str})']
+
+# def _map_click_download_button(
+# self, params: dict, history_item: dict, action_index_in_step: int, step_info_str: str, **kwargs
+# ) -> list[str]:
+# index = params.get('index')
+# selector = self._get_selector_for_action(history_item, action_index_in_step)
+# download_dir_in_script = "'./files'" # Default
+# if self.context_config and self.context_config.save_downloads_path:
+# download_dir_in_script = repr(self.context_config.save_downloads_path)
+
+# script_lines = []
+# if selector and index is not None:
+# script_lines.append(
+# f' print(f"Attempting to download file by clicking element ({selector}) ({step_info_str})")'
+# )
+# script_lines.append(' try:')
+# script_lines.append(
+# ' async with page.expect_download(timeout=120000) as download_info:'
+# ) # 2 min timeout
+# step_info_for_download = f'{step_info_str} (triggering download)'
+# script_lines.append(
+# f' await _try_locate_and_act(page, {json.dumps(selector)}, "click", step_info={json.dumps(step_info_for_download)})'
+# )
+# script_lines.append(' download = await download_info.value')
+# script_lines.append(f' configured_download_dir = {download_dir_in_script}')
+# script_lines.append(' download_dir_path = Path(configured_download_dir).resolve()')
+# script_lines.append(' download_dir_path.mkdir(parents=True, exist_ok=True)')
+# script_lines.append(
+# " base, ext = os.path.splitext(download.suggested_filename or f'download_{{len(list(download_dir_path.iterdir())) + 1}}.tmp')"
+# )
+# script_lines.append(' counter = 1')
+# script_lines.append(" download_path_obj = download_dir_path / f'{base}{ext}'")
+# script_lines.append(' while download_path_obj.exists():')
+# script_lines.append(" download_path_obj = download_dir_path / f'{base}({{counter}}){ext}'")
+# script_lines.append(' counter += 1')
+# script_lines.append(' await download.save_as(str(download_path_obj))')
+# script_lines.append(" print(f' File downloaded successfully to: {str(download_path_obj)}')")
+# script_lines.append(' except PlaywrightActionError as pae:')
+# script_lines.append(' raise pae') # Re-raise to stop script
+# script_lines.append(' except Exception as download_err:')
+# script_lines.append(
+# f" raise PlaywrightActionError(f'Download failed for {step_info_str}: {{download_err}}') from download_err"
+# )
+# else:
+# script_lines.append(
+# f' # Skipping click_download_button ({step_info_str}): missing index ({index}) or selector ({selector})'
+# )
+# return script_lines
+
+# def _map_done(self, params: dict, step_info_str: str, **kwargs) -> list[str]:
+# script_lines = []
+# if isinstance(params, dict):
+# final_text = params.get('text', '')
+# success_status = params.get('success', False)
+# escaped_final_text_with_placeholders = json.dumps(str(final_text))
+# script_lines.append(f' print("\\n--- Task marked as Done by agent ({step_info_str}) ---")')
+# script_lines.append(f' print(f"Agent reported success: {success_status}")')
+# script_lines.append(' # Final Message from agent (may contain placeholders):')
+# script_lines.append(
+# f' final_message = replace_sensitive_data({escaped_final_text_with_placeholders}, SENSITIVE_DATA)'
+# )
+# script_lines.append(' print(final_message)')
+# else:
+# script_lines.append(f' print("\\n--- Task marked as Done by agent ({step_info_str}) ---")')
+# script_lines.append(' print("Success: N/A (invalid params)")')
+# script_lines.append(' print("Final Message: N/A (invalid params)")')
+# return script_lines
+
+# def _map_action_to_playwright(
+# self,
+# action_dict: dict,
+# history_item: dict,
+# previous_history_item: dict | None,
+# action_index_in_step: int,
+# step_info_str: str,
+# ) -> list[str]:
+# """
+# Translates a single action dictionary into Playwright script lines using dictionary dispatch.
+# """
+# if not isinstance(action_dict, dict) or not action_dict:
+# return [f' # Invalid action format: {action_dict} ({step_info_str})']
+
+# action_type = next(iter(action_dict.keys()), None)
+# params = action_dict.get(action_type)
+
+# if not action_type or params is None:
+# if action_dict == {}:
+# return [f' # Empty action dictionary found ({step_info_str})']
+# return [f' # Could not determine action type or params: {action_dict} ({step_info_str})']
+
+# # Get the handler function from the dictionary
+# handler = self._action_handlers.get(action_type)
+
+# if handler:
+# # Call the specific handler method
+# return handler(
+# params=params,
+# history_item=history_item,
+# action_index_in_step=action_index_in_step,
+# step_info_str=step_info_str,
+# action_type=action_type, # Pass action_type for legacy handling etc.
+# previous_history_item=previous_history_item,
+# )
+# else:
+# # Handle unsupported actions
+# logger.warning(f'Unsupported action type encountered: {action_type} ({step_info_str})')
+# return [f' # Unsupported action type: {action_type} ({step_info_str})']
+
+# def generate_script_content(self) -> str:
+# """Generates the full Playwright script content as a string."""
+# script_lines = []
+# self._page_counter = 0 # Reset page counter for new script generation
+
+# if not self._imports_helpers_added:
+# script_lines.extend(self._get_imports_and_helpers())
+# self._imports_helpers_added = True
+
+# # Read helper script content
+# helper_script_path = Path(__file__).parent / 'playwright_script_helpers.py'
+# try:
+# with open(helper_script_path, encoding='utf-8') as f_helper:
+# helper_script_content = f_helper.read()
+# except FileNotFoundError:
+# logger.error(f'Helper script not found at {helper_script_path}. Cannot generate script.')
+# return '# Error: Helper script file missing.'
+# except Exception as e:
+# logger.error(f'Error reading helper script {helper_script_path}: {e}')
+# return f'# Error: Could not read helper script: {e}'
+
+# script_lines.extend(self._get_sensitive_data_definitions())
+
+# # Add the helper script content after imports and sensitive data
+# script_lines.append('\n# --- Helper Functions (from playwright_script_helpers.py) ---')
+# script_lines.append(helper_script_content)
+# script_lines.append('# --- End Helper Functions ---')
+
+# # Generate browser launch and context creation code
+# browser_launch_args = self._generate_browser_launch_args()
+# context_options = self._generate_context_options()
+# # Determine browser type (defaulting to chromium)
+# browser_type = 'chromium'
+# if self.browser_config and self.browser_config.browser_class in ['firefox', 'webkit']:
+# browser_type = self.browser_config.browser_class
+
+# script_lines.extend(
+# [
+# 'async def run_generated_script():',
+# ' global SENSITIVE_DATA', # Ensure sensitive data is accessible
+# ' async with async_playwright() as p:',
+# ' browser = None',
+# ' context = None',
+# ' page = None',
+# ' exit_code = 0 # Default success exit code',
+# ' try:',
+# f" print('Launching {browser_type} browser...')",
+# # Use generated launch args, remove slow_mo
+# f' browser = await p.{browser_type}.launch({browser_launch_args})',
+# # Use generated context options
+# f' context = await browser.new_context({context_options})',
+# " print('Browser context created.')",
+# ]
+# )
+
+# # Add cookie loading logic if cookies_file is specified
+# if self.context_config and self.context_config.cookies_file:
+# cookies_file_path = repr(self.context_config.cookies_file)
+# script_lines.extend(
+# [
+# ' # Load cookies if specified',
+# f' cookies_path = {cookies_file_path}',
+# ' if cookies_path and os.path.exists(cookies_path):',
+# ' try:',
+# " with open(cookies_path, 'r', encoding='utf-8') as f_cookies:",
+# ' cookies = json.load(f_cookies)',
+# ' # Validate sameSite attribute',
+# " valid_same_site = ['Strict', 'Lax', 'None']",
+# ' for cookie in cookies:',
+# " if 'sameSite' in cookie and cookie['sameSite'] not in valid_same_site:",
+# ' print(f\' Warning: Fixing invalid sameSite value "{{cookie["sameSite"]}}" to None for cookie {{cookie.get("name")}}\', file=sys.stderr)',
+# " cookie['sameSite'] = 'None'",
+# ' await context.add_cookies(cookies)',
+# " print(f' Successfully loaded {{len(cookies)}} cookies from {{cookies_path}}')",
+# ' except Exception as cookie_err:',
+# " print(f' Warning: Failed to load or add cookies from {{cookies_path}}: {{cookie_err}}', file=sys.stderr)",
+# ' else:',
+# ' if cookies_path:', # Only print if a path was specified but not found
+# " print(f' Cookie file not found at: {cookies_path}')",
+# '',
+# ]
+# )
+
+# script_lines.extend(
+# [
+# ' # Initial page handling',
+# ' if context.pages:',
+# ' page = context.pages[0]',
+# " print('Using initial page provided by context.')",
+# ' else:',
+# ' page = await context.new_page()',
+# " print('Created a new page as none existed.')",
+# " print('\\n--- Starting Generated Script Execution ---')",
+# ]
+# )
+
+# action_counter = 0
+# stop_processing_steps = False
+# previous_item_dict = None
+
+# for step_index, item_dict in enumerate(self.history):
+# if stop_processing_steps:
+# break
+
+# if not isinstance(item_dict, dict):
+# logger.warning(f'Skipping step {step_index + 1}: Item is not a dictionary ({type(item_dict)})')
+# script_lines.append(f'\n # --- Step {step_index + 1}: Skipped (Invalid Format) ---')
+# previous_item_dict = item_dict
+# continue
+
+# script_lines.append(f'\n # --- Step {step_index + 1} ---')
+# model_output = item_dict.get('model_output')
+
+# if not isinstance(model_output, dict) or 'action' not in model_output:
+# script_lines.append(' # No valid model_output or action found for this step')
+# previous_item_dict = item_dict
+# continue
+
+# actions = model_output.get('action')
+# if not isinstance(actions, list):
+# script_lines.append(f' # Actions format is not a list: {type(actions)}')
+# previous_item_dict = item_dict
+# continue
+
+# for action_index_in_step, action_detail in enumerate(actions):
+# action_counter += 1
+# script_lines.append(f' # Action {action_counter}')
+
+# step_info_str = f'Step {step_index + 1}, Action {action_index_in_step + 1}'
+# action_lines = self._map_action_to_playwright(
+# action_dict=action_detail,
+# history_item=item_dict,
+# previous_history_item=previous_item_dict,
+# action_index_in_step=action_index_in_step,
+# step_info_str=step_info_str,
+# )
+# script_lines.extend(action_lines)
+
+# action_type = next(iter(action_detail.keys()), None) if isinstance(action_detail, dict) else None
+# if action_type == 'done':
+# stop_processing_steps = True
+# break
+
+# previous_item_dict = item_dict
+
+# # Updated final block to include sys.exit
+# script_lines.extend(
+# [
+# ' except PlaywrightActionError as pae:', # Catch specific action errors
+# " print(f'\\n--- Playwright Action Error: {pae} ---', file=sys.stderr)",
+# ' exit_code = 1', # Set exit code to failure
+# ' except Exception as e:',
+# " print(f'\\n--- An unexpected error occurred: {e} ---', file=sys.stderr)",
+# ' import traceback',
+# ' traceback.print_exc()',
+# ' exit_code = 1', # Set exit code to failure
+# ' finally:',
+# " print('\\n--- Generated Script Execution Finished ---')",
+# " print('Closing browser/context...')",
+# ' if context:',
+# ' try: await context.close()',
+# " except Exception as ctx_close_err: print(f' Warning: could not close context: {ctx_close_err}', file=sys.stderr)",
+# ' if browser:',
+# ' try: await browser.close()',
+# " except Exception as browser_close_err: print(f' Warning: could not close browser: {browser_close_err}', file=sys.stderr)",
+# " print('Browser/context closed.')",
+# ' # Exit with the determined exit code',
+# ' if exit_code != 0:',
+# " print(f'Script finished with errors (exit code {exit_code}).', file=sys.stderr)",
+# ' sys.exit(exit_code)', # Exit with non-zero code on error
+# '',
+# '# --- Script Entry Point ---',
+# "if __name__ == '__main__':",
+# " if os.name == 'nt':",
+# ' asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())',
+# ' asyncio.run(run_generated_script())',
+# ]
+# )
+
+# return '\n'.join(script_lines)
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index b4c59166c..964871f30 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -12,19 +12,23 @@ from pathlib import Path
from typing import Any, Generic, TypeVar
from dotenv import load_dotenv
+
+from browser_use.browser.types import BrowserProfile
+
+load_dotenv()
+
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import (
BaseMessage,
HumanMessage,
SystemMessage,
)
-
-# from lmnr.sdk.decorators import observe
+from playwright.async_api import Browser, BrowserContext
from pydantic import BaseModel, ValidationError
+# from lmnr.sdk.decorators import observe
from browser_use.agent.gif import create_history_gif
-from browser_use.agent.memory.service import Memory
-from browser_use.agent.memory.views import MemoryConfig
+from browser_use.agent.memory import Memory, MemoryConfig
from browser_use.agent.message_manager.service import MessageManager, MessageManagerSettings
from browser_use.agent.message_manager.utils import (
convert_input_messages,
@@ -43,12 +47,12 @@ from browser_use.agent.views import (
AgentSettings,
AgentState,
AgentStepInfo,
+ BrowserStateHistory,
StepMetadata,
ToolCallingMethod,
)
-from browser_use.browser.browser import Browser
-from browser_use.browser.context import BrowserContext
-from browser_use.browser.views import BrowserState, BrowserStateHistory
+from browser_use.browser import BrowserSession
+from browser_use.browser.views import BrowserState
from browser_use.controller.registry.views import ActionModel
from browser_use.controller.service import Controller
from browser_use.dom.history_tree_processor.service import (
@@ -56,13 +60,12 @@ from browser_use.dom.history_tree_processor.service import (
HistoryTreeProcessor,
)
from browser_use.exceptions import LLMException
-from browser_use.telemetry.service import ProductTelemetry
+from browser_use.telemetry import ProductTelemetry
from browser_use.telemetry.views import (
AgentTelemetryEvent,
)
from browser_use.utils import check_env_variables, time_execution_async, time_execution_sync
-load_dotenv()
logger = logging.getLogger(__name__)
SKIP_LLM_API_KEY_VERIFICATION = os.environ.get('SKIP_LLM_API_KEY_VERIFICATION', 'false').lower()[0] in 'ty1'
@@ -99,6 +102,8 @@ class Agent(Generic[Context]):
# Optional parameters
browser: Browser | None = None,
browser_context: BrowserContext | None = None,
+ browser_profile: BrowserProfile | None = None,
+ browser_session: BrowserSession | None = None,
controller: Controller[Context] = Controller(),
# Initial agent run parameters
sensitive_data: dict[str, str] | None = None,
@@ -281,18 +286,20 @@ class Agent(Generic[Context]):
self.memory = None
# Browser setup
- self.injected_browser = browser is not None
- self.injected_browser_context = browser_context is not None
- self.browser = browser or Browser()
- self.browser.config.new_context_config.disable_security = self.browser.config.disable_security
- self.browser_context = browser_context or BrowserContext(
- browser=self.browser, config=self.browser.config.new_context_config
+ assert not (browser_session and browser_profile), 'Cannot provide both browser_session and browser_profile'
+ assert not (browser_session and browser), 'Cannot provide both browser_session and browser'
+ assert not (browser_profile and browser), 'Cannot provide both browser_profile and browser'
+ assert not (browser_profile and browser_context), 'Cannot provide both browser_profile and browser_context'
+ assert not (browser and browser_context), 'Cannot provide both browser and browser_context'
+ assert not (browser_session and browser_context), 'Cannot provide both browser_session and browser_context'
+
+ self.browser_session = browser_session or BrowserSession(
+ profile=browser_profile, browser=browser, browser_context=browser_context
)
- # Huge security warning if sensitive_data is provided but allowed_domains is not set
- if self.sensitive_data and not self.browser_context.config.allowed_domains:
+ if self.sensitive_data and not self.browser_profile.allowed_domains:
logger.error(
- '⚠️⚠️⚠️ Agent(sensitive_data=••••••••) was provided but BrowserContextConfig(allowed_domains=[...]) is not locked down! ⚠️⚠️⚠️\n'
+ '⚠️⚠️⚠️ Agent(sensitive_data=••••••••) was provided but BrowserSession(allowed_domains=[...]) is not locked down! ⚠️⚠️⚠️\n'
' ☠️ If the agent visits a malicious website and encounters a prompt-injection attack, your sensitive_data may be exposed!\n\n'
' https://docs.browser-use.com/customize/browser-settings#restrict-urls\n'
'Waiting 10 seconds before continuing... Press [Ctrl+C] to abort.'
@@ -302,7 +309,7 @@ class Agent(Generic[Context]):
time.sleep(10)
except KeyboardInterrupt:
print(
- '\n\n 🛑 Exiting now... set BrowserContextConfig(allowed_domains=["example.com", "example.org"]) to only domains you trust to see your sensitive_data.'
+ '\n\n 🛑 Exiting now... set BrowserSession(allowed_domains=["example.com", "example.org"]) to only domains you trust to see your sensitive_data.'
)
sys.exit(0)
else:
@@ -323,6 +330,18 @@ class Agent(Generic[Context]):
if self.settings.save_conversation_path:
logger.info(f'Saving conversation to {self.settings.save_conversation_path}')
+ @property
+ def browser(self) -> Browser:
+ return self.browser_session.browser
+
+ @property
+ def browser_context(self) -> BrowserContext:
+ return self.browser_session.browser_context
+
+ @property
+ def browser_profile(self) -> BrowserProfile:
+ return self.browser_session.browser_profile
+
def _set_message_context(self) -> str | None:
if self.tool_calling_method == 'raw':
# For raw tool calling, only include actions with no filters initially
@@ -442,8 +461,8 @@ class Agent(Generic[Context]):
tokens = 0
try:
- state = await self.browser_context.get_state(cache_clickable_elements_hashes=True)
- current_page = await self.browser_context.get_current_page()
+ state = await self.browser_session.get_state(cache_clickable_elements_hashes=True)
+ current_page = await self.browser_session.get_current_page()
# generate procedural memory if needed
if self.enable_memory and self.memory and self.state.n_steps % self.memory.config.memory_interval == 0:
@@ -982,8 +1001,7 @@ class Agent(Generic[Context]):
self.state.history.save_as_playwright_script(
self.settings.save_playwright_script_path,
sensitive_data_keys=keys,
- browser_config=self.browser.config,
- context_config=self.browser_context.config,
+ browser_profile=self.browser_session.browser_profile,
)
except Exception as script_gen_err:
# Log any error during script generation/saving
@@ -1008,14 +1026,14 @@ class Agent(Generic[Context]):
"""Execute multiple actions"""
results = []
- cached_selector_map = await self.browser_context.get_selector_map()
+ cached_selector_map = await self.browser_session.get_selector_map()
cached_path_hashes = {e.hash.branch_path_hash for e in cached_selector_map.values()}
- await self.browser_context.remove_highlights()
+ await self.browser_session.remove_highlights()
for i, action in enumerate(actions):
if action.get_index() is not None and i != 0:
- new_state = await self.browser_context.get_state(cache_clickable_elements_hashes=False)
+ new_state = await self.browser_session.get_state(cache_clickable_elements_hashes=False)
new_selector_map = new_state.selector_map
# Detect index change after previous action
@@ -1042,7 +1060,7 @@ class Agent(Generic[Context]):
result = await self.controller.act(
action,
- self.browser_context,
+ self.browser_session,
self.settings.page_extraction_llm,
self.sensitive_data,
self.settings.available_file_paths,
@@ -1055,7 +1073,7 @@ class Agent(Generic[Context]):
if results[-1].is_done or results[-1].error or i == len(actions) - 1:
break
- await asyncio.sleep(self.browser_context.config.wait_between_actions)
+ await asyncio.sleep(self.browser_profile.wait_between_actions)
# hash all elements. if it is a subset of cached_state its fine - else break (new elements on page)
except asyncio.CancelledError:
@@ -1081,8 +1099,8 @@ class Agent(Generic[Context]):
f' example: {{"is_valid": false, "reason": "The user wanted to search for "cat photos", but the agent searched for "dog photos" instead."}}'
)
- if self.browser_context.session:
- state = await self.browser_context.get_state(cache_clickable_elements_hashes=False)
+ if self.browser_context:
+ state = await self.browser_session.get_state(cache_clickable_elements_hashes=False)
content = AgentMessagePrompt(
state=state,
result=self.state.last_result,
@@ -1435,10 +1453,7 @@ class Agent(Generic[Context]):
"""Close all resources"""
try:
# First close browser resources
- if self.browser_context and not self.injected_browser_context:
- await self.browser_context.close()
- if self.browser and not self.injected_browser:
- await self.browser.close()
+ await self.browser_session.stop()
# Force garbage collection
gc.collect()
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index c868f909b..73f81245f 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -12,9 +12,6 @@ from openai import RateLimitError
from pydantic import BaseModel, ConfigDict, Field, ValidationError, create_model
from browser_use.agent.message_manager.views import MessageManagerState
-from browser_use.agent.playwright_script_generator import PlaywrightScriptGenerator
-from browser_use.browser.browser import BrowserConfig
-from browser_use.browser.context import BrowserContextConfig
from browser_use.browser.views import BrowserStateHistory
from browser_use.controller.registry.views import ActionModel
from browser_use.dom.history_tree_processor.service import (
@@ -258,34 +255,37 @@ class AgentHistoryList(BaseModel):
except Exception as e:
raise e
- def save_as_playwright_script(
- self,
- output_path: str | Path,
- sensitive_data_keys: list[str] | None = None,
- browser_config: BrowserConfig | None = None,
- context_config: BrowserContextConfig | None = None,
- ) -> None:
- """
- Generates a Playwright script based on the agent's history and saves it to a file.
- Args:
- output_path: The path where the generated Python script will be saved.
- sensitive_data_keys: A list of keys used as placeholders for sensitive data
- (e.g., ['username_placeholder', 'password_placeholder']).
- These will be loaded from environment variables in the
- generated script.
- browser_config: Configuration of the original Browser instance.
- context_config: Configuration of the original BrowserContext instance.
- """
- try:
- serialized_history = self.model_dump()['history']
- generator = PlaywrightScriptGenerator(serialized_history, sensitive_data_keys, browser_config, context_config)
- script_content = generator.generate_script_content()
- path_obj = Path(output_path)
- path_obj.parent.mkdir(parents=True, exist_ok=True)
- with open(path_obj, 'w', encoding='utf-8') as f:
- f.write(script_content)
- except Exception as e:
- raise e
+ # def save_as_playwright_script(
+ # self,
+ # output_path: str | Path,
+ # sensitive_data_keys: list[str] | None = None,
+ # browser_config: BrowserConfig | None = None,
+ # context_config: BrowserContextConfig | None = None,
+ # ) -> None:
+ # """
+ # Generates a Playwright script based on the agent's history and saves it to a file.
+ # Args:
+ # output_path: The path where the generated Python script will be saved.
+ # sensitive_data_keys: A list of keys used as placeholders for sensitive data
+ # (e.g., ['username_placeholder', 'password_placeholder']).
+ # These will be loaded from environment variables in the
+ # generated script.
+ # browser_config: Configuration of the original Browser instance.
+ # context_config: Configuration of the original BrowserContext instance.
+ # """
+ # from browser_use.agent.playwright_script_generator import PlaywrightScriptGenerator
+
+ # try:
+ # serialized_history = self.model_dump()['history']
+ # generator = PlaywrightScriptGenerator(serialized_history, sensitive_data_keys, browser_config, context_config)
+
+ # script_content = generator.generate_script_content()
+ # path_obj = Path(output_path)
+ # path_obj.parent.mkdir(parents=True, exist_ok=True)
+ # with open(path_obj, 'w', encoding='utf-8') as f:
+ # f.write(script_content)
+ # except Exception as e:
+ # raise e
def model_dump(self, **kwargs) -> dict[str, Any]:
"""Custom serialization that properly uses AgentHistory's model_dump"""
diff --git a/browser_use/browser/__init__.py b/browser_use/browser/__init__.py
new file mode 100644
index 000000000..487a6641e
--- /dev/null
+++ b/browser_use/browser/__init__.py
@@ -0,0 +1,11 @@
+"""
+Browser abstraction for Playwright powered by LLMs.
+"""
+
+# New API (use these moving forward)
+# Legacy API (for backward compatibility)
+from .compat import Browser, BrowserConfig, BrowserContext, BrowserContextConfig
+from .session import BrowserSession
+from .types import BrowserProfile
+
+__all__ = ['Browser', 'BrowserConfig', 'BrowserContext', 'BrowserContextConfig', 'BrowserSession', 'BrowserProfile']
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.py
index ad83fd5ab..88d2adf6f 100644
--- a/browser_use/browser/browser.py
+++ b/browser_use/browser/browser.py
@@ -1,443 +1,5 @@
-"""
-Playwright browser on steroids.
-"""
+# Re-export compatibility classes for backward compatibility
-import asyncio
-import gc
-import logging
-import os
-import socket
-import subprocess
-from pathlib import Path
-from tempfile import gettempdir
-from typing import Literal
+# Old imports will still work
-import httpx
-import psutil
-from dotenv import load_dotenv
-from playwright.async_api import Browser as PlaywrightBrowser
-from playwright.async_api import Playwright, async_playwright
-from pydantic import AliasChoices, BaseModel, ConfigDict, Field
-
-load_dotenv()
-
-
-from browser_use.browser.chrome import (
- CHROME_ARGS,
- CHROME_DEBUG_PORT,
- CHROME_DETERMINISTIC_RENDERING_ARGS,
- CHROME_DISABLE_SECURITY_ARGS,
- CHROME_DOCKER_ARGS,
- CHROME_HEADLESS_ARGS,
-)
-from browser_use.browser.context import BrowserContext, BrowserContextConfig
-from browser_use.browser.utils.screen_resolution import get_screen_resolution, get_window_adjustments
-from browser_use.utils import time_execution_async
-
-logger = logging.getLogger(__name__)
-
-IN_DOCKER = os.environ.get('IN_DOCKER', 'false').lower()[0] in 'ty1'
-
-
-class ProxySettings(BaseModel):
- """the same as playwright.sync_api.ProxySettings, but now as a Pydantic BaseModel so pydantic can validate it"""
-
- server: str
- bypass: str | None = None
- username: str | None = None
- password: str | None = None
-
- model_config = ConfigDict(populate_by_name=True, from_attributes=True)
-
- # Support dict-like behavior for compatibility with Playwright's ProxySettings
- def __getitem__(self, key):
- return getattr(self, key)
-
- def get(self, key, default=None):
- return getattr(self, key, default)
-
-
-class BrowserConfig(BaseModel):
- r"""
- Configuration for the Browser.
-
- Default values:
- headless: False
- Whether to run browser in headless mode (not recommended)
-
- disable_security: False
- Disable browser security features (required for cross-origin iframe support)
-
- extra_browser_args: []
- Extra arguments to pass to the browser
-
- wss_url: None
- Connect to a browser instance via WebSocket
-
- cdp_url: None
- Connect to a browser instance via CDP
-
- browser_binary_path: None
- Path to a Browser instance to use to connect to your normal browser
- e.g. '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'
-
- chrome_remote_debugging_port: 9222
- Chrome remote debugging port to use to when browser_binary_path is supplied.
- This allows running multiple chrome browsers with same browser_binary_path but running on different ports.
- Also, makes it possible to launch new user provided chrome browser without closing already opened chrome instances,
- by providing non-default chrome debugging port.
-
- keep_alive: False
- Keep the browser alive after the agent has finished running
-
- deterministic_rendering: False
- Enable deterministic rendering (makes GPU/font rendering consistent across different OS's and docker)
- """
-
- model_config = ConfigDict(
- arbitrary_types_allowed=True,
- extra='ignore',
- populate_by_name=True,
- from_attributes=True,
- validate_assignment=True,
- revalidate_instances='subclass-instances',
- )
-
- wss_url: str | None = None
- cdp_url: str | None = None
-
- browser_class: Literal['chromium', 'firefox', 'webkit'] = 'chromium'
- browser_binary_path: str | None = Field(
- default=None, validation_alias=AliasChoices('browser_instance_path', 'chrome_instance_path')
- )
- chrome_remote_debugging_port: int | None = CHROME_DEBUG_PORT
- extra_browser_args: list[str] = Field(default_factory=list)
-
- headless: bool = False
- disable_security: bool = False # disable_security=True is dangerous as any malicious URL visited could embed an iframe for the user's bank, and use their cookies to steal money
- deterministic_rendering: bool = False
- keep_alive: bool = Field(default=False, alias='_force_keep_browser_alive') # used to be called _force_keep_browser_alive
-
- proxy: ProxySettings | None = None
- new_context_config: BrowserContextConfig = Field(default_factory=BrowserContextConfig)
-
-
-# @singleton: TODO - think about id singleton makes sense here
-# @dev By default this is a singleton, but you can create multiple instances if you need to.
-class Browser:
- """
- Playwright browser on steroids.
-
- This is persistent browser factory that can spawn multiple browser contexts.
- It is recommended to use only one instance of Browser per your application (RAM usage will grow otherwise).
- """
-
- def __init__(
- self,
- config: BrowserConfig | None = None,
- ):
- logger.debug('🌎 Initializing new browser')
- self.config = config or BrowserConfig()
- self.playwright: Playwright | None = None
- self.playwright_browser: PlaywrightBrowser | None = None
-
- async def new_context(self, config: BrowserContextConfig | None = None) -> BrowserContext:
- """Create a browser context"""
- browser_config = self.config.model_dump() if self.config else {}
- context_config = config.model_dump() if config else {}
- merged_config = {**browser_config, **context_config}
- return BrowserContext(config=BrowserContextConfig(**merged_config), browser=self)
-
- async def get_playwright_browser(self) -> PlaywrightBrowser:
- """Get a browser context"""
- if self.playwright_browser is None:
- return await self._init()
-
- return self.playwright_browser
-
- @time_execution_async('--init (browser)')
- async def _init(self):
- """Initialize the browser session"""
- playwright = await async_playwright().start()
- self.playwright = playwright
-
- browser = await self._setup_browser(playwright)
- self.playwright_browser = browser
-
- return self.playwright_browser
-
- async def _setup_remote_cdp_browser(self, playwright: Playwright) -> PlaywrightBrowser:
- """Sets up and returns a Playwright Browser instance with anti-detection measures. Firefox has no longer CDP support."""
- if 'firefox' in (self.config.browser_binary_path or '').lower():
- raise ValueError(
- 'CDP has been deprecated for firefox, check: https://fxdx.dev/deprecating-cdp-support-in-firefox-embracing-the-future-with-webdriver-bidi/'
- )
- if not self.config.cdp_url:
- raise ValueError('CDP URL is required')
- logger.info(f'🔌 Connecting to remote browser via CDP {self.config.cdp_url}')
- browser_class = getattr(playwright, self.config.browser_class)
- browser = await browser_class.connect_over_cdp(self.config.cdp_url)
- return browser
-
- async def _setup_remote_wss_browser(self, playwright: Playwright) -> PlaywrightBrowser:
- """Sets up and returns a Playwright Browser instance with anti-detection measures."""
- if not self.config.wss_url:
- raise ValueError('WSS URL is required')
- logger.info(f'🔌 Connecting to remote browser via WSS {self.config.wss_url}')
- browser_class = getattr(playwright, self.config.browser_class)
- browser = await browser_class.connect(self.config.wss_url)
- return browser
-
- async def _setup_user_provided_browser(self, playwright: Playwright) -> PlaywrightBrowser:
- """Sets up and returns a Playwright Browser instance with anti-detection measures."""
- if not self.config.browser_binary_path:
- raise ValueError('A browser_binary_path is required')
-
- assert self.config.browser_class == 'chromium', (
- 'browser_binary_path only supports chromium browsers (make sure browser_class=chromium)'
- )
-
- try:
- # Check if browser is already running
- async with httpx.AsyncClient() as client:
- response = await client.get(
- f'http://localhost:{self.config.chrome_remote_debugging_port}/json/version', timeout=2
- )
- if response.status_code == 200:
- logger.info(
- f'🔌 Reusing existing browser found running on http://localhost:{self.config.chrome_remote_debugging_port}'
- )
- browser_class = getattr(playwright, self.config.browser_class)
- browser = await browser_class.connect_over_cdp(
- endpoint_url=f'http://localhost:{self.config.chrome_remote_debugging_port}',
- timeout=20000, # 20 second timeout for connection
- )
- return browser
- except httpx.RequestError:
- logger.debug('🌎 No existing Chrome instance found, starting a new one')
-
- provided_user_data_dir = [arg for arg in self.config.extra_browser_args if '--user-data-dir=' in arg]
-
- if provided_user_data_dir:
- user_data_dir = Path(provided_user_data_dir[0].split('=')[-1])
- else:
- fallback_user_data_dir = Path(gettempdir()) / 'browseruse' / 'profiles' / 'default' # /tmp/browseruse
- try:
- # ~/.config/browseruse/profiles/default
- user_data_dir = Path('~/.config') / 'browseruse' / 'profiles' / 'default'
- user_data_dir = user_data_dir.expanduser()
- user_data_dir.mkdir(parents=True, exist_ok=True)
- except Exception as e:
- logger.error(f'❌ Failed to create ~/.config/browseruse directory: {type(e).__name__}: {e}')
- user_data_dir = fallback_user_data_dir
- user_data_dir.mkdir(parents=True, exist_ok=True)
-
- logger.info(f'🌐 Storing Browser Profile user data dir in: {user_data_dir}')
- try:
- # Remove any existing SingletonLock file to allow the browser to start
- (user_data_dir / 'Default' / 'SingletonLock').unlink()
- self.config.extra_browser_args.append('--no-first-run')
- except (FileNotFoundError, PermissionError, OSError):
- pass
-
- # Start a new Chrome instance
- chrome_launch_args = [
- *{ # remove duplicates (usually preserves the order, but not guaranteed)
- f'--remote-debugging-port={self.config.chrome_remote_debugging_port}',
- *([f'--user-data-dir={user_data_dir.resolve()}'] if not provided_user_data_dir else []),
- *CHROME_ARGS,
- *(CHROME_DOCKER_ARGS if IN_DOCKER else []),
- *(CHROME_HEADLESS_ARGS if self.config.headless else []),
- *(CHROME_DISABLE_SECURITY_ARGS if self.config.disable_security else []),
- *(CHROME_DETERMINISTIC_RENDERING_ARGS if self.config.deterministic_rendering else []),
- *self.config.extra_browser_args,
- },
- ]
- chrome_sub_process = await asyncio.create_subprocess_exec(
- self.config.browser_binary_path,
- *chrome_launch_args,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- shell=False,
- )
- self._chrome_subprocess = psutil.Process(chrome_sub_process.pid)
-
- # Attempt to connect again after starting a new instance
- for _ in range(10):
- try:
- async with httpx.AsyncClient() as client:
- response = await client.get(
- f'http://localhost:{self.config.chrome_remote_debugging_port}/json/version', timeout=2
- )
- if response.status_code == 200:
- break
- except httpx.RequestError:
- pass
- await asyncio.sleep(1)
-
- # Attempt to connect again after starting a new instance
- try:
- browser_class = getattr(playwright, self.config.browser_class)
- browser = await browser_class.connect_over_cdp(
- endpoint_url=f'http://localhost:{self.config.chrome_remote_debugging_port}',
- timeout=20000, # 20 second timeout for connection
- )
- return browser
- except Exception as e:
- logger.error(f'❌ Failed to start a new Chrome instance: {str(e)}')
- raise RuntimeError(
- 'To start chrome in Debug mode, you need to close all existing Chrome instances and try again otherwise we can not connect to the instance.'
- )
-
- async def _setup_builtin_browser(self, playwright: Playwright) -> PlaywrightBrowser:
- """Sets up and returns a Playwright Browser instance with anti-detection measures."""
- assert self.config.browser_binary_path is None, 'browser_binary_path should be None if trying to use the builtin browsers'
-
- # Use the configured window size from new_context_config if available
- if (
- not self.config.headless
- and hasattr(self.config, 'new_context_config')
- and hasattr(self.config.new_context_config, 'window_width')
- and hasattr(self.config.new_context_config, 'window_height')
- and not self.config.new_context_config.no_viewport
- ):
- screen_size = {
- 'width': self.config.new_context_config.window_width,
- 'height': self.config.new_context_config.window_height,
- }
- offset_x, offset_y = get_window_adjustments()
- elif self.config.headless:
- screen_size = {'width': 1920, 'height': 1080}
- offset_x, offset_y = 0, 0
- else:
- screen_size = get_screen_resolution()
- offset_x, offset_y = get_window_adjustments()
-
- chrome_args = {
- f'--remote-debugging-port={self.config.chrome_remote_debugging_port}',
- *CHROME_ARGS,
- *(CHROME_DOCKER_ARGS if IN_DOCKER else []),
- *(CHROME_HEADLESS_ARGS if self.config.headless else []),
- *(CHROME_DISABLE_SECURITY_ARGS if self.config.disable_security else []),
- *(CHROME_DETERMINISTIC_RENDERING_ARGS if self.config.deterministic_rendering else []),
- f'--window-position={offset_x},{offset_y}',
- f'--window-size={screen_size["width"]},{screen_size["height"]}',
- *self.config.extra_browser_args,
- }
-
- # check if chrome remote debugging port is already taken,
- # if so remove the remote-debugging-port arg to prevent conflicts
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
- if s.connect_ex(('localhost', self.config.chrome_remote_debugging_port)) == 0:
- chrome_args.remove(f'--remote-debugging-port={self.config.chrome_remote_debugging_port}')
-
- browser_class = getattr(playwright, self.config.browser_class)
- args = {
- 'chromium': list(chrome_args),
- 'firefox': [
- *{
- '-no-remote',
- *self.config.extra_browser_args,
- }
- ],
- 'webkit': [
- *{
- '--no-startup-window',
- *self.config.extra_browser_args,
- }
- ],
- }
-
- browser = await browser_class.launch(
- channel='chromium', # https://github.com/microsoft/playwright/issues/33566
- headless=self.config.headless,
- args=args[self.config.browser_class],
- proxy=self.config.proxy.model_dump() if self.config.proxy else None,
- handle_sigterm=False,
- handle_sigint=False,
- )
- return browser
-
- async def _setup_browser(self, playwright: Playwright) -> PlaywrightBrowser:
- """Sets up and returns a Playwright Browser instance with anti-detection measures."""
- try:
- if self.config.cdp_url:
- return await self._setup_remote_cdp_browser(playwright)
- if self.config.wss_url:
- return await self._setup_remote_wss_browser(playwright)
-
- if self.config.headless:
- logger.warning('⚠️ Headless mode is not recommended. Many sites will detect and block all headless browsers.')
-
- if self.config.browser_binary_path:
- return await self._setup_user_provided_browser(playwright)
- else:
- return await self._setup_builtin_browser(playwright)
- except Exception as e:
- logger.error(f'Failed to initialize Playwright browser: {e}')
- raise
-
- async def close(self):
- """Close the browser instance"""
- if self.config.keep_alive:
- return
-
- try:
- if self.playwright_browser:
- await self.playwright_browser.close()
- del self.playwright_browser
- if self.playwright:
- await self.playwright.stop()
- del self.playwright
- if chrome_proc := getattr(self, '_chrome_subprocess', None):
- try:
- # always kill all children processes, otherwise chrome leaves a bunch of zombie processes
- for proc in chrome_proc.children(recursive=True):
- proc.kill()
- chrome_proc.kill()
- except Exception as e:
- logger.debug(f'Failed to terminate chrome subprocess: {e}')
-
- # Then cleanup httpx clients
- await self.cleanup_httpx_clients()
- except Exception as e:
- if 'OpenAI error' not in str(e):
- logger.debug(f'Failed to close browser properly: {e}')
-
- finally:
- self.playwright_browser = None
- self.playwright = None
- self._chrome_subprocess = None
- gc.collect()
-
- def __del__(self):
- """Async cleanup when object is destroyed"""
- try:
- if self.playwright_browser or self.playwright:
- loop = asyncio.get_running_loop()
- if loop.is_running():
- loop.create_task(self.close())
- else:
- asyncio.run(self.close())
- except Exception as e:
- logger.debug(f'Failed to cleanup browser in destructor: {e}')
-
- async def cleanup_httpx_clients(self):
- """Cleanup all httpx clients"""
- import gc
-
- import httpx
-
- # Force garbage collection to make sure all clients are in memory
- gc.collect()
-
- # Get all httpx clients
- clients = [obj for obj in gc.get_objects() if isinstance(obj, httpx.AsyncClient)]
-
- # Close all clients
- for client in clients:
- if not client.is_closed:
- try:
- await client.aclose()
- except Exception as e:
- logger.debug(f'Error closing httpx client: {e}')
+# New, simpler imports
diff --git a/browser_use/browser/chrome.py b/browser_use/browser/chrome.py
deleted file mode 100644
index e3e7d3a45..000000000
--- a/browser_use/browser/chrome.py
+++ /dev/null
@@ -1,177 +0,0 @@
-CHROME_EXTENSIONS = {} # coming in a separate PR
-CHROME_EXTENSIONS_PATH = 'chrome_extensions'
-CHROME_PROFILE_PATH = 'chrome_profile'
-CHROME_PROFILE_USER = 'Default'
-CHROME_DEBUG_PORT = 9242
-CHROME_DISABLED_COMPONENTS = [
- 'Translate',
- 'AcceptCHFrame',
- 'OptimizationHints',
- 'ProcessPerSiteUpToMainFrameThreshold',
- 'InterestFeedContentSuggestions',
- # 'CalculateNativeWinOcclusion',
- 'BackForwardCache',
- # 'HeavyAdPrivacyMitigations',
- 'LazyFrameLoading',
- # 'ImprovedCookieControls',
- 'PrivacySandboxSettings4',
- 'AutofillServerCommunication',
- 'CertificateTransparencyComponentUpdater',
- 'DestroyProfileOnBrowserClose',
- 'CrashReporting',
- 'OverscrollHistoryNavigation',
- 'InfiniteSessionRestore',
- #'LockProfileCookieDatabase', # disabling allows multiple chrome instances to concurrently modify profile, but might make chrome much slower https://github.com/yt-dlp/yt-dlp/issues/7271 https://issues.chromium.org/issues/40901624
-] # it's always best to give each chrome instance its own exclusive copy of the user profile
-
-
-CHROME_HEADLESS_ARGS = [
- '--headless=new',
- # '--test-type',
- # '--test-type=gpu', # https://github.com/puppeteer/puppeteer/issues/10516
- # '--enable-automation', # <- DONT USE THIS, it makes you easily detectable / blocked by cloudflare
-]
-
-CHROME_DOCKER_ARGS = [
- # Docker-specific options
- # https://github.com/GoogleChrome/lighthouse-ci/tree/main/docs/recipes/docker-client#--no-sandbox-issues-explained
- '--no-sandbox', # rely on docker sandboxing in docker, otherwise we need cap_add: SYS_ADM to use host sandboxing
- '--disable-gpu-sandbox',
- '--disable-setuid-sandbox',
- '--disable-dev-shm-usage', # docker 75mb default shm size is not big enough, disabling just uses /tmp instead
- '--no-xshm',
- # dont try to disable (or install) dbus in docker, its not needed, chrome can work without dbus despite the errors
-]
-
-CHROME_DISABLE_SECURITY_ARGS = [
- # DANGER: JS isolation security features (to allow easier tampering with pages during automation)
- # chrome://net-internals
- '--disable-web-security', # <- WARNING, breaks some sites that expect/enforce strict CORS headers (try webflow.com)
- '--disable-site-isolation-trials',
- '--disable-features=IsolateOrigins,site-per-process',
- # '--allow-file-access-from-files', # <- WARNING, dangerous, allows JS to read filesystem using file:// URLs
- # DANGER: Disable HTTPS verification
- '--allow-running-insecure-content', # Breaks CORS/CSRF/HSTS etc., useful sometimes but very easy to detect
- '--ignore-certificate-errors',
- '--ignore-ssl-errors',
- '--ignore-certificate-errors-spki-list',
- # '--allow-insecure-localhost',
-]
-
-# flags to make chrome behave more deterministically across different OS's
-CHROME_DETERMINISTIC_RENDERING_ARGS = [
- '--deterministic-mode',
- '--js-flags=--random-seed=1157259159', # make all JS random numbers deterministic by providing a seed
- '--force-device-scale-factor=1',
- # GPU, canvas, text, and pdf rendering config
- # chrome://gpu
- '--enable-webgl', # enable web-gl graphics support
- '--font-render-hinting=none', # make rendering more deterministic by ignoring OS font hints, may also need css override, try: * {text-rendering: geometricprecision !important; -webkit-font-smoothing: antialiased;}
- '--force-color-profile=srgb', # make rendering more deterministic by using consistent color profile, if browser looks weird, try: generic-rgb
- # '--disable-partial-raster', # make rendering more deterministic (TODO: verify if still needed)
- '--disable-skia-runtime-opts', # make rendering more deterministic by avoiding Skia hot path runtime optimizations
- '--disable-2d-canvas-clip-aa', # make rendering more deterministic by disabling antialiasing on 2d canvas clips
- # '--disable-gpu', # falls back to more consistent software renderer across all OS's, especially helps linux text rendering look less weird
- # // '--use-gl=swiftshader', <- DO NOT USE, breaks M1 ARM64. it makes rendering more deterministic by using simpler CPU renderer instead of OS GPU renderer bug: https://groups.google.com/a/chromium.org/g/chromium-dev/c/8eR2GctzGuw
- # // '--disable-software-rasterizer', <- DO NOT USE, harmless, used in tandem with --disable-gpu
- # // '--run-all-compositor-stages-before-draw', <- DO NOT USE, makes headful chrome hang on startup (tested v121 Google Chrome.app on macOS)
- # // '--disable-gl-drawing-for-tests', <- DO NOT USE, disables gl output (makes tests run faster if you dont care about canvas)
- # // '--blink-settings=imagesEnabled=false', <- DO NOT USE, disables images entirely (only sometimes useful to speed up loading)
-]
-
-
-CHROME_ARGS = [
- # Process management & performance tuning
- # chrome://process-internals
- # '--disable-lazy-loading', # make rendering more deterministic by loading all content up-front instead of on-focus
- # '--disable-renderer-backgrounding', # dont throttle tab rendering based on focus/visibility
- # '--disable-background-networking', # dont throttle tab networking based on focus/visibility
- # '--disable-background-timer-throttling', # dont throttle tab timers based on focus/visibility
- # '--disable-backgrounding-occluded-windows', # dont throttle tab window based on focus/visibility
- # '--disable-ipc-flooding-protection', # dont throttle ipc traffic or accessing big request/response/buffer/etc. objects will fail
- # '--disable-extensions-http-throttling', # dont throttle http traffic based on runtime heuristics
- # '--disable-field-trial-config', # disable shared field trial state between browser processes
- # '--disable-back-forward-cache', # disable browsing navigation cache
- # Profile data dir setup
- # chrome://profile-internals
- # f'--user-data-dir={CHROME_PROFILE_PATH}', # managed by playwright arg instead
- # f'--profile-directory={CHROME_PROFILE_USER}',
- # '--password-store=basic', # use mock keychain instead of OS-provided keychain (we manage auth.json instead)
- # '--use-mock-keychain',
- # '--disable-cookie-encryption', # we need to be able to write unencrypted cookies to save/load auth.json
- '--disable-sync', # don't try to use Google account sync features while automation is active
- # Extensions
- # chrome://inspect/#extensions
- # f'--load-extension={CHROME_EXTENSIONS.map(({unpacked_path}) => unpacked_path).join(',')}', # not needed when using existing profile that already has extensions installed
- # f'--allowlisted-extension-id={",".join(CHROME_EXTENSIONS.keys())}',
- '--allow-legacy-extension-manifests',
- '--allow-pre-commit-input', # allow JS mutations before page rendering is complete
- '--disable-blink-features=AutomationControlled', # hide the signatures that announce browser is being remote-controlled
- # f'--proxy-server=https://43.159.28.126:2334:u7ce652b7568805c4-zone-custom-region-us-session-szGWq3FRU-sessTime-60:u7ce652b7568805c4', # send all network traffic through a proxy https://2captcha.com/proxy
- # f'--proxy-bypass-list=127.0.0.1',
- # Browser window and viewport setup
- # chrome://version
- # f'--user-agent="{DEFAULT_USER_AGENT}"',
- # f'--window-size={DEFAULT_VIEWPORT.width},{DEFAULT_VIEWPORT.height}',
- # '--window-position=0,0',
- # '--start-maximized',
- '--install-autogenerated-theme=0,0,0', # black border makes it easier to see which chrome window is browser-use's
- '--hide-scrollbars', # stop scrollbars from affecting screenshot width/height
- #'--virtual-time-budget=60000', # DONT USE THIS, makes chrome hang forever and doesn't work, used to fast-forward all animations & timers by 60s, dont use this it's unfortunately buggy and breaks screenshot and PDF capture sometimes
- #'--autoplay-policy=no-user-gesture-required', # auto-start videos so they trigger network requests + show up in outputs
- #'--disable-gesture-requirement-for-media-playback',
- #'--lang=en-US,en;q=0.9',
- # IO: stdin/stdout, debug port config
- # chrome://inspect
- '--log-level=2', # 1=DEBUG 2=WARNING 3=ERROR
- '--enable-logging=stderr',
- # '--remote-debugging-address=127.0.0.1', <- DONT USE THIS, no longer supported on chrome >100, never expose to non-localhost, would allow attacker to drive your browser from any machine
- # '--enable-experimental-extension-apis', # add support for tab groups via chrome.tabs extension API
- '--disable-focus-on-load', # prevent browser from hijacking focus
- '--disable-window-activation',
- # '--in-process-gpu', <- DONT USE THIS, makes headful startup time ~5-10s slower (tested v121 Google Chrome.app on macOS)
- # '--disable-component-extensions-with-background-pages', # TODO: check this, disables chrome components that only run in background with no visible UI (could lower startup time)
- # uncomment to disable hardware camera/mic/speaker access + present fake devices to websites
- # (faster to disable, but disabling breaks recording browser audio in puppeteer-stream screenrecordings)
- # '--use-fake-device-for-media-stream',
- # '--use-fake-ui-for-media-stream',
- # '--disable-features=GlobalMediaControls,MediaRouter,DialMediaRouteProvider',
- # Output format options (PDF, screenshot, etc.)
- '--export-tagged-pdf', # include table on contents and tags in printed PDFs
- '--generate-pdf-document-outline',
- # Suppress first-run features, popups, hints, updates, etc.
- # chrome://system
- '--no-pings',
- '--no-default-browser-check',
- '--no-startup-window',
- '--ash-no-nudges',
- '--disable-infobars',
- '--disable-search-engine-choice-screen',
- '--disable-session-crashed-bubble',
- '--simulate-outdated-no-au="Tue, 31 Dec 2099 23:59:59 GMT"', # disable browser self-update while automation is active
- '--hide-crash-restore-bubble',
- '--suppress-message-center-popups',
- '--disable-client-side-phishing-detection',
- '--disable-domain-reliability',
- '--disable-datasaver-prompt',
- '--disable-hang-monitor',
- '--disable-session-crashed-bubble',
- '--disable-speech-synthesis-api',
- '--disable-speech-api',
- '--disable-print-preview',
- '--safebrowsing-disable-auto-update',
- # '--deny-permission-prompts',
- '--disable-external-intent-requests',
- # '--disable-notifications',
- '--disable-desktop-notifications',
- '--noerrdialogs',
- '--disable-prompt-on-repost',
- '--silent-debugger-extension-api',
- # '--block-new-web-contents',
- '--metrics-recording-only',
- '--disable-breakpad',
- # other feature flags
- # chrome://flags chrome://components
- f'--disable-features={",".join(CHROME_DISABLED_COMPONENTS)}',
- '--enable-features=NetworkService',
-]
diff --git a/browser_use/browser/compat.py b/browser_use/browser/compat.py
new file mode 100644
index 000000000..391927306
--- /dev/null
+++ b/browser_use/browser/compat.py
@@ -0,0 +1,53 @@
+DEPRECATION_MESSAGE = """
+⚠️ {} is deprecated. Use the ✨ new, simplified BrowserSession(**all_config_here) ✨ instead!\n
+ from browser_use.browser import BrowserSession, BrowserProfile
+
+ browser_profile = BrowserProfile(
+ # ⬇️ the old BrowserConfig, BrowserContextConfig kwargs all go in one place now:
+ headless=False,
+ disable_security=False,
+ keep_alive=True,
+ extra_browser_args=['--start-maximized'],
+ allowed_domains=['example.com', '*.google.com'],
+ browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ ...
+ )
+
+ # then start a session using the profile to connect/launch to the live browser:
+ browser_session = BrowserSession(
+ profile=browser_profile,
+ # pass a CDP URL to connect to an existing browser instance:
+ cdp_url='http://localhost:9222',
+ # or provide a custom binary to launch:
+ browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ # or pass live playwright or patchright objects to use them directly:
+ browser=playwright_browser,
+ browser_context=playwright_browser_context,
+ )
+ agent = Agent(browser_session=browser_session, ...)
+ ...
+"""
+
+
+class DeprecatedClass:
+ def __init__(self, *_args, **_kwargs):
+ print(DEPRECATION_MESSAGE.format(type(self).__name__))
+ raise NotImplementedError(
+ f'{type(self).__name__} is deprecated. Use browser_use.browser.BrowserProfile and BrowserSession instead.'
+ )
+
+
+class BrowserConfig(DeprecatedClass):
+ pass
+
+
+class BrowserContextConfig(DeprecatedClass):
+ pass
+
+
+class Browser(DeprecatedClass):
+ pass
+
+
+class BrowserContext(DeprecatedClass):
+ pass
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 2f47d3ca9..0c62a6606 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -1,2027 +1 @@
-"""
-Playwright browser on steroids.
-"""
-
-import asyncio
-import base64
-import gc
-import json
-import logging
-import os
-import re
-import time
-import uuid
-from dataclasses import dataclass
-from typing import TYPE_CHECKING
-
-import anyio
-from playwright._impl._errors import TimeoutError
-from playwright.async_api import Browser as PlaywrightBrowser
-from playwright.async_api import (
- BrowserContext as PlaywrightBrowserContext,
-)
-from playwright.async_api import (
- ElementHandle,
- FrameLocator,
- Page,
-)
-from pydantic import BaseModel, ConfigDict, Field
-
-from browser_use.browser.views import (
- BrowserError,
- BrowserState,
- TabInfo,
- URLNotAllowedError,
-)
-from browser_use.dom.clickable_element_processor.service import ClickableElementProcessor
-from browser_use.dom.service import DomService
-from browser_use.dom.views import DOMElementNode, SelectorMap
-from browser_use.utils import time_execution_async, time_execution_sync
-
-if TYPE_CHECKING:
- from browser_use.browser.browser import Browser
-
-logger = logging.getLogger(__name__)
-
-import platform
-
-BROWSER_NAVBAR_HEIGHT = {
- 'windows': 85,
- 'darwin': 80,
- 'linux': 90,
-}.get(platform.system().lower(), 85)
-
-_GLOB_WARNING_SHOWN = False
-
-
-class BrowserContextConfig(BaseModel):
- """
- Configuration for the BrowserContext.
-
- Default values:
- cookies_file: None
- Path to cookies file for persistence
-
- disable_security: False
- Disable browser security features (dangerous, but cross-origin iframe support requires it)
-
- minimum_wait_page_load_time: 0.5
- Minimum time to wait before getting page state for LLM input
-
- wait_for_network_idle_page_load_time: 1.0
- Time to wait for network requests to finish before getting page state.
- Lower values may result in incomplete page loads.
-
- maximum_wait_page_load_time: 5.0
- Maximum time to wait for page load before proceeding anyway
-
- wait_between_actions: 1.0
- Time to wait between multiple per step actions
-
- window_width: 1280
- window_height: 1100
- Default browser window dimensions
-
- no_viewport: True
- When True (default), the browser window size determines the viewport.
- When False, forces a fixed viewport size using window_width and window_height. (constraint of the rendered content to a smaller area than the default of the entire window size)
-
- save_recording_path: None
- Path to save video recordings
-
- save_downloads_path: None
- Path to save downloads to
-
- trace_path: None
- Path to save trace files. It will auto name the file with the TRACE_PATH/{context_id}.zip
-
- locale: None
- Specify user locale, for example en-GB, de-DE, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting rules. If not provided, defaults to the system default locale.
-
- user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
- custom user agent to use.
-
- highlight_elements: True
- Highlight elements in the DOM on the screen
-
- viewport_expansion: 0
- Viewport expansion in pixels. This amount will increase the number of elements which are included in the state what the LLM will see. If set to -1, all elements will be included (this leads to high token usage). If set to 0, only the elements which are visible in the viewport will be included.
-
- allowed_domains: None
- List of allowed domains that can be accessed. If None, all domains are allowed.
- Example: ['example.com', 'api.example.com']
-
- include_dynamic_attributes: bool = True
- Include dynamic attributes in the CSS selector. If you want to reuse the css_selectors, it might be better to set this to False.
-
- http_credentials: None
- Dictionary with HTTP basic authentication credentials for corporate intranets (only supports one set of credentials for all URLs at the moment), e.g.
- {"username": "bill", "password": "pa55w0rd"}
-
- is_mobile: None
- Whether the meta viewport tag is taken into account and touch events are enabled.
-
- has_touch: None
- Whether to enable touch events in the browser.
-
- geolocation: None
- Geolocation to be used in the browser context. Example: {'latitude': 59.95, 'longitude': 30.31667}
-
- permissions: ['clipboard-read', 'clipboard-write']
- Browser permissions to grant. See full list here: https://playwright.dev/python/docs/api/class-browsercontext#browser-context-grant-permissions
-
- timezone_id: None
- Changes the timezone of the browser. Example: 'Europe/Berlin'
-
- force_new_context: False
- Forces a new browser context to be created. Useful when running locally with branded browser (e.g Chrome, Edge) and setting a custom config.
- """
-
- model_config = ConfigDict(
- arbitrary_types_allowed=True,
- extra='ignore',
- populate_by_name=True,
- from_attributes=True,
- validate_assignment=True,
- revalidate_instances='subclass-instances',
- )
-
- cookies_file: str | None = None
- minimum_wait_page_load_time: float = 0.25
- wait_for_network_idle_page_load_time: float = 0.5
- maximum_wait_page_load_time: float = 5
- wait_between_actions: float = 0.5
-
- disable_security: bool = False # disable_security=True is dangerous as any malicious URL visited could embed an iframe for the user's bank, and use their cookies to steal money
-
- window_width: int = 1280
- window_height: int = 1100
- no_viewport: bool = True # True is the default for headful mode - browser window size determines viewport
-
- save_recording_path: str | None = None
- save_downloads_path: str | None = None
- save_har_path: str | None = None
- trace_path: str | None = None
- locale: str | None = None
- user_agent: str | None = None
-
- highlight_elements: bool = True
- viewport_expansion: int = 0
- allowed_domains: list[str] | None = None
- include_dynamic_attributes: bool = True
- http_credentials: dict[str, str] | None = None
-
- keep_alive: bool = Field(default=False, alias='_force_keep_context_alive') # used to be called _force_keep_context_alive
- is_mobile: bool | None = None
- has_touch: bool | None = None
- geolocation: dict | None = None
- permissions: list[str] = Field(
- default_factory=lambda: [
- 'clipboard-read',
- 'clipboard-write',
- ]
- )
- timezone_id: str | None = None
-
- force_new_context: bool = False
-
-
-@dataclass
-class CachedStateClickableElementsHashes:
- """
- Clickable elements hashes for the last state
- """
-
- url: str
- hashes: set[str]
-
-
-class BrowserSession:
- def __init__(self, context: PlaywrightBrowserContext, cached_state: BrowserState | None = None):
- self.context = context
- self.cached_state = cached_state
-
- self.cached_state_clickable_elements_hashes: CachedStateClickableElementsHashes | None = None
-
-
-@dataclass
-class BrowserContextState:
- """
- State of the browser context
- """
-
- target_id: str | None = None # CDP target ID
-
-
-class BrowserContext:
- def __init__(
- self,
- browser: 'Browser',
- config: BrowserContextConfig | None = None,
- state: BrowserContextState | None = None,
- ):
- self.context_id = str(uuid.uuid4())
-
- self.config = config or BrowserContextConfig(**(browser.config.model_dump() if browser.config else {}))
- self.browser = browser
-
- self.state = state or BrowserContextState()
-
- # Initialize these as None - they'll be set up when needed
- self.session: BrowserSession | None = None
-
- # Tab references - separate concepts for agent intent and browser state
- self.agent_current_page: Page | None = None # The tab the agent intends to interact with
- self.human_current_page: Page | None = None # The tab currently shown in the browser UI
-
- async def __aenter__(self):
- """Async context manager entry"""
- await self._initialize_session()
- return self
-
- async def __aexit__(self, exc_type, exc_val, exc_tb):
- """Async context manager exit"""
- await self.close()
-
- @time_execution_async('--close')
- async def close(self):
- """Close the browser instance"""
-
- try:
- if self.session is None:
- return
-
- # Then remove CDP protocol listeners
- if self._page_event_handler and self.session.context:
- try:
- # This actually sends a CDP command to unsubscribe
- self.session.context.remove_listener('page', self._page_event_handler)
- except Exception as e:
- logger.debug(f'Failed to remove CDP listener: {e}')
- self._page_event_handler = None
-
- await self.save_cookies()
-
- if self.config.trace_path:
- try:
- await self.session.context.tracing.stop(path=os.path.join(self.config.trace_path, f'{self.context_id}.zip'))
- except Exception as e:
- logger.debug(f'Failed to stop tracing: {e}')
-
- # This is crucial - it closes the CDP connection
- if not self.config.keep_alive:
- logger.debug('Closing browser context')
- try:
- await self.session.context.close()
- except Exception as e:
- logger.debug(f'Failed to close context: {e}')
-
- finally:
- # Dereference everything
- self.agent_current_page = None
- self.human_current_page = None
- self.session = None
- self._page_event_handler = None
-
- def __del__(self):
- """Cleanup when object is destroyed"""
- if not self.config.keep_alive and self.session is not None:
- logger.debug('BrowserContext was not properly closed before destruction')
- try:
- # Use sync Playwright method for force cleanup
- if hasattr(self.session.context, '_impl_obj'):
- asyncio.run(self.session.context._impl_obj.close())
-
- self.session = None
- self.agent_current_page = None
- self.human_current_page = None
- gc.collect()
- except Exception as e:
- logger.warning(f'Failed to force close browser context: {e}')
-
- @time_execution_async('--initialize_session')
- async def _initialize_session(self):
- """Initialize the browser session"""
- logger.debug(f'🌎 Initializing new browser context with id: {self.context_id}')
-
- playwright_browser = await self.browser.get_playwright_browser()
- context = await self._create_context(playwright_browser)
- self._page_event_handler = None
-
- # auto-attach the foregrounding-detection listener to all new pages opened
- context.on('page', self._add_tab_foregrounding_listener)
-
- # Get or create a page to use
- pages = context.pages
-
- self.session = BrowserSession(
- context=context,
- cached_state=None,
- )
-
- current_page = None
- if self.browser.config.cdp_url:
- # If we have a saved target ID, try to find and activate it
- if self.state.target_id:
- targets = await self._get_cdp_targets()
- for target in targets:
- if target['targetId'] == self.state.target_id:
- # Find matching page by URL
- for page in pages:
- if page.url == target['url']:
- current_page = page
- break
- break
-
- # If no target ID or couldn't find it, use existing page or create new
- if not current_page:
- if (
- pages
- and pages[0].url
- and not pages[0].url.startswith('chrome://') # skip chrome internal pages e.g. settings, history, etc
- and not pages[0].url.startswith('chrome-extension://') # skip hidden extension background pages
- ):
- current_page = pages[0]
- logger.debug('🔍 Using existing page: %s', current_page.url)
- else:
- current_page = await context.new_page()
- await current_page.goto('about:blank')
- logger.debug('🆕 Created new page: %s', current_page.url)
-
- # Get target ID for the active page
- if self.browser.config.cdp_url:
- targets = await self._get_cdp_targets()
- for target in targets:
- if target['url'] == current_page.url:
- self.state.target_id = target['targetId']
- break
-
- # Bring page to front
- logger.debug('🫨 Bringing tab to front: %s', current_page)
- await current_page.bring_to_front()
- await current_page.wait_for_load_state('load')
-
- # Set the viewport size for the active page
- await self.set_viewport_size(current_page)
-
- # Initialize both tab references to the same page initially
- self.agent_current_page = current_page
- self.human_current_page = current_page
-
- # Set up visibility listeners for all existing tabs
- for page in pages:
- if not page.url.startswith('chrome-extension://') and not page.url.startswith('chrome://') and not page.is_closed():
- await self._add_tab_foregrounding_listener(page)
- # logger.debug(f'👁️ Added visibility listener to existing tab: {page.url}')
-
- return self.session
-
- async def _add_tab_foregrounding_listener(self, page: Page):
- """
- Attaches listeners that detect when the human steals active tab focus away from the agent.
-
- Uses a combination of:
- - visibilitychange events
- - window focus/blur events
- - pointermove events
-
- This multi-method approach provides more reliable detection across browsers.
-
- TODO: pester the playwright team to add a new event that fires when a headful tab is focused.
- OR implement a browser-use chrome extension that acts as a bridge to the chrome.tabs API.
-
- - https://github.com/microsoft/playwright/issues/1290
- - https://github.com/microsoft/playwright/issues/2286
- - https://github.com/microsoft/playwright/issues/3570
- - https://github.com/microsoft/playwright/issues/13989
- """
-
- def trunc(s, max_len=None):
- s = s.replace('https://', '').replace('http://', '').replace('www.', '')
- if max_len is not None and len(s) > max_len:
- return s[:max_len] + '…'
- return s
-
- try:
- # Generate a unique function name for this page
- visibility_func_name = f'onVisibilityChange_{id(page)}{id(page.url)}'
-
- # Define the callback that will be called from browser when tab becomes visible
- async def on_visibility_change(data):
- source = data.get('source', 'unknown')
-
- # Log before and after for debugging
- old_foreground = self.human_current_page
- if old_foreground.url != page.url:
- logger.warning(
- f'👁️ Foregound tab changed by human from {trunc(old_foreground.url, 22) if old_foreground else "about:blank"} to {trunc(page.url, 22)} ({source}) but agent will stay on {trunc(self.agent_current_page.url, 22)}'
- )
-
- # Update foreground tab
- self.human_current_page = page
-
- # Expose the function to the browser
- await page.expose_function(visibility_func_name, on_visibility_change)
-
- # Set up multiple visibility detection methods in the browser
- js_code = """() => {
- // --- Method 1: visibilitychange event (unfortunately *all* tabs are always marked visible by playwright, usually does not fire) ---
- document.addEventListener('visibilitychange', () => {
- if (document.visibilityState === 'visible') {
- window.onVisibilityChange_TABID({ source: 'visibilitychange' });
- }
- });
-
- // --- Method 2: focus/blur events, most reliable method for headful browsers ---
- window.addEventListener('focus', () => {
- window.onVisibilityChange_TABID({ source: 'focus' });
- });
-
- // --- Method 3: pointermove events (may be fired by agent if we implement AI hover movements) ---
- // Use a throttled handler to avoid excessive calls
- // let lastMove = 0;
- // window.addEventListener('pointermove', () => {
- // const now = Date.now();
- // if (now - lastMove > 1000) { // Throttle to once per second
- // lastMove = now;
- // window.onVisibilityChange_TABID({ source: 'pointermove' });
- // }
- // });
- }""".replace('onVisibilityChange_TABID', visibility_func_name)
- # multiple reasons for doing it this way ^: stealth, uniqueness, sometimes pageload is cancelled and it runs twice, etc.
- await page.evaluate(js_code)
-
- # re-add listener to the page for when it navigates to a new url, because previous listeners will be cleared
- page.on('domcontentloaded', self._add_tab_foregrounding_listener)
- logger.debug(f'👀 Added tab focus listeners to tab: {page.url}')
-
- if page.url != self.agent_current_page.url:
- await on_visibility_change({'source': 'navigation'})
-
- except Exception as e:
- logger.debug(f'Failed to add tab focus listener to {page.url}: {e}')
-
- async def get_session(self) -> BrowserSession:
- """Lazy initialization of the browser and related components"""
- if self.session is None:
- try:
- return await self._initialize_session()
- except Exception as e:
- logger.error(f'❌ Failed to create new browser session: {e} (did the browser process quit?)')
- raise e
- return self.session
-
- async def get_current_page(self) -> Page:
- """Legacy method for backwards compatibility, prefer get_agent_current_page()"""
- return await self.get_agent_current_page()
-
- async def _reconcile_tab_state(self) -> None:
- """Reconcile tab state when tabs might be out of sync.
-
- This method ensures that:
- 1. Both tab references (agent_current_page and human_current_page) are valid
- 2. Recovers invalid tab references using valid ones
- 3. Handles the case where both references are invalid
- """
- session = await self.get_session()
-
- agent_tab_valid = (
- self.agent_current_page
- and self.agent_current_page in session.context.pages
- and not self.agent_current_page.is_closed()
- )
-
- human_current_page_valid = (
- self.human_current_page
- and self.human_current_page in session.context.pages
- and not self.human_current_page.is_closed()
- )
-
- # Case 1: Both references are valid - nothing to do
- if agent_tab_valid and human_current_page_valid:
- return
-
- # Case 2: Only agent_current_page is valid - update human_current_page
- if agent_tab_valid and not human_current_page_valid:
- self.human_current_page = self.agent_current_page
- return
-
- # Case 3: Only human_current_page is valid - update agent_current_page
- if human_current_page_valid and not agent_tab_valid:
- self.agent_current_page = self.human_current_page
- return
-
- # Case 4: Neither reference is valid - recover from available tabs
- non_extension_pages = [
- page
- for page in session.context.pages
- if not page.url.startswith('chrome-extension://') and not page.url.startswith('chrome://')
- ]
-
- if non_extension_pages:
- # Update both tab references to the most recently opened non-extension page
- recovered_page = non_extension_pages[-1]
- self.agent_current_page = recovered_page
- self.human_current_page = recovered_page
- return
-
- # Case 5: No valid pages at all - create a new page
- try:
- new_page = await session.context.new_page()
- self.agent_current_page = new_page
- self.human_current_page = new_page
- except Exception:
- # Last resort - recreate the session
- logger.warning('⚠️ No browser window available, recreating session')
- await self._initialize_session()
- if session.context.pages:
- page = session.context.pages[0]
- self.agent_current_page = page
- self.human_current_page = page
-
- async def get_agent_current_page(self) -> Page:
- """Get the page that the agent is currently working with.
-
- This method prioritizes agent_current_page over human_current_page, ensuring
- that agent operations happen on the intended tab regardless of user
- interaction with the browser.
-
- If agent_current_page is invalid or closed, it will attempt to recover
- with a valid tab reference by reconciling the tab state.
- """
- session = await self.get_session()
-
- # First check if agent_current_page is valid
- if (
- self.agent_current_page
- and self.agent_current_page in session.context.pages
- and not self.agent_current_page.is_closed()
- ):
- return self.agent_current_page
-
- # If we're here, reconcile tab state and try again
- await self._reconcile_tab_state()
-
- # After reconciliation, agent_current_page should be valid
- if (
- self.agent_current_page
- and self.agent_current_page in session.context.pages
- and not self.agent_current_page.is_closed()
- ):
- return self.agent_current_page
-
- # If still invalid, fall back to first page method as last resort
- logger.warning('⚠️ Failed to get agent current page, falling back to first page')
- if session.context.pages:
- page = session.context.pages[0]
- self.agent_current_page = page
- self.human_current_page = page
- return page
-
- # If no pages, create one
- return await session.context.new_page()
-
- async def _create_context(self, browser: PlaywrightBrowser):
- """Creates a new browser context with anti-detection measures and loads cookies if available."""
- if self.browser.config.cdp_url and len(browser.contexts) > 0 and not self.config.force_new_context:
- context = browser.contexts[0]
- # For existing contexts, we need to set the viewport size manually
- if context.pages and not self.browser.config.headless:
- for page in context.pages:
- await self.set_viewport_size(page)
- elif self.browser.config.browser_binary_path and len(browser.contexts) > 0 and not self.config.force_new_context:
- # Connect to existing Chrome instance instead of creating new one
- context = browser.contexts[0]
- # For existing contexts, we need to set the viewport size manually
- if context.pages and not self.browser.config.headless:
- for page in context.pages:
- await self.set_viewport_size(page)
- else:
- kwargs = {}
- # Set viewport for both headless and non-headless modes
- if self.browser.config.headless:
- # In headless mode, always set viewport and no_viewport=False
- kwargs['viewport'] = {'width': self.config.window_width, 'height': self.config.window_height}
- kwargs['no_viewport'] = False
- else:
- # In headful mode, use the no_viewport value from config (defaults to True)
- no_viewport_value = self.config.no_viewport
- kwargs['no_viewport'] = no_viewport_value
-
- # Only set viewport if no_viewport is False
- if not no_viewport_value:
- kwargs['viewport'] = {'width': self.config.window_width, 'height': self.config.window_height}
-
- if self.config.user_agent is not None:
- kwargs['user_agent'] = self.config.user_agent
-
- context = await browser.new_context(
- **kwargs,
- java_script_enabled=True,
- **({'bypass_csp': True, 'ignore_https_errors': True} if self.config.disable_security else {}),
- record_video_dir=self.config.save_recording_path,
- record_video_size={'width': self.config.window_width, 'height': self.config.window_height},
- record_har_path=self.config.save_har_path,
- locale=self.config.locale,
- http_credentials=self.config.http_credentials,
- is_mobile=self.config.is_mobile,
- has_touch=self.config.has_touch,
- geolocation=self.config.geolocation,
- permissions=self.config.permissions,
- timezone_id=self.config.timezone_id,
- )
-
- # Ensure required permissions are granted
- required_permissions = ['clipboard-read', 'clipboard-write'] # needed for google sheets automation
- if self.config.geolocation:
- required_permissions.append('geolocation')
- missing_permissions = [p for p in required_permissions if p not in self.config.permissions]
- if any(missing_permissions):
- logger.warning(
- f'⚠️ Some permissions required by browser-use {missing_permissions} are missing from BrowserContextConfig(permissions={self.config.permissions}), some features may not work properly!'
- )
- await context.grant_permissions(self.config.permissions)
-
- if self.config.trace_path:
- await context.tracing.start(screenshots=True, snapshots=True, sources=True)
-
- # Resize the window for non-headless mode
- if not self.browser.config.headless:
- await self._resize_window(context)
-
- # Load cookies if they exist
- if self.config.cookies_file and os.path.exists(self.config.cookies_file):
- async with await anyio.open_file(self.config.cookies_file, 'r') as f:
- try:
- cookies = json.loads(await f.read())
-
- valid_same_site_values = ['Strict', 'Lax', 'None']
- for cookie in cookies:
- if 'sameSite' in cookie:
- if cookie['sameSite'] not in valid_same_site_values:
- logger.warning(
- f"Fixed invalid sameSite value '{cookie['sameSite']}' to 'None' for cookie {cookie.get('name')}"
- )
- cookie['sameSite'] = 'None'
- logger.info(f'🍪 Loaded {len(cookies)} cookies from {self.config.cookies_file}')
- await context.add_cookies(cookies)
-
- except json.JSONDecodeError as e:
- logger.error(f'Failed to parse cookies file: {str(e)}')
-
- init_script = """
- // check to make sure we're not inside the PDF viewer
- window.isPdfViewer = !!document?.body?.querySelector('body > embed[type="application/pdf"][width="100%"]')
- if (!window.isPdfViewer) {
-
- // Permissions
- const originalQuery = window.navigator.permissions.query;
- window.navigator.permissions.query = (parameters) => (
- parameters.name === 'notifications' ?
- Promise.resolve({ state: Notification.permission }) :
- originalQuery(parameters)
- );
- (() => {
- if (window._eventListenerTrackerInitialized) return;
- window._eventListenerTrackerInitialized = true;
-
- const originalAddEventListener = EventTarget.prototype.addEventListener;
- const eventListenersMap = new WeakMap();
-
- EventTarget.prototype.addEventListener = function(type, listener, options) {
- if (typeof listener === "function") {
- let listeners = eventListenersMap.get(this);
- if (!listeners) {
- listeners = [];
- eventListenersMap.set(this, listeners);
- }
-
- listeners.push({
- type,
- listener,
- listenerPreview: listener.toString().slice(0, 100),
- options
- });
- }
-
- return originalAddEventListener.call(this, type, listener, options);
- };
-
- window.getEventListenersForNode = (node) => {
- const listeners = eventListenersMap.get(node) || [];
- return listeners.map(({ type, listenerPreview, options }) => ({
- type,
- listenerPreview,
- options
- }));
- };
- })();
- }
- """
-
- # Expose anti-detection scripts
- await context.add_init_script(init_script)
-
- return context
-
- async def set_viewport_size(self, page: Page) -> None:
- """
- Central method to set viewport size for a page.
- Simple for now, but we may need to add more logic here in the future to rezise surrounding window, change recording options, etc.
- """
- try:
- # Only set viewport size if no_viewport is False (aka viewport=True)
- if self.config.no_viewport is False:
- viewport_size = {'width': self.config.window_width, 'height': self.config.window_height}
- await page.set_viewport_size(viewport_size)
- logger.debug(f'Set viewport size to {self.config.window_width}x{self.config.window_height}')
- # else:
- # logger.debug('Skipping viewport size setting because no_viewport is not False')
- except Exception as e:
- logger.debug(f'Failed to set viewport size for page: {e}')
-
- async def _wait_for_stable_network(self):
- page = await self.get_agent_current_page()
-
- pending_requests = set()
- last_activity = asyncio.get_event_loop().time()
-
- # Define relevant resource types and content types
- RELEVANT_RESOURCE_TYPES = {
- 'document',
- 'stylesheet',
- 'image',
- 'font',
- 'script',
- 'iframe',
- }
-
- RELEVANT_CONTENT_TYPES = {
- 'text/html',
- 'text/css',
- 'application/javascript',
- 'image/',
- 'font/',
- 'application/json',
- }
-
- # Additional patterns to filter out
- IGNORED_URL_PATTERNS = {
- # Analytics and tracking
- 'analytics',
- 'tracking',
- 'telemetry',
- 'beacon',
- 'metrics',
- # Ad-related
- 'doubleclick',
- 'adsystem',
- 'adserver',
- 'advertising',
- # Social media widgets
- 'facebook.com/plugins',
- 'platform.twitter',
- 'linkedin.com/embed',
- # Live chat and support
- 'livechat',
- 'zendesk',
- 'intercom',
- 'crisp.chat',
- 'hotjar',
- # Push notifications
- 'push-notifications',
- 'onesignal',
- 'pushwoosh',
- # Background sync/heartbeat
- 'heartbeat',
- 'ping',
- 'alive',
- # WebRTC and streaming
- 'webrtc',
- 'rtmp://',
- 'wss://',
- # Common CDNs for dynamic content
- 'cloudfront.net',
- 'fastly.net',
- }
-
- async def on_request(request):
- # Filter by resource type
- if request.resource_type not in RELEVANT_RESOURCE_TYPES:
- return
-
- # Filter out streaming, websocket, and other real-time requests
- if request.resource_type in {
- 'websocket',
- 'media',
- 'eventsource',
- 'manifest',
- 'other',
- }:
- return
-
- # Filter out by URL patterns
- url = request.url.lower()
- if any(pattern in url for pattern in IGNORED_URL_PATTERNS):
- return
-
- # Filter out data URLs and blob URLs
- if url.startswith(('data:', 'blob:')):
- return
-
- # Filter out requests with certain headers
- headers = request.headers
- if headers.get('purpose') == 'prefetch' or headers.get('sec-fetch-dest') in [
- 'video',
- 'audio',
- ]:
- return
-
- nonlocal last_activity
- pending_requests.add(request)
- last_activity = asyncio.get_event_loop().time()
- # logger.debug(f'Request started: {request.url} ({request.resource_type})')
-
- async def on_response(response):
- request = response.request
- if request not in pending_requests:
- return
-
- # Filter by content type if available
- content_type = response.headers.get('content-type', '').lower()
-
- # Skip if content type indicates streaming or real-time data
- if any(
- t in content_type
- for t in [
- 'streaming',
- 'video',
- 'audio',
- 'webm',
- 'mp4',
- 'event-stream',
- 'websocket',
- 'protobuf',
- ]
- ):
- pending_requests.remove(request)
- return
-
- # Only process relevant content types
- if not any(ct in content_type for ct in RELEVANT_CONTENT_TYPES):
- pending_requests.remove(request)
- return
-
- # Skip if response is too large (likely not essential for page load)
- content_length = response.headers.get('content-length')
- if content_length and int(content_length) > 5 * 1024 * 1024: # 5MB
- pending_requests.remove(request)
- return
-
- nonlocal last_activity
- pending_requests.remove(request)
- last_activity = asyncio.get_event_loop().time()
- # logger.debug(f'Request resolved: {request.url} ({content_type})')
-
- # Attach event listeners
- page.on('request', on_request)
- page.on('response', on_response)
-
- try:
- # Wait for idle time
- start_time = asyncio.get_event_loop().time()
- while True:
- await asyncio.sleep(0.1)
- now = asyncio.get_event_loop().time()
- if len(pending_requests) == 0 and (now - last_activity) >= self.config.wait_for_network_idle_page_load_time:
- break
- if now - start_time > self.config.maximum_wait_page_load_time:
- logger.debug(
- f'Network timeout after {self.config.maximum_wait_page_load_time}s with {len(pending_requests)} '
- f'pending requests: {[r.url for r in pending_requests]}'
- )
- break
-
- finally:
- # Clean up event listeners
- page.remove_listener('request', on_request)
- page.remove_listener('response', on_response)
-
- logger.debug(f'⚖️ Network stabilized for {self.config.wait_for_network_idle_page_load_time} seconds')
-
- async def _wait_for_page_and_frames_load(self, timeout_overwrite: float | None = None):
- """
- Ensures page is fully loaded before continuing.
- Waits for either network to be idle or minimum WAIT_TIME, whichever is longer.
- Also checks if the loaded URL is allowed.
- """
- # Start timing
- start_time = time.time()
-
- # Wait for page load
- try:
- await self._wait_for_stable_network()
-
- # Check if the loaded URL is allowed
- page = await self.get_agent_current_page()
- await self._check_and_handle_navigation(page)
- except URLNotAllowedError as e:
- raise e
- except Exception:
- logger.warning('⚠️ Page load failed, continuing...')
- pass
-
- # Calculate remaining time to meet minimum WAIT_TIME
- elapsed = time.time() - start_time
- remaining = max((timeout_overwrite or self.config.minimum_wait_page_load_time) - elapsed, 0)
-
- logger.debug(f'--Page loaded in {elapsed:.2f} seconds, waiting for additional {remaining:.2f} seconds')
-
- # Sleep remaining time if needed
- if remaining > 0:
- await asyncio.sleep(remaining)
-
- def _is_url_allowed(self, url: str) -> bool:
- """
- Check if a URL is allowed based on the whitelist configuration.
-
- Supports glob patterns in allowed_domains:
- - *.example.com will match sub.example.com and example.com
- - *google.com will match google.com, agoogle.com, and www.google.com
- """
-
- if not self.config.allowed_domains:
- return True
-
- def _show_glob_warning(domain: str, glob: str):
- global _GLOB_WARNING_SHOWN
- if not _GLOB_WARNING_SHOWN:
- logger.warning(
- # glob patterns are very easy to mess up and match too many domains by accident
- # e.g. if you only need to access gmail, don't use *.google.com because an attacker could convince the agent to visit a malicious doc
- # on docs.google.com/s/some/evil/doc to set up a prompt injection attack
- "⚠️ Allowing agent to visit {domain} based on allowed_domains=['{glob}', ...]. Set allowed_domains=['{domain}', ...] explicitly to avoid the security risks of glob patterns!"
- )
- _GLOB_WARNING_SHOWN = True
-
- try:
- import fnmatch
- from urllib.parse import urlparse
-
- parsed_url = urlparse(url)
-
- # Special case: Allow 'about:blank' explicitly
- if url == 'about:blank' or parsed_url.scheme.lower() in ('chrome', 'brave', 'edge', 'chrome-extension'):
- return True
-
- # Extract only the hostname component (without auth credentials or port)
- # Hostname returns only the domain portion, ignoring username:password and port
- domain = parsed_url.hostname.lower() if parsed_url.hostname else ''
-
- if not domain:
- return False
-
- for allowed_domain in self.config.allowed_domains:
- allowed_domain = allowed_domain.lower()
-
- # Handle glob patterns
- if '*' in allowed_domain:
- # Special handling for *.domain.tld pattern to also match the bare domain
- if allowed_domain.startswith('*.'):
- # If pattern is *.example.com, also allow example.com (without subdomain)
- parent_domain = allowed_domain[2:] # Remove the '*.' prefix
- if domain == parent_domain or fnmatch.fnmatch(domain, allowed_domain):
- _show_glob_warning(domain, allowed_domain)
- return True
- else:
- # For other glob patterns like *google.com
- if fnmatch.fnmatch(domain, allowed_domain):
- _show_glob_warning(domain, allowed_domain)
- return True
- else:
- # Standard matching (exact or subdomain)
- if domain == allowed_domain:
- return True
-
- return False
- except Exception as e:
- logger.error(f'⛔️ Error checking URL allowlist: {type(e).__name__}: {e}')
- return False
-
- async def _check_and_handle_navigation(self, page: Page) -> None:
- """Check if current page URL is allowed and handle if not."""
- if not self._is_url_allowed(page.url):
- logger.warning(f'⛔️ Navigation to non-allowed URL detected: {page.url}')
- try:
- await self.go_back()
- except Exception as e:
- logger.error(f'⛔️ Failed to go back after detecting non-allowed URL: {str(e)}')
- raise URLNotAllowedError(f'Navigation to non-allowed URL: {page.url}')
-
- async def navigate_to(self, url: str):
- """Navigate the agent's current tab to a URL"""
- if not self._is_url_allowed(url):
- raise BrowserError(f'Navigation to non-allowed URL: {url}')
-
- page = await self.get_agent_current_page()
- await page.goto(url)
- await page.wait_for_load_state()
-
- async def refresh_page(self):
- """Refresh the agent's current page"""
- page = await self.get_agent_current_page()
- await page.reload()
- await page.wait_for_load_state()
-
- async def go_back(self):
- """Navigate the agent's tab back in browser history"""
- page = await self.get_agent_current_page()
- try:
- # 10 ms timeout
- await page.go_back(timeout=10, wait_until='domcontentloaded')
- # await self._wait_for_page_and_frames_load(timeout_overwrite=1.0)
- except Exception as e:
- # Continue even if its not fully loaded, because we wait later for the page to load
- logger.debug(f'⏮️ Error during go_back: {e}')
-
- async def go_forward(self):
- """Navigate the agent's tab forward in browser history"""
- page = await self.get_agent_current_page()
- try:
- await page.go_forward(timeout=10, wait_until='domcontentloaded')
- except Exception as e:
- # Continue even if its not fully loaded, because we wait later for the page to load
- logger.debug(f'⏭️ Error during go_forward: {e}')
-
- async def close_current_tab(self):
- """Close the current tab that the agent is working with.
-
- This closes the tab that the agent is currently using (agent_current_page),
- not necessarily the tab that is visible to the user (human_current_page).
- If they are the same tab, both references will be updated.
- """
- session = await self.get_session()
- page = await self.get_agent_current_page()
-
- # Check if this is the foreground tab as well
- is_foreground = page == self.human_current_page
-
- # Close the tab
- await page.close()
-
- # Clear agent's reference to the closed tab
- self.agent_current_page = None
-
- # Clear foreground reference if needed
- if is_foreground:
- self.human_current_page = None
-
- # Switch to the first available tab if any exist
- if session.context.pages:
- await self.switch_to_tab(0)
- # switch_to_tab already updates both tab references
-
- # Otherwise, the browser will be closed
-
- async def get_page_html(self) -> str:
- """Get the HTML content of the agent's current page"""
- page = await self.get_agent_current_page()
- return await page.content()
-
- async def execute_javascript(self, script: str):
- """Execute JavaScript code on the agent's current page"""
- page = await self.get_agent_current_page()
- return await page.evaluate(script)
-
- async def get_page_structure(self) -> str:
- """Get a debug view of the page structure including iframes"""
- debug_script = """(() => {
- function getPageStructure(element = document, depth = 0, maxDepth = 10) {
- if (depth >= maxDepth) return '';
-
- const indent = ' '.repeat(depth);
- let structure = '';
-
- // Skip certain elements that clutter the output
- const skipTags = new Set(['script', 'style', 'link', 'meta', 'noscript']);
-
- // Add current element info if it's not the document
- if (element !== document) {
- const tagName = element.tagName.toLowerCase();
-
- // Skip uninteresting elements
- if (skipTags.has(tagName)) return '';
-
- const id = element.id ? `#${element.id}` : '';
- const classes = element.className && typeof element.className === 'string' ?
- `.${element.className.split(' ').filter(c => c).join('.')}` : '';
-
- // Get additional useful attributes
- const attrs = [];
- if (element.getAttribute('role')) attrs.push(`role="${element.getAttribute('role')}"`);
- if (element.getAttribute('aria-label')) attrs.push(`aria-label="${element.getAttribute('aria-label')}"`);
- if (element.getAttribute('type')) attrs.push(`type="${element.getAttribute('type')}"`);
- if (element.getAttribute('name')) attrs.push(`name="${element.getAttribute('name')}"`);
- if (element.getAttribute('src')) {
- const src = element.getAttribute('src');
- attrs.push(`src="${src.substring(0, 50)}${src.length > 50 ? '...' : ''}"`);
- }
-
- // Add element info
- structure += `${indent}${tagName}${id}${classes}${attrs.length ? ' [' + attrs.join(', ') + ']' : ''}\\n`;
-
- // Handle iframes specially
- if (tagName === 'iframe') {
- try {
- const iframeDoc = element.contentDocument || element.contentWindow?.document;
- if (iframeDoc) {
- structure += `${indent} [IFRAME CONTENT]:\\n`;
- structure += getPageStructure(iframeDoc, depth + 2, maxDepth);
- } else {
- structure += `${indent} [IFRAME: No access - likely cross-origin]\\n`;
- }
- } catch (e) {
- structure += `${indent} [IFRAME: Access denied - ${e.message}]\\n`;
- }
- }
- }
-
- // Get all child elements
- const children = element.children || element.childNodes;
- for (const child of children) {
- if (child.nodeType === 1) { // Element nodes only
- structure += getPageStructure(child, depth + 1, maxDepth);
- }
- }
-
- return structure;
- }
-
- return getPageStructure();
- })()"""
-
- page = await self.get_agent_current_page()
- structure = await page.evaluate(debug_script)
- return structure
-
- @time_execution_sync('--get_state') # This decorator might need to be updated to handle async
- async def get_state(self, cache_clickable_elements_hashes: bool) -> BrowserState:
- """Get the current state of the browser
-
- cache_clickable_elements_hashes: bool
- If True, cache the clickable elements hashes for the current state. This is used to calculate which elements are new to the llm (from last message) -> reduces token usage.
- """
- await self._wait_for_page_and_frames_load()
- session = await self.get_session()
- updated_state = await self._get_updated_state()
-
- # Find out which elements are new
- # Do this only if url has not changed
- if cache_clickable_elements_hashes:
- # if we are on the same url as the last state, we can use the cached hashes
- if (
- session.cached_state_clickable_elements_hashes
- and session.cached_state_clickable_elements_hashes.url == updated_state.url
- ):
- # Pointers, feel free to edit in place
- updated_state_clickable_elements = ClickableElementProcessor.get_clickable_elements(updated_state.element_tree)
-
- for dom_element in updated_state_clickable_elements:
- dom_element.is_new = (
- ClickableElementProcessor.hash_dom_element(dom_element)
- not in session.cached_state_clickable_elements_hashes.hashes # see which elements are new from the last state where we cached the hashes
- )
- # in any case, we need to cache the new hashes
- session.cached_state_clickable_elements_hashes = CachedStateClickableElementsHashes(
- url=updated_state.url,
- hashes=ClickableElementProcessor.get_clickable_elements_hashes(updated_state.element_tree),
- )
-
- session.cached_state = updated_state
-
- # Save cookies if a file is specified
- if self.config.cookies_file:
- asyncio.create_task(self.save_cookies())
-
- return session.cached_state
-
- async def _get_updated_state(self, focus_element: int = -1) -> BrowserState:
- """Update and return state."""
- session = await self.get_session()
-
- # Check if current page is still valid, if not switch to another available page
- try:
- page = await self.get_agent_current_page()
- # Test if page is still accessible
- await page.evaluate('1')
- except Exception as e:
- logger.debug(f'👋 Current page is no longer accessible: {str(e)}')
- raise BrowserError('Browser closed: no valid pages available')
-
- try:
- await self.remove_highlights()
- dom_service = DomService(page)
- content = await dom_service.get_clickable_elements(
- focus_element=focus_element,
- viewport_expansion=self.config.viewport_expansion,
- highlight_elements=self.config.highlight_elements,
- )
-
- tabs_info = await self.get_tabs_info()
-
- # Get all cross-origin iframes within the page and open them in new tabs
- # mark the titles of the new tabs so the LLM knows to check them for additional content
- # unfortunately too buggy for now, too many sites use invisible cross-origin iframes for ads, tracking, youtube videos, social media, etc.
- # and it distracts the bot by opening a lot of new tabs
- # iframe_urls = await dom_service.get_cross_origin_iframes()
- # for url in iframe_urls:
- # if url in [tab.url for tab in tabs_info]:
- # continue # skip if the iframe if we already have it open in a tab
- # new_page_id = tabs_info[-1].page_id + 1
- # logger.debug(f'Opening cross-origin iframe in new tab #{new_page_id}: {url}')
- # await self.create_new_tab(url)
- # tabs_info.append(
- # TabInfo(
- # page_id=new_page_id,
- # url=url,
- # title=f'iFrame opened as new tab, treat as if embedded inside page #{self.state.target_id}: {page.url}',
- # parent_page_id=self.state.target_id,
- # )
- # )
-
- screenshot_b64 = await self.take_screenshot()
- pixels_above, pixels_below = await self.get_scroll_info(page)
-
- # Find the agent's active tab ID
- agent_current_page_id = 0
- if self.agent_current_page:
- for tab_info in tabs_info:
- if tab_info.url == self.agent_current_page.url:
- agent_current_page_id = tab_info.page_id
- break
-
- self.current_state = BrowserState(
- element_tree=content.element_tree,
- selector_map=content.selector_map,
- url=page.url,
- title=await page.title(),
- tabs=tabs_info,
- screenshot=screenshot_b64,
- pixels_above=pixels_above,
- pixels_below=pixels_below,
- )
-
- return self.current_state
- except Exception as e:
- logger.error(f'❌ Failed to update state: {str(e)}')
- # Return last known good state if available
- if hasattr(self, 'current_state'):
- return self.current_state
- raise
-
- # region - Browser Actions
- @time_execution_async('--take_screenshot')
- async def take_screenshot(self, full_page: bool = False) -> str:
- """
- Returns a base64 encoded screenshot of the current page.
- """
- page = await self.get_agent_current_page()
-
- # We no longer force tabs to the foreground as it disrupts user focus
- # await page.bring_to_front()
- await page.wait_for_load_state()
-
- screenshot = await page.screenshot(
- full_page=full_page,
- animations='disabled',
- caret='initial',
- )
-
- screenshot_b64 = base64.b64encode(screenshot).decode('utf-8')
-
- # await self.remove_highlights()
-
- return screenshot_b64
-
- @time_execution_async('--remove_highlights')
- async def remove_highlights(self):
- """
- Removes all highlight overlays and labels created by the highlightElement function.
- Handles cases where the page might be closed or inaccessible.
- """
- try:
- page = await self.get_agent_current_page()
- 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:
- logger.debug(f'⚠ Failed to remove highlights (this is usually ok): {str(e)}')
- # Don't raise the error since this is not critical functionality
- pass
-
- # endregion
-
- # region - User Actions
-
- @classmethod
- def _convert_simple_xpath_to_css_selector(cls, xpath: str) -> str:
- """Converts simple XPath expressions to CSS selectors."""
- if not xpath:
- return ''
-
- # Remove leading slash if present
- xpath = xpath.lstrip('/')
-
- # Split into parts
- parts = xpath.split('/')
- css_parts = []
-
- for part in parts:
- if not part:
- continue
-
- # Handle custom elements with colons by escaping them
- if ':' in part and '[' not in part:
- base_part = part.replace(':', r'\:')
- css_parts.append(base_part)
- continue
-
- # Handle index notation [n]
- if '[' in part:
- base_part = part[: part.find('[')]
- # Handle custom elements with colons in the base part
- if ':' in base_part:
- base_part = base_part.replace(':', r'\:')
- index_part = part[part.find('[') :]
-
- # Handle multiple indices
- indices = [i.strip('[]') for i in index_part.split(']')[:-1]]
-
- for idx in indices:
- try:
- # Handle numeric indices
- if idx.isdigit():
- index = int(idx) - 1
- base_part += f':nth-of-type({index + 1})'
- # Handle last() function
- elif idx == 'last()':
- base_part += ':last-of-type'
- # Handle position() functions
- elif 'position()' in idx:
- if '>1' in idx:
- base_part += ':nth-of-type(n+2)'
- except ValueError:
- continue
-
- css_parts.append(base_part)
- else:
- css_parts.append(part)
-
- base_selector = ' > '.join(css_parts)
- return base_selector
-
- @classmethod
- @time_execution_sync('--enhanced_css_selector_for_element')
- def _enhanced_css_selector_for_element(cls, element: DOMElementNode, include_dynamic_attributes: bool = True) -> str:
- """
- 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
-
- Returns:
- A valid CSS selector string
- """
- try:
- # Get base selector from XPath
- css_selector = cls._convert_simple_xpath_to_css_selector(element.xpath)
-
- # Handle class attributes
- if 'class' in element.attributes and element.attributes['class'] and include_dynamic_attributes:
- # Define a regex pattern for valid class names in CSS
- valid_class_name_pattern = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_-]*$')
-
- # Iterate through the class attribute values
- classes = element.attributes['class'].split()
- for class_name in classes:
- # Skip empty class names
- if not class_name.strip():
- continue
-
- # Check if the class name is valid
- if valid_class_name_pattern.match(class_name):
- # Append the valid class name to the CSS selector
- css_selector += f'.{class_name}'
- else:
- # Skip invalid class names
- continue
-
- # Expanded set of safe attributes that are stable and useful for selection
- SAFE_ATTRIBUTES = {
- # Data attributes (if they're stable in your application)
- 'id',
- # Standard HTML attributes
- 'name',
- 'type',
- 'placeholder',
- # Accessibility attributes
- 'aria-label',
- 'aria-labelledby',
- 'aria-describedby',
- 'role',
- # Common form attributes
- 'for',
- 'autocomplete',
- 'required',
- 'readonly',
- # Media attributes
- 'alt',
- 'title',
- 'src',
- # Custom stable attributes (add any application-specific ones)
- 'href',
- 'target',
- }
-
- if include_dynamic_attributes:
- dynamic_attributes = {
- 'data-id',
- 'data-qa',
- 'data-cy',
- 'data-testid',
- }
- SAFE_ATTRIBUTES.update(dynamic_attributes)
-
- # Handle other attributes
- for attribute, value in element.attributes.items():
- if attribute == 'class':
- continue
-
- # Skip invalid attribute names
- if not attribute.strip():
- continue
-
- if attribute not in SAFE_ATTRIBUTES:
- continue
-
- # Escape special characters in attribute names
- safe_attribute = attribute.replace(':', r'\:')
-
- # Handle different value cases
- if value == '':
- css_selector += f'[{safe_attribute}]'
- elif any(char in value for char in '"\'<>`\n\r\t'):
- # Use contains for values with special characters
- # For newline-containing text, only use the part before the newline
- if '\n' in value:
- value = value.split('\n')[0]
- # Regex-substitute *any* whitespace with a single space, then strip.
- collapsed_value = re.sub(r'\s+', ' ', value).strip()
- # Escape embedded double-quotes.
- safe_value = collapsed_value.replace('"', '\\"')
- css_selector += f'[{safe_attribute}*="{safe_value}"]'
- else:
- css_selector += f'[{safe_attribute}="{value}"]'
-
- 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}']"
-
- @time_execution_async('--is_visible')
- async def _is_visible(self, element: ElementHandle) -> bool:
- """
- Checks if an element is visible on the page.
- We use our own implementation instead of relying solely on Playwright's is_visible() because
- of edge cases with CSS frameworks like Tailwind. When elements use Tailwind's 'hidden' class,
- the computed style may return display as '' (empty string) instead of 'none', causing Playwright
- to incorrectly consider hidden elements as visible. By additionally checking the bounding box
- dimensions, we catch elements that have zero width/height regardless of how they were hidden.
- """
- is_hidden = await element.is_hidden()
- bbox = await element.bounding_box()
-
- return not is_hidden and bbox is not None and bbox['width'] > 0 and bbox['height'] > 0
-
- @time_execution_async('--get_locate_element')
- async def get_locate_element(self, element: DOMElementNode) -> ElementHandle | None:
- current_frame = await self.get_agent_current_page()
-
- # Start with the target element and collect all parents
- parents: list[DOMElementNode] = []
- current = element
- while current.parent is not None:
- parent = current.parent
- parents.append(parent)
- current = parent
-
- # Reverse the parents list to process from top to bottom
- parents.reverse()
-
- # Process all iframe parents in sequence
- iframes = [item for item in parents if item.tag_name == 'iframe']
- for parent in iframes:
- css_selector = self._enhanced_css_selector_for_element(
- parent,
- include_dynamic_attributes=self.config.include_dynamic_attributes,
- )
- current_frame = current_frame.frame_locator(css_selector)
-
- css_selector = self._enhanced_css_selector_for_element(
- element, include_dynamic_attributes=self.config.include_dynamic_attributes
- )
-
- try:
- if isinstance(current_frame, FrameLocator):
- element_handle = await current_frame.locator(css_selector).element_handle()
- return element_handle
- else:
- # Try to scroll into view if hidden
- element_handle = await current_frame.query_selector(css_selector)
- if element_handle:
- is_visible = await self._is_visible(element_handle)
- if is_visible:
- await element_handle.scroll_into_view_if_needed()
- return element_handle
- return None
- except Exception as e:
- logger.error(f'❌ Failed to locate element: {str(e)}')
- return None
-
- @time_execution_async('--get_locate_element_by_xpath')
- async def get_locate_element_by_xpath(self, xpath: str) -> ElementHandle | None:
- """
- Locates an element on the page using the provided XPath.
- """
- current_frame = await self.get_agent_current_page()
-
- try:
- # Use XPath to locate the element
- element_handle = await current_frame.query_selector(f'xpath={xpath}')
- if element_handle:
- is_visible = await self._is_visible(element_handle)
- if is_visible:
- await element_handle.scroll_into_view_if_needed()
- return element_handle
- return None
- except Exception as e:
- logger.error(f'❌ Failed to locate element by XPath {xpath}: {str(e)}')
- return None
-
- @time_execution_async('--get_locate_element_by_css_selector')
- async def get_locate_element_by_css_selector(self, css_selector: str) -> ElementHandle | None:
- """
- Locates an element on the page using the provided CSS selector.
- """
- current_frame = await self.get_agent_current_page()
-
- try:
- # Use CSS selector to locate the element
- element_handle = await current_frame.query_selector(css_selector)
- if element_handle:
- is_visible = await self._is_visible(element_handle)
- if is_visible:
- await element_handle.scroll_into_view_if_needed()
- return element_handle
- return None
- except Exception as e:
- logger.error(f'❌ Failed to locate element by CSS selector {css_selector}: {str(e)}')
- return None
-
- @time_execution_async('--get_locate_element_by_text')
- async def get_locate_element_by_text(
- self, text: str, nth: int | None = 0, element_type: str | None = None
- ) -> ElementHandle | None:
- """
- Locates an element on the page using the provided text.
- If `nth` is provided, it returns the nth matching element (0-based).
- If `element_type` is provided, filters by tag name (e.g., 'button', 'span').
- """
- current_frame = await self.get_agent_current_page()
- try:
- # handle also specific element type or use any type.
- selector = f'{element_type or "*"}:text("{text}")'
- elements = await current_frame.query_selector_all(selector)
- # considering only visible elements
- elements = [el for el in elements if await self._is_visible(el)]
-
- if not elements:
- logger.error(f"No visible element with text '{text}' found.")
- return None
-
- if nth is not None:
- if 0 <= nth < len(elements):
- element_handle = elements[nth]
- else:
- logger.error(f"Visible element with text '{text}' not found at index {nth}.")
- return None
- else:
- element_handle = elements[0]
-
- is_visible = await self._is_visible(element_handle)
- if is_visible:
- await element_handle.scroll_into_view_if_needed()
- return element_handle
- except Exception as e:
- logger.error(f"❌ Failed to locate element by text '{text}': {str(e)}")
- return None
-
- @time_execution_async('--input_text_element_node')
- async def _input_text_element_node(self, element_node: DOMElementNode, 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.
- """
- try:
- # Highlight before typing
- # if element_node.highlight_index is not None:
- # await self._update_state(focus_element=element_node.highlight_index)
-
- element_handle = await self.get_locate_element(element_node)
-
- if element_handle is None:
- raise BrowserError(f'Element: {repr(element_node)} not found')
-
- # Ensure element is ready for input
- try:
- await element_handle.wait_for_element_state('stable', timeout=1000)
- is_visible = await self._is_visible(element_handle)
- if is_visible:
- await element_handle.scroll_into_view_if_needed(timeout=1000)
- except Exception:
- pass
-
- # Get element properties to determine input method
- tag_handle = await element_handle.get_property('tagName')
- tag_name = (await tag_handle.json_value()).lower()
- is_contenteditable = await element_handle.get_property('isContentEditable')
- readonly_handle = await element_handle.get_property('readOnly')
- disabled_handle = await element_handle.get_property('disabled')
-
- readonly = await readonly_handle.json_value() if readonly_handle else False
- disabled = await disabled_handle.json_value() if disabled_handle else False
-
- # always click the element first to make sure it's in the focus
- await element_handle.click()
- await asyncio.sleep(0.1)
-
- try:
- if (await is_contenteditable.json_value() or tag_name == 'input') and not (readonly or disabled):
- await element_handle.evaluate('el => {el.textContent = ""; el.value = "";}')
- await element_handle.type(text, delay=5)
- else:
- await element_handle.fill(text)
- except Exception:
- # last resort fallback, assume it's already focused after we clicked on it,
- # just simulate keypresses on the entire page
- await self.get_agent_current_page().keyboard.type(text)
-
- except Exception as e:
- logger.debug(f'❌ Failed to input text into element: {repr(element_node)}. Error: {str(e)}')
- raise BrowserError(f'Failed to input text into index {element_node.highlight_index}')
-
- @time_execution_async('--click_element_node')
- async def _click_element_node(self, element_node: DOMElementNode) -> str | None:
- """
- Optimized method to click an element using xpath.
- """
- page = await self.get_agent_current_page()
-
- try:
- # Highlight before clicking
- # if element_node.highlight_index is not None:
- # await self._update_state(focus_element=element_node.highlight_index)
-
- element_handle = await self.get_locate_element(element_node)
-
- if element_handle is None:
- raise Exception(f'Element: {repr(element_node)} not found')
-
- async def perform_click(click_func):
- """Performs the actual click, handling both download
- and navigation scenarios."""
- if self.config.save_downloads_path:
- try:
- # Try short-timeout expect_download to detect a file download has been been triggered
- async with page.expect_download(timeout=5000) as download_info:
- await click_func()
- download = await download_info.value
- # Determine file path
- suggested_filename = download.suggested_filename
- unique_filename = await self._get_unique_filename(self.config.save_downloads_path, suggested_filename)
- download_path = os.path.join(self.config.save_downloads_path, unique_filename)
- await download.save_as(download_path)
- logger.debug(f'⬇️ Download triggered. Saved file to: {download_path}')
- return download_path
- except TimeoutError:
- # If no download is triggered, treat as normal click
- logger.debug('No download triggered within timeout. Checking navigation...')
- await page.wait_for_load_state()
- await self._check_and_handle_navigation(page)
- else:
- # Standard click logic if no download is expected
- await click_func()
- await page.wait_for_load_state()
- await self._check_and_handle_navigation(page)
-
- try:
- return await perform_click(lambda: element_handle.click(timeout=1500))
- except URLNotAllowedError as e:
- raise e
- except Exception:
- try:
- return await perform_click(lambda: page.evaluate('(el) => el.click()', element_handle))
- except URLNotAllowedError as e:
- raise e
- except Exception as e:
- raise Exception(f'Failed to click element: {str(e)}')
-
- except URLNotAllowedError as e:
- raise e
- except Exception as e:
- raise Exception(f'Failed to click element: {repr(element_node)}. Error: {str(e)}')
-
- @time_execution_async('--get_tabs_info')
- async def get_tabs_info(self) -> list[TabInfo]:
- """Get information about all tabs"""
- session = await self.get_session()
-
- tabs_info = []
- for page_id, page in enumerate(session.context.pages):
- try:
- tab_info = TabInfo(page_id=page_id, url=page.url, title=await asyncio.wait_for(page.title(), timeout=1))
- except TimeoutError:
- # page.title() can hang forever on tabs that are crashed/disappeared/about:blank
- # we dont want to try automating those tabs because they will hang the whole script
- logger.debug('⚠ Failed to get tab info for tab #%s: %s (ignoring)', page_id, page.url)
- tab_info = TabInfo(page_id=page_id, url='about:blank', title='ignore this tab and do not use it')
- tabs_info.append(tab_info)
-
- return tabs_info
-
- @time_execution_async('--switch_to_tab')
- async def switch_to_tab(self, page_id: int) -> None:
- """Switch to a specific tab by its page_id"""
- session = await self.get_session()
- pages = session.context.pages
-
- if page_id >= len(pages):
- raise BrowserError(f'No tab found with page_id: {page_id}')
-
- page = pages[page_id]
-
- # Check if the tab's URL is allowed before switching
- if not self._is_url_allowed(page.url):
- raise BrowserError(f'Cannot switch to tab with non-allowed URL: {page.url}')
-
- # Update target ID if using CDP
- if self.browser.config.cdp_url:
- targets = await self._get_cdp_targets()
- for target in targets:
- if target['url'] == page.url:
- self.state.target_id = target['targetId']
- break
-
- # Update both tab references - agent wants this tab, and it's now in the foreground
- self.agent_current_page = page
- self.human_current_page = page
-
- # Bring tab to front and wait for it to load
- await page.bring_to_front()
- await page.wait_for_load_state()
-
- # Set the viewport size for the tab
- await self.set_viewport_size(page)
-
- @time_execution_async('--create_new_tab')
- async def create_new_tab(self, url: str | None = None) -> None:
- """Create a new tab and optionally navigate to a URL"""
- if url and not self._is_url_allowed(url):
- raise BrowserError(f'Cannot create new tab with non-allowed URL: {url}')
-
- session = await self.get_session()
- new_page = await session.context.new_page()
-
- # Update both tab references - agent wants this tab, and it's now in the foreground
- self.agent_current_page = new_page
- self.human_current_page = new_page
-
- await new_page.wait_for_load_state()
-
- # Set the viewport size for the new tab
- await self.set_viewport_size(new_page)
-
- if url:
- await new_page.goto(url)
- await self._wait_for_page_and_frames_load(timeout_overwrite=1)
-
- # Get target ID for new page if using CDP
- if self.browser.config.cdp_url:
- targets = await self._get_cdp_targets()
- for target in targets:
- if target['url'] == new_page.url:
- self.state.target_id = target['targetId']
- break
-
- # region - Helper methods for easier access to the DOM
-
- async def get_selector_map(self) -> SelectorMap:
- session = await self.get_session()
- if session.cached_state is None:
- return {}
- return session.cached_state.selector_map
-
- 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])
- return element_handle
-
- async def get_dom_element_by_index(self, index: int) -> DOMElementNode:
- selector_map = await self.get_selector_map()
- return selector_map[index]
-
- async def save_cookies(self):
- """Save current cookies to file"""
- if self.session and self.session.context and self.config.cookies_file:
- try:
- cookies = await self.session.context.cookies()
- logger.debug(f'🍪 Saving {len(cookies)} cookies to {self.config.cookies_file}')
-
- # Check if the path is a directory and create it if necessary
- dirname = os.path.dirname(self.config.cookies_file)
- if dirname:
- os.makedirs(dirname, exist_ok=True)
-
- async with await anyio.open_file(self.config.cookies_file, 'w') as f:
- await f.write(json.dumps(cookies))
- except Exception as e:
- logger.warning(f'❌ Failed to save cookies: {str(e)}')
-
- async def is_file_uploader(self, element_node: DOMElementNode, max_depth: int = 3, current_depth: int = 0) -> bool:
- """Check if element or its children are file uploaders"""
- if current_depth > max_depth:
- return False
-
- # Check current element
- is_uploader = False
-
- if not isinstance(element_node, DOMElementNode):
- return False
-
- # Check for file input attributes
- if element_node.tag_name == 'input':
- is_uploader = element_node.attributes.get('type') == 'file' or element_node.attributes.get('accept') is not None
-
- if is_uploader:
- return True
-
- # Recursively check children
- if element_node.children and current_depth < max_depth:
- for child in element_node.children:
- if isinstance(child, DOMElementNode):
- if await self.is_file_uploader(child, max_depth, current_depth + 1):
- return True
-
- return False
-
- async def get_scroll_info(self, page: Page) -> tuple[int, int]:
- """Get scroll position information for the current page."""
- scroll_y = await page.evaluate('window.scrollY')
- viewport_height = await page.evaluate('window.innerHeight')
- total_height = await page.evaluate('document.documentElement.scrollHeight')
- pixels_above = scroll_y
- pixels_below = total_height - (scroll_y + viewport_height)
- return pixels_above, pixels_below
-
- async def reset_context(self):
- """Reset the browser session
- Call this when you don't want to kill the context but just kill the state
- """
- # close all tabs and clear cached state
- session = await self.get_session()
-
- pages = session.context.pages
- for page in pages:
- await page.close()
-
- session.cached_state = None
- self.state.target_id = None
-
- async def _get_unique_filename(self, directory, filename):
- """Generate a unique filename by appending (1), (2), etc., if a file already exists."""
- base, ext = os.path.splitext(filename)
- counter = 1
- new_filename = filename
- while os.path.exists(os.path.join(directory, new_filename)):
- new_filename = f'{base} ({counter}){ext}'
- counter += 1
- return new_filename
-
- async def _get_cdp_targets(self) -> list[dict]:
- """Get all CDP targets directly using CDP protocol"""
- if not self.browser.config.cdp_url or not self.session:
- return []
-
- try:
- pages = self.session.context.pages
- if not pages:
- return []
-
- cdp_session = await pages[0].context.new_cdp_session(pages[0])
- result = await cdp_session.send('Target.getTargets')
- await cdp_session.detach()
- return result.get('targetInfos', [])
- except Exception as e:
- logger.debug(f'Failed to get CDP targets: {e}')
- return []
-
- async def _resize_window(self, context: PlaywrightBrowserContext) -> None:
- """Resize the browser window to match the configured size"""
- try:
- if not context.pages:
- return
-
- page = context.pages[0]
- window_size = {'width': self.config.window_width, 'height': self.config.window_height}
-
- # First, set the viewport size
- await self.set_viewport_size(page)
-
- # Then, try to set the actual window size using CDP
- try:
- cdp_session = await context.new_cdp_session(page)
-
- # Get the window ID
- window_id_result = await cdp_session.send('Browser.getWindowForTarget')
-
- # Set the window bounds
- await cdp_session.send(
- 'Browser.setWindowBounds',
- {
- 'windowId': window_id_result['windowId'],
- 'bounds': {
- 'width': window_size['width'],
- 'height': window_size['height'] + BROWSER_NAVBAR_HEIGHT, # Add height for browser chrome
- 'windowState': 'normal', # Ensure window is not minimized/maximized
- },
- },
- )
-
- await cdp_session.detach()
- logger.debug(f'Set window size to {window_size["width"]}x{window_size["height"] + BROWSER_NAVBAR_HEIGHT}')
- except Exception as e:
- logger.debug(f'CDP window resize failed: {e}')
-
- # Fallback to using JavaScript
- try:
- await page.evaluate(
- """
- (width, height) => {
- window.resizeTo(width, height);
- }
- """,
- window_size['width'],
- window_size['height'] + BROWSER_NAVBAR_HEIGHT,
- )
- logger.debug(
- f'Used JavaScript to set window size to {window_size["width"]}x{window_size["height"] + BROWSER_NAVBAR_HEIGHT}'
- )
- except Exception as e:
- logger.debug(f'JavaScript window resize failed: {e}')
-
- logger.debug(f'Attempted to resize window to {window_size["width"]}x{window_size["height"]}')
- except Exception as e:
- logger.debug(f'Failed to resize browser window: {e}')
- # Non-critical error, continue execution
-
- async def wait_for_element(self, selector: str, timeout: float) -> None:
- """
- Waits for an element matching the given CSS selector to become visible.
-
- Args:
- selector (str): The CSS selector of the element.
- timeout (float): The maximum time to wait for the element to be visible (in milliseconds).
-
- Raises:
- TimeoutError: If the element does not become visible within the specified timeout.
- """
- page = await self.get_agent_current_page()
- await page.wait_for_selector(selector, state='visible', timeout=timeout)
+# Re-export compatibility classes for backward compatibility
diff --git a/browser_use/browser/dolphin_service.py b/browser_use/browser/dolphin_service.py
deleted file mode 100644
index b90585c4b..000000000
--- a/browser_use/browser/dolphin_service.py
+++ /dev/null
@@ -1,348 +0,0 @@
-import logging
-import os
-
-import aiohttp
-from playwright.async_api import Page, async_playwright
-
-from browser_use.browser.service import Browser
-from browser_use.browser.views import BrowserState, TabInfo
-
-logger = logging.getLogger(__name__)
-
-
-class DolphinBrowser(Browser):
- """A class for managing Dolphin Anty browser sessions using Playwright"""
-
- def __init__(self, headless: bool = False, keep_open: bool = False):
- """
- Initialize the DolphinBrowser instance.
-
- Args:
- headless (bool): Run browser in headless mode (default: False).
- keep_open (bool): Keep browser open after finishing tasks (default: False).
- """
- # Retrieve environment variables for API connection
- self.api_token = os.getenv('DOLPHIN_API_TOKEN')
- self.api_url = os.getenv('DOLPHIN_API_URL', 'http://localhost:3001/v1.0')
- self.profile_id = os.getenv('DOLPHIN_PROFILE_ID')
-
- # Initialize internal attributes
- self.playwright = None
- self.browser = None
- self.context = None
- self.page = None
- self.headless = headless
- self.keep_open = keep_open
- self._pages: list[Page] = [] # List to store open pages
- self.session = None
- self.cached_state = None
-
- async def get_current_page(self) -> Page:
- """
- Get the currently active page.
-
- Raises:
- Exception: If no active page is available.
- """
- if not self.page:
- raise Exception('No active page. Browser might not be connected.')
- return self.page
-
- async def create_new_tab(self, url: str | None = None) -> None:
- """
- Create a new tab and optionally navigate to a given URL.
-
- Args:
- url (str, optional): URL to navigate to after creating the tab. Defaults to None.
-
- Raises:
- Exception: If browser context is not initialized or navigation fails.
- """
- if not self.context:
- raise Exception('Browser context not initialized')
-
- # Create new page (tab) in the current browser context
- new_page = await self.context.new_page()
- self._pages.append(new_page)
- self.page = new_page # Set as current page
-
- if url:
- try:
- # Navigate to the URL and wait for the page to load
- await new_page.goto(url, wait_until='networkidle')
- await self.wait_for_page_load()
- except Exception as e:
- logger.error(f'Failed to navigate to URL {url}: {str(e)}')
- raise
-
- async def switch_to_tab(self, page_id: int) -> None:
- """
- Switch to a specific tab by its page ID.
-
- Args:
- page_id (int): The index of the tab to switch to.
-
- Raises:
- Exception: If the tab index is out of range or no tabs are available.
- """
- if not self._pages:
- raise Exception('No tabs available')
-
- # Handle negative indices (e.g., -1 for last tab)
- if page_id < 0:
- page_id = len(self._pages) + page_id
-
- if page_id >= len(self._pages) or page_id < 0:
- raise Exception(f'Tab index {page_id} out of range')
-
- # Set the current page to the selected tab
- self.page = self._pages[page_id]
- await self.page.bring_to_front() # Bring tab to the front
- await self.wait_for_page_load()
-
- async def get_tabs_info(self) -> list[TabInfo]:
- """
- Get information about all open tabs.
-
- Returns:
- list: A list of TabInfo objects containing details about each tab.
- """
- tabs_info = []
- for idx, page in enumerate(self._pages):
- tab_info = TabInfo(
- page_id=idx,
- url=page.url,
- title=await page.title(), # Fetch the title of the page
- )
- tabs_info.append(tab_info)
- return tabs_info
-
- async def wait_for_page_load(self, timeout: int = 30000):
- """
- Wait for the page to load completely.
-
- Args:
- timeout (int): Maximum time to wait for page load in milliseconds (default: 30000ms).
-
- Raises:
- Exception: If the page fails to load within the specified timeout.
- """
- if self.page:
- try:
- await self.page.wait_for_load_state('networkidle', timeout=timeout)
- except Exception as e:
- logger.warning(f'Wait for page load timeout: {str(e)}')
-
- async def get_session(self):
- """
- Get the current session.
-
- Returns:
- DolphinBrowser: The current DolphinBrowser instance.
-
- Raises:
- Exception: If the browser is not connected.
- """
- if not self.browser:
- raise Exception('Browser not connected. Call connect() first.')
- self.session = self
- return self
-
- async def authenticate(self):
- """
- Authenticate with Dolphin Anty API using the API token.
-
- Raises:
- Exception: If authentication fails.
- """
- async with aiohttp.ClientSession() as session:
- auth_url = f'{self.api_url}/auth/login-with-token'
- auth_data = {'token': self.api_token}
- async with session.post(auth_url, json=auth_data) as response:
- if not response.ok:
- raise Exception(f'Failed to authenticate with Dolphin Anty: {await response.text()}')
- return await response.json()
-
- async def get_browser_profiles(self):
- """
- Get a list of available browser profiles from Dolphin Anty.
-
- Returns:
- list: A list of browser profiles.
-
- Raises:
- Exception: If fetching the browser profiles fails.
- """
- # Authenticate before fetching profiles
- await self.authenticate()
-
- async with aiohttp.ClientSession() as session:
- headers = {'Authorization': f'Bearer {self.api_token}'}
- async with session.get(f'{self.api_url}/browser_profiles', headers=headers) as response:
- if not response.ok:
- raise Exception(f'Failed to get browser profiles: {await response.text()}')
- data = await response.json()
- return data.get('data', []) # Return the profiles array from the response
-
- async def start_profile(self, profile_id: str | None = None, headless: bool = False) -> dict:
- """
- Start a browser profile on Dolphin Anty.
-
- Args:
- profile_id (str, optional): Profile ID to start (defaults to the one set in the environment).
- headless (bool): Run browser in headless mode (default: False).
-
- Returns:
- dict: Information about the started profile.
-
- Raises:
- ValueError: If no profile ID is provided and no default is set.
- Exception: If starting the profile fails.
- """
- # Authenticate before starting the profile
- await self.authenticate()
-
- profile_id = profile_id or self.profile_id
- if not profile_id:
- raise ValueError('No profile ID provided')
-
- url = f'{self.api_url}/browser_profiles/{profile_id}/start'
- params = {'automation': 1}
- if headless:
- params['headless'] = 1
-
- async with aiohttp.ClientSession() as session:
- async with session.get(url, params=params) as response:
- if not response.ok:
- raise Exception(f'Failed to start profile: {await response.text()}')
- return await response.json()
-
- async def stop_profile(self, profile_id: str | None = None):
- """
- Stop a browser profile on Dolphin Anty.
-
- Args:
- profile_id (str, optional): Profile ID to stop (defaults to the one set in the environment).
-
- Returns:
- dict: Information about the stopped profile.
-
- Raises:
- ValueError: If no profile ID is provided and no default is set.
- """
- # Authenticate before stopping the profile
- await self.authenticate()
-
- profile_id = profile_id or self.profile_id
- if not profile_id:
- raise ValueError('No profile ID provided')
-
- url = f'{self.api_url}/browser_profiles/{profile_id}/stop'
- async with aiohttp.ClientSession() as session:
- async with session.get(url) as response:
- return await response.json()
-
- async def connect(self, profile_id: str | None = None):
- """
- Connect to a running browser profile using Playwright.
-
- Args:
- profile_id (str, optional): Profile ID to connect to (defaults to the one set in the environment).
-
- Returns:
- PlaywrightBrowser: The connected browser instance.
-
- Raises:
- Exception: If authentication or profile connection fails.
- """
- # Authenticate before connecting to the profile
- await self.authenticate()
-
- # Start the browser profile
- profile_data = await self.start_profile(profile_id)
-
- if not profile_data.get('success'):
- raise Exception(f'Failed to start profile: {profile_data}')
-
- automation = profile_data['automation']
- port = automation['port']
- ws_endpoint = automation['wsEndpoint']
- ws_url = f'ws://127.0.0.1:{port}{ws_endpoint}'
-
- # Use Playwright to connect to the browser's WebSocket endpoint
- self.playwright = await async_playwright().start()
- self.browser = await self.playwright.chromium.connect_over_cdp(ws_url)
-
- # Get or create a browser context and page
- contexts = self.browser.contexts
- self.context = contexts[0] if contexts else await self.browser.new_context()
- pages = self.context.pages
- self.page = pages[0] if pages else await self.context.new_page()
-
- self._pages = [self.page] # Initialize pages list with the first page
-
- return self.browser
-
- async def close(self, force: bool = False):
- """
- Close the browser connection and clean up resources.
-
- Args:
- force (bool): If True, forcefully stop the associated profile (default: False).
- """
- try:
- # Close all open pages
- if self._pages:
- for page in self._pages:
- try:
- await page.close()
- except BaseException:
- pass
- self._pages = []
-
- # Close the browser and Playwright instance
- if self.browser:
- await self.browser.close()
-
- if self.playwright:
- await self.playwright.stop()
-
- if force:
- await self.stop_profile() # Force stop the profile
- except Exception as e:
- logger.error(f'Error during browser cleanup: {str(e)}')
-
- async def get_current_state(self) -> BrowserState:
- """
- Get the current state of the browser (URL, content, viewport size, tabs).
-
- Returns:
- BrowserState: The current state of the browser.
-
- Raises:
- Exception: If no active page is available.
- """
- if not self.page:
- raise Exception('No active page')
-
- # Get page content and viewport size
- content = await self.page.content()
- viewport_size = await self.page.viewport_size()
-
- # Create and return the current browser state
- state = BrowserState(
- url=self.page.url,
- content=content,
- viewport_height=viewport_size['height'] if viewport_size else 0,
- viewport_width=viewport_size['width'] if viewport_size else 0,
- tabs=await self.get_tabs_info(),
- )
-
- # Cache and return the state
- self.cached_state = state
- return state
-
- def __del__(self):
- """Clean up resources when the DolphinBrowser instance is deleted."""
- # No need to handle session cleanup as we're using self as session
- pass
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
new file mode 100644
index 000000000..73b2712fb
--- /dev/null
+++ b/browser_use/browser/session.py
@@ -0,0 +1,608 @@
+from __future__ import annotations
+
+import json
+import logging
+import os
+from functools import wraps
+from pathlib import Path
+from typing import Any, Self
+
+import psutil
+from playwright.async_api import Browser as PlaywrightBrowser
+from playwright.async_api import BrowserContext as PlaywrightBrowserContext
+from playwright.async_api import Page, Playwright, async_playwright
+from pydantic import BaseModel, ConfigDict, Field, InstanceOf, model_validator
+
+from browser_use.browser.types import BrowserProfile
+
+# Check if running in Docker
+IN_DOCKER = os.environ.get('IN_DOCKER', 'false').lower()[0] in 'ty1'
+
+logger = logging.getLogger('browser_use.browser.session')
+
+
+def truncate_url(s: str, max_len: int | None = None) -> str:
+ """Truncate/pretty-print a URL with a maximum length, removing the protocol and www. prefix"""
+ s = s.replace('https://', '').replace('http://', '').replace('www.', '')
+ if max_len is not None and len(s) > max_len:
+ return s[:max_len] + '…'
+ return s
+
+
+def require_initialization(func):
+ """decorator for BrowserSession methods to require the BrowserSession be already active"""
+
+ @wraps(func)
+ def wrapper(self, *args, **kwargs):
+ if not self.initialized:
+ raise RuntimeError('BrowserSession(...).start() must be called first to launch or connect to the browser')
+ return func(self, *args, **kwargs)
+
+ return wrapper
+
+
+DEFAULT_BROWSER_PROFILE = BrowserProfile()
+
+
+class BrowserSession(BaseModel):
+ """
+ Represents an active browser session with a running browser process somewhere.
+
+ Chromium flags should be passed via extra_launch_args.
+ Extra Playwright launch options (e.g., handle_sigterm, handle_sigint) can be passed as kwargs to BrowserSession and will be forwarded to the launch() call.
+ """
+
+ model_config = ConfigDict(
+ extra='allow', validate_assignment=False, revalidate_instances='always', frozen=False, arbitrary_types_allowed=True
+ )
+ # this class accepts arbitrary extra **kwargs in init because of the extra='allow' pydantic option
+ # they are saved on the model, then applied to self.browser_profile via .apply_session_overrides_to_profile()
+
+ # template profile for the BrowserSession, will be copied at init/validation time, and overrides applied to the copy
+ browser_profile: InstanceOf[BrowserProfile] = Field(
+ default=DEFAULT_BROWSER_PROFILE, description='BrowserProfile() instance containing config for the BrowserSession'
+ )
+
+ # runtime state: connection and process handles
+ wss_url: str | None = Field(
+ default=None,
+ description='WSS URL of the node.js playwright browser server to connect to, outputted by (await chromium.launchServer()).wsEndpoint()',
+ )
+ cdp_url: str | None = Field(
+ default=None,
+ description='CDP URL of the browser to connect to, e.g. http://localhost:9222 or ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4',
+ )
+ chrome_process: psutil.Process | None = Field(
+ default=None, description='psutil Process object for the running chrome process to connect to (optional)'
+ )
+ playwright: Playwright | None = Field(
+ default=None, description='Playwright library object returned by (playwright or patchright).async_playwright().start()'
+ )
+ browser: InstanceOf[PlaywrightBrowser] | None = Field(default=None, description='playwright Browser object to use (optional)')
+ browser_context: InstanceOf[PlaywrightBrowserContext] | None = Field(
+ default=None, description='playwright BrowserContext object to use (optional)'
+ )
+ initialized: bool = Field(
+ default=False, description='Skip BrowserSession launch/connection setup entirely if True (not recommended)'
+ )
+
+ # runtime state: internally tracked attrs updated by BrowserSession class methods
+ agent_current_page: InstanceOf[Page] | None = Field(default=None, description='Foreground Page that the agent is focused on')
+ human_current_page: InstanceOf[Page] | None = Field(default=None, description='Foreground Page that the human is focused on')
+
+ def __getattr__(self, key: str) -> Any:
+ # fall back to getting attributes from BrowserProfile when not found on BrowserSession
+ return getattr(self.browser_profile, key)
+
+ @model_validator(mode='after')
+ def apply_session_overrides_to_profile(self) -> Self:
+ session_own_fields = type(self).model_fields.keys()
+ overrides = self.model_dump(exclude=session_own_fields)
+ self.browser_profile = self.browser_profile.model_copy(update=overrides)
+ return self
+
+ async def start(self) -> Self:
+ # unlock the user data dir for first-run initialization
+ assert isinstance(self.browser_profile, BrowserProfile)
+ self.browser_profile.prepare_user_data_dir()
+ self.browser_profile.detect_display_configuration()
+
+ # setup playwright, Browser, and BrowserContext objects
+ await self.setup_playwright()
+ await self.setup_browser_connection()
+ await self.setup_browser_context()
+ assert self.browser_context
+
+ # resize the existing pages and set up foreground tab detection
+ await self.setup_viewport_sizing()
+ await self.setup_foreground_tab_detection()
+
+ self.initialized = True
+
+ return self
+
+ async def stop(self) -> None:
+ if not self.browser_profile.keep_alive:
+ logger.info('🛑 Shutting down browser...')
+ await self.browser_context.close()
+ await self.browser.close()
+
+ # kill the chrome subprocess if we were the ones that started it
+ if self.chrome_process:
+ self.chrome_process.terminate()
+
+ async def __aenter__(self) -> BrowserSession:
+ await self.start()
+ return self
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
+ await self.stop()
+
+ async def setup_playwright(self) -> None:
+ """Override to customize the set up of the playwright or patchright library object"""
+ self.playwright = self.playwright or await async_playwright().start()
+ return self.playwright
+
+ async def setup_browser_connection(self) -> None:
+ """Override to customize the set up of the connection to an existing browser"""
+
+ # if process is provided, calcuclate its CDP URL by looking for --remote-debugging-port=... in the launch args
+ if self.chrome_process:
+ assert isinstance(self.chrome_process, psutil.Process) and self.chrome_process.is_running(), (
+ 'Chrome process is not running'
+ )
+ args = self.chrome_process.cmdline()
+ debug_port = next((arg for arg in args if arg.startswith('--remote-debugging-port=')), '').split('=')[-1].strip()
+ assert debug_port, (
+ f'Could not connect because could not find --remote-debugging-port=... in chrome launch args: pid={self.chrome_process.pid} {self.chrome_process.cmdline()}'
+ )
+ # we could automatically relaunch the browser process with that arg added here, but they may have tabs open they dont want to lose
+ self.cdp_url = self.cdp_url or f'http://localhost:{debug_port}/'
+ logger.info(f'🌎 Connecting to existing chromium process: pid={self.chrome_process.pid} on {self.cdp_url}')
+
+ if self.wss_url:
+ logger.info(f'🌎 Connecting to remote chromium playwright node.js server over WSS: {self.wss_url}')
+ self.browser = self.browser or await self.playwright.chromium.connect(
+ self.wss_url,
+ **self.browser_profile.kwargs_for_connect().model_dump(),
+ )
+ # dont default to closing the browser when the BrowserSession is over if we connect by WSS
+ if self.browser_profile.keep_alive is None:
+ self.browser_profile.keep_alive = True
+ elif self.cdp_url:
+ logger.info(f'🌎 Connecting to remote chromium browser over CDP: {self.cdp_url}')
+ self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(
+ self.cdp_url,
+ **self.browser_profile.kwargs_for_connect().model_dump(),
+ )
+ # dont default to closing the browser when the BrowserSession is over if we connect by CDP
+ if self.browser_profile.keep_alive is None:
+ self.browser_profile.keep_alive = True
+
+ # self.browser may still be None at this point if we have no config implying we should connect to an existing browser
+ # self.setup_browser_context() will be called next and if it finds self.browser is None, it will
+ # launch a new browser+context all in one go using launch_persistent_context()
+
+ return self.browser
+
+ async def setup_browser_context(self) -> None:
+ # if we have a browser_context but no browser, use the browser from the context
+ if self.browser_context:
+ logger.info(f'🌎 Using existing user-provided browser_context and browser: {self.browser_context}')
+ self.browser = self.browser or self.browser_context.browser
+ # dont default to closing the browser when the BrowserSession is over if we are passed an external browser
+ if self.browser_profile.keep_alive is None:
+ self.browser_profile.keep_alive = True
+
+ current_process = psutil.Process(os.getpid())
+ child_pids_before_launch = {child.pid for child in current_process.children(recursive=True)}
+
+ # if we have a browser object but no browser_context, use the first context discovered or make a new one
+ if self.browser and not self.browser_context:
+ if self.browser.contexts:
+ self.browser_context = self.browser.contexts[0]
+ logger.info(f'🌎 Using first browser_context available in user-provided browser: {self.browser_context}')
+ else:
+ self.browser_context = await self.browser.new_context(
+ **self.browser_profile.kwargs_for_new_context().model_dump()
+ )
+ storage_info = (
+ f' + loaded storage_state={len(self.browser_profile.storage_state.cookies) if self.browser_profile.storage_state else 0} cookies'
+ if self.browser_profile.storage_state
+ else ''
+ )
+ logger.info(f'🌎 Created new empty browser_context in existing browser{storage_info}: {self.browser_context}')
+
+ # if we still have no browser_context by now, launch a new local one using launch_persistent_context()
+ if not self.browser_context:
+ logger.info(f'🌎 Launching local playwright chromium context with user_data_dir={self.browser_profile.user_data_dir}')
+ self.browser_context = await self.playwright.chromium.launch_persistent_context(
+ **self.browser_profile.kwargs_for_launch_persistent_context().model_dump()
+ )
+ self.browser = self.browser_context.browser
+ # ^ this is unfortunately = None ^ playwright does not give us a browser object when we use launch_persistent_context()
+
+ # Detect any new child chrome processes that we might have launched above
+ child_pids_after_launch = {child.pid for child in current_process.children(recursive=True)}
+ new_child_pids = child_pids_after_launch - child_pids_before_launch
+ new_child_procs = [psutil.Process(pid) for pid in new_child_pids]
+ new_chrome_procs = [proc for proc in new_child_procs if 'Helper' not in proc.name() and proc.status() == 'running']
+ if new_chrome_procs and not self.chrome_process:
+ self.chrome_process = new_chrome_procs[0]
+ logger.debug(f' ↳ Spawned chrome subprocess: pid={self.chrome_process.pid} {" ".join(self.chrome_process.cmdline())}')
+ # default to closing the browser ourselves when the BrowserSession is over if we launched it ourselves
+ if self.browser_profile.keep_alive is None:
+ self.browser_profile.keep_alive = False
+
+ if self.browser:
+ assert self.browser.is_connected(), 'Browser is not connected, did the browser process crash or get killed?'
+ assert self.browser_context, f'BrowserContext {self.browser_context} is not set up'
+
+ return self.browser_context
+
+ async def setup_foreground_tab_detection(self) -> None:
+ # Uses a combination of:
+ # - visibilitychange events
+ # - window focus/blur events
+ # - pointermove events
+
+ # This multi-method approach provides more reliable detection across browsers.
+
+ # TODO: pester the playwright team to add a new event that fires when a headful tab is focused.
+ # OR implement a browser-use chrome extension that acts as a bridge to the chrome.tabs API.
+
+ # - https://github.com/microsoft/playwright/issues/1290
+ # - https://github.com/microsoft/playwright/issues/2286
+ # - https://github.com/microsoft/playwright/issues/3570
+ # - https://github.com/microsoft/playwright/issues/13989
+
+ # set up / detect foreground page
+ pages = self.browser_context.pages
+ foreground_page = None
+ if pages:
+ foreground_page = pages[0]
+ logger.debug(f'👁️ Found {len(pages)} existing pages in browser, agent will start with: {foreground_page.url}')
+ else:
+ foreground_page = await self.browser_context.new_page()
+ pages = [foreground_page]
+ logger.debug('📄 Opened new page in empty fresh browser context...')
+
+ self.agent_current_page = self.agent_current_page or foreground_page
+ self.human_current_page = self.human_current_page or foreground_page
+
+ def _BrowserUseonTabVisibilityChange(source):
+ new_page = source['page']
+
+ # Update human foreground tab state
+ old_foreground = self.human_current_page
+ self.human_current_page = new_page
+
+ # Log before and after for debugging
+ if old_foreground.url != new_page.url:
+ logger.info(
+ f'👁️ Foregound tab changed by human from {truncate_url(old_foreground.url, 22) if old_foreground else "about:blank"} '
+ f'➡️ {truncate_url(new_page.url, 22)} '
+ f'(agent will stay on {truncate_url(self.agent_current_page.url, 22)})'
+ )
+ return new_page.url
+
+ await self.browser_context.expose_binding('_BrowserUseonTabVisibilityChange', _BrowserUseonTabVisibilityChange)
+ update_tab_focus_script = """
+ // --- Method 1: visibilitychange event (unfortunately *all* tabs are always marked visible by playwright, usually does not fire) ---
+ document.addEventListener('visibilitychange', async () => {
+ if (document.visibilityState === 'visible') {
+ await window._BrowserUseonTabVisibilityChange({ source: 'visibilitychange', url: document.location.href });
+ console.log('BrowserUse Foreground tab change event fired', document.location.href);
+ }
+ });
+
+ // --- Method 2: focus/blur events, most reliable method for headful browsers ---
+ window.addEventListener('focus', async () => {
+ await window._BrowserUseonTabVisibilityChange({ source: 'focus', url: document.location.href });
+ console.log('BrowserUse Foreground tab change event fired', document.location.href);
+ });
+
+ // --- Method 3: pointermove events (may be fired by agent if we implement AI hover movements) ---
+ // Use a throttled handler to avoid excessive calls
+ // let lastMove = 0;
+ // window.addEventListener('pointermove', async () => {
+ // const now = Date.now();
+ // if (now - lastMove > 1000) { // Throttle to once per second
+ // lastMove = now;
+ // await window._BrowserUseonTabVisibilityChange({ source: 'pointermove', url: document.location.href });
+ // console.log('BrowserUse Foreground tab change event fired', document.location.href);
+ // }
+ // });
+ """
+ await self.browser_context.add_init_script(update_tab_focus_script)
+
+ # set the user agent to the one we want
+ # Set up visibility listeners for all existing tabs
+ for page in self.browser_context.pages:
+ if not page.url.startswith('chrome-extension://') and not page.url.startswith('chrome://') and not page.is_closed():
+ await page.evaluate(update_tab_focus_script)
+ # logger.debug(f'👁️ Added visibility listener to existing tab: {page.url}')
+
+ async def setup_viewport_sizing(self) -> None:
+ """Resize any existing page viewports to match the configured size"""
+
+ if not self.browser_context.pages:
+ return
+
+ # First, set the viewport size on any existing pages
+ use_viewport = (not self.browser_profile.no_viewport) and self.viewport
+ if use_viewport:
+ logger.debug(
+ '👁️ Resizing existing pages '
+ f'headless={self.browser_profile.headless}'
+ f'use_viewport={use_viewport} '
+ f'screen={self.browser_profile.screen["width"] if self.browser_profile.screen else "0"}x{self.browser_profile.screen["height"] if self.browser_profile.screen else "0"} '
+ f'window={self.browser_profile.window_size["width"] if self.browser_profile.window_size else "0"}x{self.browser_profile.window_size["height"] if self.browser_profile.window_size else "0"} '
+ f'viewport={self.browser_profile.viewport["width"] if self.browser_profile.viewport else "0"}x{self.browser_profile.viewport["height"] if self.browser_profile.viewport else "0"} '
+ )
+ for page in self.browser_context.pages:
+ await page.set_viewport_size(self.browser_profile.viewport)
+
+ # --- Tab management ---
+ @property
+ def tabs(self) -> list[Page]:
+ if not self.browser_context:
+ return []
+ return list(self.browser_context.pages)
+
+ @require_initialization
+ async def new_tab(self, url: str | None = None) -> Page:
+ page = await self.browser_context.new_page()
+ if url:
+ await page.goto(url)
+ self.agent_current_page = page
+ self.human_current_page = page
+ return page
+
+ @require_initialization
+ async def switch_tab(self, tab_index: int) -> Page:
+ pages = self.tabs
+ if not pages or tab_index >= len(pages):
+ raise IndexError('Tab index out of range')
+ page = pages[tab_index]
+ self.agent_current_page = page
+ self.human_current_page = page
+ return page
+
+ @require_initialization
+ async def wait_for_element(self, selector: str, timeout: int = 10000) -> None:
+ await self.agent_current_page.wait_for_selector(selector, timeout=timeout)
+
+ @require_initialization
+ async def get_current_page(self) -> Page | None:
+ """Get the current page. Used by controller/agent."""
+ return self.agent_current_page
+
+ @require_initialization
+ async def go_back(self) -> None:
+ """Navigate back. Used by controller/agent."""
+ if self.agent_current_page:
+ await self.agent_current_page.go_back()
+
+ @require_initialization
+ async def get_selector_map(self) -> dict[int, Any]:
+ """Get selector map for the current page."""
+ if not self.agent_current_page:
+ return {}
+
+ from browser_use.dom.service import DomService
+
+ dom_service = DomService(self.agent_current_page)
+ dom_state = await dom_service.get_clickable_elements(
+ highlight_elements=self.browser_profile.highlight_elements, viewport_expansion=self.browser_profile.viewport_expansion
+ )
+ return dom_state.selector_map
+
+ @require_initialization
+ async def remove_highlights(self):
+ """
+ Removes all highlight overlays and labels created by the highlightElement function.
+ Handles cases where the page might be closed or inaccessible.
+ """
+ try:
+ page = await self.get_agent_current_page()
+ 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:
+ logger.debug(f'⚠ Failed to remove highlights (this is usually ok): {str(e)}')
+ # Don't raise the error since this is not critical functionality
+ pass
+
+ @require_initialization
+ async def get_dom_element_by_index(self, index: int) -> Any | None:
+ """Get DOM element by index."""
+ selector_map = await self.get_selector_map()
+ return selector_map.get(index)
+
+ @require_initialization
+ async def is_file_uploader(self, element: Any) -> bool:
+ """Check if element is a file uploader."""
+ if not self.agent_current_page or not element:
+ return False
+
+ # Check if the element is an input with type=file
+ if element.tag_name.lower() == 'input' and element.attributes.get('type') == 'file':
+ return True
+
+ # Or if it has an ancestor that's an input with type=file
+ xpath = element.xpath
+ try:
+ file_inputs = await self.agent_current_page.query_selector_all('input[type="file"]')
+ for file_input in file_inputs:
+ if await file_input.is_visible():
+ return True
+ except Exception as e:
+ logging.warning(f'Error checking if element is file uploader: {e}')
+
+ return False
+
+ @require_initialization
+ async def _click_element_node(self, element: Any) -> str | None:
+ """
+ Click on a DOM element node.
+ Returns download path if a download was triggered, None otherwise.
+ """
+ if not self.agent_current_page or not element:
+ return None
+
+ if not hasattr(element, 'xpath') or not element.xpath:
+ logging.warning('Element has no xpath')
+ return None
+
+ try:
+ # Use the xpath to find the element
+ element_handle = await self.agent_current_page.query_selector_all(f'xpath={element.xpath}')
+ if not element_handle or len(element_handle) == 0:
+ logging.warning(f'Element not found with xpath: {element.xpath}')
+ return None
+
+ # Click the element
+ await element_handle[0].scroll_into_view_if_needed()
+ await element_handle[0].click()
+
+ # Check if a download was triggered
+ # This would require tracking downloads and returning the path
+ # For now, we'll return None as a placeholder
+ return None
+ except Exception as e:
+ logging.warning(f'Error clicking element: {e}')
+ return None
+
+ @require_initialization
+ async def _input_text_element_node(self, element: Any, text: str) -> None:
+ """Input text into an element node."""
+ if not self.agent_current_page or not element:
+ return
+
+ if not hasattr(element, 'xpath') or not element.xpath:
+ logging.warning('Element has no xpath')
+ return
+
+ try:
+ # Use the xpath to find the element
+ element_handle = await self.agent_current_page.query_selector_all(f'xpath={element.xpath}')
+ if not element_handle or len(element_handle) == 0:
+ logging.warning(f'Element not found with xpath: {element.xpath}')
+ return
+
+ # Clear existing text (if any) and input new text
+ await element_handle[0].click()
+ await element_handle[0].fill(text)
+ except Exception as e:
+ logging.warning(f'Error inputting text to element: {e}')
+ return
+
+ @require_initialization
+ async def close_tab(self, tab_index: int | None = None) -> None:
+ pages = self.tabs
+ if not pages:
+ return
+ if tab_index is None:
+ page = self.agent_current_page or pages[0]
+ else:
+ page = pages[tab_index]
+ await page.close()
+ # Update current page refs
+ remaining = self.tabs
+ if remaining:
+ self.agent_current_page = remaining[0]
+ self.human_current_page = remaining[0]
+ else:
+ self.agent_current_page = None
+ self.human_current_page = None
+
+ # --- Page navigation ---
+ @require_initialization
+ async def navigate(self, url: str) -> None:
+ if not self.agent_current_page:
+ await self.new_tab(url)
+ else:
+ await self.agent_current_page.goto(url)
+
+ @require_initialization
+ async def refresh(self) -> None:
+ if self.agent_current_page:
+ await self.agent_current_page.reload()
+
+ # --- State and info ---
+ @require_initialization
+ async def get_state(self) -> dict[str, Any]:
+ """Return a dict with basic session state info (for compatibility)."""
+ return {
+ 'current_url': self.agent_current_page.url if self.agent_current_page else None,
+ 'tabs': [p.url for p in self.tabs],
+ 'downloads_dir': str(self.browser_profile.downloads_dir),
+ 'uploads_dir': str(self.browser_profile.uploads_dir) if self.browser_profile.uploads_dir else None,
+ }
+
+ @require_initialization
+ async def take_screenshot(self, full_page: bool = False) -> bytes | None:
+ if self.agent_current_page:
+ return await self.agent_current_page.screenshot(full_page=full_page)
+ return None
+
+ @require_initialization
+ async def execute_javascript(self, script: str) -> Any:
+ if self.agent_current_page:
+ return await self.agent_current_page.evaluate(script)
+ return None
+
+ async def get_cookies(self) -> list[dict[str, Any]]:
+ if self.browser_context:
+ return await self.browser_context.cookies()
+ return []
+
+ async def save_cookies(self, path: Path | None = None) -> None:
+ """
+ Save cookies to the specified path or the default cookies_file in the downloads_dir.
+ """
+ if self.browser_context:
+ cookies = await self.browser_context.cookies()
+ out_path = path or self.browser_profile.cookies_file
+ if out_path:
+ # If out_path is not absolute, resolve relative to downloads_dir
+ out_path = Path(out_path)
+ if not out_path.is_absolute():
+ out_path = Path(self.browser_profile.downloads_dir) / out_path
+ out_path.parent.mkdir(parents=True, exist_ok=True)
+ out_path.write_text(json.dumps(cookies, indent=4)) # TODO: replace with anyio asyncio write
+
+ # --- Compatibility properties for old API ---
+ @property
+ def browser_pages(self) -> list[Page]:
+ return self.tabs
+
+ @property
+ def browser_extension_pages(self) -> list[Page]:
+ if not self.browser_context:
+ return []
+ return [p for p in self.browser_context.pages if p.url.startswith('chrome-extension://')]
+
+ @property
+ def saved_downloads(self) -> list[Path]:
+ """
+ Return a list of files in the downloads_dir.
+ """
+ return list(Path(self.browser_profile.downloads_dir).glob('*'))
diff --git a/browser_use/browser/types.py b/browser_use/browser/types.py
new file mode 100644
index 000000000..7fe9e6cdf
--- /dev/null
+++ b/browser_use/browser/types.py
@@ -0,0 +1,705 @@
+import os
+import sys
+from collections.abc import Iterable
+from enum import Enum
+from functools import cache
+from pathlib import Path
+from re import Pattern
+from typing import Annotated, Any, Self
+from urllib.parse import urlparse
+from venv import logger
+
+from playwright._impl._api_structures import (
+ ClientCertificate,
+ Geolocation,
+ HttpCredentials,
+ ProxySettings,
+ StorageState,
+ ViewportSize,
+)
+from pydantic import AfterValidator, BaseModel, ConfigDict, Field, model_validator
+from uuid_extensions import uuid7str
+
+# fix pydantic error on python 3.11
+# PydanticUserError: Please use `typing_extensions.TypedDict` instead of `typing.TypedDict` on Python < 3.12.
+# For further information visit https://errors.pydantic.dev/2.10/u/typed-dict-version
+if sys.version_info < (3, 12):
+ from typing_extensions import TypedDict
+
+ # convert new-style typing.TypedDict used by playwright to old-style typing_extensions.TypedDict used by pydantic
+ ClientCertificate = TypedDict('ClientCertificate', ClientCertificate.__annotations__, total=ClientCertificate.__total__)
+ Geolocation = TypedDict('Geolocation', Geolocation.__annotations__, total=Geolocation.__total__)
+ ProxySettings = TypedDict('ProxySettings', ProxySettings.__annotations__, total=ProxySettings.__total__)
+ ViewportSize = TypedDict('ViewportSize', ViewportSize.__annotations__, total=ViewportSize.__total__)
+ HttpCredentials = TypedDict('HttpCredentials', HttpCredentials.__annotations__, total=HttpCredentials.__total__)
+ StorageState = TypedDict('StorageState', StorageState.__annotations__, total=StorageState.__total__)
+
+IN_DOCKER = os.environ.get('IN_DOCKER', 'false').lower()[0] in 'ty1'
+CHROME_DEBUG_PORT = 9242 # use a non-default port to avoid conflicts with other tools / devs using 9222
+CHROME_DISABLED_COMPONENTS = [
+ # Playwright defaults: https://github.com/microsoft/playwright/blob/41008eeddd020e2dee1c540f7c0cdfa337e99637/packages/playwright-core/src/server/chromium/chromiumSwitches.ts#L76
+ # See https:#github.com/microsoft/playwright/pull/10380
+ 'AcceptCHFrame',
+ # See https:#github.com/microsoft/playwright/pull/10679
+ 'AutoExpandDetailsElement',
+ # See https:#github.com/microsoft/playwright/issues/14047
+ 'AvoidUnnecessaryBeforeUnloadCheckSync',
+ # See https:#github.com/microsoft/playwright/pull/12992
+ 'CertificateTransparencyComponentUpdater',
+ 'DestroyProfileOnBrowserClose',
+ # See https:#github.com/microsoft/playwright/pull/13854
+ 'DialMediaRouteProvider',
+ # Chromium is disabling manifest version 2. Allow testing it as long as Chromium can actually run it.
+ # Disabled in https:#chromium-review.googlesource.com/c/chromium/src/+/6265903.
+ 'ExtensionManifestV2Disabled',
+ 'GlobalMediaControls',
+ # See https:#github.com/microsoft/playwright/pull/27605
+ 'HttpsUpgrades',
+ 'ImprovedCookieControls',
+ 'LazyFrameLoading',
+ # Hides the Lens feature in the URL address bar. Its not working in unofficial builds.
+ 'LensOverlay',
+ # See https:#github.com/microsoft/playwright/pull/8162
+ 'MediaRouter',
+ # See https:#github.com/microsoft/playwright/issues/28023
+ 'PaintHolding',
+ # See https:#github.com/microsoft/playwright/issues/32230
+ 'ThirdPartyStoragePartitioning',
+ # See https://github.com/microsoft/playwright/issues/16126
+ 'Translate',
+ 'AutomationControlled',
+ # Added by us:
+ 'OptimizationHints',
+ 'ProcessPerSiteUpToMainFrameThreshold',
+ 'InterestFeedContentSuggestions',
+ 'CalculateNativeWinOcclusion', # chrome normally stops rendering tabs if they are not visible (occluded by a foreground window or other app)
+ # 'BackForwardCache', # agent does actually use back/forward navigation, but we can disable if we ever remove that
+ 'HeavyAdPrivacyMitigations',
+ 'PrivacySandboxSettings4',
+ 'AutofillServerCommunication',
+ 'CrashReporting',
+ 'OverscrollHistoryNavigation',
+ 'InfiniteSessionRestore',
+]
+
+CHROME_HEADLESS_ARGS = [
+ '--headless=new',
+]
+
+CHROME_DOCKER_ARGS = [
+ '--no-sandbox',
+ '--disable-gpu-sandbox',
+ '--disable-setuid-sandbox',
+ '--disable-dev-shm-usage',
+ '--no-xshm',
+]
+
+CHROME_DISABLE_SECURITY_ARGS = [
+ '--disable-web-security',
+ '--disable-site-isolation-trials',
+ '--disable-features=IsolateOrigins,site-per-process',
+ '--allow-running-insecure-content',
+ '--ignore-certificate-errors',
+ '--ignore-ssl-errors',
+ '--ignore-certificate-errors-spki-list',
+]
+
+CHROME_DETERMINISTIC_RENDERING_ARGS = [
+ '--deterministic-mode',
+ '--js-flags=--random-seed=1157259159',
+ '--force-device-scale-factor=1',
+ '--enable-webgl',
+ '--font-render-hinting=none',
+ '--force-color-profile=srgb',
+ '--disable-skia-runtime-opts',
+ '--disable-2d-canvas-clip-aa',
+]
+
+CHROME_DEFAULT_ARGS = [
+ # provided by playwright by default: https://github.com/microsoft/playwright/blob/41008eeddd020e2dee1c540f7c0cdfa337e99637/packages/playwright-core/src/server/chromium/chromiumSwitches.ts#L76
+ # we don't need to include them twice in our own config
+ '--disable-field-trial-config', # https://source.chromium.org/chromium/chromium/src/+/main:testing/variations/README.md
+ '--disable-background-networking',
+ '--disable-background-timer-throttling',
+ '--disable-backgrounding-occluded-windows',
+ '--disable-back-forward-cache', # Avoids surprises like main request not being intercepted during page.goBack().
+ '--disable-breakpad',
+ '--disable-client-side-phishing-detection',
+ '--disable-component-extensions-with-background-pages',
+ '--disable-component-update', # Avoids unneeded network activity after startup.
+ '--no-default-browser-check',
+ # '--disable-default-apps',
+ '--disable-dev-shm-usage',
+ # '--disable-extensions',
+ # '--disable-features=' + disabledFeatures(assistantMode).join(','),
+ '--allow-pre-commit-input',
+ '--disable-hang-monitor',
+ '--disable-ipc-flooding-protection',
+ '--disable-popup-blocking',
+ '--disable-prompt-on-repost',
+ '--disable-renderer-backgrounding',
+ '--force-color-profile=srgb',
+ '--metrics-recording-only',
+ '--no-first-run',
+ '--password-store=basic',
+ '--use-mock-keychain',
+ # // See https://chromium-review.googlesource.com/c/chromium/src/+/2436773
+ '--no-service-autorun',
+ '--export-tagged-pdf',
+ # // https://chromium-review.googlesource.com/c/chromium/src/+/4853540
+ '--disable-search-engine-choice-screen',
+ # // https://issues.chromium.org/41491762
+ '--unsafely-disable-devtools-self-xss-warnings',
+ '--enable-features=NetworkService,NetworkServiceInProcess',
+ # added by us:
+ '--test-type=gpu',
+ '--disable-sync',
+ '--allow-legacy-extension-manifests',
+ '--allow-pre-commit-input',
+ '--disable-blink-features=AutomationControlled',
+ '--install-autogenerated-theme=0,0,0',
+ '--hide-scrollbars',
+ '--log-level=2',
+ # '--enable-logging=stderr',
+ '--disable-focus-on-load',
+ '--disable-window-activation',
+ '--generate-pdf-document-outline',
+ '--no-pings',
+ '--ash-no-nudges',
+ '--disable-infobars',
+ '--simulate-outdated-no-au="Tue, 31 Dec 2099 23:59:59 GMT"',
+ '--hide-crash-restore-bubble',
+ '--suppress-message-center-popups',
+ '--disable-domain-reliability',
+ '--disable-datasaver-prompt',
+ '--disable-speech-synthesis-api',
+ '--disable-speech-api',
+ '--disable-print-preview',
+ '--safebrowsing-disable-auto-update',
+ '--disable-external-intent-requests',
+ '--disable-desktop-notifications',
+ '--noerrdialogs',
+ '--silent-debugger-extension-api',
+ f'--disable-features={",".join(CHROME_DISABLED_COMPONENTS)}',
+]
+
+
+@cache
+def get_display_size() -> ViewportSize | None:
+ # macOS
+ try:
+ from AppKit import NSScreen
+
+ screen = NSScreen.mainScreen().frame()
+ return ViewportSize(width=int(screen.size.width), height=int(screen.size.height))
+ except Exception:
+ pass
+
+ # Windows & Linux
+ try:
+ from screeninfo import get_monitors
+
+ monitors = get_monitors()
+ monitor = monitors[0]
+ return ViewportSize(width=int(monitor.width), height=int(monitor.height))
+ except Exception:
+ pass
+
+ return None
+
+
+def get_window_adjustments() -> tuple[int, int]:
+ """Returns recommended x, y offsets for window positioning"""
+
+ if sys.platform == 'darwin': # macOS
+ return -4, 24 # macOS has a small title bar, no border
+ elif sys.platform == 'win32': # Windows
+ return -8, 0 # Windows has a border on the left
+ else: # Linux
+ return 0, 0
+
+
+# ===== Validator functions =====
+
+BROWSERUSE_CONFIG_DIR = Path('~/.config/browseruse')
+BROWSERUSE_PROFILES_DIR = BROWSERUSE_CONFIG_DIR / 'profiles'
+
+
+def validate_url(url: str, schemes: Iterable[str] = ()) -> str:
+ """Validate URL format and optionally check for specific schemes."""
+ parsed_url = urlparse(url)
+ if not parsed_url.netloc:
+ raise ValueError(f'Invalid URL format: {url}')
+ if schemes and parsed_url.scheme and parsed_url.scheme.lower() not in schemes:
+ raise ValueError(f'URL has invalid scheme: {url} (expected one of {schemes})')
+ return url
+
+
+def validate_float_range(value: float, min_val: float, max_val: float) -> float:
+ """Validate that float is within specified range."""
+ if not min_val <= value <= max_val:
+ raise ValueError(f'Value {value} outside of range {min_val}-{max_val}')
+ return value
+
+
+def validate_cli_arg(arg: str) -> str:
+ """Validate that arg is a valid CLI argument."""
+ if not arg.startswith('--'):
+ raise ValueError(f'Invalid CLI argument: {arg} (should start with --, e.g. --some-key="some value here")')
+ return arg
+
+
+# ===== Enum definitions =====
+
+
+class ColorScheme(str, Enum):
+ LIGHT = 'light'
+ DARK = 'dark'
+ NO_PREFERENCE = 'no-preference'
+ NULL = 'null'
+
+
+class Contrast(str, Enum):
+ NO_PREFERENCE = 'no-preference'
+ MORE = 'more'
+ NULL = 'null'
+
+
+class ReducedMotion(str, Enum):
+ REDUCE = 'reduce'
+ NO_PREFERENCE = 'no-preference'
+ NULL = 'null'
+
+
+class ForcedColors(str, Enum):
+ ACTIVE = 'active'
+ NONE = 'none'
+ NULL = 'null'
+
+
+class ServiceWorkers(str, Enum):
+ ALLOW = 'allow'
+ BLOCK = 'block'
+
+
+class RecordHarContent(str, Enum):
+ OMIT = 'omit'
+ EMBED = 'embed'
+ ATTACH = 'attach'
+
+
+class RecordHarMode(str, Enum):
+ FULL = 'full'
+ MINIMAL = 'minimal'
+
+
+class BrowserChannel(str, Enum):
+ CHROMIUM = 'chromium'
+ CHROME = 'chrome'
+ CHROME_BETA = 'chrome-beta'
+ CHROME_DEV = 'chrome-dev'
+ CHROME_CANARY = 'chrome-canary'
+ MSEDGE = 'msedge'
+ MSEDGE_BETA = 'msedge-beta'
+ MSEDGE_DEV = 'msedge-dev'
+ MSEDGE_CANARY = 'msedge-canary'
+
+
+# ===== Type definitions with validators =====
+
+UrlStr = Annotated[str, AfterValidator(validate_url)]
+NonNegativeFloat = Annotated[float, AfterValidator(lambda x: validate_float_range(x, 0, float('inf')))]
+CliArgStr = Annotated[str, AfterValidator(validate_cli_arg)]
+
+
+# ===== Base Models =====
+
+
+class BrowserContextArgs(BaseModel):
+ """
+ Base model for common browser context parameters used by
+ both new_context() and launch_persistent_context().
+ """
+
+ model_config = ConfigDict(extra='ignore', validate_assignment=False, revalidate_instances='always')
+
+ # Browser context parameters
+ accept_downloads: bool = True
+ offline: bool = False
+ strict_selectors: bool = False
+
+ # Security options
+ proxy: ProxySettings | None = None
+ permissions: list[str] = Field(
+ default_factory=lambda: ['clipboard-read', 'clipboard-write'], description='Browser permissions to grant.'
+ )
+ bypass_csp: bool = False
+ client_certificates: list[ClientCertificate] = Field(default_factory=list)
+ extra_http_headers: dict[str, str] = Field(default_factory=dict)
+ http_credentials: HttpCredentials | None = None
+ ignore_https_errors: bool = False
+ java_script_enabled: bool = True
+ base_url: UrlStr | None = None
+ service_workers: ServiceWorkers = ServiceWorkers.ALLOW
+
+ # Viewport options
+ user_agent: str | None = None
+ screen: ViewportSize | None = None
+ viewport: ViewportSize | None = Field(default=None)
+ no_viewport: bool | None = None
+ device_scale_factor: NonNegativeFloat | None = None
+ is_mobile: bool = False
+ has_touch: bool = False
+ locale: str | None = None
+ geolocation: Geolocation | None = None
+ timezone_id: str | None = None
+ color_scheme: ColorScheme = ColorScheme.LIGHT
+ contrast: Contrast = Contrast.NO_PREFERENCE
+ reduced_motion: ReducedMotion = ReducedMotion.NO_PREFERENCE
+ forced_colors: ForcedColors = ForcedColors.NONE
+
+ # Recording Options
+ record_har_content: RecordHarContent = RecordHarContent.EMBED
+ record_har_mode: RecordHarMode = RecordHarMode.FULL
+ record_har_omit_content: bool = False
+ record_har_path: str | Path | None = None
+ record_har_url_filter: str | Pattern | None = None
+ record_video_dir: str | Path | None = None
+ record_video_size: ViewportSize | None = None
+
+
+class BrowserConnectArgs(BaseModel):
+ """
+ Base model for common browser connect parameters used by
+ both connect_over_cdp() and connect_over_ws().
+ """
+
+ model_config = ConfigDict(extra='ignore', validate_assignment=True, revalidate_instances='always')
+
+ headers: dict[str, str] = Field(default_factory=dict)
+ slow_mo: float = 0.0
+ timeout: float = 30_000
+
+
+class BrowserLaunchArgs(BaseModel):
+ """
+ Base model for common browser launch parameters used by
+ both launch() and launch_persistent_context().
+ """
+
+ model_config = ConfigDict(
+ extra='ignore',
+ validate_assignment=True,
+ revalidate_instances='always',
+ from_attributes=True,
+ validate_by_name=True,
+ validate_by_alias=True,
+ )
+
+ env: dict[str, str | float | bool] = Field(default_factory=dict)
+ executable_path: str | Path | None = Field(default=None, validation_alias='chrome_binary_path')
+ headless: bool | None = None
+ args: list[CliArgStr] = Field(default_factory=list)
+ ignore_default_args: list[CliArgStr] = Field(
+ default_factory=lambda: ['--enable-automation'],
+ description='List of default CLI args to stop playwright from applying (see https://github.com/microsoft/playwright/blob/41008eeddd020e2dee1c540f7c0cdfa337e99637/packages/playwright-core/src/server/chromium/chromiumSwitches.ts)',
+ )
+ channel: BrowserChannel = BrowserChannel.CHROMIUM
+ chromium_sandbox: bool = False
+ devtools: bool = False
+ slow_mo: float = 0
+ timeout: float = 30000
+ proxy: ProxySettings | None = None
+ downloads_path: str | Path | None = None
+ traces_dir: str | Path | None = None
+ handle_sighup: bool = True
+ handle_sigint: bool = True
+ handle_sigterm: bool = True
+ # firefox_user_prefs: dict[str, str | float | bool] = Field(default_factory=dict)
+
+ @model_validator(mode='after')
+ def validate_devtools_headless(self) -> Self:
+ """Cannot open devtools when headless is True"""
+ assert not (self.headless and self.devtools), 'headless=True and devtools=True cannot both be set at the same time'
+ return self
+
+ @staticmethod
+ def args_as_dict(args: list[str]) -> dict[str, str]:
+ """Return the extra launch CLI args as a dictionary."""
+ args_dict = {}
+ for arg in args:
+ key, value, *_ = [*arg.split('=', 1), '', '', '']
+ args_dict[key.strip().lstrip('-')] = value.strip()
+ return args_dict
+
+ @staticmethod
+ def args_as_list(args: dict[str, str]) -> list[str]:
+ """Return the extra launch CLI args as a list of strings."""
+ return [f'--{key.lstrip("-")}={value}' if value else f'--{key.lstrip("-")}' for key, value in args.items()]
+
+
+# ===== API-specific Models =====
+
+
+class BrowserNewContextArgs(BrowserContextArgs):
+ """
+ Pydantic model for new_context() arguments.
+ Extends BaseContextParams with storage_state parameter.
+ """
+
+ # storage_state is not supported in launch_persistent_context()
+ storage_state: str | Path | dict[str, Any] | None = None
+ # TODO: use StorageState type
+
+ # to apply this to existing contexts (incl cookies, localStorage, IndexedDB), see:
+ # - https://github.com/microsoft/playwright/pull/34591/files
+ # - playwright-core/src/server/storageScript.ts restore() function
+ # - https://github.com/Skn0tt/playwright/blob/c446bc44bac4fbfdf52439ba434f92192459be4e/packages/playwright-core/src/server/storageScript.ts#L84C1-L123C2
+
+ # @field_validator('storage_state', mode='after')
+ # def load_storage_state_from_file(self) -> Self:
+ # """Load storage_state from file if it's a path."""
+ # if isinstance(self.storage_state, (str, Path)):
+ # storage_state_file = Path(self.storage_state)
+ # try:
+ # parsed_storage_state = json.loads(storage_state_file.read_text())
+ # validated_storage_state = StorageState(**parsed_storage_state)
+ # self.storage_state = validated_storage_state
+ # except Exception as e:
+ # raise ValueError(f'Failed to load storage state file {self.storage_state}: {e}') from e
+ # return self
+ pass
+
+
+class BrowserLaunchPersistentContextArgs(BrowserLaunchArgs, BrowserContextArgs):
+ """
+ Pydantic model for launch_persistent_context() arguments.
+ Combines browser launch parameters and context parameters,
+ plus adds the user_data_dir parameter.
+ """
+
+ # Required parameter specific to launch_persistent_context
+ user_data_dir: str | Path = BROWSERUSE_PROFILES_DIR / 'default'
+
+ # @field_validator('user_data_dir', mode='after')
+ # def validate_user_data_dir(self) -> Self:
+ # """Ensure that user_data_dir is a valid path."""
+
+ # self.user_data_dir = Path(self.user_data_dir).expanduser().resolve()
+ # self.user_data_dir.mkdir(parents=True, exist_ok=True)
+
+ # # check if they passed a chrome profile subdir by accident
+ # if (self.user_data_dir / 'History').is_file() and (self.user_data_dir / 'Cookies').is_file():
+ # raise ValueError(
+ # f'user_data_dir={self.user_data_dir} is incorrect, you should pass the parent dir instead: {self.user_data_dir.parent}'
+ # )
+
+ # launch_args = self.args or []
+ # launch_args.append('--no-default-browser-check')
+ # launch_args.append('--disable-first-run-ui')
+
+ # # check if the user_data_dir is initialized
+ # if (self.user_data_dir / 'Local State').is_file() and (self.user_data_dir / self.profile_directory).is_dir():
+ # # profile dir already exists and is fully set up, skip first-run inits
+ # launch_args.append('--no-first-run')
+ # self._user_data_dir_is_initialized = True
+ # else:
+ # # profile dir is empty or has not been initialized yet, it's our first run
+ # self._user_data_dir_is_initialized = False
+ # if self.ignore_default_args is not True:
+ # self.ignore_default_args = (self.ignore_default_args or []).append('--no-first-run')
+
+ # # assignment is required to re-trigger the args field validator
+ # self.args = launch_args
+
+ # return self
+
+
+class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, BrowserLaunchArgs, BrowserNewContextArgs):
+ """
+ A BrowserProfile is a static collection of kwargs that can be passed to:
+ - BrowserType.launch(**BrowserLaunchArgs)
+ - BrowserType.connect(**BrowserConnectArgs)
+ - BrowserType.connect_over_cdp(**BrowserConnectArgs)
+ - BrowserType.launch_persistent_context(**BrowserLaunchPersistentContextArgs)
+ - BrowserContext.new_context(**BrowserNewContextArgs)
+ """
+
+ model_config = ConfigDict(
+ extra='ignore',
+ validate_assignment=True,
+ revalidate_instances='always',
+ from_attributes=True,
+ validate_by_name=True,
+ validate_by_alias=True,
+ )
+
+ id: str = Field(default_factory=uuid7str)
+ label: str = 'default'
+
+ # custom options we provide that aren't native playwright kwargs
+ disable_security: bool = Field(default=False, description='Disable browser security features.')
+ deterministic_rendering: bool = Field(default=False, description='Enable deterministic rendering flags.')
+ allowed_domains: list[str] | None = Field(default=None, description='List of allowed domains for navigation.')
+ keep_alive: bool | None = Field(default=None, description='Keep browser alive after agent run.')
+ window_size: ViewportSize | None = Field(
+ default=None,
+ description='Window size to use for the browser when headless=False.',
+ )
+ window_position: ViewportSize | None = Field(
+ default_factory=lambda: {'width': 0, 'height': 0},
+ description='Window position to use for the browser x,y from the top left when headless=False.',
+ )
+
+ # --- Page load/wait timings ---
+ minimum_wait_page_load_time: float = Field(default=0.25, description='Minimum time to wait before capturing page state.')
+ wait_for_network_idle_page_load_time: float = Field(default=0.5, description='Time to wait for network idle.')
+ maximum_wait_page_load_time: float = Field(default=5.0, description='Maximum time to wait for page load.')
+ wait_between_actions: float = Field(default=0.5, description='Time to wait between actions.')
+
+ # --- UI/viewport/DOM ---
+ include_dynamic_attributes: bool = Field(default=True, description='Include dynamic attributes in selectors.')
+ highlight_elements: bool = Field(default=True, description='Highlight interactive elements on the page.')
+ viewport_expansion: int = Field(default=500, description='Viewport expansion in pixels for LLM context.')
+
+ profile_directory: str = 'Default' # e.g. 'Profile 1', 'Profile 2', 'Custom Profile', etc.
+
+ save_recording_path: str | None = Field(default=None, description='Directory for video recordings.')
+ save_downloads_path: str | None = Field(default=None, description='Directory for saving downloads.')
+ save_har_path: str | None = Field(default=None, description='Directory for saving HAR files.')
+ trace_path: str | None = Field(default=None, description='Directory for saving trace files.')
+
+ # extension_ids_to_preinstall: list[str] = Field(
+ # default_factory=list, description='List of Chrome extension IDs to preinstall.'
+ # )
+ # extensions_dir: Path = Field(
+ # default_factory=lambda: Path('~/.config/browseruse/cache/extensions').expanduser(),
+ # description='Directory containing .crx extension files.',
+ # )
+
+ # # --- File paths ---
+ # downloads_dir: Path = Field(
+ # default_factory=lambda: Path('~/.config/browseruse/profiles/default/downloads').expanduser(),
+ # description='Directory for downloads.',
+ # )
+ # uploads_dir: Path | None = Field(default=None, description='Directory for uploads (defaults to downloads_dir if not set).')
+
+ def __repr__(self) -> str:
+ return f'BrowserProfile(label={self.label})'
+
+ def __str__(self) -> str:
+ return repr(self)
+
+ def get_args(self) -> list[str]:
+ return BrowserLaunchArgs.args_as_list( # convert back to ['--arg=value', '--arg', '--arg=value', ...]
+ BrowserLaunchArgs.args_as_dict( # uniquify via dict {'arg': 'value', 'arg2': 'value2', ...}
+ [
+ *CHROME_DEFAULT_ARGS,
+ *self.args,
+ f'--profile-directory={self.profile_directory}',
+ *(CHROME_DOCKER_ARGS if IN_DOCKER else []),
+ *(CHROME_HEADLESS_ARGS if self.headless else []),
+ *(CHROME_DISABLE_SECURITY_ARGS if self.disable_security else []),
+ *(CHROME_DETERMINISTIC_RENDERING_ARGS if self.deterministic_rendering else []),
+ *(
+ [f'--window-size={self.window_size["height"]},{self.window_size["width"]}']
+ if self.window_size
+ else (['--start-maximized' if not self.headless else []])
+ ),
+ *(
+ [f'--window-position={self.window_position["width"]},{self.window_position["height"]}']
+ if self.window_position
+ else []
+ ),
+ ]
+ )
+ )
+
+ def kwargs_for_launch_persistent_context(self) -> BrowserLaunchPersistentContextArgs:
+ """Return the kwargs for BrowserType.launch()."""
+ return BrowserLaunchPersistentContextArgs(**self.model_dump(exclude={'args'}), args=self.get_args())
+
+ def kwargs_for_new_context(self) -> BrowserNewContextArgs:
+ """Return the kwargs for BrowserContext.new_context()."""
+ return BrowserNewContextArgs(**self.model_dump(exclude={'args'}), args=self.get_args())
+
+ def kwargs_for_connect(self) -> BrowserConnectArgs:
+ """Return the kwargs for BrowserType.connect()."""
+ return BrowserConnectArgs(**self.model_dump(exclude={'args'}), args=self.get_args())
+
+ def kwargs_for_launch(self) -> BrowserLaunchArgs:
+ """Return the kwargs for BrowserType.connect_over_cdp()."""
+ return BrowserLaunchArgs(**self.model_dump(exclude={'args'}), args=self.get_args())
+
+ def prepare_user_data_dir(self) -> None:
+ """Create and unlock the user data dir for first-run initialization."""
+
+ if self.user_data_dir:
+ self.user_data_dir = Path(self.user_data_dir).expanduser().resolve()
+ self.user_data_dir.mkdir(parents=True, exist_ok=True)
+
+ # clear any existing locks by any other chrome processes
+ # hacky way to prevent chrome crashes from leaving dirs locked,
+ # but can cause conflicts if they are actually running)
+ singleton_lock = self.user_data_dir / 'SingletonLock'
+ if singleton_lock.exists():
+ singleton_lock.unlink()
+ logger.warning(
+ f'⚠️ Multiple chrome processes may be trying to share user_data_dir={self.user_data_dir} which can lead to crashes and profile data corruption!'
+ )
+
+ def detect_display_configuration(self) -> None:
+ """Detect the display size and set the screen option."""
+
+ display_size = get_display_size()
+ if display_size:
+ self.screen = self.screen or display_size or ViewportSize(width=1280, height=1100)
+
+ # if no headless preference specified, prefer headful if there is a display available
+ if self.headless is None:
+ self.headless = not bool(display_size)
+
+ # set up window size and position if headful
+ if self.headless:
+ # headless mode: no window available, use viewport instead to constrain content size
+ self.window_size = None
+ self.window_position = None
+ self.no_viewport = False
+ self.viewport = self.viewport or display_size or ViewportSize(width=1280, height=1100)
+ else:
+ # headful mode: use window, disable viewport, content fits to size of window
+ self.window_size = self.window_size or display_size or ViewportSize(width=1280, height=1100)
+ self.no_viewport = True if self.no_viewport is None else self.no_viewport
+ self.viewport = None if self.no_viewport else self.viewport
+
+ # automatically setup viewport if any config requires it
+ use_viewport = self.headless or self.viewport or self.device_scale_factor
+ self.no_viewport = not use_viewport if self.no_viewport is None else self.no_viewport
+ if use_viewport:
+ self.viewport = self.viewport or display_size or ViewportSize(width=1280, height=1100)
+ self.device_scale_factor = self.device_scale_factor or 1.0
+ self.screen = self.screen or display_size or ViewportSize(width=1280, height=1100)
+ else:
+ self.viewport = None
+ self.device_scale_factor = None
+ self.screen = None
+
+
+# For convenience, example function signatures:
+"""
+def launch(
+ **kwargs: Unpack[LaunchArgs]
+) -> Browser:
+ ...
+
+def new_context(
+ **kwargs: Unpack[NewContextArgs]
+) -> BrowserContext:
+ ...
+
+def launch_persistent_context(
+ user_data_dir: str | Path,
+ **kwargs: Unpack[LaunchPersistentContextArgs]
+) -> BrowserContext:
+ ...
+"""
diff --git a/browser_use/browser/utils/screen_resolution.py b/browser_use/browser/utils/screen_resolution.py
deleted file mode 100644
index 260797084..000000000
--- a/browser_use/browser/utils/screen_resolution.py
+++ /dev/null
@@ -1,41 +0,0 @@
-import sys
-
-
-def get_screen_resolution():
- if sys.platform == 'darwin': # macOS
- try:
- from AppKit import NSScreen
-
- screen = NSScreen.mainScreen().frame()
- return {'width': int(screen.size.width), 'height': int(screen.size.height)}
- except ImportError:
- print('AppKit is not available. Make sure you are running this on macOS with pyobjc installed.')
- except Exception as e:
- print(f'Error retrieving macOS screen resolution: {e}')
- return {'width': 2560, 'height': 1664}
-
- else: # Windows & Linux
- try:
- from screeninfo import get_monitors
-
- monitors = get_monitors()
- if not monitors:
- raise Exception('No monitors detected.')
- monitor = monitors[0]
- return {'width': monitor.width, 'height': monitor.height}
- except ImportError:
- print("screeninfo package not found. Install it using 'pip install screeninfo'.")
- except Exception as e:
- print(f'Error retrieving screen resolution: {e}')
-
- return {'width': 1920, 'height': 1080}
-
-
-def get_window_adjustments():
- """Returns recommended x, y offsets for window positioning"""
- if sys.platform == 'darwin': # macOS
- return -4, 24 # macOS has a small title bar, no border
- elif sys.platform == 'win32': # Windows
- return -8, 0 # Windows has a border on the left
- else: # Linux
- return 0, 0
diff --git a/browser_use/cli.py b/browser_use/cli.py
index 435b54bc5..813721c6b 100644
--- a/browser_use/cli.py
+++ b/browser_use/cli.py
@@ -34,8 +34,9 @@ except ImportError:
# readline not available on Windows by default
READLINE_AVAILABLE = False
-from browser_use import Agent, Browser, BrowserConfig, BrowserContextConfig, Controller
+from browser_use import Agent, Controller
from browser_use.agent.views import AgentSettings
+from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.logging_config import addLoggingLevel
# Paths
@@ -149,19 +150,24 @@ def update_config_with_click_args(config: dict[str, Any], ctx: click.Context) ->
if 'browser_context' not in config:
config['browser_context'] = {}
+ # Create a merged browser profile config for all browser settings
+ browser_profile = config.get('browser', {}) | config.get('browser_context', {})
+
# Update configuration with command-line args if provided
if ctx.params.get('model'):
config['model']['name'] = ctx.params['model']
if ctx.params.get('headless') is not None:
- config['browser']['headless'] = ctx.params['headless']
+ browser_profile['headless'] = ctx.params['headless']
if ctx.params.get('window_width'):
- config['browser']['window_width'] = ctx.params['window_width']
- if 'viewport_width' in config['browser_context']:
- config['browser_context']['viewport_width'] = ctx.params['window_width']
+ browser_profile['window_width'] = ctx.params['window_width']
if ctx.params.get('window_height'):
- config['browser']['window_height'] = ctx.params['window_height']
- if 'viewport_height' in config['browser_context']:
- config['browser_context']['viewport_height'] = ctx.params['window_height']
+ browser_profile['window_height'] = ctx.params['window_height']
+
+ # Update config with the merged profile
+ config['browser'] = browser_profile
+ # Remove the old split config
+ if 'browser_context' in config:
+ del config['browser_context']
return config
@@ -418,7 +424,7 @@ class BrowserUseApp(App):
def __init__(self, config: dict[str, Any], *args, **kwargs):
super().__init__(*args, **kwargs)
self.config = config
- self.browser = None # Will be set before app.run_async()
+ self.browser_session = None # Will be set before app.run_async()
self.controller = None # Will be set before app.run_async()
self.agent = None
self.llm = None # Will be set before app.run_async()
@@ -719,24 +725,23 @@ class BrowserUseApp(App):
browser_info = self.query_one('#browser-info')
browser_info.clear()
- if self.browser:
+ if self.browser_session:
# Get basic browser info
- browser_type = self.browser.__class__.__name__
- headless = self.browser.config.headless
- browser_class = self.browser.config.browser_class
+ browser_type = self.browser_session.browser.__class__.__name__
+ headless = self.browser_session.headless
# Determine connection type based on config
connection_type = 'playwright' # Default
- if self.browser.config.cdp_url:
+ if self.browser_session.cdp_url:
connection_type = 'CDP'
- elif self.browser.config.wss_url:
+ elif self.browser_session.wss_url:
connection_type = 'WSS'
- elif self.browser.config.browser_binary_path:
+ elif self.browser_session.executable_path:
connection_type = 'user-provided'
# Get window size details
- window_width = self.browser.config.new_context_config.window_width
- window_height = self.browser.config.new_context_config.window_height
+ window_width = self.browser_session.viewport['width']
+ window_height = self.browser_session.viewport['height']
# Try to get browser PID
browser_pid = 'Unknown'
@@ -744,31 +749,22 @@ class BrowserUseApp(App):
browser_status = '[red]Disconnected[/]'
try:
- # First check if Chrome subprocess is available directly
- if hasattr(self.browser, '_chrome_subprocess') and self.browser._chrome_subprocess:
- try:
- if hasattr(self.browser._chrome_subprocess, 'pid'):
- browser_pid = str(self.browser._chrome_subprocess.pid)
- connected = True
- browser_status = '[green]Connected[/]'
- except Exception as e:
- browser_pid = f'Error: {str(e)}'
- # Then check if we have a playwright browser connection
- elif hasattr(self.browser, 'playwright_browser') and self.browser.playwright_browser:
+ # First check if Chrome subprocess is tracked
+ if hasattr(self.browser_session, 'chrome_process') and self.browser_session.chrome_process.pid:
+ browser_pid = str(self.browser_session.chrome_process.pid)
+ connected = True
+ browser_status = '[green]Connected[/]'
+ # Then check if we have a browser connection
+ elif hasattr(self.browser_session, 'browser') and self.browser_session.browser.is_connected():
connected = True
browser_status = '[green]Connected[/]'
- # Try to get PID from related processes by checking for Chrome/Firefox
+ # Try to get PID from related processes by checking for Chrome processes
import psutil
for proc in psutil.process_iter(['pid', 'name']):
try:
- if (
- browser_class in proc.name().lower()
- or 'chrome' in proc.name().lower()
- or 'chromium' in proc.name().lower()
- or 'firefox' in proc.name().lower()
- ):
+ if 'chrome' in proc.name().lower() or 'chromium' in proc.name().lower():
browser_pid = str(proc.pid)
break
except (psutil.NoSuchProcess, psutil.AccessDenied):
@@ -777,12 +773,12 @@ class BrowserUseApp(App):
browser_pid = f'Error: {str(e)}'
# Display browser information
- browser_info.write(f'[bold cyan]{browser_class}[/] Browser ({browser_status})')
+ browser_info.write(f'[bold cyan]Chromium[/] Browser ({browser_status})')
browser_info.write(
f'Type: [yellow]{connection_type}[/] [{"green" if not headless else "red"}]{" (headless)" if headless else ""}[/]'
)
browser_info.write(f'PID: [dim]{browser_pid}[/]')
- browser_info.write(f'CDP Port: {self.browser.config.chrome_remote_debugging_port}')
+ browser_info.write(f'CDP Port: {self.browser_session.cdp_url}')
if window_width and window_height:
browser_info.write(f'Window: [blue]{window_width}[/] × [blue]{window_height}[/]')
@@ -798,9 +794,9 @@ class BrowserUseApp(App):
pass
# Show the agent's current page URL if available
- if hasattr(self.agent.browser_context, 'agent_current_page') and self.agent.browser_context.agent_current_page:
+ if self.browser_session.agent_current_page:
current_url = (
- self.agent.browser_context.agent_current_page.url.replace('https://', '')
+ self.browser_session.agent_current_page.url.replace('https://', '')
.replace('http://', '')
.replace('www.', '')[:36]
+ '…'
@@ -1205,13 +1201,11 @@ async def textual_interface(config: dict[str, Any]):
# Step 1: Configure BrowserUse components
logger.debug('Validating browser configs...')
try:
- browser_config = BrowserConfig.model_validate(config.get('browser', {}))
- context_config = BrowserContextConfig.model_validate(config.get('browser_context', {}))
- browser_config.new_context_config = context_config
- logger.info(f'Browser type: {browser_config.browser_class}')
- if browser_config.browser_binary_path:
- logger.info(f'Browser binary: {browser_config.browser_binary_path}')
- if browser_config.headless:
+ browser_profile = BrowserProfile.model_validate(config.get('browser', {}) | config.get('browser_context', {}))
+ logger.info('Browser type: chromium') # BrowserProfile only supports chromium
+ if browser_profile.executable_path:
+ logger.info(f'Browser binary: {browser_profile.executable_path}')
+ if browser_profile.headless:
logger.info('Browser mode: headless')
else:
logger.info('Browser mode: visible')
@@ -1223,7 +1217,7 @@ async def textual_interface(config: dict[str, Any]):
# Step 2: Initialize Browser
logger.debug('Initializing Browser...')
try:
- browser = Browser(config=browser_config)
+ browser = BrowserSession(profile=browser_profile)
logger.debug('Browser initialized successfully')
# Log browser version if available
@@ -1274,7 +1268,7 @@ async def textual_interface(config: dict[str, Any]):
setup_textual_logging()
# Log browser and model configuration that will be used
- browser_type = config.get('browser', {}).get('browser_class', 'Chrome')
+ browser_type = 'Chromium' # BrowserProfile only supports Chromium
model_name = config.get('model', {}).get('name', 'auto-detected')
headless = config.get('browser', {}).get('headless', True)
headless_str = 'headless' if headless else 'visible'
@@ -1361,7 +1355,7 @@ def main(ctx: click.Context, debug: bool = False, **kwargs):
logger.debug('Setting up handlers for Textual UI...')
# Log browser and model configuration that will be used
- browser_type = config.get('browser', {}).get('browser_class', 'Chrome')
+ browser_type = 'Chromium' # BrowserProfile only supports Chromium
model_name = config.get('model', {}).get('name', 'auto-detected')
headless = config.get('browser', {}).get('headless', True)
headless_str = 'headless' if headless else 'visible'
diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.py
index 5f86642f2..c29218ff6 100644
--- a/browser_use/controller/registry/service.py
+++ b/browser_use/controller/registry/service.py
@@ -6,7 +6,7 @@ from typing import Any, Generic, Optional, TypeVar
from langchain_core.language_models.chat_models import BaseChatModel
from pydantic import BaseModel, Field, create_model
-from browser_use.browser.context import BrowserContext
+from browser_use.browser import BrowserSession
from browser_use.controller.registry.views import (
ActionModel,
ActionRegistry,
@@ -95,7 +95,7 @@ class Registry(Generic[Context]):
self,
action_name: str,
params: dict,
- browser: BrowserContext | None = None,
+ browser_session: BrowserSession | None = None,
page_extraction_llm: BaseChatModel | None = None,
sensitive_data: dict[str, str] | None = None,
available_file_paths: list[str] | None = None,
@@ -121,8 +121,8 @@ class Registry(Generic[Context]):
validated_params = self._replace_sensitive_data(validated_params, sensitive_data)
# Check if the action requires browser
- if 'browser' in parameter_names and not browser:
- raise ValueError(f'Action {action_name} requires browser but none provided.')
+ if 'browser_session' in parameter_names and not browser_session:
+ raise ValueError(f'Action {action_name} requires browser_session but none provided.')
if 'page_extraction_llm' in parameter_names and not page_extraction_llm:
raise ValueError(f'Action {action_name} requires page_extraction_llm but none provided.')
if 'available_file_paths' in parameter_names and not available_file_paths:
@@ -135,8 +135,8 @@ class Registry(Generic[Context]):
extra_args = {}
if 'context' in parameter_names:
extra_args['context'] = context
- if 'browser' in parameter_names:
- extra_args['browser'] = browser
+ if 'browser_session' in parameter_names:
+ extra_args['browser_session'] = browser_session
if 'page_extraction_llm' in parameter_names:
extra_args['page_extraction_llm'] = page_extraction_llm
if 'available_file_paths' in parameter_names:
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index fbfb9caf9..9a0435196 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -13,7 +13,7 @@ from playwright.async_api import ElementHandle, Page
from pydantic import BaseModel
from browser_use.agent.views import ActionModel, ActionResult
-from browser_use.browser.context import BrowserContext
+from browser_use.browser import BrowserSession
from browser_use.controller.registry.service import Registry
from browser_use.controller.views import (
ClickElementAction,
@@ -82,8 +82,8 @@ class Controller(Generic[Context]):
'Search the query in Google in the current tab, the query should be a search query like humans search in Google, concrete and not vague or super long. More the single most important items. ',
param_model=SearchGoogleAction,
)
- async def search_google(params: SearchGoogleAction, browser: BrowserContext):
- page = await browser.get_current_page()
+ async def search_google(params: SearchGoogleAction, browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
await page.goto(f'https://www.google.com/search?q={params.query}&udm=14')
await page.wait_for_load_state()
msg = f'🔍 Searched for "{params.query}" in Google'
@@ -91,8 +91,8 @@ class Controller(Generic[Context]):
return ActionResult(extracted_content=msg, include_in_memory=True)
@self.registry.action('Navigate to URL in the current tab', param_model=GoToUrlAction)
- async def go_to_url(params: GoToUrlAction, browser: BrowserContext):
- page = await browser.get_current_page()
+ async def go_to_url(params: GoToUrlAction, browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
await page.goto(params.url)
await page.wait_for_load_state()
msg = f'🔗 Navigated to {params.url}'
@@ -100,8 +100,8 @@ class Controller(Generic[Context]):
return ActionResult(extracted_content=msg, include_in_memory=True)
@self.registry.action('Go back', param_model=NoParamsAction)
- async def go_back(_: NoParamsAction, browser: BrowserContext):
- await browser.go_back()
+ async def go_back(_: NoParamsAction, browser_session: BrowserSession):
+ await browser_session.go_back()
msg = '🔙 Navigated back'
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
@@ -116,17 +116,17 @@ class Controller(Generic[Context]):
# Element Interaction Actions
@self.registry.action('Click element by index', param_model=ClickElementAction)
- async def click_element_by_index(params: ClickElementAction, browser: BrowserContext):
- session = await browser.get_session()
+ async def click_element_by_index(params: ClickElementAction, browser_session: BrowserSession):
+ # Browser is now a BrowserSession itself
- if params.index not in await browser.get_selector_map():
+ if params.index not in await browser_session.get_selector_map():
raise Exception(f'Element with index {params.index} does not exist - retry or use alternative actions')
- element_node = await browser.get_dom_element_by_index(params.index)
- initial_pages = len(session.context.pages)
+ element_node = await browser_session.get_dom_element_by_index(params.index)
+ initial_pages = len(browser_session.browser_context.pages if browser_session.browser_context else [])
# if element has file uploader then dont click
- if await browser.is_file_uploader(element_node):
+ if await browser_session.is_file_uploader(element_node):
msg = f'Index {params.index} - has an element which opens file upload dialog. To upload files please use a specific function to upload files '
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
@@ -134,7 +134,7 @@ class Controller(Generic[Context]):
msg = None
try:
- download_path = await browser._click_element_node(element_node)
+ download_path = await browser_session._click_element_node(element_node)
if download_path:
msg = f'💾 Downloaded file to {download_path}'
else:
@@ -142,11 +142,11 @@ class Controller(Generic[Context]):
logger.info(msg)
logger.debug(f'Element xpath: {element_node.xpath}')
- if len(session.context.pages) > initial_pages:
+ if len(browser_session.browser_context.pages) > initial_pages:
new_tab_msg = 'New tab opened - switching to it'
msg += f' - {new_tab_msg}'
logger.info(new_tab_msg)
- await browser.switch_to_tab(-1)
+ await browser_session.switch_to_tab(-1)
return ActionResult(extracted_content=msg, include_in_memory=True)
except Exception as e:
logger.warning(f'Element not clickable with index {params.index} - most likely the page changed')
@@ -156,12 +156,12 @@ class Controller(Generic[Context]):
'Input text into a input interactive element',
param_model=InputTextAction,
)
- async def input_text(params: InputTextAction, browser: BrowserContext, has_sensitive_data: bool = False):
- if params.index not in await browser.get_selector_map():
+ async def input_text(params: InputTextAction, browser_session: BrowserSession, has_sensitive_data: bool = False):
+ if params.index not in await browser_session.get_selector_map():
raise Exception(f'Element index {params.index} does not exist - retry or use alternative actions')
- element_node = await browser.get_dom_element_by_index(params.index)
- await browser._input_text_element_node(element_node, params.text)
+ element_node = await browser_session.get_dom_element_by_index(params.index)
+ await browser_session._input_text_element_node(element_node, params.text)
if not has_sensitive_data:
msg = f'⌨️ Input {params.text} into index {params.index}'
else:
@@ -174,8 +174,8 @@ class Controller(Generic[Context]):
@self.registry.action(
'Save the current page as a PDF file',
)
- async def save_pdf(browser: BrowserContext):
- page = await browser.get_current_page()
+ async def save_pdf(browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
short_url = re.sub(r'^https?://(?:www\.)?|/$', '', page.url)
slug = re.sub(r'[^a-zA-Z0-9]+', '-', short_url).strip('-').lower()
sanitized_filename = f'{slug}.pdf'
@@ -188,28 +188,28 @@ class Controller(Generic[Context]):
# Tab Management Actions
@self.registry.action('Switch tab', param_model=SwitchTabAction)
- async def switch_tab(params: SwitchTabAction, browser: BrowserContext):
- await browser.switch_to_tab(params.page_id)
+ async def switch_tab(params: SwitchTabAction, browser_session: BrowserSession):
+ await browser_session.switch_to_tab(params.page_id)
# Wait for tab to be ready and ensure references are synchronized
- page = await browser.get_agent_current_page()
+ page = await browser_session.get_agent_current_page()
await page.wait_for_load_state()
msg = f'🔄 Switched to tab {params.page_id}'
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
@self.registry.action('Open url in new tab', param_model=OpenTabAction)
- async def open_tab(params: OpenTabAction, browser: BrowserContext):
- await browser.create_new_tab(params.url)
+ async def open_tab(params: OpenTabAction, browser_session: BrowserSession):
+ await browser_session.browser_context.create_new_tab(params.url)
# Ensure tab references are properly synchronized
- await browser.get_agent_current_page() # this has side-effects (even though it looks like a getter)
+ await browser_session.get_agent_current_page() # this has side-effects (even though it looks like a getter)
msg = f'🔗 Opened new tab with {params.url}'
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
@self.registry.action('Close an existing tab', param_model=CloseTabAction)
- async def close_tab(params: CloseTabAction, browser: BrowserContext):
- await browser.switch_to_tab(params.page_id)
- page = await browser.get_current_page()
+ async def close_tab(params: CloseTabAction, browser_session: BrowserSession):
+ await browser_session.switch_to_tab(params.page_id)
+ page = await browser_session.get_current_page()
url = page.url
await page.close()
msg = f'❌ Closed tab #{params.page_id} with url {url}'
@@ -221,9 +221,9 @@ class Controller(Generic[Context]):
'Extract page content to retrieve specific information from the page, e.g. all company names, a specific description, all information about, links with companies in structured format or simply links',
)
async def extract_content(
- goal: str, should_strip_link_urls: bool, browser: BrowserContext, page_extraction_llm: BaseChatModel
+ goal: str, should_strip_link_urls: bool, browser_session: BrowserSession, page_extraction_llm: BaseChatModel
):
- page = await browser.get_current_page()
+ page = await browser_session.get_current_page()
import markdownify
strip = []
@@ -255,8 +255,8 @@ class Controller(Generic[Context]):
'Scroll down the page by pixel amount - if no amount is specified, scroll down one page',
param_model=ScrollAction,
)
- async def scroll_down(params: ScrollAction, browser: BrowserContext):
- page = await browser.get_current_page()
+ async def scroll_down(params: ScrollAction, browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
if params.amount is not None:
await page.evaluate(f'window.scrollBy(0, {params.amount});')
else:
@@ -275,8 +275,8 @@ class Controller(Generic[Context]):
'Scroll up the page by pixel amount - if no amount is specified, scroll up one page',
param_model=ScrollAction,
)
- async def scroll_up(params: ScrollAction, browser: BrowserContext):
- page = await browser.get_current_page()
+ async def scroll_up(params: ScrollAction, browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
if params.amount is not None:
await page.evaluate(f'window.scrollBy(0, -{params.amount});')
else:
@@ -295,8 +295,8 @@ class Controller(Generic[Context]):
'Send strings of special keys like Escape,Backspace, Insert, PageDown, Delete, Enter, Shortcuts such as `Control+o`, `Control+Shift+T` are supported as well. This gets used in keyboard.press. ',
param_model=SendKeysAction,
)
- async def send_keys(params: SendKeysAction, browser: BrowserContext):
- page = await browser.get_current_page()
+ async def send_keys(params: SendKeysAction, browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
try:
await page.keyboard.press(params.keys)
@@ -318,8 +318,8 @@ class Controller(Generic[Context]):
@self.registry.action(
description='If you dont find something which you want to interact with, scroll to it',
)
- async def scroll_to_text(text: str, browser: BrowserContext): # type: ignore
- page = await browser.get_current_page()
+ async def scroll_to_text(text: str, browser_session: BrowserSession): # type: ignore
+ page = await browser_session.get_current_page()
try:
# Try different locator strategies
locators = [
@@ -360,10 +360,10 @@ class Controller(Generic[Context]):
@self.registry.action(
description='Get all options from a native dropdown',
)
- async def get_dropdown_options(index: int, browser: BrowserContext) -> ActionResult:
+ async def get_dropdown_options(index: int, browser_session: BrowserSession) -> ActionResult:
"""Get all options from a native dropdown"""
- page = await browser.get_current_page()
- selector_map = await browser.get_selector_map()
+ page = await browser_session.get_current_page()
+ selector_map = await browser_session.get_selector_map()
dom_element = selector_map[index]
try:
@@ -433,11 +433,11 @@ class Controller(Generic[Context]):
async def select_dropdown_option(
index: int,
text: str,
- browser: BrowserContext,
+ browser_session: BrowserSession,
) -> ActionResult:
"""Select dropdown option by the text of the option you want to select"""
- page = await browser.get_current_page()
- selector_map = await browser.get_selector_map()
+ page = await browser_session.get_current_page()
+ selector_map = await browser_session.get_selector_map()
dom_element = selector_map[index]
# Validate that we're working with a select element
@@ -527,7 +527,7 @@ class Controller(Generic[Context]):
'Drag and drop elements or between coordinates on the page - useful for canvas drawing, sortable lists, sliders, file uploads, and UI rearrangement',
param_model=DragDropAction,
)
- async def drag_drop(params: DragDropAction, browser: BrowserContext) -> ActionResult:
+ async def drag_drop(params: DragDropAction, browser_session: BrowserSession) -> ActionResult:
"""
Performs a precise drag and drop operation between elements or coordinates.
"""
@@ -651,7 +651,7 @@ class Controller(Generic[Context]):
except Exception as e:
return False, f'Error during drag operation: {str(e)}'
- page = await browser.get_current_page()
+ page = await browser_session.get_current_page()
try:
# Initialize variables
@@ -738,8 +738,8 @@ class Controller(Generic[Context]):
return ActionResult(error=error_msg, include_in_memory=True)
@self.registry.action('Google Sheets: Get the contents of the entire sheet', domains=['sheets.google.com'])
- async def get_sheet_contents(browser: BrowserContext):
- page = await browser.get_current_page()
+ async def get_sheet_contents(browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
# select all cells
await page.keyboard.press('Enter')
@@ -751,8 +751,8 @@ class Controller(Generic[Context]):
return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)
@self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['sheets.google.com'])
- async def select_cell_or_range(browser: BrowserContext, cell_or_range: str):
- page = await browser.get_current_page()
+ async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):
+ page = await browser_session.get_current_page()
await page.keyboard.press('Enter') # make sure we dont delete current cell contents if we were last editing
await page.keyboard.press('Escape') # to clear current focus (otherwise select range popup is additive)
@@ -772,10 +772,10 @@ class Controller(Generic[Context]):
@self.registry.action(
'Google Sheets: Get the contents of a specific cell or range of cells', domains=['sheets.google.com']
)
- async def get_range_contents(browser: BrowserContext, cell_or_range: str):
- page = await browser.get_current_page()
+ async def get_range_contents(browser_session: BrowserSession, cell_or_range: str):
+ page = await browser_session.get_current_page()
- await select_cell_or_range(browser, cell_or_range)
+ await select_cell_or_range(browser_session, cell_or_range)
await page.keyboard.press('ControlOrMeta+C')
await asyncio.sleep(0.1)
@@ -783,15 +783,15 @@ class Controller(Generic[Context]):
return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)
@self.registry.action('Google Sheets: Clear the currently selected cells', domains=['sheets.google.com'])
- async def clear_selected_range(browser: BrowserContext):
- page = await browser.get_current_page()
+ async def clear_selected_range(browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
await page.keyboard.press('Backspace')
return ActionResult(extracted_content='Cleared selected range', include_in_memory=False)
@self.registry.action('Google Sheets: Input text into the currently selected cell', domains=['sheets.google.com'])
- async def input_selected_cell_text(browser: BrowserContext, text: str):
- page = await browser.get_current_page()
+ async def input_selected_cell_text(browser_session: BrowserSession, text: str):
+ page = await browser_session.get_current_page()
await page.keyboard.type(text, delay=0.1)
await page.keyboard.press('Enter') # make sure to commit the input so it doesn't get overwritten by the next action
@@ -799,10 +799,10 @@ class Controller(Generic[Context]):
return ActionResult(extracted_content=f'Inputted text {text}', include_in_memory=False)
@self.registry.action('Google Sheets: Batch update a range of cells', domains=['sheets.google.com'])
- async def update_range_contents(browser: BrowserContext, range: str, new_contents_tsv: str):
- page = await browser.get_current_page()
+ async def update_range_contents(browser_session: BrowserSession, range: str, new_contents_tsv: str):
+ page = await browser_session.get_current_page()
- await select_cell_or_range(browser, range)
+ await select_cell_or_range(browser_session, range)
# simulate paste event from clipboard with TSV content
await page.evaluate(f"""
@@ -828,7 +828,7 @@ class Controller(Generic[Context]):
async def act(
self,
action: ActionModel,
- browser_context: BrowserContext,
+ browser_session: BrowserSession,
#
page_extraction_llm: BaseChatModel | None = None,
sensitive_data: dict[str, str] | None = None,
@@ -852,7 +852,7 @@ class Controller(Generic[Context]):
result = await self.registry.execute_action(
action_name,
params,
- browser=browser_context,
+ browser_session=browser_session,
page_extraction_llm=page_extraction_llm,
sensitive_data=sensitive_data,
available_file_paths=available_file_paths,
diff --git a/browser_use/telemetry/__init__.py b/browser_use/telemetry/__init__.py
new file mode 100644
index 000000000..3e7dbabf4
--- /dev/null
+++ b/browser_use/telemetry/__init__.py
@@ -0,0 +1,8 @@
+"""
+Telemetry for Browser Use.
+"""
+
+from browser_use.telemetry.service import ProductTelemetry
+from browser_use.telemetry.views import BaseTelemetryEvent, ControllerRegisteredFunctionsTelemetryEvent
+
+__all__ = ['BaseTelemetryEvent', 'ControllerRegisteredFunctionsTelemetryEvent', 'ProductTelemetry']
diff --git a/conftest.py b/conftest.py
deleted file mode 100644
index 297403f26..000000000
--- a/conftest.py
+++ /dev/null
@@ -1,10 +0,0 @@
-import os
-import sys
-
-from browser_use.logging_config import setup_logging
-
-# Get the absolute path to the project root
-project_root = os.path.dirname(os.path.abspath(__file__))
-sys.path.insert(0, project_root)
-
-setup_logging()
diff --git a/pyproject.toml b/pyproject.toml
index b60e0e649..ff20b16f9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -35,6 +35,7 @@ dependencies = [
"psutil>=7.0.0",
"faiss-cpu>=1.9.0",
"mem0ai==0.1.93",
+ "uuid7>=0.1.0",
]
# pydantic: >2.11 introduces many pydantic deprecation warnings until langchain-core upgrades their pydantic support lets keep it on 2.10
# google-api-core: only used for Google LLM APIs
@@ -81,14 +82,17 @@ line-length = 130
fix = true
[tool.ruff.lint]
-select = ["ASYNC", "E", "F", "FAST", "I", "PLE"]
-ignore = ["ASYNC109", "E101", "E402", "E501", "F841", "E731"] # TODO: determine if adding timeouts to all the unbounded async functions is needed / worth-it so we can un-ignore ASYNC109
+select = ["ASYNC", "E", "F", "FAST", "I", "PLE", "E261"]
+ignore = ["ASYNC109", "E101", "E402", "E501", "F841", "E731", "W291"] # TODO: determine if adding timeouts to all the unbounded async functions is needed / worth-it so we can un-ignore ASYNC109
unfixable = ["E101", "E402", "E501", "F841", "E731"]
[tool.ruff.format]
quote-style = "single"
indent-style = "tab"
+line-ending = "lf"
docstring-code-format = true
+docstring-code-line-length = 140
+skip-magic-trailing-comma = false
[tool.pyright]
typeCheckingMode = "off"
diff --git a/tests/conftest.py b/tests/conftest.py
deleted file mode 100644
index 663966c27..000000000
--- a/tests/conftest.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""
-Test configuration for browser-use.
-"""
-
-import logging
-import os
-import sys
-
-import pytest
-from langchain_openai import ChatOpenAI
-from pydantic import SecretStr
-
-# Ensure the project root is in the Python path
-sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
-
-# Load environment variables
-from dotenv import load_dotenv
-
-load_dotenv()
-
-# Configure logging
-logging.basicConfig(level=logging.DEBUG)
-logger = logging.getLogger(__name__)
-
-
-from browser_use.browser.browser import Browser, BrowserConfig
-from browser_use.browser.context import BrowserContext
-
-
[email protected](scope='session')
-def llm():
- """
- Fixture to provide a ChatOpenAI instance or a mock for testing.
- Uses a mock if OPENAI_API_KEY is not set.
- """
- api_key = os.getenv('OPENAI_API_KEY')
- logger.debug(f'API Key present: {bool(api_key)}')
- logger.debug('Using actual ChatOpenAI model')
- return ChatOpenAI(model='gpt-4o', api_key=SecretStr(api_key) if api_key else None)
-
-
[email protected](scope='session')
-def browser():
- """
- Fixture to provide a Browser instance for testing.
- """
- logger.debug('Creating Browser instance for testing')
- return Browser(config=BrowserConfig(headless=True, disable_security=True))
-
-
[email protected](scope='function')
-async def browser_context(browser):
- """
- Fixture to provide a BrowserContext instance for testing.
- """
- logger.debug('Creating BrowserContext instance for testing')
- context = BrowserContext(browser=browser)
- yield context
- await context.close()
diff --git a/tests/test_browser.py b/tests/test_browser.py
index 26f921279..57025af87 100644
--- a/tests/test_browser.py
+++ b/tests/test_browser.py
@@ -1,20 +1,13 @@
-import asyncio
-import subprocess
-
-import psutil
import pytest
-import requests
-from browser_use.browser.browser import Browser, BrowserConfig, ProxySettings
-from browser_use.browser.context import BrowserContext, BrowserContextConfig
+from browser_use.browser import BrowserProfile, BrowserSession
@pytest.mark.asyncio
async def test_builtin_browser_launch(monkeypatch):
"""
- Test that the standard browser is launched correctly:
- When no remote (cdp or wss) or chrome instance is provided, the Browser class uses _setup_builtin_browser.
- This test monkeypatches async_playwright to return dummy objects, and asserts that get_playwright_browser returns the expected DummyBrowser.
+ Test that the standard browser is launched correctly.
+ This test monkeypatches async_playwright to return dummy objects, and asserts that BrowserSession.initialize() returns the expected browser.
"""
class DummyBrowser:
@@ -35,544 +28,21 @@ async def test_builtin_browser_launch(monkeypatch):
async def start(self):
return DummyPlaywright()
- monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
- config = BrowserConfig(headless=True, disable_security=False, extra_browser_args=['--test'])
- browser_obj = Browser(config=config)
- result_browser = await browser_obj.get_playwright_browser()
- assert isinstance(result_browser, DummyBrowser), 'Expected DummyBrowser from _setup_builtin_browser'
- await browser_obj.close()
-
-
-async def test_cdp_browser_launch(monkeypatch):
- """
- Test that when a CDP URL is provided in the configuration, the Browser uses _setup_cdp
- and returns the expected DummyBrowser.
- """
-
- class DummyBrowser:
- pass
-
- class DummyChromium:
- async def connect_over_cdp(self, endpoint_url, timeout=20000):
- assert endpoint_url == 'ws://dummy-cdp-url', 'The endpoint URL should match the configuration.'
- return DummyBrowser()
-
- class DummyPlaywright:
- def __init__(self):
- self.chromium = DummyChromium()
-
- async def stop(self):
- pass
-
- class DummyAsyncPlaywrightContext:
- async def start(self):
- return DummyPlaywright()
-
- monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
- config = BrowserConfig(cdp_url='ws://dummy-cdp-url')
- browser_obj = Browser(config=config)
- result_browser = await browser_obj.get_playwright_browser()
- assert isinstance(result_browser, DummyBrowser), 'Expected DummyBrowser from _setup_cdp'
- await browser_obj.close()
-
-
-async def test_wss_browser_launch(monkeypatch):
- """
- Test that when a WSS URL is provided in the configuration,
- the Browser uses setup_wss and returns the expected DummyBrowser.
- """
-
- class DummyBrowser:
- pass
-
- class DummyChromium:
- async def connect(self, wss_url):
- assert wss_url == 'ws://dummy-wss-url', 'WSS URL should match the configuration.'
- return DummyBrowser()
-
- class DummyPlaywright:
- def __init__(self):
- self.chromium = DummyChromium()
-
- async def stop(self):
- pass
-
- class DummyAsyncPlaywrightContext:
- async def start(self):
- return DummyPlaywright()
-
- monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
- config = BrowserConfig(wss_url='ws://dummy-wss-url')
- browser_obj = Browser(config=config)
- result_browser = await browser_obj.get_playwright_browser()
- assert isinstance(result_browser, DummyBrowser), 'Expected DummyBrowser from _setup_wss'
- await browser_obj.close()
-
-
-async def test_user_provided_browser_launch(monkeypatch):
- """
- Test that when a browser_binary_path is provided the Browser class uses
- _setup_user_provided_browser branch and returns the expected DummyBrowser object
- by reusing an existing Chrome instance.
- """
-
- # Dummy response for requests.get when checking chrome debugging endpoint.
- class DummyResponse:
- status_code = 200
-
- def dummy_get(url, timeout):
- if url == 'http://localhost:9222/json/version':
- return DummyResponse()
- raise requests.ConnectionError('Connection failed')
-
- monkeypatch.setattr(requests, 'get', dummy_get)
-
- class DummyBrowser:
- pass
-
- class DummyChromium:
- async def connect_over_cdp(self, endpoint_url, timeout=20000):
- assert endpoint_url == 'http://localhost:9222', "Endpoint URL must be 'http://localhost:9222'"
- return DummyBrowser()
-
- class DummyPlaywright:
- def __init__(self):
- self.chromium = DummyChromium()
-
- async def stop(self):
- pass
-
- class DummyAsyncPlaywrightContext:
- async def start(self):
- return DummyPlaywright()
-
- monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
- config = BrowserConfig(browser_binary_path='dummy/chrome', extra_browser_args=['--dummy-arg'])
- browser_obj = Browser(config=config)
- result_browser = await browser_obj.get_playwright_browser()
- assert isinstance(result_browser, DummyBrowser), 'Expected DummyBrowser from _setup_user_provided_browser'
- await browser_obj.close()
-
-
-async def test_user_provided_browser_launch_on_custom_chrome_remote_debugging_port(monkeypatch):
- """
- Test that when a browser_binary_path and chrome_remote_debugging_port are provided, the Browser class uses
- _setup_user_provided_browser branch and returns the expected DummyBrowser object
- by launching a new Chrome instance with --remote-debugging-port=chrome_remote_debugging_port argument.
- """
-
- # Custom remote debugging port
- custom_chrome_remote_debugging_port = 9223
-
- # Dummy response for requests.get when checking chrome debugging endpoint.
- class DummyResponse:
- status_code = 200
-
- def dummy_get(url, timeout):
- if url == f'http://localhost:{custom_chrome_remote_debugging_port}/json/version':
- return DummyResponse()
- raise requests.ConnectionError('Connection failed')
-
- monkeypatch.setattr(requests, 'get', dummy_get)
-
- class DummyProcess:
- def __init__(self, *args, **kwargs):
- pass
-
- class DummySubProcess:
- pid = 1234
-
- async def dummy_create_subprocess_exec(browser_binary_path, *args, **kwargs):
- assert f'--remote-debugging-port={custom_chrome_remote_debugging_port}' in args, (
- f'Chrome must be started with with --remote-debugging-port={custom_chrome_remote_debugging_port} argument'
- )
-
- return DummySubProcess()
-
- monkeypatch.setattr(asyncio, 'create_subprocess_exec', dummy_create_subprocess_exec)
- monkeypatch.setattr(psutil, 'Process', DummyProcess)
-
- class DummyBrowser:
- pass
-
- class DummyChromium:
- async def connect_over_cdp(self, endpoint_url, timeout=20000):
- assert endpoint_url == f'http://localhost:{custom_chrome_remote_debugging_port}', (
- f"Endpoint URL must be 'http://localhost:{custom_chrome_remote_debugging_port}'"
- )
- return DummyBrowser()
-
- class DummyPlaywright:
- def __init__(self):
- self.chromium = DummyChromium()
-
- async def stop(self):
- pass
-
- class DummyAsyncPlaywrightContext:
- async def start(self):
- return DummyPlaywright()
-
- monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
-
- config = BrowserConfig(
- browser_binary_path='dummy/chrome',
- chrome_remote_debugging_port=custom_chrome_remote_debugging_port,
- extra_browser_args=['--dummy-arg'],
- )
-
- browser_obj = Browser(config=config)
- result_browser = await browser_obj.get_playwright_browser()
- assert isinstance(result_browser, DummyBrowser), (
- f'Expected DummyBrowser with remote debugging port {custom_chrome_remote_debugging_port} from _setup_user_provided_browser'
- )
- await browser_obj.close()
-
-
-async def test_builtin_browser_disable_security_args(monkeypatch):
- """
- Test that the standard browser launch includes disable-security arguments when disable_security is True.
- This verifies that _setup_builtin_browser correctly appends the security disabling arguments along with
- the base arguments and any extra arguments provided.
- """
- # These are the base arguments defined in _setup_builtin_browser.
- base_args = [
- '--no-sandbox',
- '--disable-blink-features=AutomationControlled',
- '--disable-infobars',
- '--disable-background-timer-throttling',
- '--disable-popup-blocking',
- '--disable-backgrounding-occluded-windows',
- '--disable-renderer-backgrounding',
- '--disable-window-activation',
- '--disable-focus-on-load',
- '--no-first-run',
- '--no-default-browser-check',
- '--no-startup-window',
- '--window-position=0,0',
- ]
- # When disable_security is True, these arguments should be added.
- disable_security_args = [
- '--disable-web-security',
- '--disable-site-isolation-trials',
- '--disable-features=IsolateOrigins,site-per-process',
- ]
- # Additional arbitrary argument for testing extra args
- extra_args = ['--dummy-extra']
-
- class DummyBrowser:
- pass
-
- class DummyChromium:
- async def launch(self, headless, args, proxy=None, handle_sigterm=False, handle_sigint=False):
- # Expected args is the base args plus disable security args and the extra args.
- expected_args = base_args + disable_security_args + extra_args
- assert headless is True, 'Expected headless to be True'
- assert args == expected_args, f'Expected args {expected_args}, but got {args}'
- assert proxy is None, 'Expected proxy to be None'
- return DummyBrowser()
-
- class DummyPlaywright:
- def __init__(self):
- self.chromium = DummyChromium()
-
- async def stop(self):
- pass
-
- class DummyAsyncPlaywrightContext:
- async def start(self):
- return DummyPlaywright()
-
- monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
- config = BrowserConfig(headless=True, disable_security=True, extra_browser_args=extra_args)
- browser_obj = Browser(config=config)
- result_browser = await browser_obj.get_playwright_browser()
- assert isinstance(result_browser, DummyBrowser), (
- 'Expected DummyBrowser from _setup_builtin_browser with disable_security active'
- )
- await browser_obj.close()
+ monkeypatch.setattr('browser_use.browser.session.async_playwright', lambda: DummyAsyncPlaywrightContext())
+ session = BrowserSession(headless=True, disable_security=False, extra_launch_args=['--test'])
+ await session.initialize()
+ assert isinstance(session.browser, DummyBrowser), 'Expected DummyBrowser from _launch_browser'
+ await session.close()
@pytest.mark.asyncio
async def test_new_context_creation():
"""
- Test that the new_context method returns a BrowserContext with the correct attributes.
- This verifies that the BrowserContext is initialized with the provided Browser instance and configuration.
- """
- config = BrowserConfig()
- browser_obj = Browser(config=config)
- custom_context_config = BrowserContextConfig()
- context = await browser_obj.new_context(custom_context_config)
- assert isinstance(context, BrowserContext), 'Expected new_context to return an instance of BrowserContext'
- assert context.browser is browser_obj, "Expected the context's browser attribute to be the Browser instance"
- assert context.config == custom_context_config, "Expected the context's config attribute to be the provided config"
- await browser_obj.close()
-
-
-async def test_user_provided_browser_launch_failure(monkeypatch):
- """
- Test that when a Chrome instance cannot be started or connected to,
- the Browser._setup_user_provided_browser branch eventually raises a RuntimeError.
- We simulate failure by:
- - Forcing requests.get to always raise a ConnectionError (so no existing instance is found).
- - Monkeypatching subprocess.Popen to do nothing.
- - Replacing asyncio.sleep to avoid delays.
- - Having the dummy playwright's connect_over_cdp method always raise an Exception.
- """
-
- def dummy_get(url, timeout):
- raise requests.ConnectionError('Simulated connection failure')
-
- monkeypatch.setattr(requests, 'get', dummy_get)
- monkeypatch.setattr(subprocess, 'Popen', lambda args, stdout, stderr: None)
-
- async def fake_sleep(seconds):
- return
-
- monkeypatch.setattr(asyncio, 'sleep', fake_sleep)
-
- class DummyChromium:
- async def connect_over_cdp(self, endpoint_url, timeout=20000):
- raise Exception('Connection failed simulation')
-
- class DummyPlaywright:
- def __init__(self):
- self.chromium = DummyChromium()
-
- async def stop(self):
- pass
-
- class DummyAsyncPlaywrightContext:
- async def start(self):
- return DummyPlaywright()
-
- monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
- config = BrowserConfig(browser_binary_path='dummy/chrome', extra_browser_args=['--dummy-arg'])
- browser_obj = Browser(config=config)
- with pytest.raises(RuntimeError, match='To start chrome in Debug mode'):
- await browser_obj.get_playwright_browser()
- await browser_obj.close()
-
-
-async def test_get_playwright_browser_caching(monkeypatch):
- """
- Test that get_playwright_browser returns a cached browser instance.
- On the first call, the browser is initialized; on subsequent calls,
- the same instance is returned.
- """
-
- class DummyBrowser:
- pass
-
- class DummyChromium:
- async def launch(self, headless, args, proxy=None, handle_sigterm=False, handle_sigint=False):
- return DummyBrowser()
-
- class DummyPlaywright:
- def __init__(self):
- self.chromium = DummyChromium()
-
- async def stop(self):
- pass
-
- class DummyAsyncPlaywrightContext:
- async def start(self):
- return DummyPlaywright()
-
- monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
- config = BrowserConfig(headless=True, disable_security=False, extra_browser_args=['--test'])
- browser_obj = Browser(config=config)
- first_browser = await browser_obj.get_playwright_browser()
- second_browser = await browser_obj.get_playwright_browser()
- assert first_browser is second_browser, 'Expected the browser to be cached and reused across calls.'
- await browser_obj.close()
-
-
-async def test_close_error_handling(monkeypatch):
- """
- Test that the close method properly handles exceptions thrown by
- playwright_browser.close() and playwright.stop(), ensuring that the
- browser's attributes are set to None even if errors occur.
- """
-
- class DummyBrowserWithError:
- async def close(self):
- raise Exception('Close error simulation')
-
- class DummyPlaywrightWithError:
- async def stop(self):
- raise Exception('Stop error simulation')
-
- config = BrowserConfig()
- browser_obj = Browser(config=config)
- browser_obj.playwright_browser = DummyBrowserWithError()
- browser_obj.playwright = DummyPlaywrightWithError()
- await browser_obj.close()
- assert browser_obj.playwright_browser is None, 'Expected playwright_browser to be None after close'
- assert browser_obj.playwright is None, 'Expected playwright to be None after close'
-
-
-async def test_standard_browser_launch_with_proxy(monkeypatch):
- """
- Test that when a proxy is provided in the BrowserConfig, the _setup_builtin_browser method
- correctly passes the proxy parameter to the playwright.chromium.launch method.
- This test sets up a dummy async_playwright context and verifies that the dummy proxy is received.
+ Test that the BrowserSession is initialized with the correct attributes.
+ This verifies that the BrowserSession is initialized with the provided profile configuration.
"""
-
- class DummyBrowser:
- pass
-
- # Create a dummy proxy settings instance.
- dummy_proxy = ProxySettings(server='http://dummy.proxy')
-
- class DummyChromium:
- async def launch(self, headless, args, proxy=None, handle_sigterm=False, handle_sigint=False):
- # Assert that the proxy passed equals the dummy proxy provided in the configuration.
- assert isinstance(proxy, dict) and proxy['server'] == 'http://dummy.proxy', (
- f'Expected proxy {dummy_proxy} but got {proxy}'
- )
- # We can also verify some base parameters if needed (headless, args) but our focus is proxy.
- return DummyBrowser()
-
- class DummyPlaywright:
- def __init__(self):
- self.chromium = DummyChromium()
-
- async def stop(self):
- pass
-
- class DummyAsyncPlaywrightContext:
- async def start(self):
- return DummyPlaywright()
-
- # Monkeypatch async_playwright to return our dummy async playwright context.
- monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
- # Create a BrowserConfig with the dummy proxy.
- config = BrowserConfig(headless=False, disable_security=False, proxy=dummy_proxy)
- browser_obj = Browser(config=config)
- # Call get_playwright_browser and verify that the returned browser is as expected.
- result_browser = await browser_obj.get_playwright_browser()
- assert isinstance(result_browser, DummyBrowser), 'Expected DummyBrowser from _setup_builtin_browser with proxy provided'
- await browser_obj.close()
-
-
-async def test_browser_window_size(monkeypatch):
- """
- Test that when window_width and window_height are provided in BrowserContextConfig,
- they're properly converted to a dictionary when passed to Playwright.
- """
-
- class DummyPage:
- def __init__(self):
- self.url = 'about:blank'
-
- async def goto(self, url):
- pass
-
- async def wait_for_load_state(self, state):
- pass
-
- async def title(self):
- return 'Test Page'
-
- async def bring_to_front(self):
- pass
-
- async def evaluate(self, script):
- return True
-
- def is_closed(self):
- return False
-
- class DummyContext:
- def __init__(self):
- self.pages = [DummyPage()]
- self.tracing = self
-
- async def new_page(self):
- return DummyPage()
-
- async def add_init_script(self, script):
- pass
-
- async def start(self):
- pass
-
- async def stop(self, path=None):
- pass
-
- def on(self, event, handler):
- pass
-
- async def close(self):
- pass
-
- async def grant_permissions(self, permissions, origin=None):
- pass
-
- class DummyBrowser:
- def __init__(self):
- self.contexts = []
-
- async def new_context(self, **kwargs):
- # Assert that record_video_size is a dictionary with expected values
- assert isinstance(kwargs['record_video_size'], dict), (
- f'Expected record_video_size to be a dictionary, got {type(kwargs["record_video_size"])}'
- )
- assert kwargs['record_video_size']['width'] == 1280, (
- f'Expected width to be 1280, got {kwargs["record_video_size"].get("width")}'
- )
- assert kwargs['record_video_size']['height'] == 1100, (
- f'Expected height to be 1100, got {kwargs["record_video_size"].get("height")}'
- )
-
- context = DummyContext()
- self.contexts.append(context)
- return context
-
- async def close(self):
- pass
-
- class DummyPlaywright:
- def __init__(self):
- self.chromium = self
-
- async def launch(self, **kwargs):
- return DummyBrowser()
-
- async def stop(self):
- pass
-
- class DummyAsyncPlaywrightContext:
- async def start(self):
- return DummyPlaywright()
-
- # Monkeypatch async_playwright to return our dummy async playwright context
- monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
-
- # Create browser with default config
- browser_obj = Browser()
-
- # Get browser instance
- playwright_browser = await browser_obj.get_playwright_browser()
-
- # Create context config with specific window size
- context_config = BrowserContextConfig(window_width=1280, window_height=1100)
-
- # Create browser context - this will test if window dimensions are properly converted
- browser_context = BrowserContext(browser=browser_obj, config=context_config)
- await browser_context._initialize_session()
-
- # Clean up
- await browser_context.close()
- await browser_obj.close()
+ profile = BrowserProfile()
+ session = BrowserSession(profile=profile)
+ await session.initialize()
+ assert session.profile == profile, "Expected the session's profile to be the provided profile"
+ await session.close()
diff --git a/tests/test_context.py b/tests/test_context.py
index b4d5a2ad5..5d705384e 100644
--- a/tests/test_context.py
+++ b/tests/test_context.py
@@ -3,7 +3,7 @@ from unittest.mock import Mock
import pytest
-from browser_use.browser.context import BrowserContext, BrowserContextConfig
+from browser_use.browser import BrowserContext, BrowserContextConfig
from browser_use.browser.views import BrowserState
from browser_use.dom.views import DOMElementNode