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
Merge remote-tracking branch 'origin/main' into laminar-ignore-input-output
Magnus Müller48c903556637
diff --cc browser_use/browser/session.pyindex 0db85cdcd,dab45f760..989f470ce--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@@ -681,10 -749,10 +749,10 @@@ class BrowserSession(BaseModel)trace_filename = f'BrowserSession_{self.id}.zip'final_trace_path = traces_path / trace_filename- self.logger.info(f'🎥 Saving browser context trace to {final_trace_path}...')+ self.logger.info(f'🎥 Saving browser_context trace to {final_trace_path}...')await self.browser_context.tracing.stop(path=str(final_trace_path))- @observe_debug(name='connect_or_launch_browser')+ @observe_debug(ignore_input=True, ignore_output=True, name='connect_or_launch_browser')async def _connect_or_launch_browser(self) -> None:"""Try all connection methods in order of precedence."""# Try connecting via passed objects first@@@ -710,77 -778,9 +778,9 @@@# Launch new browser as last resortawait self.setup_new_browser_context()- @observe_debug(ignore_input=True, ignore_output=True)- @retry(- wait=1, # wait 1s between each attempt to take a screenshot- retries=1, # try up to 1 time to take the screenshot (2 total attempts)- timeout=12, # allow up to 12s for each attempt to take a screenshot- semaphore_limit=2, # Allow 2 screenshots at a time to better utilize resources- semaphore_name='screenshot_global',- semaphore_scope='multiprocess',- semaphore_lax=True, # Continue without semaphore if it can't be acquired- semaphore_timeout=15, # Wait up to 15s for semaphore acquisition- )- async def _take_screenshot_hybrid(self, clip: dict[str, int] | None = None) -> str:- """Take screenshot using Playwright, with retry and semaphore protection."""- # Use Playwright screenshot directly-- page = await self.get_current_page()- assert self.browser_context- # try:- # # get fresh page handle- # page = [p for p in self.browser_context.pages if p.url == page.url][0]- # except Exception:- # pass- assert await page.evaluate('() => true'), 'Page is not usable before screenshot!'-- try:- await page.bring_to_front()- await page.wait_for_load_state('load', timeout=8000)- except Exception:- pass-- screenshot_b64 = None- cdp_session = None- try:- # Use a shorter timeout for screenshots to prevent semaphore starvation- # 10 seconds should be enough for most screenshots- # screenshot = await page.screenshot(- # full_page=False,- # # scale='css',- # timeout=screenshot_timeout,- # # clip=FloatRect(**clip) if clip else None,- # animations='allow',- # caret='initial',- #- cdp_session = await page.context.new_cdp_session(page) # type: ignore- screenshot = await cdp_session.send(- 'Page.captureScreenshot',- {- 'captureBeyondViewport': False,- 'fromSurface': True,- 'format': 'png',- # 'clip': clip,- },- )- screenshot_b64 = screenshot['data']- except Exception as err:- # Don't reset browser on timeout - this can cause semaphore deadlocks- # Just re-raise the error and let the retry decorator handle it- if 'timeout' in str(err).lower():- self.logger.warning(f'⏱️ Screenshot timed out on page {page.url}: {err}')- raise err- finally:- try:- assert cdp_session- await cdp_session.detach()- except Exception:- pass- assert await page.evaluate('() => true'), 'Page is not usable after screenshot!'- assert screenshot_b64, 'Playwright page.screenshot() returned empty base64'- return screenshot_b64+ # Removed _take_screenshot_hybrid - merged into take_screenshot- @observe_debug(name='setup_playwright')+ @observe_debug(ignore_input=True, ignore_output=True, name='setup_playwright')@retry(wait=1,retries=3,@@@ -2908,9 -3047,9 +3049,9 @@@structure = await page.evaluate(debug_script)return structure- @observe_debug(ignore_output=True)+ @observe_debug(ignore_input=True, ignore_output=True)@time_execution_async('--get_state_summary')- @require_initialization+ @require_healthy_browser(usable_page=True, reopen_page=True)async def get_state_summary(self, cache_clickable_elements_hashes: bool) -> BrowserStateSummary:self.logger.debug('🔄 Starting get_state_summary...')"""Get a summary of the current browser state@@@ -2952,8 -3091,8 +3093,8 @@@return self._cached_browser_state_summary- @observe_debug(name='get_minimal_state_summary', ignore_output=True)+ @observe_debug(ignore_input=True, ignore_output=True, name='get_minimal_state_summary')- @require_initialization+ @require_healthy_browser(usable_page=True, reopen_page=True)@time_execution_async('--get_minimal_state_summary')async def get_minimal_state_summary(self) -> BrowserStateSummary:"""Get basic page info without DOM processing, but try to capture screenshot"""@@@ -3140,50 -3279,340 +3281,340 @@@return self.browser_state_summaryraise+ # region - Page Health Check Helpers-++ @observe_debug(ignore_output=True)+ async def _is_page_responsive(self, page: Page, timeout: float = 5.0) -> bool:+ """Check if a page is responsive by trying to evaluate simple JavaScript."""+ eval_task = None+ try:+ eval_task = asyncio.create_task(page.evaluate('1'))+ done, pending = await asyncio.wait([eval_task], timeout=timeout)++ if eval_task in done:+ try:+ await eval_task # This will raise if the evaluation failed+ return True+ except Exception:+ return False+ else:+ # Timeout - the page is unresponsive+ return False+ except Exception:+ return False+ finally:+ # Always clean up the eval task+ if eval_task and not eval_task.done():+ eval_task.cancel()+ try:+ await eval_task+ except (asyncio.CancelledError, Exception):+ pass++ async def _force_close_page_via_cdp(self, page_url: str) -> bool:+ """Force close a crashed page using CDP from a clean temporary page."""+ try:+ # self.logger.info('🔨 Creating temporary page for CDP force-close...')++ # Create a clean page for CDP operations+ assert self.browser_context, 'Browser context is not set up yet'+ temp_page = await asyncio.wait_for(self.browser_context.new_page(), timeout=5.0)+ await asyncio.wait_for(temp_page.goto('about:blank'), timeout=2.0)++ # Create CDP session from the clean page+ cdp_session = await asyncio.wait_for(self.browser_context.new_cdp_session(temp_page), timeout=5.0) # type: ignore++ try:+ # Get all browser targets+ targets = await asyncio.wait_for(cdp_session.send('Target.getTargets'), timeout=2.0)++ # Find the crashed page target+ blocked_target_id = None+ for target in targets.get('targetInfos', []):+ if target.get('type') == 'page' and target.get('url') == page_url:+ blocked_target_id = target.get('targetId')+ # self.logger.debug(f'Found target to close: {page_url}')+ break++ if blocked_target_id:+ # Force close the target+ self.logger.warning(+ f'🪓 Force-closing crashed page target_id={blocked_target_id} via CDP: {_log_pretty_url(page_url)}...'+ )+ await asyncio.wait_for(cdp_session.send('Target.closeTarget', {'targetId': blocked_target_id}), timeout=2.0)+ # self.logger.debug(f'☠️ Successfully force-closed crashed page target_id={blocked_target_id} via CDP: {_log_pretty_url(page_url)}')+ return True+ else:+ self.logger.debug(+ f'❌ Could not find CDP page target_id to force-close: {_log_pretty_url(page_url)} (concurrency issues?)'+ )+ return False++ finally:+ # Clean up+ try:+ await asyncio.wait_for(cdp_session.detach(), timeout=1.0)+ except Exception:+ pass+ await temp_page.close()++ except Exception as e:+ self.logger.error(f'❌ Using raw CDP to force-close crashed page failed: {type(e).__name__}: {e}')+ return False++ async def _try_reopen_url(self, url: str, timeout_ms: int | None = None) -> bool:+ """Try to reopen a URL in a new page and check if it's responsive."""+ if not url or is_new_tab_page(url):+ return False++ timeout_ms = int(timeout_ms or self.browser_profile.default_navigation_timeout or 6000)++ try:+ self.logger.debug(f'🔄 Attempting to reload URL that crashed: {_log_pretty_url(url)}')++ # Create new page directly to avoid circular dependency+ assert self.browser_context is not None, 'Browser context is not set'+ new_page = await self.browser_context.new_page()+ self.agent_current_page = new_page++ # Update human tab reference if there is no human tab yet+ if (not self.human_current_page) or self.human_current_page.is_closed():+ self.human_current_page = new_page++ # Set viewport for new tab+ if self.browser_profile.viewport:+ await new_page.set_viewport_size(self.browser_profile.viewport)++ # Navigate with timeout using asyncio.wait+ nav_task = asyncio.create_task(new_page.goto(url, wait_until='load', timeout=timeout_ms))+ done, pending = await asyncio.wait([nav_task], timeout=(timeout_ms + 500) / 1000)++ if nav_task in pending:+ # Navigation timed out+ self.logger.debug(+ f'⚠️ Attempting to reload previously crashed URL {_log_pretty_url(url)} failed again, timed out again after {timeout_ms / 1000}s'+ )+ nav_task.cancel()+ try:+ await nav_task+ except asyncio.CancelledError:+ pass+ elif nav_task in done:+ try:+ await nav_task # This will raise if navigation failed+ except Exception as e:+ self.logger.debug(+ f'⚠️ Attempting to reload previously crashed URL {_log_pretty_url(url)} failed again: {type(e).__name__}'+ )++ # Wait a bit for any transient blocking to resolve+ await asyncio.sleep(1.0)++ # Check if the reopened page is responsive+ # self.logger.debug('Checking if reopened page is responsive...')+ is_responsive = await self._is_page_responsive(new_page, timeout=2.0)++ if is_responsive:+ self.logger.info(f'✅ Page recovered and is now responsive after reopening on: {_log_pretty_url(url)}')+ return True+ else:+ self.logger.warning(f'⚠️ Reopened page {_log_pretty_url(url)} is still unresponsive')+ # Close the unresponsive page before returning+ # This is critical to prevent the recovery flow from hanging+ try:+ await self._force_close_page_via_cdp(new_page.url)+ except Exception as e:+ self.logger.error(+ f'❌ Failed to close crashed page {_log_pretty_url(url)} via CDP: {type(e).__name__}: {e} (something is very wrong or system is extremely overloaded)'+ )+ self.agent_current_page = None # Clear reference to closed page+ return False++ except Exception as e:+ self.logger.error(f'❌ Retrying crashed page {_log_pretty_url(url)} failed: {type(e).__name__}: {e}')+ return False++ async def _create_blank_fallback_page(self, url: str) -> None:+ """Create a new blank page as a fallback when recovery fails."""+ self.logger.warning(+ f'⚠️ Resetting to about:blank as fallback because browser is unable to load the original URL without crashing: {_log_pretty_url(url)}'+ )+ # self.logger.debug(f'Current agent_current_page: {self.agent_current_page}')++ # Close any existing broken page+ if self.agent_current_page and not self.agent_current_page.is_closed():+ try:+ await self.agent_current_page.close()+ except Exception:+ pass++ # Create fresh page directly (avoid decorated methods to prevent circular dependency)+ assert self.browser_context is not None, 'Browser context is not set'+ new_page = await self.browser_context.new_page()+ self.agent_current_page = new_page++ # Update human tab reference if there is no human tab yet+ if (not self.human_current_page) or self.human_current_page.is_closed():+ self.human_current_page = new_page++ # Set viewport for new tab+ if self.browser_profile.viewport:+ await new_page.set_viewport_size(self.browser_profile.viewport)++ # Navigate to blank+ try:+ await new_page.goto('about:blank', wait_until='load', timeout=5000)+ except Exception as e:+ self.logger.error(+ f'❌ Failed to navigate to about:blank: {type(e).__name__}: {e} (something is very wrong or system is extremely overloaded)'+ )+ raise++ # Verify it's responsive+ if not await self._is_page_responsive(new_page, timeout=1.0):+ raise BrowserError(+ 'Browser is unable to load any new about:blank pages (something is very wrong or browser is extremely overloaded)'+ )++ async def _recover_unresponsive_page(self, calling_method: str, timeout_ms: int | None = None) -> None:+ """Recover from an unresponsive page by closing and reopening it."""+ self.logger.warning(f'⚠️ Page JS engine became unresponsive in {calling_method}(), attempting recovery...')+ timeout_ms = min(3000, int(timeout_ms or self.browser_profile.default_navigation_timeout or 5000))++ # Prevent re-entrance+ self._in_recovery = True+ try:+ # Get current URL before recovery+ assert self.agent_current_page, 'Agent current page is not set'+ current_url = self.agent_current_page.url+ # self.logger.debug(f'Current URL: {current_url}')++ # Clear page references+ blocked_page = self.agent_current_page+ self.agent_current_page = None+ if blocked_page == self.human_current_page:+ self.human_current_page = None++ # Force-close the crashed page via CDP+ self.logger.debug('🪓 Page Recovery Step 1/3: Force-closing crashed page via CDP...')+ await self._force_close_page_via_cdp(current_url)++ # Remove the closed page from browser_context.pages by forcing a refresh+ # This prevents TargetClosedError when iterating through pages later+ if self.browser_context and self.browser_context.pages:+ # Additional cleanup: close any page objects that have the same url as the crashed page+ # (could close too many pages by accident if we have a few different tabs on the same URL)+ # Sometimes playwright doesn't immediately remove force-closed pages from the list+ for page in self.browser_context.pages[:]: # Use slice to avoid modifying list during iteration+ if page.url == current_url and not page.is_closed() and not is_new_tab_page(page.url):+ try:+ # Try to close it via playwright as well+ await page.close()+ self.logger.debug(+ f'🪓 Closed 🅟 {str(id(page))[-2:]} because it has a known crash-causing URL: {_log_pretty_url(page.url)}'+ )+ except Exception:+ pass # Page might already be closed via CDP++ # Try to reopen the URL (in case blocking was transient)+ self.logger.debug('🍼 Page Recovery Step 2/3: Trying to reopen the URL again...')+ if await self._try_reopen_url(current_url, timeout_ms=timeout_ms):+ self.logger.debug('✅ Page Recovery Step 3/3: Page loading succeeded after 2nd attempt!')+ return # Success!++ # If that failed, fall back to blank page+ self.logger.debug(+ '❌ Page Recovery Step 3/3: Loading the page a 2nd time failed as well, browser seems unable to load this URL without getting stuck, retreating to a safe page...'+ )+ await self._create_blank_fallback_page(current_url)++ finally:+ # Always clear recovery flag+ self._in_recovery = False+# region - Browser Actions- @observe_debug(ignore_input=True, ignore_output=True, name='take_screenshot')- @require_initialization+ @observe_debug(name='take_screenshot', ignore_output=True)+ @retry(+ retries=1, # try up to 1 time to take the screenshot (2 total attempts)+ timeout=30, # allow up to 30s for each attempt (includes recovery time)+ wait=1, # wait 1s between each attempt+ semaphore_limit=2, # Allow 2 screenshots at a time to better utilize resources+ semaphore_name='screenshot_global',+ semaphore_scope='multiprocess',+ semaphore_lax=True, # Continue without semaphore if it can't be acquired+ semaphore_timeout=15, # Wait up to 15s for semaphore acquisition+ )+ @require_healthy_browser(usable_page=True, reopen_page=True)@time_execution_async('--take_screenshot')- async def take_screenshot(self, full_page: bool = False) -> str:+ async def take_screenshot(self, full_page: bool = False) -> str | None:"""- Returns a base64 encoded screenshot of the current page.+ Returns a base64 encoded screenshot of the current page using CDP.++ The decorator order ensures:+ 1. @retry runs first (outer decorator)+ 2. @require_healthy_browser runs on each retry attempt+ 3. Page responsiveness is checked before each screenshot attempt+ 4. If page is unresponsive, it's recovered and the method is retried"""assert self.agent_current_page is not None, 'Agent current page is not set'+ assert self.browser_context, 'Browser context is not set'++ page = self.agent_current_page+ if is_new_tab_page(page.url):+ self.logger.warning(+ f'▫️ Sending LLM 1px placeholder instead of real screenshot of: {_log_pretty_url(page.url)} (page empty)'+ )+ # not an exception because there's no point in retrying if we hit this, its always pointless to screenshot about:blank+ # raise ValueError('Refusing to take unneeded screenshot of empty new tab page')+ # return a 1px*1px white png to avoid wasting tokens+ return 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII='++ # Always bring page to front before rendering, otherwise it crashes in some cases, not sure whytry:- # Take screenshot with comprehensive crash detection- return await self._take_screenshot_hybrid()- except Exception as e:- # Check for specific crash-related errors- error_str = str(e).lower()- if any(- crash_indicator in error_str- for crash_indicator in [- 'target crashed',- 'target closed',- 'context has been closed',- 'page has been closed',- 'crashed target',- 'page is closed',- 'timeout', # Add timeout to trigger reconnection with fresh page- ]- ):- self.logger.warning(f'🚨 Detected crashed target during screenshot: {type(e).__name__}: {e}')- self.logger.warning('🔄 Attempting browser restart...')- try:- self._reset_connection_state()- await self.start()- result = await self._take_screenshot_hybrid()- self.logger.info('✅ Screenshot successful after browser restart')- return result- except Exception as restart_error:- self.logger.error(- f'❌ Failed to restart browser after crash: {type(restart_error).__name__}: {restart_error}'- )- raise Exception(f'Browser crashed and restart failed: {restart_error}')+ await page.bring_to_front()+ except Exception:+ pass++ # Take screenshot using CDP to get around playwright's unnecessary slowness and weird behavior+ cdp_session = None+ try:+ # Create CDP session for the screenshot+ self.logger.debug(+ f'📸 Taking viewport-only PNG screenshot of page via fresh CDP session: {_log_pretty_url(page.url)}'+ )+ cdp_session = await self.browser_context.new_cdp_session(page) # type: ignore++ # Capture screenshot via CDP+ screenshot_response = await cdp_session.send(+ 'Page.captureScreenshot',+ {+ 'captureBeyondViewport': False,+ 'fromSurface': True,+ 'format': 'png',+ },+ )++ screenshot_b64 = screenshot_response.get('data')+ if not screenshot_b64:+ raise Exception(+ f'CDP returned empty screenshot data for page {_log_pretty_url(page.url)}? (expected png base64)'+ ) # have never seen this happen in practice++ return screenshot_b64++ except Exception as err:+ error_str = f'{type(err).__name__}: {err}'+ if 'timeout' in error_str.lower():+ self.logger.warning(f'⏱️ Screenshot timed out on page {_log_pretty_url(page.url)} (possibly crashed): {error_str}')else:- self.logger.error(f'❌ Failed to take screenshot: {type(e).__name__}: {e}')- raise+ self.logger.error(f'❌ Screenshot failed on page {_log_pretty_url(page.url)} (possibly crashed): {error_str}')+ raise+ finally:+ if cdp_session:+ try:+ await asyncio.wait_for(cdp_session.detach(), timeout=1.0)+ except Exception:+ pass# region - User Actions@@@ -3679,112 -4108,16 +4110,16 @@@return page- @observe_debug(ignore_input=True, ignore_output=True, name='create_new_tab')- @time_execution_async('--create_new_tab')- async def create_new_tab(self, url: str | None = None) -> Page:- """Create a new tab and optionally navigate to a URL"""-- # Add https:// if there's no protocol- normalized_url = url- if url:- normalized_url = normalize_url(url)-- if not self._is_url_allowed(normalized_url):- raise BrowserError(f'Cannot create new tab with non-allowed URL: {normalized_url}')-- try:- assert self.browser_context is not None, 'Browser context is not set'- new_page = await self.browser_context.new_page()- except Exception:- self.initialized = False- self.browser_context = None # Clear the closed context-- if not self.initialized or not self.browser_context:- # If we were initialized but lost connection, reset state first to avoid infinite loops- if self.initialized and not self.browser_context:- self.logger.warning(- f'💔 Browser {self._connection_str} disconnected while trying to create a new tab, reconnecting...'- )- self._reset_connection_state()- await self.start()- assert self.browser_context, 'Browser context is not set'- new_page = await self.browser_context.new_page()-- # Update agent tab reference- self.agent_current_page = new_page-- # Update human tab reference if there is no human tab yet- if (not self.human_current_page) or self.human_current_page.is_closed():- self.human_current_page = new_page-- tab_idx = self.tabs.index(new_page)- try:- await new_page.wait_for_load_state()- except Exception as e:- self.logger.warning(- f'⚠️ New page [{tab_idx}]{_log_pretty_url(new_page.url)} failed to fully load: {type(e).__name__}: {e}'- )-- # Show DVD animation on new tab pages (after navigating to about:blank if needed)- if not normalized_url and is_new_tab_page(new_page.url):- # Navigate to about:blank if we're on chrome://new-tab-page to avoid security restrictions- if new_page.url.startswith('chrome://new-tab-page'):- await new_page.goto('about:blank')- await self._show_dvd_screensaver_loading_animation(new_page)-- # Set the viewport size for the new tab- if self.browser_profile.viewport:- await new_page.set_viewport_size(self.browser_profile.viewport)-- if normalized_url:- try:- await new_page.goto(normalized_url, wait_until='domcontentloaded')- await self._wait_for_page_and_frames_load(timeout_overwrite=1)- except Exception as e:- self.logger.error(f'❌ Error navigating to {normalized_url}: {type(e).__name__}: {e} (proceeding anyway...)')-- assert self.human_current_page is not None- assert self.agent_current_page is not None- # if url: # sometimes this does not pass because JS or HTTP redirects the page really fast- # assert self.agent_current_page.url == url- # else:- # assert self.agent_current_page.url == 'about:blank'-- # if there are any unused new tab pages after we open a new tab, close them to clean up unused tabs- assert self.browser_context is not None, 'Browser context is not set'- # hacky way to be sure we only close our own tabs, check the title of the tab for our BrowserSession name- title_of_our_setup_tab = (- f'Starting agent {str(self.id)[-4:]}...' # set up by self._show_dvd_screensaver_loading_animation()- )- for page in self.browser_context.pages:- try:- # sometimes this fails, because the page is not accessible- page_title = await self._get_page_title(page)- except Exception:- page_title = 'Title unavailable'-- if is_new_tab_page(page.url) and page != self.agent_current_page and page_title == title_of_our_setup_tab:- await page.close()- self.human_current_page = ( # in case we just closed the human's tab, fix the refs- self.human_current_page if not self.human_current_page.is_closed() else self.agent_current_page- )- break # only close a maximum of one unused new tab page,- # if multiple parallel agents share one BrowserSession- # closing every new_page() tab (which start on new tab pages) causes lots of problems- # (the title check is not enough when they share a single BrowserSession)-- return new_page-# region - Helper methods for easier access to the DOM- @observe_debug(ignore_input=True, ignore_output=True, name='get_selector_map')- @require_initialization- @observe_debug(name='get_selector_map')++ @observe_debug(name='get_selector_map', ignore_output=True, ignore_input=True)+ @require_healthy_browser(usable_page=True, reopen_page=True)async def get_selector_map(self) -> SelectorMap:if self._cached_browser_state_summary is None:return {}return self._cached_browser_state_summary.selector_map- @observe_debug(name='get_element_by_index')+ @observe_debug(ignore_input=True, ignore_output=True, name='get_element_by_index')- @require_initialization+ @require_healthy_browser(usable_page=True, reopen_page=True)async def get_element_by_index(self, index: int) -> ElementHandle | None:selector_map = await self.get_selector_map()element_handle = await self.get_locate_element(selector_map[index])@@@ -4036,102 -4372,105 +4374,105 @@@# all in one JS function for speed, we want as few roundtrip CDP calls as possible# between opening the tab and showing the animation- await page.evaluate(- """(browser_session_label) => {- const animated_title = `Starting agent ${browser_session_label}...`;- if (document.title === animated_title) {- return; // already run on this tab, dont run again- }- document.title = animated_title;-- // Create the main overlay- const loadingOverlay = document.createElement('div');- loadingOverlay.id = 'pretty-loading-animation';- loadingOverlay.style.position = 'fixed';- loadingOverlay.style.top = '0';- loadingOverlay.style.left = '0';- loadingOverlay.style.width = '100vw';- loadingOverlay.style.height = '100vh';- loadingOverlay.style.background = '#000';- loadingOverlay.style.zIndex = '99999';- loadingOverlay.style.overflow = 'hidden';-- // Create the image element- const img = document.createElement('img');- img.src = 'https://cf.browser-use.com/logo.svg';- img.alt = 'Browser-Use';- img.style.width = '200px';- img.style.height = 'auto';- img.style.position = 'absolute';- img.style.left = '0px';- img.style.top = '0px';- img.style.zIndex = '2';- img.style.opacity = '0.8';-- loadingOverlay.appendChild(img);- document.body.appendChild(loadingOverlay);-- // DVD screensaver bounce logic- let x = Math.random() * (window.innerWidth - 300);- let y = Math.random() * (window.innerHeight - 300);- let dx = 1.2 + Math.random() * 0.4; // px per frame- let dy = 1.2 + Math.random() * 0.4;- // Randomize direction- if (Math.random() > 0.5) dx = -dx;- if (Math.random() > 0.5) dy = -dy;-- function animate() {- const imgWidth = img.offsetWidth || 300;- const imgHeight = img.offsetHeight || 300;- x += dx;- y += dy;-- if (x <= 0) {- x = 0;- dx = Math.abs(dx);- } else if (x + imgWidth >= window.innerWidth) {- x = window.innerWidth - imgWidth;- dx = -Math.abs(dx);- }- if (y <= 0) {- y = 0;- dy = Math.abs(dy);- } else if (y + imgHeight >= window.innerHeight) {- y = window.innerHeight - imgHeight;- dy = -Math.abs(dy);+ try:+ await page.evaluate(+ """(browser_session_label) => {+ const animated_title = `Starting agent ${browser_session_label}...`;+ if (document.title === animated_title) {+ return; // already run on this tab, dont run again}+ document.title = animated_title;++ // Create the main overlay+ const loadingOverlay = document.createElement('div');+ loadingOverlay.id = 'pretty-loading-animation';+ loadingOverlay.style.position = 'fixed';+ loadingOverlay.style.top = '0';+ loadingOverlay.style.left = '0';+ loadingOverlay.style.width = '100vw';+ loadingOverlay.style.height = '100vh';+ loadingOverlay.style.background = '#000';+ loadingOverlay.style.zIndex = '99999';+ loadingOverlay.style.overflow = 'hidden';++ // Create the image element+ const img = document.createElement('img');+ img.src = 'https://cf.browser-use.com/logo.svg';+ img.alt = 'Browser-Use';+ img.style.width = '200px';+ img.style.height = 'auto';+ img.style.position = 'absolute';+ img.style.left = '0px';+ img.style.top = '0px';+ img.style.zIndex = '2';+ img.style.opacity = '0.8';++ loadingOverlay.appendChild(img);+ document.body.appendChild(loadingOverlay);++ // DVD screensaver bounce logic+ let x = Math.random() * (window.innerWidth - 300);+ let y = Math.random() * (window.innerHeight - 300);+ let dx = 1.2 + Math.random() * 0.4; // px per frame+ let dy = 1.2 + Math.random() * 0.4;+ // Randomize direction+ if (Math.random() > 0.5) dx = -dx;+ if (Math.random() > 0.5) dy = -dy;++ function animate() {+ const imgWidth = img.offsetWidth || 300;+ const imgHeight = img.offsetHeight || 300;+ x += dx;+ y += dy;++ if (x <= 0) {+ x = 0;+ dx = Math.abs(dx);+ } else if (x + imgWidth >= window.innerWidth) {+ x = window.innerWidth - imgWidth;+ dx = -Math.abs(dx);+ }+ if (y <= 0) {+ y = 0;+ dy = Math.abs(dy);+ } else if (y + imgHeight >= window.innerHeight) {+ y = window.innerHeight - imgHeight;+ dy = -Math.abs(dy);+ }- img.style.left = `${x}px`;- img.style.top = `${y}px`;-- requestAnimationFrame(animate);- }- animate();-- // Responsive: update bounds on resize- window.addEventListener('resize', () => {- x = Math.min(x, window.innerWidth - img.offsetWidth);- y = Math.min(y, window.innerHeight - img.offsetHeight);- });+ img.style.left = `${x}px`;+ img.style.top = `${y}px`;- // Add a little CSS for smoothness- const style = document.createElement('style');- style.textContent = `- #pretty-loading-animation {- /*backdrop-filter: blur(2px) brightness(0.9);*/- }- #pretty-loading-animation img {- user-select: none;- pointer-events: none;+ requestAnimationFrame(animate);}- `;- document.head.appendChild(style);- }""",- str(self.id)[-4:],- )+ animate();++ // Responsive: update bounds on resize+ window.addEventListener('resize', () => {+ x = Math.min(x, window.innerWidth - img.offsetWidth);+ y = Math.min(y, window.innerHeight - img.offsetHeight);+ });++ // Add a little CSS for smoothness+ const style = document.createElement('style');+ style.textContent = `+ #pretty-loading-animation {+ /*backdrop-filter: blur(2px) brightness(0.9);*/+ }+ #pretty-loading-animation img {+ user-select: none;+ pointer-events: none;+ }+ `;+ document.head.appendChild(style);+ }""",+ str(self.id)[-4:],+ )+ except Exception as e:+ self.logger.debug(f'❌ Failed to show 📀 DVD loading animation: {type(e).__name__}: {e}')- @observe_debug(name='get_state_summary_with_fallback', ignore_output=True)+ @observe_debug(ignore_input=True, ignore_output=True, name='get_state_summary_with_fallback')- @require_initialization+ @require_healthy_browser(usable_page=True, reopen_page=True)@time_execution_async('--get_state_summary_with_fallback')async def get_state_summary_with_fallback(self, cache_clickable_elements_hashes: bool = True) -> BrowserStateSummary:"""Get browser state with fallback to minimal state on errors