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 add_new_task for eventbus
Magnus Müller1e400c3da1b6
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 534923b07..3ea492dfb 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -637,6 +637,13 @@ class Agent(Generic[Context, AgentStructuredOutput]):# The task continues with new instructions, it doesn't end and start a new oneself.task = new_taskself._message_manager.add_new_task(new_task)+ # Mark as follow-up task and recreate eventbus (gets shut down after each run)+ self.state.follow_up_task = True+ self.eventbus = EventBus(name=f'Agent_{str(self.id)[-self.state.n_steps :]}')++ # Re-register cloud sync handler if it exists (if not disabled)+ if hasattr(self, 'cloud_sync') and self.cloud_sync and self.enable_cloud_sync:+ self.eventbus.on('*', self.cloud_sync.handle_event)@observe_debug(ignore_input=True, ignore_output=True, name='_raise_if_stopped_or_paused')async def _raise_if_stopped_or_paused(self) -> None:@@ -1314,7 +1321,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.logger.debug('🔧 Browser session started with watchdogs attached')# Check if task contains a URL and add it as an initial action (only if preload is enabled)- if self.preload:+ if self.preload and not self.state.follow_up_task:initial_url = self._extract_url_from_task(self.task)if initial_url:self.logger.info(f'🔗 Found URL in task: {initial_url}, adding as initial action...')@@ -1347,7 +1354,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.logger.debug(f'✅ Added navigation to {initial_url} as initial action')# Execute initial actions if provided- if self.initial_actions:+ if self.initial_actions and not self.state.follow_up_task:self.logger.debug(f'⚡ Executing {len(self.initial_actions)} initial actions...')result = await self.multi_act(self.initial_actions, check_for_new_elements=False)self.state.last_result = result@@ -1509,7 +1516,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):# Stop the event bus gracefully, waiting for all events to be processed# Use longer timeout to avoid deadlocks in tests with multiple agents- await self.eventbus.stop(timeout=10.0)+ await self.eventbus.stop(timeout=3.0)await self.close()diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 1bbc570aa..0a4afeb29 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -70,6 +70,7 @@ class AgentState(BaseModel):paused: bool = Falsestopped: bool = Falsesession_initialized: bool = False # Track if session events have been dispatched+ follow_up_task: bool = False # Track if the agent is a follow-up taskmessage_manager_state: MessageManagerState = Field(default_factory=MessageManagerState)file_system_state: FileSystemState | None = Nonediff --git a/examples/features/follow_up_tasks.py b/examples/features/follow_up_tasks.pyindex 229d2eb29..cb0044fbd 100644--- a/examples/features/follow_up_tasks.py+++ b/examples/features/follow_up_tasks.py@@ -2,46 +2,34 @@ import asyncioimport osimport sys+from browser_use.browser.profile import BrowserProfile+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))from dotenv import load_dotenvload_dotenv()-from browser_use import Agent, ChatOpenAI, Controller-from browser_use.browser import BrowserProfile, BrowserSession--# Initialize the model-llm = ChatOpenAI(- model='gpt-4.1',- temperature=0.0,-)-# Get your chrome path-browser_session = BrowserSession(- browser_profile=BrowserProfile(- executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',- keep_alive=True,- user_data_dir='~/.config/browseruse/profiles/default',- ),-)--controller = Controller()+from browser_use import Agent+profile = BrowserProfile(keep_alive=True)-task = 'Find the founders of browser-use and draft them a short personalized message'-agent = Agent(task=task, llm=llm, controller=controller, browser_session=browser_session)+task = """Go to reddit.com"""async def main():- await agent.run()-- # new_task = input('Type in a new task: ')- new_task = 'Find an image of the founders'-- agent.add_new_task(new_task)-- await agent.run()+ agent = Agent(task=task, browser_profile=profile)+ await agent.run(max_steps=1)+ while True:+ user_response = input('\n👤 New task or "q" to quit: ')+ print()+ if user_response == 'q':+ break++ print(f'🟢 Continuing with your input: {user_response}')+ agent.add_new_task(f'New task: {user_response}')+ await agent.run()if __name__ == '__main__':