Skip to content

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

Merge branch 'main' into bug-bash

Nick Sweeting22bf1c30c6c7
diff --cc browser_use/browser/session.py
index 232fa8f77,a833cc62f..047f1a2b7
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@@ -165,8 -187,9 +187,9 @@@ class BrowserSession(BaseModel)
"""Apply any extra **kwargs passed to BrowserSession(...) as config overrides on top of browser_profile"""
session_own_fields = type(self).model_fields.keys()
- # get all the extra BrowserProfile kwarg overrides passed to BrowserSession(...) that are not Fields on self
- overrides = self.model_dump(exclude=set(session_own_fields))
+ # get all the extra kwarg overrides passed to BrowserSession(...) that are actually
+ # config Fields tracked by BrowserProfile, instead of BrowserSession's own args
- profile_overrides = self.model_dump(exclude=session_own_fields)
++ profile_overrides = self.model_dump(exclude=set(session_own_fields))
# FOR REPL DEBUGGING ONLY, NEVER ALLOW CIRCULAR REFERENCES IN REAL CODE:
# self.browser_profile._in_use_by_session = self
@@@ -254,59 -299,77 +299,77 @@@
# # patchright handles all its own default args, dont mess with them
# self.browser_profile.ignore_default_args = True
- return self.playwright
+ # return self.playwright
- async def setup_browser_connection(self) -> None:
+ async def setup_browser_via_passed_objects(self) -> None:
"""Override to customize the set up of the connection to an existing browser"""
- # if process is provided, calcuclate its CDP URL by looking for --remote-debugging-port=... in the launch args
- if self.chrome_pid:
- chrome_process = psutil.Process(pid=self.chrome_pid)
- assert chrome_process.is_running(), 'Chrome process is not running'
- args = chrome_process.cmdline()
- debug_port = next((arg for arg in args if arg.startswith('--remote-debugging-port=')), '').split('=')[-1].strip()
- assert debug_port, (
- f'Could not connect because could not find --remote-debugging-port=... in chrome launch args: pid={self.chrome_pid} {args}'
- )
- # we could automatically relaunch the browser process with that arg added here, but they may have tabs open they dont want to lose
- self.cdp_url = self.cdp_url or f'http://localhost:{debug_port}/'
- logger.info(f'🌎 Connecting to existing chromium process: pid={self.chrome_pid} on {self.cdp_url}')
-
- if self.wss_url:
- logger.info(f'🌎 Connecting to remote chromium playwright node.js server over WSS: {self.wss_url}')
- assert self.playwright, 'Playwright object is not set'
- self.browser = self.browser or await self.playwright.chromium.connect(
- self.wss_url,
- **self.browser_profile.kwargs_for_connect().model_dump(),
- )
- # dont default to closing the browser when the BrowserSession is over if we connect by WSS
- if self.browser_profile.keep_alive is None:
- self.browser_profile.keep_alive = True
- elif self.cdp_url:
- logger.info(f'🌎 Connecting to remote chromium browser over CDP: {self.cdp_url}')
- self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(
- self.cdp_url,
- **self.browser_profile.kwargs_for_connect().model_dump(),
- )
- # dont default to closing the browser when the BrowserSession is over if we connect by CDP
- if self.browser_profile.keep_alive is None:
- self.browser_profile.keep_alive = True
+ # 1. check for a passed Page object, if present, it always takes priority, set browser_context = page.context
+ self.browser_context = (self.agent_current_page and self.agent_current_page.context) or self.browser_context or None
- # self.browser may still be None at this point if we have no config implying we should connect to an existing browser
- # self.setup_browser_context() will be called next and if it finds self.browser is None, it will
- # launch a new browser+context all in one go using launch_persistent_context()
+ # 2. if we have a context now, it always takes precedence, set browser = context.browser, otherwise use the passed browser
+ self.browser = (self.browser_context and self.browser_context.browser) or self.browser or None
- # return self.browser
+ if self.browser or self.browser_context:
+ logger.info(f'🌎 Connected to existing user-provided browser_context: {self.browser_context}')
+ self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end
- async def setup_browser_context(self) -> None:
- # if we have a browser_context but no browser, use the browser from the context
- if self.browser_context:
- logger.info(f'🌎 Using existing user-provided browser_context and browser: {self.browser_context}')
- self.browser = self.browser or self.browser_context.browser
- # dont default to closing the browser when the BrowserSession is over if we are passed an external browser
- if self.browser_profile.keep_alive is None:
- self.browser_profile.keep_alive = True
+ async def setup_browser_via_browser_pid(self) -> None:
+ """if browser_pid is provided, calcuclate its CDP URL by looking for --remote-debugging-port=... in its CLI args, then connect to it"""
+
+ if self.browser or self.browser_context:
+ return # already connected to a browser
+ if not self.browser_pid:
+ return # no browser_pid provided, nothing to do
+
+ chrome_process = psutil.Process(pid=self.browser_pid)
+ assert chrome_process.is_running(), 'Chrome process is not running'
+ args = chrome_process.cmdline()
+ debug_port = next((arg for arg in args if arg.startswith('--remote-debugging-port=')), '').split('=')[-1].strip()
+ assert debug_port, (
+ f'Could not find --remote-debugging-port=... to connect to in browser launch args: browser_pid={self.browser_pid} {args}'
+ )
+ # we could automatically relaunch the browser process with that arg added here, but they may have tabs open they dont want to lose
+ self.cdp_url = self.cdp_url or f'http://localhost:{debug_port}/'
+ logger.info(f'🌎 Connecting to existing local browser process: browser_pid={self.browser_pid} on {self.cdp_url}')
+ self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(
+ self.cdp_url,
+ **self.browser_profile.kwargs_for_connect().model_dump(),
+ )
+ self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end
+ async def setup_browser_via_wss_url(self) -> None:
+ """check for a passed wss_url, connect to a remote playwright browser server via WSS"""
+
+ if self.browser or self.browser_context:
+ return # already connected to a browser
+ if not self.wss_url:
+ return # no wss_url provided, nothing to do
+
+ logger.info(f'🌎 Connecting to existing remote chromium playwright node.js server over WSS: {self.wss_url}')
+ self.browser = self.browser or await self.playwright.chromium.connect(
+ self.wss_url,
+ **self.browser_profile.kwargs_for_connect().model_dump(),
+ )
+ self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end
+
+ async def setup_browser_via_cdp_url(self) -> None:
+ """check for a passed cdp_url, connect to a remote chromium-based browser via CDP"""
+
+ if self.browser or self.browser_context:
+ return # already connected to a browser
+ if not self.cdp_url:
+ return # no cdp_url provided, nothing to do
+
+ logger.info(f'🌎 Connecting to existing remote chromium-based browser over CDP: {self.cdp_url}')
+ self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(
+ self.cdp_url,
+ **self.browser_profile.kwargs_for_connect().model_dump(),
+ )
+ self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end
+
+ async def setup_new_browser_context(self) -> None:
+ """Launch a new browser and browser_context"""
current_process = psutil.Process(os.getpid())
child_pids_before_launch = {child.pid for child in current_process.children(recursive=True)}