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
feat: remove event bus dependency, add dialog handling
ShawnPanae09ba11ef11e
diff --git a/browser_use/skill_cli/actions.py b/browser_use/skill_cli/actions.pyindex 7f61331ee..873fdca16 100644--- a/browser_use/skill_cli/actions.py+++ b/browser_use/skill_cli/actions.py@@ -173,4 +173,5 @@ class ActionHandler:tabs=tabs,screenshot=screenshot_b64,page_info=page_info,+ closed_popup_messages=self.bs._closed_popup_messages.copy(),)diff --git a/browser_use/skill_cli/browser.py b/browser_use/skill_cli/browser.pyindex 61be4b15f..673c45a05 100644--- a/browser_use/skill_cli/browser.py+++ b/browser_use/skill_cli/browser.py@@ -55,6 +55,43 @@ class CLIBrowserSession(BrowserSession):# Disable auto-reconnect — daemon should die when CDP dropsself._intentional_stop = True+ # Register popup/dialog handler so JS alerts don't freeze Chrome+ await self._register_dialog_handler()++ async def _register_dialog_handler(self) -> None:+ """Register CDP handler to auto-dismiss JS dialogs (alert, confirm, prompt).++ Without this, any JS dialog freezes all CDP commands until manually dismissed.+ Messages are stored in _closed_popup_messages for inclusion in state output.+ """+ import asyncio as _asyncio++ if not self._cdp_client_root:+ return++ async def handle_dialog(event_data: dict, session_id: str | None = None) -> None:+ try:+ dialog_type = event_data.get('type', 'alert')+ message = event_data.get('message', '')+ if message:+ self._closed_popup_messages.append(f'[{dialog_type}] {message}')+ # Accept alerts/confirms/beforeunload, dismiss prompts+ should_accept = dialog_type in ('alert', 'confirm', 'beforeunload')+ logger.info(f'Auto-{"accepting" if should_accept else "dismissing"} {dialog_type}: {message[:100]}')+ if not self._cdp_client_root:+ return+ await _asyncio.wait_for(+ self._cdp_client_root.send.Page.handleJavaScriptDialog(+ params={'accept': should_accept},+ session_id=session_id,+ ),+ timeout=0.5,+ )+ except Exception:+ pass++ self._cdp_client_root.register.Page.javascriptDialogOpening(handle_dialog) # type: ignore[arg-type]+async def _launch_local_browser(self) -> None:"""Launch Chromium using LocalBrowserWatchdog's launch logic."""from bubus import EventBusdiff --git a/browser_use/skill_cli/commands/browser.py b/browser_use/skill_cli/commands/browser.pyindex b82d5712e..944a51291 100644--- a/browser_use/skill_cli/commands/browser.py+++ b/browser_use/skill_cli/commands/browser.py@@ -84,21 +84,14 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> A"""Handle browser control command."""bs = session.browser_sessionactions = session.actions+ assert actions is not None, 'ActionHandler must be set on SessionInfo'if action == 'open':url = params['url']- # Ensure URL has schemeif not url.startswith(('http://', 'https://', 'file://')):url = 'https://' + url-- if actions:- await actions.navigate(url)- else:- from browser_use.browser.events import NavigateToUrlEvent-- await bs.event_bus.dispatch(NavigateToUrlEvent(url=url))+ await actions.navigate(url)result: dict[str, Any] = {'url': url}- # Add live preview URL for cloud browsersif bs.browser_profile.use_cloud and bs.cdp_url:from urllib.parse import quote@@ -108,33 +101,20 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Aelif action == 'click':args = params.get('args', [])if len(args) == 2:- # Coordinate click: browser-use click <x> <y>x, y = args- if actions:- await actions.click_coordinate(x, y)- else:- from browser_use.browser.events import ClickCoordinateEvent-- await bs.event_bus.dispatch(ClickCoordinateEvent(coordinate_x=x, coordinate_y=y))+ await actions.click_coordinate(x, y)return {'clicked_coordinate': {'x': x, 'y': y}}elif len(args) == 1:- # Index click: browser-use click <index>index = args[0]node = await bs.get_element_by_index(index)if node is None:return {'error': f'Element index {index} not found - page may have changed'}- if actions:- await actions.click_element(node)- else:- from browser_use.browser.events import ClickElementEvent-- await bs.event_bus.dispatch(ClickElementEvent(node=node))+ await actions.click_element(node)return {'clicked': index}else:return {'error': 'Usage: click <index> or click <x> <y>'}elif action == 'type':- # Type into currently focused element using CDP directlytext = params['text']cdp_session = await bs.get_or_create_cdp_session(target_id=None, focus=False)if not cdp_session:@@ -151,34 +131,18 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Anode = await bs.get_element_by_index(index)if node is None:return {'error': f'Element index {index} not found - page may have changed'}- if actions:- await actions.click_element(node)- await actions.type_text(node, text)- else:- from browser_use.browser.events import ClickElementEvent, TypeTextEvent-- await bs.event_bus.dispatch(ClickElementEvent(node=node))- await bs.event_bus.dispatch(TypeTextEvent(node=node, text=text))+ await actions.click_element(node)+ await actions.type_text(node, text)return {'input': text, 'element': index}elif action == 'scroll':direction = params.get('direction', 'down')amount = params.get('amount', 500)- if actions:- await actions.scroll(direction, amount)- else:- from browser_use.browser.events import ScrollEvent-- await bs.event_bus.dispatch(ScrollEvent(direction=direction, amount=amount))+ await actions.scroll(direction, amount)return {'scrolled': direction, 'amount': amount}elif action == 'back':- if actions:- await actions.go_back()- else:- from browser_use.browser.events import GoBackEvent-- await bs.event_bus.dispatch(GoBackEvent())+ await actions.go_back()return {'back': True}elif action == 'screenshot':@@ -193,15 +157,11 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Areturn {'screenshot': base64.b64encode(data).decode(), 'size': len(data)}elif action == 'state':- # Return the LLM representation with viewport info for coordinate clicking- if actions:- state = await actions.get_state()- else:- state = await bs.get_browser_state_summary()+ state = await actions.get_state()assert state.dom_state is not Nonestate_text = state.dom_state.llm_representation()- # Prepend viewport dimensions so LLMs know the coordinate space+ # Prepend viewport dimensionsif state.page_info:pi = state.page_infoviewport_text = f'viewport: {pi.viewport_width}x{pi.viewport_height}\n'@@ -209,12 +169,17 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Aviewport_text += f'scroll: ({pi.scroll_x}, {pi.scroll_y})\n'state_text = viewport_text + state_text+ # Append auto-dismissed popup messages+ if bs._closed_popup_messages:+ state_text += '\nAuto-closed dialogs:\n'+ for msg in bs._closed_popup_messages:+ state_text += f' {msg}\n'+ bs._closed_popup_messages.clear()+return {'_raw_text': state_text}elif action == 'switch':- from browser_use.browser.events import SwitchTabEvent-- # Use pre-resolved target_id from tab ownership (scoped to caller's tabs)+ # Backward compat alias — just update internal focus, no visual activationif '_resolved_target_id' in params:target_id = params['_resolved_target_id']else:@@ -223,13 +188,11 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Aif tab_index < 0 or tab_index >= len(page_targets):return {'error': f'Invalid tab index {tab_index}. Available: 0-{len(page_targets) - 1}'}target_id = page_targets[tab_index].target_id- await bs.event_bus.dispatch(SwitchTabEvent(target_id=target_id))+ bs.agent_focus_target_id = target_idreturn {'switched': params.get('tab', 0)}elif action == 'close-tab':- from browser_use.browser.events import CloseTabEvent-- # Use pre-resolved target_id from tab ownership (scoped to caller's tabs)+ # Backward compat alias — close via direct CDPif '_resolved_target_id' in params:target_id = params['_resolved_target_id']else:@@ -240,11 +203,12 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Areturn {'error': f'Invalid tab index {tab_index}. Available: 0-{len(page_targets) - 1}'}target_id = page_targets[tab_index].target_idelse:- # Close current/focused tabtarget_id = bs.session_manager.get_focused_target().target_id if bs.session_manager else Noneif not target_id:return {'error': 'No focused tab to close'}- await bs.event_bus.dispatch(CloseTabEvent(target_id=target_id))+ cdp_session = await bs.get_or_create_cdp_session(target_id=None, focus=False)+ if cdp_session:+ await cdp_session.cdp_client.send.Target.closeTarget(params={'targetId': target_id})return {'closed': params.get('tab')}elif action == 'tab':@@ -282,24 +246,25 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Areturn {'switched': params.get('tab', 0)}elif tab_command == 'close':- from browser_use.browser.events import CloseTabEvent-tab_indices = params.get('tabs', [])page_targets = bs.session_manager.get_all_page_targets() if bs.session_manager else []+ async def _close_target(tid: str) -> None:+ cdp_session = await bs.get_or_create_cdp_session(target_id=None, focus=False)+ if cdp_session:+ await cdp_session.cdp_client.send.Target.closeTarget(params={'targetId': tid})+if not tab_indices:- # Close current/focused tabtarget_id = bs.session_manager.get_focused_target().target_id if bs.session_manager else Noneif not target_id:return {'error': 'No focused tab to close'}- await bs.event_bus.dispatch(CloseTabEvent(target_id=target_id))+ await _close_target(target_id)return {'closed': [0]}- # Close specific tabsclosed = []errors = []- for idx in sorted(tab_indices, reverse=True): # reverse to avoid index shift+ for idx in sorted(tab_indices, reverse=True):if idx < 0 or idx >= len(page_targets):errors.append(f'Tab {idx} out of range')continue@@ -308,7 +273,7 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Aerrors.append(f'Tab {idx}: {lock_err}')continuetry:- await bs.event_bus.dispatch(CloseTabEvent(target_id=page_targets[idx].target_id))+ await _close_target(page_targets[idx].target_id)closed.append(idx)except Exception as e:errors.append(f'Tab {idx}: {e}')@@ -321,12 +286,7 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Aelif action == 'keys':keys = params['keys']- if actions:- await actions.send_keys(keys)- else:- from browser_use.browser.events import SendKeysEvent-- await bs.event_bus.dispatch(SendKeysEvent(keys=keys))+ await actions.send_keys(keys)return {'sent': keys}elif action == 'select':@@ -335,19 +295,13 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Anode = await bs.get_element_by_index(index)if node is None:return {'error': f'Element index {index} not found - page may have changed'}- if actions:- await actions.select_dropdown(node, value)- else:- from browser_use.browser.events import SelectDropdownOptionEvent-- await bs.event_bus.dispatch(SelectDropdownOptionEvent(node=node, text=value))+ await actions.select_dropdown(node, value)return {'selected': value, 'element': index}elif action == 'upload':index = params['index']file_path = params['path']- # Validate file exists and is non-emptyp = Path(file_path)if not p.exists():return {'error': f'File not found: {file_path}'}@@ -356,12 +310,10 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Aif p.stat().st_size == 0:return {'error': f'File is empty (0 bytes): {file_path}'}- # Look up nodenode = await bs.get_element_by_index(index)if node is None:return {'error': f'Element index {index} not found - page may have changed'}- # Find file input near the element (reuses core library heuristic)file_input_node = bs.find_file_input_near_element(node)if file_input_node is None:@@ -373,12 +325,7 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Ahint = ' No file input found on the page.'return {'error': f'Element {index} is not a file input.{hint}'}- if actions:- await actions.upload_file(file_input_node, file_path)- else:- from browser_use.browser.events import UploadFileEvent-- await bs.event_bus.dispatch(UploadFileEvent(node=file_input_node, file_path=file_path))+ await actions.upload_file(file_input_node, file_path)return {'uploaded': file_path, 'element': index}elif action == 'eval':diff --git a/browser_use/skill_cli/commands/python_exec.py b/browser_use/skill_cli/commands/python_exec.pyindex 770ff761e..5bb001527 100644--- a/browser_use/skill_cli/commands/python_exec.py+++ b/browser_use/skill_cli/commands/python_exec.py@@ -49,7 +49,7 @@ async def handle(session: SessionInfo, params: dict[str, Any]) -> Any:# Execute code in a thread pool so browser operations can schedule back to the event looploop = asyncio.get_running_loop()- result = await loop.run_in_executor(None, python_session.execute, code, browser_session, loop)+ result = await loop.run_in_executor(None, python_session.execute, code, browser_session, loop, session.actions)if result.success:# Return raw text output for clean displaydiff --git a/browser_use/skill_cli/daemon.py b/browser_use/skill_cli/daemon.pyindex 6e527ccc6..805e1d39c 100644--- a/browser_use/skill_cli/daemon.py+++ b/browser_use/skill_cli/daemon.py@@ -120,19 +120,10 @@ class Daemon:self._tab_ownership = TabOwnershipManager(bs)self._tab_ownership.set_agents_file(get_home_dir() / 'agents.json')- # Listen for tab lifecycle events to track ownership- from browser_use.browser.events import TabClosedEvent, TabCreatedEvent-- def _on_tab_created(event: TabCreatedEvent) -> None:- assert self._tab_ownership is not None- self._tab_ownership.on_tab_created(event.target_id)-- def _on_tab_closed(event: TabClosedEvent) -> None:- assert self._tab_ownership is not None- self._tab_ownership.on_tab_closed(event.target_id)-- bs.event_bus.on(TabCreatedEvent, _on_tab_created)- bs.event_bus.on(TabClosedEvent, _on_tab_closed)+ # Register initial tabs with tab ownership (no event bus)+ if bs.session_manager:+ for target in bs.session_manager.get_all_page_targets():+ self._tab_ownership.on_tab_created(target.target_id)# Start periodic agent cleanupself._agent_cleanup_task = asyncio.create_task(self._cleanup_stale_agents())diff --git a/browser_use/skill_cli/python_session.py b/browser_use/skill_cli/python_session.pyindex ebe458b49..cdcb23b3a 100644--- a/browser_use/skill_cli/python_session.py+++ b/browser_use/skill_cli/python_session.py@@ -10,6 +10,7 @@ from typing import TYPE_CHECKING, Any, Literalif TYPE_CHECKING:from browser_use.browser.session import BrowserSession+ from browser_use.skill_cli.actions import ActionHandler@dataclass@@ -48,7 +49,11 @@ class PythonSession:)def execute(- self, code: str, browser_session: 'BrowserSession', loop: asyncio.AbstractEventLoop | None = None+ self,+ code: str,+ browser_session: 'BrowserSession',+ loop: asyncio.AbstractEventLoop | None = None,+ actions: 'ActionHandler | None' = None,) -> ExecutionResult:"""Execute code in persistent namespace.@@ -59,10 +64,11 @@ class PythonSession:code: Python code to executebrowser_session: The browser session for browser operationsloop: The event loop for async operations (required for browser access)+ actions: Optional ActionHandler for direct execution (no event bus)"""# Inject browser wrapper with the event loop for async operationsif loop is not None:- self.namespace['browser'] = BrowserWrapper(browser_session, loop)+ self.namespace['browser'] = BrowserWrapper(browser_session, loop, actions)self.execution_count += 1stdout = io.StringIO()@@ -115,9 +121,10 @@ class BrowserWrapper:Runs coroutines on the server's event loop using run_coroutine_threadsafe."""- def __init__(self, session: 'BrowserSession', loop: asyncio.AbstractEventLoop) -> None:+ def __init__(self, session: 'BrowserSession', loop: asyncio.AbstractEventLoop, actions: 'ActionHandler | None' = None) -> None:self._session = sessionself._loop = loop+ self._actions = actionsdef _run(self, coro: Any) -> Any:"""Run coroutine on the server's event loop."""@@ -147,21 +154,27 @@ class BrowserWrapper:self._run(self._goto_async(url))async def _goto_async(self, url: str) -> None:- from browser_use.browser.events import NavigateToUrlEvent+ if self._actions:+ await self._actions.navigate(url)+ else:+ from browser_use.browser.events import NavigateToUrlEvent- await self._session.event_bus.dispatch(NavigateToUrlEvent(url=url))+ await self._session.event_bus.dispatch(NavigateToUrlEvent(url=url))def click(self, index: int) -> None:"""Click element by index."""self._run(self._click_async(index))async def _click_async(self, index: int) -> None:- from browser_use.browser.events import ClickElementEvent-node = await self._session.get_element_by_index(index)if node is None:raise ValueError(f'Element index {index} not found')- await self._session.event_bus.dispatch(ClickElementEvent(node=node))+ if self._actions:+ await self._actions.click_element(node)+ else:+ from browser_use.browser.events import ClickElementEvent++ await self._session.event_bus.dispatch(ClickElementEvent(node=node))def type(self, text: str) -> None:"""Type text into focused element."""@@ -181,13 +194,17 @@ class BrowserWrapper:self._run(self._input_async(index, text))async def _input_async(self, index: int, text: str) -> None:- from browser_use.browser.events import ClickElementEvent, TypeTextEvent-node = await self._session.get_element_by_index(index)if node is None:raise ValueError(f'Element index {index} not found')- await self._session.event_bus.dispatch(ClickElementEvent(node=node))- await self._session.event_bus.dispatch(TypeTextEvent(node=node, text=text))+ if self._actions:+ await self._actions.click_element(node)+ await self._actions.type_text(node, text)+ else:+ from browser_use.browser.events import ClickElementEvent, TypeTextEvent++ await self._session.event_bus.dispatch(ClickElementEvent(node=node))+ await self._session.event_bus.dispatch(TypeTextEvent(node=node, text=text))def upload(self, index: int, path: str) -> None:"""Upload a file to a file input element."""@@ -196,8 +213,6 @@ class BrowserWrapper:async def _upload_async(self, index: int, path: str) -> None:from pathlib import Path as P- from browser_use.browser.events import UploadFileEvent-file_path = str(P(path).expanduser().resolve())p = P(file_path)if not p.exists():@@ -215,16 +230,24 @@ class BrowserWrapper:if file_input_node is None:raise ValueError(f'Element {index} is not a file input and no file input found nearby')- await self._session.event_bus.dispatch(UploadFileEvent(node=file_input_node, file_path=file_path))+ if self._actions:+ await self._actions.upload_file(file_input_node, file_path)+ else:+ from browser_use.browser.events import UploadFileEvent++ await self._session.event_bus.dispatch(UploadFileEvent(node=file_input_node, file_path=file_path))def scroll(self, direction: Literal['up', 'down', 'left', 'right'] = 'down', amount: int = 500) -> None:"""Scroll the page."""self._run(self._scroll_async(direction, amount))async def _scroll_async(self, direction: Literal['up', 'down', 'left', 'right'], amount: int) -> None:- from browser_use.browser.events import ScrollEvent+ if self._actions:+ await self._actions.scroll(direction, amount)+ else:+ from browser_use.browser.events import ScrollEvent- await self._session.event_bus.dispatch(ScrollEvent(direction=direction, amount=amount))+ await self._session.event_bus.dispatch(ScrollEvent(direction=direction, amount=amount))def screenshot(self, path: str | None = None) -> bytes:"""Take screenshot, optionally save to file."""@@ -261,18 +284,24 @@ class BrowserWrapper:self._run(self._keys_async(keys))async def _keys_async(self, keys: str) -> None:- from browser_use.browser.events import SendKeysEvent+ if self._actions:+ await self._actions.send_keys(keys)+ else:+ from browser_use.browser.events import SendKeysEvent- await self._session.event_bus.dispatch(SendKeysEvent(keys=keys))+ await self._session.event_bus.dispatch(SendKeysEvent(keys=keys))def back(self) -> None:"""Go back in history."""self._run(self._back_async())async def _back_async(self) -> None:- from browser_use.browser.events import GoBackEvent+ if self._actions:+ await self._actions.go_back()+ else:+ from browser_use.browser.events import GoBackEvent- await self._session.event_bus.dispatch(GoBackEvent())+ await self._session.event_bus.dispatch(GoBackEvent())def wait(self, seconds: float) -> None:"""Wait for specified seconds."""