Skip to content

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

fix test liveness checking of sessions

Nick Sweeting75895ab9ca97
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 77c091504..df72b97bf 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -321,11 +321,17 @@ class BrowserSession(BaseModel):
def __repr__(self) -> str:
is_copy = '©' if self._original_browser_session else '#'
- return f'BrowserSession🆂 {self.id[-4:]} {is_copy}{str(id(self))[-2:]} ({self._connection_str}, profile={self.browser_profile})'
+ port_number_or_pid = (
+ (self.cdp_url or self.wss_url or str(self.browser_pid) or 'playwright').rsplit(':', 1)[-1].split('/', 1)[0]
+ )
+ return f'BrowserSession🆂 {self.id[-4:]}:{port_number_or_pid} {is_copy}{str(id(self))[-2:]} ({self._connection_str}, profile={self.browser_profile})'
def __str__(self) -> str:
is_copy = '©' if self._original_browser_session else '#'
- return f'BrowserSession🆂 {self.id[-4:]} {is_copy}{str(id(self))[-2:]} ({self._connection_str})' # ' 🅟 {str(id(self.agent_current_page))[-2:]}'
+ port_number_or_pid = (
+ (self.cdp_url or self.wss_url or str(self.browser_pid) or 'playwright').rsplit(':', 1)[-1].split('/', 1)[0]
+ )
+ return f'BrowserSession🆂 {self.id[-4:]}:{port_number_or_pid} {is_copy}{str(id(self))[-2:]}' # ' 🅟 {str(id(self.agent_current_page))[-2:]}'
# better to force people to get it from the right object, "only one way to do it" is better python
# def __getattr__(self, key: str) -> Any:
@@ -2221,7 +2227,7 @@ class BrowserSession(BaseModel):
# --- Page navigation ---
@observe_debug()
- @retry(retries=1, timeout=90, wait=1)
+ @retry(retries=0, timeout=30, wait=1)
@require_healthy_browser(usable_page=False, reopen_page=False)
async def navigate(self, url: str = 'about:blank', new_tab: bool = False, timeout_ms: int | None = None) -> Page:
"""
@@ -2266,6 +2272,7 @@ class BrowserSession(BaseModel):
try:
# Use asyncio.wait to prevent hanging on slow page loads
# Don't cap the timeout - respect what was requested
+ self.logger.debug(f'🧭 Starting navigation to {_log_pretty_url(normalized_url)} with timeout {timeout_ms}ms')
nav_task = asyncio.create_task(page.goto(normalized_url, wait_until='load', timeout=timeout_ms))
done, pending = await asyncio.wait([nav_task], timeout=(timeout_ms + 500) / 1000)
diff --git a/tests/ci/test_browser_session_crashed_page_recovery.py b/tests/ci/test_browser_session_crashed_page_recovery.py
index 2e49ab056..72fdcf24d 100644
--- a/tests/ci/test_browser_session_crashed_page_recovery.py
+++ b/tests/ci/test_browser_session_crashed_page_recovery.py
@@ -429,7 +429,7 @@ class TestBrowserSessionRecovery:
assert 'normal' in page2.url
[email protected](30) # 30 second timeout to prevent hanging forever
async def test_multiple_sessions_with_blocking_pages(httpserver: HTTPServer):
"""Test multiple browser sessions with blocking pages simultaneously"""
httpserver.expect_request('/infinite-loop').respond_with_data(
@@ -443,7 +443,7 @@ async def test_multiple_sessions_with_blocking_pages(httpserver: HTTPServer):
browser_profile=BrowserProfile(
headless=True,
keep_alive=False,
- default_navigation_timeout=5000, # 5 second timeout
+ default_navigation_timeout=6000, # 5 second timeout
user_data_dir=None,
)
)
@@ -455,7 +455,7 @@ async def test_multiple_sessions_with_blocking_pages(httpserver: HTTPServer):
# Navigate to blocking pages - should handle without crashing
nav_tasks = []
for s in sessions:
- nav_tasks.append(s.navigate(httpserver.url_for('/infinite-loop')))
+ nav_tasks.append(s.navigate(httpserver.url_for('/infinite-loop'), timeout_ms=5000))
# All navigations should complete within 5s (they may fail but shouldn't hang forever)
results = await asyncio.gather(*nav_tasks, return_exceptions=True)
@@ -465,9 +465,9 @@ async def test_multiple_sessions_with_blocking_pages(httpserver: HTTPServer):
if isinstance(result, Exception):
print(f'Session {i} navigation failed as expected: {type(result).__name__}')
- # Sessions should still be functional
+ # Sessions should still be functional, test by creating a new page and executing JS
for i, session in enumerate(sessions):
- assert await session.is_connected(), f'Session {i} disconnected'
+ assert await (await session.browser_context.new_page()).evaluate('1+1') == 2, f'Session {i} page failed to execute JS'
finally:
# Kill sessions with exception handling to avoid cascade failures