Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat: add --use-local-profile to browser serve for Chrome profile reuse (#4958)
Marc Kelechava3d1e1c14c494
diff --git a/skyvern/cli/commands/browser.py b/skyvern/cli/commands/browser.pyindex 0557f2530..b96c41bce 100644--- a/skyvern/cli/commands/browser.py+++ b/skyvern/cli/commands/browser.py@@ -15,7 +15,7 @@ if TYPE_CHECKING:import typer-from skyvern.cli.commands._output import output, output_error+from skyvern.cli.commands._output import console, output, output_errorfrom skyvern.cli.commands._state import CLIState, clear_state, load_state, save_statefrom skyvern.cli.core.artifacts import save_artifactfrom skyvern.cli.core.browser_ops import do_act, do_extract, do_navigate, do_screenshot@@ -938,6 +938,16 @@ def serve("--profile-dir",help="Chrome user data directory. Uses existing cookies/auth if specified.",),+ use_local_profile: bool = typer.Option(+ False,+ "--use-local-profile",+ help="Copy cookies/logins from your local Chrome profile so Skyvern can reuse existing sessions.",+ ),+ chrome_profile_name: str = typer.Option(+ "Default",+ "--chrome-profile-name",+ help="Chrome profile subdirectory to copy from (e.g. 'Default', 'Profile 1'). Only used with --use-local-profile.",+ ),download_dir: str | None = typer.Option(None,"--download-dir",@@ -950,6 +960,11 @@ def serve(help="API key for authenticating requests. If set, requires x-api-key header.",),headless: bool = typer.Option(False, "--headless", help="Run Chrome in headless mode."),+ full_profile_copy: bool = typer.Option(+ False,+ "--full-profile-copy",+ help="Copy the entire Chrome user data directory instead of just auth-relevant files. Requires Chrome to be closed.",+ ),chrome_path: str | None = typer.Option(None,"--chrome-path",@@ -985,16 +1000,35 @@ def serve(import signalfrom skyvern.cli.core.browser_launcher import (+ clone_local_chrome_profile,generate_browser_id,get_default_chrome_path,get_default_download_dir,get_default_profile_dir,+ is_chrome_running,launch_chrome_with_cdp,terminate_browser,)from skyvern.cli.core.unified_server import UnifiedServer, UnifiedServerConfigfrom skyvern.cli.run_commands import get_pids_on_port+ if use_local_profile and profile_dir:+ raise typer.BadParameter("--use-local-profile and --profile-dir are mutually exclusive.")++ if full_profile_copy and not use_local_profile:+ raise typer.BadParameter("--full-profile-copy requires --use-local-profile.")++ # Full copy needs Chrome closed; selective copy works while Chrome is open+ if use_local_profile and full_profile_copy and is_chrome_running():+ output_error(+ "Chrome is currently running. Please close all Chrome windows first.",+ hint="--full-profile-copy needs to copy your entire Chrome profile, which requires Chrome to be closed. "+ "Close Chrome, then re-run this command. "+ "Or omit --full-profile-copy for a fast selective copy that works while Chrome is open.",+ json_mode=json_output,+ )+ raise SystemExit(1)+# Chrome runs on internal port, unified server on exposed portchrome_internal_port = port + 1000 # e.g., 9222 -> 10222@@ -1018,6 +1052,29 @@ def serve(# Use unique download directory if not specifiedresolved_download_dir = download_dir or get_default_download_dir(browser_id)+ if use_local_profile:+ try:+ if full_profile_copy and not json_output:+ with console.status("Copying full Chrome profile — this may take 10-20 seconds..."):+ clone_local_chrome_profile(chrome_profile_name, Path(resolved_profile_dir), full=True)+ else:+ clone_local_chrome_profile(chrome_profile_name, Path(resolved_profile_dir), full=full_profile_copy)+ except (FileNotFoundError, ValueError, PermissionError) as e:+ output_error(str(e), json_mode=json_output)+ raise SystemExit(1)+ if not json_output:+ copy_mode = "full" if full_profile_copy else "selective"+ output(+ {+ "status": "profile_cloned",+ "profile_name": chrome_profile_name,+ "dest": resolved_profile_dir,+ "copy_mode": copy_mode,+ },+ action="profile_clone",+ json_mode=False,+ )+if not json_output:output({@@ -1056,10 +1113,11 @@ def serve(# Launch Chrome on internal portbrowser_info = await launch_chrome_with_cdp(port=chrome_internal_port,- profile_dir=profile_dir,+ profile_dir=resolved_profile_dir,headless=headless,chrome_path=chrome_path,download_dir=resolved_download_dir,+ profile_name=chrome_profile_name if use_local_profile else None,)# Start unified server on exposed portdiff --git a/skyvern/cli/core/browser_launcher.py b/skyvern/cli/core/browser_launcher.pyindex cf097ea49..fa2f46bef 100644--- a/skyvern/cli/core/browser_launcher.py+++ b/skyvern/cli/core/browser_launcher.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport platform+import shutilimport subprocessimport uuidfrom dataclasses import dataclass@@ -11,6 +12,7 @@ from pathlib import Pathfrom typing import TYPE_CHECKINGimport httpx+import psutilif TYPE_CHECKING:from subprocess import Popen@@ -85,12 +87,145 @@ def get_default_download_dir(browser_id: str) -> str:return str(download_dir)+def get_local_chrome_profile_dir() -> Path:+ """Return the platform-specific Chrome user data directory."""+ system = platform.system()+ if system == "Darwin":+ return Path.home() / "Library/Application Support/Google/Chrome"+ elif system == "Windows":+ local_app = Path.home() / "AppData" / "Local"+ return local_app / "Google" / "Chrome" / "User Data"+ else:+ return Path.home() / ".config" / "google-chrome"+++_CHROME_MAIN_NAMES = {"chrome", "google-chrome", "google-chrome-stable", "google chrome", "chromium"}+_CHROME_SKIP_NAMES = {"chrome_crashpad_handler", "chromedriver", "chrome helper", "google chrome helper"}+++def is_chrome_running() -> bool:+ """Check if Chrome is already running (main browser process only).++ Uses exact name matching to avoid false positives from helper processes+ (renderer, GPU, utility) and unrelated tools like chromedriver.+ """+ for proc in psutil.process_iter(["name"]):+ try:+ name = (proc.info["name"] or "").lower()+ if name in _CHROME_SKIP_NAMES:+ continue+ if name in _CHROME_MAIN_NAMES:+ return True+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):+ pass+ return False+++_PROFILE_COPY_IGNORE = {+ "Cache",+ "Code Cache",+ "GPUCache",+ "Service Worker",+ "blob_storage",+ "BudgetDatabase",+ "coupon_db",+ "Download Service",+ "GCM Store",+ "optimization_guide_model_metadata",+ "optimization_guide_prediction_model_downloads",+ "Extensions",+ "IndexedDB",+ "File System",+ "Session Storage",+}++_LOCK_FILES = {"SingletonLock", "SingletonSocket", "SingletonCookie"}+++def clone_local_chrome_profile(chrome_profile_name: str, dest_user_data_dir: Path, *, full: bool = False) -> None:+ """Copy the user's local Chrome profile into *dest_user_data_dir*.++ Args:+ chrome_profile_name: Profile subdirectory name (e.g. ``"Default"``).+ dest_user_data_dir: Destination path that will be used as ``--user-data-dir``.+ full: When ``True``, copy the **entire** Chrome user-data directory+ (requires Chrome to be closed). When ``False`` (default), copy+ only the target profile subdir (skipping caches) plus ``Local State``,+ which is much faster (~50-200 MB vs 2-10+ GB).+ """+ source_user_data_dir = get_local_chrome_profile_dir()+ if not source_user_data_dir.is_dir():+ raise FileNotFoundError(+ f"Chrome user data directory not found at {source_user_data_dir}. Is Google Chrome installed?"+ )++ source_profile = source_user_data_dir / chrome_profile_name+ if not source_profile.resolve().is_relative_to(source_user_data_dir.resolve()):+ raise ValueError(f"Profile name '{chrome_profile_name}' resolves outside the Chrome data directory.")++ if not source_profile.is_dir():+ available = [d.name for d in source_user_data_dir.iterdir() if d.is_dir() and not d.name.startswith(".")]+ raise FileNotFoundError(+ f"Chrome profile '{chrome_profile_name}' not found in {source_user_data_dir}. "+ f"Available profiles: {', '.join(sorted(available)[:10])}"+ )++ resolved_dest = dest_user_data_dir.resolve()+ skyvern_data = SKYVERN_DATA_DIR.resolve()+ if not resolved_dest.is_relative_to(skyvern_data):+ raise ValueError(+ f"Refusing to overwrite {dest_user_data_dir} — it is outside Skyvern's data directory ({SKYVERN_DATA_DIR}). "+ "Remove it manually or use the default profile directory."+ )++ if dest_user_data_dir.exists():+ shutil.rmtree(dest_user_data_dir)++ if full:+ shutil.copytree(source_user_data_dir, dest_user_data_dir, ignore_dangling_symlinks=True)+ else:+ _selective_copy(source_user_data_dir, source_profile, chrome_profile_name, dest_user_data_dir)++ # Remove lock files so Chrome can open the copied profile+ for lock_name in _LOCK_FILES:+ lock_file = dest_user_data_dir / lock_name+ if lock_file.exists():+ lock_file.unlink()+++def _selective_copy(+ source_user_data_dir: Path,+ source_profile: Path,+ chrome_profile_name: str,+ dest_user_data_dir: Path,+) -> None:+ """Copy only auth-relevant files from the Chrome profile."""+ dest_user_data_dir.mkdir(parents=True, exist_ok=True)++ # 1. Copy the profile subdir, skipping cache directories+ def _ignore(directory: str, contents: list[str]) -> set[str]:+ return {c for c in contents if c in _PROFILE_COPY_IGNORE}++ shutil.copytree(+ source_profile,+ dest_user_data_dir / chrome_profile_name,+ ignore=_ignore,+ ignore_dangling_symlinks=True,+ )++ # 2. Copy Local State (needed for cookie decryption on macOS/Linux)+ local_state = source_user_data_dir / "Local State"+ if local_state.is_file():+ shutil.copy2(local_state, dest_user_data_dir / "Local State")++async def launch_chrome_with_cdp(port: int,profile_dir: str | None = None,headless: bool = False,chrome_path: str | None = None,download_dir: str | None = None,+ profile_name: str | None = None,) -> LocalBrowserInfo:"""Launch Chrome with CDP enabled and wait for it to be ready.@@ -100,6 +235,9 @@ async def launch_chrome_with_cdp(headless: Whether to run in headless mode.chrome_path: Path to Chrome executable. Auto-detects if not specified.download_dir: Directory for downloads. Uses default if not specified.+ profile_name: Chrome profile subdirectory name (e.g. "Profile 1").+ When set, passes ``--profile-directory`` so Chrome loads the+ correct profile instead of defaulting to ``Default/``.Returns:LocalBrowserInfo with connection details.@@ -122,8 +260,12 @@ async def launch_chrome_with_cdp("--disable-sync","--disable-translate","--metrics-recording-only",+ "--hide-crash-restore-bubble",]+ if profile_name:+ args.append(f"--profile-directory={profile_name}")+if headless:args.append("--headless=new")diff --git a/tests/unit/test_browser_launcher_profile.py b/tests/unit/test_browser_launcher_profile.pynew file mode 100644index 000000000..1bbb6781f--- /dev/null+++ b/tests/unit/test_browser_launcher_profile.py@@ -0,0 +1,318 @@+"""Tests for Chrome profile utilities in browser_launcher.py."""++from __future__ import annotations++from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest++from skyvern.cli.core.browser_launcher import (+ _PROFILE_COPY_IGNORE,+ clone_local_chrome_profile,+ get_local_chrome_profile_dir,+ is_chrome_running,+)+++class TestGetLocalChromeProfileDir:+ def test_darwin(self) -> None:+ with patch("skyvern.cli.core.browser_launcher.platform.system", return_value="Darwin"):+ result = get_local_chrome_profile_dir()+ assert result == Path.home() / "Library/Application Support/Google/Chrome"++ def test_windows(self) -> None:+ with patch("skyvern.cli.core.browser_launcher.platform.system", return_value="Windows"):+ result = get_local_chrome_profile_dir()+ assert result == Path.home() / "AppData" / "Local" / "Google" / "Chrome" / "User Data"++ def test_linux(self) -> None:+ with patch("skyvern.cli.core.browser_launcher.platform.system", return_value="Linux"):+ result = get_local_chrome_profile_dir()+ assert result == Path.home() / ".config" / "google-chrome"+++def _create_mock_chrome_dir(base: Path, profile_name: str = "Default") -> Path:+ """Create a minimal mock Chrome user data directory with cache dirs."""+ chrome_dir = base / "chrome_data"+ profile = chrome_dir / profile_name+ profile.mkdir(parents=True)++ # Local State at the chrome data dir level+ (chrome_dir / "Local State").write_text('{"os_crypt": {}}')++ # Lock files+ (chrome_dir / "SingletonLock").write_text("")+ (chrome_dir / "SingletonSocket").write_text("")+ (chrome_dir / "SingletonCookie").write_text("")++ # Profile-level files+ (profile / "Preferences").write_text('{"profile": {}}')+ (profile / "Cookies").write_bytes(b"fake-sqlite-data")++ # Subdirectory+ local_storage = profile / "Local Storage"+ local_storage.mkdir()+ (local_storage / "data.txt").write_text("stored_value")++ # Cache directories (should be skipped in selective mode)+ for cache_name in [+ "Cache",+ "Code Cache",+ "GPUCache",+ "Service Worker",+ "blob_storage",+ "Extensions",+ "IndexedDB",+ "File System",+ "Session Storage",+ ]:+ cache_dir = profile / cache_name+ cache_dir.mkdir()+ (cache_dir / "data").write_bytes(b"cache_data")++ return chrome_dir+++def _patch_for_clone(chrome_dir: Path, tmp_path: Path):+ """Return a combined context manager that patches both get_local_chrome_profile_dir and SKYVERN_DATA_DIR."""+ return _MultiPatch(chrome_dir, tmp_path)+++class _MultiPatch:+ """Patches get_local_chrome_profile_dir and SKYVERN_DATA_DIR together."""++ def __init__(self, chrome_dir: Path, skyvern_data: Path) -> None:+ self._p1 = patch("skyvern.cli.core.browser_launcher.get_local_chrome_profile_dir", return_value=chrome_dir)+ self._p2 = patch("skyvern.cli.core.browser_launcher.SKYVERN_DATA_DIR", skyvern_data)++ def __enter__(self):+ self._p1.__enter__()+ self._p2.__enter__()+ return self++ def __exit__(self, *args):+ self._p2.__exit__(*args)+ self._p1.__exit__(*args)+++class TestCloneLocalChromeProfileSelective:+ """Tests for selective (default) copy mode."""++ def test_copies_profile_and_local_state(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)+ dest = tmp_path / "dest_data"++ with _patch_for_clone(chrome_dir, tmp_path):+ clone_local_chrome_profile("Default", dest)++ assert (dest / "Local State").exists()+ assert (dest / "Local State").read_text() == '{"os_crypt": {}}'+ assert (dest / "Default" / "Preferences").exists()+ assert (dest / "Default" / "Cookies").exists()+ assert (dest / "Default" / "Local Storage" / "data.txt").exists()+ assert (dest / "Default" / "Local Storage" / "data.txt").read_text() == "stored_value"++ def test_skips_cache_directories(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)+ dest = tmp_path / "dest_data"++ with _patch_for_clone(chrome_dir, tmp_path):+ clone_local_chrome_profile("Default", dest)++ for cache_name in _PROFILE_COPY_IGNORE:+ assert not (dest / "Default" / cache_name).exists(), f"Cache dir {cache_name} should have been skipped"++ def test_clears_lock_files(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)+ dest = tmp_path / "dest_data"++ with _patch_for_clone(chrome_dir, tmp_path):+ clone_local_chrome_profile("Default", dest)++ assert not (dest / "SingletonLock").exists()+ assert not (dest / "SingletonSocket").exists()+ assert not (dest / "SingletonCookie").exists()++ def test_removes_existing_dest_before_copy(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)+ dest = tmp_path / "dest_data"+ dest.mkdir(parents=True)+ (dest / "stale_file.txt").write_text("old")++ with _patch_for_clone(chrome_dir, tmp_path):+ clone_local_chrome_profile("Default", dest)++ assert not (dest / "stale_file.txt").exists()+ assert (dest / "Default" / "Preferences").exists()++ def test_copies_profile_with_spaces_in_name(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path, profile_name="Profile 1")+ dest = tmp_path / "dest_data"++ with _patch_for_clone(chrome_dir, tmp_path):+ clone_local_chrome_profile("Profile 1", dest)++ assert (dest / "Profile 1" / "Preferences").exists()+ assert (dest / "Profile 1" / "Cookies").exists()+ assert (dest / "Local State").exists()++ def test_works_without_local_state(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)+ (chrome_dir / "Local State").unlink()+ dest = tmp_path / "dest_data"++ with _patch_for_clone(chrome_dir, tmp_path):+ clone_local_chrome_profile("Default", dest)++ assert not (dest / "Local State").exists()+ assert (dest / "Default" / "Preferences").exists()+++class TestCloneLocalChromeProfileFull:+ """Tests for full copy mode."""++ def test_copies_full_user_data_dir(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)+ dest = tmp_path / "dest_data"++ with _patch_for_clone(chrome_dir, tmp_path):+ clone_local_chrome_profile("Default", dest, full=True)++ assert (dest / "Local State").exists()+ assert (dest / "Default" / "Preferences").exists()+ assert (dest / "Default" / "Cookies").exists()+ assert (dest / "Default" / "Local Storage" / "data.txt").exists()+ assert (dest / "Default" / "Local Storage" / "data.txt").read_text() == "stored_value"++ def test_full_includes_cache_dirs(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)+ dest = tmp_path / "dest_data"++ with _patch_for_clone(chrome_dir, tmp_path):+ clone_local_chrome_profile("Default", dest, full=True)++ assert (dest / "Default" / "Cache" / "data").exists()+ assert (dest / "Default" / "Code Cache" / "data").exists()++ def test_full_clears_lock_files(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)+ dest = tmp_path / "dest_data"++ with _patch_for_clone(chrome_dir, tmp_path):+ clone_local_chrome_profile("Default", dest, full=True)++ assert not (dest / "SingletonLock").exists()+ assert not (dest / "SingletonSocket").exists()+ assert not (dest / "SingletonCookie").exists()++ def test_full_removes_existing_dest_before_copy(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)+ dest = tmp_path / "dest_data"+ dest.mkdir(parents=True)+ (dest / "stale_file.txt").write_text("old")++ with _patch_for_clone(chrome_dir, tmp_path):+ clone_local_chrome_profile("Default", dest, full=True)++ assert not (dest / "stale_file.txt").exists()+ assert (dest / "Default" / "Preferences").exists()+++class TestCloneLocalChromeProfileErrors:+ def test_raises_when_profile_not_found(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)++ with _patch_for_clone(chrome_dir, tmp_path):+ with pytest.raises(FileNotFoundError, match="NoSuchProfile"):+ clone_local_chrome_profile("NoSuchProfile", tmp_path / "dest")++ def test_lists_available_profiles_in_error(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)+ (chrome_dir / "Profile 1").mkdir()++ with _patch_for_clone(chrome_dir, tmp_path):+ with pytest.raises(FileNotFoundError, match="Default"):+ clone_local_chrome_profile("BadName", tmp_path / "dest")++ def test_rejects_dest_outside_skyvern_data_dir(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)+ skyvern_dir = tmp_path / "skyvern_data"+ skyvern_dir.mkdir()+ outside_dest = tmp_path / "somewhere_else"++ with _patch_for_clone(chrome_dir, skyvern_dir):+ with pytest.raises(ValueError, match="outside Skyvern's data directory"):+ clone_local_chrome_profile("Default", outside_dest)++ def test_raises_when_chrome_not_installed(self, tmp_path: Path) -> None:+ nonexistent = tmp_path / "no_chrome_here"++ with _patch_for_clone(nonexistent, tmp_path):+ with pytest.raises(FileNotFoundError, match="Is Google Chrome installed"):+ clone_local_chrome_profile("Default", tmp_path / "dest")++ def test_rejects_path_traversal_in_profile_name(self, tmp_path: Path) -> None:+ chrome_dir = _create_mock_chrome_dir(tmp_path)++ with _patch_for_clone(chrome_dir, tmp_path):+ with pytest.raises(ValueError, match="resolves outside"):+ clone_local_chrome_profile("../../etc", tmp_path / "dest")+++def _make_proc(name: str) -> MagicMock:+ proc = MagicMock()+ proc.info = {"name": name}+ return proc+++class TestIsChromeRunning:+ def test_detects_chrome_main_process(self) -> None:+ procs = [_make_proc("Google Chrome")]+ with patch("psutil.process_iter", return_value=procs):+ assert is_chrome_running() is True++ def test_detects_lowercase_chrome(self) -> None:+ procs = [_make_proc("chrome")]+ with patch("psutil.process_iter", return_value=procs):+ assert is_chrome_running() is True++ def test_detects_google_chrome_stable(self) -> None:+ procs = [_make_proc("google-chrome-stable")]+ with patch("psutil.process_iter", return_value=procs):+ assert is_chrome_running() is True++ def test_detects_chromium(self) -> None:+ procs = [_make_proc("chromium")]+ with patch("psutil.process_iter", return_value=procs):+ assert is_chrome_running() is True++ def test_ignores_crashpad_handler(self) -> None:+ procs = [_make_proc("chrome_crashpad_handler")]+ with patch("psutil.process_iter", return_value=procs):+ assert is_chrome_running() is False++ def test_ignores_chromedriver(self) -> None:+ procs = [_make_proc("chromedriver")]+ with patch("psutil.process_iter", return_value=procs):+ assert is_chrome_running() is False++ def test_ignores_chrome_helper(self) -> None:+ procs = [_make_proc("Google Chrome Helper")]+ with patch("psutil.process_iter", return_value=procs):+ assert is_chrome_running() is False++ def test_no_false_positive_on_substring(self) -> None:+ """Processes with 'chrome' as a substring should NOT match."""+ procs = [_make_proc("chrome_renderer"), _make_proc("chrome-sandbox")]+ with patch("psutil.process_iter", return_value=procs):+ assert is_chrome_running() is False++ def test_returns_false_with_no_processes(self) -> None:+ with patch("psutil.process_iter", return_value=[]):+ assert is_chrome_running() is False++ def test_returns_false_with_unrelated_processes(self) -> None:+ procs = [_make_proc("firefox"), _make_proc("code"), _make_proc("python")]+ with patch("psutil.process_iter", return_value=procs):+ assert is_chrome_running() is False