Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(browser): select an installed browser compatible with the profile
trohitgde227d816eda
diff --git a/.env.template b/.env.templateindex abb652af..c2ce279c 100644--- a/.env.template+++ b/.env.template@@ -224,6 +224,7 @@ MAX_DELEGATION_DEPTH=2# BROWSER_SANDBOX: auto turns Chrome's sandbox off only as root on Linux# (Docker, the GCP VM), where it cannot start; on/off force it.# BROWSER_CHROME_PATH explicitly selects a browser instead of auto-discovery.+# Auto-discovery skips browsers older than the selected profile requires.# System mode never falls back to a testing-browser download.# BROWSER_DOWNLOAD_MAX_MB caps each file a# page downloads.diff --git a/docs-internal/browser.md b/docs-internal/browser.mdindex 9525c3bb..3d9072f8 100644--- a/docs-internal/browser.md+++ b/docs-internal/browser.md@@ -24,8 +24,11 @@ session. Normal and Dev modes use the same viewer component.## Installation and configuration-The default `BROWSER_RUNTIME=system` discovers installed Chrome first, then-Edge/Chromium. `BROWSER_CHROME_PATH` selects an explicit executable. If none+The default `BROWSER_RUNTIME=system` checks installed Chrome first, then+Edge/Chromium, selecting the first browser new enough for the requested profile+and runtime minimum. For example, a profile last opened by version 154 skips+Chrome 153 and can use installed Edge 154. `BROWSER_CHROME_PATH` selects an+exclusive executable override; an incompatible override fails instead of switching browsers. If noneis available, startup fails with setup guidance: there is no automatic Chromefor Testing download or fallback. System mode preserves the browser's nativeuser agent. An installed browser is not a guarantee that a website will accept@@ -71,7 +74,8 @@ The CLI receives its own per-profile home, runtime and temporary directories.The profile version guard checks the browser executable actually selected, notthe testing pin. A browser older than the version that last wrote the profile-is rejected with actionable guidance. OpenCompany neither deletes that profile+is skipped during automatic discovery, or rejected with actionable guidance+when explicitly selected or no compatible browser is installed. OpenCompany neither deletes that profilenor silently creates a replacement; select a compatible browser or explicitlychoose a different profile. This protects saved sessions during runtime changes.diff --git a/server/nodes/browser/_install_chrome.py b/server/nodes/browser/_install_chrome.pyindex fc9fdf5f..7ec5de82 100644--- a/server/nodes/browser/_install_chrome.py+++ b/server/nodes/browser/_install_chrome.py@@ -173,19 +173,20 @@ class ChromeInstaller:raise NodeUserError("BROWSER_RUNTIME must be system or testing.")return provider- async def _selected(self, exe: Path, source: str) -> Path:+ async def _selected(self, exe: Path, source: str, *, min_major: int = 0, version: Optional[str] = None) -> Path:from ._system_browser import browser_version, version_major- version = await browser_version(exe)- if version_major(version) < self.pin.min_major:- raise NodeUserError(f"The selected browser is version {version}; OpenCompany requires version {self.pin.min_major} or newer. Update your browser or select another BROWSER_CHROME_PATH.")+ version = version or await browser_version(exe)+ required_major = max(min_major, self.pin.min_major)+ if version_major(version) < required_major:+ raise NodeUserError(f"The selected browser is version {version}; this profile requires version {required_major} or newer. Update your browser or select another BROWSER_CHROME_PATH.")self.state.phase, self.state.exe, self.state.version = "ready", str(exe), versionself.state.source, self.state.error = source, Nonereturn exe# -- install ----------------------------------------------------------- async def ensure(self, *, wait: float) -> Path:+ async def ensure(self, *, wait: float, min_major: int = 0) -> Path:"""Path to a supported browser; only testing mode may download it.Testing downloads wait at most ``wait`` seconds and keep running in@@ -193,21 +194,21 @@ class ChromeInstaller:"""from core.container import container- from ._system_browser import discover_browser+ from ._system_browser import select_browserprovider = self.provider()raw = str(getattr(container.settings(), "browser_chrome_path", "") or "").strip()if raw or provider == "system":try:- exe, source = discover_browser(raw)- return await self._selected(exe, source)+ exe, source, version = await select_browser(min_major=max(min_major, self.pin.min_major), override=raw)+ return await self._selected(exe, source, min_major=min_major, version=version)except Exception as exc:self.state.phase, self.state.error = "failed", str(exc)self.state.version, self.state.exe, self.state.source = "", None, ""raiseexe = self.installed_exe()if exe is not None:- return await self._selected(exe, "testing")+ return await self._selected(exe, "testing", min_major=min_major)task = await self._start()try:@@ -216,7 +217,7 @@ class ChromeInstaller:pct = self.state.percentprogress = f" ({pct}%)" if pct is not None else ""raise NodeUserError(f"Installing the browser{progress}. This happens once; try again in a minute.") from None- return await self._selected(exe, "testing")+ return await self._selected(exe, "testing", min_major=min_major)async def _start(self) -> asyncio.Task:async with self._lock:diff --git a/server/nodes/browser/_runtime.py b/server/nodes/browser/_runtime.pyindex f4c8a8d0..cfa7bbd6 100644--- a/server/nodes/browser/_runtime.py+++ b/server/nodes/browser/_runtime.py@@ -227,7 +227,7 @@ class BrowserRuntime:settings = self._settings()pin = get_config().chromeinstaller = get_chrome_installer()- exe = await installer.ensure(wait=float(settings.browser_install_timeout_seconds))+ exe = await installer.ensure(wait=float(settings.browser_install_timeout_seconds), min_major=profile.chrome_major or 0)selected_version = installer.state.versionselected_major = version_major(selected_version)if profile.chrome_major and profile.chrome_major > selected_major:diff --git a/server/nodes/browser/_system_browser.py b/server/nodes/browser/_system_browser.pyindex b820f985..55d88978 100644--- a/server/nodes/browser/_system_browser.py+++ b/server/nodes/browser/_system_browser.py@@ -39,7 +39,8 @@ def _candidates():yield Path(found), name-def discover_browser(override: str = "") -> tuple[Path, str]:+def discover_browsers(override: str = "") -> list[tuple[Path, str]]:+ """Installed candidates in preference order; an explicit path is exclusive."""if override.strip():path = Path(override).expanduser()if not path.is_file():@@ -47,6 +48,7 @@ def discover_browser(override: str = "") -> tuple[Path, str]:candidates = [(path, "override")]else:candidates = _candidates()+ found = []for path, source in candidates:if not path.is_file():continue@@ -54,10 +56,36 @@ def discover_browser(override: str = "") -> tuple[Path, str]:if override:raise NodeUserError("BROWSER_CHROME_PATH points at a snap browser. Install Chrome/Chromium outside snap so it can access OpenCompany's profile.")continue- return path, source+ if not any(existing == path for existing, _ in found):+ found.append((path, source))+ if found:+ return foundraise NodeUserError("No installed Chrome, Edge or Chromium was found. Install one or set BROWSER_CHROME_PATH to its executable. To download the managed test browser instead, explicitly set BROWSER_RUNTIME=testing.")+def discover_browser(override: str = "") -> tuple[Path, str]:+ return discover_browsers(override)[0]+++async def select_browser(*, min_major: int, override: str = "") -> tuple[Path, str, str]:+ """Prefer Chrome, but skip browsers too old to open the requested profile."""+ rejected = []+ for path, source in discover_browsers(override):+ try:+ version = await browser_version(path)+ if version_major(version) >= min_major:+ return path, source, version+ rejected.append(f"{source}: {version}")+ except (NodeUserError, OSError, TimeoutError) as exc:+ rejected.append(f"{source}: {exc}")+ selection = "BROWSER_CHROME_PATH" if override else "The installed browsers"+ raise NodeUserError(+ f"{selection} cannot open this profile: it requires version {min_major} or newer. "+ f"Found: {'; '.join(rejected)}. Update your browser or select a compatible BROWSER_CHROME_PATH. "+ "The existing profile has been preserved."+ )++def _windows_version(path: Path) -> str:# chrome.exe --version can open a GUI on Windows. Read VERSIONINFO instead.from ctypes import wintypesdiff --git a/server/tests/nodes/browser/test_system_browser.py b/server/tests/nodes/browser/test_system_browser.pyindex 026e3233..9cb440ba 100644--- a/server/tests/nodes/browser/test_system_browser.py+++ b/server/tests/nodes/browser/test_system_browser.py@@ -71,7 +71,7 @@ async def test_posix_version_timeout_kills_and_reaps(monkeypatch):async def test_system_provider_reports_actual_version_and_never_installs(monkeypatch):settings(monkeypatch)installer = ChromeInstaller()- monkeypatch.setattr(system, "discover_browser", lambda raw: (Path("edge"), "edge"))+ monkeypatch.setattr(system, "discover_browsers", lambda raw: [(Path("edge"), "edge")])monkeypatch.setattr(system, "browser_version", AsyncMock(return_value="151.2.3.4"))monkeypatch.setattr(installer, "_start", AsyncMock(side_effect=AssertionError("no download")))assert installer.status()["version"] == ""@@ -83,7 +83,7 @@ async def test_system_provider_reports_actual_version_and_never_installs(monkeypasync def test_missing_system_browser_does_not_download(monkeypatch):settings(monkeypatch)installer = ChromeInstaller()- monkeypatch.setattr(system, "discover_browser", Mock(side_effect=NodeUserError("install a browser")))+ monkeypatch.setattr(system, "discover_browsers", Mock(side_effect=NodeUserError("install a browser")))download = AsyncMock(side_effect=AssertionError("no fallback"))monkeypatch.setattr(installer, "_start", download)with pytest.raises(NodeUserError, match="install a browser"):@@ -96,12 +96,55 @@ async def test_missing_system_browser_does_not_download(monkeypatch):async def test_minimum_browser_gate(monkeypatch):settings(monkeypatch)installer = ChromeInstaller()- monkeypatch.setattr(system, "discover_browser", lambda raw: (Path("chrome"), "chrome"))+ monkeypatch.setattr(system, "discover_browsers", lambda raw: [(Path("chrome"), "chrome")])monkeypatch.setattr(system, "browser_version", AsyncMock(return_value="100.0.0.0"))with pytest.raises(NodeUserError, match="requires version"):await installer.ensure(wait=10)[email protected]("required,expected", [(0, "chrome"), (154, "edge")])+async def test_selection_uses_first_browser_compatible_with_profile(monkeypatch, required, expected):+ settings(monkeypatch)+ monkeypatch.setattr(system, "discover_browsers", lambda raw: [(Path("chrome"), "chrome"), (Path("edge"), "edge")])+ versions = {"chrome": "153.0.0.0", "edge": "154.0.0.0"}+ monkeypatch.setattr(system, "browser_version", AsyncMock(side_effect=lambda path: versions[path.name]))+ installer = ChromeInstaller()+ monkeypatch.setattr(installer, "_start", AsyncMock(side_effect=AssertionError("no download")))+ assert await installer.ensure(wait=10, min_major=required) == Path(expected)+ assert installer.state.version == versions[expected]+ assert installer.state.source == expected+++async def test_all_installed_browsers_too_old_preserves_profile(monkeypatch):+ settings(monkeypatch)+ monkeypatch.setattr(system, "discover_browsers", lambda raw: [(Path("chrome"), "chrome"), (Path("edge"), "edge")])+ monkeypatch.setattr(system, "browser_version", AsyncMock(return_value="153.0.0.0"))+ installer = ChromeInstaller()+ with pytest.raises(NodeUserError, match="requires version 154.*profile has been preserved"):+ await installer.ensure(wait=10, min_major=154)+ assert installer.state.phase == "failed"+ assert installer.state.exe is None+++async def test_old_explicit_browser_never_switches_to_another_browser(monkeypatch):+ settings(monkeypatch, browser_chrome_path="chosen.exe")+ monkeypatch.setattr(Path, "is_file", lambda path: path.name == "chosen.exe")+ monkeypatch.setattr(system, "_candidates", Mock(side_effect=AssertionError("override is exclusive")))+ monkeypatch.setattr(system, "browser_version", AsyncMock(return_value="153.0.0.0"))+ with pytest.raises(NodeUserError, match="BROWSER_CHROME_PATH.*requires version 154"):+ await ChromeInstaller().ensure(wait=10, min_major=154)+++async def test_unreadable_candidate_does_not_hide_compatible_browser(monkeypatch):+ monkeypatch.setattr(system, "discover_browsers", lambda raw: [(Path("chrome"), "chrome"), (Path("edge"), "edge")])+ monkeypatch.setattr(system, "browser_version", AsyncMock(side_effect=[OSError("unreadable"), "154.0.0.0"]))+ assert await system.select_browser(min_major=154) == (Path("edge"), "edge", "154.0.0.0")++@pytest.mark.asyncioasync def test_testing_provider_is_explicit_and_override_still_wins(monkeypatch):config = settings(monkeypatch, browser_runtime="testing")@@ -111,7 +154,7 @@ async def test_testing_provider_is_explicit_and_override_still_wins(monkeypatch)assert await installer.ensure(wait=10) == Path("testing")assert installer.status()["source"] == "testing"config.browser_chrome_path = "custom"- monkeypatch.setattr(system, "discover_browser", lambda raw: (Path(raw), "override"))+ monkeypatch.setattr(system, "discover_browsers", lambda raw: [(Path(raw), "override")])assert await installer.ensure(wait=10) == Path("custom")assert installer.status()["source"] == "override"@@ -130,6 +173,7 @@ async def test_downgrade_guard_uses_selected_browser_before_launch(monkeypatch):profile = Profile("id", "owner", "saved", "custom", None, 152)with pytest.raises(NodeUserError, match="browser 151"):await runtime._start(profile)+ installer.ensure.assert_awaited_once_with(wait=10.0, min_major=152)@pytest.mark.asyncio