Skip to content

Self-improving AI Employees for everyone

fix(browser): discover installed browser paths dynamically by family

trohitg9674c49ef83d
diff --git a/.env.template b/.env.template
index ea7b90c4..d8d25f72 100644
--- a/.env.template
+++ b/.env.template
@@ -223,8 +223,9 @@ MAX_DELEGATION_DEPTH=2
# BROWSER_INSTALL_TIMEOUT_SECONDS bounds CLI installation and testing downloads.
# 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.
-# Set it to installed Chrome's executable to prevent switching to Edge/Chromium.
+# BROWSER_FAMILY selects chrome (default), edge, chromium, or auto by name.
+# Discovery uses OS registration, PATH, and standard installation locations.
+# BROWSER_CHROME_PATH is an optional explicit override; normally leave it empty.
# 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
@@ -234,6 +235,7 @@ BROWSER_IDLE_TIMEOUT_MS=600000
BROWSER_INSTALL_TIMEOUT_SECONDS=900
BROWSER_SANDBOX=auto
BROWSER_CHROME_PATH=
+BROWSER_FAMILY=chrome
BROWSER_RUNTIME=system
BROWSER_HEADLESS=true
BROWSER_DOWNLOAD_MAX_MB=200
diff --git a/CLAUDE.md b/CLAUDE.md
index 976d6686..553ad682 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2720,7 +2720,7 @@ This function:
- Supports TTL expiration and automatic cleanup of expired entries
- **Conditional Redis (historical)**: the Docker Compose topology (Redis profiles, `scripts/docker.js` wrapper) is historical — see [docs-internal/deployment_legacy.md](./docs-internal/deployment_legacy.md)
- **WebSocket Reconnect via PartySocket** (`partysocket/ws` from Cloudflare): native-WS-compatible class handles jittered exponential backoff, message replay (`maxEnqueuedMessages: 200`), and intentional-close (RFC 6455 §7.4.1 code 1000) automatically. Replaces the previous flat 3 s `setTimeout(connect, 3000)` loop. Reconnect envelope (`MIN_DELAY_MS: 250`, `MAX_DELAY_MS: 8000`, `GROW_FACTOR: 1.3`) lives in `client/src/lib/connectionConfig.ts`. The +12 s WS-drop-and-reconnect cycle observed under React Strict Mode is gone — verified across two consecutive cold launches with zero `Client disconnected` events through 130+ s of activity. See `docs-internal/performance.md` for measurements.
-- **Docker image runs uvicorn, not `company serve`**: `docker/entrypoint.sh` writes the three secrets into `/data/opencompany.env` once (the container env's value when set there, else a random one), then execs the desktop shell's uvicorn argv (`--timeout-graceful-shutdown 5`, port resolved through `core.env_defaults`). `company serve` would need root `node_modules` + the CLI venv, ignores `OPENCOMPANY_ENV_FILE`, and its supervisor tree-kills the backend 5 s after SIGTERM. `HOST` stays `127.0.0.1` (the backend dials itself at `ws://HOST:PORT/ws/internal`); the external bind is the `--host 0.0.0.0` argument. The image has no Node: `/usr/local/bin/node` links to bun, so the `#!/usr/bin/env node` bin scripts (vercel, cf) run. The Dockerfile now sets `BROWSER_RUNTIME=system`, `BROWSER_CHROME_PATH=/usr/bin/chromium` and `BROWSER_HEADLESS=true`; the browser extra supplies Chromium. This matches the default of rendering inside the workspace without a desktop window. The retired agent-browser variable `AGENT_BROWSER_EXECUTABLE_PATH` is no longer in the image. Installed-browser discovery, opt-in Chrome for Testing/browser-use installation and explicit headless deployment requirements are documented in [Browser](./docs-internal/browser.md). The compose project is named `opencompany-selfhost` so it never merges with another compose project called `opencompany`. See [docker.md](./docs-internal/docker.md).
+- **Docker image runs uvicorn, not `company serve`**: `docker/entrypoint.sh` writes the three secrets into `/data/opencompany.env` once (the container env's value when set there, else a random one), then execs the desktop shell's uvicorn argv (`--timeout-graceful-shutdown 5`, port resolved through `core.env_defaults`). `company serve` would need root `node_modules` + the CLI venv, ignores `OPENCOMPANY_ENV_FILE`, and its supervisor tree-kills the backend 5 s after SIGTERM. `HOST` stays `127.0.0.1` (the backend dials itself at `ws://HOST:PORT/ws/internal`); the external bind is the `--host 0.0.0.0` argument. The image has no Node: `/usr/local/bin/node` links to bun, so the `#!/usr/bin/env node` bin scripts (vercel, cf) run. The Dockerfile now sets `BROWSER_RUNTIME=system`, `BROWSER_FAMILY=chromium` and `BROWSER_HEADLESS=true`; the browser extra supplies Chromium. This matches the default of rendering inside the workspace without a desktop window. The retired agent-browser variable `AGENT_BROWSER_EXECUTABLE_PATH` is no longer in the image. Installed-browser discovery, opt-in Chrome for Testing/browser-use installation and explicit headless deployment requirements are documented in [Browser](./docs-internal/browser.md). The compose project is named `opencompany-selfhost` so it never merges with another compose project called `opencompany`. See [docker.md](./docs-internal/docker.md).
- **Configurable Authentication**: `VITE_AUTH_ENABLED` environment variable
- Set to `false` to bypass login entirely (useful for local development)
- Frontend creates anonymous user with owner privileges when disabled
diff --git a/docker/Dockerfile b/docker/Dockerfile
index a58e1c1f..662d4b24 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -123,7 +123,7 @@ ENV DATA_DIR=/data \
NODEJS_EXECUTOR_HOST=127.0.0.1 \
NODEJS_USER_PACKAGES_DIR=/data/nodejs-user-packages \
BROWSER_RUNTIME=system \
- BROWSER_CHROME_PATH=/usr/bin/chromium \
+ BROWSER_FAMILY=chromium \
BROWSER_HEADLESS=true \
PYTHONUNBUFFERED=1
diff --git a/docs-internal/browser.md b/docs-internal/browser.md
index 1b84cd0e..eb68799e 100644
--- a/docs-internal/browser.md
+++ b/docs-internal/browser.md
@@ -25,11 +25,18 @@ session. Normal and Dev modes use the same viewer component.
## Installation and configuration
-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 none
+The defaults `BROWSER_RUNTIME=system` and `BROWSER_FAMILY=chrome` discover
+installed Chrome without storing its executable path in `.env`. Windows discovery
+reads per-user and machine App Paths registrations (both registry views), then
+PATH and standard installation locations. macOS checks PATH and application
+folders; Linux checks PATH. Discovery runs again at profile startup, so a moved
+installation is not cached indefinitely.
+
+`BROWSER_FAMILY=edge` or `chromium` chooses another installed browser by name.
+`auto` explicitly allows Chrome → Edge → Chromium fallback when checking profile
+version compatibility. Selecting `chrome` never silently switches to Edge.
+`BROWSER_CHROME_PATH` remains an optional exclusive executable override for
+special deployments; normally leave it empty. If no compatible browser
is available, startup fails with setup guidance: there is no automatic Chrome
for Testing download or fallback. System mode preserves the browser's native
user agent. An installed browser is not a guarantee that a website will accept
@@ -51,6 +58,7 @@ its opt-in flag directly from the process environment:
| Setting | Default | Purpose |
| --- | --- | --- |
| `BROWSER_RUNTIME` | `system` | Installed browser discovery; `testing` explicitly enables pinned Chrome for Testing |
+| `BROWSER_FAMILY` | `chrome` | Discover `chrome`, `edge`, or `chromium`; `auto` allows cross-browser fallback |
| `BROWSER_HEADLESS` | `true` | Render in the workspace without a desktop window; `false` additionally opens a separate window |
| `BROWSER_CHROME_PATH` | Empty | Explicit Chrome/Edge/Chromium executable override |
| `BROWSER_MAX_INSTANCES` | `3` | Bound simultaneously running browser profiles |
diff --git a/docs-internal/browser_workspace.md b/docs-internal/browser_workspace.md
index 8bf8b8ca..7d777351 100644
--- a/docs-internal/browser_workspace.md
+++ b/docs-internal/browser_workspace.md
@@ -6,8 +6,9 @@ workspace surface and its live-stream contract. By default the runtime launches
installed Chrome/Edge/Chromium headless in a dedicated OpenCompany profile and
renders it inside this workspace. It does not attach to your personal profile.
`BROWSER_HEADLESS=false` additionally opens a desktop window; Chrome for Testing
-requires `BROWSER_RUNTIME=testing`. Set `BROWSER_CHROME_PATH` to installed Chrome
-to keep Chrome selected even when another installed browser has a newer version.
+requires `BROWSER_RUNTIME=testing`. `BROWSER_FAMILY=chrome` (the default) discovers
+installed Chrome dynamically and keeps it selected even when another browser
+has a newer version; no machine-specific executable path is needed.
Normal mode and Dev mode share `components/workspace/WorkspaceTabs.tsx`
(Browser, Canvas, Android) and `components/browser/BrowserWorkspace.tsx`.
diff --git a/docs-internal/desktop_host_contract.md b/docs-internal/desktop_host_contract.md
index 50bb6325..a98b4710 100644
--- a/docs-internal/desktop_host_contract.md
+++ b/docs-internal/desktop_host_contract.md
@@ -179,7 +179,8 @@ the codex provider (`bun x @openai/codex` when no system `codex` exists), and
the Browser runtime's pinned `uv tool install browser-use==<pin>` installation.
The Browser installer respects `UV_TOOL_DIR` / `UV_TOOL_BIN_DIR`; otherwise it
uses `<DATA_DIR>/packages/browser-use/{tools,bin}`. OpenCompany supervises installed Chrome/Edge/Chromium in a dedicated profile,
-rendering headless inside the workspace by default. `BROWSER_CHROME_PATH` overrides discovery;
+rendering headless inside the workspace by default. `BROWSER_FAMILY=chrome` selects
+Chrome by name through dynamic discovery; `BROWSER_CHROME_PATH` is an optional override;
`BROWSER_HEADLESS=false` additionally opens a desktop window. Chrome for Testing is downloaded only with
`BROWSER_RUNTIME=testing`, never as a fallback when no installed browser exists. See [browser.md](./browser.md) and
[browser_workspace.md](./browser_workspace.md). `BUN_INSTALL` / `BUN_INSTALL_CACHE_DIR`
diff --git a/docs-internal/docker.md b/docs-internal/docker.md
index 5134b4ec..06a5aabf 100644
--- a/docs-internal/docker.md
+++ b/docs-internal/docker.md
@@ -68,11 +68,11 @@ The image sets these on top of the template:
| `NODEJS_EXECUTOR_HOST` | `127.0.0.1` | The code sidecar binds IPv4 loopback, which exists even where container IPv6 is off |
| `NODEJS_USER_PACKAGES_DIR` | `/data/nodejs-user-packages` | Packages installed for code nodes persist |
| `BROWSER_RUNTIME` | `system` | Use the image's installed browser; no testing-browser fallback |
-| `BROWSER_CHROME_PATH` | `/usr/bin/chromium` | Select Chromium supplied by the browser extra |
+| `BROWSER_FAMILY` | `chromium` | Discover Chromium supplied by the browser extra through PATH |
| `BROWSER_HEADLESS` | `true` | Render inside the workspace without a desktop window |
| `PYTHONUNBUFFERED` | `1` | Log lines reach `docker compose logs` as they are written |
-**Browser runtime configuration:** the Dockerfile sets `BROWSER_RUNTIME=system`, `BROWSER_CHROME_PATH=/usr/bin/chromium` and `BROWSER_HEADLESS=true` for the browser extra. These are already the image defaults; compose `environment:` can override them. The headless image setting matches the application default: render in the workspace without a desktop window. Discovery can find installed Chromium, but the explicit path makes image selection deterministic. The former `AGENT_BROWSER_EXECUTABLE_PATH` has been removed from the Dockerfile and is not read by this runtime. `BROWSER_RUNTIME=testing` is the only mode that downloads pinned Chrome for Testing; it is never a missing-browser fallback. Validate the built image and Linux libraries before deployment.
+**Browser runtime configuration:** the Dockerfile sets `BROWSER_RUNTIME=system`, `BROWSER_FAMILY=chromium` and `BROWSER_HEADLESS=true` for the browser extra. These are already the image defaults; compose `environment:` can override them. The headless image setting matches the application default: render in the workspace without a desktop window. Chromium is resolved through PATH at startup; the image does not pin an executable path. The former `AGENT_BROWSER_EXECUTABLE_PATH` has been removed from the Dockerfile and is not read by this runtime. `BROWSER_RUNTIME=testing` is the only mode that downloads pinned Chrome for Testing; it is never a missing-browser fallback. Validate the built image and Linux libraries before deployment.
The image has no Node. It links `/usr/local/bin/node` to bun, so the plugin CLIs whose entry scripts start `#!/usr/bin/env node` (vercel, cf) run on bun, as in the official oven/bun images. Browser automation installs browser-use through uv instead.
@@ -108,7 +108,7 @@ With plain `docker run`, pass `--init` and `--stop-timeout 120` to get the same
- **Temporal Web UI.** The dev server binds loopback inside the container, so its UI is not reachable from outside.
- **Claude Code login.** The login button in the credentials panel waits for a browser callback on the container's own localhost, so it cannot finish. Log in from an interactive shell in the container (`docker compose exec opencompany sh`) with `CLAUDE_CONFIG_DIR=/data/claude` set, or supply `ANTHROPIC_API_KEY` through `environment:`. Codex has no login button at all; run its login from the same shell.
- **Owner-checked panels under login.** The image always requires a login, and the editor saves workflows through a REST route that records the placeholder owner `owner` rather than the logged-in account. The Canvas, Memory, Context and dataSource panels check that owner, so they can refuse the logged-in user for such a workflow. `company deploy` VMs, which also require a login, behave the same.
-- **Browser image integration.** The image selects system Chromium with `BROWSER_CHROME_PATH=/usr/bin/chromium` and enables `BROWSER_HEADLESS=true` for displayless operation. The default system mode fails clearly when no installed browser exists. Testing mode is a separate opt-in download. Both modes install the pinned browser-use CLI with uv. Validate selected-browser version/profile compatibility and Linux libraries in the built image; adding the extra alone is not an end-to-end browser check.
+- **Browser image integration.** The image selects system Chromium with `BROWSER_FAMILY=chromium` and enables `BROWSER_HEADLESS=true` for displayless operation. The default system mode fails clearly when no installed browser exists. Testing mode is a separate opt-in download. Both modes install the pinned browser-use CLI with uv. Validate selected-browser version/profile compatibility and Linux libraries in the built image; adding the extra alone is not an end-to-end browser check.
- **Agent nodes need the `git` extra and a git repository.** Claude Code and Codex agents work in git worktrees, and the image contains no `.git`. Run `git init` in a workflow's workspace and make a first commit before pointing an agent at it. Set a commit identity once from a shell in the container (`git config --global user.name ...` and `user.email ...`); it is stored in `/data/home` and survives upgrades.
- **Bind mounts.** A bind mount works in place of the named volume, but the Temporal CLI is then downloaded on first start (a new named volume receives the copy baked into the image), and the directory must allow executables, symlinks and Unix sockets. Prefer the named volume on Windows and macOS hosts.
- **Memory.** Give the container at least 1 GB. At idle the backend holds about 180 MB of process memory and the Temporal dev server about 115 MB; `docker stats` shows up to about 450 MiB because it also counts the page cache of the code they run.
diff --git a/server/core/config.py b/server/core/config.py
index 8f0b559f..ee5034c5 100644
--- a/server/core/config.py
+++ b/server/core/config.py
@@ -454,7 +454,8 @@ class Settings(BaseSettings):
# the browser-use CLI install (and Chrome only in explicit testing mode). Sandbox:
# auto disables Chrome's sandbox only as root on Linux, where it cannot
# start. system discovers installed Chrome/Edge/Chromium; testing opts into
- # the pinned download. chrome_path selects an explicit executable.
+ # the pinned download. browser_family selects the browser by name;
+ # chrome_path is an optional explicit executable override.
# Render inside the workspace by default; a separate window is opt-in.
# Downloads a page starts are
# capped at download_max_mb each.
@@ -463,6 +464,7 @@ class Settings(BaseSettings):
browser_install_timeout_seconds: int = Field(default=900, env="BROWSER_INSTALL_TIMEOUT_SECONDS", ge=60)
browser_sandbox: str = Field(default="auto", env="BROWSER_SANDBOX", pattern="^(auto|on|off)$")
browser_chrome_path: str = Field(default="", env="BROWSER_CHROME_PATH")
+ browser_family: str = Field(default="chrome", env="BROWSER_FAMILY", pattern="^(chrome|edge|chromium|auto)$")
browser_runtime: str = Field(default="system", env="BROWSER_RUNTIME", pattern="^(system|testing)$")
browser_headless: bool = Field(default=True, env="BROWSER_HEADLESS")
browser_download_max_mb: int = Field(default=200, env="BROWSER_DOWNLOAD_MAX_MB", ge=1)
diff --git a/server/nodes/browser/_install_chrome.py b/server/nodes/browser/_install_chrome.py
index 7ec5de82..11e23ba0 100644
--- a/server/nodes/browser/_install_chrome.py
+++ b/server/nodes/browser/_install_chrome.py
@@ -200,7 +200,8 @@ class ChromeInstaller:
raw = str(getattr(container.settings(), "browser_chrome_path", "") or "").strip()
if raw or provider == "system":
try:
- exe, source, version = await select_browser(min_major=max(min_major, self.pin.min_major), override=raw)
+ family = str(getattr(container.settings(), "browser_family", "chrome") or "chrome").lower()
+ exe, source, version = await select_browser(min_major=max(min_major, self.pin.min_major), override=raw, family=family)
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)
diff --git a/server/nodes/browser/_system_browser.py b/server/nodes/browser/_system_browser.py
index 55d88978..72b00fcf 100644
--- a/server/nodes/browser/_system_browser.py
+++ b/server/nodes/browser/_system_browser.py
@@ -20,15 +20,40 @@ def version_major(version: str) -> int:
return int(match.group(1))
+def _windows_app_paths(executable: str):
+ """Read OS-registered executable paths, including per-user/custom installs."""
+ import winreg
+
+ key_name = rf"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\{executable}"
+ for hive in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE):
+ for view in (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY):
+ try:
+ with winreg.OpenKey(hive, key_name, 0, winreg.KEY_READ | view) as key:
+ value, kind = winreg.QueryValueEx(key, "")
+ if kind in (winreg.REG_SZ, winreg.REG_EXPAND_SZ) and isinstance(value, str) and value.strip():
+ yield Path(winreg.ExpandEnvironmentStrings(value.strip().strip('"')))
+ except OSError:
+ continue
+
+
def _candidates():
if sys.platform == "win32":
roots = [os.environ.get(k, "") for k in ("PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA")]
for name, suffix in (("chrome", "Google/Chrome/Application/chrome.exe"), ("edge", "Microsoft/Edge/Application/msedge.exe"), ("chromium", "Chromium/Application/chrome.exe")):
+ command = {"chrome": "chrome.exe", "edge": "msedge.exe", "chromium": "chromium.exe"}[name]
+ for path in _windows_app_paths(command):
+ yield path, name
+ found = shutil.which(command)
+ if found:
+ yield Path(found), name
for root in roots:
if root:
yield Path(root) / suffix, name
elif sys.platform == "darwin":
for name, app, binary in (("chrome", "Google Chrome", "Google Chrome"), ("edge", "Microsoft Edge", "Microsoft Edge"), ("chromium", "Chromium", "Chromium")):
+ found = shutil.which(binary)
+ if found:
+ yield Path(found), name
for root in (Path("/Applications"), Path.home() / "Applications"):
yield root / f"{app}.app/Contents/MacOS/{binary}", name
else:
@@ -67,10 +92,14 @@ 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."""
+async def select_browser(*, min_major: int, override: str = "", family: str = "auto") -> tuple[Path, str, str]:
+ """Resolve the requested family afresh, checking profile version compatibility."""
+ if family not in {"chrome", "edge", "chromium", "auto"}:
+ raise NodeUserError("BROWSER_FAMILY must be chrome, edge, chromium or auto.")
rejected = []
for path, source in discover_browsers(override):
+ if not override and family != "auto" and source != family:
+ continue
try:
version = await browser_version(path)
if version_major(version) >= min_major:
@@ -78,7 +107,9 @@ async def select_browser(*, min_major: int, override: str = "") -> tuple[Path, s
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"
+ selection = "BROWSER_CHROME_PATH" if override else ("The installed browsers" if family == "auto" else f"Installed {family}")
+ if not rejected:
+ raise NodeUserError(f"No installed {family} was found. Install {family} or choose another BROWSER_FAMILY. The existing profile has been preserved.")
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. "
diff --git a/server/tests/nodes/browser/test_system_browser.py b/server/tests/nodes/browser/test_system_browser.py
index 143bcb2f..6201855c 100644
--- a/server/tests/nodes/browser/test_system_browser.py
+++ b/server/tests/nodes/browser/test_system_browser.py
@@ -14,7 +14,7 @@ from services.plugin.base import NodeUserError
def settings(monkeypatch, **values):
from core.container import container
- result = SimpleNamespace(browser_runtime="system", browser_chrome_path="", browser_install_timeout_seconds=10)
+ result = SimpleNamespace(browser_runtime="system", browser_family="auto", browser_chrome_path="", browser_install_timeout_seconds=10)
result.__dict__.update(values)
monkeypatch.setattr(container, "settings", lambda: result)
return result
@@ -44,10 +44,75 @@ def test_platform_candidates_prefer_chrome_then_edge_then_chromium(monkeypatch,
monkeypatch.setenv("PROGRAMFILES(X86)", "Programs86")
monkeypatch.setenv("LOCALAPPDATA", "Local")
monkeypatch.setattr(system.shutil, "which", lambda command: command)
+ monkeypatch.setattr(system, "_windows_app_paths", lambda command: [])
names = [name for _, name in system._candidates()]
assert names and names == sorted(names, key={"chrome": 0, "edge": 1, "chromium": 2}.get)
+def test_windows_registry_custom_install_precedes_path_and_defaults(monkeypatch):
+ monkeypatch.setattr(system.sys, "platform", "win32")
+ monkeypatch.setattr(system, "_windows_app_paths", lambda command: [Path("relocated") / command])
+ monkeypatch.setattr(system.shutil, "which", lambda command: str(Path("on-path") / command))
+ monkeypatch.setattr(Path, "is_file", lambda path: "relocated" in path.parts or "on-path" in path.parts)
+ assert system.discover_browser() == (Path("relocated/chrome.exe"), "chrome")
+ monkeypatch.setattr(Path, "is_file", lambda path: "on-path" in path.parts)
+ assert system.discover_browser() == (Path("on-path/chrome.exe"), "chrome")
+
+
+def test_windows_registry_reads_both_scopes_and_views(monkeypatch):
+ import sys
+ from contextlib import nullcontext
+
+ calls = []
+
+ def open_key(hive, key, reserved, access):
+ calls.append((hive, key, access))
+ if hive == "machine" and access == 5:
+ return nullcontext("registered")
+ raise FileNotFoundError
+
+ registry = SimpleNamespace(
+ HKEY_CURRENT_USER="user", HKEY_LOCAL_MACHINE="machine", KEY_READ=1,
+ KEY_WOW64_64KEY=2, KEY_WOW64_32KEY=4, REG_SZ=1, REG_EXPAND_SZ=2,
+ OpenKey=open_key, QueryValueEx=lambda key, value: ('"%INSTALL_ROOT%/chrome.exe"', 2),
+ ExpandEnvironmentStrings=lambda value: value.replace("%INSTALL_ROOT%", "custom-location"),
+ )
+ monkeypatch.setitem(sys.modules, "winreg", registry)
+ assert list(system._windows_app_paths("chrome.exe")) == [Path("custom-location/chrome.exe")]
+ assert [(hive, access) for hive, _, access in calls] == [("user", 3), ("user", 5), ("machine", 3), ("machine", 5)]
+ assert all(key.endswith(r"App Paths\chrome.exe") for _, key, _ in calls)
+
+
+async def test_named_chrome_never_switches_to_edge(monkeypatch):
+ settings(monkeypatch, browser_family="chrome")
+ monkeypatch.setattr(system, "discover_browsers", lambda raw: [(Path("chrome"), "chrome"), (Path("edge"), "edge")])
+ probe = AsyncMock(side_effect=lambda path: "153.0.0.0" if path.name == "chrome" else "154.0.0.0")
+ monkeypatch.setattr(system, "browser_version", probe)
+ with pytest.raises(NodeUserError, match="Installed chrome.*requires version 154"):
+ await ChromeInstaller().ensure(wait=10, min_major=154)
+ probe.assert_awaited_once_with(Path("chrome"))
+
+
+async def test_named_browser_is_rediscovered_after_relocation(monkeypatch):
+ settings(monkeypatch, browser_family="chrome")
+ discover = Mock(side_effect=[[(Path("old/chrome.exe"), "chrome")], [(Path("new/chrome.exe"), "chrome")]])
+ monkeypatch.setattr(system, "discover_browsers", discover)
+ monkeypatch.setattr(system, "browser_version", AsyncMock(return_value="154.0.0.0"))
+ installer = ChromeInstaller()
+ assert await installer.ensure(wait=10) == Path("old/chrome.exe")
+ assert await installer.ensure(wait=10) == Path("new/chrome.exe")
+ assert discover.call_count == 2
+
+
+async def test_missing_named_browser_is_actionable(monkeypatch):
+ monkeypatch.setattr(system, "discover_browsers", lambda raw: [(Path("edge"), "edge")])
+ with pytest.raises(NodeUserError, match="No installed chrome was found"):
+ await system.select_browser(min_major=154, family="chrome")
+
+
@pytest.mark.asyncio
async def test_windows_version_reads_metadata_without_launch(monkeypatch):
monkeypatch.setattr(system.sys, "platform", "win32")