Skip to content

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

refactor: improve CDP session handling in cua.py and test_frame_hierarchy.py

reformedot2bfb3497d9cf
diff --git a/examples/custom-functions/cua.py b/examples/custom-functions/cua.py
index 20af82fe4..67038feca 100644
--- a/examples/custom-functions/cua.py
+++ b/examples/custom-functions/cua.py
@@ -46,10 +46,11 @@ async def handle_model_action(browser_session: BrowserSession, action) -> Action
if not browser_session.agent_focus_target_id:
return ActionResult(error='No active browser session')
- # Get CDP session for the focused target
- cdp_session = browser_session.session_manager.get_session_for_target(browser_session.agent_focus_target_id)
- if not cdp_session:
- return ActionResult(error='No CDP session for focused target')
+ # Get CDP session for the focused target using the public API
+ try:
+ cdp_session = await browser_session.get_or_create_cdp_session(browser_session.agent_focus_target_id, focus=False)
+ except Exception as e:
+ return ActionResult(error=f'Failed to get CDP session: {e}')
try:
match action_type:
diff --git a/tests/scripts/test_frame_hierarchy.py b/tests/scripts/test_frame_hierarchy.py
index 4105cbfdc..4013dc18c 100755
--- a/tests/scripts/test_frame_hierarchy.py
+++ b/tests/scripts/test_frame_hierarchy.py
@@ -47,8 +47,12 @@ async def analyze_frame_hierarchy(url):
print(f' URL: {target.url}')
print(f' Target ID: {target.target_id[:30]}...')
- # Check if target has active sessions
- has_session = session.session_manager.get_session_for_target(target.target_id) is not None
+ # Check if target has active sessions using the public API
+ try:
+ cdp_session = await session.get_or_create_cdp_session(target.target_id, focus=False)
+ has_session = cdp_session is not None
+ except Exception:
+ has_session = False
print(f' Has Session: {has_session}')
# Get main page frame tree