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
update tests to use new BrowserProfile and BrowserSession
Nick Sweeting84e2cc653f27
diff --git a/tests/test_agent_actions.py b/tests/test_agent_actions.pyindex 6a2c049d6..b7654ee50 100644--- a/tests/test_agent_actions.py+++ b/tests/test_agent_actions.py@@ -8,7 +8,6 @@ from pydantic import BaseModel, SecretStrfrom browser_use.agent.service import Agentfrom browser_use.agent.views import AgentHistoryListfrom browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.views import BrowserState@pytest.fixture@@ -202,7 +201,7 @@ async def test_captcha_solver(llm, context, captcha: CaptchaTest):history: AgentHistoryList = await agent.run(max_steps=7)- state: BrowserState = await context.get_state()+ state = await context.get_state_summary()all_text = state.element_tree.get_all_text_till_next_clickable_element()diff --git a/tests/test_browser_config_models.py b/tests/test_browser_config_models.pyindex d62b23789..4828d70c6 100644--- a/tests/test_browser_config_models.py+++ b/tests/test_browser_config_models.py@@ -2,8 +2,8 @@ import osimport pytest-from browser_use.browser.browser import Browser, BrowserConfig, ProxySettings-from browser_use.browser.context import BrowserContext, BrowserContextConfig+from browser_use.browser.session import BrowserSession+from browser_use.browser.types import BrowserProfile, ProxySettings@pytest.mark.asyncio@@ -35,25 +35,25 @@ async def test_proxy_settings_pydantic_model():@pytest.mark.asyncioasync def test_window_size_config():"""- Test that BrowserContextConfig correctly handles window_width and window_height properties.+ Test that BrowserProfile correctly handles window_size property."""- # Create config with specific window dimensions- config = BrowserContextConfig(window_width=1280, window_height=1100)+ # Create profile with specific window dimensions+ profile = BrowserProfile(window_size={'width': 1280, 'height': 1100})# Verify the properties are set correctly- assert config.window_width == 1280- assert config.window_height == 1100+ assert profile.window_size['width'] == 1280+ assert profile.window_size['height'] == 1100# Verify model_dump works correctly- config_dict = config.model_dump()- assert isinstance(config_dict, dict)- assert config_dict['window_width'] == 1280- assert config_dict['window_height'] == 1100+ profile_dict = profile.model_dump()+ assert isinstance(profile_dict, dict)+ assert profile_dict['window_size']['width'] == 1280+ assert profile_dict['window_size']['height'] == 1100# Create with different values- config2 = BrowserContextConfig(window_width=1920, window_height=1080)- assert config2.window_width == 1920- assert config2.window_height == 1080+ profile2 = BrowserProfile(window_size={'width': 1920, 'height': 1080})+ assert profile2.window_size['width'] == 1920+ assert profile2.window_size['height'] == 1080@pytest.mark.asyncio@@ -64,39 +64,25 @@ async def test_window_size_with_real_browser():passed to Playwright and the actual browser window is configured with these settings.This test is skipped in CI environments."""- # Create browser config with headless mode- browser_config = BrowserConfig(+ # Create browser profile with headless mode and specific dimensions+ browser_profile = BrowserProfile(headless=True, # Use headless for faster test- )-- # Create context config with specific dimensions we can check- context_config = BrowserContextConfig(- window_width=1024,- window_height=768,+ window_size={'width': 1024, 'height': 768},maximum_wait_page_load_time=2.0, # Faster timeouts for testminimum_wait_page_load_time=0.2,no_viewport=True, # Use actual window size instead of viewport)- # Create browser and context- browser = Browser(config=browser_config)+ # Create browser session+ browser_session = BrowserSession(browser_profile=browser_profile)try:- # Initialize browser- playwright_browser = await browser.get_playwright_browser()- assert playwright_browser is not None, 'Browser initialization failed'-- # Create context- browser_context = BrowserContext(browser=browser, config=context_config)- try:- # Initialize session- await browser_context._initialize_session()-- # Get the current page- page = await browser_context.get_current_page()- assert page is not None, 'Failed to get current page'-- # Get the context configuration used for browser window size- video_size = await page.evaluate("""+ await browser_session.start()+ # Get the current page+ page = await browser_session.get_current_page()+ assert page is not None, 'Failed to get current page'++ # Get the context configuration used for browser window size+ video_size = await page.evaluate("""() => {// This returns information about the context recording settings// which should match our configured video size (browser_window_size)@@ -116,8 +102,8 @@ async def test_window_size_with_real_browser():}""")- # Let's also check the viewport size- viewport_size = await page.evaluate("""+ # Let's also check the viewport size+ viewport_size = await page.evaluate("""() => {return {width: window.innerWidth,@@ -126,23 +112,19 @@ async def test_window_size_with_real_browser():}""")- print(f'Window size config: width={context_config.window_width}, height={context_config.window_height}')- print(f'Browser viewport size: {viewport_size}')+ print(f'Window size config: width={browser_profile.window_size["width"]}, height={browser_profile.window_size["height"]}')+ print(f'Browser viewport size: {viewport_size}')- # This is a lightweight test to verify that the page has a size (details may vary by browser)- assert viewport_size['width'] > 0, 'Expected viewport width to be positive'- assert viewport_size['height'] > 0, 'Expected viewport height to be positive'+ # This is a lightweight test to verify that the page has a size (details may vary by browser)+ assert viewport_size['width'] > 0, 'Expected viewport width to be positive'+ assert viewport_size['height'] > 0, 'Expected viewport height to be positive'- # For browser context creation in record_video_size, this is what truly matters- # Verify that our window size was properly serialized to a dictionary- print(f'Content of context session: {browser_context.session.context}')- print('✅ Browser window size used in the test')- finally:- # Clean up context- await browser_context.close()+ # For browser context creation in record_video_size, this is what truly matters+ # Verify that our window size was properly serialized to a dictionary+ print(f'Content of context session: {browser_session.browser_context}')+ print('✅ Browser window size used in the test')finally:- # Clean up browser- await browser.close()+ await browser_session.stop()@pytest.mark.asyncio@@ -153,7 +135,7 @@ async def test_proxy_with_real_browser():This test:1. Creates a ProxySettings Pydantic model- 2. Passes it to BrowserConfig+ 2. Passes it to BrowserProfile3. Verifies browser initialization works (proving the model was correctly serialized)4. We don't actually verify proxy functionality (would require a working proxy)"""@@ -167,35 +149,18 @@ async def test_proxy_with_real_browser():assert isinstance(proxy_dict, dict)assert proxy_dict['server'] == 'http://non.existent.proxy:9999'- # Create browser config with proxy- browser_config = BrowserConfig(+ # Create browser profile with proxy+ browser_profile = BrowserProfile(headless=True,proxy=proxy_settings,)- # Create browser- browser = Browser(config=browser_config)+ # Create browser session+ browser_session = BrowserSession(browser_profile=browser_profile)try:- # Initialize browser - this should succeed even with invalid proxy- # because we're just checking configuration, not actual proxy functionality- try:- playwright_browser = await browser.get_playwright_browser()- assert playwright_browser is not None, 'Browser initialization failed'-- # Success - the browser was initialized with our proxy settings- # We won't try to make requests (which would fail with non-existent proxy)- print('✅ Browser initialized with proxy settings successfully')-- # We can inspect browser settings here to verify proxy was passed- # but the specific API to access these settings depends on the browser-- except Exception as e:- # Make sure any exception isn't related to the proxy configuration format- # (Network errors due to non-existent proxy are acceptable, invalid type conversion isn't)- error_text = str(e).lower()- assert 'proxy' not in error_text or any(- term in error_text for term in ['connect', 'connection', 'network', 'timeout', 'unreachable']- ), f'Proxy configuration error (not network error): {e}'+ await browser_session.start()+ # Success - the browser was initialized with our proxy settings+ # We won't try to make requests (which would fail with non-existent proxy)+ print('✅ Browser initialized with proxy settings successfully')finally:- # Clean up browser- await browser.close()+ await browser_session.stop()diff --git a/tests/test_browser_session.py b/tests/test_browser_session.pynew file mode 100644index 000000000..b292ed4f5--- /dev/null+++ b/tests/test_browser_session.py@@ -0,0 +1,333 @@+import asyncio+import base64++import pytest+from pytest_httpserver import HTTPServer++from browser_use.browser import BrowserProfile, BrowserSession+from browser_use.dom.views import DOMElementNode+++class TestBrowserContext:+ """Tests for browser context functionality using real browser instances."""++ @pytest.fixture(scope='module')+ def event_loop(self):+ """Create and provide an event loop for async tests."""+ loop = asyncio.get_event_loop_policy().new_event_loop()+ yield loop+ loop.close()++ @pytest.fixture(scope='module')+ def http_server(self):+ """Create and provide a test HTTP server that serves static content."""+ server = HTTPServer()+ server.start()++ # Add routes for test pages+ server.expect_request('/').respond_with_data(+ '<html><head><title>Test Home Page</title></head><body><h1>Test Home Page</h1><p>Welcome to the test site</p></body></html>',+ content_type='text/html',+ )++ server.expect_request('/scroll_test').respond_with_data(+ """+ <html>+ <head>+ <title>Scroll Test</title>+ <style>+ body { height: 3000px; }+ .marker { position: absolute; }+ #top { top: 0; }+ #middle { top: 1000px; }+ #bottom { top: 2000px; }+ </style>+ </head>+ <body>+ <div id="top" class="marker">Top of the page</div>+ <div id="middle" class="marker">Middle of the page</div>+ <div id="bottom" class="marker">Bottom of the page</div>+ </body>+ </html>+ """,+ content_type='text/html',+ )++ yield server+ server.stop()++ @pytest.fixture+ def base_url(self, http_server):+ """Return the base URL for the test HTTP server."""+ return f'http://{http_server.host}:{http_server.port}'++ @pytest.fixture(scope='module')+ async def browser_session(self, event_loop):+ """Create and provide a BrowserSession instance with security disabled."""+ browser_session = BrowserSession(+ # browser_profile=BrowserProfile(...),+ headless=True,+ user_data_dir=None,+ disable_security=False,+ )+ await browser_session.start()+ yield browser_session+ await browser_session.stop()++ def test_is_url_allowed(self):+ """+ Test the _is_url_allowed method to verify that it correctly checks URLs against+ the allowed domains configuration.+ """+ # Scenario 1: allowed_domains is None, any URL should be allowed.+ config1 = BrowserProfile(allowed_domains=None)+ context1 = BrowserSession(browser_profile=config1)+ assert context1._is_url_allowed('http://anydomain.com') is True+ assert context1._is_url_allowed('https://anotherdomain.org/path') is True++ # Scenario 2: allowed_domains is provided.+ allowed = ['example.com', '*.mysite.org']+ config2 = BrowserProfile(allowed_domains=allowed)+ context2 = BrowserSession(browser_profile=config2)++ # URL exactly matching+ assert context2._is_url_allowed('http://example.com') is True+ # URL with subdomain (should not be allowed)+ assert context2._is_url_allowed('http://sub.example.com/path') is False+ # URL with different domain (should not be allowed)+ assert context2._is_url_allowed('http://sub.mysite.org') is True+ # URL that matches second allowed domain+ assert context2._is_url_allowed('https://mysite.org/page') is True+ # URL with port number, still allowed (port is stripped)+ assert context2._is_url_allowed('http://example.com:8080') is True+ assert context2._is_url_allowed('https://example.com:443') is True++ # Scenario 3: Malformed URL or empty domain+ # urlparse will return an empty netloc for some malformed URLs.+ assert context2._is_url_allowed('notaurl') is False++ def test_convert_simple_xpath_to_css_selector(self):+ """+ Test the _convert_simple_xpath_to_css_selector method of BrowserSession.+ This verifies that simple XPath expressions are correctly converted to CSS selectors.+ """+ # Test empty xpath returns empty string+ assert BrowserSession._convert_simple_xpath_to_css_selector('') == ''++ # Test a simple xpath without indices+ xpath = '/html/body/div/span'+ expected = 'html > body > div > span'+ result = BrowserSession._convert_simple_xpath_to_css_selector(xpath)+ assert result == expected++ # Test xpath with an index on one element: [2] should translate to :nth-of-type(2)+ xpath = '/html/body/div[2]/span'+ expected = 'html > body > div:nth-of-type(2) > span'+ result = BrowserSession._convert_simple_xpath_to_css_selector(xpath)+ assert result == expected++ # Test xpath with indices on multiple elements+ xpath = '/ul/li[3]/a[1]'+ expected = 'ul > li:nth-of-type(3) > a:nth-of-type(1)'+ result = BrowserSession._convert_simple_xpath_to_css_selector(xpath)+ assert result == expected++ def test_enhanced_css_selector_for_element(self):+ """+ Test the _enhanced_css_selector_for_element method to verify that+ it returns the correct CSS selector string for a DOMElementNode.+ """+ # Create a DOMElementNode instance with a complex set of attributes+ dummy_element = DOMElementNode(+ tag_name='div',+ is_visible=True,+ parent=None,+ xpath='/html/body/div[2]',+ attributes={'class': 'foo bar', 'id': 'my-id', 'placeholder': 'some "quoted" text', 'data-testid': '123'},+ children=[],+ )++ # Call the method with include_dynamic_attributes=True+ actual_selector = BrowserSession._enhanced_css_selector_for_element(dummy_element, include_dynamic_attributes=True)++ # Expected conversion includes the xpath conversion, class attributes, and other attributes+ expected_selector = (+ 'html > body > div:nth-of-type(2).foo.bar[id="my-id"][placeholder*="some \\"quoted\\" text"][data-testid="123"]'+ )+ assert actual_selector == expected_selector, f'Expected {expected_selector}, but got {actual_selector}'++ @pytest.mark.asyncio+ async def test_navigate_and_get_current_page(self, browser_session, base_url):+ """Test that navigate method changes the URL and get_current_page returns the proper page."""+ # Navigate to the test page+ await browser_session.navigate(f'{base_url}/')++ # Get the current page+ page = await browser_session.get_current_page()++ # Verify the page URL matches what we navigated to+ assert f'{base_url}/' in page.url++ # Verify the page title+ title = await page.title()+ assert title == 'Test Home Page'++ @pytest.mark.asyncio+ async def test_refresh_page(self, browser_session, base_url):+ """Test that refresh_page correctly reloads the current page."""+ # Navigate to the test page+ await browser_session.navigate(f'{base_url}/')++ # Get the current page before refresh+ page_before = await browser_session.get_current_page()++ # Refresh the page+ await browser_session.refresh()++ # Get the current page after refresh+ page_after = await browser_session.get_current_page()++ # Verify it's still on the same URL+ assert page_after.url == page_before.url++ # Verify the page title is still correct+ title = await page_after.title()+ assert title == 'Test Home Page'++ @pytest.mark.asyncio+ async def test_execute_javascript(self, browser_session, base_url):+ """Test that execute_javascript correctly executes JavaScript in the current page."""+ # Navigate to a test page+ await browser_session.navigate(f'{base_url}/')++ # Execute a simple JavaScript snippet that returns a value+ result = await browser_session.execute_javascript('document.title')++ # Verify the result+ assert result == 'Test Home Page'++ # Execute JavaScript that modifies the page+ await browser_session.execute_javascript("document.body.style.backgroundColor = 'red'")++ # Verify the change by reading back the value+ bg_color = await browser_session.execute_javascript('document.body.style.backgroundColor')+ assert bg_color == 'red'++ @pytest.mark.asyncio+ async def test_get_scroll_info(self, browser_session, base_url):+ """Test that get_scroll_info returns the correct scroll position information."""+ # Navigate to the scroll test page+ await browser_session.navigate(f'{base_url}/scroll_test')+ page = await browser_session.get_current_page()++ # Get initial scroll info+ pixels_above_initial, pixels_below_initial = await browser_session.get_scroll_info(page)++ # Verify initial scroll position+ assert pixels_above_initial == 0, 'Initial scroll position should be at the top'+ assert pixels_below_initial > 0, 'There should be content below the viewport'++ # Scroll down the page+ await browser_session.execute_javascript('window.scrollBy(0, 500)')+ await asyncio.sleep(0.2) # Brief delay for scroll to complete++ # Get new scroll info+ pixels_above_after_scroll, pixels_below_after_scroll = await browser_session.get_scroll_info(page)++ # Verify new scroll position+ assert pixels_above_after_scroll > 0, 'Page should be scrolled down'+ assert pixels_above_after_scroll >= 400, 'Page should be scrolled down at least 400px'+ assert pixels_below_after_scroll < pixels_below_initial, 'Less content should be below viewport after scrolling'++ @pytest.mark.asyncio+ async def test_take_screenshot(self, browser_session, base_url):+ """Test that take_screenshot returns a valid base64 encoded image."""+ # Navigate to the test page+ await browser_session.navigate(f'{base_url}/')++ # Take a screenshot+ screenshot_base64 = await browser_session.take_screenshot()++ # Verify the screenshot is a valid base64 string+ assert isinstance(screenshot_base64, str)+ assert len(screenshot_base64) > 0++ # Verify it can be decoded as base64+ try:+ image_data = base64.b64decode(screenshot_base64)+ # Verify the data starts with a valid image signature (PNG file header)+ assert image_data[:8] == b'\x89PNG\r\n\x1a\n', 'Screenshot is not a valid PNG image'+ except Exception as e:+ pytest.fail(f'Failed to decode screenshot as base64: {e}')++ @pytest.mark.asyncio+ async def test_switch_tab_operations(self, browser_session, base_url):+ """Test tab creation, switching, and closing operations."""+ # Navigate to home page in first tab+ await browser_session.navigate(f'{base_url}/')++ # Create a new tab+ await browser_session.create_new_tab(f'{base_url}/scroll_test')++ # Verify we have two tabs now+ tabs_info = await browser_session.get_tabs_info()+ assert len(tabs_info) == 2, 'Should have two tabs open'++ # Verify current tab is the scroll test page+ current_page = await browser_session.get_current_page()+ assert f'{base_url}/scroll_test' in current_page.url++ # Switch back to the first tab+ await browser_session.switch_to_tab(0)++ # Verify we're back on the home page+ current_page = await browser_session.get_current_page()+ assert f'{base_url}/' in current_page.url++ # Close the second tab+ await browser_session.close_tab(1)++ # Verify we only have one tab left+ tabs_info = await browser_session.get_tabs_info()+ assert len(tabs_info) == 1, 'Should have one tab open after closing the second'++ @pytest.mark.asyncio+ async def test_remove_highlights(self, browser_session, base_url):+ """Test that remove_highlights successfully removes highlight elements."""+ # Navigate to a test page+ await browser_session.navigate(f'{base_url}/')++ # Add a highlight via JavaScript+ await browser_session.execute_javascript("""+ const container = document.createElement('div');+ container.id = 'playwright-highlight-container';+ document.body.appendChild(container);++ const highlight = document.createElement('div');+ highlight.id = 'playwright-highlight-1';+ container.appendChild(highlight);++ const element = document.querySelector('h1');+ element.setAttribute('browser-user-highlight-id', 'playwright-highlight-1');+ """)++ # Verify the highlight container exists+ container_exists = await browser_session.execute_javascript(+ "document.getElementById('playwright-highlight-container') !== null"+ )+ assert container_exists, 'Highlight container should exist before removal'++ # Call remove_highlights+ await browser_session.remove_highlights()++ # Verify the highlight container was removed+ container_exists_after = await browser_session.execute_javascript(+ "document.getElementById('playwright-highlight-container') !== null"+ )+ assert not container_exists_after, 'Highlight container should be removed'++ # Verify the highlight attribute was removed from the element+ attribute_exists = await browser_session.execute_javascript(+ "document.querySelector('h1').hasAttribute('browser-user-highlight-id')"+ )+ assert not attribute_exists, 'browser-user-highlight-id attribute should be removed'diff --git a/tests/test_context.py b/tests/test_context.pydeleted file mode 100644index ac17a57d8..000000000--- a/tests/test_context.py+++ /dev/null@@ -1,363 +0,0 @@-import base64-from unittest.mock import Mock--import pytest--from browser_use.browser import BrowserProfile, BrowserSession-from browser_use.browser.views import BrowserState-from browser_use.dom.views import DOMElementNode---def test_is_url_allowed():- """- Test the _is_url_allowed method to verify that it correctly checks URLs against- the allowed domains configuration.- Scenario 1: When allowed_domains is None, all URLs should be allowed.- Scenario 2: When allowed_domains is a list, only URLs matching the allowed domain(s) are allowed.- Scenario 3: When the URL is malformed, it should return False.- Scenario 4: When allowed_domains contain glob patterns, see: test_url_allowlist_security.py- """- # Create a dummy Browser mock. Only the 'config' attribute is needed for _is_url_allowed.- dummy_browser = Mock()- # Set an empty config for dummy_browser; it won't be used in _is_url_allowed.- dummy_browser.config = Mock()- # Scenario 1: allowed_domains is None, any URL should be allowed.- config1 = BrowserProfile(allowed_domains=None)- context1 = BrowserSession(browser=dummy_browser, browser_profile=config1)- assert context1._is_url_allowed('http://anydomain.com') is True- assert context1._is_url_allowed('https://anotherdomain.org/path') is True- # Scenario 2: allowed_domains is provided.- allowed = ['example.com', 'mysite.org']- config2 = BrowserProfile(allowed_domains=allowed)- context2 = BrowserSession(browser=dummy_browser, browser_profile=config2)- # URL exactly matching- assert context2._is_url_allowed('http://example.com') is True- # URL with subdomain (should be allowed)- assert context2._is_url_allowed('http://sub.example.com/path') is True- # URL with different domain (should not be allowed)- assert context2._is_url_allowed('http://notexample.com') is False- # URL that matches second allowed domain- assert context2._is_url_allowed('https://mysite.org/page') is True- # URL with port number, still allowed (port is stripped)- assert context2._is_url_allowed('http://example.com:8080') is True- # Scenario 3: Malformed URL or empty domain- # urlparse will return an empty netloc for some malformed URLs.- assert context2._is_url_allowed('notaurl') is False---def test_convert_simple_xpath_to_css_selector():- """- Test the _convert_simple_xpath_to_css_selector method of BrowserContext.- This verifies that simple XPath expressions (with and without indices) are correctly converted to CSS selectors.- """- # Test empty xpath returns empty string- assert BrowserContext._convert_simple_xpath_to_css_selector('') == ''- # Test a simple xpath without indices- xpath = '/html/body/div/span'- expected = 'html > body > div > span'- result = BrowserContext._convert_simple_xpath_to_css_selector(xpath)- assert result == expected- # Test xpath with an index on one element: [2] should translate to :nth-of-type(2)- xpath = '/html/body/div[2]/span'- expected = 'html > body > div:nth-of-type(2) > span'- result = BrowserContext._convert_simple_xpath_to_css_selector(xpath)- assert result == expected- # Test xpath with indices on multiple elements:- # For "li[3]" -> li:nth-of-type(3) and for "a[1]" -> a:nth-of-type(1)- xpath = '/ul/li[3]/a[1]'- expected = 'ul > li:nth-of-type(3) > a:nth-of-type(1)'- result = BrowserContext._convert_simple_xpath_to_css_selector(xpath)- assert result == expected---def test_get_initial_state():- """- Test the _get_initial_state method to verify it returns the correct initial BrowserState.- The test checks that when a dummy page with a URL is provided,- the returned state contains that URL and other default values.- """- # Create a dummy browser since only its existence is needed.- dummy_browser = Mock()- dummy_browser.config = Mock()- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())-- # Define a dummy page with a 'url' attribute.- class DummyPage:- url = 'http://dummy.com'-- dummy_page = DummyPage()- # Call _get_initial_state with a page: URL should be set from page.url.- state_with_page = context._get_initial_state(page=dummy_page)- assert state_with_page.url == dummy_page.url- # Verify that the element_tree is initialized with tag 'root'- assert state_with_page.element_tree.tag_name == 'root'- # Call _get_initial_state without a page: URL should be empty.- state_without_page = context._get_initial_state()- assert state_without_page.url == ''---async def test_execute_javascript():- """- Test the execute_javascript method by mocking the current page's evaluate function.- This ensures that when execute_javascript is called, it correctly returns the value- from the page's evaluate method.- """-- # Define a dummy page with an async evaluate method.- class DummyPage:- async def evaluate(self, script):- return 'dummy_result'-- # Create a dummy session object with a dummy current_page.- dummy_session = type('DummySession', (), {})()- dummy_session.current_page = DummyPage()- # Create a dummy browser mock with a minimal config.- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize the BrowserContext with the dummy browser and config.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- # Manually set the session to our dummy session.- context.session = dummy_session- # Call execute_javascript and verify it returns the expected result.- result = await context.execute_javascript('return 1+1')- assert result == 'dummy_result'---async def test_enhanced_css_selector_for_element():- """- Test the _enhanced_css_selector_for_element method to verify that- it returns the correct CSS selector string for a dummy DOMElementNode.- The test checks that:- - The provided xpath is correctly converted (handling indices),- - Class attributes are appended as CSS classes,- - Standard and dynamic attributes (including ones with special characters)- are correctly added to the selector.- """- # Create a dummy DOMElementNode instance with a complex set of attributes.- dummy_element = DOMElementNode(- tag_name='div',- is_visible=True,- parent=None,- xpath='/html/body/div[2]',- attributes={'class': 'foo bar', 'id': 'my-id', 'placeholder': 'some "quoted" text', 'data-testid': '123'},- children=[],- )- # Call the method with include_dynamic_attributes=True.- actual_selector = BrowserContext._enhanced_css_selector_for_element(dummy_element, include_dynamic_attributes=True)- # Expected conversion:- # 1. The xpath "/html/body/div[2]" converts to "html > body > div:nth-of-type(2)".- # 2. The class attribute "foo bar" appends ".foo.bar".- # 3. The "id" attribute is added as [id="my-id"].- # 4. The "placeholder" attribute contains quotes; it is added as- # [placeholder*="some \"quoted\" text"].- # 5. The dynamic attribute "data-testid" is added as [data-testid="123"].- expected_selector = (- 'html > body > div:nth-of-type(2).foo.bar[id="my-id"][placeholder*="some \\"quoted\\" text"][data-testid="123"]'- )- assert actual_selector == expected_selector, f'Expected {expected_selector}, but got {actual_selector}'---async def test_get_scroll_info():- """- Test the get_scroll_info method by mocking the page's evaluate method.- This dummy page returns preset values for window.scrollY, window.innerHeight,- and document.documentElement.scrollHeight. The test then verifies that the- computed scroll information (pixels_above and pixels_below) match the expected values.- """-- # Define a dummy page with an async evaluate method returning preset values.- class DummyPage:- async def evaluate(self, script):- if 'window.scrollY' in script:- return 100 # scrollY- elif 'window.innerHeight' in script:- return 500 # innerHeight- elif 'document.documentElement.scrollHeight' in script:- return 1200 # total scrollable height- return None-- # Create a dummy session with a dummy current_page.- dummy_session = type('DummySession', (), {})()- dummy_session.current_page = DummyPage()- # We also need a dummy context attribute but it won't be used in this test.- dummy_session.context = type('DummyContext', (), {})()- # Create a dummy browser mock.- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize BrowserContext with the dummy browser and config.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- # Manually set the session to our dummy session.- context.session = dummy_session- # Call get_scroll_info on the dummy page.- pixels_above, pixels_below = await context.get_scroll_info(dummy_session.current_page)- # Expected calculations:- # pixels_above = scrollY = 100- # pixels_below = total_height - (scrollY + innerHeight) = 1200 - (100 + 500) = 600- assert pixels_above == 100, f'Expected 100 pixels above, got {pixels_above}'- assert pixels_below == 600, f'Expected 600 pixels below, got {pixels_below}'---async def test_reset_context():- """- Test the reset_context method to ensure it correctly closes all existing tabs,- resets the cached state, and creates a new page.- """-- # Dummy Page with close and wait_for_load_state methods.- class DummyPage:- def __init__(self, url='http://dummy.com'):- self.url = url- self.closed = False-- async def close(self):- self.closed = True-- async def wait_for_load_state(self):- pass-- # Dummy Context that holds pages and can create a new page.- class DummyContext:- def __init__(self):- self.pages = []-- async def new_page(self):- new_page = DummyPage(url='')- self.pages.append(new_page)- return new_page-- # Create a dummy session with a context containing two pages.- dummy_session = type('DummySession', (), {})()- dummy_context = DummyContext()- page1 = DummyPage(url='http://page1.com')- page2 = DummyPage(url='http://page2.com')- dummy_context.pages.extend([page1, page2])- dummy_session.context = dummy_context- dummy_session.current_page = page1- dummy_session.cached_state = None- # Create a dummy browser mock.- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize BrowserContext using our dummy_browser and config,- # and manually set its session to our dummy session.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- context.session = dummy_session- # Confirm session has 2 pages before reset.- assert len(dummy_session.context.pages) == 2- # Call reset_context which should close existing pages,- # reset the cached state, and create a new page as current_page.- await context.reset_context()- # Verify that initial pages were closed.- assert page1.closed is True- assert page2.closed is True- # Check that a new page is created and set as current_page.- assert dummy_session.current_page is not None- new_page = dummy_session.current_page- # New page URL should be empty as per _get_initial_state.- assert new_page.url == ''- # Verify that cached_state is reset to an initial BrowserState.- state = dummy_session.cached_state- assert isinstance(state, BrowserState)- assert state.url == ''- assert state.element_tree.tag_name == 'root'---async def test_take_screenshot():- """- Test the take_screenshot method to verify that it returns a base64 encoded screenshot string.- A dummy page with a mocked screenshot method is used, returning a predefined byte string.- """-- class DummyPage:- async def screenshot(self, full_page, animations):- # Verify that parameters are forwarded correctly.- assert full_page is True, 'full_page parameter was not correctly passed'- assert animations == 'disabled', 'animations parameter was not correctly passed'- # Return a test byte string.- return b'test'-- # Create a dummy session with the DummyPage as the current_page.- dummy_session = type('DummySession', (), {})()- dummy_session.current_page = DummyPage()- dummy_session.context = None # Not used in this test- # Create a dummy browser mock.- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize the BrowserContext with the dummy browser and config.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- # Manually set the session to our dummy session.- context.session = dummy_session- # Call take_screenshot and check that it returns the expected base64 encoded string.- result = await context.take_screenshot(full_page=True)- expected = base64.b64encode(b'test').decode('utf-8')- assert result == expected, f'Expected {expected}, but got {result}'---async def test_refresh_page_behavior():- """- Test the refresh_page method of BrowserContext to verify that it correctly reloads the current page- and waits for the page's load state. This is done by creating a dummy page that flags when its- reload and wait_for_load_state methods are called.- """-- class DummyPage:- def __init__(self):- self.reload_called = False- self.wait_for_load_state_called = False-- async def reload(self):- self.reload_called = True-- async def wait_for_load_state(self):- self.wait_for_load_state_called = True-- # Create a dummy session with the dummy page as the current_page.- dummy_page = DummyPage()- dummy_session = type('DummySession', (), {})()- dummy_session.current_page = dummy_page- dummy_session.context = None # Not required for this test- # Create a dummy browser mock- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize BrowserContext with the dummy browser and config,- # and manually set its session to our dummy session.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- context.session = dummy_session- # Call refresh_page and verify that reload and wait_for_load_state were called.- await context.refresh_page()- assert dummy_page.reload_called is True, 'Expected the page to call reload()'- assert dummy_page.wait_for_load_state_called is True, 'Expected the page to call wait_for_load_state()'---async def test_remove_highlights_failure():- """- Test the remove_highlights method to ensure that if the page.evaluate call fails,- the exception is caught and does not propagate (i.e. the method handles errors gracefully).- """-- # Dummy page that always raises an exception when evaluate is called.- class DummyPage:- async def evaluate(self, script):- raise Exception('dummy error')-- # Create a dummy session with the DummyPage as current_page.- dummy_session = type('DummySession', (), {})()- dummy_session.current_page = DummyPage()- dummy_session.context = None # Not used in this test- # Create a dummy browser mock.- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize BrowserContext with the dummy browser and configuration.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- context.session = dummy_session- # Call remove_highlights and verify that no exception is raised.- try:- await context.remove_highlights()- except Exception as e:- pytest.fail(f'remove_highlights raised an exception: {e}')diff --git a/tests/test_controller.py b/tests/test_controller.pyindex 7316e3924..af8014c45 100644--- a/tests/test_controller.py+++ b/tests/test_controller.py@@ -6,8 +6,7 @@ from pydantic import BaseModelfrom pytest_httpserver import HTTPServerfrom browser_use.agent.views import ActionModel, ActionResult-from browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.context import BrowserContext+from browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.controller.service import Controllerfrom browser_use.controller.views import (ClickElementAction,@@ -83,22 +82,17 @@ class TestControllerIntegration:return f'http://{http_server.host}:{http_server.port}'@pytest.fixture(scope='module')- async def browser(self, event_loop):+ async def browser_session(self, event_loop):"""Create and provide a Browser instance with security disabled."""- browser_instance = Browser(- config=BrowserConfig(+ browser_session = BrowserSession(+ browser_profile=BrowserProfile(headless=True,- )+ ),+ user_data_dir=None,)- yield browser_instance- await browser_instance.close()-- @pytest.fixture- async def browser_context(self, browser):- """Create and provide a BrowserContext instance."""- context = BrowserContext(browser=browser)- yield context- await context.close()+ await browser_session.start()+ yield browser_session+ await browser_session.stop()@pytest.fixturedef controller(self):@@ -106,7 +100,7 @@ class TestControllerIntegration:return Controller()@pytest.mark.asyncio- async def test_go_to_url_action(self, controller, browser_context, base_url):+ async def test_go_to_url_action(self, controller, browser_session, base_url):"""Test that GoToUrlAction navigates to the specified URL."""# Create action model for go_to_urlaction_data = {'go_to_url': GoToUrlAction(url=f'{base_url}/page1')}@@ -118,18 +112,18 @@ class TestControllerIntegration:action_model = GoToUrlActionModel(**action_data)# Execute the action- result = await controller.act(action_model, browser_context)+ result = await controller.act(action_model, browser_session)# Verify the resultassert isinstance(result, ActionResult)assert f'Navigated to {base_url}/page1' in result.extracted_content# Verify the current page URL- page = await browser_context.get_current_page()+ page = await browser_session.get_current_page()assert f'{base_url}/page1' in page.url@pytest.mark.asyncio- async def test_scroll_actions(self, controller, browser_context, base_url):+ async def test_scroll_actions(self, controller, browser_session, base_url):"""Test that scroll actions correctly scroll the page."""# First navigate to a pagegoto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/page1')}@@ -137,7 +131,7 @@ class TestControllerIntegration:class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None- await controller.act(GoToUrlActionModel(**goto_action), browser_context)+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)# Create scroll down actionscroll_action = {'scroll_down': ScrollAction(amount=200)}@@ -146,7 +140,7 @@ class TestControllerIntegration:scroll_down: ScrollAction | None = None# Execute scroll down- result = await controller.act(ScrollActionModel(**scroll_action), browser_context)+ result = await controller.act(ScrollActionModel(**scroll_action), browser_session)# Verify the resultassert isinstance(result, ActionResult)@@ -159,14 +153,14 @@ class TestControllerIntegration:scroll_up: ScrollAction | None = None# Execute scroll up- result = await controller.act(ScrollUpActionModel(**scroll_up_action), browser_context)+ result = await controller.act(ScrollUpActionModel(**scroll_up_action), browser_session)# Verify the resultassert isinstance(result, ActionResult)assert 'Scrolled up' in result.extracted_content@pytest.mark.asyncio- async def test_registry_actions(self, controller, browser_context):+ async def test_registry_actions(self, controller, browser_session):"""Test that the registry contains the expected default actions."""# Check that common actions are registeredcommon_actions = [@@ -189,7 +183,7 @@ class TestControllerIntegration:assert controller.registry.registry.actions[action].description is not None@pytest.mark.asyncio- async def test_custom_action_registration(self, controller, browser_context, base_url):+ async def test_custom_action_registration(self, controller, browser_session, base_url):"""Test registering a custom action and executing it."""# Define a custom action@@ -197,8 +191,8 @@ class TestControllerIntegration:text: str@controller.action('Test custom action', param_model=CustomParams)- async def custom_action(params: CustomParams, browser):- page = await browser.get_current_page()+ async def custom_action(params: CustomParams, browser_session):+ page = await browser_session.get_current_page()return ActionResult(extracted_content=f'Custom action executed with: {params.text} on {page.url}')# Navigate to a page first@@ -207,7 +201,7 @@ class TestControllerIntegration:class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None- await controller.act(GoToUrlActionModel(**goto_action), browser_context)+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)# Create the custom action modelcustom_action_data = {'custom_action': CustomParams(text='test_value')}@@ -216,7 +210,7 @@ class TestControllerIntegration:custom_action: CustomParams | None = None# Execute the custom action- result = await controller.act(CustomActionModel(**custom_action_data), browser_context)+ result = await controller.act(CustomActionModel(**custom_action_data), browser_session)# Verify the resultassert isinstance(result, ActionResult)@@ -224,7 +218,7 @@ class TestControllerIntegration:assert f'{base_url}/page1' in result.extracted_content@pytest.mark.asyncio- async def test_input_text_action(self, controller, browser_context, base_url, http_server):+ async def test_input_text_action(self, controller, browser_session, base_url, http_server):"""Test that InputTextAction correctly inputs text into form fields."""# Set up search form endpoint for this testhttp_server.expect_request('/searchform').respond_with_data(@@ -249,11 +243,11 @@ class TestControllerIntegration:class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None- await controller.act(GoToUrlActionModel(**goto_action), browser_context)+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)# Get the search input field index- page = await browser_context.get_current_page()- selector_map = await browser_context.get_selector_map()+ page = await browser_session.get_current_page()+ selector_map = await browser_session.get_selector_map()# Find the search input field - this requires examining the DOM# We'll mock this part since we can't rely on specific element indices@@ -272,7 +266,7 @@ class TestControllerIntegration:# The actual input might fail if the page structure changes or in headless mode# So we'll just verify the controller correctly processes the actiontry:- result = await controller.act(InputTextActionModel(**input_action), browser_context)+ result = await controller.act(InputTextActionModel(**input_action), browser_session)# If successful, verify the resultassert isinstance(result, ActionResult)assert 'Input' in result.extracted_content@@ -281,7 +275,7 @@ class TestControllerIntegration:assert 'Element index' in str(e) or 'does not exist' in str(e)@pytest.mark.asyncio- async def test_error_handling(self, controller, browser_context):+ async def test_error_handling(self, controller, browser_session):"""Test error handling when an action fails."""# Create an action with an invalid indexinvalid_action = {'click_element_by_index': ClickElementAction(index=9999)}@@ -291,13 +285,13 @@ class TestControllerIntegration:# This should fail since the element doesn't existwith pytest.raises(Exception) as excinfo:- await controller.act(ClickActionModel(**invalid_action), browser_context)+ await controller.act(ClickActionModel(**invalid_action), browser_session)# Verify that an appropriate error is raisedassert 'does not exist' in str(excinfo.value) or 'Element with index' in str(excinfo.value)@pytest.mark.asyncio- async def test_wait_action(self, controller, browser_context):+ async def test_wait_action(self, controller, browser_session):"""Test that the wait action correctly waits for the specified duration."""# Create wait action for 1 second - fix to use a dictionarywait_action = {'wait': {'seconds': 1}} # Corrected format@@ -309,7 +303,7 @@ class TestControllerIntegration:start_time = time.time()# Execute wait action- result = await controller.act(WaitActionModel(**wait_action), browser_context)+ result = await controller.act(WaitActionModel(**wait_action), browser_session)# Record end timeend_time = time.time()@@ -322,7 +316,7 @@ class TestControllerIntegration:assert end_time - start_time >= 0.9 # Allow some timing margin@pytest.mark.asyncio- async def test_go_back_action(self, controller, browser_context, base_url):+ async def test_go_back_action(self, controller, browser_session, base_url):"""Test that go_back action navigates to the previous page."""# Navigate to first pagegoto_action1 = {'go_to_url': GoToUrlAction(url=f'{base_url}/page1')}@@ -330,19 +324,19 @@ class TestControllerIntegration:class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None- await controller.act(GoToUrlActionModel(**goto_action1), browser_context)+ await controller.act(GoToUrlActionModel(**goto_action1), browser_session)# Store the first page URL- page1 = await browser_context.get_current_page()+ page1 = await browser_session.get_current_page()first_url = page1.urlprint(f'First page URL: {first_url}')# Navigate to second pagegoto_action2 = {'go_to_url': GoToUrlAction(url=f'{base_url}/page2')}- await controller.act(GoToUrlActionModel(**goto_action2), browser_context)+ await controller.act(GoToUrlActionModel(**goto_action2), browser_session)# Verify we're on the second page- page2 = await browser_context.get_current_page()+ page2 = await browser_session.get_current_page()second_url = page2.urlprint(f'Second page URL: {second_url}')assert f'{base_url}/page2' in second_url@@ -353,7 +347,7 @@ class TestControllerIntegration:class GoBackActionModel(ActionModel):go_back: NoParamsAction | None = None- result = await controller.act(GoBackActionModel(**go_back_action), browser_context)+ result = await controller.act(GoBackActionModel(**go_back_action), browser_session)# Verify the resultassert isinstance(result, ActionResult)@@ -363,7 +357,7 @@ class TestControllerIntegration:await asyncio.sleep(1)# Verify we're back on a different page than before- page3 = await browser_context.get_current_page()+ page3 = await browser_session.get_current_page()final_url = page3.urlprint(f'Final page URL after going back: {final_url}')@@ -371,7 +365,7 @@ class TestControllerIntegration:assert f'{base_url}/page1' in final_url, f'Expected to return to page1 but got {final_url}'@pytest.mark.asyncio- async def test_navigation_chain(self, controller, browser_context, base_url):+ async def test_navigation_chain(self, controller, browser_session, base_url):"""Test navigating through multiple pages and back through history."""# Set up a chain of navigation: Home -> Page1 -> Page2urls = [f'{base_url}/', f'{base_url}/page1', f'{base_url}/page2']@@ -383,10 +377,10 @@ class TestControllerIntegration:class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None- await controller.act(GoToUrlActionModel(**action_data), browser_context)+ await controller.act(GoToUrlActionModel(**action_data), browser_session)# Verify current page- page = await browser_context.get_current_page()+ page = await browser_session.get_current_page()assert url in page.url# Go back twice and verify each step@@ -396,14 +390,14 @@ class TestControllerIntegration:class GoBackActionModel(ActionModel):go_back: NoParamsAction | None = None- await controller.act(GoBackActionModel(**go_back_action), browser_context)+ await controller.act(GoBackActionModel(**go_back_action), browser_session)await asyncio.sleep(1) # Wait for navigation to complete- page = await browser_context.get_current_page()+ page = await browser_session.get_current_page()assert expected_url in page.url@pytest.mark.asyncio- async def test_concurrent_tab_operations(self, controller, browser_context, base_url):+ async def test_concurrent_tab_operations(self, controller, browser_session, base_url):"""Test operations across multiple tabs."""# Create two tabs with different contenturls = [f'{base_url}/page1', f'{base_url}/page2']@@ -414,7 +408,7 @@ class TestControllerIntegration:class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None- await controller.act(GoToUrlActionModel(**goto_action1), browser_context)+ await controller.act(GoToUrlActionModel(**goto_action1), browser_session)# Open second tabopen_tab_action = {'open_tab': OpenTabAction(url=urls[1])}@@ -422,10 +416,10 @@ class TestControllerIntegration:class OpenTabActionModel(ActionModel):open_tab: OpenTabAction | None = None- await controller.act(OpenTabActionModel(**open_tab_action), browser_context)+ await controller.act(OpenTabActionModel(**open_tab_action), browser_session)# Verify we're on second tab- page = await browser_context.get_current_page()+ page = await browser_session.get_current_page()assert urls[1] in page.url# Switch back to first tab@@ -434,10 +428,10 @@ class TestControllerIntegration:class SwitchTabActionModel(ActionModel):switch_tab: SwitchTabAction | None = None- await controller.act(SwitchTabActionModel(**switch_tab_action), browser_context)+ await controller.act(SwitchTabActionModel(**switch_tab_action), browser_session)# Verify we're back on first tab- page = await browser_context.get_current_page()+ page = await browser_session.get_current_page()assert urls[0] in page.url# Close the second tab@@ -446,15 +440,15 @@ class TestControllerIntegration:class CloseTabActionModel(ActionModel):close_tab: CloseTabAction | None = None- await controller.act(CloseTabActionModel(**close_tab_action), browser_context)+ await controller.act(CloseTabActionModel(**close_tab_action), browser_session)# Verify only one tab remains- tabs_info = await browser_context.get_tabs_info()+ tabs_info = await browser_session.get_tabs_info()assert len(tabs_info) == 1assert urls[0] in tabs_info[0].url@pytest.mark.asyncio- async def test_excluded_actions(self, browser_context):+ async def test_excluded_actions(self, browser_session):"""Test that excluded actions are not registered."""# Create controller with excluded actionsexcluded_controller = Controller(exclude_actions=['search_google', 'open_tab'])@@ -468,10 +462,10 @@ class TestControllerIntegration:assert 'click_element_by_index' in excluded_controller.registry.registry.actions@pytest.mark.asyncio- async def test_search_google_action(self, controller, browser_context, base_url):+ async def test_search_google_action(self, controller, browser_session, base_url):"""Test the search_google action."""- # Add a custom search handler for our test server- # Since this is a mock test, we'll just navigate to the /search page++ await browser_session.get_current_page()# Execute search_google action - it will actually navigate to our search results pagesearch_action = {'search_google': SearchGoogleAction(query='Python web automation')}@@ -479,18 +473,18 @@ class TestControllerIntegration:class SearchGoogleActionModel(ActionModel):search_google: SearchGoogleAction | None = None- result = await controller.act(SearchGoogleActionModel(**search_action), browser_context)+ result = await controller.act(SearchGoogleActionModel(**search_action), browser_session)# Verify the resultassert isinstance(result, ActionResult)assert 'Searched for "Python web automation" in Google' in result.extracted_content# For our test purposes, we just verify we're on some URL- page = await browser_context.get_current_page()+ page = await browser_session.get_current_page()assert page.url is not None and 'Python' in page.url@pytest.mark.asyncio- async def test_done_action(self, controller, browser_context, base_url):+ async def test_done_action(self, controller, browser_session, base_url):"""Test that DoneAction completes a task and reports success or failure."""# First navigate to a pagegoto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/page1')}@@ -498,7 +492,7 @@ class TestControllerIntegration:class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None- await controller.act(GoToUrlActionModel(**goto_action), browser_context)+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)success_done_message = 'Successfully completed task'@@ -509,7 +503,7 @@ class TestControllerIntegration:done: DoneAction | None = None# Execute done action- result = await controller.act(DoneActionModel(**done_action), browser_context)+ result = await controller.act(DoneActionModel(**done_action), browser_session)# Verify the resultassert isinstance(result, ActionResult)@@ -524,7 +518,7 @@ class TestControllerIntegration:failed_done_action = {'done': DoneAction(text=failed_done_message, success=False)}# Execute failed done action- result = await controller.act(DoneActionModel(**failed_done_action), browser_context)+ result = await controller.act(DoneActionModel(**failed_done_action), browser_session)# Verify the resultassert isinstance(result, ActionResult)@@ -534,7 +528,7 @@ class TestControllerIntegration:assert result.error is None@pytest.mark.asyncio- async def test_drag_drop_action(self, controller, browser_context, base_url, http_server):+ async def test_drag_drop_action(self, controller, browser_session, base_url, http_server):"""Test that DragDropAction correctly drags and drops elements."""# Set up drag and drop test page for this testhttp_server.expect_request('/dragdrop').respond_with_data(@@ -678,14 +672,14 @@ class TestControllerIntegration:class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None- goto_result = await controller.act(GoToUrlActionModel(**goto_action), browser_context)+ goto_result = await controller.act(GoToUrlActionModel(**goto_action), browser_session)# Verify navigation workedassert goto_result.error is None, f'Navigation failed: {goto_result.error}'assert f'Navigated to {base_url}/dragdrop' in goto_result.extracted_content# Get page reference- page = await browser_context.get_current_page()+ page = await browser_session.get_current_page()# Verify we loaded the page correctlytitle = await page.title()@@ -737,7 +731,7 @@ class TestControllerIntegration:drag_drop: DragDropAction | None = None# Execute the drag action through the controller- result = await controller.act(DragDropActionModel(**drag_action), browser_context)+ result = await controller.act(DragDropActionModel(**drag_action), browser_session)# Step 5: Verify the controller action resultassert result.error is None, f'Drag operation failed with error: {result.error}'@@ -762,7 +756,7 @@ class TestControllerIntegration:assert drag_succeeded, "Drag and drop events weren't fired correctly"@pytest.mark.asyncio- async def test_send_keys_action(self, controller, browser_context, base_url, http_server):+ async def test_send_keys_action(self, controller, browser_session, base_url, http_server):"""Test SendKeysAction using a controlled local HTML file."""# Set up keyboard test page for this testhttp_server.expect_request('/keyboard').respond_with_data(@@ -829,7 +823,7 @@ class TestControllerIntegration:go_to_url: GoToUrlAction | None = None# Execute navigation- goto_result = await controller.act(GoToUrlActionModel(**goto_action), browser_context)+ goto_result = await controller.act(GoToUrlActionModel(**goto_action), browser_session)await asyncio.sleep(0.1)# Verify navigation result@@ -839,7 +833,7 @@ class TestControllerIntegration:assert goto_result.is_done is False# Get the page object- page = await browser_context.get_current_page()+ page = await browser_session.get_current_page()# Verify page loadedtitle = await page.title()@@ -855,7 +849,7 @@ class TestControllerIntegration:class SendKeysActionModel(ActionModel):send_keys: SendKeysAction | None = None- tab_result = await controller.act(SendKeysActionModel(**tab_keys_action), browser_context)+ tab_result = await controller.act(SendKeysActionModel(**tab_keys_action), browser_session)await asyncio.sleep(0.1)# Verify Tab action result@@ -875,7 +869,7 @@ class TestControllerIntegration:# 2. Type text into the inputtest_text = 'This is a test'type_action = {'send_keys': SendKeysAction(keys=test_text)}- type_result = await controller.act(SendKeysActionModel(**type_action), browser_context)+ type_result = await controller.act(SendKeysActionModel(**type_action), browser_session)await asyncio.sleep(0.1)# Verify typing action result@@ -895,7 +889,7 @@ class TestControllerIntegration:# 3. Test Ctrl+A for select allselect_all_action = {'send_keys': SendKeysAction(keys='ControlOrMeta+a')}- select_all_result = await controller.act(SendKeysActionModel(**select_all_action), browser_context)+ select_all_result = await controller.act(SendKeysActionModel(**select_all_action), browser_session)# Wait longer for selection to take effectawait asyncio.sleep(1.0)@@ -917,7 +911,7 @@ class TestControllerIntegration:assert 'Selection length:' in result_text# 4. Test Tab to next field- tab_result2 = await controller.act(SendKeysActionModel(**tab_keys_action), browser_context)+ tab_result2 = await controller.act(SendKeysActionModel(**tab_keys_action), browser_session)await asyncio.sleep(0.1)# Verify second Tab action result@@ -936,7 +930,7 @@ class TestControllerIntegration:# 5. Type in the textareatextarea_text = 'Testing multiline\ninput text'textarea_action = {'send_keys': SendKeysAction(keys=textarea_text)}- textarea_result = await controller.act(SendKeysActionModel(**textarea_action), browser_context)+ textarea_result = await controller.act(SendKeysActionModel(**textarea_action), browser_session)# Verify textarea typing action resultassert isinstance(textarea_result, ActionResult)@@ -955,8 +949,8 @@ class TestControllerIntegration:assert lines[1] == 'input text'# Test that Tab cycles back to the first element if we tab again- await controller.act(SendKeysActionModel(**tab_keys_action), browser_context)- await controller.act(SendKeysActionModel(**tab_keys_action), browser_context)+ await controller.act(SendKeysActionModel(**tab_keys_action), browser_session)+ await controller.act(SendKeysActionModel(**tab_keys_action), browser_session)active_element_id = await page.evaluate('() => document.activeElement.id')assert active_element_id == 'textInput', 'Tab cycling through form elements failed'@@ -966,7 +960,7 @@ class TestControllerIntegration:assert input_value == test_text, "Input value shouldn't have changed after tabbing"@pytest.mark.asyncio- async def test_get_dropdown_options(self, controller, browser_context, base_url, http_server):+ async def test_get_dropdown_options(self, controller, browser_session, base_url, http_server):"""Test that get_dropdown_options correctly retrieves options from a dropdown."""# Add route for dropdown test pagehttp_server.expect_request('/dropdown1').respond_with_data(@@ -996,23 +990,23 @@ class TestControllerIntegration:class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None- await controller.act(GoToUrlActionModel(**goto_action), browser_context)+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)# Wait for the page to load- page = await browser_context.get_current_page()+ page = await browser_session.get_current_page()await page.wait_for_load_state()# Initialize the DOM state to populate the selector map- await browser_context.get_state(cache_clickable_elements_hashes=True)+ await browser_session.get_state_summary(cache_clickable_elements_hashes=True)# Interact with the dropdown to ensure it's recognizedawait page.click('select#test-dropdown')# Update the state after interaction- await browser_context.get_state(cache_clickable_elements_hashes=True)+ await browser_session.get_state_summary(cache_clickable_elements_hashes=True)# Get the selector map- selector_map = await browser_context.get_selector_map()+ selector_map = await browser_session.get_selector_map()# Find the dropdown element in the selector mapdropdown_index = None@@ -1027,10 +1021,13 @@ class TestControllerIntegration:# Create a model for the standard get_dropdown_options actionclass GetDropdownOptionsModel(ActionModel):- get_dropdown_options: dict+ get_dropdown_options: dict[str, int]# Execute the action with the dropdown index- result = await controller.act(GetDropdownOptionsModel(get_dropdown_options={'index': dropdown_index}), browser_context)+ result = await controller.act(+ action=GetDropdownOptionsModel(get_dropdown_options={'index': dropdown_index}),+ browser_session=browser_session,+ )expected_options = [{'index': 0, 'text': 'Please select', 'value': ''},@@ -1074,7 +1071,7 @@ class TestControllerIntegration:)@pytest.mark.asyncio- async def test_select_dropdown_option(self, controller, browser_context, base_url, http_server):+ async def test_select_dropdown_option(self, controller, browser_session, base_url, http_server):"""Test that select_dropdown_option correctly selects an option from a dropdown."""# Add route for dropdown test pagehttp_server.expect_request('/dropdown2').respond_with_data(@@ -1104,17 +1101,17 @@ class TestControllerIntegration:class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None- await controller.act(GoToUrlActionModel(**goto_action), browser_context)+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)# Wait for the page to load- page = await browser_context.get_current_page()+ page = await browser_session.get_current_page()await page.wait_for_load_state()# populate the selector map with highlight indices- await browser_context.get_state(cache_clickable_elements_hashes=True)+ await browser_session.get_state_summary(cache_clickable_elements_hashes=True)# Now get the selector map which should contain our dropdown- selector_map = await browser_context.get_selector_map()+ selector_map = await browser_session.get_selector_map()# Find the dropdown element in the selector mapdropdown_index = None@@ -1134,7 +1131,7 @@ class TestControllerIntegration:# Execute the action with the dropdown indexresult = await controller.act(SelectDropdownOptionModel(select_dropdown_option={'index': dropdown_index, 'text': 'Second Option'}),- browser_context,+ browser_session,)# Verify the result structure@@ -1149,7 +1146,7 @@ class TestControllerIntegration:assert selected_value == 'option2' # Second Option has value "option2"@pytest.mark.asyncio- async def test_click_element_by_index(self, controller, browser_context, base_url, http_server):+ async def test_click_element_by_index(self, controller, browser_session, base_url, http_server):"""Test that click_element_by_index correctly clicks an element and handles different outcomes."""# Add route for clickable elements test pagehttp_server.expect_request('/clickable').respond_with_data(@@ -1197,17 +1194,17 @@ class TestControllerIntegration:class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None- await controller.act(GoToUrlActionModel(**goto_action), browser_context)+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)# Wait for the page to load- page = await browser_context.get_current_page()+ page = await browser_session.get_current_page()await page.wait_for_load_state()# Initialize the DOM state to populate the selector map- await browser_context.get_state(cache_clickable_elements_hashes=True)+ await browser_session.get_state_summary(cache_clickable_elements_hashes=True)# Get the selector map- selector_map = await browser_context.get_selector_map()+ selector_map = await browser_session.get_selector_map()# Find a clickable element in the selector mapbutton_index = None@@ -1237,7 +1234,7 @@ class TestControllerIntegration:click_element_by_index: ClickElementAction | None = None# Execute the action with the button index- result = await controller.act(ClickElementActionModel(click_element_by_index={'index': button_index}), browser_context)+ result = await controller.act(ClickElementActionModel(click_element_by_index={'index': button_index}), browser_session)# Verify the result structureassert isinstance(result, ActionResult), 'Result should be an ActionResult instance'diff --git a/tests/test_core_functionality.py b/tests/test_core_functionality.pyindex 424688842..3f4411062 100644--- a/tests/test_core_functionality.py+++ b/tests/test_core_functionality.py@@ -1,202 +1,302 @@import asyncio-import osimport pytest-from langchain_openai import AzureChatOpenAI-from pydantic import SecretStr+from langchain_openai import ChatOpenAI+from pytest_httpserver import HTTPServerfrom browser_use.agent.service import Agentfrom browser_use.agent.views import AgentHistoryList-from browser_use.browser.browser import Browser, BrowserConfig--[email protected](scope='function')-def event_loop():- """Create an instance of the default event loop for each test case."""- loop = asyncio.get_event_loop_policy().new_event_loop()- yield loop- loop.close()--[email protected](scope='function')-async def browser(event_loop):- browser_instance = Browser(- config=BrowserConfig(- headless=True,- )- )- yield browser_instance- await browser_instance.close()---async def context(browser):- async with await browser.new_context() as context:- yield context---def llm():- """Initialize language model for testing"""- return AzureChatOpenAI(- model='gpt-4o',- api_version='2024-10-21',- azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),- api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),- )---# pytest -s -k test_search_google-async def test_search_google(llm, context):- """Test 'Search Google' action"""- agent = Agent(- task="Search Google for 'OpenAI'.",- llm=llm,- browser_context=context,- )- history: AgentHistoryList = await agent.run(max_steps=2)- action_names = history.action_names()- assert 'search_google' in action_names---async def test_go_to_url(llm, context):- """Test 'Navigate to URL' action"""- agent = Agent(- task="Navigate to 'https://www.python.org'.",- llm=llm,- browser_context=context,- )- history = await agent.run(max_steps=2)- action_names = history.action_names()- assert 'go_to_url' in action_names---async def test_go_back(llm, context):- """Test 'Go back' action"""- agent = Agent(- task="Go to 'https://www.example.com', then go back.",- llm=llm,- browser_context=context,- )- history = await agent.run(max_steps=3)- action_names = history.action_names()- assert 'go_to_url' in action_names- assert 'go_back' in action_names---async def test_click_element(llm, context):- """Test 'Click element' action"""- agent = Agent(- task="Go to 'https://www.python.org' and click on the first link.",- llm=llm,- browser_context=context,- )- history = await agent.run(max_steps=4)- action_names = history.action_names()- assert 'go_to_url' in action_names or 'open_tab' in action_names- assert 'click_element_by_index' in action_names---async def test_input_text(llm, context):- """Test 'Input text' action"""- agent = Agent(- task="Go to 'https://www.google.com' and input 'OpenAI' into the search box.",- llm=llm,- browser_context=context,- )- history = await agent.run(max_steps=4)- action_names = history.action_names()- assert 'go_to_url' in action_names- assert 'input_text' in action_names---async def test_switch_tab(llm, context):- """Test 'Switch tab' action"""- agent = Agent(- task="Open new tabs with 'https://www.google.com' and 'https://www.wikipedia.org', then switch to the first tab.",- llm=llm,- browser_context=context,- )- history = await agent.run(max_steps=6)- action_names = history.action_names()- open_tab_count = action_names.count('open_tab')- assert open_tab_count >= 2- assert 'switch_tab' in action_names---async def test_open_new_tab(llm, context):- """Test 'Open new tab' action"""- agent = Agent(- task="Open a new tab and go to 'https://www.example.com'.",- llm=llm,- browser_context=context,- )- history = await agent.run(max_steps=3)- action_names = history.action_names()- assert 'open_tab' in action_names---async def test_extract_page_content(llm, context):- """Test 'Extract page content' action"""- agent = Agent(- task="Go to 'https://www.example.com' and extract the page content.",- llm=llm,- browser_context=context,- )- history = await agent.run(max_steps=3)- action_names = history.action_names()- assert 'go_to_url' in action_names- assert 'extract_content' in action_names---# pytest -k test_done_action-async def test_done_action(llm, context):- """Test 'Complete task' action"""- agent = Agent(- task="Navigate to 'https://www.example.com' and signal that the task is done.",- llm=llm,- browser_context=context,- )-- history = await agent.run(max_steps=3)- action_names = history.action_names()- assert 'go_to_url' in action_names- assert 'done' in action_names---# run with: pytest -k test_scroll_down-async def test_scroll_down(llm, context):- """Test 'Scroll down' action and validate that the page actually scrolled"""- agent = Agent(- task="Go to 'https://en.wikipedia.org/wiki/Internet' and scroll down the page.",- llm=llm,- browser_context=context,- )- # Get the browser instance- page = await context.get_current_page()-- # Navigate to the page and get initial scroll position- await agent.run(max_steps=1)- initial_scroll_position = await page.evaluate('window.scrollY;')-- # Perform the scroll down action- await agent.run(max_steps=2)- final_scroll_position = await page.evaluate('window.scrollY;')-- # Validate that the scroll position has changed- assert final_scroll_position > initial_scroll_position, 'Page did not scroll down'-- # Validate that the 'scroll_down' action was executed- history = agent.history- action_names = history.action_names()- assert 'scroll_down' in action_names+from browser_use.browser import BrowserProfile, BrowserSession+++class TestCoreFunctionality:+ """Tests for core functionality of the Agent using real browser instances."""++ @pytest.fixture(scope='module')+ def event_loop(self):+ """Create and provide an event loop for async tests."""+ loop = asyncio.get_event_loop_policy().new_event_loop()+ yield loop+ loop.close()++ @pytest.fixture(scope='module')+ def http_server(self):+ """Create and provide a test HTTP server that serves static content."""+ server = HTTPServer()+ server.start()++ # Add routes for common test pages+ server.expect_request('/').respond_with_data(+ '<html><head><title>Test Home Page</title></head><body><h1>Test Home Page</h1><p>Welcome to the test site</p></body></html>',+ content_type='text/html',+ )++ server.expect_request('/page1').respond_with_data(+ '<html><head><title>Test Page 1</title></head><body><h1>Test Page 1</h1><p>This is test page 1</p><a href="/page2">Link to Page 2</a></body></html>',+ content_type='text/html',+ )++ server.expect_request('/page2').respond_with_data(+ '<html><head><title>Test Page 2</title></head><body><h1>Test Page 2</h1><p>This is test page 2</p><a href="/page1">Back to Page 1</a></body></html>',+ content_type='text/html',+ )++ server.expect_request('/search').respond_with_data(+ """+ <html>+ <head><title>Search Results</title></head>+ <body>+ <h1>Search Results</h1>+ <form>+ <input type="text" id="search-box" placeholder="Search...">+ <button type="submit">Search</button>+ </form>+ <div class="results">+ <div class="result">Result 1</div>+ <div class="result">Result 2</div>+ <div class="result">Result 3</div>+ </div>+ </body>+ </html>+ """,+ content_type='text/html',+ )++ yield server+ server.stop()++ @pytest.fixture+ def base_url(self, http_server):+ """Return the base URL for the test HTTP server."""+ return f'http://{http_server.host}:{http_server.port}'++ @pytest.fixture(scope='module')+ async def browser_session(self, event_loop):+ """Create and provide a BrowserSession instance with security disabled."""+ browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ headless=True,+ disable_security=True,+ )+ )+ yield browser_session+ await browser_session.stop()++ @pytest.fixture+ def llm(self):+ """Initialize language model for testing with minimal settings."""+ return ChatOpenAI(+ model='gpt-4o',+ temperature=0.0,+ )++ @pytest.mark.asyncio+ async def test_search_google(self, llm, browser_session, base_url):+ """Test 'Search Google' action using a mock search page."""+ agent = Agent(+ task=f"Go to '{base_url}/search' and search for 'OpenAI'.",+ llm=llm,+ browser_session=browser_session,+ )+ history: AgentHistoryList = await agent.run(max_steps=3)+ action_names = history.action_names()+ assert 'go_to_url' in action_names+ assert any('input_text' in action or 'click_element_by_index' in action for action in action_names)++ @pytest.mark.asyncio+ async def test_go_to_url(self, llm, browser_session, base_url):+ """Test 'Navigate to URL' action."""+ agent = Agent(+ task=f"Navigate to '{base_url}/page1'.",+ llm=llm,+ browser_session=browser_session,+ )+ history = await agent.run(max_steps=2)+ action_names = history.action_names()+ assert 'go_to_url' in action_names++ # Verify we're on the correct page+ page = await browser_session.get_current_page()+ assert f'{base_url}/page1' in page.url++ @pytest.mark.asyncio+ async def test_go_back(self, llm, browser_session, base_url):+ """Test 'Go back' action."""+ # First navigate to page1, then to page2, then go back+ agent = Agent(+ task=f"Go to '{base_url}/page1', then go to '{base_url}/page2', then go back.",+ llm=llm,+ browser_session=browser_session,+ )+ history = await agent.run(max_steps=4)+ action_names = history.action_names()+ assert 'go_to_url' in action_names+ assert 'go_back' in action_names++ # Verify we're back on page1+ page = await browser_session.get_current_page()+ assert f'{base_url}/page1' in page.url++ @pytest.mark.asyncio+ async def test_click_element(self, llm, browser_session, base_url):+ """Test 'Click element' action."""+ agent = Agent(+ task=f"Go to '{base_url}/page1' and click on the link to Page 2.",+ llm=llm,+ browser_session=browser_session,+ )+ history = await agent.run(max_steps=3)+ action_names = history.action_names()+ assert 'go_to_url' in action_names+ assert 'click_element_by_index' in action_names++ # Verify we're now on page2 after clicking the link+ page = await browser_session.get_current_page()+ assert f'{base_url}/page2' in page.url++ @pytest.mark.asyncio+ async def test_input_text(self, llm, browser_session, base_url):+ """Test 'Input text' action."""+ agent = Agent(+ task=f"Go to '{base_url}/search' and input 'OpenAI' into the search box.",+ llm=llm,+ browser_session=browser_session,+ )+ history = await agent.run(max_steps=3)+ action_names = history.action_names()+ assert 'go_to_url' in action_names+ assert 'input_text' in action_names++ # Verify text was entered in the search box+ page = await browser_session.get_current_page()+ search_value = await page.evaluate("document.getElementById('search-box').value")+ assert 'OpenAI' in search_value++ @pytest.mark.asyncio+ async def test_switch_tab(self, llm, browser_session, base_url):+ """Test 'Switch tab' action."""+ agent = Agent(+ task=f"Open '{base_url}/page1' in the current tab, then open a new tab with '{base_url}/page2', then switch back to the first tab.",+ llm=llm,+ browser_session=browser_session,+ )+ history = await agent.run(max_steps=4)+ action_names = history.action_names()+ assert 'go_to_url' in action_names+ assert 'open_tab' in action_names+ assert 'switch_tab' in action_names++ # Verify we're back on the first tab with page1+ page = await browser_session.get_current_page()+ assert f'{base_url}/page1' in page.url++ @pytest.mark.asyncio+ async def test_open_new_tab(self, llm, browser_session, base_url):+ """Test 'Open new tab' action."""+ agent = Agent(+ task=f"Open a new tab and go to '{base_url}/page2'.",+ llm=llm,+ browser_session=browser_session,+ )+ history = await agent.run(max_steps=2)+ action_names = history.action_names()+ assert 'open_tab' in action_names++ # Verify we have at least two tabs+ tabs_info = await browser_session.get_tabs_info()+ assert len(tabs_info) >= 2++ # Verify the current page is page2+ page = await browser_session.get_current_page()+ assert f'{base_url}/page2' in page.url++ @pytest.mark.asyncio+ async def test_extract_page_content(self, llm, browser_session, base_url):+ """Test 'Extract page content' action."""+ agent = Agent(+ task=f"Go to '{base_url}/page1' and extract the page content.",+ llm=llm,+ browser_session=browser_session,+ )+ history = await agent.run(max_steps=3)+ action_names = history.action_names()+ assert 'go_to_url' in action_names+ assert 'extract_content' in action_names++ # Verify the extracted content includes some expected text+ extracted_content = None+ for action_result in history.history[-1].result:+ if action_result.extracted_content and 'This is test page 1' in action_result.extracted_content:+ extracted_content = action_result.extracted_content+ break++ assert extracted_content is not None, 'Expected content not found in extraction'++ @pytest.mark.asyncio+ async def test_done_action(self, llm, browser_session, base_url):+ """Test 'Complete task' action."""+ agent = Agent(+ task=f"Navigate to '{base_url}/page1' and signal that the task is done.",+ llm=llm,+ browser_session=browser_session,+ )+ history = await agent.run(max_steps=3)+ action_names = history.action_names()+ assert 'go_to_url' in action_names+ assert 'done' in action_names++ # Verify the task was marked as successful+ assert history.is_successful()++ @pytest.mark.asyncio+ async def test_scroll_down(self, llm, browser_session, base_url, http_server):+ """Test 'Scroll down' action and validate that the page actually scrolled."""+ # Create a test page with scrollable content+ http_server.expect_request('/scroll-test').respond_with_data(+ """+ <html>+ <head><title>Scroll Test</title>+ <style>+ body { height: 3000px; }+ .marker { position: absolute; }+ #top { top: 0; }+ #middle { top: 1000px; }+ #bottom { top: 2000px; }+ </style>+ </head>+ <body>+ <div id="top" class="marker">Top of the page</div>+ <div id="middle" class="marker">Middle of the page</div>+ <div id="bottom" class="marker">Bottom of the page</div>+ </body>+ </html>+ """,+ content_type='text/html',+ )++ agent = Agent(+ task=f"Go to '{base_url}/scroll-test' and scroll down the page.",+ llm=llm,+ browser_session=browser_session,+ )++ # First go to the page+ await agent.run(max_steps=1)+ page = await browser_session.get_current_page()++ # Get initial scroll position+ initial_scroll_position = await page.evaluate('window.scrollY')++ # Execute a few more steps to allow for scrolling+ await agent.run(max_steps=2)++ # Get final scroll position+ final_scroll_position = await page.evaluate('window.scrollY')++ # Verify that scrolling occurred+ assert final_scroll_position > initial_scroll_position, 'Page did not scroll down'++ # Verify the action was executed+ history = agent.state.history+ action_names = history.action_names()+ assert 'scroll_down' in action_namesdiff --git a/tests/test_service.py b/tests/test_service.pyindex e3f449b19..0b8035fdd 100644--- a/tests/test_service.py+++ b/tests/test_service.py@@ -9,7 +9,7 @@ from browser_use.agent.service import Agentfrom browser_use.agent.views import ActionResultfrom browser_use.browser.browser import Browserfrom browser_use.browser.context import BrowserContext-from browser_use.browser.views import BrowserState+from browser_use.browser.views import BrowserStateSummaryfrom browser_use.controller.registry.service import Registryfrom browser_use.controller.registry.views import ActionModelfrom browser_use.controller.service import Controller@@ -101,8 +101,8 @@ class TestAgent:# Mock the browser_contextagent.browser_context = AsyncMock()- agent.browser_context.get_state = AsyncMock(- return_value=BrowserState(+ agent.browser_context.get_state_summary = AsyncMock(+ return_value=BrowserStateSummary(url='https://example.com',title='Example',element_tree=MagicMock(), # Mocked element tree@@ -237,8 +237,8 @@ class TestAgentRetry:@pytest.fixturedef mock_browser_context(self):browser_context = Mock()- browser_context.get_state = AsyncMock(- return_value=BrowserState(+ browser_context.get_state_summary = AsyncMock(+ return_value=BrowserStateSummary(url='https://parabank.parasoft.com/parabank/index.htm',title='ParaBank',element_tree=MagicMock(),diff --git a/tests/test_tab_management.py b/tests/test_tab_management.pyindex 396497af9..e4c421251 100644--- a/tests/test_tab_management.py+++ b/tests/test_tab_management.py@@ -8,15 +8,9 @@ from pytest_httpserver import HTTPServerload_dotenv()from browser_use.agent.views import ActionModel-from browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.context import BrowserContext+from browser_use.browser.session import BrowserSession+from browser_use.browser.types import BrowserProfilefrom browser_use.controller.service import Controller-from browser_use.controller.views import (- CloseTabAction,- GoToUrlAction,- OpenTabAction,- SwitchTabAction,-)# Set up test logginglogger = logging.getLogger('tab_tests')@@ -57,40 +51,32 @@ class TestTabManagement:server.stop()@pytest.fixture(scope='module')- async def browser(self, event_loop):- """Create and provide a Browser instance with security disabled."""- browser_instance = Browser(- config=BrowserConfig(- headless=True,- )- )- yield browser_instance- await browser_instance.close()-- @pytest.fixture- async def browser_context(self, browser, http_server):- """Create and provide a BrowserContext instance with a properly initialized tab."""- context = BrowserContext(browser=browser)-- # Initialize a session- session = await context.get_session()+ async def browser_profile(self, event_loop):+ """Create and provide a BrowserProfile with security disabled."""+ profile = BrowserProfile(headless=True)+ yield profile- # Ensure we start with no pages (close any that might exist)- for page in session.context.pages:- await page.close()+ @pytest.fixture(scope='module')+ async def browser_session(self, browser_profile, http_server):+ """Create and provide a BrowserSession instance with a properly initialized tab."""+ browser_session = BrowserSession(+ browser_profile=browser_profile,+ user_data_dir=None,+ )+ await browser_session.start()# Create an initial tab and wait for it to load completelybase_url = f'http://{http_server.host}:{http_server.port}'- await context.create_new_tab(f'{base_url}/page1')+ await browser_session.new_tab(f'{base_url}/page1')await asyncio.sleep(1) # Wait for the tab to fully initialize# Verify that agent_current_page and human_current_page are properly set- assert context.agent_current_page is not None- assert context.human_current_page is not None- assert f'{http_server.host}:{http_server.port}' in context.agent_current_page.url+ assert browser_session.agent_current_page is not None+ assert browser_session.human_current_page is not None+ assert f'{http_server.host}:{http_server.port}' in browser_session.agent_current_page.url- yield context- await context.close()+ yield browser_session+ await browser_session.stop()@pytest.fixturedef controller(self):@@ -104,7 +90,7 @@ class TestTabManagement:# Helper methods- async def _execute_action(self, controller, browser_context, action_data):+ async def _execute_action(self, controller, browser_session: BrowserSession, action_data):"""Generic helper to execute any action via the controller."""# Dynamically create an appropriate ActionModel classaction_type = list(action_data.keys())[0]@@ -118,34 +104,39 @@ class TestTabManagement:setattr(DynamicActionModel, action_type, type(action_value) | None)# Execute the action- result = await controller.act(DynamicActionModel(**action_data), browser_context)+ result = await controller.act(DynamicActionModel(**action_data), browser_session)# Give the browser a moment to process the actionawait asyncio.sleep(0.5)return result- async def _ensure_synchronized_state(self, browser_context, base_url):- """Helper to ensure tab references are properly synchronized before tests."""- # Make sure agent_current_page and human_current_page are set and valid- session = await browser_context.get_session()+ async def _reset_tab_state(self, browser_session: BrowserSession, base_url: str):+ browser_session.human_current_page = None+ browser_session.agent_current_page = None- if not browser_context.agent_current_page or browser_context.agent_current_page not in session.context.pages:- if session.context.pages:- browser_context.agent_current_page = session.context.pages[0]- else:- # Create a tab with the test server- await browser_context.create_new_tab(f'{base_url}/page1')- await asyncio.sleep(1) # Wait longer for tab to initialize+ # close all existing tabs+ for page in browser_session.browser_context.pages:+ await page.close()- if not browser_context.human_current_page or browser_context.human_current_page not in session.context.pages:- browser_context.human_current_page = browser_context.agent_current_page+ await asyncio.sleep(0.5)- async def _simulate_user_tab_change(self, page, browser_context):+ # open one new tab and set it as the human_current_page & agent_current_page+ initial_tab = await browser_session.get_current_page()++ assert initial_tab is not None+ assert browser_session.human_current_page is not None+ assert browser_session.agent_current_page is not None+ assert browser_session.human_current_page.url == initial_tab.url+ assert browser_session.agent_current_page.url == initial_tab.url+ return initial_tab++ async def _simulate_human_tab_change(self, page, browser_session: BrowserSession):"""Simulate a user changing tabs by properly triggering events with Playwright."""+logger.debug(- f'BEFORE: agent_tab={browser_context.agent_current_page.url if browser_context.agent_current_page else "None"}, '- f'human_current_page={browser_context.human_current_page.url if browser_context.human_current_page else "None"}'+ f'BEFORE: agent_tab={browser_session.agent_current_page.url if browser_session.agent_current_page else "None"}, '+ f'human_current_page={browser_session.human_current_page.url if browser_session.human_current_page else "None"}')logger.debug(f'Simulating user changing to -> {page.url}')@@ -170,406 +161,155 @@ class TestTabManagement:# cheat for now, because playwright really messes with foreground tab detection# TODO: fix this properly by triggering the right events and detecting them in playwright- await page.evaluate("""() => {- const listener = Object.keys(window).filter(k => k.startsWith('onVisibilityChange'))[0]- if (listener) {- window[listener]({ bubbles: true, cancelable: false })- }+ if page.url == 'about:blank':+ raise Exception(+ 'Cannot simulate tab change on about:blank because cannot execute JS to fire focus event on about:blank'+ )+ await page.evaluate("""async () => {+ return await window._BrowserUseonTabVisibilityChange({ bubbles: true, cancelable: false });}""")# Give the event handlers time to processawait asyncio.sleep(0.5)logger.debug(- f'AFTER: agent_tab URL={browser_context.agent_current_page.url if browser_context.agent_current_page else "None"}, '- f'human_current_page URL={browser_context.human_current_page.url if browser_context.human_current_page else "None"}'+ f'AFTER: agent_tab URL={browser_session.agent_current_page.url if browser_session.agent_current_page else "None"}, '+ f'human_current_page URL={browser_session.human_current_page.url if browser_session.human_current_page else "None"}')# Tab management tests@pytest.mark.asyncio- async def test_open_tab_updates_both_references(self, browser_context, base_url):+ async def test_initial_values(self, browser_session, base_url):"""Test that open_tab correctly updates both tab references."""- # Ensure tab references are synchronized- await self._ensure_synchronized_state(browser_context, base_url)-- # Store initial tab count and references- session = await browser_context.get_session()- initial_tab_count = len(session.context.pages)- initial_agent_tab = browser_context.agent_current_page- # Open a new tab directly via BrowserContext- await browser_context.create_new_tab(f'{base_url}/page2')+ await self._reset_tab_state(browser_session, base_url)- # Give time for events to process- await asyncio.sleep(1)+ initial_tab = await browser_session.get_current_page()+ assert initial_tab.url == 'about:blank'+ assert browser_session.human_current_page == initial_tab+ assert browser_session.agent_current_page == initial_tab- # Verify a new tab was created- session = await browser_context.get_session()- assert len(session.context.pages) == initial_tab_count + 1+ for page in browser_session.browser_context.pages:+ await page.close()- # Both references should be set to the new tab and different from initial tab- assert browser_context.human_current_page is not None- assert browser_context.agent_current_page is not None- assert browser_context.human_current_page == browser_context.agent_current_page- assert initial_agent_tab != browser_context.agent_current_page- assert f'{base_url}/page2' in browser_context.agent_current_page.url+ # should never be none even after all pages are closed+ current_tab = await browser_session.get_current_page()+ assert current_tab is not None+ assert current_tab.url == 'about:blank'@pytest.mark.asyncio- async def test_switch_tab_updates_both_references(self, browser_context, base_url):- """Test that switch_tab updates both tab references."""- # Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context, base_url)-- # Create a new tab in addition to existing one- await browser_context.create_new_tab(f'{base_url}/page2')- await asyncio.sleep(1)-- # Verify we now have the second tab active- assert f'{base_url}/page2' in browser_context.agent_current_page.url-- # Switch to the first tab- session = await browser_context.get_session()- first_tab = session.context.pages[0]- await browser_context.switch_to_tab(0)- await asyncio.sleep(0.5)-- # Both references should point to the first tab- assert browser_context.human_current_page is not None- assert browser_context.agent_current_page is not None- assert browser_context.human_current_page == browser_context.agent_current_page- assert browser_context.agent_current_page == first_tab- assert f'{base_url}/page1' in browser_context.agent_current_page.url-- # Verify the underlying page is correct by checking we can interact with it- page = await browser_context.get_agent_current_page()- title = await page.title()- assert 'Test Page 1' in title+ async def test_agent_changes_tab(self, browser_session, base_url):+ """Test that agent_current_page changes and human_current_page remains the same when a new tab is opened."""++ initial_tab = await self._reset_tab_state(browser_session, base_url)+ assert initial_tab.url == 'about:blank'+ initial_tab_count = len(browser_session.tabs)+ assert initial_tab_count == 1++ # test opening a new tab+ new_tab = await browser_session.create_new_tab(f'{base_url}/page2')+ new_tab_count = len(browser_session.browser_context.pages)+ assert new_tab_count == len(browser_session.tabs) == 2++ # test agent open new tab updates agent focus + doesn't steal human focus+ assert browser_session.agent_current_page.url == new_tab.url == f'{base_url}/page2'+ assert browser_session.human_current_page.url == initial_tab.url == 'about:blank'++ # test agent navigation updates agent focus +doesn't steal human focus+ await browser_session.navigate(f'{base_url}/page3')+ assert browser_session.agent_current_page.url == f'{base_url}/page3' # agent should now be on the new tab+ assert (+ browser_session.human_current_page.url == initial_tab.url == 'about:blank'+ ) # human should still be on the very first tab@pytest.mark.asyncio- async def test_close_tab_handles_references_correctly(self, browser_context, base_url):- """Test that closing a tab updates references correctly."""- # Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context, base_url)-- # Create two tabs with different URLs- initial_tab = browser_context.agent_current_page- await browser_context.create_new_tab(f'{base_url}/page2')- await asyncio.sleep(1)-- # Verify the second tab is now active- assert f'{base_url}/page2' in browser_context.agent_current_page.url-- # Close the current tab- await browser_context.close_current_tab()- await asyncio.sleep(0.5)-- # Both references should be updated to the remaining available tab- assert browser_context.human_current_page is not None- assert browser_context.agent_current_page is not None- assert browser_context.human_current_page == browser_context.agent_current_page- assert browser_context.agent_current_page == initial_tab- assert not browser_context.human_current_page.is_closed()- assert f'{base_url}/page1' in browser_context.human_current_page.url+ async def test_human_changes_tab(self, browser_session, base_url):+ """Test that human_current_page changes and agent_current_page remains the same when a new tab is opened."""++ initial_tab = await self._reset_tab_state(browser_session, base_url)+ assert initial_tab.url == 'about:blank'++ # assert human opening new tab updates human focus + doesn't steal agent focus+ new_human_tab = await browser_session.browser_context.new_page()+ await new_human_tab.goto(f'{base_url}/page2')+ await self._simulate_human_tab_change(new_human_tab, browser_session)+ current_agent_page = await browser_session.get_current_page()+ assert current_agent_page.url == initial_tab.url == 'about:blank'+ assert browser_session.human_current_page.url == new_human_tab.url == f'{base_url}/page2'++ # test human navigating to new URL updates human focus + doesn't steal agent focus+ await new_human_tab.goto(f'{base_url}/page3')+ await self._simulate_human_tab_change(new_human_tab, browser_session)+ current_agent_page = await browser_session.get_current_page()+ assert current_agent_page.url == initial_tab.url == 'about:blank'+ assert browser_session.human_current_page.url == new_human_tab.url == f'{base_url}/page3'@pytest.mark.asyncio- async def test_user_changes_tab(self, browser_context, base_url):- """Test that agent_current_page is preserved when user changes the foreground tab."""- # Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context, base_url)-- # Create a second tab with a different URL- await browser_context.create_new_tab(f'{base_url}/page2')- await asyncio.sleep(1)- assert f'{base_url}/page2' in browser_context.agent_current_page.url-- # Switch back to the first tab for the agent- session = await browser_context.get_session()- first_tab = session.context.pages[0]- await browser_context.switch_to_tab(0)- await self._simulate_user_tab_change(first_tab, browser_context)- await asyncio.sleep(0.5)-- # Store agent's active tab- agent_tab = browser_context.agent_current_page- assert f'{base_url}/page1' in agent_tab.url-- # Simulate user switching to the second tab- session = await browser_context.get_session()- user_tab = session.context.pages[1] # Second tab-- # First, log the visibility listeners- listeners = await user_tab.evaluate("() => Object.keys(window).filter(k => k.startsWith('onVisibilityChange'))")- logger.debug(f'Tab visibility listeners: {listeners}')-- # Make sure handlers exist before attempting to trigger them- assert len(listeners) > 0, 'No visibility listeners found on the page'-- # Now try the simulation- await self._simulate_user_tab_change(user_tab, browser_context)-- # Verify agent_current_page remains unchanged while human_current_page changed- assert browser_context.agent_current_page == agent_tab- assert browser_context.human_current_page != browser_context.agent_current_page- assert f'{base_url}/page1' in browser_context.agent_current_page.url- assert f'{base_url}/page2' in browser_context.human_current_page.url-- @pytest.mark.asyncio- async def test_get_agent_current_page(self, browser_context, base_url):- """Test that get_agent_current_page returns agent_current_page regardless of human_current_page."""- # Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context, base_url)-- # Create a second tab with a different URL- await browser_context.create_new_tab(f'{base_url}/page2')- await asyncio.sleep(1)-- # Switch back to the first tab for the agent- await browser_context.switch_to_tab(0)- await asyncio.sleep(0.5)-- # Simulate user switching to the second tab- session = await browser_context.get_session()- user_tab = session.context.pages[1] # Second tab- await self._simulate_user_tab_change(user_tab, browser_context)+ async def test_switch_tab(self, browser_session, base_url):+ """Test that switch_tab updates both tab references."""- # Verify get_agent_current_page returns agent's tab, not foreground tab- agent_page = await browser_context.get_agent_current_page()- assert agent_page == browser_context.agent_current_page- assert f'{base_url}/page1' in agent_page.url+ # open a new tab for the human + agent to start on+ first_tab = await self._reset_tab_state(browser_session, base_url)+ await browser_session.navigate(f'{base_url}/page1')+ await self._simulate_human_tab_change(first_tab, browser_session)+ assert first_tab.url == f'{base_url}/page1'- # Call a method on the page to verify it's fully functional- title = await agent_page.title()- assert 'Test Page 1' in title+ # open a new tab that the agent will switch to automatically+ second_tab = await browser_session.create_new_tab(f'{base_url}/page2')+ current_tab = await browser_session.get_current_page()- @pytest.mark.asyncio- async def test_browser_operations_use_agent_current_page(self, browser_context, base_url):- """Test that browser operations use agent_current_page, not human_current_page."""- # Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context, base_url)+ # assert agent focus is on new tab and human focus is on first tab+ assert current_tab.url == second_tab.url == f'{base_url}/page2' == browser_session.agent_current_page.url+ assert browser_session.human_current_page.url == first_tab.url == f'{base_url}/page1'- # Create a second tab with a different URL- await browser_context.create_new_tab(f'{base_url}/page2')- await asyncio.sleep(1)-- # Switch back to the first tab for the agent- await browser_context.switch_to_tab(0)+ # Switch agent back to the first tab+ await browser_session.switch_tab(0)await asyncio.sleep(0.5)- # Simulate user switching to the second tab- session = await browser_context.get_session()- user_tab = session.context.pages[1] # Second tab- await self._simulate_user_tab_change(user_tab, browser_context)-- # Verify we have the setup we want- assert browser_context.human_current_page != browser_context.agent_current_page- assert f'{base_url}/page2' in browser_context.human_current_page.url- assert f'{base_url}/page1' in browser_context.agent_current_page.url+ # assert agent focus is on first tab and human focus is also first tab+ current_tab = await browser_session.get_current_page()+ assert current_tab.url == first_tab.url == f'{base_url}/page1' == browser_session.agent_current_page.url+ assert browser_session.human_current_page.url == first_tab.url == f'{base_url}/page1'- # Execute a navigation directly on agent's tab- agent_page = await browser_context.get_agent_current_page()- await agent_page.goto(f'{base_url}/page3')+ # round-trip, switch agent back to second tab+ await browser_session.switch_tab(1)await asyncio.sleep(0.5)- # Verify navigation happened on agent_current_page- assert f'{base_url}/page3' in browser_context.agent_current_page.url- # But human_current_page remains unchanged- assert f'{base_url}/page2' in browser_context.human_current_page.url+ # assert agent focus is back on second tab and human focus is still on first tab+ current_tab = await browser_session.get_current_page()+ assert current_tab.url == second_tab.url == f'{base_url}/page2' == browser_session.agent_current_page.url+ assert browser_session.human_current_page.url == first_tab.url == f'{base_url}/page1'@pytest.mark.asyncio- async def test_tab_reference_recovery(self, browser_context, base_url):- """Test recovery when a tab reference becomes invalid."""- # Ensure we start with at least one valid tab- await self._ensure_synchronized_state(browser_context, base_url)-- # Create a second tab so we have multiple- await browser_context.create_new_tab(f'{base_url}/page2')- await asyncio.sleep(1)-- # Deliberately corrupt the agent_current_page reference- browser_context.agent_current_page = None-- # Call get_agent_current_page, which should recover the reference- agent_page = await browser_context.get_agent_current_page()-- # Verify recovery worked- assert agent_page is not None- assert not agent_page.is_closed()-- # Verify the tab is fully functional- title = await agent_page.title()- assert title, 'Page should have a title'-- # Verify both references are now valid again- assert browser_context.agent_current_page is not None- assert browser_context.human_current_page is not None-- @pytest.mark.asyncio- async def test_reconcile_tab_state_handles_both_invalid(self, browser_context, base_url):- """Test that reconcile_tab_state can recover when both tab references are invalid."""- # Ensure we start with at least one valid tab- await self._ensure_synchronized_state(browser_context, base_url)-- # Corrupt both references- browser_context.agent_current_page = None- browser_context.human_current_page = None-- # Call reconcile_tab_state directly- await browser_context._reconcile_tab_state()-- # Verify both references are restored- assert browser_context.agent_current_page is not None- assert browser_context.human_current_page is not None- # and they are the same tab- assert browser_context.agent_current_page == browser_context.human_current_page- # and the tab is valid- assert not browser_context.agent_current_page.is_closed()-- @pytest.mark.asyncio- async def test_race_condition_resilience(self, browser_context, base_url):- """Test resilience against race conditions in tab operations."""- # Ensure we start with at least one valid tab- await self._ensure_synchronized_state(browser_context, base_url)-- # Create two more tabs to have three in total- await browser_context.create_new_tab(f'{base_url}/page2')- await asyncio.sleep(0.5)- await browser_context.create_new_tab(f'{base_url}/page3')- await asyncio.sleep(0.5)-- # Verify we have at least 3 tabs- session = await browser_context.get_session()- assert len(session.context.pages) >= 3-- # Perform a series of rapid tab switches to simulate race conditions- for i in range(5):- tab_index = i % 3- await browser_context.switch_to_tab(tab_index)- await asyncio.sleep(0.1) # Very short delay between switches-- # Verify the state is consistent after rapid operations- assert browser_context.human_current_page is not None- assert browser_context.agent_current_page is not None- assert browser_context.human_current_page == browser_context.agent_current_page- assert not browser_context.human_current_page.is_closed()-- # Verify we can still navigate on the final tab- page = await browser_context.get_agent_current_page()- await page.goto(f'{base_url}/page4')- assert f'{base_url}/page4' in page.url-- @pytest.mark.asyncio- async def test_tab_management_using_controller_actions(self, browser_context, controller, base_url):- """- Test tab management using Controller actions instead of directly calling browser_context methods,- ensuring that both human and agent tab detection works correctly.- """- # Ensure we start with at least one tab- await self._ensure_synchronized_state(browser_context, base_url)-- # Make sure we have a clean single tab to start with- session = await browser_context.get_session()- while len(session.context.pages) > 1:- await browser_context.close_current_tab()- await asyncio.sleep(0.5)-- # Store the initial tab for reference- initial_tab = browser_context.agent_current_page- initial_tab_id = initial_tab.page_id if hasattr(initial_tab, 'page_id') else 0-- # Define action models for tab operations- class OpenTabActionModel(ActionModel):- open_tab: OpenTabAction | None = None-- class SwitchTabActionModel(ActionModel):- switch_tab: SwitchTabAction | None = None-- class GoToUrlActionModel(ActionModel):- go_to_url: GoToUrlAction | None = None-- class CloseTabActionModel(ActionModel):- close_tab: CloseTabAction | None = None-- # Create second tab with OpenTabAction- open_tab_action = {'open_tab': OpenTabAction(url=f'{base_url}/page2')}- await controller.act(OpenTabActionModel(**open_tab_action), browser_context)- await asyncio.sleep(1) # Wait for the tab to fully initialize-- # Verify the second tab is opened and active for both agent and human- second_tab = browser_context.agent_current_page- assert browser_context.human_current_page == browser_context.agent_current_page- assert f'{base_url}/page2' in browser_context.agent_current_page.url- second_tab_id = second_tab.page_id if hasattr(second_tab, 'page_id') else 1-- # Create third tab with OpenTabAction- open_tab_action2 = {'open_tab': OpenTabAction(url=f'{base_url}/page3')}- await controller.act(OpenTabActionModel(**open_tab_action2), browser_context)- await asyncio.sleep(1) # Wait for the tab to fully initialize+ async def test_close_tab(self, browser_session, base_url):+ """Test that closing a tab updates references correctly."""- # Verify the third tab is opened and active- third_tab = browser_context.agent_current_page- assert browser_context.human_current_page == browser_context.agent_current_page- assert f'{base_url}/page3' in browser_context.agent_current_page.url- third_tab_id = third_tab.page_id if hasattr(third_tab, 'page_id') else 2+ initial_tab = await self._reset_tab_state(browser_session, base_url)+ await browser_session.navigate(f'{base_url}/page1')+ assert initial_tab.url == f'{base_url}/page1'- # Use SwitchTabAction to go back to the first tab (for the agent)- switch_tab_action = {'switch_tab': SwitchTabAction(page_id=initial_tab_id)}- await controller.act(SwitchTabActionModel(**switch_tab_action), browser_context)- await asyncio.sleep(0.5)+ # Create two tabs with different URLs+ second_tab = await browser_session.create_new_tab(f'{base_url}/page2')- # Verify agent is now on the first tab- assert browser_context.agent_current_page == initial_tab- assert f'{base_url}/page1' in browser_context.agent_current_page.url- assert browser_context.human_current_page == browser_context.agent_current_page+ # Verify the second tab is now active+ current_page = await browser_session.get_current_page()+ assert current_page.url == second_tab.url == f'{base_url}/page2'- # Simulate human switching to the second tab- await self._simulate_user_tab_change(second_tab, browser_context)+ # Close the second tab+ await browser_session.close_tab()await asyncio.sleep(0.5)- # Verify human and agent are on different tabs- assert browser_context.human_current_page == second_tab- assert browser_context.agent_current_page == initial_tab- assert browser_context.human_current_page != browser_context.agent_current_page- assert f'{base_url}/page2' in browser_context.human_current_page.url- assert f'{base_url}/page1' in browser_context.agent_current_page.url+ # Both references should be auto-updated to the first available tab+ assert browser_session.human_current_page.url == initial_tab.url == f'{base_url}/page1'+ assert browser_session.agent_current_page.url == initial_tab.url == f'{base_url}/page1'+ assert not browser_session.human_current_page.is_closed()+ assert not browser_session.agent_current_page.is_closed()- # Use GoToUrlAction to navigate the agent's tab to a new URL- goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/page4')}- await controller.act(GoToUrlActionModel(**goto_action), browser_context)+ # close the only remaining tab+ await browser_session.close_tab()await asyncio.sleep(0.5)- # Refresh the agent's page reference and verify navigation- agent_page = await browser_context.get_agent_current_page()- assert agent_page is not None- assert f'{base_url}/page4' in agent_page.url-- # Verify human's tab remains unchanged- assert f'{base_url}/page2' in browser_context.human_current_page.url-- # Use CloseTabAction to close the third tab- close_tab_action = {'close_tab': CloseTabAction(page_id=third_tab_id)}- await controller.act(CloseTabActionModel(**close_tab_action), browser_context)- await asyncio.sleep(1.0) # Extended wait to ensure tab cleanup-- # Verify tab was closed- session = await browser_context.get_session()- assert len(session.context.pages) == 2-- # Close the second tab, which is the human's current tab- close_tab_action2 = {'close_tab': CloseTabAction(page_id=second_tab_id)}- await controller.act(CloseTabActionModel(**close_tab_action2), browser_context)- await asyncio.sleep(1.0) # Extended wait to ensure tab cleanup-- # Verify we have only one tab left- session = await browser_context.get_session()- assert len(session.context.pages) == 1-- # Refresh references and verify both human and agent point to the same tab- await browser_context._reconcile_tab_state()- assert browser_context.human_current_page is not None- assert browser_context.agent_current_page is not None- assert browser_context.human_current_page == browser_context.agent_current_page-- # Verify the URL of the remaining tab- final_page = await browser_context.get_current_page()- assert f'{base_url}' in final_page.url+ # close_tab should have called get_current_page, which creates a new about:blank tab if none are left+ assert browser_session.human_current_page.url == 'about:blank'+ assert browser_session.agent_current_page.url == 'about:blank'diff --git a/tests/test_url_allowlist_security.py b/tests/test_url_allowlist_security.pyindex 02f988b89..70e1146b9 100644--- a/tests/test_url_allowlist_security.py+++ b/tests/test_url_allowlist_security.py@@ -1,4 +1,4 @@-from browser_use.browser.context import BrowserContext, BrowserContextConfig+from browser_use.browser import BrowserProfile, BrowserSessionclass TestUrlAllowlistSecurity:@@ -7,85 +7,85 @@ class TestUrlAllowlistSecurity:def test_authentication_bypass_prevention(self):"""Test that the URL allowlist cannot be bypassed using authentication credentials."""# Create a context config with a sample allowed domain- config = BrowserContextConfig(allowed_domains=['example.com'])- context = BrowserContext(browser=None, config=config)+ browser_profile = BrowserProfile(allowed_domains=['example.com'])+ browser_session = BrowserSession(browser_profile=browser_profile)# Security vulnerability test cases# These should all be detected as malicious despite containing "example.com"- assert context._is_url_allowed('https://example.com:[email protected]') is False- assert context._is_url_allowed('https://[email protected]') is False- assert context._is_url_allowed('https://example.com%[email protected]') is False- assert context._is_url_allowed('https://example.com%[email protected]') is False+ assert browser_session._is_url_allowed('https://example.com:[email protected]') is False+ assert browser_session._is_url_allowed('https://[email protected]') is False+ assert browser_session._is_url_allowed('https://example.com%[email protected]') is False+ assert browser_session._is_url_allowed('https://example.com%[email protected]') is False# Make sure legitimate auth credentials still work- assert context._is_url_allowed('https://user:[email protected]') is True+ assert browser_session._is_url_allowed('https://user:[email protected]') is Truedef test_glob_pattern_matching(self):"""Test that glob patterns in allowed_domains work correctly."""# Test *.example.com pattern (should match subdomains and main domain)- glob_config = BrowserContextConfig(allowed_domains=['*.example.com'])- glob_context = BrowserContext(browser=None, config=glob_config)+ browser_profile = BrowserProfile(allowed_domains=['*.example.com'])+ browser_session = BrowserSession(browser_profile=browser_profile)# Should match subdomains- assert glob_context._is_url_allowed('https://sub.example.com') is True- assert glob_context._is_url_allowed('https://deep.sub.example.com') is True+ assert browser_session._is_url_allowed('https://sub.example.com') is True+ assert browser_session._is_url_allowed('https://deep.sub.example.com') is True# Should also match main domain- assert glob_context._is_url_allowed('https://example.com') is True+ assert browser_session._is_url_allowed('https://example.com') is True# Should not match other domains- assert glob_context._is_url_allowed('https://notexample.com') is False- assert glob_context._is_url_allowed('https://example.org') is False+ assert browser_session._is_url_allowed('https://notexample.com') is False+ assert browser_session._is_url_allowed('https://example.org') is False# Test more complex glob patterns- stars_config = BrowserContextConfig(allowed_domains=['*google.com', 'wiki*'])- stars_context = BrowserContext(browser=None, config=stars_config)+ browser_profile = BrowserProfile(allowed_domains=['*google.com', 'wiki*'])+ browser_session = BrowserSession(browser_profile=browser_profile)# Should match domains ending with google.com- assert stars_context._is_url_allowed('https://google.com') is True- assert stars_context._is_url_allowed('https://www.google.com') is True- assert stars_context._is_url_allowed('https://anygoogle.com') is True+ assert browser_session._is_url_allowed('https://google.com') is True+ assert browser_session._is_url_allowed('https://www.google.com') is True+ assert browser_session._is_url_allowed('https://anygoogle.com') is True# Should match domains starting with wiki- assert stars_context._is_url_allowed('https://wiki.org') is True- assert stars_context._is_url_allowed('https://wikipedia.org') is True+ assert browser_session._is_url_allowed('https://wiki.org') is True+ assert browser_session._is_url_allowed('https://wikipedia.org') is True# Should not match other domains- assert stars_context._is_url_allowed('https://example.com') is False+ assert browser_session._is_url_allowed('https://example.com') is False# Test browser internal URLs- assert stars_context._is_url_allowed('chrome://settings') is True- assert stars_context._is_url_allowed('about:blank') is True+ assert browser_session._is_url_allowed('chrome://settings') is True+ assert browser_session._is_url_allowed('about:blank') is True# Test security for glob patterns (authentication credentials bypass attempts)# These should all be detected as malicious despite containing allowed domain patterns- assert glob_context._is_url_allowed('https://allowed.example.com:[email protected]') is False- assert glob_context._is_url_allowed('https://[email protected]') is False- assert glob_context._is_url_allowed('https://sub.example.com%[email protected]') is False- assert stars_context._is_url_allowed('https://[email protected]') is False+ assert browser_session._is_url_allowed('https://allowed.example.com:[email protected]') is False+ assert browser_session._is_url_allowed('https://[email protected]') is False+ assert browser_session._is_url_allowed('https://sub.example.com%[email protected]') is False+ assert browser_session._is_url_allowed('https://[email protected]') is Falsedef test_glob_pattern_edge_cases(self):"""Test edge cases for glob pattern matching to ensure proper behavior."""# Test with domains containing glob pattern in the middle- stars_config = BrowserContextConfig(allowed_domains=['*google.com', 'wiki*'])- stars_context = BrowserContext(browser=None, config=stars_config)+ browser_profile = BrowserProfile(allowed_domains=['*google.com', 'wiki*'])+ browser_session = BrowserSession(browser_profile=browser_profile)# Verify that 'wiki*' pattern doesn't match domains that merely contain 'wiki' in the middle- assert stars_context._is_url_allowed('https://notawiki.com') is False- assert stars_context._is_url_allowed('https://havewikipages.org') is False- assert stars_context._is_url_allowed('https://my-wiki-site.com') is False+ assert browser_session._is_url_allowed('https://notawiki.com') is False+ assert browser_session._is_url_allowed('https://havewikipages.org') is False+ assert browser_session._is_url_allowed('https://my-wiki-site.com') is False# Verify that '*google.com' doesn't match domains that have 'google' in the middle- assert stars_context._is_url_allowed('https://mygoogle.company.com') is False+ assert browser_session._is_url_allowed('https://mygoogle.company.com') is False# Create context with potentially risky glob pattern that demonstrates security concerns- risky_config = BrowserContextConfig(allowed_domains=['*.google.*'])- risky_context = BrowserContext(browser=None, config=risky_config)+ browser_profile = BrowserProfile(allowed_domains=['*.google.*'])+ browser_session = BrowserSession(browser_profile=browser_profile)# Should match legitimate Google domains- assert risky_context._is_url_allowed('https://www.google.com') is True- assert risky_context._is_url_allowed('https://mail.google.co.uk') is True+ assert browser_session._is_url_allowed('https://www.google.com') is True+ assert browser_session._is_url_allowed('https://mail.google.co.uk') is True# But could also match potentially malicious domains with a subdomain structure# This demonstrates why such wildcard patterns can be risky- assert risky_context._is_url_allowed('https://www.google.evil.com') is True+ assert browser_session._is_url_allowed('https://www.google.evil.com') is True