Skip to content

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

add new tests

Nick Sweeting35b9d754da51
diff --git a/tests/ci/test_browser_session_ownership.py b/tests/ci/test_browser_session_ownership.py
new file mode 100644
index 000000000..b4123962a
--- /dev/null
+++ b/tests/ci/test_browser_session_ownership.py
@@ -0,0 +1,209 @@
+"""
+Test browser resource ownership when BrowserSession is copied.
+"""
+
+import asyncio
+import gc
+
+from browser_use import Agent, BrowserProfile, BrowserSession
+from tests.ci.conftest import create_mock_llm
+
+
+class TestBrowserOwnership:
+ """Test that browser resource ownership is properly managed when sessions are copied."""
+
+ async def test_copied_session_doesnt_own_browser(self):
+ """Test that copied BrowserSession instances don't own the browser resources."""
+ # Create original browser session
+ original = BrowserSession(
+ browser_profile=BrowserProfile(
+ headless=True,
+ keep_alive=False, # Should still work even with keep_alive=False
+ user_data_dir=None,
+ )
+ )
+
+ # Verify original owns the browser
+ assert original._owns_browser_resources is True
+
+ # Create a copy
+ copy1 = original.model_copy()
+
+ # Verify copy doesn't own the browser
+ assert copy1._owns_browser_resources is False
+ assert copy1._original_browser_session is original
+
+ # Create another copy
+ copy2 = original.model_copy()
+ assert copy2._owns_browser_resources is False
+ assert copy2._original_browser_session is original
+
+ async def test_agent_copies_dont_kill_browser(self, httpserver):
+ """Test that when agents copy a browser session, they don't kill the browser when garbage collected."""
+ # Set up test page
+ httpserver.expect_request('/test').respond_with_data(
+ '<html><body><h1>Test Page</h1><button>Click me</button></body></html>'
+ )
+
+ # Create original browser session with keep_alive=False
+ original_session = BrowserSession(
+ browser_profile=BrowserProfile(
+ headless=True,
+ keep_alive=False, # Browser should be killed when owner is GC'd
+ user_data_dir=None,
+ )
+ )
+ await original_session.start()
+ initial_browser_pid = original_session.browser_pid
+ assert initial_browser_pid is not None
+
+ # Create first agent that will copy the session
+ async def run_agent1():
+ agent1 = Agent(
+ task='Navigate to test page',
+ llm=create_mock_llm(
+ [
+ f'''{{
+ "thinking": "Navigating to test page",
+ "evaluation_previous_goal": "Starting task",
+ "memory": "Need to navigate",
+ "next_goal": "Navigate to test page",
+ "action": [
+ {{
+ "go_to_url": {{
+ "url": "{httpserver.url_for('/test')}"
+ }}
+ }}
+ ]
+ }}'''
+ ]
+ ),
+ browser_session=original_session,
+ )
+ await agent1.run(max_steps=1)
+ # agent1's copied session should have owns_browser=False
+ assert agent1.browser_session is not None
+ assert agent1.browser_session._owns_browser_resources is False
+ assert agent1.browser_session._original_browser_session is original_session
+ # Browser should still be running
+ assert original_session.browser_pid == initial_browser_pid
+
+ await run_agent1()
+
+ # Force garbage collection to ensure agent1's copy is cleaned up
+ gc.collect()
+ await asyncio.sleep(0.1)
+
+ # Browser should still be alive because the copy didn't own it
+ assert await original_session.is_connected()
+ assert original_session.browser_pid == initial_browser_pid
+
+ # Create second agent
+ async def run_agent2():
+ agent2 = Agent(
+ task='Click the button',
+ llm=create_mock_llm(
+ [
+ """{
+ "thinking": "Clicking button",
+ "evaluation_previous_goal": "On test page",
+ "memory": "Need to click button",
+ "next_goal": "Click button",
+ "action": [
+ {
+ "click_element_by_index": {
+ "index": 0
+ }
+ }
+ ]
+ }"""
+ ]
+ ),
+ browser_session=original_session,
+ )
+ await agent2.run(max_steps=1)
+ assert agent2.browser_session is not None
+ assert agent2.browser_session._owns_browser_resources is False
+
+ await run_agent2()
+
+ # Force garbage collection again
+ gc.collect()
+ await asyncio.sleep(0.1)
+
+ # Browser should still be alive
+ assert await original_session.is_connected()
+ assert original_session.browser_pid == initial_browser_pid
+
+ # Now clean up the original - this should kill the browser
+ await original_session.stop()
+
+ # Browser should be disconnected now
+ assert not await original_session.is_connected()
+
+ async def test_shared_browser_recovery_after_disconnect(self, httpserver):
+ """Test that copied sessions can recover if the shared browser is disconnected."""
+ # Set up test page
+ httpserver.expect_request('/test').respond_with_data('<html><body><h1>Recovery Test</h1></body></html>')
+
+ # Create original browser session
+ original_session = BrowserSession(
+ browser_profile=BrowserProfile(
+ headless=True,
+ keep_alive=True, # Keep alive for sharing
+ user_data_dir=None,
+ )
+ )
+ await original_session.start()
+
+ # Create a copy (simulating what Agent does)
+ copied_session = original_session.model_copy()
+ copied_session.playwright = original_session.playwright
+ copied_session.browser = original_session.browser
+ copied_session.browser_context = original_session.browser_context
+ copied_session.agent_current_page = original_session.agent_current_page
+
+ # Verify copy doesn't own the browser
+ assert copied_session._owns_browser_resources is False
+
+ # Navigate using the copy
+ await copied_session.create_new_tab(httpserver.url_for('/test'))
+
+ # Force disconnect the browser context
+ assert original_session.browser_context is not None
+ await original_session.browser_context.close()
+
+ # Try to use the copy - it should recover
+ await copied_session.start() # Should reconnect
+ screenshot = await copied_session.take_screenshot()
+ assert screenshot is not None
+ assert len(screenshot) > 0
+
+ # Clean up
+ await original_session.kill()
+
+ async def test_multiple_copies_single_owner(self):
+ """Test that multiple copies all reference the same original owner."""
+ original = BrowserSession(
+ browser_profile=BrowserProfile(
+ headless=True,
+ user_data_dir=None,
+ )
+ )
+
+ # Create multiple copies
+ copies = []
+ for i in range(5):
+ copy = original.model_copy()
+ copies.append(copy)
+
+ # Verify each copy doesn't own the browser
+ assert copy._owns_browser_resources is False
+ assert copy._original_browser_session is original
+
+ # All copies should reference the same original
+ for copy in copies:
+ assert copy._original_browser_session is original
+
+ # Only the original owns the browser
+ assert original._owns_browser_resources is True
diff --git a/tests/ci/test_browser_session_reuse.py b/tests/ci/test_browser_session_reuse.py
new file mode 100644
index 000000000..0d47194b9
--- /dev/null
+++ b/tests/ci/test_browser_session_reuse.py
@@ -0,0 +1,155 @@
+"""
+Test browser session reuse and regeneration after browser disconnection.
+
+Tests cover:
+- Browser regeneration after context is closed
+- Screenshot functionality after regeneration
+- Multiple regeneration cycles
+"""
+
+import asyncio
+
+from browser_use.browser.profile import BrowserProfile
+from browser_use.browser.session import BrowserSession
+
+
+class TestBrowserSessionReuse:
+ """Tests for browser session reuse and regeneration after disconnection."""
+
+ async def test_browser_regeneration_after_disconnect(self):
+ """Test that browser regenerates and screenshot succeeds after disconnection"""
+ session = BrowserSession(browser_profile=BrowserProfile(headless=True, user_data_dir=None))
+
+ try:
+ # Start browser session
+ await session.start()
+
+ # Navigate to a test page
+ assert session.agent_current_page is not None
+ await session.agent_current_page.goto('data:text/html,<h1>Test Page - Before Disconnect</h1>')
+
+ # Take a screenshot before disconnection
+ screenshot1 = await session.take_screenshot()
+ assert screenshot1 is not None
+ assert len(screenshot1) > 0
+
+ # Store initial browser PID
+ initial_browser_pid = session.browser_pid
+ assert initial_browser_pid is not None
+
+ # Force disconnect the browser by closing the browser context
+ assert session.browser_context is not None
+ await session.browser_context.close()
+
+ # Try to take a screenshot - this should trigger regeneration internally
+ # Thanks to the @require_initialization decorator and our fix, this should succeed
+ screenshot2 = await session.take_screenshot()
+ assert screenshot2 is not None
+ assert len(screenshot2) > 0
+
+ # Check if browser was regenerated (new browser context created)
+ assert session.browser_context is not None
+ # Verify the context is valid by checking if we can access its pages
+ assert session.browser_context.pages is not None
+
+ # Verify we can still interact with the browser
+ assert session.agent_current_page is not None
+ await session.agent_current_page.goto('data:text/html,<h1>Test Page - After Regeneration</h1>')
+ screenshot3 = await session.take_screenshot()
+ assert screenshot3 is not None
+ assert len(screenshot3) > 0
+
+ finally:
+ await session.stop()
+
+ async def test_multiple_browser_regenerations(self):
+ """Test multiple browser regeneration cycles"""
+ session = BrowserSession(browser_profile=BrowserProfile(headless=True, user_data_dir=None))
+
+ try:
+ await session.start()
+
+ for i in range(3):
+ # Navigate to a test page
+ assert session.agent_current_page is not None
+ await session.agent_current_page.goto(f'data:text/html,<h1>Cycle {i + 1}</h1>')
+
+ # Take screenshot before disconnect
+ screenshot_before = await session.take_screenshot()
+ assert screenshot_before is not None
+ assert len(screenshot_before) > 0
+
+ # Force disconnect
+ if session.browser_context:
+ await session.browser_context.close()
+
+ # Force a small delay to ensure disconnection is processed
+ await asyncio.sleep(0.1)
+
+ # Reset the connection state to ensure the closed context is cleared
+ session._reset_connection_state()
+
+ # Manually restart for the next iteration
+ await session.start()
+
+ # Take screenshot after regeneration
+ screenshot_after = await session.take_screenshot()
+ assert screenshot_after is not None
+ assert len(screenshot_after) > 0
+
+ finally:
+ await session.stop()
+
+ async def test_browser_session_reuse_with_retry_decorator(self):
+ """Test that the retry decorator properly handles browser regeneration"""
+ session = BrowserSession(browser_profile=BrowserProfile(headless=True, user_data_dir=None))
+
+ try:
+ await session.start()
+
+ # Navigate to a test page
+ assert session.agent_current_page is not None
+ await session.agent_current_page.goto('data:text/html,<h1>Test Retry Decorator</h1>')
+
+ # Take a screenshot to verify it works
+ screenshot1 = await session.take_screenshot()
+ assert screenshot1 is not None
+
+ # Store browser PID
+ initial_pid = session.browser_pid
+
+ # Close the browser context while a screenshot is in progress
+ # This simulates a browser crash during CDP operation
+ async def close_during_operation():
+ await asyncio.sleep(0.05) # Small delay to let CDP operation start
+ if session.browser_context:
+ try:
+ await session.browser_context.close()
+ except Exception:
+ # Context might already be closed
+ pass
+
+ # Start the close task
+ close_task = asyncio.create_task(close_during_operation())
+
+ # Try to take a screenshot - the retry decorator should handle the failure
+ # Note: This might succeed if the screenshot completes before the close
+ try:
+ screenshot2 = await session.take_screenshot()
+ # If it succeeded, the browser should have been regenerated
+ assert screenshot2 is not None
+ except Exception:
+ # If it failed, that's also OK - the browser state was reset
+ pass
+
+ # Wait for close task to complete
+ await close_task
+
+ # Verify we can still use the browser after regeneration
+ await session.start() # Ensure browser is started
+ screenshot3 = await session.take_screenshot()
+ assert screenshot3 is not None
+ assert len(screenshot3) > 0
+
+ finally:
+ await session.stop()
diff --git a/tests/ci/test_semaphores.py b/tests/ci/test_semaphores.py
new file mode 100644
index 000000000..6b005b7b6
--- /dev/null
+++ b/tests/ci/test_semaphores.py
@@ -0,0 +1,493 @@
+"""
+Test semaphore functionality, especially multiprocess semaphores.
+"""
+
+import asyncio
+import multiprocessing
+import os
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+# Add the browser-use directory to the path so we can import from it
+sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+from browser_use.utils import retry
+
+
+def worker_acquire_semaphore(
+ worker_id: int,
+ start_time: float,
+ results_queue: multiprocessing.Queue,
+ hold_time: float = 0.5,
+ timeout: float = 5.0,
+ should_release: bool = True,
+):
+ """Worker process that tries to acquire a semaphore."""
+ try:
+ print(f'Worker {worker_id} starting...')
+
+ # Define a function decorated with multiprocess semaphore
+ @retry(
+ retries=0,
+ timeout=10,
+ semaphore_limit=3, # Only 3 concurrent processes allowed
+ semaphore_name='test_multiprocess_sem',
+ semaphore_scope='multiprocess',
+ semaphore_timeout=timeout,
+ semaphore_lax=False, # Strict mode - must acquire semaphore
+ )
+ async def semaphore_protected_function():
+ acquire_time = time.time() - start_time
+ results_queue.put(('acquired', worker_id, acquire_time))
+
+ # Hold the semaphore for a bit
+ await asyncio.sleep(hold_time)
+
+ release_time = time.time() - start_time
+ results_queue.put(('released', worker_id, release_time))
+ return f'Worker {worker_id} completed'
+
+ # Run the async function
+ print(f'Worker {worker_id} running async function...')
+ result = asyncio.run(semaphore_protected_function())
+ print(f'Worker {worker_id} completed with result: {result}')
+ results_queue.put(('completed', worker_id, result))
+
+ except TimeoutError as e:
+ timeout_time = time.time() - start_time
+ print(f'Worker {worker_id} timed out: {e}')
+ results_queue.put(('timeout', worker_id, timeout_time, str(e)))
+ except Exception as e:
+ error_time = time.time() - start_time
+ print(f'Worker {worker_id} error: {type(e).__name__}: {e}')
+ import traceback
+
+ traceback.print_exc()
+ results_queue.put(('error', worker_id, error_time, str(e)))
+
+
+def worker_that_dies(
+ worker_id: int,
+ start_time: float,
+ results_queue: multiprocessing.Queue,
+ die_after: float = 0.2,
+):
+ """Worker process that acquires semaphore then dies without releasing."""
+ try:
+
+ @retry(
+ retries=0,
+ timeout=10,
+ semaphore_limit=2, # Only 2 concurrent processes
+ semaphore_name='test_death_sem',
+ semaphore_scope='multiprocess',
+ semaphore_timeout=5.0,
+ semaphore_lax=False,
+ )
+ async def semaphore_protected_function():
+ acquire_time = time.time() - start_time
+ results_queue.put(('acquired', worker_id, acquire_time))
+
+ # Hold for a bit then simulate crash
+ await asyncio.sleep(die_after)
+
+ # Simulate unexpected death
+ os._exit(1) # Hard exit without cleanup
+
+ asyncio.run(semaphore_protected_function())
+
+ except Exception as e:
+ error_time = time.time() - start_time
+ results_queue.put(('error', worker_id, error_time, str(e)))
+
+
+def worker_death_test_normal(
+ worker_id: int,
+ start_time: float,
+ results_queue: multiprocessing.Queue,
+):
+ """Worker for death test that uses the same semaphore."""
+
+ @retry(
+ retries=0,
+ timeout=10,
+ semaphore_limit=2,
+ semaphore_name='test_death_sem',
+ semaphore_scope='multiprocess',
+ semaphore_timeout=5.0,
+ semaphore_lax=False,
+ )
+ async def semaphore_protected_function():
+ acquire_time = time.time() - start_time
+ results_queue.put(('acquired', worker_id, acquire_time))
+ await asyncio.sleep(0.2)
+ release_time = time.time() - start_time
+ results_queue.put(('released', worker_id, release_time))
+ return f'Worker {worker_id} completed'
+
+ try:
+ result = asyncio.run(semaphore_protected_function())
+ results_queue.put(('completed', worker_id, result))
+ except Exception as e:
+ error_time = time.time() - start_time
+ results_queue.put(('error', worker_id, error_time, str(e)))
+
+
+class TestMultiprocessSemaphore:
+ """Test multiprocess semaphore functionality."""
+
+ def test_basic_multiprocess_semaphore(self):
+ """Test that semaphore limits work across processes."""
+ results_queue = multiprocessing.Queue()
+ start_time = time.time()
+ processes = []
+
+ # Start 6 worker processes (semaphore limit is 3)
+ for i in range(6):
+ p = multiprocessing.Process(target=worker_acquire_semaphore, args=(i, start_time, results_queue, 0.5, 5.0))
+ p.start()
+ processes.append(p)
+ time.sleep(0.05) # Small delay to ensure processes start in order
+
+ # Wait for all processes to complete
+ for p in processes:
+ p.join(timeout=10)
+
+ # Collect results
+ results = []
+ while not results_queue.empty():
+ results.append(results_queue.get())
+
+ # Analyze results
+ acquired_events = [r for r in results if r[0] == 'acquired']
+ released_events = [r for r in results if r[0] == 'released']
+ completed_events = [r for r in results if r[0] == 'completed']
+
+ # All 6 workers should complete successfully
+ assert len(completed_events) == 6, f'Expected 6 completions, got {len(completed_events)}'
+
+ # Sort by acquisition time
+ acquired_events.sort(key=lambda x: x[2])
+
+ # Extract worker IDs in order of acquisition
+ acquisition_order = [event[1] for event in acquired_events]
+
+ # Since we have a semaphore limit of 3:
+ # The first 3 to acquire should be from workers 0, 1, 2 (started first)
+ first_three = set(acquisition_order[:3])
+ assert first_three == {0, 1, 2}, f'First 3 acquisitions should be workers 0, 1, 2, got {first_three}'
+
+ # The next 3 should be from workers 3, 4, 5 (started later)
+ last_three = set(acquisition_order[3:])
+ assert last_three == {3, 4, 5}, f'Last 3 acquisitions should be workers 3, 4, 5, got {last_three}'
+
+ # First 3 should acquire quickly (within 1.5s accounting for process startup and Python import overhead)
+ for i in range(3):
+ assert acquired_events[i][2] < 1.5, (
+ f'Worker {acquired_events[i][1]} should acquire quickly, took {acquired_events[i][2]:.2f}s'
+ )
+
+ # Next 3 should wait longer (should take > 0.4s to acquire due to 0.5s hold time)
+ for i in range(3, 6):
+ assert acquired_events[i][2] > 0.4, (
+ f'Worker {acquired_events[i][1]} should wait for semaphore, took {acquired_events[i][2]:.2f}s'
+ )
+
+ def test_semaphore_timeout(self):
+ """Test that semaphore timeout works correctly."""
+ results_queue = multiprocessing.Queue()
+ start_time = time.time()
+ processes = []
+
+ # Start 4 workers with short timeout (semaphore limit is 3)
+ for i in range(4):
+ p = multiprocessing.Process(
+ target=worker_acquire_semaphore,
+ args=(i, start_time, results_queue, 2.0, 0.5), # 2s hold, 0.5s timeout
+ )
+ p.start()
+ processes.append(p)
+
+ # Wait for processes
+ for p in processes:
+ p.join(timeout=5)
+
+ # Collect results
+ results = []
+ while not results_queue.empty():
+ results.append(results_queue.get())
+
+ # Check that we have timeout events
+ timeout_events = [r for r in results if r[0] == 'timeout']
+ completed_events = [r for r in results if r[0] == 'completed']
+
+ # 3 should complete, 1 should timeout
+ assert len(completed_events) == 3, f'Expected 3 completions, got {len(completed_events)}'
+ assert len(timeout_events) == 1, f'Expected 1 timeout, got {len(timeout_events)}'
+
+ # Timeout should occur relatively quickly (< 2s)
+ assert timeout_events[0][2] < 2.0, f'Timeout should occur within ~0.5s, took {timeout_events[0][2]:.2f}s'
+
+ def test_process_death_releases_semaphore(self):
+ """Test that killing a process releases its semaphore slot."""
+ results_queue = multiprocessing.Queue()
+ start_time = time.time()
+
+ # Start 2 processes that will die (limit is 2)
+ death_processes = []
+ for i in range(2):
+ p = multiprocessing.Process(target=worker_that_dies, args=(i, start_time, results_queue, 0.3))
+ p.start()
+ death_processes.append(p)
+
+ # Wait a bit for them to acquire
+ time.sleep(0.5)
+
+ # Now start 2 more processes that should be able to acquire after the first 2 die
+ normal_processes = []
+ for i in range(2, 4):
+ p = multiprocessing.Process(target=worker_death_test_normal, args=(i, start_time, results_queue))
+ p.start()
+ normal_processes.append(p)
+
+ # Wait for death processes to exit
+ for p in death_processes:
+ p.join(timeout=2)
+ assert p.exitcode == 1, f'Process should have exited with code 1, got {p.exitcode}'
+
+ # Wait for normal processes
+ for p in normal_processes:
+ p.join(timeout=10)
+ assert p.exitcode == 0, 'Process should complete successfully'
+
+ # Collect results
+ results = []
+ while not results_queue.empty():
+ results.append(results_queue.get())
+
+ # Check that processes 2 and 3 were able to acquire
+ acquired_events = [r for r in results if r[0] == 'acquired']
+ completed_events = [r for r in results if r[0] == 'completed' and r[1] >= 2]
+
+ # Should have 4 acquisitions total (2 that died + 2 that completed)
+ assert len(acquired_events) >= 4, f'Expected at least 4 acquisitions, got {len(acquired_events)}'
+
+ # Processes 2 and 3 should complete
+ assert len(completed_events) == 2, f'Expected 2 completions from workers 2-3, got {len(completed_events)}'
+
+ def test_concurrent_acquisition_order(self):
+ """Test that processes acquire semaphore with fairness."""
+ results_queue = multiprocessing.Queue()
+ start_time = time.time()
+ processes = []
+
+ # Start 5 processes with delays to establish clear order (limit is 2)
+ for i in range(5):
+ p = multiprocessing.Process(
+ target=worker_acquire_semaphore,
+ args=(i, start_time, results_queue, 0.3, 5.0), # 0.3s hold time
+ )
+ p.start()
+ processes.append(p)
+ time.sleep(0.1) # 100ms delay between starts to establish clear order
+
+ # Wait for all to complete
+ for p in processes:
+ p.join(timeout=10)
+
+ # Collect and analyze results
+ results = []
+ while not results_queue.empty():
+ results.append(results_queue.get())
+
+ acquired_events = [r for r in results if r[0] == 'acquired']
+ acquired_events.sort(key=lambda x: x[2]) # Sort by acquisition time
+
+ # Extract worker IDs in order of acquisition
+ acquisition_order = [event[1] for event in acquired_events]
+
+ # With a limit of 2 and clear start order:
+ # - Workers 0, 1 should acquire first (they started first)
+ # - Workers 2, 3, 4 should acquire after 0, 1 release
+
+ # First two should be from the first two started
+ first_two = set(acquisition_order[:2])
+ assert first_two == {0, 1}, f'First 2 acquisitions should be workers 0 and 1, got {first_two}'
+
+ # The remaining should all eventually acquire
+ assert len(acquisition_order) == 5, f'All 5 workers should acquire, got {len(acquisition_order)}'
+ assert set(acquisition_order) == {0, 1, 2, 3, 4}, f'All workers should acquire: {acquisition_order}'
+
+ def test_semaphore_persistence_across_runs(self):
+ """Test that semaphore state persists correctly across process runs."""
+ results_queue = multiprocessing.Queue()
+ start_time = time.time()
+
+ # First run: Start 3 processes that hold semaphore (limit is 3)
+ first_batch = []
+ for i in range(3):
+ p = multiprocessing.Process(
+ target=worker_acquire_semaphore,
+ args=(i, start_time, results_queue, 1.0, 5.0), # Hold for 1 second
+ )
+ p.start()
+ first_batch.append(p)
+
+ # Wait for them to acquire and ensure all slots are taken
+ time.sleep(0.5)
+
+ # Try to start one more - should timeout quickly
+ timeout_worker = multiprocessing.Process(
+ target=worker_acquire_semaphore,
+ args=(99, start_time, results_queue, 0.5, 0.3), # Very short timeout
+ )
+ timeout_worker.start()
+ timeout_worker.join(timeout=2)
+
+ # Wait for first batch to complete
+ for p in first_batch:
+ p.join(timeout=5)
+
+ # Now start a new batch - should work immediately
+ second_batch = []
+ for i in range(3, 6):
+ p = multiprocessing.Process(target=worker_acquire_semaphore, args=(i, start_time, results_queue, 0.2, 5.0))
+ p.start()
+ second_batch.append(p)
+
+ for p in second_batch:
+ p.join(timeout=5)
+
+ # Analyze results
+ results = []
+ while not results_queue.empty():
+ results.append(results_queue.get())
+
+ timeout_events = [r for r in results if r[0] == 'timeout' and r[1] == 99]
+ second_batch_acquired = [r for r in results if r[0] == 'acquired' and r[1] >= 3]
+
+ # Worker 99 should timeout
+ assert len(timeout_events) == 1, 'Worker 99 should timeout'
+
+ # Second batch should all acquire successfully
+ assert len(second_batch_acquired) == 3, 'All second batch workers should acquire'
+
+ # Second batch should acquire after first batch releases
+ for event in second_batch_acquired:
+ # Should acquire within 4 seconds (1s hold + overhead)
+ assert event[2] < 4.0, f'Worker {event[1]} took too long to acquire: {event[2]}s'
+
+
+class TestRegularSemaphoreScopes:
+ """Test non-multiprocess semaphore scopes still work correctly."""
+
+ async def test_global_scope(self):
+ """Test global scope semaphore."""
+ results = []
+
+ @retry(
+ retries=0,
+ timeout=1,
+ semaphore_limit=2,
+ semaphore_scope='global',
+ semaphore_name='test_global',
+ )
+ async def test_func(worker_id: int):
+ results.append(('start', worker_id, time.time()))
+ await asyncio.sleep(0.1)
+ results.append(('end', worker_id, time.time()))
+ return worker_id
+
+ # Run 4 tasks concurrently (limit is 2)
+ tasks = [test_func(i) for i in range(4)]
+ await asyncio.gather(*tasks)
+
+ # Check that only 2 ran concurrently
+ starts = [r for r in results if r[0] == 'start']
+ starts.sort(key=lambda x: x[2])
+
+ # First 2 should start immediately
+ assert starts[1][2] - starts[0][2] < 0.05
+
+ # 3rd should wait for first to finish
+ assert starts[2][2] - starts[0][2] > 0.08
+
+ async def test_class_scope(self):
+ """Test class scope semaphore."""
+
+ class TestClass:
+ def __init__(self):
+ self.results = []
+
+ @retry(
+ retries=0,
+ timeout=1,
+ semaphore_limit=1,
+ semaphore_scope='class',
+ semaphore_name='test_method',
+ )
+ async def test_method(self, worker_id: int):
+ self.results.append(('start', worker_id, time.time()))
+ await asyncio.sleep(0.1)
+ self.results.append(('end', worker_id, time.time()))
+ return worker_id
+
+ # Create two instances
+ obj1 = TestClass()
+ obj2 = TestClass()
+
+ # Run method on both instances concurrently
+ # They should share the semaphore (class scope)
+ start_time = time.time()
+ await asyncio.gather(
+ obj1.test_method(1),
+ obj2.test_method(2),
+ )
+ end_time = time.time()
+
+ # Should take ~0.2s (sequential) not ~0.1s (parallel)
+ assert end_time - start_time > 0.18
+
+ async def test_self_scope(self):
+ """Test self scope semaphore."""
+
+ class TestClass:
+ def __init__(self):
+ self.results = []
+
+ @retry(
+ retries=0,
+ timeout=1,
+ semaphore_limit=1,
+ semaphore_scope='self',
+ semaphore_name='test_method',
+ )
+ async def test_method(self, worker_id: int):
+ self.results.append(('start', worker_id, time.time()))
+ await asyncio.sleep(0.1)
+ self.results.append(('end', worker_id, time.time()))
+ return worker_id
+
+ # Create two instances
+ obj1 = TestClass()
+ obj2 = TestClass()
+
+ # Run method on both instances concurrently
+ # They should NOT share the semaphore (self scope)
+ start_time = time.time()
+ await asyncio.gather(
+ obj1.test_method(1),
+ obj2.test_method(2),
+ )
+ end_time = time.time()
+
+ # Should take ~0.1s (parallel) not ~0.2s (sequential)
+ assert end_time - start_time < 0.15
+
+
+if __name__ == '__main__':
+ # Run the tests
+ pytest.main([__file__, '-v'])
diff --git a/tests/ci/test_sequential_agents_reuse.py b/tests/ci/test_sequential_agents_reuse.py
new file mode 100644
index 000000000..de0652a27
--- /dev/null
+++ b/tests/ci/test_sequential_agents_reuse.py
@@ -0,0 +1,425 @@
+"""
+Test that sequential agents can properly reuse the same BrowserSession without
+it being closed prematurely due to garbage collection or page handle issues.
+"""
+
+import asyncio
+import gc
+
+from browser_use import Agent, BrowserProfile, BrowserSession
+from tests.ci.conftest import create_mock_llm
+
+
+class TestSequentialAgentsReuse:
+ """Test that sequential agents can properly reuse the same BrowserSession"""
+
+ async def test_sequential_agents_share_browser_session(self, httpserver):
+ """Test that multiple agents can reuse the same browser session without it being closed"""
+ # Set up test HTML pages
+ httpserver.expect_request('/page1').respond_with_data(
+ '<html><body><h1>Page 1</h1><a href="/page2">Go to Page 2</a></body></html>'
+ )
+ httpserver.expect_request('/page2').respond_with_data(
+ '<html><body><h1>Page 2</h1><a href="/page3">Go to Page 3</a></body></html>'
+ )
+ httpserver.expect_request('/page3').respond_with_data(
+ '<html><body><h1>Page 3</h1><div id="result">Success!</div></body></html>'
+ )
+
+ # Create a browser session with keep_alive=True
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
+ keep_alive=True,
+ headless=True,
+ user_data_dir=None, # Use temporary directory
+ )
+ )
+ await browser_session.start()
+
+ # Agent 1: Navigate to page 1 and open a new tab
+ agent1_actions = [
+ f"""{{
+ "thinking": "Navigating to page 1 and opening page 2 in new tab",
+ "evaluation_previous_goal": "Starting task",
+ "memory": "Need to navigate to page 1 and open new tab",
+ "next_goal": "Navigate to page 1 and open page 2 in new tab",
+ "action": [
+ {{"go_to_url": {{"url": "{httpserver.url_for('/page1')}"}}}},
+ {{"open_tab": {{"url": "{httpserver.url_for('/page2')}"}}}}
+ ]
+ }}"""
+ ]
+
+ agent1 = Agent(
+ task='Navigate to page 1 and open page 2 in a new tab',
+ llm=create_mock_llm(agent1_actions),
+ browser_session=browser_session,
+ )
+ history1 = await agent1.run(max_steps=2)
+ assert len(history1.history) >= 1
+ assert history1.history[-1].state.url == httpserver.url_for('/page2')
+
+ # Verify browser session is still alive
+ assert browser_session.initialized
+ assert browser_session.browser_pid is not None
+ assert len(browser_session.tabs) == 2 # Two tabs should be open
+
+ # Agent 2: Switch to tab 0 and extract content to see what's there
+ agent2_actions = [
+ """{
+ "thinking": "Switching to first tab",
+ "evaluation_previous_goal": "Previous agent opened two tabs successfully",
+ "memory": "Two tabs are open, need to switch to first one",
+ "next_goal": "Switch to tab 0",
+ "action": [
+ {
+ "switch_tab": {
+ "page_id": 0
+ }
+ }
+ ]
+ }""",
+ """{
+ "thinking": "Taking screenshot to see page state",
+ "evaluation_previous_goal": "Switched to tab 0 successfully",
+ "memory": "Now on tab 0, need to see what's on the page",
+ "next_goal": "Take screenshot and extract content",
+ "action": [
+ {
+ "screenshot": {}
+ },
+ {
+ "extract_page_content": {}
+ }
+ ]
+ }""",
+ """{
+ "thinking": "Clicking on the link",
+ "evaluation_previous_goal": "Can see the page content",
+ "memory": "Page has a link, need to click it",
+ "next_goal": "Click the link to go to page 2",
+ "action": [
+ {
+ "click_element_by_index": {
+ "index": 0
+ }
+ }
+ ]
+ }""",
+ ]
+
+ agent2 = Agent(
+ task='Switch to the first tab and click the link',
+ llm=create_mock_llm(agent2_actions),
+ browser_session=browser_session,
+ )
+ history2 = await agent2.run(max_steps=4)
+ assert len(history2.history) >= 1
+ assert history2.history[-1].state.url == httpserver.url_for('/page2')
+
+ # Verify browser session is still alive after second agent
+ assert browser_session.initialized
+ assert browser_session.browser is not None
+ assert browser_session.browser_context is not None
+
+ # Agent 3: Click link to go to page 3
+ agent3_actions = [
+ """{
+ "thinking": "Clicking link to navigate to page 3",
+ "evaluation_previous_goal": "Now on page 2",
+ "memory": "Need to click link to page 3",
+ "next_goal": "Click link to go to page 3",
+ "action": [
+ {
+ "click_element_by_index": {
+ "index": 0
+ }
+ }
+ ]
+ }"""
+ ]
+
+ agent3 = Agent(
+ task='Click link to go to page 3',
+ llm=create_mock_llm(agent3_actions),
+ browser_session=browser_session,
+ )
+ history3 = await agent3.run(max_steps=1)
+ assert len(history3.history) >= 1
+ assert history3.history[-1].state.url == httpserver.url_for('/page3')
+
+ # Agent 4: Take a screenshot and extract content
+ agent4_actions = [
+ """{
+ "thinking": "Taking screenshot and extracting content",
+ "evaluation_previous_goal": "Successfully navigated to page 3",
+ "memory": "On page 3, need to capture content",
+ "next_goal": "Take screenshot and extract page content",
+ "action": [
+ {"screenshot": {}},
+ {"extract_page_content": {}}
+ ]
+ }"""
+ ]
+
+ agent4 = Agent(
+ task='Take a screenshot and extract content',
+ llm=create_mock_llm(agent4_actions),
+ browser_session=browser_session,
+ )
+ history4 = await agent4.run(max_steps=2)
+ assert len(history4.history) >= 1
+
+ # Verify all agents completed successfully
+ found_success = False
+ for step in history4.history:
+ for result in step.result:
+ if hasattr(result, 'extracted_content') and result.extracted_content:
+ if 'Success!' in result.extracted_content:
+ found_success = True
+ break
+ assert found_success, "Did not find 'Success!' in extracted content"
+
+ # Clean up
+ await browser_session.stop()
+
+ async def test_agents_track_separate_current_pages(self, httpserver):
+ """Test that each agent tracks its own current page independently"""
+ # Set up test pages
+ httpserver.expect_request('/a').respond_with_data('<html><body><h1>Page A</h1></body></html>')
+ httpserver.expect_request('/b').respond_with_data('<html><body><h1>Page B</h1></body></html>')
+
+ # Create shared browser session
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
+ keep_alive=True,
+ headless=True,
+ user_data_dir=None, # Use temporary directory
+ )
+ )
+ await browser_session.start()
+
+ # Agent 1 opens two tabs
+ agent1_actions = [
+ f"""{{
+ "thinking": "Opening two tabs",
+ "evaluation_previous_goal": "Starting task",
+ "memory": "Need to open page A and page B",
+ "next_goal": "Open two tabs with different pages",
+ "action": [
+ {{"go_to_url": {{"url": "{httpserver.url_for('/a')}"}}}},
+ {{"open_tab": {{"url": "{httpserver.url_for('/b')}"}}}}
+ ]
+ }}"""
+ ]
+
+ agent1 = Agent(
+ task='Open two tabs',
+ llm=create_mock_llm(agent1_actions),
+ browser_session=browser_session,
+ )
+ await agent1.run(max_steps=2)
+
+ # Verify agent1's view - should be on tab 1 (page B)
+ assert agent1.browser_session
+ assert agent1.browser_session.agent_current_page is not None
+ assert '/b' in agent1.browser_session.agent_current_page.url
+
+ # Agent 2 switches back to first tab
+ agent2_actions = [
+ """{{
+ "thinking": "Switching to first tab",
+ "evaluation_previous_goal": "Two tabs are open",
+ "memory": "Need to switch to tab 0",
+ "next_goal": "Switch to first tab",
+ "action": [
+ {{"switch_tab": {{"page_id": 0}}}}
+ ]
+ }}"""
+ ]
+
+ agent2 = Agent(
+ task='Switch to first tab',
+ llm=create_mock_llm(agent2_actions),
+ browser_session=browser_session,
+ )
+ await agent2.run(max_steps=1)
+
+ # Verify agent2's view - should be on tab 0 (page A)
+ assert agent2.browser_session
+ assert agent2.browser_session.agent_current_page is not None
+ assert '/a' in agent2.browser_session.agent_current_page.url
+
+ # Verify original agent1's page reference wasn't affected
+ # (This would fail without proper copying)
+ assert agent1.browser_session
+ assert agent1.browser_session.agent_current_page is not None
+ assert '/b' in agent1.browser_session.agent_current_page.url
+
+ await browser_session.stop()
+
+ async def test_garbage_collection_doesnt_close_browser(self, httpserver):
+ """Test that browser doesn't close when agent is garbage collected"""
+ httpserver.expect_request('/test').respond_with_data('<html><body>Test</body></html>')
+
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
+ keep_alive=True,
+ headless=True,
+ user_data_dir=None, # Use temporary directory
+ )
+ )
+ await browser_session.start()
+
+ # Store initial browser process ID
+ initial_browser_pid = browser_session.browser_pid
+
+ # Create and run first agent in a scope that will be garbage collected
+ async def run_agent1():
+ agent1_actions = [
+ f'''{{
+ "thinking": "Navigating to test page",
+ "evaluation_previous_goal": "Starting task",
+ "memory": "Need to go to test page",
+ "next_goal": "Navigate to test page",
+ "action": [
+ {{
+ "go_to_url": {{
+ "url": "{httpserver.url_for('/test')}"
+ }}
+ }}
+ ]
+ }}'''
+ ]
+
+ agent1 = Agent(
+ task='Navigate to test page',
+ llm=create_mock_llm(agent1_actions),
+ browser_session=browser_session,
+ )
+ await agent1.run(max_steps=1)
+ # agent1 goes out of scope here and should be garbage collected
+
+ await run_agent1()
+
+ # Force garbage collection
+ gc.collect()
+ await asyncio.sleep(0.1) # Give time for any async cleanup
+
+ # Verify browser is still alive
+ assert browser_session.initialized
+ assert browser_session.browser_context is not None
+ assert browser_session.browser_pid == initial_browser_pid # Same browser process
+
+ # Create second agent - should work without issues
+ agent2_actions = [
+ """{{
+ "thinking": "Taking screenshot of current page",
+ "evaluation_previous_goal": "On test page",
+ "memory": "Need to take screenshot",
+ "next_goal": "Take screenshot",
+ "action": [
+ {{
+ "screenshot": {{}}
+ }}
+ ]
+ }}"""
+ ]
+
+ agent2 = Agent(
+ task='Take screenshot',
+ llm=create_mock_llm(agent2_actions),
+ browser_session=browser_session,
+ )
+ history = await agent2.run(max_steps=1)
+ assert len(history.history) >= 1
+
+ # Verify screenshot was taken successfully
+ screenshot_taken = False
+ for step in history.history:
+ for result in step.result:
+ if hasattr(result, 'screenshot'):
+ screenshot_taken = True
+ break
+ assert screenshot_taken, 'Screenshot was not taken successfully'
+
+ await browser_session.stop()
+
+ async def test_multiple_tabs_with_sequential_agents(self, httpserver):
+ """Test that opening multiple tabs doesn't break page handles when switching agents"""
+ # Set up test pages
+ for i in range(5):
+ httpserver.expect_request(f'/page{i}').respond_with_data(
+ f'<html><body><h1>Page {i}</h1><div id="content">Content {i}</div></body></html>'
+ )
+
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
+ keep_alive=True,
+ headless=True,
+ user_data_dir=None, # Use temporary directory
+ )
+ )
+ await browser_session.start()
+
+ # Agent 1: Open 4 tabs
+ tab_actions = []
+ for i in range(4):
+ url = httpserver.url_for(f'/page{i}')
+ if i == 0:
+ tab_actions.append(f'{{"go_to_url": {{"url": "{url}"}}}}')
+ else:
+ tab_actions.append(f'{{"open_tab": {{"url": "{url}"}}}}')
+
+ agent1_actions = [
+ f"""{{
+ "thinking": "Opening multiple tabs",
+ "evaluation_previous_goal": "Starting task",
+ "memory": "Need to open 4 tabs",
+ "next_goal": "Open 4 different pages in tabs",
+ "action": [{', '.join(tab_actions)}]
+ }}"""
+ ]
+
+ agent1 = Agent(
+ task='Open 4 tabs with different pages',
+ llm=create_mock_llm(agent1_actions),
+ browser_session=browser_session,
+ )
+ await agent1.run(max_steps=2)
+
+ # Verify 4 tabs are open
+ assert len(browser_session.tabs) == 4
+
+ # Agent 2: Switch between tabs and take screenshots
+ agent2_actions = []
+ for i in [2, 0, 3, 1]: # Random order
+ agent2_actions.append(
+ f"""{{
+ "thinking": "Switching to tab {i} and taking screenshot",
+ "evaluation_previous_goal": "Ready to switch tabs",
+ "memory": "Multiple tabs are open",
+ "next_goal": "Switch to tab {i} and screenshot",
+ "action": [
+ {{"switch_tab": {{"page_id": {i}}}}},
+ {{"screenshot": {{}}}}
+ ]
+ }}"""
+ )
+
+ agent2 = Agent(
+ task='Switch between tabs and take screenshots',
+ llm=create_mock_llm(agent2_actions),
+ browser_session=browser_session,
+ )
+ history2 = await agent2.run(max_steps=len(agent2_actions) + 1)
+
+ # Verify we successfully switched tabs and took screenshots
+ assert len(history2.history) >= len(agent2_actions)
+
+ # Verify browser is still functional
+ assert browser_session.initialized
+ assert browser_session.browser is not None
+ assert len(browser_session.tabs) == 4
+
+ await browser_session.stop()
diff --git a/tests/ci/test_sequential_agents_simple.py b/tests/ci/test_sequential_agents_simple.py
new file mode 100644
index 000000000..1590ea1cc
--- /dev/null
+++ b/tests/ci/test_sequential_agents_simple.py
@@ -0,0 +1,175 @@
+"""
+Simple test to verify that sequential agents can reuse the same BrowserSession
+without it being closed prematurely due to garbage collection.
+"""
+
+import asyncio
+import gc
+
+from browser_use import Agent, BrowserProfile, BrowserSession
+from tests.ci.conftest import create_mock_llm
+
+
+class TestSequentialAgentsSimple:
+ """Test that sequential agents can properly reuse the same BrowserSession"""
+
+ async def test_sequential_agents_share_browser_session_simple(self, httpserver):
+ """Test that multiple agents can reuse the same browser session without it being closed"""
+ # Set up test HTML pages
+ httpserver.expect_request('/page1').respond_with_data('<html><body><h1>Page 1</h1></body></html>')
+ httpserver.expect_request('/page2').respond_with_data('<html><body><h1>Page 2</h1></body></html>')
+
+ # Create a browser session with keep_alive=True
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
+ keep_alive=True,
+ headless=True,
+ user_data_dir=None, # Use temporary directory
+ )
+ )
+ await browser_session.start()
+
+ # Verify browser is running
+ initial_pid = browser_session.browser_pid
+ assert initial_pid is not None
+
+ # Agent 1: Navigate to page 1
+ agent1_actions = [
+ f"""{{
+ "thinking": "Navigating to page 1",
+ "evaluation_previous_goal": "Starting task",
+ "memory": "Need to navigate to page 1",
+ "next_goal": "Navigate to page 1",
+ "action": [
+ {{"go_to_url": {{"url": "{httpserver.url_for('/page1')}"}}}}
+ ]
+ }}"""
+ ]
+
+ agent1 = Agent(
+ task='Navigate to page 1',
+ llm=create_mock_llm(agent1_actions),
+ browser_session=browser_session,
+ )
+ history1 = await agent1.run(max_steps=2)
+ assert len(history1.history) >= 1
+ assert history1.history[-1].state.url == httpserver.url_for('/page1')
+
+ # Verify browser session is still alive
+ assert browser_session.initialized
+ assert browser_session.browser_pid == initial_pid
+
+ # Delete agent1 and force garbage collection
+ del agent1
+ gc.collect()
+ await asyncio.sleep(0.1) # Give time for any async cleanup
+
+ # Verify browser is STILL alive after garbage collection
+ assert browser_session.initialized
+ assert browser_session.browser_pid == initial_pid
+ assert browser_session.browser_context is not None
+
+ # Agent 2: Navigate to page 2
+ agent2_actions = [
+ f"""{{
+ "thinking": "Navigating to page 2",
+ "evaluation_previous_goal": "Previous agent successfully navigated",
+ "memory": "Browser is still open, need to go to page 2",
+ "next_goal": "Navigate to page 2",
+ "action": [
+ {{"go_to_url": {{"url": "{httpserver.url_for('/page2')}"}}}}
+ ]
+ }}"""
+ ]
+
+ agent2 = Agent(
+ task='Navigate to page 2',
+ llm=create_mock_llm(agent2_actions),
+ browser_session=browser_session,
+ )
+ history2 = await agent2.run(max_steps=2)
+ assert len(history2.history) >= 1
+ assert history2.history[-1].state.url == httpserver.url_for('/page2')
+
+ # Verify browser session is still alive after second agent
+ assert browser_session.initialized
+ assert browser_session.browser_pid == initial_pid
+ assert browser_session.browser_context is not None
+
+ # Clean up
+ await browser_session.stop()
+
+ async def test_multiple_tabs_sequential_agents(self, httpserver):
+ """Test that sequential agents can work with multiple tabs"""
+ # Set up test pages
+ httpserver.expect_request('/tab1').respond_with_data('<html><body><h1>Tab 1</h1></body></html>')
+ httpserver.expect_request('/tab2').respond_with_data('<html><body><h1>Tab 2</h1></body></html>')
+
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
+ keep_alive=True,
+ headless=True,
+ user_data_dir=None, # Use temporary directory
+ )
+ )
+ await browser_session.start()
+
+ # Agent 1: Open two tabs
+ agent1_actions = [
+ f"""{{
+ "thinking": "Opening two tabs",
+ "evaluation_previous_goal": "Starting task",
+ "memory": "Need to open two tabs",
+ "next_goal": "Open tab 1 and tab 2",
+ "action": [
+ {{"go_to_url": {{"url": "{httpserver.url_for('/tab1')}"}}}},
+ {{"open_tab": {{"url": "{httpserver.url_for('/tab2')}"}}}}
+ ]
+ }}"""
+ ]
+
+ agent1 = Agent(
+ task='Open two tabs',
+ llm=create_mock_llm(agent1_actions),
+ browser_session=browser_session,
+ )
+ await agent1.run(max_steps=2)
+
+ # Verify 2 tabs are open
+ assert len(browser_session.tabs) == 2
+ # Agent1 should be on the second tab (tab2)
+ assert agent1.browser_session is not None
+ assert agent1.browser_session.agent_current_page is not None
+ assert '/tab2' in agent1.browser_session.agent_current_page.url
+
+ # Agent 2: Switch to first tab and take screenshot
+ agent2_actions = [
+ """{{
+ "thinking": "Switching to first tab and taking screenshot",
+ "evaluation_previous_goal": "Two tabs are open",
+ "memory": "Need to switch to tab 0",
+ "next_goal": "Switch to tab 0 and screenshot",
+ "action": [
+ {{"switch_tab": {{"page_id": 0}}}},
+ {{"screenshot": {{}}}}
+ ]
+ }}"""
+ ]
+
+ agent2 = Agent(
+ task='Switch to first tab and screenshot',
+ llm=create_mock_llm(agent2_actions),
+ browser_session=browser_session,
+ )
+ history2 = await agent2.run(max_steps=2)
+
+ # Verify agent2 is on the first tab
+ assert agent2.browser_session is not None
+ assert agent2.browser_session.agent_current_page is not None
+ assert '/tab1' in agent2.browser_session.agent_current_page.url
+
+ # Verify browser is still functional
+ assert browser_session.initialized
+ assert len(browser_session.tabs) == 2
+
+ await browser_session.stop()