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
type hint fixes
Nick Sweetingf878b8f07c46
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 92457b08b..e809deece 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -575,56 +575,6 @@ class BrowserSession(BaseModel):GLOBAL_PLAYWRIGHT_EVENT_LOOP = current_loopreturn GLOBAL_PLAYWRIGHT_API_OBJECT- def _kill_child_processes(self) -> None:- """Kill any child processes that might be related to the browser"""-- if not self.browser_profile.keep_alive and self.browser_pid:- try:- browser_proc = psutil.Process(self.browser_pid)- try:- browser_proc.terminate()- browser_proc.wait(- timeout=5- ) # wait up to 5 seconds for the process to exit cleanly and commit its user_data_dir changes- except (psutil.NoSuchProcess, psutil.AccessDenied, TimeoutError):- pass-- # Kill all child processes first (recursive)- for child in browser_proc.children(recursive=True):- try:- # self.logger.debug(f'Force killing child process: {child.pid} ({child.name()})')- child.kill()- except (psutil.NoSuchProcess, psutil.AccessDenied):- pass-- # Kill the main browser process- # self.logger.debug(f'Force killing browser process: {self.browser_pid}')- browser_proc.kill()- except psutil.NoSuchProcess:- pass- except Exception as e:- self.logger.warning(f'Error force-killing browser in BrowserSession.__del__: {type(e).__name__}: {e}')-- @staticmethod- async def _start_global_playwright_subprocess(is_stealth: bool) -> PlaywrightOrPatchright:- """Create and return a new playwright or patchright node.js subprocess / API connector"""- global GLOBAL_PLAYWRIGHT_API_OBJECT, GLOBAL_PATCHRIGHT_API_OBJECT- global GLOBAL_PLAYWRIGHT_EVENT_LOOP, GLOBAL_PATCHRIGHT_EVENT_LOOP-- try:- current_loop = asyncio.get_running_loop()- except RuntimeError:- current_loop = None-- if is_stealth:- GLOBAL_PATCHRIGHT_API_OBJECT = await async_patchright().start()- GLOBAL_PATCHRIGHT_EVENT_LOOP = current_loop- return GLOBAL_PATCHRIGHT_API_OBJECT- else:- GLOBAL_PLAYWRIGHT_API_OBJECT = await async_playwright().start()- GLOBAL_PLAYWRIGHT_EVENT_LOOP = current_loop- return GLOBAL_PLAYWRIGHT_API_OBJECT-async def setup_playwright(self) -> None:"""Set up playwright library client object: usually the result of (await async_playwright().start())@@ -1282,8 +1232,7 @@ class BrowserSession(BaseModel):# fallback to javascript resize if cdp setWindowBounds failsawait page.evaluate("""(width, height) => {window.resizeTo(width, height)}""",- self.browser_profile.window_size['width'],- self.browser_profile.window_size['height'],+ [self.browser_profile.window_size['width'], self.browser_profile.window_size['height']],)returnexcept Exception:diff --git a/browser_use/cli.py b/browser_use/cli.pyindex cc898d0bf..2f505358c 100644--- a/browser_use/cli.py+++ b/browser_use/cli.py@@ -39,7 +39,7 @@ os.environ['BROWSER_USE_LOGGING_LEVEL'] = 'result'from browser_use import Agent, Controllerfrom browser_use.agent.views import AgentSettings-from browser_use.browser import BrowserSession+from browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.config import CONFIGfrom browser_use.logging_config import addLoggingLevel@@ -200,7 +200,7 @@ def get_llm(config: dict[str, Any]):if not CONFIG.ANTHROPIC_API_KEY:print('⚠️ Anthropic API key not found. Please update your config or set ANTHROPIC_API_KEY environment variable.')sys.exit(1)- return langchain_anthropic.ChatAnthropic(model=model_name, temperature=temperature)+ return langchain_anthropic.ChatAnthropic(model_name=model_name, temperature=temperature, timeout=30, stop=None)elif model_name.startswith('gemini'):if not CONFIG.GOOGLE_API_KEY:print('⚠️ Google API key not found. Please update your config or set GOOGLE_API_KEY environment variable.')@@ -211,7 +211,9 @@ def get_llm(config: dict[str, Any]):if CONFIG.OPENAI_API_KEY:return langchain_openai.ChatOpenAI(model='gpt-4o', temperature=temperature)elif CONFIG.ANTHROPIC_API_KEY:- return langchain_anthropic.ChatAnthropic(model='claude-3.5-sonnet-exp', temperature=temperature)+ return langchain_anthropic.ChatAnthropic(+ model_name='claude-3.5-sonnet-exp', temperature=temperature, timeout=30, stop=None+ )elif CONFIG.GOOGLE_API_KEY:return langchain_google_genai.ChatGoogleGenerativeAI(model='gemini-2.0-flash-lite', temperature=temperature)else:@@ -417,10 +419,10 @@ class BrowserUseApp(App):def __init__(self, config: dict[str, Any], *args, **kwargs):super().__init__(*args, **kwargs)self.config = config- self.browser_session = None # Will be set before app.run_async()- self.controller = None # Will be set before app.run_async()- self.agent = None- self.llm = None # Will be set before app.run_async()+ self.browser_session: BrowserSession | None = None # Will be set before app.run_async()+ self.controller: Controller | None = None # Will be set before app.run_async()+ self.agent: Agent | None = None+ self.llm: Any | None = None # Will be set before app.run_async()self.task_history = config.get('command_history', [])# Track current position in history for up/down navigationself.history_index = len(self.task_history)@@ -434,7 +436,7 @@ class BrowserUseApp(App):pass # Level already exists, which is fine# Get the RichLog widget- rich_log = self.query_one('#results-log')+ rich_log = self.query_one('#results-log', RichLog)# Create and set up the custom handlerlog_handler = RichLogHandler(rich_log)@@ -527,7 +529,7 @@ class BrowserUseApp(App):# Step 3: Focus the input fieldlogger.debug('Focusing input field...')try:- input_field = self.query_one('#task-input')+ input_field = self.query_one('#task-input', Input)input_field.focus()logger.debug('Input field focused')except Exception as e:@@ -548,7 +550,7 @@ 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 event.sender.id != 'task-input':+ if not hasattr(event, 'input') or event.input.id != 'task-input':return# Only process if we have history@@ -558,9 +560,10 @@ class BrowserUseApp(App):# Move back in history if possibleif self.history_index > 0:self.history_index -= 1- self.query_one('#task-input').value = self.task_history[self.history_index]+ task_input = self.query_one('#task-input', Input)+ task_input.value = self.task_history[self.history_index]# Move cursor to end of text- self.query_one('#task-input').cursor_position = len(self.query_one('#task-input').value)+ task_input.cursor_position = len(task_input.value)# Prevent default behavior (cursor movement)event.prevent_default()@@ -569,7 +572,7 @@ 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 event.sender.id != 'task-input':+ if not hasattr(event, 'input') or event.input.id != 'task-input':return# Only process if we have history@@ -579,13 +582,14 @@ class BrowserUseApp(App):# Move forward in history or clear input if at the endif self.history_index < len(self.task_history) - 1:self.history_index += 1- self.query_one('#task-input').value = self.task_history[self.history_index]+ task_input = self.query_one('#task-input', Input)+ task_input.value = self.task_history[self.history_index]# Move cursor to end of text- self.query_one('#task-input').cursor_position = len(self.query_one('#task-input').value)+ task_input.cursor_position = len(task_input.value)elif self.history_index == len(self.task_history) - 1:# At the end of history, go to "new line" stateself.history_index += 1- self.query_one('#task-input').value = ''+ self.query_one('#task-input', Input).value = ''# Prevent default behavior (cursor movement)event.prevent_default()@@ -674,7 +678,7 @@ class BrowserUseApp(App):def update_browser_panel(self) -> None:"""Update browser information panel with details about the browser."""- browser_info = self.query_one('#browser-info')+ browser_info = self.query_one('#browser-info', RichLog)browser_info.clear()# Try to use the agent's browser session if available@@ -769,7 +773,7 @@ class BrowserUseApp(App):def update_model_panel(self) -> None:"""Update model information panel with details about the LLM."""- model_info = self.query_one('#model-info')+ model_info = self.query_one('#model-info', RichLog)model_info.clear()if self.llm:@@ -824,7 +828,7 @@ class BrowserUseApp(App):# Add current state informationif hasattr(self.agent, 'running'):- if self.agent.running:+ if getattr(self.agent, 'running', False):model_info.write('[yellow]LLM is thinking[blink]...[/][/]')elif hasattr(self.agent, 'state') and hasattr(self.agent.state, 'paused') and self.agent.state.paused:model_info.write('[orange]LLM paused[/]')@@ -833,7 +837,7 @@ class BrowserUseApp(App):def update_tasks_panel(self) -> None:"""Update tasks information panel with details about the tasks and steps hierarchy."""- tasks_info = self.query_one('#tasks-info')+ tasks_info = self.query_one('#tasks-info', RichLog)tasks_info.clear()if self.agent:@@ -970,14 +974,14 @@ class BrowserUseApp(App):self.update_info_panels()# Clear the log to start fresh- rich_log = self.query_one('#results-log')+ rich_log = self.query_one('#results-log', RichLog)rich_log.clear()if self.agent is None:self.agent = Agent(task=task,llm=self.llm,- controller=self.controller,+ controller=self.controller if self.controller else None,browser_session=self.browser_session,source='cli',**agent_settings.model_dump(),@@ -993,19 +997,22 @@ class BrowserUseApp(App):logger.debug('\n🚀 Working on task: %s', task)# Set flags to indicate the agent is running- self.agent.running = True- self.agent.last_response_time = 0+ if self.agent:+ self.agent.running = True # type: ignore+ self.agent.last_response_time = 0 # type: ignore# Panel updates are already happening via the timer in update_info_panelstry:# Run the agent task, redirecting output to RichLog through our handler- await self.agent.run()+ if self.agent:+ await self.agent.run()except Exception as e:logger.error('\nError running agent: %s', str(e))finally:# Clear the running flag- self.agent.running = False+ if self.agent:+ self.agent.running = False # type: ignore# No need to call update_info_panels() here as it's already updating via timer@@ -1016,7 +1023,7 @@ class BrowserUseApp(App):task_input_container.display = True# Refocus the input field- input_field = self.query_one('#task-input')+ input_field = self.query_one('#task-input', Input)input_field.focus()# Ensure the input is visible by scrolling to it@@ -1028,7 +1035,7 @@ class BrowserUseApp(App):def action_input_history_prev(self) -> None:"""Navigate to the previous item in command history."""# Only process if we have history and input is focused- input_field = self.query_one('#task-input')+ input_field = self.query_one('#task-input', Input)if not input_field.has_focus or not self.task_history:return@@ -1042,7 +1049,7 @@ class BrowserUseApp(App):def action_input_history_next(self) -> None:"""Navigate to the next item in command history or clear input."""# Only process if we have history and input is focused- input_field = self.query_one('#task-input')+ input_field = self.query_one('#task-input', Input)if not input_field.has_focus or not self.task_history:return@@ -1173,10 +1180,10 @@ async def run_prompt_mode(prompt: str, ctx: click.Context, debug: bool = False):# Create browser session with config parametersbrowser_config = config.get('browser', {})+ # Create BrowserProfile with user_data_dir+ profile = BrowserProfile(user_data_dir=str(USER_DATA_DIR), **browser_config)browser_session = BrowserSession(- stealth=True,- user_data_dir=USER_DATA_DIR,- **browser_config,+ browser_profile=profile,)# Create and run agent@@ -1236,19 +1243,17 @@ async def textual_interface(config: dict[str, Any]):logger.info('Browser mode: visible')# Create BrowserSession directly with config parameters+ # Create BrowserProfile with user_data_dir+ profile = BrowserProfile(user_data_dir=str(USER_DATA_DIR), **browser_config)browser_session = BrowserSession(- stealth=True,- user_data_dir=USER_DATA_DIR,- **browser_config,+ browser_profile=profile,)logger.debug('BrowserSession initialized successfully')# Log browser version if availabletry:- if hasattr(browser_session, 'version') and browser_session.version:- logger.info(f'Browser version: {browser_session.version}')- elif hasattr(browser_session, 'playwright_browser') and browser_session.playwright_browser:- version = browser_session.playwright_browser.version+ if hasattr(browser_session, 'browser') and browser_session.browser:+ version = browser_session.browser.versionlogger.info(f'Browser version: {version}')except Exception as e:logger.debug(f'Could not determine browser version: {e}')diff --git a/browser_use/sync/auth.py b/browser_use/sync/auth.pyindex 98e49ba70..b1e32f1a8 100644--- a/browser_use/sync/auth.py+++ b/browser_use/sync/auth.py@@ -290,9 +290,13 @@ class DeviceAuthClient:except Exception as e:# Log the error details for debuggingif hasattr(e, 'response'):- logger.debug(- f'Failed to get pre-auth token for cloud sync: HTTP {e.response.status_code} - {e.response.text[:200]}'- )+ response = getattr(e, 'response')+ if hasattr(response, 'status_code') and hasattr(response, 'text'):+ logger.debug(+ f'Failed to get pre-auth token for cloud sync: HTTP {response.status_code} - {response.text[:200]}'+ )+ else:+ logger.debug(f'Failed to get pre-auth token for cloud sync: {type(e).__name__}: {e}')else:logger.debug(f'Failed to get pre-auth token for cloud sync: {type(e).__name__}: {e}')diff --git a/examples/browser/multiple_agents_same_browser.py b/examples/browser/multiple_agents_same_browser.pyindex eaec0454b..9cea98329 100644--- a/examples/browser/multiple_agents_same_browser.py+++ b/examples/browser/multiple_agents_same_browser.py@@ -12,14 +12,17 @@ load_dotenv()from langchain_openai import ChatOpenAIfrom browser_use import Agent+from browser_use.browser.profile import BrowserProfilefrom browser_use.browser.session import BrowserSessionasync def main():browser_session = BrowserSession(- keep_alive=True,- user_data_dir=None,- headless=False,+ browser_profile=BrowserProfile(+ keep_alive=True,+ user_data_dir=None,+ headless=False,+ ))await browser_session.start()diff --git a/examples/browser/using_cdp.py b/examples/browser/using_cdp.pyindex f6e72cf86..6168f4204 100644--- a/examples/browser/using_cdp.py+++ b/examples/browser/using_cdp.py@@ -25,14 +25,16 @@ from langchain_google_genai import ChatGoogleGenerativeAIfrom pydantic import SecretStrfrom browser_use import Agent, Controller-from browser_use.browser import BrowserSession+from browser_use.browser import BrowserProfile, BrowserSessionapi_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError('GOOGLE_API_KEY is not set')browser_session = BrowserSession(- headless=False,+ browser_profile=BrowserProfile(+ headless=False,+ ),cdp_url='http://localhost:9222',)controller = Controller()@@ -41,6 +43,8 @@ controller = Controller()async def main():task = 'In docs.google.com write my Papa a quick thank you for everything letter \n - Magnus'task += ' and save the document as pdf'+ # Assert api_key is not None to satisfy type checker+ assert api_key is not None, 'GOOGLE_API_KEY must be set'model = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))agent = Agent(task=task,diff --git a/examples/browser/window_sizing.py b/examples/browser/window_sizing.pyindex 518c7196a..4eb679f25 100644--- a/examples/browser/window_sizing.py+++ b/examples/browser/window_sizing.py@@ -53,12 +53,15 @@ async def example_custom_window_size():actual_content_size = await page.evaluate("""() => ({width: window.innerWidth, height: window.innerHeight})""")if profile.viewport:- expected_page_size = profile.viewport+ expected_page_size = dict(profile.viewport)elif profile.window_size:expected_page_size = {'width': profile.window_size['width'],'height': profile.window_size['height'] - 87,} # 87px is the height of the navbar, title, rim ish+ else:+ # Default expected size if neither viewport nor window_size is set+ expected_page_size = {'width': 800, 'height': 600}_log_size = lambda size: f'{size["width"]}x{size["height"]}px'print(f'Expected {_log_size(expected_page_size)} vs actual {_log_size(actual_content_size)}')@@ -95,7 +98,10 @@ async def example_no_viewport_option():# Get viewport size (inner dimensions)viewport = await page.evaluate('() => ({width: window.innerWidth, height: window.innerHeight})')- print(f'Configured size: width={profile.window_size["width"]}, height={profile.window_size["height"]}')+ if profile.window_size:+ print(f'Configured size: width={profile.window_size["width"]}, height={profile.window_size["height"]}')+ else:+ print('No window size configured')print(f'Actual viewport size: {viewport}')# Get the actual window size (outer dimensions)diff --git a/examples/custom-functions/custom_hooks_before_after_step.py b/examples/custom-functions/custom_hooks_before_after_step.pyindex 9503c533e..b358d5bf4 100644--- a/examples/custom-functions/custom_hooks_before_after_step.py+++ b/examples/custom-functions/custom_hooks_before_after_step.py@@ -148,14 +148,13 @@ async def record_activity(agent_obj):extracted_content_json_last_elem = Noneprint('--- ON_STEP_START HOOK ---')- website_html: str = await agent_obj.browser_context.get_page_html()- website_screenshot: str = await agent_obj.browser_context.take_screenshot()+ website_html = await agent_obj.browser_context.get_page_html()+ website_screenshot = await agent_obj.browser_context.take_screenshot()print('--> History:')- if hasattr(agent_obj, 'state'):- history = agent_obj.state.history- else:- history = None+ # Assert agent has state to satisfy type checker+ assert hasattr(agent_obj, 'state'), 'Agent must have state attribute'+ history = agent_obj.state.historymodel_thoughts = obj_to_json(obj=history.model_thoughts(), check_circular=False)diff --git a/examples/features/download_file.py b/examples/features/download_file.pyindex 912c55486..1c2b03c86 100644--- a/examples/features/download_file.py+++ b/examples/features/download_file.py@@ -18,11 +18,16 @@ api_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError('GOOGLE_API_KEY is not set')+assert api_key is not None, 'GOOGLE_API_KEY must be set'llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))+from browser_use.browser import BrowserProfile+browser_session = BrowserSession(- downloads_path='~/Downloads',- user_data_dir='~/.config/browseruse/profiles/default',+ browser_profile=BrowserProfile(+ downloads_path='~/Downloads',+ user_data_dir='~/.config/browseruse/profiles/default',+ ))diff --git a/examples/features/parallel_agents.py b/examples/features/parallel_agents.pyindex 17b379465..0912a30fa 100644--- a/examples/features/parallel_agents.py+++ b/examples/features/parallel_agents.py@@ -11,13 +11,15 @@ load_dotenv()from langchain_openai import ChatOpenAIfrom browser_use.agent.service import Agent-from browser_use.browser import BrowserSession+from browser_use.browser import BrowserProfile, BrowserSessionbrowser_session = BrowserSession(- keep_alive=True,- headless=False,- save_recording_path='./tmp/recordings',- user_data_dir='~/.config/browseruse/profiles/default',+ browser_profile=BrowserProfile(+ keep_alive=True,+ headless=False,+ record_video_dir='./tmp/recordings',+ user_data_dir='~/.config/browseruse/profiles/default',+ ))llm = ChatOpenAI(model='gpt-4o')diff --git a/examples/features/result_processing.py b/examples/features/result_processing.pyindex b65212afd..38c12847b 100644--- a/examples/features/result_processing.py+++ b/examples/features/result_processing.py@@ -22,7 +22,7 @@ async def main():async with BrowserSession(browser_profile=BrowserProfile(headless=False,- trace_path='./tmp/result_processing',+ traces_dir='./tmp/result_processing',window_size={'width': 1280, 'height': 1000},user_data_dir='~/.config/browseruse/profiles/default',)diff --git a/examples/use-cases/play_chess.py b/examples/use-cases/play_chess.pyindex 5294369f3..114685b5f 100755--- a/examples/use-cases/play_chess.py+++ b/examples/use-cases/play_chess.py@@ -64,7 +64,7 @@ def parse_transform(style: str) -> tuple[float, float] | None:return x_px_str, y_px_strexcept Exception as e:logger.error(f'Error parsing transform style: {e}')- return None, None+ return None, 0.0def algebraic_to_pixels(square: str, square_size: float) -> tuple[str, str]:@@ -164,10 +164,10 @@ async def get_current_board_info(page) -> tuple[str | None, float]:square_size = await calculate_square_size(page)except Exception as e:logger.error(f'Error (get_info): Could not read cg-board: {e}')- return None, None+ return None, 0.0if not board_html or not square_size:- return None, None+ return None, 0.0soup = BeautifulSoup(board_html, 'html.parser')pieces = soup.find_all('piece')@@ -186,7 +186,7 @@ async def get_current_board_info(page) -> tuple[str | None, float]:logger.error(f'Error: {ve}')if not board_state or not square_size:- return None, None+ return None, 0.0fen_board = create_fen_board(board_state)full_fen = f'{fen_board} w KQkq - 0 1'diff --git a/examples/use-cases/post-twitter.py b/examples/use-cases/post-twitter.pyindex 3472d4712..e6ce42196 100644--- a/examples/use-cases/post-twitter.py+++ b/examples/use-cases/post-twitter.py@@ -55,8 +55,11 @@ class TwitterConfig:# Customize these settings+openai_key = os.getenv('OPENAI_API_KEY')+assert openai_key is not None, 'OPENAI_API_KEY must be set'+config = TwitterConfig(- openai_api_key=os.getenv('OPENAI_API_KEY'),+ openai_api_key=openai_key,chrome_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', # This is for MacOS (Chrome)target_user='XXXXX',message='XXXXX',@@ -66,7 +69,9 @@ config = TwitterConfig(def create_twitter_agent(config: TwitterConfig) -> Agent:- llm = ChatOpenAI(model=config.model, api_key=config.openai_api_key)+ from pydantic import SecretStr++ llm = ChatOpenAI(model=config.model, api_key=SecretStr(config.openai_api_key))browser_profile = BrowserProfile(headless=config.headless,@@ -111,7 +116,6 @@ def create_twitter_agent(config: TwitterConfig) -> Agent:async def post_tweet(agent: Agent):try:await agent.run(max_steps=100)- agent.create_history_gif()print('Tweet posted successfully!')except Exception as e:print(f'Error posting tweet: {str(e)}')diff --git a/tests/ci/conftest.py b/tests/ci/conftest.pyindex 7dd58fcf6..e52e91c1e 100644--- a/tests/ci/conftest.py+++ b/tests/ci/conftest.py@@ -24,7 +24,7 @@ os.environ['SKIP_LLM_API_KEY_VERIFICATION'] = 'true'from bubus import BaseEventfrom browser_use import Agent-from browser_use.browser import BrowserSession+from browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.sync.service import CloudSync@@ -147,9 +147,11 @@ def create_mock_llm(actions=None):async def browser_session():"""Create a real browser session for testing"""session = BrowserSession(- headless=True,- user_data_dir=None, # Use temporary directory- keep_alive=True,+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None, # Use temporary directory+ keep_alive=True,+ ))await session.start()yield sessiondiff --git a/tests/ci/test_action_parameter_injection.py b/tests/ci/test_action_parameter_injection.pyindex 945a07579..1770c2a79 100644--- a/tests/ci/test_action_parameter_injection.py+++ b/tests/ci/test_action_parameter_injection.py@@ -58,9 +58,10 @@ class TestBrowserContext:async def browser_session(self):"""Create and provide a BrowserSession 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_agent_multiprocessing.py b/tests/ci/test_agent_multiprocessing.pyindex 009d28c7a..71b08ca40 100644--- a/tests/ci/test_agent_multiprocessing.py+++ b/tests/ci/test_agent_multiprocessing.py@@ -147,9 +147,11 @@ class TestParallelism:# Create a shared browser sessionbrowser_session = BrowserSession(- headless=True,- user_data_dir=None, # Use temp directory- keep_alive=True,+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None, # Use temp directory+ keep_alive=True,+ ))try:@@ -197,9 +199,11 @@ class TestParallelism:# Create a shared browser sessionbrowser_session = BrowserSession(- headless=True,- user_data_dir=None, # Use temp directory- keep_alive=True,+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None, # Use temp directory+ keep_alive=True,+ ))try:@@ -400,9 +404,11 @@ class TestParallelism:# Create shared browser sessionshared_session = BrowserSession(- headless=True,- user_data_dir=None,- keep_alive=True,+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ keep_alive=True,+ ))try:@@ -459,9 +465,11 @@ class TestParallelism:# Create a session with keep_alivesession = BrowserSession(- headless=True,- user_data_dir=None,- keep_alive=True,+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ keep_alive=True,+ ))try:@@ -514,13 +522,15 @@ class TestParallelism:# Create session with existing playwright objectsbrowser_session = BrowserSession(- page=page,+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ keep_alive=False,+ ),+ agent_current_page=page,browser_context=context,browser=browser,playwright=playwright,- headless=True,- user_data_dir=None,- keep_alive=False,)# Create mock LLMdiff --git a/tests/ci/test_browser_session_cookies.py b/tests/ci/test_browser_session_cookies.pyindex d3da458e9..6e5a8ffa2 100644--- a/tests/ci/test_browser_session_cookies.py+++ b/tests/ci/test_browser_session_cookies.py@@ -62,7 +62,7 @@ class TestBrowserSessionCookies:@pytest.fixtureasync def browser_profile_with_cookies(self, temp_cookies_file):"""Create a BrowserProfile with cookies_file set."""- profile = BrowserProfile(headless=True, user_data_dir=None, cookies_file=str(temp_cookies_file))+ profile = BrowserProfile(headless=True, user_data_dir=None, cookies_file=temp_cookies_file)yield profile@pytest.fixture@@ -158,7 +158,7 @@ class TestBrowserSessionCookies:async def test_nonexistent_cookies_file(self):"""Test that browser starts normally when cookies_file doesn't exist."""# Use a non-existent file path- profile = BrowserProfile(headless=True, user_data_dir=None, cookies_file='/tmp/nonexistent_cookies.json')+ profile = BrowserProfile(headless=True, user_data_dir=None, cookies_file=Path('/tmp/nonexistent_cookies.json'))session = BrowserSession(browser_profile=profile)# Should start without errors@@ -176,7 +176,7 @@ class TestBrowserSessionCookies:invalid_file = tmp_path / 'invalid_cookies.json'invalid_file.write_text('not valid json')- profile = BrowserProfile(headless=True, user_data_dir=None, cookies_file=str(invalid_file))+ profile = BrowserProfile(headless=True, user_data_dir=None, cookies_file=invalid_file)session = BrowserSession(browser_profile=profile)# Should start without errors (warning logged)diff --git a/tests/ci/test_sync_client.py b/tests/ci/test_sync_client.pyindex 634a41e27..aacbf992d 100644--- a/tests/ci/test_sync_client.py+++ b/tests/ci/test_sync_client.py@@ -9,6 +9,7 @@ import pytestfrom bubus import BaseEventfrom pytest_httpserver import HTTPServer+from browser_use.agent.cloud_events import CreateAgentTaskEventfrom browser_use.sync.auth import TEMP_USER_ID, DeviceAuthClientfrom browser_use.sync.service import CloudSync@@ -92,7 +93,11 @@ class TestCloudSyncEventHandling:httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)# Send event- await authenticated_sync.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Test task', priority='high'))+ await authenticated_sync.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Test task', user_id='test-user-123'+ )+ )# Verify forwardingassert len(requests) == 1@@ -112,7 +117,11 @@ class TestCloudSyncEventHandling:httpserver.expect_request('/api/v1/events', method='POST').respond_with_json({'error': 'unauthorized'}, status=401)# Send event- await unauthenticated_sync.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Queued task'))+ await unauthenticated_sync.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Queued task', user_id=TEMP_USER_ID+ )+ )# Event should be queuedassert len(unauthenticated_sync.pending_events) == 1@@ -134,7 +143,11 @@ class TestCloudSyncEventHandling:httpserver.expect_request('/api/v1/events', method='POST').respond_with_handler(capture_request)# Send event without user_id- await unauthenticated_sync.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Pre-auth task'))+ await unauthenticated_sync.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Pre-auth task', user_id=TEMP_USER_ID+ )+ )# Verify temp user ID was injectedassert len(requests) == 1@@ -172,8 +185,12 @@ class TestCloudSyncRetryLogic:# Manually add pending events (simulating 401 scenario)sync_with_auth.pending_events.extend([- BaseEvent(event_type='CreateAgentTaskEvent', task='Pending task 1', user_id=TEMP_USER_ID),- BaseEvent(event_type='CreateAgentTaskEvent', task='Pending task 2', user_id=TEMP_USER_ID),+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Pending task 1', user_id=TEMP_USER_ID+ ),+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Pending task 2', user_id=TEMP_USER_ID+ ),])@@ -196,7 +213,11 @@ class TestCloudSyncRetryLogic:httpserver.expect_request('/api/v1/events', method='POST').respond_with_data('Internal Server Error', status=500)# Should not raise exception- await sync_with_auth.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Task during outage'))+ await sync_with_auth.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Task during outage', user_id='test-user-123'+ )+ )# Events should not be queued for 500 errors (only 401)assert len(sync_with_auth.pending_events) == 0@@ -207,7 +228,11 @@ class TestCloudSyncRetryLogic:sync_with_auth.base_url = 'http://localhost:99999' # Invalid port# Should not raise exception- await sync_with_auth.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Task during network error'))+ await sync_with_auth.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Task during network error', user_id='test-user-123'+ )+ )# Should handle gracefully without crashing@@ -228,7 +253,11 @@ class TestCloudSyncRetryLogic:# Send multiple events concurrentlytasks = []for i in range(5):- task = sync_with_auth.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task=f'Concurrent task {i}'))+ task = sync_with_auth.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task=f'Concurrent task {i}', user_id='test-user-123'+ )+ )tasks.append(task)await asyncio.gather(*tasks)@@ -279,7 +308,11 @@ class TestCloudSyncBackendCommunication:service.auth_client = authservice.session_id = 'test-session-id'- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Format validation test'))+ await service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Format validation test', user_id='test-user-123'+ )+ )assert len(requests) == 1@@ -308,7 +341,11 @@ class TestCloudSyncBackendCommunication:service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)service.auth_client = auth- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Auth header test'))+ await service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Auth header test', user_id='test-user-123'+ )+ )# Check auth header was includedassert len(requests) == 1@@ -320,7 +357,9 @@ class TestCloudSyncBackendCommunication:requests.clear()service.auth_client = DeviceAuthClient(base_url=httpserver.url_for('')) # No credentials- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='No auth test'))+ await service.handle_event(+ CreateAgentTaskEvent(agent_session_id='test-session', llm_model='test-model', task='No auth test', user_id='')+ )# Check no auth headerassert len(requests) == 1@@ -342,7 +381,11 @@ class TestCloudSyncErrorHandling:sync_service.base_url = 'http://10.255.255.1' # Non-routable IP for timeout# Should not raise exception- await sync_service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Timeout test'))+ await sync_service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Timeout test', user_id='test-user-123'+ )+ )async def test_malformed_event_handling(self, httpserver: HTTPServer, sync_service):"""Test handling of events that can't be serialized."""@@ -368,7 +411,14 @@ class TestCloudSyncErrorHandling:)# Should not raise exception- await sync_service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task=f'Error {status_code} test'))+ await sync_service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session',+ llm_model='test-model',+ task=f'Error {status_code} test',+ user_id='test-user-123',+ )+ )async def test_invalid_response_handling(self, httpserver: HTTPServer, sync_service):"""Test handling of invalid server responses."""@@ -376,7 +426,11 @@ class TestCloudSyncErrorHandling:httpserver.expect_request('/api/v1/events', method='POST').respond_with_data('Not JSON', status=200)# Should not raise exception- await sync_service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Invalid response test'))+ await sync_service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Invalid response test', user_id='test-user-123'+ )+ )async def test_event_with_restricted_attributes(self, httpserver: HTTPServer, sync_service):"""Test handling events that don't allow user_id attribute."""@@ -420,7 +474,14 @@ class TestCloudSyncErrorHandling:# Send 10 events concurrentlytasks = []for i in range(10):- task = sync_service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task=f'Concurrent error test {i}'))+ task = sync_service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session',+ llm_model='test-model',+ task=f'Concurrent error test {i}',+ user_id='test-user-123',+ )+ )tasks.append(task)# All should complete without raisingdiff --git a/tests/ci/test_sync_client_auth.py b/tests/ci/test_sync_client_auth.pyindex 3dc9ff080..876e6e0af 100644--- a/tests/ci/test_sync_client_auth.py+++ b/tests/ci/test_sync_client_auth.py@@ -16,8 +16,8 @@ from pytest_httpserver import HTTPServer# Load environment variables before any importsload_dotenv()-from bubus import BaseEvent+from browser_use.agent.cloud_events import CreateAgentSessionEvent, CreateAgentTaskEventfrom browser_use.sync.auth import TEMP_USER_ID, DeviceAuthClientfrom browser_use.sync.service import CloudSync@@ -355,12 +355,11 @@ class TestCloudSync:service.session_id = 'test-session-id'# Send event- event_data = {- 'task': 'Test task',- 'status': 'running',- }-- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', **event_data))+ await service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Test task', user_id='test-user-123'+ )+ )# Check request was madeassert len(requests) == 1@@ -404,12 +403,9 @@ class TestCloudSync:service.session_id = 'test-session-id'# Send event- event_data = {- 'task': 'Test task',- 'status': 'running',- }-- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', **event_data))+ await service.handle_event(+ CreateAgentTaskEvent(agent_session_id='test-session', llm_model='test-model', task='Test task', user_id=TEMP_USER_ID)+ )# Check request was made without auth headerassert len(requests) == 1@@ -460,7 +456,11 @@ class TestCloudSync:service.session_id = 'test-session-id'# Send pre-auth event (should get 401 and be queued)- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Pre-auth task'))+ await service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Pre-auth task', user_id=TEMP_USER_ID+ )+ )# Event should be in pending_events since we got 401assert len(service.pending_events) == 1@@ -503,7 +503,11 @@ class TestCloudSync:service.session_id = 'test-session-id'# Send event - should not raise exception but handle gracefully- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Test task'))+ await service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Test task', user_id='test-user-123'+ )+ )# Should handle error gracefully without crashing@@ -640,7 +644,14 @@ class TestIntegration:service.session_id = 'test-session-id'# Send pre-auth event- await service.handle_event(BaseEvent(event_type='CreateAgentSessionEvent', started_at=datetime.utcnow().isoformat()))+ await service.handle_event(+ CreateAgentSessionEvent(+ user_id=TEMP_USER_ID,+ browser_session_id='test-browser-session',+ browser_session_live_url='http://example.com/live',+ browser_session_cdp_url='ws://example.com/cdp',+ )+ )# Authenticateauthenticated = await service.authenticate(show_instructions=False)@@ -650,7 +661,11 @@ class TestIntegration:assert service.auth_client.user_id == 'test-user-123'# Send authenticated event- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Authenticated task'))+ await service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Authenticated task', user_id='test-user-123'+ )+ )# Verify auth was savedauth_file = temp_config_dir / 'cloud_auth.json'@@ -712,7 +727,14 @@ class TestAuthResilience:service.auth_client = auth# Send event - should not raise exception even though token is expired- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Test task after token expiry'))+ await service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session',+ llm_model='test-model',+ task='Test task after token expiry',+ user_id='test-user-123',+ )+ )# Agent should continue functioning despite sync failureassert True # No exception raised@@ -744,7 +766,11 @@ class TestAuthResilience:).respond_with_json({'processed': 1, 'failed': 0})# Should be able to send events without auth (pre-auth mode)- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Test task without auth'))+ await service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task='Test task without auth', user_id=''+ )+ )async def test_server_downtime_resilience(self, httpserver: HTTPServer, http_client, temp_config_dir):"""Test that server downtime doesn't break the agent."""@@ -763,7 +789,14 @@ class TestAuthResilience:# Should be able to send events even when server is down# They will be queued locally- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Test task during server downtime'))+ await service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session',+ llm_model='test-model',+ task='Test task during server downtime',+ user_id='test-user-123',+ )+ )async def test_excessive_event_queue_handling(self, httpserver: HTTPServer, http_client, temp_config_dir):"""Test that excessive event queuing doesn't break the agent."""@@ -776,7 +809,11 @@ class TestAuthResilience:# Send many events while server is down (no responses configured)for i in range(100):- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task=f'Test task {i}'))+ await service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session', llm_model='test-model', task=f'Test task {i}', user_id='test-user-123'+ )+ )# Agent should still be functioningassert True # No memory issues or crashes@@ -809,4 +846,11 @@ class TestAuthResilience:service.auth_client = auth# Should handle malformed event response gracefully- await service.handle_event(BaseEvent(event_type='CreateAgentTaskEvent', task='Test task with malformed response'))+ await service.handle_event(+ CreateAgentTaskEvent(+ agent_session_id='test-session',+ llm_model='test-model',+ task='Test task with malformed response',+ user_id='test-user-123',+ )+ )