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
more tests passing
Nick Sweetinga0e2fac3caab
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.pyindex 209a5918b..407874653 100644--- a/browser_use/browser/downloads_watchdog.py+++ b/browser_use/browser/downloads_watchdog.py@@ -124,6 +124,10 @@ class DownloadsWatchdog(BaseWatchdog):self._active_downloads[download_id] = downloadlogger.info(f'[DownloadsWatchdog] Handling download: {download.suggested_filename} from {download.url[:100]}...')+ # Debug: Check if download is already being handled elsewhere+ logger.info(f'[DownloadsWatchdog] Download state - canceled: {download.failure()}, url: {download.url}')+ logger.info(f'[DownloadsWatchdog] Active downloads count: {len(self._active_downloads)}')+try:current_step = 'getting_download_info'# Get download info immediately@@ -238,8 +242,17 @@ class DownloadsWatchdog(BaseWatchdog):return self._pdf_viewer_cache[page_url]try:- # Check if we're in Chrome's PDF viewer- is_pdf_viewer = await page.evaluate("""+ # Check if page is still valid before evaluation+ if page.is_closed():+ logger.debug(f'[DownloadsWatchdog] Page is closed, cannot check for PDF: {page_url}')+ self._pdf_viewer_cache[page_url] = False+ return False++ # Add timeout to prevent hanging on unresponsive pages+ import asyncio++ is_pdf_viewer = await asyncio.wait_for(+ page.evaluate("""() => {// Check for Chrome's built-in PDF viewer (both old and new selectors)const pdfEmbed = document.querySelector('embed[type="application/x-google-chrome-pdf"]') ||@@ -291,7 +304,9 @@ class DownloadsWatchdog(BaseWatchdog):return { isPdf: false };}- """)+ """),+ timeout=5.0, # 5 second timeout to prevent hanging+ )if is_pdf_viewer.get('isPdf', False):logger.info(@@ -304,8 +319,13 @@ class DownloadsWatchdog(BaseWatchdog):self._pdf_viewer_cache[page_url] = Falsereturn False+ except TimeoutError:+ logger.debug(f'[DownloadsWatchdog] PDF check timed out for page: {page_url}')+ self._pdf_viewer_cache[page_url] = False+ return Falseexcept Exception as e:logger.debug(f'[DownloadsWatchdog] Error checking for PDF viewer: {e}')+ self._pdf_viewer_cache[page_url] = Falsereturn Falseasync def trigger_pdf_download(self, page: Page) -> str | None:@@ -318,8 +338,16 @@ class DownloadsWatchdog(BaseWatchdog):return Nonetry:- # Try to get the PDF URL- pdf_info = await page.evaluate("""+ # Check if page is still valid before evaluation+ if page.is_closed():+ logger.debug('[DownloadsWatchdog] Page is closed, cannot trigger PDF download')+ return None++ # Try to get the PDF URL with timeout+ import asyncio++ pdf_info = await asyncio.wait_for(+ page.evaluate("""() => {const embedElement = document.querySelector('embed[type="application/x-google-chrome-pdf"]') ||document.querySelector('embed[type="application/pdf"]');@@ -328,7 +356,9 @@ class DownloadsWatchdog(BaseWatchdog):}return { url: window.location.href };}- """)+ """),+ timeout=5.0, # 5 second timeout to prevent hanging+ )pdf_url = pdf_info.get('url', '')if not pdf_url:@@ -358,7 +388,8 @@ class DownloadsWatchdog(BaseWatchdog):# Properly escape the URL to prevent JavaScript injectionescaped_pdf_url = json.dumps(pdf_url)- download_result = await page.evaluate(f"""+ download_result = await asyncio.wait_for(+ page.evaluate(f"""async () => {{try {{// Use fetch with cache: 'force-cache' to prioritize cached version@@ -389,7 +420,9 @@ class DownloadsWatchdog(BaseWatchdog):throw new Error(`Fetch failed: ${{error.message}}`);}}}}- """)+ """),+ timeout=10.0, # 10 second timeout for download operation+ )if download_result and download_result.get('data') and len(download_result['data']) > 0:# Ensure unique filename@@ -433,6 +466,9 @@ class DownloadsWatchdog(BaseWatchdog):logger.warning(f'[DownloadsWatchdog] Failed to auto-download PDF from {pdf_url}: {type(e).__name__}: {e}')return None+ except TimeoutError:+ logger.debug('[DownloadsWatchdog] PDF download operation timed out')+ return Noneexcept Exception as e:logger.error(f'[DownloadsWatchdog] Error in PDF download: {type(e).__name__}: {e}')return Nonediff --git a/browser_use/browser/events.py b/browser_use/browser/events.pyindex 489fbe5ac..c24671311 100644--- a/browser_use/browser/events.py+++ b/browser_use/browser/events.py@@ -109,8 +109,8 @@ class GetPageInfoEvent(BaseEvent):tab_index: int-class EvaluateJavaScriptEvent(BaseEvent):- """Evaluate JavaScript in page context."""+class ExecuteJavaScriptEvent(BaseEvent):+ """Execute JavaScript in page context."""tab_index: intexpression: str@@ -232,6 +232,7 @@ class ScreenshotResponseEvent(BaseEvent):"""Response to ScreenshotRequestEvent."""screenshot: str # base64 encoded+ error: str | None = Noneclass TabsInfoResponseEvent(BaseEvent):@@ -240,13 +241,6 @@ class TabsInfoResponseEvent(BaseEvent):tabs: list[dict[str, Any]]-class EvaluateJavaScriptResponseEvent(BaseEvent):- """Response to EvaluateJavaScriptEvent."""-- result: Any- error: str | None = None--# ============================================================================# Storage State Events# ============================================================================diff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.pyindex 437dfc0ad..b35735a3d 100644--- a/browser_use/browser/navigation_watchdog.py+++ b/browser_use/browser/navigation_watchdog.py@@ -132,8 +132,11 @@ class NavigationWatchdog(BaseWatchdog):)try:- # Perform navigation- response = await page.goto(event.url, wait_until=event.wait_until)+ # Perform navigation with timeout protection+ response = await asyncio.wait_for(+ page.goto(event.url, wait_until=event.wait_until),+ timeout=30.0, # 30 second timeout to prevent hanging+ )# Dispatch completion eventself.event_bus.dispatch(@@ -146,8 +149,23 @@ class NavigationWatchdog(BaseWatchdog):# Network monitoring is handled by CrashWatchdog+ except TimeoutError:+ # Handle navigation timeout for new tab+ error_message = 'Navigation timed out after 30 seconds'+ loading_status = 'Navigation timeout: 30 seconds'+ logger.warning(f'[NavigationWatchdog] Navigation to {event.url} timed out in new tab')++ self.event_bus.dispatch(+ NavigationCompleteEvent(+ tab_index=tab_index,+ url=event.url,+ status=None,+ error_message=error_message,+ loading_status=loading_status,+ )+ )except Exception as e:- # Handle navigation error for new tab+ # Handle other navigation errors for new taberror_message = str(e)loading_status = Noneif 'timeout' in error_message.lower() or 'timed out' in error_message.lower():@@ -224,10 +242,13 @@ class NavigationWatchdog(BaseWatchdog):))- # Perform navigation- response = await page.goto(- event.url,- wait_until=event.wait_until,+ # Perform navigation with timeout protection+ response = await asyncio.wait_for(+ page.goto(+ event.url,+ wait_until=event.wait_until,+ ),+ timeout=30.0, # 30 second timeout to prevent hanging)# Dispatch completion event@@ -241,8 +262,27 @@ class NavigationWatchdog(BaseWatchdog):# Network monitoring is handled by CrashWatchdog+ except TimeoutError:+ # Handle navigation timeout for standard navigation+ error_message = 'Navigation timed out after 30 seconds'+ loading_status = 'Navigation timeout: 30 seconds'+ logger.warning(f'[NavigationWatchdog] Navigation to {event.url} timed out in standard navigation')++ # Get tab index for timeout error reporting+ tab_index = self.browser_session.get_tab_index(page) if page else 0++ # Dispatch NavigationCompleteEvent with timeout error details+ self.event_bus.dispatch(+ NavigationCompleteEvent(+ tab_index=tab_index,+ url=event.url,+ status=None,+ error_message=error_message,+ loading_status=loading_status,+ )+ )except Exception as e:- # Handle navigation errors+ # Handle other navigation errorserror_message = str(e)loading_status = Nonediff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 00ea72e71..cdc291675 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -20,6 +20,7 @@ from browser_use.browser.events import (BrowserStoppedEvent,ClickElementEvent,CloseTabEvent,+ ExecuteJavaScriptEvent,FileDownloadedEvent,LoadStorageStateEvent,NavigateToUrlEvent,@@ -206,28 +207,29 @@ class BrowserSession(BaseModel):def _register_handlers(self) -> None:"""Register event handlers for browser control."""# Browser lifecycle- self.event_bus.on(StartBrowserEvent, self._handle_start)- self.event_bus.on(StopBrowserEvent, self._handle_stop)+ self.event_bus.on(StartBrowserEvent, self.on_StartBrowserEvent)+ self.event_bus.on(StopBrowserEvent, self.on_StopBrowserEvent)# Navigation is handled by NavigationWatchdog# Interaction- self.event_bus.on(ClickElementEvent, self._handle_click)- self.event_bus.on(TypeTextEvent, self._handle_input_text)- self.event_bus.on(ScrollEvent, self._handle_scroll)+ self.event_bus.on(ClickElementEvent, self.on_ClickElementEvent)+ self.event_bus.on(TypeTextEvent, self.on_TypeTextEvent)+ self.event_bus.on(ScrollEvent, self.on_ScrollEvent)# Tab management - handled by watchdogs- self.event_bus.on(CloseTabEvent, self._handle_close_tab)+ self.event_bus.on(CloseTabEvent, self.on_CloseTabEvent)# Browser state- self.event_bus.on(BrowserStateRequestEvent, self._handle_browser_state_request)- self.event_bus.on(ScreenshotRequestEvent, self._handle_screenshot_request)- self.event_bus.on(TabsInfoRequestEvent, self._handle_tabs_info_request)+ self.event_bus.on(BrowserStateRequestEvent, self.on_BrowserStateRequestEvent)+ self.event_bus.on(ScreenshotRequestEvent, self.on_ScreenshotRequestEvent)+ self.event_bus.on(TabsInfoRequestEvent, self.on_TabsInfoRequestEvent)+ self.event_bus.on(ExecuteJavaScriptEvent, self.on_ExecuteJavaScriptEvent)# Storage state is handled by StorageStateWatchdog# ========== Event Handlers ==========- async def _handle_start(self, event: StartBrowserEvent) -> None:+ async def on_StartBrowserEvent(self, event: StartBrowserEvent) -> None:"""Handle browser start request."""if self._browser and self._browser.is_connected():# Already started@@ -347,7 +349,7 @@ class BrowserSession(BaseModel):)raise- async def _handle_stop(self, event: StopBrowserEvent) -> None:+ async def on_StopBrowserEvent(self, event: StopBrowserEvent) -> None:"""Handle browser stop request."""if not self._browser:self.event_bus.dispatch(@@ -439,7 +441,7 @@ class BrowserSession(BaseModel):event = self.event_bus.dispatch(StopBrowserEvent())await event- async def _handle_click(self, event: ClickElementEvent) -> None:+ async def on_ClickElementEvent(self, event: ClickElementEvent) -> None:"""Handle click request."""try:page = await self.get_current_page()@@ -500,7 +502,7 @@ class BrowserSession(BaseModel):))- async def _handle_input_text(self, event: TypeTextEvent) -> None:+ async def on_TypeTextEvent(self, event: TypeTextEvent) -> None:"""Handle text input request."""try:page = await self.get_current_page()@@ -535,7 +537,7 @@ class BrowserSession(BaseModel):))- async def _handle_scroll(self, event: ScrollEvent) -> None:+ async def on_ScrollEvent(self, event: ScrollEvent) -> None:"""Handle scroll request."""try:page = await self.get_current_page()@@ -568,14 +570,14 @@ class BrowserSession(BaseModel):))- async def _handle_close_tab(self, event: CloseTabEvent) -> None:+ async def on_CloseTabEvent(self, event: CloseTabEvent) -> None:"""Handle tab close request."""if 0 <= event.tab_index < len(self.pages):await self.pages[event.tab_index].close()# Dispatch tab closed event for watchdogsself.event_bus.dispatch(TabClosedEvent(tab_index=event.tab_index))- async def _handle_browser_state_request(self, event: BrowserStateRequestEvent) -> None:+ async def on_BrowserStateRequestEvent(self, event: BrowserStateRequestEvent) -> None:"""Handle browser state request."""try:# Use the internal method directly to avoid infinite loop@@ -590,7 +592,7 @@ class BrowserSession(BaseModel):minimal_state = await self.get_minimal_state_summary()self.event_bus.dispatch(BrowserStateResponseEvent(state=minimal_state))- async def _handle_screenshot_request(self, event: ScreenshotRequestEvent) -> None:+ async def on_ScreenshotRequestEvent(self, event: ScreenshotRequestEvent) -> None:"""Handle screenshot request."""try:page = await self.get_current_page()@@ -607,14 +609,24 @@ class BrowserSession(BaseModel):height=event.clip['height'],)- screenshot_bytes = await page.screenshot(- full_page=event.full_page,- clip=clip_rect,- )+ # Add timeout protection to prevent hanging on unresponsive pages+ try:+ screenshot_bytes = await asyncio.wait_for(+ page.screenshot(+ full_page=event.full_page,+ clip=clip_rect,+ ),+ timeout=10.0, # 10 second timeout for screenshots+ )+ except TimeoutError:+ logger.warning(f'[Session] Screenshot timed out after 10 seconds for page: {page.url}')+ # Return empty response or could dispatch error event+ self.event_bus.dispatch(ScreenshotResponseEvent(screenshot='', error='Screenshot timed out'))+ returnscreenshot_b64 = base64.b64encode(screenshot_bytes).decode('utf-8')self.event_bus.dispatch(ScreenshotResponseEvent(screenshot=screenshot_b64))- async def _handle_tabs_info_request(self, event: TabsInfoRequestEvent) -> None:+ async def on_TabsInfoRequestEvent(self, event: TabsInfoRequestEvent) -> None:"""Handle tabs info request."""from browser_use.browser.views import TabInfo@@ -638,6 +650,18 @@ class BrowserSession(BaseModel):# Dispatch the response eventself.event_bus.dispatch(TabsInfoResponseEvent(tabs=tabs))+ async def on_ExecuteJavaScriptEvent(self, event: ExecuteJavaScriptEvent) -> Any:+ """Handle JavaScript evaluation request."""+ # Get the correct page by tab index+ if 0 <= event.tab_index < len(self.pages):+ page = self.pages[event.tab_index]+ else:+ page = await self.get_current_page()++ # Execute the JavaScript and return result directly+ result = await page.evaluate(event.expression)+ return result+def _generate_recent_events_summary(self, max_events: int = 10) -> str:"""Generate a JSON summary of recent browser events."""@@ -1018,9 +1042,13 @@ class BrowserSession(BaseModel):screenshot_b64 = Noneif include_screenshot:try:- screenshot_bytes = await page.screenshot()+ screenshot_bytes = await asyncio.wait_for(+ page.screenshot(),+ timeout=10.0, # 10 second timeout for screenshots+ )screenshot_b64 = base64.b64encode(screenshot_bytes).decode('utf-8')- except Exception:+ except (Exception, TimeoutError) as e:+ logger.debug(f'[Session] Screenshot failed: {e}')pass# Get page dimensions@@ -1294,14 +1322,14 @@ class BrowserSession(BaseModel):A valid CSS selector string"""try:+ import re+# Get base selector from XPathcss_selector = cls._convert_simple_xpath_to_css_selector(element.xpath)# Handle class attributesif 'class' in element.attributes and element.attributes['class'] and include_dynamic_attributes:# Define a regex pattern for valid class names in CSS- import re-valid_class_name_pattern = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_-]*$')# Iterate through the class attribute values@@ -1328,18 +1356,63 @@ class BrowserSession(BaseModel):'type','placeholder',# Accessibility attributes- 'role','aria-label',- 'title',+ 'aria-labelledby',+ 'aria-describedby',+ 'role',+ # Common form attributes+ 'for',+ 'autocomplete',+ 'required',+ 'readonly',+ # Media attributes'alt',+ 'title',+ 'src',+ # Custom stable attributes (add any application-specific ones)+ 'href',+ 'target',}- for attr in SAFE_ATTRIBUTES:- if attr in element.attributes and element.attributes[attr] and include_dynamic_attributes:- value = element.attributes[attr]- # Escape special characters in attribute values- value = value.replace('"', '\\"')- css_selector += f'[{attr}="{value}"]'+ if include_dynamic_attributes:+ dynamic_attributes = {+ 'data-id',+ 'data-qa',+ 'data-cy',+ 'data-testid',+ }+ SAFE_ATTRIBUTES.update(dynamic_attributes)++ # Handle other attributes+ for attribute, value in element.attributes.items():+ if attribute == 'class':+ continue++ # Skip invalid attribute names+ if not attribute.strip():+ continue++ if attribute not in SAFE_ATTRIBUTES:+ continue++ # Escape special characters in attribute names+ safe_attribute = attribute.replace(':', r'\:')++ # Handle different value cases+ if value == '':+ css_selector += f'[{safe_attribute}]'+ elif any(char in value for char in '"\'<>`\n\r\t'):+ # Use contains for values with special characters+ # For newline-containing text, only use the part before the newline+ if '\n' in value:+ value = value.split('\n')[0]+ # Regex-substitute *any* whitespace with a single space, then strip.+ collapsed_value = re.sub(r'\s+', ' ', value).strip()+ # Escape embedded double-quotes.+ safe_value = collapsed_value.replace('"', '\\"')+ css_selector += f'[{safe_attribute}*="{safe_value}"]'+ else:+ css_selector += f'[{safe_attribute}="{value}"]'return css_selectorexcept Exception:@@ -1378,18 +1451,25 @@ class BrowserSession(BaseModel):index_part = part[part.find('[') :]# Handle multiple indices- if '][' in index_part:- # Multiple conditions, just use the element name- css_parts.append(base_part)- else:- # Extract the index+ indices = [i.strip('[]') for i in index_part.split(']')[:-1]]++ for idx in indices:try:- index = int(index_part[1:-1]) # Remove [ and ]- # CSS uses 1-based :nth-child, XPath uses 1-based indexing- css_parts.append(f'{base_part}:nth-child({index})')+ # Handle numeric indices+ if idx.isdigit():+ index = int(idx) - 1+ base_part += f':nth-of-type({index + 1})'+ # Handle last() function+ elif idx == 'last()':+ base_part += ':last-of-type'+ # Handle position() functions+ elif 'position()' in idx:+ if '>1' in idx:+ base_part += ':nth-of-type(n+2)'except ValueError:- # Not a simple index, just use the element name- css_parts.append(base_part)+ continue++ css_parts.append(base_part)else:# Handle custom elements with colonsif ':' in part:@@ -1626,6 +1706,12 @@ class BrowserSession(BaseModel):prefix = pattern[:-1] # Remove the * at the endif url.startswith(prefix):return True+ elif '://*.' in pattern:+ # Pattern like http://*.example.com should match http://sub.example.com+ scheme_and_wildcard, domain_part = pattern.split('://*.')+ expected_scheme = scheme_and_wildcard+ if parsed.scheme == expected_scheme and (host == domain_part or host.endswith('.' + domain_part)):+ return Trueelse:# Use fnmatch for other glob patternsif fnmatch.fnmatch(host, pattern):@@ -1688,6 +1774,57 @@ class BrowserSession(BaseModel):selector_map = await self.get_selector_map()return selector_map.get(index)+ async def execute_javascript(self, script: str) -> Any:+ """Execute JavaScript in the current page (compatibility method)."""+ # Get current tab index+ current_page = await self.get_current_page()+ tab_index = self.get_tab_index(current_page) if current_page else 0++ # Dispatch the event and await the result+ event = self.event_bus.dispatch(ExecuteJavaScriptEvent(tab_index=tab_index, expression=script))+ result = await event.event_result()+ return result++ async def get_scroll_info(self, page: Page) -> tuple[int, int]:+ """Get scroll position information for the current page (compatibility method)."""+ scroll_y = await page.evaluate('window.scrollY')+ viewport_height = await page.evaluate('window.innerHeight')+ total_height = await page.evaluate('document.documentElement.scrollHeight')+ # Convert to int to handle fractional pixels+ pixels_above = int(scroll_y)+ pixels_below = int(max(0, total_height - (scroll_y + viewport_height)))+ return pixels_above, pixels_below++ async def remove_highlights(self):+ """+ Removes all highlight overlays and labels created by the highlightElement function (compatibility method).+ Handles cases where the page might be closed or inaccessible.+ """+ page = await self.get_current_page()+ try:+ await page.evaluate(+ """+ try {+ // Remove the highlight container and all its contents+ const container = document.getElementById('playwright-highlight-container');+ if (container) {+ container.remove();+ }++ // Remove highlight attributes from elements+ const highlightedElements = document.querySelectorAll('[browser-user-highlight-id^="playwright-highlight-"]');+ highlightedElements.forEach(el => {+ el.removeAttribute('browser-user-highlight-id');+ });+ } catch (e) {+ console.error('Failed to remove highlights:', e);+ }+ """+ )+ except Exception as e:+ logger.debug(f'⚠️ Failed to remove highlights (this is usually ok): {type(e).__name__}: {e}')+ # Don't raise the error since this is not critical functionality+# ========== PDF API Methods ==========def set_auto_download_pdfs(self, enabled: bool) -> None:diff --git a/tests/ci/test_browser_session_downloads_simple.py b/tests/ci/test_browser_session_downloads_simple.pyindex 93d222c1d..c99c4040f 100644--- a/tests/ci/test_browser_session_downloads_simple.py+++ b/tests/ci/test_browser_session_downloads_simple.py@@ -4,14 +4,16 @@ import asyncioimport tempfilefrom pathlib import Path+import pytestfrom playwright.async_api import async_playwright+from pytest_httpserver import HTTPServerfrom browser_use.browser import BrowserSessionfrom browser_use.browser.profile import BrowserProfileasync def test_simple_playwright_download():- """Test basic Playwright download functionality without browser-use"""+ """Test basic Playwright download functionality without browser-use - this just validates the browser setup"""async with async_playwright() as p:# Create temp directory for downloads@@ -39,18 +41,28 @@ async def test_simple_playwright_download():await page.set_content(html_content)- # Set up download promise- async with page.expect_download() as download_info:- await page.click('a[download]')- download = await download_info.value+ # Set up download handling+ downloads = []+ page.on('download', lambda download: downloads.append(download))- # Save the download- save_path = downloads_path / download.suggested_filename- await download.save_as(str(save_path))+ # Click download link+ await page.click('a[download]')- # Verify file exists- assert save_path.exists()- assert save_path.read_text() == 'Hello World'+ # Wait for download to be triggered+ await asyncio.sleep(1)++ # Verify download was triggered+ assert len(downloads) > 0, 'No download was triggered'++ download = downloads[0]++ # Save the download to our test directory+ download_path = downloads_path / download.suggested_filename+ await download.save_as(str(download_path))++ # Verify file was saved and has correct content+ assert download_path.exists(), f'Downloaded file not found at {download_path}'+ assert download_path.read_text() == 'Hello World', 'Downloaded file has incorrect content'print('✅ Basic Playwright download test passed!')@@ -58,8 +70,23 @@ async def test_simple_playwright_download():await browser.close()-async def test_browser_use_download_with_data_url():- """Test browser-use download with data URL"""[email protected](scope='function')+def http_server():+ """Create a test HTTP server with a downloadable file."""+ server = HTTPServer()+ server.start()++ # Add a route that serves a downloadable text file+ server.expect_request('/download/test.txt').respond_with_data(+ 'Hello BrowserUse', content_type='text/plain', headers={'Content-Disposition': 'attachment; filename="test.txt"'}+ )++ yield server+ server.stop()+++async def test_browser_use_download_with_http_server(http_server):+ """Test browser-use download with HTTP server and event coordination"""with tempfile.TemporaryDirectory() as tmpdir:downloads_path = Path(tmpdir) / 'downloads'@@ -76,13 +103,14 @@ async def test_browser_use_download_with_data_url():await browser_session.start()page = await browser_session.get_current_page()- # Create a simple HTML page with download link using data URL- html_content = """+ # Create HTML page with download link pointing to HTTP server+ base_url = f'http://{http_server.host}:{http_server.port}'+ html_content = f"""<!DOCTYPE html><html><body><h1>Download Test</h1>- <a id="download-link" href="data:text/plain;base64,SGVsbG8gQnJvd3NlclVzZQ==" download="browseruse.txt">Download BrowserUse File</a>+ <a id="download-link" href="{base_url}/download/test.txt">Download Test File</a></body></html>"""@@ -93,7 +121,6 @@ async def test_browser_use_download_with_data_url():await asyncio.sleep(0.5)# Click the download link and let the DownloadsWatchdog handle it completely- # Don't use page.expect_download() to avoid conflicts with the watchdogawait page.click('#download-link')# Wait for the DownloadsWatchdog to process the download by expecting the FileDownloadedEvent@@ -105,13 +132,14 @@ async def test_browser_use_download_with_data_url():print(f'📁 Download completed: {download_event.file_name} ({download_event.file_size} bytes)')except TimeoutError:print('❌ Download did not complete within timeout')+ raise AssertionError('Download event not received within timeout')# Verify file exists in downloads directory- expected_file = downloads_path / 'browseruse.txt' # filename from the HTML+ expected_file = downloads_path / 'test.txt'assert expected_file.exists()assert expected_file.read_text() == 'Hello BrowserUse'- print('✅ BrowserUse data URL download test passed!')+ print('✅ BrowserUse HTTP server download test passed!')# Check if browser_session sees the downloaded filedownloaded_files = browser_session.downloaded_files@@ -126,6 +154,15 @@ if __name__ == '__main__':if len(sys.argv) > 1 and sys.argv[1] == 'playwright':asyncio.run(test_simple_playwright_download())elif len(sys.argv) > 1 and sys.argv[1] == 'browseruse':- asyncio.run(test_browser_use_download_with_data_url())+ # Run the HTTP server test+ server = HTTPServer()+ server.start()+ server.expect_request('/download/test.txt').respond_with_data(+ 'Hello BrowserUse', content_type='text/plain', headers={'Content-Disposition': 'attachment; filename="test.txt"'}+ )+ try:+ asyncio.run(test_browser_use_download_with_http_server(server))+ finally:+ server.stop()else:print('Usage: python test_browser_session_downloads_simple.py [playwright|browseruse]')diff --git a/tests/ci/test_storage_state_watchdog.py b/tests/ci/test_storage_state_watchdog.pyindex 887259fe9..08d3933e0 100644--- a/tests/ci/test_storage_state_watchdog.py+++ b/tests/ci/test_storage_state_watchdog.py@@ -28,7 +28,8 @@ async def test_storage_state_watchdog_lifecycle():try:# Start browser- session.event_bus.dispatch(StartBrowserEvent())+ start_event = session.event_bus.dispatch(StartBrowserEvent())+ await start_event # Wait for the event and all handlers to completeawait session.event_bus.expect(BrowserStartedEvent, timeout=5.0)# Verify storage state watchdog was created