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
more lint and hint fixes
Nick Sweeting6c695d0a4269
diff --git a/browser_use/cli.py b/browser_use/cli.pyindex 2f505358c..e546e74ec 100644--- a/browser_use/cli.py+++ b/browser_use/cli.py@@ -549,8 +549,9 @@ class BrowserUseApp(App):def on_input_key_up(self, event: events.Key) -> None:"""Handle up arrow key in the input field."""- # Check if event is from the input field- if not hasattr(event, 'input') or event.input.id != 'task-input':+ # For textual key events, we need to check focus manually+ input_field = self.query_one('#task-input', Input)+ if not input_field.has_focus:return# Only process if we have history@@ -571,8 +572,9 @@ class BrowserUseApp(App):def on_input_key_down(self, event: events.Key) -> None:"""Handle down arrow key in the input field."""- # Check if event is from the input field- if not hasattr(event, 'input') or event.input.id != 'task-input':+ # For textual key events, we need to check focus manually+ input_field = self.query_one('#task-input', Input)+ if not input_field.has_focus:return# Only process if we have history@@ -811,8 +813,12 @@ class BrowserUseApp(App):# Get the last step metadata to show the most recent LLM response timeif num_steps > 0 and self.agent.state.history.history[-1].metadata:last_step = self.agent.state.history.history[-1]- step_duration = last_step.metadata.duration_seconds- step_tokens = last_step.metadata.input_tokens+ if last_step.metadata:+ step_duration = last_step.metadata.duration_seconds+ step_tokens = last_step.metadata.input_tokens+ else:+ step_duration = 0+ step_tokens = 0if step_tokens > 0:tokens_per_second = step_tokens / step_duration if step_duration > 0 else 0@@ -943,7 +949,7 @@ class BrowserUseApp(App):tasks_info.write('')# If agent is actively running, show a status indicator- if hasattr(self.agent, 'running') and self.agent.running:+ if hasattr(self.agent, 'running') and getattr(self.agent, 'running', False):tasks_info.write('[yellow]Agent is actively working[blink]...[/][/]')elif hasattr(self.agent, 'state') and hasattr(self.agent.state, 'paused') and self.agent.state.paused:tasks_info.write('[orange]Agent is paused (press Enter to resume)[/]')@@ -978,10 +984,12 @@ class BrowserUseApp(App):rich_log.clear()if self.agent is None:+ if not self.llm:+ raise RuntimeError('LLM not initialized')self.agent = Agent(task=task,llm=self.llm,- controller=self.controller if self.controller else None,+ controller=self.controller if self.controller else Controller(),browser_session=self.browser_session,source='cli',**agent_settings.model_dump(),diff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 3d2cfece4..0964f37cc 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -223,7 +223,7 @@ class DOMElementNode(DOMBaseNode):elif isinstance(node, DOMTextNode):# Add text only if it doesn't have a highlighted parentif (- node.parent.highlight_index is None and node.parent and node.parent.is_visible and node.parent.is_top_element+ node.parent and node.parent.highlight_index is None and node.parent.is_visible and node.parent.is_top_element): # and node.is_parent_top_element()formatted_text.append(f'{depth_str}{node.text}')diff --git a/browser_use/utils.py b/browser_use/utils.pyindex 5ed31adfe..fe91a7555 100644--- a/browser_use/utils.py+++ b/browser_use/utils.py@@ -569,14 +569,16 @@ def handle_llm_error(e: Exception) -> tuple[dict[str, Any], Any | None]:# Handle Groq BadRequestError with failed_generationif (- GroqBadRequestError+ GroqBadRequestError is not Noneand isinstance(e, GroqBadRequestError)and hasattr(e, 'body')- and e.body- and 'error' in e.body- and 'failed_generation' in e.body['error']+ and e.body # type: ignore[attr-defined]+ and isinstance(e.body, dict) # type: ignore[attr-defined]+ and 'error' in e.body # type: ignore[attr-defined]+ and isinstance(e.body['error'], dict) # type: ignore[attr-defined,index]+ and 'failed_generation' in e.body['error'] # type: ignore[attr-defined,index]):- raw = e.body['error']['failed_generation'] # type: ignore+ raw = e.body['error']['failed_generation'] # type: ignore[attr-defined,index]response = {'raw': raw, 'parsed': None}parsed = Nonelogger.debug(f'Failed to do tool call, trying to parse raw response: {raw}')diff --git a/examples/custom-functions/2fa.py b/examples/custom-functions/2fa.pyindex 766dcca4a..b5a31cd3c 100644--- a/examples/custom-functions/2fa.py+++ b/examples/custom-functions/2fa.py@@ -9,7 +9,7 @@ from dotenv import load_dotenvload_dotenv()-import pyotp+import pyotp # type: ignorefrom langchain_openai import ChatOpenAIfrom browser_use import ActionResult, Agent, Controllerdiff --git a/examples/custom-functions/custom_hooks_before_after_step.py b/examples/custom-functions/custom_hooks_before_after_step.pyindex b358d5bf4..98bacc80f 100644--- a/examples/custom-functions/custom_hooks_before_after_step.py+++ b/examples/custom-functions/custom_hooks_before_after_step.py@@ -46,7 +46,7 @@ def b64_to_png(b64_string: str, output_file):import jsonfrom pathlib import Path-import prettyprinter+import prettyprinter # type: ignorefrom fastapi import FastAPI, Requestprettyprinter.install_extras()@@ -124,7 +124,7 @@ load_dotenv()import requestsfrom langchain_openai import ChatOpenAI-from pyobjtojson import obj_to_json+from pyobjtojson import obj_to_json # type: ignorefrom browser_use import Agentdiff --git a/examples/custom-functions/extract_pdf_content.py b/examples/custom-functions/extract_pdf_content.pyindex efe942750..3b3070748 100755--- a/examples/custom-functions/extract_pdf_content.py+++ b/examples/custom-functions/extract_pdf_content.py@@ -18,7 +18,7 @@ import loggingfrom typing import Anyfrom langchain_openai import ChatOpenAI-from mistralai import Mistral+from mistralai import Mistral # type: ignorefrom pydantic import BaseModel, Fieldfrom browser_use import Agent, Controllerdiff --git a/examples/custom-functions/notification.py b/examples/custom-functions/notification.pyindex a8c6a425d..31dde9266 100644--- a/examples/custom-functions/notification.py+++ b/examples/custom-functions/notification.py@@ -17,7 +17,7 @@ controller = Controller()@controller.registry.action('Done with task ')async def done(text: str):- import yagmail+ import yagmail # type: ignore# To send emails use# STEP 1: go to https://support.google.com/accounts/answer/185833diff --git a/examples/custom-functions/onepassword_2fa.py b/examples/custom-functions/onepassword_2fa.pyindex cc58c2cce..f98f3767a 100644--- a/examples/custom-functions/onepassword_2fa.py+++ b/examples/custom-functions/onepassword_2fa.py@@ -10,7 +10,7 @@ from dotenv import load_dotenvload_dotenv()from langchain_openai import ChatOpenAI-from onepassword.client import Client # pip install onepassword-sdk+from onepassword.client import Client # type: ignore # pip install onepassword-sdkfrom browser_use import ActionResult, Agent, Controllerdiff --git a/examples/custom-functions/solve_amazon_captcha.py b/examples/custom-functions/solve_amazon_captcha.pyindex 397b60936..7c8d3f756 100644--- a/examples/custom-functions/solve_amazon_captcha.py+++ b/examples/custom-functions/solve_amazon_captcha.py@@ -8,7 +8,7 @@ from dotenv import load_dotenvload_dotenv()-from amazoncaptcha import AmazonCaptcha+from amazoncaptcha import AmazonCaptcha # type: ignorefrom langchain_openai import ChatOpenAIfrom browser_use import ActionResultdiff --git a/examples/use-cases/play_chess.py b/examples/use-cases/play_chess.pyindex 114685b5f..598f74823 100755--- a/examples/use-cases/play_chess.py+++ b/examples/use-cases/play_chess.py@@ -16,7 +16,7 @@ load_dotenv()import asyncioimport logging-import chess+import chess # type: ignorefrom bs4 import BeautifulSoupfrom langchain_openai import ChatOpenAIfrom pydantic import BaseModel, Fielddiff --git a/pyproject.toml b/pyproject.tomlindex 091f1b6f9..46b7f1d67 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -14,7 +14,6 @@ dependencies = ["aiofiles>=24.1.0","anyio>=4.9.0","bubus>=1.1.2",- "faiss-cpu>=1.11.0","google-api-core>=2.25.0","httpx>=0.28.1","langchain-anthropic==0.3.15",@@ -53,6 +52,7 @@ dependencies = [[project.optional-dependencies]memory = [# sentence-transformers: depends on pytorch, which does not support python 3.13 yet+ "faiss-cpu>=1.11.0","sentence-transformers>=4.0.2",]cli = [@@ -156,6 +156,15 @@ log_level = "DEBUG"allow-direct-references = true[tool.uv]+required-environments = [+ "sys_platform == 'darwin' and platform_machine == 'arm64'",+ "sys_platform == 'darwin' and platform_machine == 'x86_64'",+ "sys_platform == 'linux' and platform_machine == 'x86_64'",+ "sys_platform == 'linux' and platform_machine == 'aarch64'",+ # "sys_platform == 'linux' and platform_machine == 'arm64'", # no pytorch wheels available yet+ "sys_platform == 'win32' and platform_machine == 'x86_64'",+ # "sys_platform == 'win32' and platform_machine == 'arm64'", # no pytorch wheels available yet+]dev-dependencies = ["ruff>=0.11.2","tokencost>=0.1.16",@@ -172,6 +181,6 @@ dev-dependencies = ["codespell>=2.4.1","pyright>=1.1.399","ty>=0.0.1a1",- "pytest-xdist>=3.7.0"+ "pytest-xdist>=3.7.0",# "pytest-playwright-asyncio>=0.7.0", # not actually needed I think]diff --git a/tests/ci/test_browser_session_cookies.py b/tests/ci/test_browser_session_cookies.pyindex 6e5a8ffa2..664fd9f65 100644--- a/tests/ci/test_browser_session_cookies.py+++ b/tests/ci/test_browser_session_cookies.py@@ -194,7 +194,7 @@ class TestBrowserSessionCookies:profile = BrowserProfile(headless=True,user_data_dir=None,- cookies_file='./test_cookies.json', # Relative path+ cookies_file=Path('./test_cookies.json'), # Relative pathdownloads_path=browser_profile_with_cookies.downloads_path,)diff --git a/tests/ci/test_browser_session_downloads.py b/tests/ci/test_browser_session_downloads.pyindex a4fcf90b7..f7ea7e7a3 100644--- a/tests/ci/test_browser_session_downloads.py+++ b/tests/ci/test_browser_session_downloads.py@@ -6,6 +6,7 @@ import timeimport pytestfrom browser_use.browser import BrowserSession+from browser_use.browser.profile import BrowserProfile@pytest.fixture(scope='function')@@ -37,9 +38,11 @@ async def test_download_detection_timing(test_server, tmp_path):# Test 1: With downloads_dir set (default behavior)browser_with_downloads = BrowserSession(- headless=True,- downloads_dir=str(tmp_path / 'downloads'),- user_data_dir=None,+ browser_profile=BrowserProfile(+ headless=True,+ downloads_dir=str(tmp_path / 'downloads'),+ user_data_dir=None,+ ))await browser_with_downloads.start()@@ -72,9 +75,11 @@ async def test_download_detection_timing(test_server, tmp_path):# Test 2: With downloads_dir set to empty string (disables download detection)browser_no_downloads = BrowserSession(- headless=True,- downloads_dir=None,- user_data_dir=None,+ browser_profile=BrowserProfile(+ headless=True,+ downloads_dir=None,+ user_data_dir=None,+ ))await browser_no_downloads.start()@@ -124,9 +129,11 @@ async def test_actual_download_detection(test_server, tmp_path):downloads_path.mkdir()browser_session = BrowserSession(- headless=True,- downloads_path=str(downloads_path),- user_data_dir=None,+ browser_profile=BrowserProfile(+ headless=True,+ downloads_path=str(downloads_path),+ user_data_dir=None,+ ))await browser_session.start()diff --git a/tests/ci/test_browser_session_element_cache.py b/tests/ci/test_browser_session_element_cache.pyindex d0201f958..04b199eab 100644--- a/tests/ci/test_browser_session_element_cache.py+++ b/tests/ci/test_browser_session_element_cache.py@@ -3,11 +3,10 @@ Systematic debugging of the selector map issue.Test each assumption step by step to isolate the problem."""-import os-import pytestfrom browser_use.browser import BrowserSession+from browser_use.browser.profile import BrowserProfilefrom browser_use.controller.service import Controller@@ -62,9 +61,10 @@ def httpserver(make_httpserver):async def browser_session():"""Create a real browser session for testing."""session = BrowserSession(- executable_path=os.getenv('BROWSER_PATH'),- user_data_dir=None, # Use temporary profile- headless=True,+ browser_profile=BrowserProfile(+ user_data_dir=None, # Use temporary profile+ headless=True,+ ))async with session:yield sessiondiff --git a/tests/ci/test_browser_session_file_uploads.py b/tests/ci/test_browser_session_file_uploads.pyindex dfafcf329..4e6e2493f 100644--- a/tests/ci/test_browser_session_file_uploads.py+++ b/tests/ci/test_browser_session_file_uploads.py@@ -11,6 +11,7 @@ Tests cover common real-world file upload patterns:import pytestfrom pytest_httpserver import HTTPServer+from browser_use.browser.profile import BrowserProfilefrom browser_use.browser.session import BrowserSession@@ -20,7 +21,7 @@ class TestBrowserSessionFileUploads:@pytest.fixtureasync def browser_session(self):"""Create a BrowserSession instance for testing."""- session = BrowserSession(headless=True, user_data_dir=None, keep_alive=True)+ session = BrowserSession(browser_profile=BrowserProfile(headless=True, user_data_dir=None, keep_alive=True))yield sessionawait session.kill()diff --git a/tests/ci/test_browser_session_via_cdp.py b/tests/ci/test_browser_session_via_cdp.pyindex 81d4ffa7f..f133a99d1 100644--- a/tests/ci/test_browser_session_via_cdp.py+++ b/tests/ci/test_browser_session_via_cdp.py@@ -1,14 +1,17 @@import pytestfrom browser_use.browser import BrowserSession+from browser_use.browser.profile import BrowserProfilefrom browser_use.browser.types import async_playwrightasync def test_connection_via_cdp():browser_session = BrowserSession(cdp_url='http://localhost:9898',- headless=True,- keep_alive=True,+ browser_profile=BrowserProfile(+ headless=True,+ keep_alive=True,+ ),)with pytest.raises(Exception) as e:await browser_session.start()diff --git a/tests/ci/test_browser_session_viewport_and_proxy.py b/tests/ci/test_browser_session_viewport_and_proxy.pyindex 8a99ba6fe..bdbfc9690 100644--- a/tests/ci/test_browser_session_viewport_and_proxy.py+++ b/tests/ci/test_browser_session_viewport_and_proxy.py@@ -1,5 +1,5 @@from browser_use.browser import BrowserSession-from browser_use.browser.profile import ProxySettings+from browser_use.browser.profile import BrowserProfile, ProxySettingsasync def test_proxy_settings_pydantic_model():@@ -33,11 +33,13 @@ async def test_window_size_with_real_browser():"""# Create browser profile with headless mode and specific dimensionsbrowser_session = BrowserSession(- user_data_dir=None,- headless=True, # window size gets converted to viewport size in headless mode- window_size={'width': 999, 'height': 888},- maximum_wait_page_load_time=2.0,- minimum_wait_page_load_time=0.2,+ browser_profile=BrowserProfile(+ user_data_dir=None,+ headless=True, # window size gets converted to viewport size in headless mode+ window_size={'width': 999, 'height': 888},+ maximum_wait_page_load_time=2.0,+ minimum_wait_page_load_time=0.2,+ ))await browser_session.start()page = await browser_session.get_current_page()@@ -117,9 +119,11 @@ async def test_proxy_with_real_browser():# Create browser sessionbrowser_session = BrowserSession(- headless=True,- proxy=proxy_settings,- user_data_dir=None,+ browser_profile=BrowserProfile(+ headless=True,+ proxy=proxy_settings,+ user_data_dir=None,+ ))await browser_session.start()# Success - the browser was initialized with our proxy settingsdiff --git a/tests/ci/test_controller.py b/tests/ci/test_controller.pyindex d9af6ef4b..08368fe58 100644--- a/tests/ci/test_controller.py+++ b/tests/ci/test_controller.py@@ -8,6 +8,7 @@ from pytest_httpserver import HTTPServerfrom browser_use.agent.views import ActionModel, ActionResultfrom browser_use.browser import BrowserSession+from browser_use.browser.profile import BrowserProfilefrom browser_use.controller.service import Controllerfrom browser_use.controller.views import (ClickElementAction,@@ -79,9 +80,10 @@ def base_url(http_server):async def browser_session():"""Create and provide a Browser instance with security disabled."""browser_session = BrowserSession(- # browser_profile=BrowserProfile(),- headless=True,- user_data_dir=None,+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ ))await browser_session.start()yield browser_sessiondiff --git a/tests/ci/test_registry.py b/tests/ci/test_registry.pyindex d83ba011b..c1480884d 100644--- a/tests/ci/test_registry.py+++ b/tests/ci/test_registry.py@@ -20,6 +20,7 @@ from pytest_httpserver.httpserver import HandlerTypefrom browser_use.agent.views import ActionResultfrom browser_use.browser import BrowserSession+from browser_use.browser.profile import BrowserProfilefrom browser_use.browser.types import Pagefrom browser_use.controller.registry.service import Registryfrom browser_use.controller.registry.views import ActionModel as BaseActionModel@@ -96,8 +97,10 @@ def registry():async def browser_session(base_url):"""Create a real BrowserSession for testing"""browser_session = BrowserSession(- headless=True,- user_data_dir=None,+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ ))await browser_session.start()await browser_session.create_new_tab(f'{base_url}/test')