Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
new BrowserSession and BrowserProfile design, renamed BrowserState to BrowserStateSummary and more
Nick Sweeting86ec6a78b033
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex 5307c39d8..dca76ceb3 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -14,7 +14,7 @@ from pydantic import BaseModelfrom browser_use.agent.message_manager.views import MessageMetadatafrom browser_use.agent.prompts import AgentMessagePromptfrom browser_use.agent.views import ActionResult, AgentOutput, AgentStepInfo, MessageManagerState-from browser_use.browser.views import BrowserState+from browser_use.browser.views import BrowserStateSummaryfrom browser_use.utils import time_execution_synclogger = logging.getLogger(__name__)@@ -121,7 +121,7 @@ class MessageManager:@time_execution_sync('--add_state_message')def add_state_message(self,- state: BrowserState,+ browser_state_summary: BrowserStateSummary,result: list[ActionResult] | None = None,step_info: AgentStepInfo | None = None,use_vision=True,@@ -147,7 +147,7 @@ class MessageManager:# otherwise add state message and result to next message (which will not stay in memory)state_message = AgentMessagePrompt(- state,+ browser_state_summary,result,include_attributes=self.settings.include_attributes,step_info=step_info,diff --git a/browser_use/agent/message_manager/tests.py b/browser_use/agent/message_manager/tests.pyindex 94c1beb59..506f829aa 100644--- a/browser_use/agent/message_manager/tests.py+++ b/browser_use/agent/message_manager/tests.py@@ -5,7 +5,7 @@ from langchain_openai import AzureChatOpenAI, ChatOpenAIfrom browser_use.agent.message_manager.service import MessageManager, MessageManagerSettingsfrom browser_use.agent.views import ActionResult-from browser_use.browser.views import BrowserState, TabInfo+from browser_use.browser.views import BrowserStateSummary, TabInfofrom browser_use.dom.views import DOMElementNode, DOMTextNode@@ -42,7 +42,7 @@ def test_initial_messages(message_manager: MessageManager):def test_add_state_message(message_manager: MessageManager):"""Test adding browser state message"""- state = BrowserState(+ state = BrowserStateSummary(url='https://test.com',title='Test Page',element_tree=DOMElementNode(@@ -66,7 +66,7 @@ def test_add_state_message(message_manager: MessageManager):def test_add_state_with_memory_result(message_manager: MessageManager):"""Test adding state with result that should be included in memory"""- state = BrowserState(+ state = BrowserStateSummary(url='https://test.com',title='Test Page',element_tree=DOMElementNode(@@ -95,7 +95,7 @@ def test_add_state_with_memory_result(message_manager: MessageManager):def test_add_state_with_non_memory_result(message_manager: MessageManager):"""Test adding state with result that should not be included in memory"""- state = BrowserState(+ state = BrowserStateSummary(url='https://test.com',title='Test Page',element_tree=DOMElementNode(@@ -130,7 +130,7 @@ def test_token_overflow_handling_with_real_flow(message_manager: MessageManager,# Create a long sequence of interactionsfor i in range(200): # Simulate 40 steps of interaction# Create state with varying content length- state = BrowserState(+ state = BrowserStateSummary(url=f'https://test{i}.com',title=f'Test Page {i}',element_tree=DOMElementNode(diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex b37c06486..29de20b7c 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -6,7 +6,7 @@ from langchain_core.messages import HumanMessage, SystemMessageif TYPE_CHECKING:from browser_use.agent.views import ActionResult, AgentStepInfo- from browser_use.browser.views import BrowserState+ from browser_use.browser.views import BrowserStateSummaryclass SystemPrompt:@@ -62,12 +62,12 @@ class SystemPrompt:class AgentMessagePrompt:def __init__(self,- state: 'BrowserState',+ browser_state_summary: 'BrowserStateSummary',result: list['ActionResult'] | None = None,include_attributes: list[str] | None = None,step_info: Optional['AgentStepInfo'] = None,):- self.state = state+ self.state = browser_state_summaryself.result = resultself.include_attributes = include_attributes or []self.step_info = step_infodiff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex c0f18a68c..0e23c6fb8 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -51,7 +51,7 @@ from browser_use.agent.views import (from browser_use.browser import BrowserProfile, BrowserSession# from lmnr.sdk.decorators import observe-from browser_use.browser.views import BrowserState+from browser_use.browser.views import BrowserStateSummaryfrom browser_use.controller.registry.views import ActionModelfrom browser_use.controller.service import Controllerfrom browser_use.dom.history_tree_processor.service import (@@ -109,8 +109,8 @@ class Agent(Generic[Context]):initial_actions: list[dict[str, dict[str, Any]]] | None = None,# Cloud Callbacksregister_new_step_callback: (- Callable[['BrowserState', 'AgentOutput', int], None] # Sync callback- | Callable[['BrowserState', 'AgentOutput', int], Awaitable[None]] # Async callback+ Callable[['BrowserStateSummary', 'AgentOutput', int], None] # Sync callback+ | Callable[['BrowserStateSummary', 'AgentOutput', int], Awaitable[None]] # Async callback| None) = None,register_done_callback: (@@ -321,7 +321,7 @@ class Agent(Generic[Context]):self.register_external_agent_status_raise_error_callback = register_external_agent_status_raise_error_callback# Context- self.context = context+ self.context: Context | None = context# Telemetryself.telemetry = ProductTelemetry()@@ -460,7 +460,7 @@ class Agent(Generic[Context]):tokens = 0try:- state = await self.browser_session.get_state(cache_clickable_elements_hashes=True)+ browser_state_summary = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=True)current_page = await self.browser_session.get_current_page()# generate procedural memory if needed@@ -551,9 +551,9 @@ class Agent(Generic[Context]):if self.register_new_step_callback:if inspect.iscoroutinefunction(self.register_new_step_callback):- await self.register_new_step_callback(state, model_output, self.state.n_steps)+ await self.register_new_step_callback(browser_state_summary, model_output, self.state.n_steps)else:- self.register_new_step_callback(state, model_output, self.state.n_steps)+ self.register_new_step_callback(browser_state_summary, model_output, self.state.n_steps)if self.settings.save_conversation_path:target = self.settings.save_conversation_path + f'_{self.state.n_steps}.txt'save_conversation(input_messages, model_output, target, self.settings.save_conversation_path_encoding)@@ -615,7 +615,7 @@ class Agent(Generic[Context]):step_end_time=step_end_time,input_tokens=tokens,)- self._make_history_item(model_output, state, result, metadata)+ self._make_history_item(model_output, browser_state_summary, result, metadata)@time_execution_async('--handle_step_error (agent)')async def _handle_step_error(self, error: Exception) -> list[ActionResult]:@@ -665,23 +665,23 @@ class Agent(Generic[Context]):def _make_history_item(self,model_output: AgentOutput | None,- state: BrowserState,+ browser_state_summary: BrowserStateSummary,result: list[ActionResult],metadata: StepMetadata | None = None,) -> None:"""Create and store history item"""if model_output:- interacted_elements = AgentHistory.get_interacted_element(model_output, state.selector_map)+ interacted_elements = AgentHistory.get_interacted_element(model_output, browser_state_summary.selector_map)else:interacted_elements = [None]state_history = BrowserStateHistory(- url=state.url,- title=state.title,- tabs=state.tabs,+ url=browser_state_summary.url,+ title=browser_state_summary.title,+ tabs=browser_state_summary.tabs,interacted_element=interacted_elements,- screenshot=state.screenshot,+ screenshot=browser_state_summary.screenshot,)history_item = AgentHistory(model_output=model_output, result=result, state=state_history, metadata=metadata)@@ -1032,8 +1032,8 @@ class Agent(Generic[Context]):for i, action in enumerate(actions):if action.get_index() is not None and i != 0:- new_state = await self.browser_session.get_state(cache_clickable_elements_hashes=False)- new_selector_map = new_state.selector_map+ new_browser_state_summary = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=False)+ new_selector_map = new_browser_state_summary.selector_map# Detect index change after previous actionorig_target = cached_selector_map.get(action.get_index()) # type: ignore@@ -1058,11 +1058,11 @@ class Agent(Generic[Context]):await self._raise_if_stopped_or_paused()result = await self.controller.act(- action,- self.browser_session,- self.settings.page_extraction_llm,- self.sensitive_data,- self.settings.available_file_paths,+ action=action,+ browser_session=self.browser_session,+ page_extraction_llm=self.settings.page_extraction_llm,+ sensitive_data=self.sensitive_data,+ available_file_paths=self.settings.available_file_paths,context=self.context,)@@ -1099,9 +1099,9 @@ class Agent(Generic[Context]):)if self.browser_context:- state = await self.browser_session.get_state(cache_clickable_elements_hashes=False)+ browser_state_summary = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=False)content = AgentMessagePrompt(- state=state,+ state=browser_state_summary,result=self.state.last_result,include_attributes=self.settings.include_attributes,)@@ -1209,7 +1209,7 @@ class Agent(Generic[Context]):async def _execute_history_step(self, history_item: AgentHistory, delay: float) -> list[ActionResult]:"""Execute a single step from history with element validation"""- state = await self.browser_context.get_state(cache_clickable_elements_hashes=False)+ state = await self.browser_context.get_state_summary(cache_clickable_elements_hashes=False)if not state or not history_item.model_output:raise ValueError('Invalid state or model output')updated_actions = []@@ -1233,16 +1233,18 @@ class Agent(Generic[Context]):self,historical_element: DOMHistoryElement | None,action: ActionModel, # Type this properly based on your action model- current_state: BrowserState,+ browser_state_summary: BrowserStateSummary,) -> ActionModel | None:"""Update action indices based on current page state.Returns updated action or None if element cannot be found."""- if not historical_element or not current_state.element_tree:+ if not historical_element or not browser_state_summary.element_tree:return action- current_element = HistoryTreeProcessor.find_history_element_in_tree(historical_element, current_state.element_tree)+ current_element = HistoryTreeProcessor.find_history_element_in_tree(+ historical_element, browser_state_summary.element_tree+ )if not current_element or current_element.highlight_index is None:return Nonediff --git a/browser_use/agent/tests.py b/browser_use/agent/tests.pyindex a0d084cc7..5f58a8e21 100644--- a/browser_use/agent/tests.py+++ b/browser_use/agent/tests.py@@ -7,7 +7,7 @@ from browser_use.agent.views import (AgentHistoryList,AgentOutput,)-from browser_use.browser.views import BrowserState, BrowserStateHistory, TabInfo+from browser_use.browser.views import BrowserStateHistory, BrowserStateSummary, TabInfofrom browser_use.controller.registry.service import Registryfrom browser_use.controller.views import ClickElementAction, DoneAction, ExtractPageContentActionfrom browser_use.dom.views import DOMElementNode@@ -15,7 +15,7 @@ from browser_use.dom.views import DOMElementNode@pytest.fixturedef sample_browser_state():- return BrowserState(+ return BrowserStateSummary(url='https://example.com',title='Example Page',tabs=[TabInfo(url='https://example.com', title='Example Page', page_id=1)],diff --git a/browser_use/browser/extensions.py b/browser_use/browser/extensions.pynew file mode 100644index 000000000..675deb48a--- /dev/null+++ b/browser_use/browser/extensions.py@@ -0,0 +1,413 @@+# import asyncio+# import hashlib+# import json+# import logging+# import subprocess+# import zipfile+# from pathlib import Path++# import aiohttp+# import anyio++# logger = logging.getLogger(__name__)+++# def get_extension_id(unpacked_path: str | Path) -> str | None:+# manifest_path = Path(unpacked_path) / 'manifest.json'+# if not manifest_path.exists():+# return None++# # chrome uses a SHA256 hash of the unpacked extension directory path to compute a dynamic id for unpacked extensions+# hash_obj = hashlib.sha256()+# hash_obj.update(str(unpacked_path).encode('utf-8'))+# detected_extension_id = ''.join(chr(int(h, 16) + ord('a')) for h in hash_obj.hexdigest()[:32])+# return detected_extension_id+++# async def install_extension(extension: dict) -> bool:+# manifest_path = Path(extension['unpacked_path']) / 'manifest.json'+# crx_path = Path(extension['crx_path'])++# # Download extensions using:+# # curl -fsSL 'https://clients2.google.com/service/update2/crx?response=redirect&prodversion=1230&acceptformat=crx3&x=id%3D${EXTENSION_ID}%26uc' > extensionname.crx+# # unzip -d extensionname extensionname.crx++# if not manifest_path.exists() and not crx_path.exists():+# logger.info(f'[๐ ๏ธ] Downloading missing extension {extension["name"]} {extension["webstore_id"]} -> {crx_path}')++# # Download crx file from ext.crx_url -> ext.crx_path+# async with aiohttp.ClientSession() as session:+# async with session.get(extension['crx_url']) as response:+# if response.headers.get('content-length') and response.content:+# async with anyio.open(crx_path, 'wb') as f:+# await f.write(await response.read())+# else:+# logger.warning(f'[โ ๏ธ] Failed to download extension {extension["name"]} {extension["webstore_id"]}')+# return False++# # Unzip crx file from ext.crx_url -> ext.unpacked_path+# unpacked_path = Path(extension['unpacked_path'])+# unpacked_path.mkdir(parents=True, exist_ok=True)++# try:+# # Try system unzip first+# result = subprocess.run(['/usr/bin/unzip', str(crx_path), '-d', str(unpacked_path)], capture_output=True, text=True)+# stdout, stderr = result.stdout, result.stderr+# except Exception as err1:+# try:+# # Fallback to Python's zipfile+# with zipfile.ZipFile(crx_path) as zf:+# zf.extractall(unpacked_path)+# stdout, stderr = '', ''+# except Exception as err2:+# logger.error(f'[โ] Failed to install {crx_path}: could not unzip crx', exc_info=(err1, err2))+# return False++# if not manifest_path.exists():+# logger.error(f'[โ] Failed to install {crx_path}: could not find manifest.json in unpacked_path', stdout, stderr)+# return False++# return True+++# async def load_or_install_extension(ext: dict) -> dict:+# if not (ext.get('webstore_id') or ext.get('unpacked_path')):+# raise ValueError('Extension must have either webstore_id or unpacked_path')++# # Set statically computable extension metadata+# ext['webstore_id'] = ext.get('webstore_id') or ext.get('id')+# ext['name'] = ext.get('name') or ext['webstore_id']+# ext['webstore_url'] = ext.get('webstore_url') or f'https://chromewebstore.google.com/detail/{ext["webstore_id"]}'+# ext['crx_url'] = (+# ext.get('crx_url')+# or f'https://clients2.google.com/service/update2/crx?response=redirect&prodversion=1230&acceptformat=crx3&x=id%3D{ext["webstore_id"]}%26uc'+# )+# ext['crx_path'] = ext.get('crx_path') or str(Path(CHROME_EXTENSIONS_DIR) / f'{ext["webstore_id"]}__{ext["name"]}.crx')+# ext['unpacked_path'] = ext.get('unpacked_path') or str(Path(CHROME_EXTENSIONS_DIR) / f'{ext["webstore_id"]}__{ext["name"]}')++# manifest_path = Path(ext['unpacked_path']) / 'manifest.json'++# def read_manifest():+# with open(manifest_path) as f:+# return json.load(f)++# def read_version():+# return manifest_path.exists() and read_manifest().get('version')++# ext['read_manifest'] = read_manifest+# ext['read_version'] = read_version++# # if extension is not installed, download and unpack it+# if not ext['read_version']():+# await install_extension(ext)++# # autodetect id from filesystem path (unpacked extensions dont have stable IDs)+# ext['id'] = get_extension_id(ext['unpacked_path'])+# ext['version'] = ext['read_version']()++# if not ext['version']:+# logger.warning(f'[โ] Unable to detect ID and version of installed extension {pretty_path(ext["unpacked_path"])}')+# else:+# logger.info(f'[โ] Installed extension {ext["name"]} ({ext["version"]})...'.ljust(82) + pretty_path(ext['unpacked_path']))++# return ext+++# async def is_target_extension(target):+# target_type = None+# target_ctx = None+# target_url = None+# try:+# target_type = await target.type+# target_ctx = await target.worker() or await target.page() or None+# target_url = await target.url or (await target_ctx.url if target_ctx else None)+# except Exception as err:+# if 'No target with given id found' in str(err):+# # because this runs on initial browser startup, we sometimes race with closing the initial+# # new tab page. it will throw a harmless error if we try to check a target that's already closed,+# # ignore it and return null since that page is definitely not an extension's bg page anyway+# target_type = 'closed'+# target_ctx = None+# target_url = 'about:closed'+# else:+# raise err++# target_is_bg = target_type in ['service_worker', 'background_page']+# target_is_extension = target_url and target_url.startswith('chrome-extension://')+# extension_id = target_url.split('://')[1].split('/')[0] if target_is_extension else None+# manifest_version = '3' if target_type == 'service_worker' else '2'++# return {+# 'target_type': target_type,+# 'target_ctx': target_ctx,+# 'target_url': target_url,+# 'target_is_bg': target_is_bg,+# 'target_is_extension': target_is_extension,+# 'extension_id': extension_id,+# 'manifest_version': manifest_version,+# }+++# async def load_extension_from_target(extensions, target):+# extension_info = await is_target_extension(target)+# target_is_bg = extension_info['target_is_bg']+# target_is_extension = extension_info['target_is_extension']+# target_type = extension_info['target_type']+# target_ctx = extension_info['target_ctx']+# target_url = extension_info['target_url']+# extension_id = extension_info['extension_id']+# manifest_version = extension_info['manifest_version']++# if not (target_is_bg and extension_id and target_ctx):+# return None++# manifest = await target_ctx.evaluate('() => chrome.runtime.getManifest()')++# name = manifest.get('name')+# version = manifest.get('version')+# homepage_url = manifest.get('homepage_url')+# options_page = manifest.get('options_page')+# options_ui = manifest.get('options_ui', {})++# if not version or not extension_id:+# return None++# options_url = await target_ctx.evaluate(+# '(options_page) => chrome.runtime.getURL(options_page)',+# options_page or options_ui.get('page') or 'options.html',+# )++# commands = await target_ctx.evaluate("""+# async () => {+# return await new Promise((resolve, reject) => {+# if (chrome.commands)+# chrome.commands.getAll(resolve)+# else+# resolve({})+# })+# }+# """)++# # logger.debug(f"[+] Found Manifest V{manifest_version} Extension: {extension_id} {name} {target_url} {len(commands)}")++# async def dispatch_eval(*args):+# return await target_ctx.evaluate(*args)++# async def dispatch_popup():+# return await target_ctx.evaluate(+# "() => chrome.action?.openPopup() || chrome.tabs.create({url: chrome.runtime.getURL('popup.html')})"+# )++# if manifest_version == '3':++# async def dispatch_action(tab=None):+# # https://developer.chrome.com/docs/extensions/reference/api/action#event-onClicked+# return await target_ctx.evaluate(+# """+# async (tab) => {+# tab = tab || (await new Promise((resolve) =>+# chrome.tabs.query({currentWindow: true, active: true}, ([tab]) => resolve(tab))))+# return await chrome.action.onClicked.dispatch(tab)+# }+# """,+# tab,+# )++# async def dispatch_message(message, options=None):+# # https://developer.chrome.com/docs/extensions/reference/api/runtime+# return await target_ctx.evaluate(+# """+# async (extension_id, message, options) => {+# return await chrome.runtime.sendMessage(extension_id, message, options)+# }+# """,+# extension_id,+# message,+# options,+# )++# async def dispatch_command(command, tab=None):+# # https://developer.chrome.com/docs/extensions/reference/api/commands#event-onCommand+# return await target_ctx.evaluate(+# """+# async (command, tab) => {+# return await chrome.commands.onCommand.dispatch(command, tab)+# }+# """,+# command,+# tab,+# )++# elif manifest_version == '2':++# async def dispatch_action(tab=None):+# # https://developer.chrome.com/docs/extensions/mv2/reference/browserAction#event-onClicked+# return await target_ctx.evaluate(+# """+# async (tab) => {+# tab = tab || (await new Promise((resolve) =>+# chrome.tabs.query({currentWindow: true, active: true}, ([tab]) => resolve(tab))))+# return await chrome.browserAction.onClicked.dispatch(tab)+# }+# """,+# tab,+# )++# async def dispatch_message(message, options=None):+# # https://developer.chrome.com/docs/extensions/mv2/reference/runtime#method-sendMessage+# return await target_ctx.evaluate(+# """+# async (extension_id, message, options) => {+# return await new Promise((resolve) =>+# chrome.runtime.sendMessage(extension_id, message, options, resolve)+# )+# }+# """,+# extension_id,+# message,+# options,+# )++# async def dispatch_command(command, tab=None):+# # https://developer.chrome.com/docs/extensions/mv2/reference/commands#event-onCommand+# return await target_ctx.evaluate(+# """+# async (command, tab) => {+# return await new Promise((resolve) =>+# chrome.commands.onCommand.dispatch(command, tab, resolve)+# )+# }+# """,+# command,+# tab,+# )++# existing_extension = next((ext for ext in extensions if ext.get('id') == extension_id), {})++# new_extension = {+# **existing_extension,+# 'id': extension_id,+# 'webstore_name': name,+# 'target': target,+# 'target_ctx': target_ctx,+# 'target_type': target_type,+# 'target_url': target_url,+# 'manifest_version': manifest_version,+# 'manifest': manifest,+# 'version': version,+# 'homepage_url': homepage_url,+# 'options_url': options_url,+# 'dispatch_eval': dispatch_eval, # run some JS in the extension's service worker context+# 'dispatch_popup': dispatch_popup, # open the extension popup+# 'dispatch_action': dispatch_action, # trigger an extension menubar icon click+# 'dispatch_message': dispatch_message, # send a chrome runtime message in the service worker context+# 'dispatch_command': dispatch_command, # trigger an extension keyboard shortcut command+# }++# logger.info(f'[โ] Loaded extension {name[:32]} ({version}) {target_type}...'.ljust(82) + target_url)+# existing_extension.update(new_extension)++# return new_extension+++# async def get_chrome_extensions_from_persona(CHROME_EXTENSIONS, CHROME_EXTENSIONS_DIR):+# logger.info('*************************************************************************')+# logger.info(f'[โ๏ธ] Installing {len(CHROME_EXTENSIONS)} chrome extensions from CHROME_EXTENSIONS...')+# try:+# # read extension metadata from filesystem (installing from Chrome webstore if extension is missing)+# for extension in CHROME_EXTENSIONS:+# extension.update(await load_or_install_extension(extension))++# # for easier debugging, write parsed extension info to filesystem+# await overwrite_file(+# CHROME_EXTENSIONS_JSON_PATH.replace('.json', '.present.json'),+# CHROME_EXTENSIONS,+# )+# except Exception as err:+# logger.error(err)+# logger.info('*************************************************************************')+# return CHROME_EXTENSIONS+++# _EXTENSIONS_CACHE = None+++# async def get_chrome_extensions_from_cache(browser, extensions=None, extensions_dir=None):+# global _EXTENSIONS_CACHE++# if extensions is None:+# extensions = CHROME_EXTENSIONS+# if extensions_dir is None:+# extensions_dir = CHROME_EXTENSIONS_DIR++# if _EXTENSIONS_CACHE is None:+# logger.info(f'[โ๏ธ] Loading {len(extensions)} chrome extensions from CHROME_EXTENSIONS...')++# # find loaded Extensions at runtime / browser launch time & connect handlers+# # looks at all the open targets for extension service workers / bg pages+# for target in await browser.targets():+# # mutates extensions object in-place to add metadata loaded from filesystem persona dir+# await load_extension_from_target(extensions, target)+# _EXTENSIONS_CACHE = extensions++# # write installed extension metadata to filesystem extensions.json for easier debugging+# await overwrite_file(+# CHROME_EXTENSIONS_JSON_PATH.replace('.json', '.loaded.json'),+# extensions,+# )+# await overwrite_symlink(+# CHROME_EXTENSIONS_JSON_PATH.replace('.json', '.loaded.json'),+# CHROME_EXTENSIONS_JSON_PATH,+# )++# return _EXTENSIONS_CACHE+++# async def setup_2captcha_extension(browser, extensions):+# page = None+# try:+# # open a new tab to finish setting up the 2captcha extension manually using its extension options page+# page = await browser.new_page()+# options_url = next((ext.get('options_url') for ext in extensions if ext.get('name') == 'captcha2'), None)+# await page.goto(options_url)+# await asyncio.sleep(2.5)+# await page.bring_to_front()++# # type in the API key and click the Login button (and auto-close success modal after it pops up)+# await page.evaluate("""() => {+# const elem = document.querySelector("input[name=apiKey]");+# elem.value = "";+# }""")+# await page.type('input[name=apiKey]', API_KEY_2CAPTCHA, delay=25)++# # toggle all the important switches to ON+# await page.evaluate("""() => {+# const checkboxes = Array.from(document.querySelectorAll('input#isPluginEnabled, input[name*=enabledFor], input[name*=autoSolve]'));+# for (const checkbox of checkboxes) {+# if (!checkbox.checked) checkbox.click();+# }+# }""")++# dialog_opened = False++# async def handle_dialog(dialog):+# nonlocal dialog_opened+# await asyncio.sleep(0.5)+# await dialog.accept()+# dialog_opened = True++# page.on('dialog', handle_dialog)+# await page.click('button#connect')+# await asyncio.sleep(2.5)++# if not dialog_opened:+# raise ValueError(+# f'2captcha extension login confirmation dialog never opened, please check its options page manually: {options_url}'+# )++# logger.info('[๐] Configured the 2captcha extension using its options page...')+# except Exception as err:+# logger.warning(f'[โ] Failed to configure the 2captcha extension using its options page! {err}')++# if page:+# await page.close()diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex b73dadaa8..fd757cc61 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -1,9 +1,13 @@from __future__ import annotationsimport asyncio+import base64import jsonimport loggingimport os+import re+import time+from dataclasses import dataclassfrom functools import wrapsfrom pathlib import Pathfrom typing import Any, Self@@ -11,10 +15,20 @@ from typing import Any, Selfimport psutilfrom playwright.async_api import Browser as PlaywrightBrowserfrom 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 playwright.async_api import ElementHandle, FrameLocator, Page, Playwright, async_playwright+from pydantic import AliasChoices, BaseModel, ConfigDict, Field, InstanceOf, PrivateAttr, model_validatorfrom browser_use.browser.types import BrowserProfile+from browser_use.browser.views import (+ BrowserError,+ BrowserStateSummary,+ 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# Check if running in DockerIN_DOCKER = os.environ.get('IN_DOCKER', 'false').lower()[0] in 'ty1'@@ -22,6 +36,9 @@ IN_DOCKER = os.environ.get('IN_DOCKER', 'false').lower()[0] in 'ty1'logger = logging.getLogger('browser_use.browser.session')+_GLOB_WARNING_SHOWN = False # used inside _is_url_allowed to avoid spamming the logs with the same warning multiple times++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.', '')@@ -37,6 +54,16 @@ def require_initialization(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')+ if not self.agent_current_page or self.agent_current_page.is_closed():+ self.agent_current_page = self.browser_context.pages[0] if self.browser_context.pages else None++ if not self.agent_current_page or self.agent_current_page.is_closed():+ self.create_new_tab()+ assert self.agent_current_page and not self.agent_current_page.is_closed()++ if not hasattr(self, '_cached_browser_state_summary'):+ raise RuntimeError('BrowserSession(...).start() must be called first to initialize the browser session')+return func(self, *args, **kwargs)return wrapper@@ -45,6 +72,16 @@ def require_initialization(func):DEFAULT_BROWSER_PROFILE = BrowserProfile()+@dataclass+class CachedClickableElementHashes:+ """+ Clickable elements hashes for the last state+ """++ url: str+ hashes: set[str]++class BrowserSession(BaseModel):"""Represents an active browser session with a running browser process somewhere.@@ -54,17 +91,24 @@ class BrowserSession(BaseModel):"""model_config = ConfigDict(- extra='allow', validate_assignment=False, revalidate_instances='always', frozen=False, arbitrary_types_allowed=True+ extra='allow',+ validate_assignment=False,+ revalidate_instances='always',+ frozen=False,+ arbitrary_types_allowed=True,+ populate_by_name=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 copybrowser_profile: InstanceOf[BrowserProfile] = Field(- default=DEFAULT_BROWSER_PROFILE, description='BrowserProfile() instance containing config for the BrowserSession'+ default=DEFAULT_BROWSER_PROFILE,+ description='BrowserProfile() instance containing config for the BrowserSession',+ validation_alias=AliasChoices('profile', 'config', 'new_context_config'), # old names for this field, remove eventually)- # runtime state: connection and process handles+ # runtime props/state: these can be passed in as props at init, or get auto-setup by BrowserSession.start()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()',@@ -73,45 +117,86 @@ class BrowserSession(BaseModel):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)'+ chrome_pid: int | None = Field(+ default=None, description='pid of the running chrome process to connect to on localhost (optional)')playwright: Playwright | None = Field(- default=None, description='Playwright library object returned by (playwright or patchright).async_playwright().start()'+ default=None,+ description='Playwright library object returned by (playwright or patchright).async_playwright().start()',+ exclude=True,+ )+ browser: InstanceOf[PlaywrightBrowser] | None = Field(+ default=None,+ description='playwright Browser object to use (optional)',+ validation_alias=AliasChoices('playwright_browser'),+ exclude=True,)- 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)'+ default=None,+ description='playwright BrowserContext object to use (optional)',+ validation_alias=AliasChoices('playwright_browser_context', 'context'),+ exclude=True,)initialized: bool = Field(- default=False, description='Skip BrowserSession launch/connection setup entirely if True (not recommended)'+ default=False,+ description='Skip BrowserSession launch/connection setup entirely if True (not recommended)',+ validation_alias=AliasChoices('initialized', 'is_initialized'),)# 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')+ agent_current_page: InstanceOf[Page] | None = Field( # mutated by self.create_new_tab(url)+ default=None,+ description='Foreground Page that the agent is focused on',+ validation_alias=AliasChoices('current_page', 'page'),+ exclude=True,+ )+ human_current_page: InstanceOf[Page] | None = Field( # mutated by self.setup_foreground_tab_detection()+ default=None,+ description='Foreground Page that the human is focused on',+ exclude=True,+ )- def __getattr__(self, key: str) -> Any:- # fall back to getting attributes from BrowserProfile when not found on BrowserSession- return getattr(self.browser_profile, key)+ _cached_browser_state_summary: BrowserStateSummary | None = PrivateAttr(default=None)+ _cached_clickable_element_hashes: CachedClickableElementHashes | None = PrivateAttr(default=None)@model_validator(mode='after')def apply_session_overrides_to_profile(self) -> Self:+ """Apply any extra **kwargs passed to BrowserSession(...) as config overrides on top of browser_profile"""session_own_fields = type(self).model_fields.keys()++ # get all the extra BrowserProfile kwarg overrides passed to BrowserSession(...) that are not Fields on selfoverrides = self.model_dump(exclude=session_own_fields)++ # FOR REPL DEBUGGING ONLY, NEVER ALLOW CIRCULAR REFERENCES IN REAL CODE:+ # self.browser_profile._in_use_by_session = self++ # replace browser_profile with patched versionself.browser_profile = self.browser_profile.model_copy(update=overrides)++ # FOR REPL DEBUGGING ONLY, NEVER ALLOW CIRCULAR REFERENCES IN REAL CODE:+ # self.browser_profile._in_use_by_session = self+return self+ # def __getattr__(self, key: str) -> Any:+ # """+ # fall back to getting any attrs from the underlying self.browser_profile when not defined on self.+ # (extra kwargs passed e.g. BrowserSession(extra_kwarg=124) on init get saved into self.browser_profile on validation,+ # so this also allows you to read those: browser_session.extra_kwarg => browser_session.browser_profile.extra_kwarg)+ # """+ # return getattr(self.browser_profile, key)+async def start(self) -> Self:- # unlock the user data dir for first-run initialization+ # finish initializing/validate the browser_profile:assert isinstance(self.browser_profile, BrowserProfile)- self.browser_profile.prepare_user_data_dir()- self.browser_profile.detect_display_configuration()+ self.browser_profile.prepare_user_data_dir() # create/unlock the <user_data_dir>/SingletonLock+ self.browser_profile.detect_display_configuration() # adjusts config values, must come before launch/connect- # setup playwright, Browser, and BrowserContext objects+ # launch/connect to the browser:+ # setup playwright library client, Browser, and BrowserContext objectsawait self.setup_playwright()- await self.setup_browser_connection()- await self.setup_browser_context()+ await self.setup_browser_connection() # connects to existing browser if available+ await self.setup_browser_context() # creates a new context in existing browser or launches a new persistent contextassert self.browser_context# resize the existing pages and set up foreground tab detection@@ -125,12 +210,28 @@ class BrowserSession(BaseModel):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()+ if self.browser_context:+ try:+ await self.browser_context.close()+ except Exception as e:+ logger.debug(f'โ Error closing playwright BrowserContext {self.browser_context}: {type(e).__name__}: {e}')++ if self.browser:+ try:+ await self.browser.close()+ except Exception as e:+ logger.debug(f'โ Error closing playwright Browser {self.browser}: {type(e).__name__}: {e}')# kill the chrome subprocess if we were the ones that started it- if self.chrome_process:- self.chrome_process.terminate()+ if self.chrome_pid:+ try:+ psutil.Process(pid=self.chrome_pid).terminate()+ except Exception as e:+ logger.debug(f'โ Error terminating chrome subprocess pid={self.chrome_pid}: {type(e).__name__}: {e}')++ async def close(self) -> None:+ """Shortcut for self.stop()"""+ await self.stop()async def __aenter__(self) -> BrowserSession:await self.start()@@ -148,18 +249,17 @@ class BrowserSession(BaseModel):"""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()+ if self.chrome_pid:+ chrome_process = psutil.Process(pid=self.chrome_pid)+ assert chrome_process.is_running(), 'Chrome process is not running'+ args = 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()}'+ f'Could not connect because could not find --remote-debugging-port=... in chrome launch args: pid={self.chrome_pid} {args}')# we could automatically relaunch the browser process with that arg added here, but they may have tabs open they dont want to loseself.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}')+ logger.info(f'๐ Connecting to existing chromium process: pid={self.chrome_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}')@@ -217,20 +317,30 @@ class BrowserSession(BaseModel):# 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()+ if not self.browser_profile.user_data_dir:+ # if no user_data_dir is provided, launch an incognito context with no persistent user_data_dir+ self.browser = self.browser or await self.playwright.chromium.launch(+ **self.browser_profile.kwargs_for_launch().model_dump()+ )+ self.browser_context = await self.browser.new_context(+ **self.browser_profile.kwargs_for_new_context().model_dump()+ )+ else:+ # if a user_data_dir is provided, launch a persistent context with that 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 or self.browser+ # ^ this can unfortunately be 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 abovechild_pids_after_launch = {child.pid for child in current_process.children(recursive=True)}new_child_pids = child_pids_after_launch - child_pids_before_launchnew_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())}')+ if new_chrome_procs and not self.chrome_pid:+ self.chrome_pid = new_chrome_procs[0].pid+ logger.debug(f' โณ Spawned chrome subprocess: pid={self.chrome_pid} {" ".join(new_chrome_procs[0].cmdline())}')# default to closing the browser ourselves when the BrowserSession is over if we launched it ourselvesif self.browser_profile.keep_alive is None:self.browser_profile.keep_alive = False@@ -276,14 +386,16 @@ class BrowserSession(BaseModel):# Update human foreground tab stateold_foreground = self.human_current_page+ old_tab_idx = self.browser_context.pages.index(old_foreground)self.human_current_page = new_page+ new_tab_idx = self.browser_context.pages.index(new_page)# Log before and after for debuggingif 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)})'+ f'๐๏ธ Foregound tab changed by human from [{old_tab_idx}]{truncate_url(old_foreground.url, 22) if old_foreground else "about:blank"} '+ f'โก๏ธ [{new_tab_idx}]{truncate_url(new_page.url, 22)} '+ f'(agent will stay on [{self.browser_context.pages.index(self.agent_current_page)}]{truncate_url(self.agent_current_page.url, 22)})')return new_page.url@@ -331,7 +443,7 @@ class BrowserSession(BaseModel):return# First, set the viewport size on any existing pages- use_viewport = (not self.browser_profile.no_viewport) and self.viewport+ use_viewport = (not self.browser_profile.no_viewport) and self.browser_profile.viewportif use_viewport:logger.debug('๐๏ธ Resizing existing pages '@@ -345,6 +457,41 @@ class BrowserSession(BaseModel):await page.set_viewport_size(self.browser_profile.viewport)# --- Tab management ---+ async def get_current_page(self) -> Page:+ """Get the current page + ensure it's not None / closed"""++ # get-or-create the browser_context if it's not already set up+ if not self.browser_context:+ self.start()+ assert self.browser_context, 'BrowserContext is not set up'++ # if either focused page is closed, clear it so we dont use a dead object+ if (not self.human_current_page) or self.human_current_page.is_closed():+ self.human_current_page = None+ if (not self.agent_current_page) or self.agent_current_page.is_closed():+ self.agent_current_page = None++ # if either one is None, fallback to using the other one for both+ self.agent_current_page = self.agent_current_page or self.human_current_page or None+ self.human_current_page = self.human_current_page or self.agent_current_page or None++ if self.agent_current_page is None:+ # if both are still None, fallback to using the first open tab we can find+ if self.browser_context.pages:+ first_available_tab = self.browser_context.pages[0]+ self.agent_current_page = first_available_tab+ self.human_current_page = first_available_tab+ else:+ # if all tabs are closed, open a new one+ new_tab = await self.create_new_tab()+ self.agent_current_page = new_tab+ self.human_current_page = new_tab++ assert self.agent_current_page is not None+ assert self.human_current_page is not None++ return self.agent_current_page+@propertydef tabs(self) -> list[Page]:if not self.browser_context:@@ -353,60 +500,32 @@ class BrowserSession(BaseModel):@require_initializationasync 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+ return await self.create_new_tab(url=url)@require_initializationasync def switch_tab(self, tab_index: int) -> Page:- pages = self.tabs+ pages = self.browser_context.pagesif 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_initializationasync 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+ page = await self.get_current_page()+ await page.wait_for_selector(selector, state='visible', timeout=timeout)@require_initialization+ @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."""+ page = await self.get_current_page()try:- page = await self.get_agent_current_page()await page.evaluate("""try {@@ -427,9 +546,8 @@ class BrowserSession(BaseModel):""")except Exception as e:- logger.debug(f'โ Failed to remove highlights (this is usually ok): {str(e)}')+ logger.debug(f'โ Failed to remove highlights (this is usually ok): {type(e).__name__}: {e}')# Don't raise the error since this is not critical functionality- pass@require_initializationasync def get_dom_element_by_index(self, index: int) -> Any | None:@@ -437,138 +555,177 @@ class BrowserSession(BaseModel):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+ @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:- 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}')+ # 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+ page = await self.get_current_page()+ await page.keyboard.type(text)- return False+ 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}')- @require_initialization- async def _click_element_node(self, element: Any) -> str | None:+ @time_execution_async('--click_element_node')+ async def _click_element_node(self, element_node: DOMElementNode) -> str | None:"""- Click on a DOM element node.- Returns download path if a download was triggered, None otherwise.+ Optimized method to click an element using xpath."""- 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-+ page = await self.get_current_page()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+ # 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.browser_profile.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.browser_profile.save_downloads_path, suggested_filename+ )+ download_path = os.path.join(self.browser_profile.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 eexcept 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+ raise Exception(f'Failed to click element: {repr(element_node)}. Error: {str(e)}')- if not hasattr(element, 'xpath') or not element.xpath:- logging.warning('Element has no xpath')- return+ @time_execution_async('--get_tabs_info')+ async def get_tabs_info(self) -> list[TabInfo]:+ """Get information about all tabs"""- 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+ tabs_info = []+ for page_id, page in enumerate(self.browser_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)- # 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+ return tabs_info@require_initializationasync def close_tab(self, tab_index: int | None = None) -> None:- pages = self.tabs+ pages = self.browser_context.pagesif not pages:return+if tab_index is None:- page = self.agent_current_page or pages[0]+ # to tab_index passed, just close the current agent page+ page = await self.get_current_page()else:+ # otherwise close the tab at the given indexpage = 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++ # reset the self.agent_current_page and self.human_current_page references to first available tab+ await self.get_current_page()# --- Page navigation ---@require_initializationasync def navigate(self, url: str) -> None:- if not self.agent_current_page:- await self.new_tab(url)- else:+ if self.agent_current_page:await self.agent_current_page.goto(url)+ else:+ await self.create_new_tab(url)@require_initializationasync def refresh(self) -> None:- if self.agent_current_page:+ if self.agent_current_page and not self.agent_current_page.is_closed():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+ else:+ await self.create_new_tab()@require_initializationasync def execute_javascript(self, script: str) -> Any:- if self.agent_current_page:- return await self.agent_current_page.evaluate(script)- return None+ page = await self.get_current_page()+ return await page.evaluate(script)async def get_cookies(self) -> list[dict[str, Any]]:if self.browser_context:@@ -588,22 +745,1164 @@ class BrowserSession(BaseModel):if not out_path.is_absolute():out_path = Path(self.browser_profile.downloads_dir) / out_pathout_path.parent.mkdir(parents=True, exist_ok=True)- out_path.write_text(json.dumps(cookies, indent=4)) # TODO: replace with anyio asyncio write+ out_path.write_text(json.dumps(cookies, indent=4)) # TODO: replace with anyio asyncio or anyio write++ # @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('*'))++ async def _wait_for_stable_network(self):+ pending_requests = set()+ last_activity = asyncio.get_event_loop().time()++ page = await self.get_current_page()++ # Define relevant resource types and content types+ RELEVANT_RESOURCE_TYPES = {+ 'document',+ 'stylesheet',+ 'image',+ 'font',+ 'script',+ 'iframe',+ }- # --- Compatibility properties for old API ---- @property- def browser_pages(self) -> list[Page]:- return self.tabs+ RELEVANT_CONTENT_TYPES = {+ 'text/html',+ 'text/css',+ 'application/javascript',+ 'image/',+ 'font/',+ 'application/json',+ }- @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://')]+ # 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',+ }- @property- def saved_downloads(self) -> list[Path]:+ 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.browser_profile.wait_for_network_idle_page_load_time+ ):+ break+ if now - start_time > self.browser_profile.maximum_wait_page_load_time:+ logger.debug(+ f'Network timeout after {self.browser_profile.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.browser_profile.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+ page = await self.get_current_page()+ try:+ await self._wait_for_stable_network()++ # Check if the loaded URL is allowed+ 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.browser_profile.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.browser_profile.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+ f"โ ๏ธ Allowing agent to visit {domain} based on allowed_domains=['{glob}', ...]. Set allowed_domains=['{domain}', ...] explicitly to avoid matching too many domains!"+ )+ _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.browser_profile.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_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_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"""+ try:+ # 10 ms timeout+ page = await self.get_current_page()+ 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"""+ try:+ page = await self.get_current_page()+ 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.+ """++ # Check if this is the foreground tab as well+ is_foreground = self.agent_current_page == self.human_current_page++ # Close the tab+ try:+ await self.agent_current_page.close()+ except Exception as e:+ logger.debug(f'โ๏ธ Error during close_current_tab: {e}')++ # 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 self.browser_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_current_page()+ return await page.content()++ 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_current_page()+ structure = await page.evaluate(debug_script)+ return structure++ @time_execution_sync('--get_state_summary') # This decorator might need to be updated to handle async+ async def get_state_summary(self, cache_clickable_elements_hashes: bool) -> BrowserStateSummary:+ """Get a summary of the current browser state++ This method builds a BrowserStateSummary object that captures the current state+ of the browser, including url, title, tabs, screenshot, and DOM tree.++ Parameters:+ -----------+ 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 since the last message,+ which helps reduce token usage.+ """+ await self._wait_for_page_and_frames_load()+ 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 self._cached_clickable_element_hashes and self._cached_clickable_element_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 self._cached_clickable_element_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+ self._cached_clickable_element_hashes = CachedClickableElementHashes(+ url=updated_state.url,+ hashes=ClickableElementProcessor.get_clickable_elements_hashes(updated_state.element_tree),+ )++ self._cached_browser_state_summary = updated_state++ # Save cookies if a file is specified+ if self.browser_profile.cookies_file:+ asyncio.create_task(self.save_cookies())++ return self._cached_browser_state_summary++ async def _get_updated_state(self, focus_element: int = -1) -> BrowserStateSummary:+ """Update and return state."""++ page = await self.get_current_page()++ # Check if current page is still valid, if not switch to another available page+ try:+ # Test if page is still accessible+ await page.evaluate('1')+ except Exception as e:+ logger.debug(f'๐ Current page is no longer accessible: {type(e).__name__}: {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.browser_profile.viewport_expansion,+ highlight_elements=self.browser_profile.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()+ # outer_page = self.agent_current_page+ # 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 {outer_page.url}: {page.url}',+ # parent_page_url=outer_page.url,+ # )+ # )++ screenshot_b64 = await self.take_screenshot()+ pixels_above, pixels_below = await self.get_scroll_info(page)++ self.browser_state_summary = BrowserStateSummary(+ 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.browser_state_summary+ except Exception as e:+ logger.error(f'โ Failed to update state: {str(e)}')+ # Return last known good state if available+ if hasattr(self, 'browser_state_summary'):+ return self.browser_state_summary+ 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.+ """++ # We no longer force tabs to the foreground as it disrupts user focus+ # await self.agent_current_page.bring_to_front()+ page = await self.get_current_page()+ await page.wait_for_load_state()++ screenshot = await self.agent_current_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++ # 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:+ page = await self.get_current_page()+ current_frame = 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.browser_profile.include_dynamic_attributes,+ )+ current_frame = current_frame.frame_locator(css_selector)++ css_selector = self._enhanced_css_selector_for_element(+ element, include_dynamic_attributes=self.browser_profile.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.+ """+ page = await self.get_current_page()++ try:+ # Use XPath to locate the element+ element_handle = await page.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."""- Return a list of files in the downloads_dir.+ page = await self.get_current_page()++ try:+ # Use CSS selector to locate the element+ element_handle = await page.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')."""- return list(Path(self.browser_profile.downloads_dir).glob('*'))+ page = await self.get_current_page()+ try:+ # handle also specific element type or use any type.+ selector = f'{element_type or "*"}:text("{text}")'+ elements = await page.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++ @require_initialization+ @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+ page = await self.get_current_page()+ await 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}')++ @require_initialization+ @time_execution_async('--switch_to_tab')+ async def switch_to_tab(self, page_id: int) -> Page:+ """Switch to a specific tab by its page_id (aka tab index exposed to LLM)"""+ pages = self.browser_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 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+ if self.browser_profile.viewport:+ await page.set_viewport_size(self.browser_profile.viewport)++ return page++ @time_execution_async('--create_new_tab')+ async def create_new_tab(self, url: str | None = None) -> Page:+ """Create a new tab and optionally navigate to a URL"""++ if url and not self._is_url_allowed(url):+ raise BrowserError(f'Cannot create new tab with non-allowed URL: {url}')++ new_page = await self.browser_context.new_page()++ # Update agent tab reference+ self.agent_current_page = new_page++ # Update human tab reference if there is no human tab yet+ if (not self.human_current_page) or self.human_current_page.is_closed():+ self.human_current_page = new_page++ await new_page.wait_for_load_state()++ # Set the viewport size for the new tab+ if self.browser_profile.viewport:+ await new_page.set_viewport_size(self.browser_profile.viewport)++ if url:+ await new_page.goto(url)+ await self._wait_for_page_and_frames_load(timeout_overwrite=1)++ assert self.human_current_page is not None+ assert self.agent_current_page is not None+ if url:+ assert self.agent_current_page.url == url+ else:+ assert self.agent_current_page.url == 'about:blank'++ return new_page++ # region - Helper methods for easier access to the DOM++ @require_initialization+ async def get_selector_map(self) -> SelectorMap:+ if self._cached_browser_state_summary is None:+ return {}+ return self._cached_browser_state_summary.selector_map++ @require_initialization+ 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++ @require_initialization+ 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 _scroll_container(self, pixels: int) -> None:+ """Scroll the element that truly owns vertical scroll.Starts at the focused node โ climbs to the first big, scroll-enabled ancestor otherwise picks the first scrollable element or the root, then calls `element.scrollBy` (or `window.scrollBy` for the root) by the supplied pixel value."""++ # An element can *really* scroll if: overflow-y is auto|scroll|overlay, it has more content than fits, its own viewport is not a postage stamp (more than 50 % of window).+ SMART_SCROLL_JS = """(dy) => {+ const bigEnough = el => el.clientHeight >= window.innerHeight * 0.5;+ const canScroll = el =>+ el &&+ /(auto|scroll|overlay)/.test(getComputedStyle(el).overflowY) &&+ el.scrollHeight > el.clientHeight &&+ bigEnough(el);++ let el = document.activeElement;+ while (el && !canScroll(el) && el !== document.body) el = el.parentElement;++ el = canScroll(el)+ ? el+ : [...document.querySelectorAll('*')].find(canScroll)+ || document.scrollingElement+ || document.documentElement;++ if (el === document.scrollingElement ||+ el === document.documentElement ||+ el === document.body) {+ window.scrollBy(0, dy);+ } else {+ el.scrollBy({ top: dy, behavior: 'auto' });+ }+ }"""+ page = await self.get_current_page()+ await page.evaluate(SMART_SCROLL_JS, pixels)++ @staticmethod+ async def _get_unique_filename(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 _resize_window(self, context: PlaywrightBrowserContext) -> None:+ # """Old approach to resize the browser window to match the configured size"""++ # BROWSER_NAVBAR_HEIGHT = 40++ # try:+ # if not context.pages:+ # return++ # page = context.pages[0]+ # window_size = {'width': self.browser_profile.window_width, 'height': self.browser_profile.window_height}++ # # First, set the viewport size+ # if self.browser_profile.viewport:+ # await page.set_viewport_size(self.browser_profile.viewport)++ # # 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 executiondiff --git a/browser_use/browser/types.py b/browser_use/browser/types.pyindex ff2f7505f..eab88a384 100644--- a/browser_use/browser/types.py+++ b/browser_use/browser/types.py@@ -17,8 +17,7 @@ from playwright._impl._api_structures import (StorageState,ViewportSize,)-from pydantic import AfterValidator, BaseModel, ConfigDict, Field, model_validator-from uuid_extensions import uuid7str+from pydantic import AfterValidator, AliasChoices, BaseModel, ConfigDict, Field, model_validator# fix pydantic error on python 3.11# PydanticUserError: Please use `typing_extensions.TypedDict` instead of `typing.TypedDict` on Python < 3.12.@@ -92,6 +91,8 @@ CHROME_DOCKER_ARGS = ['--disable-setuid-sandbox','--disable-dev-shm-usage','--no-xshm',+ # '--no-zygote',+ # '--single-process',]CHROME_DISABLE_SECURITY_ARGS = [@@ -323,7 +324,7 @@ class BrowserContextArgs(BaseModel):https://playwright.dev/python/docs/api/class-browser#browser-new-context"""- model_config = ConfigDict(extra='ignore', validate_assignment=False, revalidate_instances='always')+ model_config = ConfigDict(extra='ignore', validate_assignment=False, revalidate_instances='always', populate_by_name=True)# Browser context parametersaccept_downloads: bool = True@@ -379,7 +380,7 @@ class BrowserConnectArgs(BaseModel):https://playwright.dev/python/docs/api/class-browsertype#browser-type-connect-over-cdp"""- model_config = ConfigDict(extra='ignore', validate_assignment=True, revalidate_instances='always')+ model_config = ConfigDict(extra='ignore', validate_assignment=True, revalidate_instances='always', populate_by_name=True)headers: dict[str, str] = Field(default_factory=dict)slow_mo: float = 0.0@@ -403,25 +404,43 @@ class BrowserLaunchArgs(BaseModel):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)+ env: dict[str, str | float | bool] = Field(+ default_factory=dict, description='Extra environment variables to set when launching the browser.'+ )+ executable_path: str | Path | None = Field(+ default=None,+ validation_alias=AliasChoices('chrome_binary_path', 'browser_binary_path'),+ description='Path to the chromium-based browser executable to use.',+ )+ headless: bool | None = Field(default=None, description='Whether to run the browser in headless or windowed mode.')+ args: list[CliArgStr] = Field(+ default_factory=list, description='List of *extra* CLI args to pass to the browser when launching.'+ )ignore_default_args: list[CliArgStr] = Field(default_factory=lambda: ['--enable-automation', '--disable-extensions'],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+ channel: BrowserChannel = BrowserChannel.CHROMIUM # https://playwright.dev/docs/browsers#chromium-headless-shell+ chromium_sandbox: bool = Field(+ default=not IN_DOCKER, description='Whether to enable Chromium sandboxing (recommended unless inside Docker).'+ )+ devtools: bool = Field(+ default=False, description='Whether to open DevTools panel automatically for every page, only works when headless=False.'+ )+ slow_mo: float = Field(default=0, description='Slow down actions by this many milliseconds.')+ timeout: float = Field(default=30000, description='Default timeout in milliseconds for connecting to a remote browser.')+ proxy: ProxySettings | None = Field(default=None, description='Proxy settings to use to connect to the browser.')+ downloads_path: str | Path | None = Field(default=None, description='Directory to save downloads to.')+ traces_dir: str | Path | None = Field(default=None, description='Directory to save HAR trace files to.')+ handle_sighup: bool = Field(+ default=True, description='Whether playwright should swallow SIGHUP signals and kill the browser.'+ )+ handle_sigint: bool = Field(+ default=True, description='Whether playwright should swallow SIGINT signals and kill the browser.'+ )+ handle_sigterm: bool = Field(+ default=True, description='Whether playwright should swallow SIGTERM signals and kill the browser.'+ )# firefox_user_prefs: dict[str, str | float | bool] = Field(default_factory=dict)@model_validator(mode='after')@@ -456,7 +475,7 @@ class BrowserNewContextArgs(BrowserContextArgs):https://playwright.dev/python/docs/api/class-browser#browser-new-context"""- model_config = ConfigDict(extra='ignore', validate_assignment=False, revalidate_instances='always')+ model_config = ConfigDict(extra='ignore', validate_assignment=False, revalidate_instances='always', populate_by_name=True)# storage_state is not supported in launch_persistent_context()storage_state: str | Path | dict[str, Any] | None = None@@ -493,41 +512,8 @@ class BrowserLaunchPersistentContextArgs(BrowserLaunchArgs, BrowserContextArgs):model_config = ConfigDict(extra='ignore', validate_assignment=False, revalidate_instances='always')- # 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+ # Required parameter specific to launch_persistent_context, but can be None to use incognito temp dir+ user_data_dir: str | Path | None = BROWSERUSE_PROFILES_DIR / 'default'class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, BrowserLaunchArgs, BrowserNewContextArgs):@@ -548,10 +534,14 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Brofrom_attributes=True,validate_by_name=True,validate_by_alias=True,+ populate_by_name=True,)- id: str = Field(default_factory=uuid7str)- label: str = 'default'+ # ... extends options defined in:+ # BrowserLaunchPersistentContextArgs, BrowserLaunchArgs, BrowserNewContextArgs, BrowserConnectArgs++ # id: str = Field(default_factory=uuid7str)+ # label: str = 'default'# custom options we provide that aren't native playwright kwargsdisable_security: bool = Field(default=False, description='Disable browser security features.')@@ -562,6 +552,12 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Brodefault=None,description='Window size to use for the browser when headless=False.',)+ window_height: int | None = Field(+ default=None, description='DEPRECATED, use window_size["height"] instead', deprecated=True, exclude=True+ )+ window_width: int | None = Field(+ default=None, description='DEPRECATED, use window_size["width"] instead', deprecated=True, exclude=True+ )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.',@@ -585,6 +581,8 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Brosave_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.')+ cookies_file: str | None = Field(default=None, description='File to save cookies to.')+# extension_ids_to_preinstall: list[str] = Field(# default_factory=list, description='List of Chrome extension IDs to preinstall.'# )@@ -594,18 +592,28 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Bro# )# # --- File paths ---- # downloads_dir: Path = Field(- # default_factory=lambda: Path('~/.config/browseruse/profiles/default/downloads').expanduser(),- # description='Directory for downloads.',- # )+ downloads_dir: Path | str = Field(+ default=Path('~/.config/browseruse/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})'+ short_dir = str(self.user_data_dir).replace(str(Path('~').expanduser()), '~')+ return f'BrowserProfile(user_data_dir={short_dir}, headless={self.headless})'def __str__(self) -> str:return repr(self)+ @model_validator(mode='after')+ def copy_old_config_names_to_new(self) -> Self:+ """Copy old config window_width & window_height to window_size."""+ if self.window_width or self.window_height:+ self.window_size = self.window_size or {}+ self.window_size['width'] = (self.window_size or {}).get('width') or self.window_width or 1280+ self.window_size['height'] = (self.window_size or {}).get('height') or self.window_height or 1100+ return 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', ...}@@ -620,7 +628,7 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Bro*([f'--window-size={self.window_size["height"]},{self.window_size["width"]}']if self.window_size- else (['--start-maximized' if not self.headless else []])+ else (['--start-maximized'] if not self.headless else [])),*([f'--window-position={self.window_position["width"]},{self.window_position["height"]}']@@ -664,6 +672,10 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Brof'โ ๏ธ Multiple chrome processes may be trying to share user_data_dir={self.user_data_dir} which can lead to crashes and profile data corruption!')+ if self.downloads_dir:+ self.downloads_dir = Path(self.downloads_dir).expanduser().resolve()+ self.downloads_dir.mkdir(parents=True, exist_ok=True)+# def preinstall_extensions(self) -> None:# """Preinstall the extensions."""@@ -681,7 +693,10 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Bro# # TODO: copy this from ArchiveBox implementationdef detect_display_configuration(self) -> None:- """Detect the display size and set the screen option."""+ """+ Detect the system display size and initialize the display-related config defaults:+ screen, window_size, window_position, viewport, no_viewport, device_scale_factor+ """display_size = get_display_size()if display_size:diff --git a/browser_use/browser/views.py b/browser_use/browser/views.pyindex c5468c20a..c171c6b54 100644--- a/browser_use/browser/views.py+++ b/browser_use/browser/views.py@@ -18,7 +18,13 @@ class TabInfo(BaseModel):@dataclass-class BrowserState(DOMState):+class BrowserStateSummary(DOMState):+ """The summary of the browser's current state designed for an LLM to process"""++ # provided by DOMState:+ # element_tree: DOMElementNode+ # selector_map: SelectorMap+url: strtitle: strtabs: list[TabInfo]@@ -30,6 +36,8 @@ class BrowserState(DOMState):@dataclassclass BrowserStateHistory:+ """The summary of the browser's state at a past point in time to usse in LLM message history"""+url: strtitle: strtabs: list[TabInfo]diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.pyindex c29218ff6..58a0a49ef 100644--- a/browser_use/controller/registry/service.py+++ b/browser_use/controller/registry/service.py@@ -1,4 +1,5 @@import asyncio+import loggingfrom collections.abc import Callablefrom inspect import iscoroutinefunction, signaturefrom typing import Any, Generic, Optional, TypeVar@@ -21,6 +22,8 @@ from browser_use.utils import time_execution_asyncContext = TypeVar('Context')+logger = logging.getLogger(__name__)+class Registry(Generic[Context]):"""Service for registering and managing actions"""@@ -37,7 +40,11 @@ class Registry(Generic[Context]):params = {name: (param.annotation, ... if param.default == param.empty else param.default)for name, param in sig.parameters.items()- if name != 'browser' and name != 'page_extraction_llm' and name != 'available_file_paths'+ if name != 'browser'+ and name != 'page_extraction_llm'+ and name != 'available_file_paths'+ and name != 'browser_session'+ and name != 'browser_context'}# TODO: make the types here workreturn create_model(@@ -109,7 +116,10 @@ class Registry(Generic[Context]):action = self.registry.actions[action_name]try:# Create the validated Pydantic model- validated_params = action.param_model(**params)+ try:+ validated_params = action.param_model(**params)+ except Exception as e:+ raise ValueError(f'Invalid parameters {params} for action {action_name}: {type(e)}: {e}') from e# Check if the first parameter is a Pydantic modelsig = signature(action.function)@@ -121,7 +131,9 @@ class Registry(Generic[Context]):validated_params = self._replace_sensitive_data(validated_params, sensitive_data)# Check if the action requires browser- if 'browser_session' in parameter_names and not browser_session:+ if (+ 'browser_session' in parameter_names or 'browser' in parameter_names or 'browser_context' 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.')@@ -137,6 +149,16 @@ class Registry(Generic[Context]):extra_args['context'] = contextif 'browser_session' in parameter_names:extra_args['browser_session'] = browser_session+ if 'browser' in parameter_names: # support legacy browser: BrowserContext arg+ logger.debug(+ f'You should update this action {action_name}(browser: BrowserContext) -> to take {action_name}(browser_session: BrowserSession) instead'+ )+ extra_args['browser'] = browser_session+ if 'browser_context' in parameter_names: # support legacy browser: BrowserContext arg+ logger.debug(+ f'You should update this action {action_name}(browser_context: BrowserContext) -> to take {action_name}(browser_session: BrowserSession) instead'+ )+ extra_args['browser_context'] = browser_sessionif 'page_extraction_llm' in parameter_names:extra_args['page_extraction_llm'] = page_extraction_llmif 'available_file_paths' in parameter_names:diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 9a0435196..01d68afb9 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -83,9 +83,14 @@ class Controller(Generic[Context]):param_model=SearchGoogleAction,)async def search_google(params: SearchGoogleAction, browser_session: BrowserSession):+ search_url = f'https://www.google.com/search?q={params.query}&udm=14'+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()+ if page:+ await page.goto(search_url)+ await page.wait_for_load_state()+ else:+ page = await browser_session.create_new_tab(search_url)msg = f'๐ Searched for "{params.query}" in Google'logger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True)@@ -93,8 +98,11 @@ class Controller(Generic[Context]):@self.registry.action('Navigate to URL in the current tab', param_model=GoToUrlAction)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()+ if page:+ await page.goto(params.url)+ await page.wait_for_load_state()+ else:+ page = await browser_session.create_new_tab(params.url)msg = f'๐ Navigated to {params.url}'logger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True)@@ -123,7 +131,7 @@ class Controller(Generic[Context]):raise Exception(f'Element with index {params.index} does not exist - retry or use alternative actions')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 [])+ initial_pages = len(browser_session.tabs)# if element has file uploader then dont clickif await browser_session.is_file_uploader(element_node):@@ -142,7 +150,7 @@ class Controller(Generic[Context]):logger.info(msg)logger.debug(f'Element xpath: {element_node.xpath}')- if len(browser_session.browser_context.pages) > initial_pages:+ if len(browser_session.tabs) > initial_pages:new_tab_msg = 'New tab opened - switching to it'msg += f' - {new_tab_msg}'logger.info(new_tab_msg)@@ -191,7 +199,7 @@ class Controller(Generic[Context]):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_session.get_agent_current_page()+ page = await browser_session.get_current_page()await page.wait_for_load_state()msg = f'๐ Switched to tab {params.page_id}'logger.info(msg)@@ -199,9 +207,7 @@ class Controller(Generic[Context]):@self.registry.action('Open url in new tab', param_model=OpenTabAction)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_session.get_agent_current_page() # this has side-effects (even though it looks like a getter)+ await browser_session.create_new_tab(params.url)msg = f'๐ Opened new tab with {params.url}'logger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True)@@ -838,37 +844,34 @@ class Controller(Generic[Context]):) -> ActionResult:"""Execute an action"""- try:- for action_name, params in action.model_dump(exclude_unset=True).items():- if params is not None:- # with Laminar.start_as_current_span(- # name=action_name,- # input={- # 'action': action_name,- # 'params': params,- # },- # span_type='TOOL',- # ):- result = await self.registry.execute_action(- action_name,- params,- browser_session=browser_session,- page_extraction_llm=page_extraction_llm,- sensitive_data=sensitive_data,- available_file_paths=available_file_paths,- context=context,- )+ for action_name, params in action.model_dump(exclude_unset=True).items():+ if params is not None:+ # with Laminar.start_as_current_span(+ # name=action_name,+ # input={+ # 'action': action_name,+ # 'params': params,+ # },+ # span_type='TOOL',+ # ):+ result = await self.registry.execute_action(+ action_name=action_name,+ params=params,+ browser_session=browser_session,+ page_extraction_llm=page_extraction_llm,+ sensitive_data=sensitive_data,+ available_file_paths=available_file_paths,+ context=context,+ )- # Laminar.set_span_output(result)+ # Laminar.set_span_output(result)- if isinstance(result, str):- return ActionResult(extracted_content=result)- elif isinstance(result, ActionResult):- return result- elif result is None:- return ActionResult()- else:- raise ValueError(f'Invalid action result type: {type(result)} of {result}')- return ActionResult()- except Exception as e:- raise e+ if isinstance(result, str):+ return ActionResult(extracted_content=result)+ elif isinstance(result, ActionResult):+ return result+ elif result is None:+ return ActionResult()+ else:+ raise ValueError(f'Invalid action result type: {type(result)} of {result}')+ return ActionResult()