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
fix: don't focus when generating DOMTree in _get_viewport_ratio
reformedot3a21ce805dcf
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 2adf94ae8..8af1b0b57 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -1029,41 +1029,54 @@ class BrowserSession(BaseModel):# Get session from event-driven poolsession = await self._session_manager.get_session_for_target(target_id)- if session:- # Validate session is still active- is_valid = await self._session_manager.validate_session(target_id)- if not is_valid:- raise ValueError(f'Target {target_id} has detached - no active sessions')-- # Update focus if requested- if focus and self.agent_focus.target_id != target_id:+ if not session:+ # Session not in pool yet - wait for attach event+ self.logger.debug(f'[SessionManager] Waiting for target {target_id[:8]}... to attach...')++ # 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)+ if session:+ self.logger.debug(f'[SessionManager] Target appeared after {attempt * 100}ms')+ break++ if not session:+ # Timeout - target doesn't exist+ raise ValueError(f'Target {target_id} not found - may have detached or never existed')++ # Validate session is still active+ is_valid = await self._session_manager.validate_session(target_id)+ if not is_valid:+ raise ValueError(f'Target {target_id} has detached - no active sessions')++ # Update focus if requested+ # CRITICAL: Only allow focus change to 'page' type targets, not iframes/workers+ if focus and self.agent_focus.target_id != target_id:+ # Check target type before allowing focus change+ targets = await self._cdp_client_root.send.Target.getTargets()+ target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)+ target_type = target_info.get('type') if target_info else 'unknown'++ if target_type == 'page':self.logger.debug(f'[SessionManager] Switching focus: {self.agent_focus.target_id[:8]}... → {target_id[:8]}...')self.agent_focus = session+ else:+ # Ignore focus request for non-page targets (iframes, workers, etc.)+ # These can detach at any time, causing agent_focus to point to dead target+ self.logger.debug(+ f'[SessionManager] Ignoring focus request for {target_type} target {target_id[:8]}... '+ f'(agent_focus stays on {self.agent_focus.target_id[:8]}...)'+ )- # Resume if waiting for debugger- if focus:- try:- await session.cdp_client.send.Runtime.runIfWaitingForDebugger(session_id=session.session_id)- except Exception:- pass # May fail if not waiting-- return session-- # Session not in pool yet - wait for attach event- self.logger.debug(f'[SessionManager] Waiting for target {target_id[:8]}... to attach...')-- # 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)- if session:- self.logger.debug(f'[SessionManager] Target appeared after {attempt * 100}ms')- if focus:- self.agent_focus = session- return session+ # Resume if waiting for debugger+ if focus:+ try:+ await session.cdp_client.send.Runtime.runIfWaitingForDebugger(session_id=session.session_id)+ except Exception:+ pass # May fail if not waiting- # Timeout - target doesn't exist- raise ValueError(f'Target {target_id} not found - may have detached or never existed')+ return session@propertydef current_target_id(self) -> str | None:diff --git a/browser_use/browser/session_manager.py b/browser_use/browser/session_manager.pyindex 848e4c262..10d1a1065 100644--- a/browser_use/browser/session_manager.py+++ b/browser_use/browser/session_manager.py@@ -166,6 +166,14 @@ class SessionManager:self.logger.warning(f'[SessionManager] Session detached but target unknown (session={session_id[:8]}...)')return+ # CRITICAL: If agent_focus points to this target, clear it+ # This prevents agent from using a dead target+ if self.browser_session.agent_focus and self.browser_session.agent_focus.target_id == target_id:+ self.logger.warning(+ f'[SessionManager] Agent focus target {target_id[:8]}... is detaching! '+ f'Clearing agent_focus to prevent using dead target.'+ )+async with self._lock:# Remove this session from target's session setif target_id in self._target_sessions:diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex bdd0327a4..533a7f419 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -137,7 +137,7 @@ class DomService:async def _get_viewport_ratio(self, target_id: TargetID) -> float:"""Get viewport dimensions, device pixel ratio, and scroll position using CDP."""- cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=target_id, focus=True)+ cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=target_id, focus=False)try:# Get the layout metrics which includes the visual viewport