Skip to content

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

fix(tools): enforce per-action timeout to prevent hung event handlers

Saurav Pandace81ada89a99
diff --git a/browser_use/tools/service.py b/browser_use/tools/service.py
index 64db52033..83181c5f7 100644
--- a/browser_use/tools/service.py
+++ b/browser_use/tools/service.py
@@ -74,6 +74,16 @@ Context = TypeVar('Context')
T = TypeVar('T', bound=BaseModel)
+# Global per-action timeout: last-resort guard against hung event handlers.
+# Individual CDP calls (Page.navigate etc.) have their own shorter timeouts,
+# but event-bus `await event` and `event_result()` calls have none — if a
+# watchdog handler blocks on a dead CDP WebSocket, the action can hang past
+# any agent-level watchdog. This cap ensures every action returns within a
+# bounded window with an ActionResult(error=...) instead of hanging silently.
+# Override per-call via BROWSER_USE_ACTION_TIMEOUT_S env var or tools.act(action_timeout=...).
+_DEFAULT_ACTION_TIMEOUT_S = float(os.getenv('BROWSER_USE_ACTION_TIMEOUT_S', '90'))
+
+
def _detect_sensitive_key_name(text: str, sensitive_data: dict[str, str | dict[str, str]] | None) -> str | None:
"""Detect which sensitive key name corresponds to the given text value."""
if not sensitive_data or not text:
@@ -2041,8 +2051,17 @@ Validated Code (after quote fixing):
available_file_paths: list[str] | None = None,
file_system: FileSystem | None = None,
extraction_schema: dict | None = None,
+ action_timeout: float | None = None,
) -> ActionResult:
- """Execute an action"""
+ """Execute an action.
+
+ action_timeout: per-action wall-clock cap (seconds). Prevents actions from hanging
+ indefinitely when a CDP WebSocket goes silent — a common failure mode with remote
+ browsers where internal CDP calls (tab switches, lifecycle waits) have no timeouts.
+ Defaults to BROWSER_USE_ACTION_TIMEOUT_S env var or 90s.
+ """
+
+ timeout_s = action_timeout if action_timeout is not None else _DEFAULT_ACTION_TIMEOUT_S
for action_name, params in action.model_dump(exclude_unset=True).items():
if params is not None:
@@ -2064,22 +2083,36 @@ Validated Code (after quote fixing):
with span_context:
try:
- result = await self.registry.execute_action(
- action_name=action_name,
- params=params,
- browser_session=browser_session,
- page_extraction_llm=page_extraction_llm,
- file_system=file_system,
- sensitive_data=sensitive_data,
- available_file_paths=available_file_paths,
- extraction_schema=extraction_schema,
+ result = await asyncio.wait_for(
+ self.registry.execute_action(
+ action_name=action_name,
+ params=params,
+ browser_session=browser_session,
+ page_extraction_llm=page_extraction_llm,
+ file_system=file_system,
+ sensitive_data=sensitive_data,
+ available_file_paths=available_file_paths,
+ extraction_schema=extraction_schema,
+ ),
+ timeout=timeout_s,
)
except BrowserError as e:
logger.error(f'❌ Action {action_name} failed with BrowserError: {str(e)}')
result = handle_browser_error(e)
- except TimeoutError as e:
- logger.error(f'❌ Action {action_name} failed with TimeoutError: {str(e)}')
- result = ActionResult(error=f'{action_name} was not executed due to timeout.')
+ except TimeoutError:
+ # Covers both the per-action asyncio.wait_for cap and any inner
+ # TimeoutError that bubbled out of the handler.
+ logger.error(
+ f'❌ Action {action_name} hit the per-action timeout ({timeout_s:.0f}s) '
+ f'— likely an unresponsive CDP connection. Returning error so the agent can recover.'
+ )
+ result = ActionResult(
+ error=(
+ f'Action {action_name} timed out after {timeout_s:.0f}s. '
+ f'The browser may be unresponsive (dead CDP WebSocket). '
+ f'Try again or a different approach.'
+ )
+ )
except Exception as e:
# Log the original exception with traceback for observability
logger.error(f"Action '{action_name}' failed with error: {str(e)}")
diff --git a/tests/ci/test_action_timeout.py b/tests/ci/test_action_timeout.py
new file mode 100644
index 000000000..084b73d75
--- /dev/null
+++ b/tests/ci/test_action_timeout.py
@@ -0,0 +1,90 @@
+"""Per-action timeout regression test.
+
+When a CDP WebSocket goes silent (common failure mode with remote / cloud browsers),
+action handlers can await event-bus dispatches that never resolve — individual CDP
+calls like Page.navigate() have their own timeouts, but the surrounding event
+plumbing does not. Without a per-action cap, `tools.act()` hangs indefinitely and
+agents never emit a step, producing empty history traces.
+
+This test replaces `registry.execute_action` with a coroutine that sleeps longer
+than the per-action cap, then asserts that `tools.act()` returns within the cap
+with an ActionResult(error=...) instead of hanging.
+"""
+
+import asyncio
+import time
+from typing import Any
+
+import pytest
+
+from browser_use.agent.views import ActionModel, ActionResult
+from browser_use.tools.service import Tools
+
+
+class _StubActionModel(ActionModel):
+ """ActionModel with two arbitrary named slots for tools.act() plumbing tests.
+
+ Tests target tools.act() behaviour (timeout wrapping, error handling), not any
+ registered action — so we declare fixed slots here and stub out execute_action.
+ """
+
+ hung_action: dict[str, Any] | None = None
+ fast_action: dict[str, Any] | None = None
+
+
+async def test_act_enforces_per_action_timeout_on_hung_handler():
+ """tools.act() must return within action_timeout even if the handler hangs."""
+ tools = Tools()
+
+ # Replace the action executor with one that hangs far past the timeout.
+ sleep_seconds = 30.0
+ call_count = {'n': 0}
+
+ async def _hanging_execute_action(**_kwargs):
+ call_count['n'] += 1
+ await asyncio.sleep(sleep_seconds)
+ return ActionResult(extracted_content='should never be reached')
+
+ tools.registry.execute_action = _hanging_execute_action # type: ignore[assignment]
+
+ # Build an ActionModel with a single slot — act() iterates model_dump(exclude_unset=True).
+ action = _StubActionModel(hung_action={'url': 'https://example.com'})
+
+ # Use a tight timeout so the test runs in under a second.
+ action_timeout = 0.5
+ start = time.monotonic()
+ result = await tools.act(action=action, browser_session=None, action_timeout=action_timeout) # type: ignore[arg-type]
+ elapsed = time.monotonic() - start
+
+ # Handler got invoked exactly once.
+ assert call_count['n'] == 1
+
+ # Returned well before the sleep would have finished.
+ assert elapsed < sleep_seconds / 2, f'act() did not honor timeout; took {elapsed:.2f}s'
+ # And returned close to the timeout itself (with a reasonable grace margin).
+ assert elapsed < action_timeout + 2.0, f'act() overshot timeout; took {elapsed:.2f}s'
+
+ # Returned a proper ActionResult describing the timeout.
+ assert isinstance(result, ActionResult)
+ assert result.error is not None
+ assert 'timed out' in result.error.lower()
+ assert 'hung_action' in result.error
+
+
+async def test_act_passes_through_fast_handler():
+ """When the handler finishes fast, act() returns its result unchanged."""
+ tools = Tools()
+
+ async def _fast_execute_action(**_kwargs):
+ return ActionResult(extracted_content='done')
+
+ tools.registry.execute_action = _fast_execute_action # type: ignore[assignment]
+
+ action = _StubActionModel(fast_action={'x': 1})
+ result = await tools.act(action=action, browser_session=None, action_timeout=5.0) # type: ignore[arg-type]
+
+ assert isinstance(result, ActionResult)
+ assert result.error is None
+ assert result.extracted_content == 'done'