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: detect skeleton screens and retry navigation for blank SPA pages
Saurav Panda6d86be3a6b70
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex ca593539d..803b3547d 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -157,6 +157,7 @@ class AgentMessagePrompt:'images': 0,'interactive_elements': 0,'total_elements': 0,+ 'text_chars': 0,}if not self.browser_state.dom_state or not self.browser_state.dom_state._root:@@ -203,6 +204,9 @@ class AgentMessagePrompt:else:stats['shadow_open'] += 1+ elif original.node_type == NodeType.TEXT_NODE:+ stats['text_chars'] += len(original.node_value.strip())+elif original.node_type == NodeType.DOCUMENT_FRAGMENT_NODE:# Shadow DOM fragment - these are the actual shadow roots# But don't double-count since we count them at the host level above@@ -224,6 +228,9 @@ class AgentMessagePrompt:stats_text = '<page_stats>'if page_stats['total_elements'] < 10:stats_text += 'Page appears empty (SPA not loaded?) - '+ # Skeleton screen: many elements but almost no text = loading placeholders+ elif page_stats['total_elements'] > 20 and page_stats['text_chars'] < page_stats['total_elements'] * 5:+ stats_text += 'Page appears to show skeleton/placeholder content (still loading?) - 'stats_text += f'{page_stats["links"]} links, {page_stats["interactive_elements"]} interactive, 'stats_text += f'{page_stats["iframes"]} iframes'if page_stats['shadow_open'] > 0 or page_stats['shadow_closed'] > 0:diff --git a/browser_use/tools/service.py b/browser_use/tools/service.pyindex c42203d81..6a4d7071a 100644--- a/browser_use/tools/service.py+++ b/browser_use/tools/service.py@@ -422,22 +422,37 @@ class Tools(Generic[Context]):await eventawait event.event_result(raise_if_any=True, raise_if_none=False)- # Health check: detect empty DOM for http/https pages and retry once+ # Health check: detect empty DOM for http/https pages and retry once.+ # Uses llm_representation() to detect pages with nothing the LLM can act on+ # (empty body, SPA not yet rendered). Only returns error for truly blank pages+ # (_root is None, e.g. about:blank type failures) to avoid false positives on+ # image-only or non-interactive pages whose content is real but not in the LLM view.if not params.new_tab:state = await browser_session.get_browser_state_summary(include_screenshot=False)url_is_http = state.url.lower().startswith(('http://', 'https://'))- if url_is_http and state.dom_state._root is None:+ if url_is_http and not state.dom_state.llm_representation().strip():browser_session.logger.warning(f'⚠️ Empty DOM detected after navigation to {params.url}, waiting 3s and rechecking...')await asyncio.sleep(3.0)state = await browser_session.get_browser_state_summary(include_screenshot=False)- if state.url.lower().startswith(('http://', 'https://')) and state.dom_state._root is None:- return ActionResult(- error=f'Page loaded but returned empty content for {params.url}. '- f'The page may require JavaScript that failed to render, use anti-bot measures, '- f'or have a connection issue (e.g. tunnel/proxy error). Try a different URL or approach.'- )+ if (+ state.url.lower().startswith(('http://', 'https://'))+ and not state.dom_state.llm_representation().strip()+ ):+ # Second attempt: reload the page and wait longer+ browser_session.logger.warning(f'⚠️ Still empty after 3s, attempting page reload for {params.url}...')+ reload_event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=params.url, new_tab=False))+ await reload_event+ await reload_event.event_result(raise_if_any=False, raise_if_none=False)+ await asyncio.sleep(5.0)+ state = await browser_session.get_browser_state_summary(include_screenshot=False)+ if state.url.lower().startswith(('http://', 'https://')) and state.dom_state._root is None:+ return ActionResult(+ error=f'Page loaded but returned empty content for {params.url}. '+ f'The page may require JavaScript that failed to render, use anti-bot measures, '+ f'or have a connection issue (e.g. tunnel/proxy error). Try a different URL or approach.'+ )if params.new_tab:memory = f'Opened new tab with URL {params.url}'diff --git a/tests/ci/test_action_blank_page.py b/tests/ci/test_action_blank_page.pynew file mode 100644index 000000000..98f3995b7--- /dev/null+++ b/tests/ci/test_action_blank_page.py@@ -0,0 +1,191 @@+"""Tests for AGI-497: SPA/JS-heavy page renders blank.++Covers:+1. Skeleton screen detection — many elements but near-zero text triggers a warning in page_stats.+2. Navigate reload fallback — empty-body page triggers retry cycle but ultimately succeeds+ (no error) because the DOM root exists. Error is only returned when _root is None.+"""++import asyncio+import tempfile++import pytest+from pytest_httpserver import HTTPServer++from browser_use.agent.views import ActionResult+from browser_use.browser import BrowserProfile, BrowserSession+from browser_use.tools.service import Tools++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------++[email protected](scope='session')+def http_server():+ """Session-scoped HTTP server for blank-page tests."""+ server = HTTPServer()+ server.start()++ # --- skeleton page: 30 empty divs, essentially no text ---+ skeleton_html = '<!DOCTYPE html><html><head><title>Loading...</title></head><body>'+ skeleton_html += ''.join(f'<div class="skeleton-item skeleton-{i}"></div>' for i in range(30))+ skeleton_html += '</body></html>'+ server.expect_request('/skeleton').respond_with_data(skeleton_html, content_type='text/html')++ # --- rich page: real text content (should NOT be flagged as skeleton) ---+ server.expect_request('/products').respond_with_data(+ """<!DOCTYPE html>+<html><head><title>Products</title></head>+<body>+ <h1>Product Catalog</h1>+ <div class="product"><h2>Widget A</h2><p>Price: $29.99 - A sturdy widget for everyday use.</p></div>+ <div class="product"><h2>Widget B</h2><p>Price: $49.99 - Premium widget with extended warranty.</p></div>+ <div class="product"><h2>Gadget C</h2><p>Price: $19.50 - Compact gadget, fits in your pocket.</p></div>+ <div class="product"><h2>Gadget D</h2><p>Price: $99.00 - Professional-grade gadget for power users.</p></div>+</body>+</html>""",+ content_type='text/html',+ )++ # --- empty body page: body is always empty ---+ # Used to test the navigate retry cycle. _root is NOT None (body element exists),+ # so navigate retries but ultimately succeeds (no error).+ server.expect_request('/always-empty').respond_with_data(+ '<html><body></body></html>',+ content_type='text/html',+ )++ yield server+ server.stop()++[email protected](scope='session')+def base_url(http_server):+ return f'http://{http_server.host}:{http_server.port}'++[email protected](scope='module')+async def browser_session():+ session = BrowserSession(+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ keep_alive=True,+ )+ )+ await session.start()+ yield session+ await session.kill()++[email protected](scope='function')+def tools():+ return Tools()+++# ---------------------------------------------------------------------------+# Helper+# ---------------------------------------------------------------------------+++async def _navigate(tools, browser_session, url):+ """Navigate to url and give the page a moment to settle."""+ await tools.navigate(url=url, new_tab=False, browser_session=browser_session)+ await asyncio.sleep(0.5)+++def _make_prompt(state):+ """Build an AgentMessagePrompt from a BrowserStateSummary using a temp dir for FileSystem."""+ from browser_use.agent.prompts import AgentMessagePrompt+ from browser_use.filesystem.file_system import FileSystem++ tmp_dir = tempfile.mkdtemp(prefix='browseruse_test_')+ file_system = FileSystem(base_dir=tmp_dir, create_default_files=False)+ return AgentMessagePrompt(+ browser_state_summary=state,+ file_system=file_system,+ )+++# ---------------------------------------------------------------------------+# Test 1: Skeleton screen detection in _extract_page_statistics()+# ---------------------------------------------------------------------------+++class TestSkeletonScreenDetection:+ """_extract_page_statistics() should flag pages with many elements but very little text."""++ async def test_skeleton_page_low_text_chars(self, tools, browser_session, base_url):+ """Skeleton page: total_elements > 20 but text_chars < total_elements * 5."""+ await _navigate(tools, browser_session, f'{base_url}/skeleton')++ state = await browser_session.get_browser_state_summary(include_screenshot=False)+ prompt = _make_prompt(state)+ page_stats = prompt._extract_page_statistics()++ assert page_stats['total_elements'] > 20, f'Expected >20 elements for skeleton page, got {page_stats["total_elements"]}'+ assert page_stats['text_chars'] < page_stats['total_elements'] * 5, (+ f'Expected text_chars ({page_stats["text_chars"]}) < total_elements*5 '+ f'({page_stats["total_elements"] * 5}) for skeleton page'+ )++ async def test_skeleton_page_description_contains_warning(self, tools, browser_session, base_url):+ """_get_browser_state_description() includes skeleton warning for placeholder pages."""+ await _navigate(tools, browser_session, f'{base_url}/skeleton')++ state = await browser_session.get_browser_state_summary(include_screenshot=False)+ prompt = _make_prompt(state)+ description = prompt._get_browser_state_description()++ assert 'skeleton' in description.lower() or 'placeholder' in description.lower(), (+ f'Expected skeleton/placeholder warning in description, got:\n{description[:500]}'+ )++ async def test_rich_page_not_flagged_as_skeleton(self, tools, browser_session, base_url):+ """A page with real text content should NOT be flagged as skeleton."""+ await _navigate(tools, browser_session, f'{base_url}/products')++ state = await browser_session.get_browser_state_summary(include_screenshot=False)+ prompt = _make_prompt(state)+ page_stats = prompt._extract_page_statistics()+ description = prompt._get_browser_state_description()++ # Rich page should have substantial text relative to element count+ assert page_stats['text_chars'] >= page_stats['total_elements'] * 5, (+ f'Rich page should have text_chars ({page_stats["text_chars"]}) >= total_elements*5 '+ f'({page_stats["total_elements"] * 5})'+ )+ # No skeleton warning in description+ assert 'skeleton' not in description.lower() and 'placeholder' not in description.lower(), (+ 'Rich page should NOT produce a skeleton warning'+ )+++# ---------------------------------------------------------------------------+# Test 2: Navigate reload fallback — empty-body page triggers retry but succeeds+# ---------------------------------------------------------------------------+++class TestNavigateReloadFallback:+ """Navigate retries when llm_representation() is empty, but only errors when _root is None."""++ async def test_empty_body_page_retries_then_succeeds(self, tools, browser_session, base_url):+ """+ Navigating to a page with an empty body triggers the health-check retry cycle+ (empty llm_representation) but ultimately succeeds (no error) because the page+ HAS a DOM root (_root is not None — the body element exists and is visible).++ The error path only fires when _root is None (truly unloadable pages like those+ blocked by anti-bot or returning empty HTTP responses), which avoids false positives+ on image-only or other non-interactive-but-valid pages.+ """+ empty_url = f'{base_url}/always-empty'++ # Triggers: health check -> 3s wait -> reload -> 5s wait -> check _root -> not None -> success+ result = await tools.navigate(url=empty_url, new_tab=False, browser_session=browser_session)++ assert isinstance(result, ActionResult)+ # No error — the body IS a valid DOM root, just visually empty.+ # Skeleton detection (in AgentMessagePrompt._get_browser_state_description) warns the LLM.+ assert result.error is None, f'Expected no error for empty-body page, got: {result.error}'