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 re-use of BrowserSession between agents by copying on Agent init
Nick Sweetinga5b99f9b7fc0
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 3f65d084b..e7f687de6 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -292,12 +292,22 @@ class Agent(Generic[Context]):# assert not (browser and browser_context), 'Cannot provide both browser and browser_context'# assert not (browser_session and browser_context), 'Cannot provide both browser_session and browser_context'browser_profile = browser_profile or DEFAULT_BROWSER_PROFILE- self.browser_session = browser_session or BrowserSession(- profile=browser_profile,- browser=browser,- browser_context=browser_context,- page=page,- )++ if browser_session:+ # always copy sessions that are passed in to avoid conflicting with other agents sharing the same session+ self.browser_session = browser_session.model_copy(+ update={+ 'agent_current_page': None,+ 'human_current_page': None,+ },+ )+ else:+ self.browser_session = BrowserSession(+ browser_profile=browser_profile,+ browser=browser,+ browser_context=browser_context,+ page=page,+ )if self.sensitive_data:# Check if sensitive_data has domain-specific credentialsdiff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 535a7782c..565d26316 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -115,9 +115,7 @@ class BrowserSession(BaseModel):revalidate_instances='always',frozen=False,arbitrary_types_allowed=True,- validate_by_name=True,- validate_by_alias=True,- from_attributes=True,+ populate_by_name=True,)# this class accepts arbitrary extra **kwargs in init because of the extra='allow' pydantic option# they are saved on the model, then applied to self.browser_profile via .apply_session_overrides_to_profile()@@ -196,8 +194,10 @@ class BrowserSession(BaseModel):# FOR REPL DEBUGGING ONLY, NEVER ALLOW CIRCULAR REFERENCES IN REAL CODE:# self.browser_profile._in_use_by_session = self- # replace browser_profile with patched version- self.browser_profile = self.browser_profile.model_copy(update=profile_overrides)+ # Only create a copy if there are actual overrides to apply+ if profile_overrides:+ # replace browser_profile with patched version+ self.browser_profile = self.browser_profile.model_copy(update=profile_overrides)# FOR REPL DEBUGGING ONLY, NEVER ALLOW CIRCULAR REFERENCES IN REAL CODE:# self.browser_profile._in_use_by_session = self@@ -433,10 +433,15 @@ class BrowserSession(BaseModel):# playwright does not give us a browser object at all when we use launch_persistent_context()!# Detect any new child chrome processes that we might have launched above- child_pids_after_launch = {child.pid for child in current_process.children(recursive=True)}- new_child_pids = child_pids_after_launch - child_pids_before_launch- new_child_procs = [psutil.Process(pid) for pid in new_child_pids]- new_chrome_procs = [proc for proc in new_child_procs if 'Helper' not in proc.name() and proc.status() == 'running']+ try:+ child_pids_after_launch = {child.pid for child in current_process.children(recursive=True)}+ new_child_pids = child_pids_after_launch - child_pids_before_launch+ new_child_procs = [psutil.Process(pid) for pid in new_child_pids]+ new_chrome_procs = [proc for proc in new_child_procs if 'Helper' not in proc.name() and proc.status() == 'running']+ except Exception as e:+ logger.debug(f'❌ Error trying to find child chrome processes after launching new browser: {type(e).__name__}: {e}')+ new_chrome_procs = []+if new_chrome_procs and not self.browser_pid:self.browser_pid = new_chrome_procs[0].pidlogger.debug(diff --git a/examples/features/multiple_agents_same_browser.py b/examples/features/multiple_agents_same_browser.pyindex 59c21df0f..a7ff00532 100644--- a/examples/features/multiple_agents_same_browser.py+++ b/examples/features/multiple_agents_same_browser.py@@ -2,34 +2,37 @@ import asyncioimport osimport sys+from langchain_openai import ChatOpenAI++from browser_use.browser.session import BrowserSession+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent, BrowserSession+from browser_use import Agent# Video: https://preview.screen.studio/share/8Elaq9smasync def main():# Persist the browser state across agents-browser_session = BrowserSession(keep_alive=True,user_data_dir=None,)await browser_session.start()- model = ChatOpenAI(model='gpt-4o')- current_agent = Noneasync def get_input():return await asyncio.get_event_loop().run_in_executor(None, lambda: input('Enter task (p: pause current agent, r: resume, b: break): '))+ current_agent = None+ llm = ChatOpenAI(model='gpt-4o')+while True:task = await get_input()@@ -51,14 +54,14 @@ async def main():continue# If there's a current agent running, pause it before starting new one- if current_agent:- current_agent.pause()+ # if current_agent:+ # current_agent.pause()- # Create and run new agent with the task+ await browser_session.create_new_tab()current_agent = Agent(task=task,- llm=model,browser_session=browser_session,+ llm=llm,)# Run the agent asynchronously without blocking