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
stop playwright node subprocess when session.kill is called
Nick Sweetinge143d079af4d
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 7e082d226..491e260dd 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -437,6 +437,29 @@ class BrowserSession(BaseModel):self.browser_profile.keep_alive = Falseawait self.stop()+ # Clean up playwright instance to prevent background tasks from running+ if self.playwright:+ try:+ await self.playwright.stop()+ self.logger.debug('🎭 Stopped playwright instance')+ except Exception as e:+ self.logger.warning(f'❌ Error stopping playwright: {type(e).__name__}: {e}')+ finally:+ # Clear global references if they match this instance+ global GLOBAL_PLAYWRIGHT_API_OBJECT, GLOBAL_PATCHRIGHT_API_OBJECT+ global GLOBAL_PLAYWRIGHT_EVENT_LOOP, GLOBAL_PATCHRIGHT_EVENT_LOOP++ if self.playwright == GLOBAL_PLAYWRIGHT_API_OBJECT:+ GLOBAL_PLAYWRIGHT_API_OBJECT = None+ GLOBAL_PLAYWRIGHT_EVENT_LOOP = None+ self.logger.debug('🧹 Cleared global playwright references')+ elif self.playwright == GLOBAL_PATCHRIGHT_API_OBJECT:+ GLOBAL_PATCHRIGHT_API_OBJECT = None+ GLOBAL_PATCHRIGHT_EVENT_LOOP = None+ self.logger.debug('🧹 Cleared global patchright references')++ self.playwright = None+async def new_context(self, **kwargs):"""Deprecated: Provides backwards-compatibility with old class method Browser().new_context()."""# TODO: remove this after >=0.3.0@@ -1261,6 +1284,7 @@ class BrowserSession(BaseModel):self.human_current_page = Noneself._cached_clickable_element_hashes = Noneself._cached_browser_state_summary = None+ # Don't clear self.playwright here - it should be cleared explicitly in kill()if self.browser_pid:try:diff --git a/tests/ci/test_agent_multiprocessing.py b/tests/ci/test_agent_multiprocessing.pyindex 7b4420fcd..a4e61f6c5 100644--- a/tests/ci/test_agent_multiprocessing.py+++ b/tests/ci/test_agent_multiprocessing.py@@ -17,7 +17,6 @@ import multiprocessingfrom concurrent.futures import ThreadPoolExecutorfrom unittest.mock import AsyncMock-import pytestfrom langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.messages import AIMessagefrom playwright.async_api import async_playwright@@ -440,51 +439,6 @@ class TestParallelism:assert result['error'] is None, f'Process {i} error: {result["error"]}'assert result['success'] is True- async def test_asyncio_run_error_reproduction(self):- """Test that demonstrates the asyncio.run() RuntimeError issue"""- logger.info('Testing asyncio.run() RuntimeError reproduction')-- # This test simulates the pattern that causes the error after 40+ tests- # when asyncio.run() is called within a pytest-asyncio session-scoped event loop-- # Track if we're in an existing event loop- try:- loop = asyncio.get_running_loop()- has_running_loop = True- except RuntimeError:- has_running_loop = False-- # We should always have a running loop in async tests due to pytest-asyncio session scope- assert has_running_loop, 'Expected to be in a running event loop due to pytest-asyncio session scope'-- # If we're already in an event loop, asyncio.run() should fail- # We need to suppress the warning about unawaited coroutine- import warnings-- with warnings.catch_warnings():- warnings.simplefilter('ignore', RuntimeWarning)- with pytest.raises(RuntimeError, match='asyncio.run.*cannot be called from a running event loop'):- # This will create a coroutine that won't be awaited, but we're testing the exception- asyncio.run(asyncio.sleep(0))-- async def test_asyncio_run_in_sync_test_causes_problems(self):- """Test that shows asyncio.run() in sync tests can cause event loop issues"""- logger.info('Testing asyncio.run() in sync test context')-- # Just run in the current event loop- async def dummy_coroutine():- return 'test'-- # Run directly without creating new loops- result1 = await dummy_coroutine()- assert result1 == 'test'-- # Subsequent calls also work- result2 = await dummy_coroutine()- assert result2 == 'test'-- # This approach avoids event loop state corruption-async def test_shared_browser_session_multiple_tabs(self):"""Test multiple agents sharing same browser session with different tabs"""logger.info('Testing shared browser session with multiple tabs')@@ -575,6 +529,8 @@ class TestParallelism:assert agent1.browser_session == shared_sessionfinally:+ # Give playwright tasks a moment to complete before killing+ await asyncio.sleep(0.1)await shared_session.kill()async def test_reuse_browser_session_sequentially(self):