Skip to content

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

docs(cloud): cancel runs after example timeout

MagMueller2391a244b3bb
diff --git a/examples/cloud/01_basic_task.py b/examples/cloud/01_basic_task.py
index 2e88ff668..1be9d67f7 100644
--- a/examples/cloud/01_basic_task.py
+++ b/examples/cloud/01_basic_task.py
@@ -14,6 +14,7 @@ API_KEY = os.getenv('BROWSER_USE_API_KEY')
if not API_KEY:
raise RuntimeError('Set BROWSER_USE_API_KEY or add it to .env')
+RUN_TIMEOUT_SECONDS = float(os.getenv('BROWSER_USE_RUN_TIMEOUT', '900'))
HEADERS = {'X-Browser-Use-API-Key': API_KEY}
TERMINAL_STATUSES = {'completed', 'failed', 'cancelled'}
@@ -24,7 +25,9 @@ def create_run(task: str) -> str:
return response.json()['id']
-def wait_for_run(run_id: str, poll_seconds: float = 2) -> dict[str, Any]:
+def wait_for_run(run_id: str, poll_seconds: float = 2, timeout_seconds: float = RUN_TIMEOUT_SECONDS) -> dict[str, Any]:
+ deadline = time.monotonic() + timeout_seconds
+
while True:
response = requests.get(f'{API_URL}/runs/{run_id}/status', headers=HEADERS, timeout=30)
response.raise_for_status()
@@ -34,6 +37,11 @@ def wait_for_run(run_id: str, poll_seconds: float = 2) -> dict[str, Any]:
if status in TERMINAL_STATUSES:
break
+ if time.monotonic() >= deadline:
+ response = requests.post(f'{API_URL}/runs/{run_id}/cancel', headers=HEADERS, timeout=30)
+ response.raise_for_status()
+ raise TimeoutError(f'Cancelled run {run_id} after {timeout_seconds:g} seconds')
+
time.sleep(poll_seconds)
response = requests.get(f'{API_URL}/runs/{run_id}', headers=HEADERS, timeout=30)
diff --git a/examples/cloud/README.md b/examples/cloud/README.md
index 6c2024ac1..adea218ed 100644
--- a/examples/cloud/README.md
+++ b/examples/cloud/README.md
@@ -1,6 +1,6 @@
# Browser Use Cloud API V4
-Run one browser task through the current Cloud API. The example creates a run, polls the lightweight status endpoint, and fetches the result once the run is terminal.
+Run one browser task through the current Cloud API. The example creates a run, polls the lightweight status endpoint, and fetches the result once the run is terminal. It cancels a run that exceeds the configurable 15-minute wait limit.
## Setup
diff --git a/examples/cloud/env.example b/examples/cloud/env.example
index 73f1e2ebf..32f021455 100644
--- a/examples/cloud/env.example
+++ b/examples/cloud/env.example
@@ -3,3 +3,6 @@ BROWSER_USE_API_KEY=your_api_key_here
# Optional: override the API root for an enterprise installation.
# BROWSER_USE_API_URL=https://api.browser-use.com/api/v4
+
+# Optional: cancel a run if it has not finished after this many seconds.
+# BROWSER_USE_RUN_TIMEOUT=900