Skip to content

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

refactor(cli): consolidate tunnel code into single tunnel.py

ShawnPana4d8c4e5e483c
diff --git a/browser_use/skill_cli/commands/__init__.py b/browser_use/skill_cli/commands/__init__.py
index 9f9695884..cc9403b16 100644
--- a/browser_use/skill_cli/commands/__init__.py
+++ b/browser_use/skill_cli/commands/__init__.py
@@ -9,7 +9,6 @@ from browser_use.skill_cli.commands import (
python_exec,
session,
setup,
- tunnel,
)
__all__ = [
@@ -21,5 +20,4 @@ __all__ = [
'python_exec',
'session',
'setup',
- 'tunnel',
]
diff --git a/browser_use/skill_cli/commands/doctor.py b/browser_use/skill_cli/commands/doctor.py
index 49157ce0e..b1cca0cf1 100644
--- a/browser_use/skill_cli/commands/doctor.py
+++ b/browser_use/skill_cli/commands/doctor.py
@@ -98,7 +98,7 @@ def _check_api_key_config() -> dict[str, Any]:
def _check_cloudflared() -> dict[str, Any]:
"""Check if cloudflared is available."""
- from browser_use.skill_cli.tunnel_manager import get_tunnel_manager
+ from browser_use.skill_cli.tunnel import get_tunnel_manager
tunnel_mgr = get_tunnel_manager()
status_info = tunnel_mgr.get_status()
diff --git a/browser_use/skill_cli/commands/setup.py b/browser_use/skill_cli/commands/setup.py
index 8b4ac5f68..e60f7bbf5 100644
--- a/browser_use/skill_cli/commands/setup.py
+++ b/browser_use/skill_cli/commands/setup.py
@@ -111,7 +111,7 @@ async def run_checks(mode: Literal['local', 'remote', 'full']) -> dict[str, Any]
# Cloudflared check (remote and full modes)
if mode in ('remote', 'full'):
- from browser_use.skill_cli.tunnel_manager import get_tunnel_manager
+ from browser_use.skill_cli.tunnel import get_tunnel_manager
tunnel_mgr = get_tunnel_manager()
status = tunnel_mgr.get_status()
@@ -286,7 +286,7 @@ async def validate_setup(
if mode in ('remote', 'full'):
from browser_use.skill_cli.api_key import check_api_key
- from browser_use.skill_cli.tunnel_manager import get_tunnel_manager
+ from browser_use.skill_cli.tunnel import get_tunnel_manager
api_check = check_api_key()
results['api_key_available'] = api_check['available']
diff --git a/browser_use/skill_cli/commands/tunnel.py b/browser_use/skill_cli/commands/tunnel.py
deleted file mode 100644
index 9de063f2d..000000000
--- a/browser_use/skill_cli/commands/tunnel.py
+++ /dev/null
@@ -1,121 +0,0 @@
-"""Tunnel commands - expose localhost ports via Cloudflare quick tunnels."""
-
-import asyncio
-import logging
-import re
-from typing import Any
-
-from browser_use.skill_cli.sessions import SessionInfo
-
-logger = logging.getLogger(__name__)
-
-COMMANDS = {'tunnel'}
-
-_URL_PATTERN = re.compile(r'(https://\S+\.trycloudflare\.com)')
-
-
-async def handle(action: str, session_info: SessionInfo, params: dict[str, Any]) -> Any:
- """Handle tunnel command."""
- subcommand = params.get('subcommand', 'start')
-
- if subcommand == 'list':
- return list_tunnels(session_info)
- elif subcommand == 'stop':
- port = params.get('port')
- if port is None:
- return {'error': 'port is required for tunnel stop'}
- return await stop_tunnel(session_info, int(port))
- else:
- # Default: start
- port = params.get('port')
- if port is None:
- return {'error': 'port is required for tunnel start'}
- return await start_tunnel(session_info, int(port))
-
-
-async def start_tunnel(session_info: SessionInfo, port: int) -> dict[str, Any]:
- """Start a cloudflare quick tunnel for a local port."""
- # Check if tunnel already exists for this port
- if port in session_info.tunnels:
- info = session_info.tunnels[port]
- return {'url': info.url, 'port': port, 'existing': True}
-
- # Get cloudflared binary (auto-installs if needed)
- from browser_use.skill_cli.tunnel_manager import get_tunnel_manager
-
- try:
- tunnel_manager = get_tunnel_manager()
- cloudflared_binary = tunnel_manager.get_binary_path()
- except RuntimeError as e:
- return {'error': str(e)}
-
- # Spawn cloudflared process
- process = await asyncio.create_subprocess_exec(
- cloudflared_binary,
- 'tunnel',
- '--url',
- f'http://localhost:{port}',
- stdout=asyncio.subprocess.DEVNULL,
- stderr=asyncio.subprocess.PIPE,
- )
-
- # Read stderr lines until we find the tunnel URL
- assert process.stderr is not None
- url: str | None = None
- try:
- deadline = asyncio.get_event_loop().time() + 15
- while asyncio.get_event_loop().time() < deadline:
- try:
- line_bytes = await asyncio.wait_for(process.stderr.readline(), timeout=1.0)
- except TimeoutError:
- continue
- if not line_bytes:
- break
- line = line_bytes.decode(errors='replace')
- match = _URL_PATTERN.search(line)
- if match:
- url = match.group(1)
- break
- except Exception as e:
- process.terminate()
- return {'error': f'Failed to start tunnel: {e}'}
-
- if url is None:
- process.terminate()
- return {'error': 'Timed out waiting for cloudflare tunnel URL (15s)'}
-
- # Store tunnel info
- from browser_use.skill_cli.sessions import TunnelInfo
-
- session_info.tunnels[port] = TunnelInfo(port=port, url=url, process=process)
- logger.info(f'Tunnel started: localhost:{port} -> {url}')
-
- return {'url': url, 'port': port}
-
-
-def list_tunnels(session_info: SessionInfo) -> dict[str, Any]:
- """List active tunnels."""
- tunnels = [{'port': info.port, 'url': info.url} for info in session_info.tunnels.values()]
- return {'tunnels': tunnels, 'count': len(tunnels)}
-
-
-async def stop_tunnel(session_info: SessionInfo, port: int) -> dict[str, Any]:
- """Stop a tunnel for a specific port."""
- if port not in session_info.tunnels:
- return {'error': f'No tunnel running on port {port}'}
-
- info = session_info.tunnels.pop(port)
- info.process.terminate()
- try:
- await asyncio.wait_for(info.process.wait(), timeout=5)
- except TimeoutError:
- info.process.kill()
- logger.info(f'Tunnel stopped: localhost:{port}')
-
- return {'stopped': port, 'url': info.url}
-
-
-async def stop_all_tunnels(session_info: SessionInfo) -> None:
- """Stop all tunnels. Called during session cleanup."""
- for port in list(session_info.tunnels.keys()):
- await stop_tunnel(session_info, port)
diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.py
index f58440bdc..2538fbbd8 100755
--- a/browser_use/skill_cli/main.py
+++ b/browser_use/skill_cli/main.py
@@ -1094,19 +1094,19 @@ def main() -> int:
# Handle tunnel command - runs independently of browser session
if args.command == 'tunnel':
- from browser_use.skill_cli import tunnel_manager
+ from browser_use.skill_cli import tunnel
pos = getattr(args, 'port_or_subcommand', None)
if pos == 'list':
- result = tunnel_manager.list_tunnels()
+ result = tunnel.list_tunnels()
elif pos == 'stop':
port_arg = getattr(args, 'port_arg', None)
if getattr(args, 'all', False):
# stop --all
- result = asyncio.get_event_loop().run_until_complete(tunnel_manager.stop_all_tunnels())
+ result = asyncio.get_event_loop().run_until_complete(tunnel.stop_all_tunnels())
elif port_arg is not None:
- result = asyncio.get_event_loop().run_until_complete(tunnel_manager.stop_tunnel(port_arg))
+ result = asyncio.get_event_loop().run_until_complete(tunnel.stop_tunnel(port_arg))
else:
print('Usage: browser-use tunnel stop <port> | --all', file=sys.stderr)
return 1
@@ -1116,7 +1116,7 @@ def main() -> int:
except ValueError:
print(f'Unknown tunnel subcommand: {pos}', file=sys.stderr)
return 1
- result = asyncio.get_event_loop().run_until_complete(tunnel_manager.start_tunnel(port))
+ result = asyncio.get_event_loop().run_until_complete(tunnel.start_tunnel(port))
else:
print('Usage: browser-use tunnel <port> | list | stop <port>', file=sys.stderr)
return 0
diff --git a/browser_use/skill_cli/server.py b/browser_use/skill_cli/server.py
index cdde2dca5..859473f3c 100644
--- a/browser_use/skill_cli/server.py
+++ b/browser_use/skill_cli/server.py
@@ -103,7 +103,7 @@ class SessionServer:
try:
# Import command handlers
- from browser_use.skill_cli.commands import agent, browser, python_exec, session, tunnel
+ from browser_use.skill_cli.commands import agent, browser, python_exec, session
# Handle shutdown
if action == 'shutdown':
@@ -128,8 +128,6 @@ class SessionServer:
# Dispatch to handler
if action in browser.COMMANDS:
result = await browser.handle(action, session_info, params)
- elif action in tunnel.COMMANDS:
- result = await tunnel.handle(action, session_info, params)
elif action == 'python':
result = await python_exec.handle(session_info, params)
elif action == 'run':
diff --git a/browser_use/skill_cli/sessions.py b/browser_use/skill_cli/sessions.py
index 4c4762026..f8baf2ff1 100644
--- a/browser_use/skill_cli/sessions.py
+++ b/browser_use/skill_cli/sessions.py
@@ -1,6 +1,5 @@
"""Session registry - manages BrowserSession instances."""
-import asyncio
import logging
from dataclasses import dataclass, field
from typing import Any
@@ -11,15 +10,6 @@ from browser_use.skill_cli.python_session import PythonSession
logger = logging.getLogger(__name__)
-@dataclass
-class TunnelInfo:
- """Information about an active cloudflare tunnel."""
-
- port: int
- url: str
- process: asyncio.subprocess.Process
-
-
@dataclass
class SessionInfo:
"""Information about a browser session."""
@@ -30,7 +20,6 @@ class SessionInfo:
profile: str | None
browser_session: BrowserSession
python_session: PythonSession = field(default_factory=PythonSession)
- tunnels: dict[int, TunnelInfo] = field(default_factory=dict)
class SessionRegistry:
@@ -93,7 +82,7 @@ class SessionRegistry:
session = self._sessions.pop(name)
logger.info(f'Closing session: {name}')
- # Note: Tunnels are now managed independently via tunnel_manager.py
+ # Note: Tunnels are managed independently via tunnel.py
# They persist across session close/open cycles
try:
diff --git a/browser_use/skill_cli/tunnel_manager.py b/browser_use/skill_cli/tunnel.py
similarity index 100%
rename from browser_use/skill_cli/tunnel_manager.py
rename to browser_use/skill_cli/tunnel.py
diff --git a/tests/ci/test_doctor_command.py b/tests/ci/test_doctor_command.py
index eeec1164e..746a2ace4 100644
--- a/tests/ci/test_doctor_command.py
+++ b/tests/ci/test_doctor_command.py
@@ -82,7 +82,7 @@ def test_check_api_key_missing():
def test_check_cloudflared_available():
"""Test _check_cloudflared when available."""
- with patch('browser_use.skill_cli.tunnel_manager.get_tunnel_manager') as mock_mgr:
+ with patch('browser_use.skill_cli.tunnel.get_tunnel_manager') as mock_mgr:
mock_instance = mock_mgr.return_value
mock_instance.get_status.return_value = {
'available': True,
@@ -95,7 +95,7 @@ def test_check_cloudflared_available():
def test_check_cloudflared_missing():
"""Test _check_cloudflared when not available."""
- with patch('browser_use.skill_cli.tunnel_manager.get_tunnel_manager') as mock_mgr:
+ with patch('browser_use.skill_cli.tunnel.get_tunnel_manager') as mock_mgr:
mock_instance = mock_mgr.return_value
mock_instance.get_status.return_value = {
'available': False,
diff --git a/tests/ci/test_tunnel_manager.py b/tests/ci/test_tunnel.py
similarity index 92%
rename from tests/ci/test_tunnel_manager.py
rename to tests/ci/test_tunnel.py
index a6e8403c7..ae172f3cb 100644
--- a/tests/ci/test_tunnel_manager.py
+++ b/tests/ci/test_tunnel.py
@@ -1,10 +1,10 @@
-"""Tests for TunnelManager - cloudflared binary management."""
+"""Tests for tunnel module - cloudflared binary management."""
from unittest.mock import patch
import pytest
-from browser_use.skill_cli.tunnel_manager import TunnelManager, get_tunnel_manager
+from browser_use.skill_cli.tunnel import TunnelManager, get_tunnel_manager
@pytest.fixture
@@ -77,9 +77,9 @@ def test_tunnel_manager_status_not_installed(tunnel_manager):
def test_get_tunnel_manager_singleton():
"""Test that get_tunnel_manager returns a singleton."""
# Reset the global singleton
- import browser_use.skill_cli.tunnel_manager as tm_module
+ import browser_use.skill_cli.tunnel as tunnel_module
- tm_module._tunnel_manager = None
+ tunnel_module._tunnel_manager = None
mgr1 = get_tunnel_manager()
mgr2 = get_tunnel_manager()