Skip to content

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

track owns_browser_session on the agent and fix event result hangs

Nick Sweetingf3be5eeeaa3e
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 4829a7f9f..57010ccd3 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -31,7 +31,7 @@ from browser_use.tokens.service import TokenCost
load_dotenv()
from bubus import EventBus
-from pydantic import ValidationError
+from pydantic import PrivateAttr, ValidationError
from uuid_extensions import uuid7str
# Lazy import for gif to avoid heavy agent.views import at startup
@@ -123,6 +123,7 @@ AgentHookFunc = Callable[['Agent'], Awaitable[None]]
class Agent(Generic[Context, AgentStructuredOutput]):
browser_session: BrowserSession | None = None
_logger: logging.Logger | None = None
+ _owns_browser_session: bool = PrivateAttr(default=False)
@time_execution_sync('--init')
def __init__(
@@ -369,6 +370,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# '⚠️ Attempting to use multiple Agents with the same BrowserSession! This is not supported yet and will likely lead to strange behavior, use separate BrowserSessions for each Agent.'
# )
self.browser_session = browser_session.model_copy()
+ # Browser session was provided externally, don't own it
+ self._owns_browser_session = False
else:
if browser is not None:
assert isinstance(browser, Browser), 'Browser is not set up'
@@ -376,6 +379,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
browser_profile=browser_profile,
id=uuid7str()[:-4] + self.id[-4:], # re-use the same 4-char suffix so they show up together in logs
)
+ # We created the browser session, so we own it
+ self._owns_browser_session = True
if self.sensitive_data:
# Check if sensitive_data has domain-specific credentials
@@ -1719,9 +1724,10 @@ class Agent(Generic[Context, AgentStructuredOutput]):
async def close(self):
"""Close all resources"""
try:
- # First close browser resources
- assert self.browser_session is not None, 'BrowserSession is not set up'
- await self.browser_session.stop()
+ # Only close browser resources if we created them
+ if self._owns_browser_session:
+ assert self.browser_session is not None, 'BrowserSession is not set up'
+ await self.browser_session.stop()
# Force garbage collection
gc.collect()
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.py
index 2a8e81413..1306e9e97 100644
--- a/browser_use/browser/downloads_watchdog.py
+++ b/browser_use/browser/downloads_watchdog.py
@@ -49,6 +49,8 @@ class DownloadsWatchdog(BaseWatchdog):
) # Track pages that already have download listeners
_active_downloads: dict[str, Download] = PrivateAttr(default_factory=dict)
_pdf_viewer_cache: dict[str, bool] = PrivateAttr(default_factory=dict) # Cache PDF viewer status by page URL
+ _download_cdp_session_setup: bool = PrivateAttr(default=False) # Track if CDP session is set up
+ _download_cdp_session: Any = PrivateAttr(default=None) # Store CDP session reference
async def on_BrowserLaunchEvent(self, event: BrowserLaunchEvent) -> None:
logger.info(f'[DownloadsWatchdog] Received BrowserLaunchEvent, EventBus ID: {id(self.event_bus)}')
diff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.py
index 3f45a0d02..dfe6279e9 100644
--- a/browser_use/browser/navigation_watchdog.py
+++ b/browser_use/browser/navigation_watchdog.py
@@ -561,6 +561,11 @@ class NavigationWatchdog(BaseWatchdog):
# No tabs available or no allowed tabs, create a new one with about:blank
logger.info('[NavigationWatchdog] No active page, creating new tab')
+
+ # Check if browser is still connected before trying to create a new tab
+ if not self.browser_session._browser_context:
+ raise ValueError('Browser context is not available - browser may have disconnected')
+
nav_event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))
await nav_event # Wait for navigation to complete
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 99c056b82..b30370353 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -383,17 +383,19 @@ class BrowserSession(BaseModel):
event = self.event_bus.dispatch(BrowserStopEvent())
await event
- # Schedule EventBus cleanup after all events complete
- async def cleanup_eventbus():
- try:
- await self.event_bus.wait_until_idle(timeout=20.0)
- except TimeoutError:
- logger.warning("EventBus didn't become idle within 20 seconds during stop")
- await self.event_bus.stop(timeout=1.0, clear=True)
+ # Only cleanup EventBus if browser is actually stopping (not kept alive)
+ if not self.browser_profile.keep_alive:
+ # Schedule EventBus cleanup after all events complete
+ async def cleanup_eventbus():
+ try:
+ await self.event_bus.wait_until_idle(timeout=20.0)
+ except TimeoutError:
+ logger.warning("EventBus didn't become idle within 20 seconds during stop")
+ await self.event_bus.stop(timeout=1.0, clear=True)
- import asyncio
+ import asyncio
- asyncio.create_task(cleanup_eventbus())
+ asyncio.create_task(cleanup_eventbus())
async def on_ClickElementEvent(self, event: ClickElementEvent) -> None:
"""Handle click request."""
@@ -1720,7 +1722,8 @@ class BrowserSession(BaseModel):
# Dispatch the event and await the result with timeout
event = self.event_bus.dispatch(ExecuteJavaScriptEvent(tab_index=tab_index, expression=script))
- result = await event.event_result(timeout=1.5)
+ # Allow None results (when JavaScript returns undefined)
+ result = await event.event_result(timeout=1.5, raise_if_none=False)
return result
async def get_scroll_info(self, page: Page) -> tuple[int, int]: