Skip to content

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

refactor: reduce timeouts for various operations to improve responsiveness

Magnus Müller22f89efae411
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index b7ec79c21..c86c52442 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -813,7 +813,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
self.logger.debug(f'⚡ Step {self.state.n_steps}: Executing {len(model_output.action)} actions...')
result: list[ActionResult] = await asyncio.wait_for(
self.multi_act(model_output.action),
- timeout=60, # 1 minute timeout for actions
+ timeout=20, # 20 second aggressive timeout for actions
)
# result: list[ActionResult] = await self.multi_act(model_output.action)
self.logger.debug(f'✅ Step {self.state.n_steps}: Actions completed')
@@ -1243,7 +1243,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
step_info = AgentStepInfo(step_number=step, max_steps=max_steps)
await asyncio.wait_for(
self.step(step_info),
- timeout=60, # 1 minute timeout per step - faster recovery from hangs
+ timeout=30, # 30 second aggressive timeout per step
)
self.logger.debug(f'✅ Completed step {step + 1}/{max_steps}')
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index bbfa00ae9..1ff682151 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -698,13 +698,13 @@ class BrowserSession(BaseModel):
await self.setup_new_browser_context()
@retry(
- wait=1, # wait 1s between each attempt to take a screenshot (faster retry)
- retries=3, # try up to 3 times to take the screenshot (more attempts)
- timeout=15, # balanced timeout to catch deadlocks without being too aggressive
+ wait=0.5, # wait 0.5s between attempts - aggressive
+ retries=2, # only 2 attempts - fail fast
+ timeout=5, # 5 second aggressive timeout
semaphore_name='screenshot_global',
semaphore_limit=3, # only 3 concurrent screenshots at a time total on the entire machine (ideally)
semaphore_scope='global', # because it's a hardware VRAM bottleneck, chrome crashes if too many concurrent screenshots are rendered via CDP
- semaphore_timeout=5, # shorter semaphore timeout (was 10s)
+ semaphore_timeout=2, # 2 second aggressive semaphore timeout
semaphore_lax=True, # proceed anyway if we cant get a lock
)
async def _take_screenshot_hybrid(self, page: Page) -> str:
@@ -758,17 +758,15 @@ class BrowserSession(BaseModel):
await page.bring_to_front()
try:
- # Add extra timeout protection around screenshot to prevent deadlocks
+ # Aggressive timeout for screenshot
screenshot = await asyncio.wait_for(
page.screenshot(
full_page=False,
- # scale='css',
- timeout=10000, # Balanced playwright timeout (10s)
- # clip parameter removed - no clipping needed for deadlock protection
+ timeout=3000, # 3 second aggressive playwright timeout
animations='allow',
caret='initial',
),
- timeout=12.0, # Extra asyncio timeout as deadlock protection
+ timeout=4.0, # 4 second aggressive asyncio timeout
)
except TimeoutError:
self.logger.warning('🚨 Screenshot deadlock detected (asyncio timeout), restarting browser...')
@@ -2708,11 +2706,11 @@ class BrowserSession(BaseModel):
viewport_expansion=self.browser_profile.viewport_expansion,
highlight_elements=self.browser_profile.highlight_elements,
),
- timeout=30.0, # 30 second timeout for DOM processing
+ timeout=10.0, # 10 second aggressive timeout
)
except TimeoutError:
- self.logger.warning(f'DOM processing timed out after 30 seconds for {page.url} - page may be too complex')
- raise BrowserError(f'Page DOM processing timeout - page may be too complex: {page.url}')
+ self.logger.warning(f'DOM processing timed out after 10 seconds for {page.url}')
+ raise BrowserError(f'DOM timeout: {page.url}')
tabs_info = await self.get_tabs_info()
@@ -2738,18 +2736,13 @@ class BrowserSession(BaseModel):
# )
try:
- # Add timeout protection for screenshot to prevent long hangs on complex pages
+ # Aggressive timeout for screenshot - fail fast
screenshot_b64 = await asyncio.wait_for(
self.take_screenshot(),
- timeout=15.0, # 15 second timeout for screenshot operations
+ timeout=5.0, # 5 second aggressive timeout
)
- except TimeoutError:
- self.logger.warning(
- f'Screenshot timed out after 15 seconds for {page.url} - page may be too complex or slow to render'
- )
- screenshot_b64 = None
except Exception as e:
- self.logger.warning(f'Failed to capture screenshot: {type(e).__name__}: {e}')
+ self.logger.warning(f'Screenshot failed for {page.url}: {type(e).__name__}')
screenshot_b64 = None
pixels_above, pixels_below = await self.get_scroll_info(page)
@@ -2793,7 +2786,7 @@ class BrowserSession(BaseModel):
page = await self.get_current_page()
try:
- await page.wait_for_load_state(timeout=5000)
+ await page.wait_for_load_state(timeout=2000) # 2 second aggressive timeout
except Exception:
pass
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 75404fd81..c480f8c4c 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -352,52 +352,45 @@ Set extract_links=True ONLY if your query requires extracting links/URLs from th
# Run markdownify in a thread pool to avoid blocking the event loop
loop = asyncio.get_event_loop()
- # Try getting page content with retries and timeout protection
+ # Aggressive timeout for page content
try:
- page_html_result = await asyncio.wait_for(page.content(), timeout=10.0) # 15 second timeout
+ page_html_result = await asyncio.wait_for(page.content(), timeout=5.0) # 5 second aggressive timeout
except TimeoutError:
- return ActionResult(error='Page content extraction timed out after 10 seconds. Page content might be too long.')
+ return ActionResult(error='Page content extraction timed out after 5 seconds')
except Exception as e:
- return ActionResult(error=f"Couldn't extract page content due to an error: {e}")
+ return ActionResult(error=f"Couldn't extract page content: {e}")
page_html = page_html_result
markdownify_func = partial(markdownify.markdownify, strip=strip)
try:
- content = await asyncio.wait_for(loop.run_in_executor(None, markdownify_func, page_html), timeout=10.0)
+ content = await asyncio.wait_for(
+ loop.run_in_executor(None, markdownify_func, page_html), timeout=5.0
+ ) # 5 second aggressive timeout
except Exception as e:
- logger.warning(f'Main page markdownify failed: {type(e).__name__}: {e}')
- return ActionResult(error=f'Could not convert html to markdown: {type(e).__name__}: {e}')
+ logger.warning(f'Markdownify failed: {type(e).__name__}')
+ return ActionResult(error=f'Could not convert html to markdown: {type(e).__name__}')
# manually append iframe text into the content so it's readable by the LLM (includes cross-origin iframes)
for iframe in page.frames:
try:
- # some pages have 100 iframes so we should not wait too long here
- await iframe.wait_for_load_state(timeout=100) # extra on top of already loaded page
- except Exception as e:
- logger.debug(f'Error waiting for iframe load state: {type(e).__name__}: {e}')
+ await iframe.wait_for_load_state(timeout=1000) # 1 second aggressive timeout for iframe load
+ except Exception:
pass
if iframe.url != page.url and not iframe.url.startswith('data:') and not iframe.url.startswith('about:'):
content += f'\n\nIFRAME {iframe.url}:\n'
# Run markdownify in a thread pool for iframe content as well
try:
- # Add timeout protection for iframe content extraction
- iframe_html = await asyncio.wait_for(iframe.content(), timeout=5.0) # 5 second timeout
- # Add timeout protection for iframe markdownify to prevent indefinite hangs
+ # Aggressive timeouts for iframe content
+ iframe_html = await asyncio.wait_for(iframe.content(), timeout=2.0) # 2 second aggressive timeout
iframe_markdown = await asyncio.wait_for(
loop.run_in_executor(None, markdownify_func, iframe_html),
- timeout=5.0, # 5 second timeout for iframe markdownify
+ timeout=2.0, # 2 second aggressive timeout for iframe markdownify
)
- except TimeoutError:
- logger.warning(
- f'Iframe processing timed out for {iframe.url} (content extraction or markdownify timeout)'
- )
- iframe_markdown = f'[Iframe processing timed out: {iframe.url}]'
- except Exception as e:
- logger.debug(f'Error extracting iframe content from within page {page.url}: {type(e).__name__}: {e}')
- iframe_markdown = ''
+ except Exception:
+ iframe_markdown = '' # Skip failed iframes
content += iframe_markdown
# replace multiple sequential \n with a single \n
content = re.sub(r'\n+', '\n', content)
@@ -419,10 +412,10 @@ Set extract_links=True ONLY if your query requires extracting links/URLs from th
Explain the content of the page and that the requested information is not available in the page. Respond in JSON format.\nQuery: {query}\n Website:\n{page}"""
try:
formatted_prompt = prompt.format(query=query, page=content)
- # Add timeout protection for LLM call
+ # Aggressive timeout for LLM call
response = await asyncio.wait_for(
page_extraction_llm.ainvoke([UserMessage(content=formatted_prompt)]),
- timeout=60.0, # 60 second timeout for LLM call
+ timeout=30.0, # 30 second aggressive timeout for LLM call
)
extracted_content = f'Page Link: {page.url}\nQuery: {query}\nExtracted Content:\n{response.completion}'
@@ -453,7 +446,7 @@ Explain the content of the page and that the requested information is not availa
long_term_memory=memory,
)
except TimeoutError:
- error_msg = f'LLM call timed out in extract_structured_data after 60 seconds. Output or page content might be too long for query: {query}'
+ error_msg = f'LLM call timed out after 30 seconds for query: {query}'
logger.warning(error_msg)
return ActionResult(error=error_msg)
except Exception as e: