Skip to content

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

Fix: Preserve in-use temporary user_data_dir during browser launch

Pyry Takala8bb61d906a69
diff --git a/browser_use/browser/watchdogs/local_browser_watchdog.py b/browser_use/browser/watchdogs/local_browser_watchdog.py
index 19306e9f4..b274b2ce7 100644
--- a/browser_use/browser/watchdogs/local_browser_watchdog.py
+++ b/browser_use/browser/watchdogs/local_browser_watchdog.py
@@ -157,13 +157,22 @@ class LocalBrowserWatchdog(BaseWatchdog):
# Wait for CDP to be ready and get the URL
cdp_url = await self._wait_for_cdp_url(debug_port)
- # Success! Clean up any temp dirs we created but didn't use
- for tmp_dir in self._temp_dirs_to_cleanup:
+ # Success! Clean up only the temp dirs we created but didn't use
+ currently_used_dir = str(profile.user_data_dir)
+ unused_temp_dirs = [tmp_dir for tmp_dir in self._temp_dirs_to_cleanup if str(tmp_dir) != currently_used_dir]
+
+ for tmp_dir in unused_temp_dirs:
try:
shutil.rmtree(tmp_dir, ignore_errors=True)
except Exception:
pass
+ # Keep only the in-use directory for cleanup during browser kill
+ if currently_used_dir and 'browseruse-tmp-' in currently_used_dir:
+ self._temp_dirs_to_cleanup = [Path(currently_used_dir)]
+ else:
+ self._temp_dirs_to_cleanup = []
+
return process, cdp_url
except Exception as e: