Skip to content

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

refactor: simplify session retrieval methods in SessionManager and BrowserSession

reformedot7a31936f5db7
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 43688cf0f..8a69949bc 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -1160,7 +1160,7 @@ class BrowserSession(BaseModel):
target_id = self.agent_focus_target_id
# Get session from event-driven pool
- session = await self.session_manager.get_session_for_target(target_id)
+ session = self.session_manager.get_session_for_target(target_id)
if not session:
# Session not in pool yet - wait for attach event
@@ -1169,7 +1169,7 @@ class BrowserSession(BaseModel):
# Wait up to 2 seconds for the attach event
for attempt in range(20):
await asyncio.sleep(0.1)
- session = await self.session_manager.get_session_for_target(target_id)
+ session = self.session_manager.get_session_for_target(target_id)
if session:
self.logger.debug(f'[SessionManager] Target appeared after {attempt * 100}ms')
break
@@ -1217,7 +1217,7 @@ class BrowserSession(BaseModel):
def current_session_id(self) -> str | None:
if not self.agent_focus_target_id or not self.session_manager:
return None
- session = self.session_manager.get_session_for_target_sync(self.agent_focus_target_id)
+ session = self.session_manager.get_session_for_target(self.agent_focus_target_id)
return session.session_id if session else None
# endregion - ========== CDP-based ... ==========
@@ -1472,7 +1472,7 @@ class BrowserSession(BaseModel):
self.logger.debug(f'🔄 Redirecting {target_url} to about:blank for target {target_id}')
try:
# Sessions now exist from SessionManager initialization
- session = await self.session_manager.get_session_for_target(target_id)
+ session = self.session_manager.get_session_for_target(target_id)
if session:
await session.cdp_client.send.Page.navigate(
params={'url': 'about:blank'}, session_id=session.session_id
@@ -1495,7 +1495,7 @@ class BrowserSession(BaseModel):
# (SessionManager already attached to existing targets in start_monitoring())
for _ in range(20): # Wait up to 2 seconds
await asyncio.sleep(0.1)
- session = await self.session_manager.get_session_for_target(target_id)
+ session = self.session_manager.get_session_for_target(target_id)
if session:
self.agent_focus_target_id = target_id
self.logger.debug(f'📄 Agent focus set to {target_id[:8]}...')
@@ -1567,7 +1567,7 @@ class BrowserSession(BaseModel):
# Also enable on the focused target's session if available to ensure events are delivered
try:
if self.agent_focus_target_id:
- cdp_session = await self.session_manager.get_session_for_target(self.agent_focus_target_id)
+ cdp_session = self.session_manager.get_session_for_target(self.agent_focus_target_id)
if cdp_session:
await cdp_session.cdp_client.send.Fetch.enable(
params={'handleAuthRequests': True},
@@ -1645,7 +1645,7 @@ class BrowserSession(BaseModel):
self._cdp_client_root.register.Fetch.authRequired(_on_auth_required)
self._cdp_client_root.register.Fetch.requestPaused(_on_request_paused)
if self.agent_focus_target_id:
- cdp_session = await self.session_manager.get_session_for_target(self.agent_focus_target_id)
+ cdp_session = self.session_manager.get_session_for_target(self.agent_focus_target_id)
if cdp_session:
cdp_session.cdp_client.register.Fetch.authRequired(_on_auth_required)
cdp_session.cdp_client.register.Fetch.requestPaused(_on_request_paused)
@@ -1681,7 +1681,7 @@ class BrowserSession(BaseModel):
# Ensure Fetch is enabled for the current focused target's session, too
try:
if self.agent_focus_target_id:
- cdp_session = await self.session_manager.get_session_for_target(self.agent_focus_target_id)
+ cdp_session = self.session_manager.get_session_for_target(self.agent_focus_target_id)
if cdp_session:
await cdp_session.cdp_client.send.Fetch.enable(
params={'handleAuthRequests': True, 'patterns': [{'urlPattern': '*'}]},
@@ -2620,7 +2620,7 @@ class BrowserSession(BaseModel):
cdp_session = await self.get_or_create_cdp_session(target_id, focus=False)
elif self.agent_focus_target_id:
# Use current focus
- cdp_session = await self.session_manager.get_session_for_target(self.agent_focus_target_id)
+ cdp_session = self.session_manager.get_session_for_target(self.agent_focus_target_id)
if not cdp_session:
self.logger.warning('Cannot set viewport: focused target has no sessions')
return
@@ -2834,7 +2834,7 @@ class BrowserSession(BaseModel):
if self.agent_focus_target_id and target_id != self.agent_focus_target_id:
continue
# Use the existing agent_focus target's session
- cdp_session = await self.session_manager.get_session_for_target(self.agent_focus_target_id)
+ cdp_session = self.session_manager.get_session_for_target(self.agent_focus_target_id)
if not cdp_session:
continue # Skip if no session available
else:
@@ -3081,7 +3081,7 @@ class BrowserSession(BaseModel):
# Strategy 4: Fallback to agent_focus_target_id (the page where agent is currently working)
if self.agent_focus_target_id:
target = self.session_manager.get_target(self.agent_focus_target_id)
- cdp_session = await self.session_manager.get_session_for_target(self.agent_focus_target_id)
+ cdp_session = self.session_manager.get_session_for_target(self.agent_focus_target_id)
if cdp_session and target:
self.logger.warning(
f'⚠️ Node {node.backend_node_id} has no session/frame/target info. Using agent_focus session: {target.url}'
diff --git a/browser_use/browser/session_manager.py b/browser_use/browser/session_manager.py
index 13829e88c..a2494cb14 100644
--- a/browser_use/browser/session_manager.py
+++ b/browser_use/browser/session_manager.py
@@ -46,10 +46,7 @@ class SessionManager:
# Target -> type cache (page, iframe, worker, etc.) - types are immutable
self._target_types: dict[TargetID, str] = {}
- # Lock for thread-safe access
self._lock = asyncio.Lock()
-
- # Lock for recovery to prevent concurrent recovery attempts
self._recovery_lock = asyncio.Lock()
async def start_monitoring(self) -> None:
@@ -93,7 +90,7 @@ class SessionManager:
# Discover and initialize ALL existing targets
await self._initialize_existing_targets()
- async def get_session_for_target(self, target_id: TargetID) -> 'CDPSession | None':
+ def get_session_for_target(self, target_id: TargetID) -> 'CDPSession | None':
"""Get ANY valid session for a target (picks first available).
Args:
@@ -102,33 +99,10 @@ class SessionManager:
Returns:
CDPSession if exists, None if target has detached
"""
- async with self._lock:
- # Get any session for this target (pick first)
- session_ids = self._target_sessions.get(target_id, set())
- if not session_ids:
- return None
- # Pick first session (deterministic with sorted for stability)
- session_id = sorted(session_ids)[0]
- return self._sessions.get(session_id)
-
- def get_session_for_target_sync(self, target_id: TargetID) -> 'CDPSession | None':
- """Synchronous version: Get ANY valid session for a target.
-
- Use this in sync contexts (properties, __init__, etc). No lock needed for read.
-
- Args:
- target_id: Target ID to get session for
-
- Returns:
- CDPSession if exists, None if target has detached
- """
- # Get any session for this target (pick first) - no lock needed for read
session_ids = self._target_sessions.get(target_id, set())
if not session_ids:
return None
- # Pick first session (deterministic with sorted for stability)
- session_id = sorted(session_ids)[0]
- return self._sessions.get(session_id)
+ return self._sessions.get(next(iter(session_ids)))
def get_all_page_targets(self) -> list:
"""Get all page/tab targets using owned data.
@@ -152,11 +126,9 @@ class SessionManager:
Returns:
True if target has active sessions, False if it should be removed
"""
- async with self._lock:
- if target_id not in self._target_sessions:
- return False
-
- return len(self._target_sessions[target_id]) > 0
+ if target_id not in self._target_sessions:
+ return False
+ return len(self._target_sessions[target_id]) > 0
async def clear(self) -> None:
"""Clear all owned data structures for cleanup."""
@@ -179,13 +151,12 @@ class SessionManager:
Returns:
True if target is valid and has active sessions, False otherwise
"""
- async with self._lock:
- if target_id not in self._target_sessions:
- return False
- return len(self._target_sessions[target_id]) > 0
+ if target_id not in self._target_sessions:
+ return False
+ return len(self._target_sessions[target_id]) > 0
def get_target_id_from_session_id(self, session_id: SessionID) -> TargetID | None:
- """Look up which target a session belongs to (sync, no lock needed).
+ """Look up which target a session belongs to.
Args:
session_id: The session ID to look up
@@ -273,17 +244,15 @@ class SessionManager:
return None
return self.get_target(self.browser_session.agent_focus_target_id)
- async def get_focused_session(self) -> 'CDPSession | None':
+ def get_focused_session(self) -> 'CDPSession | None':
"""Get a session for the currently focused target.
- Convenience method that uses browser_session.agent_focus_target_id.
-
Returns:
CDPSession for focused target, None if no focus
"""
if not self.browser_session.agent_focus_target_id:
return None
- return await self.get_session_for_target(self.browser_session.agent_focus_target_id)
+ return self.get_session_for_target(self.browser_session.agent_focus_target_id)
async def _handle_target_attached(self, event: AttachedToTargetEvent) -> None:
"""Handle Target.attachedToTarget event.
@@ -538,7 +507,7 @@ class SessionManager:
new_session = None
for attempt in range(20): # Wait up to 2 seconds
await asyncio.sleep(0.1)
- new_session = await self.get_session_for_target(new_target_id)
+ new_session = self.get_session_for_target(new_target_id)
if new_session:
break
@@ -576,7 +545,7 @@ class SessionManager:
# Try one more time with fallback
for _ in range(20):
await asyncio.sleep(0.1)
- fallback_session = await self.get_session_for_target(fallback_target_id)
+ fallback_session = self.get_session_for_target(fallback_target_id)
if fallback_session:
self.browser_session.agent_focus_target_id = fallback_target_id
self.logger.warning(f'[SessionManager] ⚠️ Agent focus set to emergency fallback: {fallback_target_id[:8]}...')
@@ -642,7 +611,7 @@ class SessionManager:
while True:
ready_count = 0
for tid in target_ids_to_wait_for:
- session = await self.get_session_for_target(tid)
+ session = self.get_session_for_target(tid)
if session:
target_type = self._target_types.get(tid, 'unknown')
# For pages, verify monitoring is enabled
@@ -669,7 +638,7 @@ class SessionManager:
# Timeout - count what's ready
ready_count = 0
for tid in target_ids_to_wait_for:
- session = await self.get_session_for_target(tid)
+ session = self.get_session_for_target(tid)
if session:
target_type = self._target_types.get(tid, 'unknown')
# For pages, verify monitoring is enabled
diff --git a/browser_use/browser/watchdogs/default_action_watchdog.py b/browser_use/browser/watchdogs/default_action_watchdog.py
index e74a7a598..0cd26b45b 100644
--- a/browser_use/browser/watchdogs/default_action_watchdog.py
+++ b/browser_use/browser/watchdogs/default_action_watchdog.py
@@ -1634,7 +1634,7 @@ class DefaultActionWatchdog(BaseWatchdog):
assert self.browser_session.agent_focus_target_id is not None, (
'CDP session not initialized - browser may not be connected yet'
)
- cdp_session = await self.browser_session.session_manager.get_focused_session()
+ cdp_session = self.browser_session.session_manager.get_focused_session()
assert cdp_session is not None, 'No session for focused target'
cdp_client = cdp_session.cdp_client
session_id = cdp_session.session_id
@@ -1785,7 +1785,7 @@ class DefaultActionWatchdog(BaseWatchdog):
assert self.browser_session.agent_focus_target_id is not None, (
'CDP session not initialized - browser may not be connected yet'
)
- cdp_session = await self.browser_session.session_manager.get_focused_session()
+ cdp_session = self.browser_session.session_manager.get_focused_session()
assert cdp_session is not None, 'No session for focused target'
return cdp_session.session_id
@@ -2113,7 +2113,7 @@ class DefaultActionWatchdog(BaseWatchdog):
cdp_client = self.browser_session.cdp_client
if self.browser_session.agent_focus_target_id is None:
raise BrowserError('CDP session not initialized - browser may not be connected yet')
- cdp_session = await self.browser_session.session_manager.get_focused_session()
+ cdp_session = self.browser_session.session_manager.get_focused_session()
assert cdp_session is not None, 'No session for focused target'
session_id = cdp_session.session_id
diff --git a/browser_use/browser/watchdogs/dom_watchdog.py b/browser_use/browser/watchdogs/dom_watchdog.py
index 439862e72..ca42f7e51 100644
--- a/browser_use/browser/watchdogs/dom_watchdog.py
+++ b/browser_use/browser/watchdogs/dom_watchdog.py
@@ -258,7 +258,7 @@ class DOMWatchdog(BaseWatchdog):
page_url = await self.browser_session.get_current_page_url()
self.logger.debug(f'🔍 DOMWatchdog.on_BrowserStateRequestEvent: Got page URL: {page_url}')
if self.browser_session.agent_focus_target_id:
- cdp_session = await self.browser_session.session_manager.get_focused_session()
+ cdp_session = self.browser_session.session_manager.get_focused_session()
session_id = cdp_session.session_id if cdp_session else 'unknown'
self.logger.debug(
f'Current page URL: {page_url}, target_id: {self.browser_session.agent_focus_target_id}, session_id: {session_id}'
diff --git a/browser_use/browser/watchdogs/downloads_watchdog.py b/browser_use/browser/watchdogs/downloads_watchdog.py
index 7ddc35e8e..de7a1bd62 100644
--- a/browser_use/browser/watchdogs/downloads_watchdog.py
+++ b/browser_use/browser/watchdogs/downloads_watchdog.py
@@ -90,7 +90,7 @@ class DownloadsWatchdog(BaseWatchdog):
async def on_BrowserStateRequestEvent(self, event: BrowserStateRequestEvent) -> None:
"""Handle browser state request events."""
- cdp_session = await self.browser_session.session_manager.get_focused_session()
+ cdp_session = self.browser_session.session_manager.get_focused_session()
if not cdp_session:
return
@@ -944,7 +944,7 @@ class DownloadsWatchdog(BaseWatchdog):
"""
self.logger.debug(f'[DownloadsWatchdog] Checking if target {target_id} is PDF viewer...')
- session = await self.browser_session.session_manager.get_session_for_target(target_id)
+ session = self.browser_session.session_manager.get_session_for_target(target_id)
if not session:
self.logger.warning(f'[DownloadsWatchdog] No session found for {target_id}')
return False
diff --git a/browser_use/browser/watchdogs/popups_watchdog.py b/browser_use/browser/watchdogs/popups_watchdog.py
index efbbf9101..67b1c25d0 100644
--- a/browser_use/browser/watchdogs/popups_watchdog.py
+++ b/browser_use/browser/watchdogs/popups_watchdog.py
@@ -102,7 +102,7 @@ class PopupsWatchdog(BaseWatchdog):
# Approach 2: Try with current agent focus session
if not dismissed and self.browser_session._cdp_client_root and self.browser_session.agent_focus_target_id:
try:
- cdp_session = await self.browser_session.session_manager.get_focused_session()
+ cdp_session = self.browser_session.session_manager.get_focused_session()
if cdp_session:
self.logger.debug(f'🔄 Approach 2: Using agent focus session {cdp_session.session_id[-8:]}')
await asyncio.wait_for(