Skip to content

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

more lint and hint fixes

Nick Sweeting6c695d0a4269
diff --git a/browser_use/cli.py b/browser_use/cli.py
index 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 time
if 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 = 0
if 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.py
index 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 parent
if (
- 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.py
index 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_generation
if (
- GroqBadRequestError
+ GroqBadRequestError is not None
and 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 = None
logger.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.py
index 766dcca4a..b5a31cd3c 100644
--- a/examples/custom-functions/2fa.py
+++ b/examples/custom-functions/2fa.py
@@ -9,7 +9,7 @@ from dotenv import load_dotenv
load_dotenv()
-import pyotp
+import pyotp # type: ignore
from langchain_openai import ChatOpenAI
from browser_use import ActionResult, Agent, Controller
diff --git a/examples/custom-functions/custom_hooks_before_after_step.py b/examples/custom-functions/custom_hooks_before_after_step.py
index 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 json
from pathlib import Path
-import prettyprinter
+import prettyprinter # type: ignore
from fastapi import FastAPI, Request
prettyprinter.install_extras()
@@ -124,7 +124,7 @@ load_dotenv()
import requests
from langchain_openai import ChatOpenAI
-from pyobjtojson import obj_to_json
+from pyobjtojson import obj_to_json # type: ignore
from browser_use import Agent
diff --git a/examples/custom-functions/extract_pdf_content.py b/examples/custom-functions/extract_pdf_content.py
index efe942750..3b3070748 100755
--- a/examples/custom-functions/extract_pdf_content.py
+++ b/examples/custom-functions/extract_pdf_content.py
@@ -18,7 +18,7 @@ import logging
from typing import Any
from langchain_openai import ChatOpenAI
-from mistralai import Mistral
+from mistralai import Mistral # type: ignore
from pydantic import BaseModel, Field
from browser_use import Agent, Controller
diff --git a/examples/custom-functions/notification.py b/examples/custom-functions/notification.py
index 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/185833
diff --git a/examples/custom-functions/onepassword_2fa.py b/examples/custom-functions/onepassword_2fa.py
index 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_dotenv
load_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-sdk
from browser_use import ActionResult, Agent, Controller
diff --git a/examples/custom-functions/solve_amazon_captcha.py b/examples/custom-functions/solve_amazon_captcha.py
index 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_dotenv
load_dotenv()
-from amazoncaptcha import AmazonCaptcha
+from amazoncaptcha import AmazonCaptcha # type: ignore
from langchain_openai import ChatOpenAI
from browser_use import ActionResult
diff --git a/examples/use-cases/play_chess.py b/examples/use-cases/play_chess.py
index 114685b5f..598f74823 100755
--- a/examples/use-cases/play_chess.py
+++ b/examples/use-cases/play_chess.py
@@ -16,7 +16,7 @@ load_dotenv()
import asyncio
import logging
-import chess
+import chess # type: ignore
from bs4 import BeautifulSoup
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
diff --git a/pyproject.toml b/pyproject.toml
index 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.py
index 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 path
downloads_path=browser_profile_with_cookies.downloads_path,
)
diff --git a/tests/ci/test_browser_session_downloads.py b/tests/ci/test_browser_session_downloads.py
index a4fcf90b7..f7ea7e7a3 100644
--- a/tests/ci/test_browser_session_downloads.py
+++ b/tests/ci/test_browser_session_downloads.py
@@ -6,6 +6,7 @@ import time
import pytest
from 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.py
index 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 pytest
from browser_use.browser import BrowserSession
+from browser_use.browser.profile import BrowserProfile
from 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 session
diff --git a/tests/ci/test_browser_session_file_uploads.py b/tests/ci/test_browser_session_file_uploads.py
index 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 pytest
from pytest_httpserver import HTTPServer
+from browser_use.browser.profile import BrowserProfile
from browser_use.browser.session import BrowserSession
@@ -20,7 +21,7 @@ class TestBrowserSessionFileUploads:
@pytest.fixture
async 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 session
await session.kill()
diff --git a/tests/ci/test_browser_session_via_cdp.py b/tests/ci/test_browser_session_via_cdp.py
index 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 pytest
from browser_use.browser import BrowserSession
+from browser_use.browser.profile import BrowserProfile
from browser_use.browser.types import async_playwright
async 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.py
index 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, ProxySettings
async 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 dimensions
browser_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 session
browser_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 settings
diff --git a/tests/ci/test_controller.py b/tests/ci/test_controller.py
index d9af6ef4b..08368fe58 100644
--- a/tests/ci/test_controller.py
+++ b/tests/ci/test_controller.py
@@ -8,6 +8,7 @@ from pytest_httpserver import HTTPServer
from browser_use.agent.views import ActionModel, ActionResult
from browser_use.browser import BrowserSession
+from browser_use.browser.profile import BrowserProfile
from browser_use.controller.service import Controller
from 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_session
diff --git a/tests/ci/test_registry.py b/tests/ci/test_registry.py
index d83ba011b..c1480884d 100644
--- a/tests/ci/test_registry.py
+++ b/tests/ci/test_registry.py
@@ -20,6 +20,7 @@ from pytest_httpserver.httpserver import HandlerType
from browser_use.agent.views import ActionResult
from browser_use.browser import BrowserSession
+from browser_use.browser.profile import BrowserProfile
from browser_use.browser.types import Page
from browser_use.controller.registry.service import Registry
from 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')