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
commit missing changes
Anish Hiranandani91ce6bc19c19
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlnew file mode 100644index 000000000..635566137--- /dev/null+++ b/.github/workflows/lint.yml@@ -0,0 +1,17 @@+name: Lint+on:+ push:+ pull_request:+ workflow_dispatch:+jobs:+ ruff:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: astral-sh/setup-uv@v5+ - run: uv run ruff format+ - run: uv run pre-commit run check-toml --all-files+ - run: uv run pre-commit run check-yaml --all-files+ - run: uv run pre-commit run end-of-file-fixer --all-files+ - run: uv run pre-commit run trailing-whitespace --all-files+ #- run: uv run pytest tests/conftest.pydiff --git a/browser_use/browser/chrome.py b/browser_use/browser/chrome.pynew file mode 100644index 000000000..8626b3230--- /dev/null+++ b/browser_use/browser/chrome.py@@ -0,0 +1,184 @@+CHROME_DEFAULT_USER_AGENT = (+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'+)+CHROME_EXTENSIONS = {} # coming in a separate PR+CHROME_EXTENSIONS_PATH = 'chrome_extensions'+CHROME_PROFILE_PATH = 'chrome_profile'+CHROME_PROFILE_USER = 'Default'+CHROME_DEBUG_PORT = 9222+CHROME_DISABLED_COMPONENTS = [+ 'Translate',+ 'AcceptCHFrame',+ 'OptimizationHints',+ 'ProcessPerSiteUpToMainFrameThreshold',+ 'InterestFeedContentSuggestions',+ 'CalculateNativeWinOcclusion',+ 'BackForwardCache',+ 'HeavyAdPrivacyMitigations',+ 'LazyFrameLoading',+ 'ImprovedCookieControls',+ 'PrivacySandboxSettings4',+ 'AutofillServerCommunication',+ 'CertificateTransparencyComponentUpdater',+ 'DestroyProfileOnBrowserClose',+ 'CrashReporting',+ 'OverscrollHistoryNavigation',+ 'InfiniteSessionRestore',+ #'LockProfileCookieDatabase', # disabling allows multiple chrome instances to concurrently modify profile, but might make chrome much slower https://github.com/yt-dlp/yt-dlp/issues/7271 https://issues.chromium.org/issues/40901624+] # it's always best to give each chrome instance its own exclusive copy of the user profile+++CHROME_HEADLESS_ARGS = [+ '--headless=new',+ '--test-type',+ '--test-type=gpu', # https://github.com/puppeteer/puppeteer/issues/10516+ # '--enable-automation', # <- DONT USE THIS, it makes you easily detectable / blocked by cloudflare+]++CHROME_DOCKER_ARGS = [+ # Docker-specific options+ # https://github.com/GoogleChrome/lighthouse-ci/tree/main/docs/recipes/docker-client#--no-sandbox-issues-explained+ '--no-sandbox', # rely on docker sandboxing in docker, otherwise we need cap_add: SYS_ADM to use host sandboxing+ '--disable-gpu-sandbox',+ '--disable-setuid-sandbox',+ '--disable-dev-shm-usage', # docker 75mb default shm size is not big enough, disabling just uses /tmp instead+ '--no-xshm',+ # dont try to disable (or install) dbus in docker, its not needed, chrome can work without dbus despite the errors+]++CHROME_DISABLE_SECURITY_ARGS = [+ # DANGER: JS isolation security features (to allow easier tampering with pages during automation)+ # chrome://net-internals+ '--disable-web-security', # <- WARNING, breaks some sites that expect/enforce strict CORS headers (try webflow.com)+ '--disable-site-isolation-trials',+ '--disable-features=IsolateOrigins,site-per-process',+ # '--allow-file-access-from-files', # <- WARNING, dangerous, allows JS to read filesystem using file:// URLs+ # DANGER: Disable HTTPS verification+ '--allow-running-insecure-content', # Breaks CORS/CSRF/HSTS etc., useful sometimes but very easy to detect+ '--ignore-certificate-errors',+ '--ignore-ssl-errors',+ '--ignore-certificate-errors-spki-list',+ '--allow-insecure-localhost',+]++# flags to make chrome behave more deterministically across different OS's+CHROME_DETERMINISTIC_RENDERING_ARGS = [+ '--deterministic-mode',+ '--js-flags=--random-seed=1157259159', # make all JS random numbers deterministic by providing a seed+ '--force-device-scale-factor=1',+ '--hide-scrollbars', # hide scrollbars because otherwise they show up in screenshots+ # GPU, canvas, text, and pdf rendering config+ # chrome://gpu+ '--enable-webgl', # enable web-gl graphics support+ '--font-render-hinting=none', # make rendering more deterministic by ignoring OS font hints, may also need css override, try: * {text-rendering: geometricprecision !important; -webkit-font-smoothing: antialiased;}+ '--force-color-profile=srgb', # make rendering more deterministic by using consitent color profile, if browser looks weird, try: generic-rgb+ '--disable-partial-raster', # make rendering more deterministic (TODO: verify if still needed)+ '--disable-skia-runtime-opts', # make rendering more deterministic by avoiding Skia hot path runtime optimizations+ '--disable-2d-canvas-clip-aa', # make rendering more deterministic by disabling antialiasing on 2d canvas clips+ # '--disable-gpu', # falls back to more consistent software renderer across all OS's, especially helps linux text rendering look less weird+ # // '--use-gl=swiftshader', <- DO NOT USE, breaks M1 ARM64. it makes rendering more deterministic by using simpler CPU renderer instead of OS GPU renderer bug: https://groups.google.com/a/chromium.org/g/chromium-dev/c/8eR2GctzGuw+ # // '--disable-software-rasterizer', <- DO NOT USE, harmless, used in tandem with --disable-gpu+ # // '--run-all-compositor-stages-before-draw', <- DO NOT USE, makes headful chrome hang on startup (tested v121 Google Chrome.app on macOS)+ # // '--disable-gl-drawing-for-tests', <- DO NOT USE, disables gl output (makes tests run faster if you dont care about canvas)+ # // '--blink-settings=imagesEnabled=false', <- DO NOT USE, disables images entirely (only sometimes useful to speed up loading)+ # Process management & performance tuning+ # chrome://process-internals+ '--disable-lazy-loading', # make rendering more deterministic by loading all content up-front instead of on-focus+ '--disable-renderer-backgrounding', # dont throttle tab rendering based on focus/visibility+ '--disable-background-networking', # dont throttle tab networking based on focus/visibility+ '--disable-background-timer-throttling', # dont throttle tab timers based on focus/visibility+ '--disable-backgrounding-occluded-windows', # dont throttle tab window based on focus/visibility+ '--disable-ipc-flooding-protection', # dont throttle ipc traffic or accessing big request/response/buffer/etc. objects will fail+ '--disable-extensions-http-throttling', # dont throttle http traffic based on runtime heuristics+ '--disable-field-trial-config', # disable shared field trial state between browser processes+ '--disable-back-forward-cache', # disable browsing navigation cache+]++CHROME_ARGS = [+ # Profile data dir setup+ # chrome://profile-internals+ # f'--user-data-dir={CHROME_PROFILE_PATH}', # managed by playwright arg instead+ # f'--profile-directory={CHROME_PROFILE_USER}',+ '--password-store=basic', # use mock keychain instead of OS-provided keychain (we manage auth.json instead)+ '--use-mock-keychain',+ '--disable-cookie-encryption', # we need to be able to write unencrypted cookies to save/load auth.json+ '--disable-sync', # don't try to use Google account sync features while automation is active+ # Extensions+ # chrome://inspect/#extensions+ # f'--load-extension={CHROME_EXTENSIONS.map(({unpacked_path}) => unpacked_path).join(',')}', # not needed when using existing profile that already has extensions installed+ # f'--allowlisted-extension-id={",".join(CHROME_EXTENSIONS.keys())}',+ '--allow-legacy-extension-manifests',+ '--allow-pre-commit-input', # allow JS mutations before page rendering is complete+ '--disable-blink-features=AutomationControlled', # hide the signatures that announce browser is being remote-controlled+ # f'--proxy-server=https://43.159.28.126:2334:u7ce652b7568805c4-zone-custom-region-us-session-szGWq3FRU-sessTime-60:u7ce652b7568805c4', # send all network traffic through a proxy https://2captcha.com/proxy+ # f'--proxy-bypass-list=127.0.0.1',+ # Browser window and viewport setup+ # chrome://version+ # f'--user-agent="{DEFAULT_USER_AGENT}"',+ # f'--window-size={DEFAULT_VIEWPORT.width},{DEFAULT_VIEWPORT.height}',+ # '--window-position=0,0',+ # '--start-maximized',+ '--install-autogenerated-theme=0,0,0', # black border makes it easier to see which chrome window is browser-use's+ #'--virtual-time-budget=60000', # fast-forward all animations & timers by 60s, dont use this it's unfortunately buggy and breaks screenshot and PDF capture sometimes+ #'--autoplay-policy=no-user-gesture-required', # auto-start videos so they trigger network requests + show up in outputs+ #'--disable-gesture-requirement-for-media-playback',+ #'--lang=en-US,en;q=0.9',+ # IO: stdin/stdout, debug port config+ # chrome://inspect+ '--log-level=2', # 1=DEBUG 2=WARNING 3=ERROR+ '--enable-logging=stderr',+ '--remote-debugging-address=0.0.0.0',+ f'--remote-debugging-port={CHROME_DEBUG_PORT}',+ '--enable-experimental-extension-apis', # add support for tab groups+ '--disable-focus-on-load', # prevent browser from hijacking focus+ '--disable-window-activation',+ # '--in-process-gpu', <- DONT USE THIS, makes headful startup time ~5-10s slower (tested v121 Google Chrome.app on macOS)+ # '--disable-component-extensions-with-background-pages', # TODO: check this, disables chrome components that only run in background with no visible UI (could lower startup time)+ # uncomment to disable hardware camera/mic/speaker access + present fake devices to websites+ # (faster to disable, but disabling breaks recording browser audio in puppeteer-stream screenrecordings)+ # '--use-fake-device-for-media-stream',+ # '--use-fake-ui-for-media-stream',+ # '--disable-features=GlobalMediaControls,MediaRouter,DialMediaRouteProvider',+ # Output format options (PDF, screenshot, etc.)+ '--export-tagged-pdf', # include table on contents and tags in printed PDFs+ '--generate-pdf-document-outline',+ # Suppress first-run features, popups, hints, updates, etc.+ # chrome://system+ '--no-pings',+ '--no-first-run',+ '--no-default-browser-check',+ '--no-startup-window',+ '--disable-default-apps',+ '--ash-no-nudges',+ '--disable-infobars',+ '--disable-search-engine-choice-screen',+ '--disable-session-crashed-bubble',+ '--simulate-outdated-no-au="Tue, 31 Dec 2099 23:59:59 GMT"', # disable browser self-update while automation is active+ '--hide-crash-restore-bubble',+ '--suppress-message-center-popups',+ '--disable-client-side-phishing-detection',+ '--disable-domain-reliability',+ '--disable-component-update',+ '--disable-datasaver-prompt',+ '--disable-hang-monitor',+ '--disable-session-crashed-bubble',+ '--disable-speech-synthesis-api',+ '--disable-speech-api',+ '--disable-print-preview',+ '--safebrowsing-disable-auto-update',+ '--deny-permission-prompts',+ '--disable-external-intent-requests',+ '--disable-notifications',+ '--disable-desktop-notifications',+ '--noerrdialogs',+ '--disable-popup-blocking',+ '--disable-prompt-on-repost',+ '--silent-debugger-extension-api',+ '--block-new-web-contents',+ '--metrics-recording-only',+ '--disable-breakpad',+ # other feature flags+ # chrome://flags chrome://components+ f'--disable-features={",".join(CHROME_DISABLED_COMPONENTS)}',+ '--enable-features=NetworkService',+]diff --git a/browser_use/browser/dolphin_service.py b/browser_use/browser/dolphin_service.pynew file mode 100644index 000000000..971f09ae9--- /dev/null+++ b/browser_use/browser/dolphin_service.py@@ -0,0 +1,349 @@+import logging+import os+from typing import List, Optional++import aiohttp+from playwright.async_api import Page, async_playwright++from browser_use.browser.service import Browser+from browser_use.browser.views import BrowserState, TabInfo++logger = logging.getLogger(__name__)+++class DolphinBrowser(Browser):+ """A class for managing Dolphin Anty browser sessions using Playwright"""++ def __init__(self, headless: bool = False, keep_open: bool = False):+ """+ Initialize the DolphinBrowser instance.++ Args:+ headless (bool): Run browser in headless mode (default: False).+ keep_open (bool): Keep browser open after finishing tasks (default: False).+ """+ # Retrieve environment variables for API connection+ self.api_token = os.getenv('DOLPHIN_API_TOKEN')+ self.api_url = os.getenv('DOLPHIN_API_URL', 'http://localhost:3001/v1.0')+ self.profile_id = os.getenv('DOLPHIN_PROFILE_ID')++ # Initialize internal attributes+ self.playwright = None+ self.browser = None+ self.context = None+ self.page = None+ self.headless = headless+ self.keep_open = keep_open+ self._pages: List[Page] = [] # List to store open pages+ self.session = None+ self.cached_state = None++ async def get_current_page(self) -> Page:+ """+ Get the currently active page.++ Raises:+ Exception: If no active page is available.+ """+ if not self.page:+ raise Exception('No active page. Browser might not be connected.')+ return self.page++ async def create_new_tab(self, url: str | None = None) -> None:+ """+ Create a new tab and optionally navigate to a given URL.++ Args:+ url (str, optional): URL to navigate to after creating the tab. Defaults to None.++ Raises:+ Exception: If browser context is not initialized or navigation fails.+ """+ if not self.context:+ raise Exception('Browser context not initialized')++ # Create new page (tab) in the current browser context+ new_page = await self.context.new_page()+ self._pages.append(new_page)+ self.page = new_page # Set as current page++ if url:+ try:+ # Navigate to the URL and wait for the page to load+ await new_page.goto(url, wait_until='networkidle')+ await self.wait_for_page_load()+ except Exception as e:+ logger.error(f'Failed to navigate to URL {url}: {str(e)}')+ raise++ async def switch_to_tab(self, page_id: int) -> None:+ """+ Switch to a specific tab by its page ID.++ Args:+ page_id (int): The index of the tab to switch to.++ Raises:+ Exception: If the tab index is out of range or no tabs are available.+ """+ if not self._pages:+ raise Exception('No tabs available')++ # Handle negative indices (e.g., -1 for last tab)+ if page_id < 0:+ page_id = len(self._pages) + page_id++ if page_id >= len(self._pages) or page_id < 0:+ raise Exception(f'Tab index {page_id} out of range')++ # Set the current page to the selected tab+ self.page = self._pages[page_id]+ await self.page.bring_to_front() # Bring tab to the front+ await self.wait_for_page_load()++ async def get_tabs_info(self) -> list[TabInfo]:+ """+ Get information about all open tabs.++ Returns:+ list: A list of TabInfo objects containing details about each tab.+ """+ tabs_info = []+ for idx, page in enumerate(self._pages):+ tab_info = TabInfo(+ page_id=idx,+ url=page.url,+ title=await page.title(), # Fetch the title of the page+ )+ tabs_info.append(tab_info)+ return tabs_info++ async def wait_for_page_load(self, timeout: int = 30000):+ """+ Wait for the page to load completely.++ Args:+ timeout (int): Maximum time to wait for page load in milliseconds (default: 30000ms).++ Raises:+ Exception: If the page fails to load within the specified timeout.+ """+ if self.page:+ try:+ await self.page.wait_for_load_state('networkidle', timeout=timeout)+ except Exception as e:+ logger.warning(f'Wait for page load timeout: {str(e)}')++ async def get_session(self):+ """+ Get the current session.++ Returns:+ DolphinBrowser: The current DolphinBrowser instance.++ Raises:+ Exception: If the browser is not connected.+ """+ if not self.browser:+ raise Exception('Browser not connected. Call connect() first.')+ self.session = self+ return self++ async def authenticate(self):+ """+ Authenticate with Dolphin Anty API using the API token.++ Raises:+ Exception: If authentication fails.+ """+ async with aiohttp.ClientSession() as session:+ auth_url = f'{self.api_url}/auth/login-with-token'+ auth_data = {'token': self.api_token}+ async with session.post(auth_url, json=auth_data) as response:+ if not response.ok:+ raise Exception(f'Failed to authenticate with Dolphin Anty: {await response.text()}')+ return await response.json()++ async def get_browser_profiles(self):+ """+ Get a list of available browser profiles from Dolphin Anty.++ Returns:+ list: A list of browser profiles.++ Raises:+ Exception: If fetching the browser profiles fails.+ """+ # Authenticate before fetching profiles+ await self.authenticate()++ async with aiohttp.ClientSession() as session:+ headers = {'Authorization': f'Bearer {self.api_token}'}+ async with session.get(f'{self.api_url}/browser_profiles', headers=headers) as response:+ if not response.ok:+ raise Exception(f'Failed to get browser profiles: {await response.text()}')+ data = await response.json()+ return data.get('data', []) # Return the profiles array from the response++ async def start_profile(self, profile_id: Optional[str] = None, headless: bool = False) -> dict:+ """+ Start a browser profile on Dolphin Anty.++ Args:+ profile_id (str, optional): Profile ID to start (defaults to the one set in the environment).+ headless (bool): Run browser in headless mode (default: False).++ Returns:+ dict: Information about the started profile.++ Raises:+ ValueError: If no profile ID is provided and no default is set.+ Exception: If starting the profile fails.+ """+ # Authenticate before starting the profile+ await self.authenticate()++ profile_id = profile_id or self.profile_id+ if not profile_id:+ raise ValueError('No profile ID provided')++ url = f'{self.api_url}/browser_profiles/{profile_id}/start'+ params = {'automation': 1}+ if headless:+ params['headless'] = 1++ async with aiohttp.ClientSession() as session:+ async with session.get(url, params=params) as response:+ if not response.ok:+ raise Exception(f'Failed to start profile: {await response.text()}')+ return await response.json()++ async def stop_profile(self, profile_id: Optional[str] = None):+ """+ Stop a browser profile on Dolphin Anty.++ Args:+ profile_id (str, optional): Profile ID to stop (defaults to the one set in the environment).++ Returns:+ dict: Information about the stopped profile.++ Raises:+ ValueError: If no profile ID is provided and no default is set.+ """+ # Authenticate before stopping the profile+ await self.authenticate()++ profile_id = profile_id or self.profile_id+ if not profile_id:+ raise ValueError('No profile ID provided')++ url = f'{self.api_url}/browser_profiles/{profile_id}/stop'+ async with aiohttp.ClientSession() as session:+ async with session.get(url) as response:+ return await response.json()++ async def connect(self, profile_id: Optional[str] = None):+ """+ Connect to a running browser profile using Playwright.++ Args:+ profile_id (str, optional): Profile ID to connect to (defaults to the one set in the environment).++ Returns:+ PlaywrightBrowser: The connected browser instance.++ Raises:+ Exception: If authentication or profile connection fails.+ """+ # Authenticate before connecting to the profile+ await self.authenticate()++ # Start the browser profile+ profile_data = await self.start_profile(profile_id)++ if not profile_data.get('success'):+ raise Exception(f'Failed to start profile: {profile_data}')++ automation = profile_data['automation']+ port = automation['port']+ ws_endpoint = automation['wsEndpoint']+ ws_url = f'ws://127.0.0.1:{port}{ws_endpoint}'++ # Use Playwright to connect to the browser's WebSocket endpoint+ self.playwright = await async_playwright().start()+ self.browser = await self.playwright.chromium.connect_over_cdp(ws_url)++ # Get or create a browser context and page+ contexts = self.browser.contexts+ self.context = contexts[0] if contexts else await self.browser.new_context()+ pages = self.context.pages+ self.page = pages[0] if pages else await self.context.new_page()++ self._pages = [self.page] # Initialize pages list with the first page++ return self.browser++ async def close(self, force: bool = False):+ """+ Close the browser connection and clean up resources.++ Args:+ force (bool): If True, forcefully stop the associated profile (default: False).+ """+ try:+ # Close all open pages+ if self._pages:+ for page in self._pages:+ try:+ await page.close()+ except:+ pass+ self._pages = []++ # Close the browser and Playwright instance+ if self.browser:+ await self.browser.close()++ if self.playwright:+ await self.playwright.stop()++ if force:+ await self.stop_profile() # Force stop the profile+ except Exception as e:+ logger.error(f'Error during browser cleanup: {str(e)}')++ async def get_current_state(self) -> BrowserState:+ """+ Get the current state of the browser (URL, content, viewport size, tabs).++ Returns:+ BrowserState: The current state of the browser.++ Raises:+ Exception: If no active page is available.+ """+ if not self.page:+ raise Exception('No active page')++ # Get page content and viewport size+ content = await self.page.content()+ viewport_size = await self.page.viewport_size()++ # Create and return the current browser state+ state = BrowserState(+ url=self.page.url,+ content=content,+ viewport_height=viewport_size['height'] if viewport_size else 0,+ viewport_width=viewport_size['width'] if viewport_size else 0,+ tabs=await self.get_tabs_info(),+ )++ # Cache and return the state+ self.cached_state = state+ return state++ def __del__(self):+ """Clean up resources when the DolphinBrowser instance is deleted."""+ # No need to handle session cleanup as we're using self as session+ passdiff --git a/browser_use/exceptions.py b/browser_use/exceptions.pynew file mode 100644index 000000000..b4d10766a--- /dev/null+++ b/browser_use/exceptions.py@@ -0,0 +1,5 @@+class LLMException(Exception):+ def __init__(self, status_code, message):+ self.status_code = status_code+ self.message = message+ super().__init__(f"Error {status_code}: {message}")\ No newline at end of filediff --git a/docs/customize/hooks.mdx b/docs/customize/hooks.mdxnew file mode 100644index 000000000..8b9de9e17--- /dev/null+++ b/docs/customize/hooks.mdx@@ -0,0 +1,346 @@+---+title: "Lifecycle Hooks"+description: "Customize agent behavior with lifecycle hooks"+icon: "Wrench"+author: "Carlos A. Planchón"+---++# Using Agent Lifecycle Hooks++Browser-Use provides lifecycle hooks that allow you to execute custom code at specific points during the agent's execution. These hooks enable you to capture detailed information about the agent's actions, modify behavior, or integrate with external systems.++## Available Hooks++Currently, Browser-Use provides the following hooks:++| Hook | Description | When it's called |+| ---- | ----------- | ---------------- |+| `on_step_start` | Executed at the beginning of each agent step | Before the agent processes the current state and decides on the next action |+| `on_step_end` | Executed at the end of each agent step | After the agent has executed the action for the current step |++## Using Hooks++Hooks are passed as parameters to the `agent.run()` method. Each hook should be a callable function that accepts the agent instance as its parameter.++### Basic Example++```python+from browser_use import Agent+from langchain_openai import ChatOpenAI++async def my_step_hook(agent):+ # inside a hook you can access all the state and methods under the Agent object:+ # agent.settings, agent.state, agent.task+ # agent.controller, agent.llm, agent.browser, agent.browser_context+ # agent.pause(), agent.resume(), agent.add_new_task(...), etc.++ current_page = await agent.browser_context.get_current_page()++ visit_log = agent.state.history.urls()+ current_url = current_page.url+ previous_url = visit_log[-2] if len(visit_log) >= 2 else None+ print(f"Agent was last on URL: {previous_url} and is now on {current_url}")++ if 'completed' in current_url:+ agent.pause()+ Path('result.txt').write_text(await current_page.content())+ input('Saved "completed" page content to result.txt, press [Enter] to resume...')+ agent.resume()++agent = Agent(+ task="Search for the latest news about AI",+ llm=ChatOpenAI(model="gpt-4o"),+)++await agent.run(+ on_step_start=my_step_hook,+ # on_step_end=...+ max_steps=10+)+```++## Complete Example: Agent Activity Recording System++This comprehensive example demonstrates a complete implementation for recording and saving Browser-Use agent activity, consisting of both server and client components.++### Setup Instructions++To use this example, you'll need to:++1. Set up the required dependencies:+ ```bash+ pip install fastapi uvicorn prettyprinter pyobjtojson dotenv browser-use langchain-openai+ ```++2. Create two separate Python files:+ - `api.py` - The FastAPI server component+ - `client.py` - The Browser-Use agent with recording hook++3. Run both components:+ - Start the API server first: `python api.py`+ - Then run the client: `python client.py`++### Server Component (api.py)++The server component handles receiving and storing the agent's activity data:++```python+#!/usr/bin/env python3++#+# FastAPI API to record and save Browser-Use activity data.+# Save this code to api.py and run with `python api.py`+#++import json+import base64+from pathlib import Path++from fastapi import FastAPI, Request+import prettyprinter+import uvicorn++prettyprinter.install_extras()++# Utility function to save screenshots+def b64_to_png(b64_string: str, output_file):+ """+ Convert a Base64-encoded string to a PNG file.++ :param b64_string: A string containing Base64-encoded data+ :param output_file: The path to the output PNG file+ """+ with open(output_file, "wb") as f:+ f.write(base64.b64decode(b64_string))++# Initialize FastAPI app+app = FastAPI()++[email protected]("/post_agent_history_step")+async def post_agent_history_step(request: Request):+ data = await request.json()+ prettyprinter.cpprint(data)++ # Ensure the "recordings" folder exists using pathlib+ recordings_folder = Path("recordings")+ recordings_folder.mkdir(exist_ok=True)++ # Determine the next file number by examining existing .json files+ existing_numbers = []+ for item in recordings_folder.iterdir():+ if item.is_file() and item.suffix == ".json":+ try:+ file_num = int(item.stem)+ existing_numbers.append(file_num)+ except ValueError:+ # In case the file name isn't just a number+ pass++ if existing_numbers:+ next_number = max(existing_numbers) + 1+ else:+ next_number = 1++ # Construct the file path+ file_path = recordings_folder / f"{next_number}.json"++ # Save the JSON data to the file+ with file_path.open("w") as f:+ json.dump(data, f, indent=2)++ # Optionally save screenshot if needed+ # if "website_screenshot" in data and data["website_screenshot"]:+ # screenshot_folder = Path("screenshots")+ # screenshot_folder.mkdir(exist_ok=True)+ # b64_to_png(data["website_screenshot"], screenshot_folder / f"{next_number}.png")++ return {"status": "ok", "message": f"Saved to {file_path}"}++if __name__ == "__main__":+ print("Starting Browser-Use recording API on http://0.0.0.0:9000")+ uvicorn.run(app, host="0.0.0.0", port=9000)+```++### Client Component (client.py)++The client component runs the Browser-Use agent with a recording hook:++```python+#!/usr/bin/env python3++#+# Client to record and save Browser-Use activity.+# Save this code to client.py and run with `python client.py`+#++import asyncio+import requests+from dotenv import load_dotenv+from pyobjtojson import obj_to_json+from langchain_openai import ChatOpenAI+from browser_use import Agent++# Load environment variables (for API keys)+load_dotenv()+++def send_agent_history_step(data):+ """Send the agent step data to the recording API"""+ url = "http://127.0.0.1:9000/post_agent_history_step"+ response = requests.post(url, json=data)+ return response.json()+++async def record_activity(agent_obj):+ """Hook function that captures and records agent activity at each step"""+ website_html = None+ website_screenshot = None+ urls_json_last_elem = None+ model_thoughts_last_elem = None+ model_outputs_json_last_elem = None+ model_actions_json_last_elem = None+ extracted_content_json_last_elem = None++ print('--- ON_STEP_START HOOK ---')++ # Capture current page state+ website_html = await agent_obj.browser_context.get_page_html()+ website_screenshot = await agent_obj.browser_context.take_screenshot()++ # Make sure we have state history+ if hasattr(agent_obj, "state"):+ history = agent_obj.state.history+ else:+ history = None+ print("Warning: Agent has no state history")+ return++ # Process model thoughts+ model_thoughts = obj_to_json(+ obj=history.model_thoughts(),+ check_circular=False+ )+ if len(model_thoughts) > 0:+ model_thoughts_last_elem = model_thoughts[-1]++ # Process model outputs+ model_outputs = agent_obj.state.history.model_outputs()+ model_outputs_json = obj_to_json(+ obj=model_outputs,+ check_circular=False+ )+ if len(model_outputs_json) > 0:+ model_outputs_json_last_elem = model_outputs_json[-1]++ # Process model actions+ model_actions = agent_obj.state.history.model_actions()+ model_actions_json = obj_to_json(+ obj=model_actions,+ check_circular=False+ )+ if len(model_actions_json) > 0:+ model_actions_json_last_elem = model_actions_json[-1]++ # Process extracted content+ extracted_content = agent_obj.state.history.extracted_content()+ extracted_content_json = obj_to_json(+ obj=extracted_content,+ check_circular=False+ )+ if len(extracted_content_json) > 0:+ extracted_content_json_last_elem = extracted_content_json[-1]++ # Process URLs+ urls = agent_obj.state.history.urls()+ urls_json = obj_to_json(+ obj=urls,+ check_circular=False+ )+ if len(urls_json) > 0:+ urls_json_last_elem = urls_json[-1]++ # Create a summary of all data for this step+ model_step_summary = {+ "website_html": website_html,+ "website_screenshot": website_screenshot,+ "url": urls_json_last_elem,+ "model_thoughts": model_thoughts_last_elem,+ "model_outputs": model_outputs_json_last_elem,+ "model_actions": model_actions_json_last_elem,+ "extracted_content": extracted_content_json_last_elem+ }++ print("--- MODEL STEP SUMMARY ---")+ print(f"URL: {urls_json_last_elem}")++ # Send data to the API+ result = send_agent_history_step(data=model_step_summary)+ print(f"Recording API response: {result}")+++async def run_agent():+ """Run the Browser-Use agent with the recording hook"""+ agent = Agent(+ task="Compare the price of gpt-4o and DeepSeek-V3",+ llm=ChatOpenAI(model="gpt-4o"),+ )++ try:+ print("Starting Browser-Use agent with recording hook")+ await agent.run(+ on_step_start=record_activity,+ max_steps=30+ )+ except Exception as e:+ print(f"Error running agent: {e}")+++if __name__ == "__main__":+ # Check if API is running+ try:+ requests.get("http://127.0.0.1:9000")+ print("Recording API is available")+ except:+ print("Warning: Recording API may not be running. Start api.py first.")++ # Run the agent+ asyncio.run(run_agent())+```++### Working with the Recorded Data++After running the agent, you'll find the recorded data in the `recordings` directory. Here's how you can use this data:++1. **View recorded sessions**: Each JSON file contains a snapshot of agent activity for one step+2. **Extract screenshots**: You can modify the API to save screenshots separately+3. **Analyze agent behavior**: Use the recorded data to study how the agent navigates websites++### Extending the Example++You can extend this recording system in several ways:++1. **Save screenshots separately**: Uncomment the screenshot saving code in the API+2. **Add a web dashboard**: Create a simple web interface to view recorded sessions+3. **Add session IDs**: Modify the API to group steps by agent session+4. **Add filtering**: Implement filters to record only specific types of actions++## Data Available in Hooks++When working with agent hooks, you have access to the entire agent instance. Here are some useful data points you can access:++- `agent.state.history.model_thoughts()`: Reasoning from Browser Use's model.+- `agent.state.history.model_outputs()`: Raw outputs from the Browsre Use's model.+- `agent.state.history.model_actions()`: Actions taken by the agent+- `agent.state.history.extracted_content()`: Content extracted from web pages+- `agent.state.history.urls()`: URLs visited by the agent+- `agent.browser_context.get_page_html()`: Current page HTML+- `agent.browser_context.take_screenshot()`: Screenshot of the current page++## Tips for Using Hooks++- **Avoid blocking operations**: Since hooks run in the same execution thread as the agent, try to keep them efficient or use asynchronous patterns.+- **Handle exceptions**: Make sure your hook functions handle exceptions gracefully to prevent interrupting the agent's main flow.+- **Consider storage needs**: When capturing full HTML and screenshots, be mindful of storage requirements.++Contribution by Carlos A. Planchón.diff --git a/examples/browser/stealth.py b/examples/browser/stealth.pynew file mode 100644index 000000000..b69601636--- /dev/null+++ b/examples/browser/stealth.py@@ -0,0 +1,58 @@+import asyncio+import os+import sys++from langchain_openai import ChatOpenAI++sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from browser_use import Agent, Browser, BrowserConfig, BrowserContextConfig++llm = ChatOpenAI(model='gpt-4o')+browser = Browser(+ config=BrowserConfig(+ headless=False,+ disable_security=False,+ keep_alive=True,+ new_context_config=BrowserContextConfig(+ keep_alive=True,+ disable_security=False,+ ),+ )+)+++async def main():+ agent = Agent(+ task="""+ Go to https://www.webflow.com/ and verify that the page is not blocked by a bot check.+ """,+ llm=llm,+ browser=browser,+ )+ await agent.run()+ input('Press Enter to continue to the next test...')++ agent = Agent(+ task="""+ Go to https://www.okta.com/ and verify that the page is not blocked by a bot check.+ """,+ llm=llm,+ browser=browser,+ )+ await agent.run()++ agent = Agent(+ task="""+ Go to https://nowsecure.nl/ check the "I'm not a robot" checkbox.+ """,+ llm=llm,+ browser=browser,+ )+ await agent.run()++ input('Press Enter to close the browser...')+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/examples/custom-functions/action_filters.py b/examples/custom-functions/action_filters.pynew file mode 100644index 000000000..7976ab9d3--- /dev/null+++ b/examples/custom-functions/action_filters.py@@ -0,0 +1,86 @@+"""+Action filters (domains and page_filter) let you limit actions available to the Agent on a step-by-step/page-by-page basis.+[email protected](..., domains=['*'], page_filter=lambda page: return True)+async def some_action(browser: BrowserContext):+ ...++This helps prevent the LLM from deciding to use an action that is not compatible with the current page.+It helps limit decision fatique by scoping actions only to pages where they make sense.+It also helps prevent mis-triggering stateful actions or actions that could break other programs or leak secrets.++For example:+ - only run on certain domains @registry.action(..., domains=['example.com', '*.example.com', 'example.co.*']) (supports globs, but no regex)+ - only fill in a password on a specific login page url+ - only run if this action has not run before on this page (e.g. by looking up the url in a file on disk)++During each step, the agent recalculates the actions available specifically for that page, and informs the LLM.+"""++import asyncio++from langchain_openai import ChatOpenAI+from playwright.async_api import Page++from browser_use.agent.service import Agent, Browser, BrowserContext, Controller++# Initialize controller and registry+controller = Controller()+registry = controller.registry+++# Action will only be available to Agent on Google domains because of the domain filter[email protected](description='Trigger disco mode', domains=['google.com', '*.google.com'])+async def disco_mode(browser: BrowserContext):+ page = await browser.get_current_page()+ await page.evaluate("""() => {+ // define the wiggle animation+ document.styleSheets[0].insertRule('@keyframes wiggle { 0% { transform: rotate(0deg); } 50% { transform: rotate(10deg); } 100% { transform: rotate(0deg); } }');++ document.querySelectorAll("*").forEach(element => {+ element.style.animation = "wiggle 0.5s infinite";+ });+ }""")+++# you can create a custom page filter function that determines if the action should be available for a given page+def is_login_page(page: Page) -> bool:+ return 'login' in page.url.lower() or 'signin' in page.url.lower()+++# then use it in the action decorator to limit the action to only be available on pages where the filter returns True[email protected](description='Use the force, luke', page_filter=is_login_page)+async def use_the_force(browser: BrowserContext):+ # this will only ever run on pages that matched the filter+ page = await browser.get_current_page()+ assert is_login_page(page)++ await page.evaluate("""() => { document.querySelector('body').innerHTML = 'These are not the droids you are looking for';}""")+++async def main():+ """Main function to run the example"""+ browser = Browser()+ llm = ChatOpenAI(model_name='gpt-4o')++ # Create the agent+ agent = Agent( # disco mode will not be triggered on apple.com because the LLM wont be able to see that action available, it should work on Google.com though.+ task="""+ Go to apple.com and trigger disco mode (if dont know how to do that, then just move on).+ Then go to google.com and trigger disco mode.+ After that, go to the Google login page and Use the force, luke.+ """,+ llm=llm,+ browser=browser,+ controller=controller,+ )++ # Run the agent+ await agent.run(max_steps=10)++ # Cleanup+ await browser.close()+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/examples/custom-functions/custom_hooks_before_after_step.py b/examples/custom-functions/custom_hooks_before_after_step.pynew file mode 100644index 000000000..8c2e6f5a4--- /dev/null+++ b/examples/custom-functions/custom_hooks_before_after_step.py@@ -0,0 +1,251 @@+#!/usr/bin/env python3++"""+Description: These Python modules are designed to capture detailed+browser usage datafor analysis, with both server and client+components working together to record and store the information.++Author: Carlos A. Planchón+https://github.com/carlosplanchon/++Adapt this code to your needs.++Feedback is appreciated!+"""++#####################+# #+# --- UTILS --- #+# #+#####################++import base64+++def b64_to_png(b64_string: str, output_file):+ """+ Convert a Base64-encoded string to a PNG file.++ :param b64_string: A string containing Base64-encoded data+ :param output_file: The path to the output PNG file+ """+ with open(output_file, "wb") as f:+ f.write(base64.b64decode(b64_string))+++###################################################################+# #+# --- FASTAPI API TO RECORD AND SAVE Browser-Use ACTIVITY --- #+# #+###################################################################++# Save to api.py and run with `python api.py`++# ! pip install uvicorn+# ! pip install fastapi+# ! pip install prettyprinter++import json+from pathlib import Path++import prettyprinter+from fastapi import FastAPI, Request++prettyprinter.install_extras()++app = FastAPI()++[email protected]("/post_agent_history_step")+async def post_agent_history_step(request: Request):+ data = await request.json()+ prettyprinter.cpprint(data)++ # Ensure the "recordings" folder exists using pathlib+ recordings_folder = Path("recordings")+ recordings_folder.mkdir(exist_ok=True)++ # Determine the next file number by examining existing .json files+ existing_numbers = []+ for item in recordings_folder.iterdir():+ if item.is_file() and item.suffix == ".json":+ try:+ file_num = int(item.stem)+ existing_numbers.append(file_num)+ except ValueError:+ # In case the file name isn't just a number+ ...++ if existing_numbers:+ next_number = max(existing_numbers) + 1+ else:+ next_number = 1++ # Construct the file path+ file_path = recordings_folder / f"{next_number}.json"++ # Save the JSON data to the file+ with file_path.open("w") as f:+ json.dump(data, f, indent=2)++ return {"status": "ok", "message": f"Saved to {file_path}"}+++if __name__ == "__main__":+ import uvicorn+ uvicorn.run(app, host="0.0.0.0", port=9000)+++##############################################################+# #+# --- CLIENT TO RECORD AND SAVE Browser-Use ACTIVITY --- #+# #+##############################################################++"""+pyobjtojson:++A Python library to safely and recursively serialize any Python object+(including Pydantic models and dataclasses) into JSON-ready structures,+gracefully handling circular references.+"""++# ! pip install -U pyobjtojson+# ! pip install -U prettyprinter++import asyncio++import requests+from dotenv import load_dotenv+from langchain_openai import ChatOpenAI+from pyobjtojson import obj_to_json++from browser_use import Agent++# import prettyprinter++# prettyprinter.install_extras()++load_dotenv()+++def send_agent_history_step(data):+ url = "http://127.0.0.1:9000/post_agent_history_step"+ response = requests.post(url, json=data)+ return response.json()+++async def record_activity(agent_obj):+ website_html = None+ website_screenshot = None+ urls_json_last_elem = None+ model_thoughts_last_elem = None+ model_outputs_json_last_elem = None+ model_actions_json_last_elem = None+ extracted_content_json_last_elem = None++ print('--- 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()++ print("--> History:")+ if hasattr(agent_obj, "state"):+ history = agent_obj.state.history+ else:+ history = None++ model_thoughts = obj_to_json(+ obj=history.model_thoughts(),+ check_circular=False+ )++ # print("--- MODEL THOUGHTS ---")+ if len(model_thoughts) > 0:+ model_thoughts_last_elem = model_thoughts[-1]+ # prettyprinter.cpprint(model_thoughts_last_elem)++ # print("--- MODEL OUTPUT ACTION ---")+ model_outputs = agent_obj.state.history.model_outputs()+ model_outputs_json = obj_to_json(+ obj=model_outputs,+ check_circular=False+ )++ if len(model_outputs_json) > 0:+ model_outputs_json_last_elem = model_outputs_json[-1]+ # prettyprinter.cpprint(model_outputs_json_last_elem)++ # print("--- MODEL INTERACTED ELEM ---")+ model_actions = agent_obj.state.history.model_actions()+ model_actions_json = obj_to_json(+ obj=model_actions,+ check_circular=False+ )++ if len(model_actions_json) > 0:+ model_actions_json_last_elem = model_actions_json[-1]+ # prettyprinter.cpprint(model_actions_json_last_elem)++ # print("--- EXTRACTED CONTENT ---")+ extracted_content = agent_obj.state.history.extracted_content()+ extracted_content_json = obj_to_json(+ obj=extracted_content,+ check_circular=False+ )+ if len(extracted_content_json) > 0:+ extracted_content_json_last_elem = extracted_content_json[-1]+ # prettyprinter.cpprint(extracted_content_json_last_elem)++ # print("--- URLS ---")+ urls = agent_obj.state.history.urls()+ # prettyprinter.cpprint(urls)+ urls_json = obj_to_json(+ obj=urls,+ check_circular=False+ )++ if len(urls_json) > 0:+ urls_json_last_elem = urls_json[-1]+ # prettyprinter.cpprint(urls_json_last_elem)++ model_step_summary = {+ "website_html": website_html,+ "website_screenshot": website_screenshot,+ "url": urls_json_last_elem,+ "model_thoughts": model_thoughts_last_elem,+ "model_outputs": model_outputs_json_last_elem,+ "model_actions": model_actions_json_last_elem,+ "extracted_content": extracted_content_json_last_elem+ }++ print("--- MODEL STEP SUMMARY ---")+ # prettyprinter.cpprint(model_step_summary)++ send_agent_history_step(data=model_step_summary)++ # response = send_agent_history_step(data=history)+ # print(response)++ # print("--> Website HTML:")+ # print(website_html[:200])+ # print("--> Website Screenshot:")+ # print(website_screenshot[:200])+++agent = Agent(+ task="Compare the price of gpt-4o and DeepSeek-V3",+ llm=ChatOpenAI(model="gpt-4o"),+)+++async def run_agent():+ try:+ await agent.run(+ on_step_start=record_activity,+ max_steps=30+ )+ except Exception as e:+ print(e)+++asyncio.run(run_agent())diff --git a/tests/test_action_filters.py b/tests/test_action_filters.pynew file mode 100644index 000000000..4b8d12a90--- /dev/null+++ b/tests/test_action_filters.py@@ -0,0 +1,305 @@+from unittest.mock import MagicMock++import pytest+from playwright.async_api import Page+from pydantic import BaseModel++from browser_use.controller.registry.service import Registry+from browser_use.controller.registry.views import ActionRegistry, RegisteredAction+++class EmptyParamModel(BaseModel):+ pass+++class TestActionFilters:+ def test_get_prompt_description_no_filters(self):+ """Test that system prompt only includes actions with no filters"""+ registry = ActionRegistry()++ # Add actions with and without filters+ no_filter_action = RegisteredAction(+ name='no_filter_action',+ description='Action with no filters',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=None,+ page_filter=None,+ )++ page_filter_action = RegisteredAction(+ name='page_filter_action',+ description='Action with page filter',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=None,+ page_filter=lambda page: True,+ )++ domain_filter_action = RegisteredAction(+ name='domain_filter_action',+ description='Action with domain filter',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=['example.com'],+ page_filter=None,+ )++ registry.actions = {+ 'no_filter_action': no_filter_action,+ 'page_filter_action': page_filter_action,+ 'domain_filter_action': domain_filter_action,+ }++ # System prompt (no page) should only include actions with no filters+ system_description = registry.get_prompt_description()+ assert 'no_filter_action' in system_description+ assert 'page_filter_action' not in system_description+ assert 'domain_filter_action' not in system_description++ def test_page_filter_matching(self):+ """Test that page filters work correctly"""+ registry = ActionRegistry()++ # Create a mock page+ mock_page = MagicMock(spec=Page)+ mock_page.url = 'https://example.com/page'++ # Create actions with different page filters+ matching_action = RegisteredAction(+ name='matching_action',+ description='Action with matching page filter',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=None,+ page_filter=lambda page: 'example.com' in page.url,+ )++ non_matching_action = RegisteredAction(+ name='non_matching_action',+ description='Action with non-matching page filter',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=None,+ page_filter=lambda page: 'other.com' in page.url,+ )++ registry.actions = {'matching_action': matching_action, 'non_matching_action': non_matching_action}++ # Page-specific description should only include matching actions+ page_description = registry.get_prompt_description(mock_page)+ assert 'matching_action' in page_description+ assert 'non_matching_action' not in page_description++ def test_domain_filter_matching(self):+ """Test that domain filters work correctly with glob patterns"""+ registry = ActionRegistry()++ # Create actions with different domain patterns+ actions = {+ 'exact_match': RegisteredAction(+ name='exact_match',+ description='Exact domain match',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=['example.com'],+ page_filter=None,+ ),+ 'subdomain_match': RegisteredAction(+ name='subdomain_match',+ description='Subdomain wildcard match',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=['*.example.com'],+ page_filter=None,+ ),+ 'prefix_match': RegisteredAction(+ name='prefix_match',+ description='Prefix wildcard match',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=['example*'],+ page_filter=None,+ ),+ 'non_matching': RegisteredAction(+ name='non_matching',+ description='Non-matching domain',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=['other.com'],+ page_filter=None,+ ),+ }++ registry.actions = actions++ # Test exact domain match+ mock_page = MagicMock(spec=Page)+ mock_page.url = 'https://example.com/page'++ exact_match_description = registry.get_prompt_description(mock_page)+ assert 'exact_match' in exact_match_description+ assert 'non_matching' not in exact_match_description++ # Test subdomain match+ mock_page.url = 'https://sub.example.com/page'+ subdomain_match_description = registry.get_prompt_description(mock_page)+ assert 'subdomain_match' in subdomain_match_description+ assert 'exact_match' not in subdomain_match_description++ # Test prefix match+ mock_page.url = 'https://example123.org/page'+ prefix_match_description = registry.get_prompt_description(mock_page)+ assert 'prefix_match' in prefix_match_description++ def test_domain_and_page_filter_together(self):+ """Test that actions can be filtered by both domain and page filter"""+ registry = ActionRegistry()++ # Create a mock page+ mock_page = MagicMock(spec=Page)+ mock_page.url = 'https://example.com/admin'++ # Actions with different combinations of filters+ actions = {+ 'domain_only': RegisteredAction(+ name='domain_only',+ description='Domain filter only',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=['example.com'],+ page_filter=None,+ ),+ 'page_only': RegisteredAction(+ name='page_only',+ description='Page filter only',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=None,+ page_filter=lambda page: 'admin' in page.url,+ ),+ 'both_matching': RegisteredAction(+ name='both_matching',+ description='Both filters matching',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=['example.com'],+ page_filter=lambda page: 'admin' in page.url,+ ),+ 'both_one_fail': RegisteredAction(+ name='both_one_fail',+ description='One filter fails',+ function=lambda: None,+ param_model=EmptyParamModel,+ domains=['other.com'],+ page_filter=lambda page: 'admin' in page.url,+ ),+ }++ registry.actions = actions++ # Check that only actions with matching filters are included+ description = registry.get_prompt_description(mock_page)+ assert 'domain_only' in description # Domain matches+ assert 'page_only' in description # Page filter matches+ assert 'both_matching' in description # Both filters match+ assert 'both_one_fail' not in description # Domain filter fails++ # Test with different URL where page filter fails+ mock_page.url = 'https://example.com/dashboard'+ description = registry.get_prompt_description(mock_page)+ assert 'domain_only' in description # Domain matches+ assert 'page_only' not in description # Page filter fails+ assert 'both_matching' not in description # Page filter fails+ assert 'both_one_fail' not in description # Domain filter fails++ @pytest.mark.asyncio+ async def test_registry_action_decorator(self):+ """Test the action decorator with filters"""+ registry = Registry()++ # Define actions with different filters+ @registry.action(+ description='No filter action',+ )+ def no_filter_action():+ pass++ @registry.action(description='Domain filter action', domains=['example.com'])+ def domain_filter_action():+ pass++ @registry.action(description='Page filter action', page_filter=lambda page: 'admin' in page.url)+ def page_filter_action():+ pass++ # Check that system prompt only includes the no_filter_action+ system_description = registry.get_prompt_description()+ assert 'No filter action' in system_description+ assert 'Domain filter action' not in system_description+ assert 'Page filter action' not in system_description++ # Check that page-specific prompt includes the right actions+ mock_page = MagicMock(spec=Page)+ mock_page.url = 'https://example.com/admin'++ page_description = registry.get_prompt_description(mock_page)+ assert 'Domain filter action' in page_description+ assert 'Page filter action' in page_description++ @pytest.mark.asyncio+ async def test_action_model_creation(self):+ """Test that action models are created correctly with filters"""+ registry = Registry()++ # Define actions with different filters+ @registry.action(+ description='No filter action',+ )+ def no_filter_action():+ pass++ @registry.action(description='Domain filter action', domains=['example.com'])+ def domain_filter_action():+ pass++ @registry.action(description='Page filter action', page_filter=lambda page: 'admin' in page.url)+ def page_filter_action():+ pass++ @registry.action(description='Both filters action', domains=['example.com'], page_filter=lambda page: 'admin' in page.url)+ def both_filters_action():+ pass++ # Initial action model should only include no_filter_action+ initial_model = registry.create_action_model()+ assert 'no_filter_action' in initial_model.model_fields+ assert 'domain_filter_action' not in initial_model.model_fields+ assert 'page_filter_action' not in initial_model.model_fields+ assert 'both_filters_action' not in initial_model.model_fields++ # Action model with matching page should include all matching actions+ mock_page = MagicMock(spec=Page)+ mock_page.url = 'https://example.com/admin'++ page_model = registry.create_action_model(page=mock_page)+ assert 'no_filter_action' in page_model.model_fields+ assert 'domain_filter_action' in page_model.model_fields+ assert 'page_filter_action' in page_model.model_fields+ assert 'both_filters_action' in page_model.model_fields++ # Action model with non-matching domain should exclude domain-filtered actions+ mock_page.url = 'https://other.com/admin'+ non_matching_domain_model = registry.create_action_model(page=mock_page)+ assert 'no_filter_action' in non_matching_domain_model.model_fields+ assert 'domain_filter_action' not in non_matching_domain_model.model_fields+ assert 'page_filter_action' in non_matching_domain_model.model_fields+ assert 'both_filters_action' not in non_matching_domain_model.model_fields++ # Action model with non-matching page filter should exclude page-filtered actions+ mock_page.url = 'https://example.com/dashboard'+ non_matching_page_model = registry.create_action_model(page=mock_page)+ assert 'no_filter_action' in non_matching_page_model.model_fields+ assert 'domain_filter_action' in non_matching_page_model.model_fields+ assert 'page_filter_action' not in non_matching_page_model.model_fields+ assert 'both_filters_action' not in non_matching_page_model.model_fieldsdiff --git a/tests/test_wait_for_element.py b/tests/test_wait_for_element.pynew file mode 100644index 000000000..a716e05b0--- /dev/null+++ b/tests/test_wait_for_element.py@@ -0,0 +1,66 @@+import asyncio+import os+import sys++project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))+if project_root not in sys.path:+ sys.path.insert(0, project_root)++import pytest+from dotenv import load_dotenv+from langchain_openai import ChatOpenAI++# Third-party imports+from browser_use import Agent, Controller++# Local imports+from browser_use.browser.browser import Browser, BrowserConfig+from browser_use.browser.context import BrowserContext++# Load environment variables.+load_dotenv()++# Initialize language model and controller.+llm = ChatOpenAI(model='gpt-4o')+controller = Controller()+[email protected](reason='this is for local testing only')+async def test_wait_for_element():+ """Test 'Wait for element' action."""++ initial_actions = [+ {'open_tab': {'url': 'https://pypi.org/'}},+ # Uncomment the line below to include the wait action in initial actions.+ # {'wait_for_element': {'selector': '#search', 'timeout': 30}},+ ]++ # Set up the browser context.+ context = BrowserContext(+ browser=Browser(config=BrowserConfig(headless=False, disable_security=True)),+ )++ # Create the agent with the task.+ agent = Agent(+ task="Wait for element '#search' to be visible with a timeout of 30 seconds.",+ llm=llm,+ browser_context=context,+ initial_actions=initial_actions,+ controller=controller+ )++ # Run the agent for a few steps to trigger navigation and then the wait action.+ history = await agent.run(max_steps=3)+ action_names = history.action_names()++ # Ensure that the wait_for_element action was executed.+ assert 'wait_for_element' in action_names, "Expected wait_for_element action to be executed."++ # Verify that the #search element is visible by querying the page.+ page = await context.get_current_page()+ header_handle = await page.query_selector("#search")+ assert header_handle is not None, "Expected to find a #search element on the page."+ is_visible = await header_handle.is_visible()+ assert is_visible, "Expected the #search element to be visible."++if __name__ == '__main__':+ asyncio.run(test_wait_for_element())