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(cli): detect browser mode mismatch between existing session and requested mode
ShawnPana3c9b2501acfa
diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex 2041f6d68..96c0e4e87 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -182,14 +182,41 @@ def connect_to_server(session: str, timeout: float = 60.0) -> socket.socket:return sock+def get_session_metadata_path(session: str) -> Path:+ """Get path to session metadata file (stores browser_mode, headed, profile)."""+ return Path(tempfile.gettempdir()) / f'browser-use-{session}.meta'++def ensure_server(session: str, browser: str, headed: bool, profile: str | None, api_key: str | None) -> bool:"""Start server if not running. Returns True if started."""+ meta_path = get_session_metadata_path(session)+# Check if server is already running and responsiveif is_server_running(session):try:sock = connect_to_server(session, timeout=0.1)sock.close()- return False # Already running++ # Check browser mode matches existing session+ if meta_path.exists():+ try:+ meta = json.loads(meta_path.read_text())+ existing_mode = meta.get('browser_mode', 'chromium')+ if existing_mode != browser:+ print(+ f"Error: Session '{session}' is running with --browser {existing_mode}, "+ f"but --browser {browser} was requested.\n\n"+ f"Options:\n"+ f" 1. Use existing browser: browser-use --browser {existing_mode} <command>\n"+ f" 2. Use different session: browser-use --browser {browser} --session other <command>\n"+ f" 3. Close existing session: browser-use close",+ file=sys.stderr,+ )+ sys.exit(1)+ except (json.JSONDecodeError, OSError):+ pass # Metadata file corrupt, ignore++ return False # Already running with correct modeexcept Exception:pass # Server dead, restart@@ -239,6 +266,16 @@ def ensure_server(session: str, browser: str, headed: bool, profile: str | None,try:sock = connect_to_server(session, timeout=0.1)sock.close()++ # Write metadata file to track session config+ meta_path.write_text(+ json.dumps({+ 'browser_mode': browser,+ 'headed': headed,+ 'profile': profile,+ })+ )+return Trueexcept Exception:pass@@ -1176,6 +1213,10 @@ def main() -> int:response = send_command(name, 'close', {})if response.get('success'):closed.append(name)+ # Clean up metadata file+ meta_path = get_session_metadata_path(name)+ if meta_path.exists():+ meta_path.unlink()except Exception:pass # Server may already be stopping@@ -1286,6 +1327,12 @@ def main() -> int:# Send command to serverresponse = send_command(args.session, args.command, params)+ # Clean up metadata file on successful close+ if args.command == 'close' and response.get('success'):+ meta_path = get_session_metadata_path(args.session)+ if meta_path.exists():+ meta_path.unlink()+# Output responseif args.json:print(json.dumps(response))diff --git a/tests/ci/test_session_browser_mode.py b/tests/ci/test_session_browser_mode.pynew file mode 100644index 000000000..ea4d3ad42--- /dev/null+++ b/tests/ci/test_session_browser_mode.py@@ -0,0 +1,145 @@+"""Tests for session browser mode validation.++When a session is started with a specific browser mode (chromium, remote, real),+subsequent commands with a different mode should error with helpful guidance.+"""++import json+import tempfile+from pathlib import Path+from unittest.mock import patch++import pytest++from browser_use.skill_cli.main import get_session_metadata_path+++def test_get_session_metadata_path():+ """Test that metadata path is generated correctly."""+ path = get_session_metadata_path('default')+ assert path.parent == Path(tempfile.gettempdir())+ assert path.name == 'browser-use-default.meta'+++def test_get_session_metadata_path_custom_session():+ """Test metadata path for custom session names."""+ path = get_session_metadata_path('my-session')+ assert path.name == 'browser-use-my-session.meta'+++def test_metadata_file_format():+ """Test metadata file format matches expected structure."""+ meta_path = get_session_metadata_path('test-format')+ try:+ # Write metadata as the code does+ meta_path.write_text(+ json.dumps({+ 'browser_mode': 'chromium',+ 'headed': False,+ 'profile': None,+ })+ )++ # Read and verify+ meta = json.loads(meta_path.read_text())+ assert meta['browser_mode'] == 'chromium'+ assert meta['headed'] is False+ assert meta['profile'] is None+ finally:+ if meta_path.exists():+ meta_path.unlink()+++def test_metadata_file_remote_mode():+ """Test metadata file with remote browser mode."""+ meta_path = get_session_metadata_path('test-remote')+ try:+ meta_path.write_text(+ json.dumps({+ 'browser_mode': 'remote',+ 'headed': True,+ 'profile': 'cloud-profile-123',+ })+ )++ meta = json.loads(meta_path.read_text())+ assert meta['browser_mode'] == 'remote'+ assert meta['headed'] is True+ assert meta['profile'] == 'cloud-profile-123'+ finally:+ if meta_path.exists():+ meta_path.unlink()+++def test_metadata_cleanup():+ """Test that metadata file can be cleaned up."""+ meta_path = get_session_metadata_path('test-cleanup')+ meta_path.write_text(json.dumps({'browser_mode': 'chromium'}))+ assert meta_path.exists()++ # Cleanup+ meta_path.unlink()+ assert not meta_path.exists()+++def test_mode_mismatch_detection_logic():+ """Test the mode mismatch detection logic directly."""+ meta_path = get_session_metadata_path('test-mismatch')+ try:+ # Simulate existing session with chromium mode+ meta_path.write_text(json.dumps({'browser_mode': 'chromium'}))++ # Check mismatch detection+ meta = json.loads(meta_path.read_text())+ existing_mode = meta.get('browser_mode', 'chromium')+ requested_mode = 'remote'++ assert existing_mode != requested_mode+ assert existing_mode == 'chromium'+ assert requested_mode == 'remote'+ finally:+ if meta_path.exists():+ meta_path.unlink()+++def test_mode_match_detection_logic():+ """Test that matching modes pass validation."""+ meta_path = get_session_metadata_path('test-match')+ try:+ # Simulate existing session with chromium mode+ meta_path.write_text(json.dumps({'browser_mode': 'chromium'}))++ # Check match passes+ meta = json.loads(meta_path.read_text())+ existing_mode = meta.get('browser_mode', 'chromium')+ requested_mode = 'chromium'++ assert existing_mode == requested_mode+ finally:+ if meta_path.exists():+ meta_path.unlink()+++def test_different_sessions_independent():+ """Test that different session names are independent."""+ session1_meta = get_session_metadata_path('session-a')+ session2_meta = get_session_metadata_path('session-b')++ try:+ # Session A with chromium+ session1_meta.write_text(json.dumps({'browser_mode': 'chromium'}))++ # Session B with remote+ session2_meta.write_text(json.dumps({'browser_mode': 'remote'}))++ # Verify they are independent+ meta1 = json.loads(session1_meta.read_text())+ meta2 = json.loads(session2_meta.read_text())++ assert meta1['browser_mode'] == 'chromium'+ assert meta2['browser_mode'] == 'remote'+ finally:+ if session1_meta.exists():+ session1_meta.unlink()+ if session2_meta.exists():+ session2_meta.unlink()