Skip to content

Self-improving AI Employees for everyone

feat(browser): default to installed browsers with persistent profiles

trohitg9d2a4ebedb0c
diff --git a/.env.template b/.env.template
index 7af5cb11..abb652af 100644
--- a/.env.template
+++ b/.env.template
@@ -212,23 +212,28 @@ AGENT_RECURSION_LIMIT=200
MAX_CONCURRENT_SUBAGENTS=3
MAX_DELEGATION_DEPTH=2
-# Browser node. OpenCompany downloads a pinned Chrome for Testing on first
-# use (server/config/browser_runtime.json) and runs one headless Chrome per
-# browser profile. BROWSER_MAX_INSTANCES caps running profiles — when
+# Browser node. Uses installed Chrome/Edge/Chromium with a dedicated persistent
+# profile and a visible window by default; the workspace also shows its stream.
+# BROWSER_RUNTIME=testing explicitly opts into pinned Chrome for Testing.
+# BROWSER_HEADLESS=true supports servers without a desktop display.
+# BROWSER_MAX_INSTANCES caps running profiles — when
# another would exceed it, the least recently used idle profile is stopped
# first. BROWSER_IDLE_TIMEOUT_MS stops a profile's Chrome after that many
# milliseconds with no agent step, viewer or login (0 disables).
-# BROWSER_INSTALL_TIMEOUT_SECONDS bounds the first-use download.
+# 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 runs a Chrome of your own instead of the pinned
-# download (e.g. musl hosts). BROWSER_DOWNLOAD_MAX_MB caps each file a
+# BROWSER_CHROME_PATH explicitly selects a browser instead of auto-discovery.
+# System mode never falls back to a testing-browser download.
+# BROWSER_DOWNLOAD_MAX_MB caps each file a
# page downloads.
BROWSER_MAX_INSTANCES=3
BROWSER_IDLE_TIMEOUT_MS=600000
BROWSER_INSTALL_TIMEOUT_SECONDS=900
BROWSER_SANDBOX=auto
BROWSER_CHROME_PATH=
+BROWSER_RUNTIME=system
+BROWSER_HEADLESS=false
BROWSER_DOWNLOAD_MAX_MB=200
# Dead-letter queue for failed workflow executions. Off by default.
diff --git a/CLAUDE.md b/CLAUDE.md
index b4b5dc15..4d297e30 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -28,7 +28,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Pricing Service](./docs-internal/pricing_service.md)** | Centralized cost tracking for LLM tokens and API services (Twitter, Google Maps) with HTTPX event hooks |
| **[Proxy Service](./docs-internal/proxy_service.md)** | Residential proxy provider management with template-based URL formatting, health scoring, and transparent HTTP node injection |
| **[Email Service](./docs-internal/email_service.md)** | IMAP/SMTP integration via Himalaya CLI with EmailService orchestrator, provider presets, custom credential fallback, and polling triggers |
-| **[Browser](./docs-internal/browser.md)** | Current `browser` node: managed Chrome for Testing and pinned browser-use CLI, persistent employee/shared profiles, session leases, agent/user handoff, network policy, screenshots as workspace FileRefs, and authenticated `/ws/browser` live viewing. Plugin-owned installation is lazy (`_install_chrome.py`, `_install_bu.py`); importing or shutting down the plugin never installs it. Replaces the former agent-browser and separate `browserHarness` implementations. |
+| **[Browser](./docs-internal/browser.md)** | Current `browser` node: installed Chrome/Edge/Chromium in a dedicated visible profile by default (`BROWSER_RUNTIME=system`, `BROWSER_HEADLESS=false`) and pinned browser-use CLI. Chrome for Testing requires explicit `BROWSER_RUNTIME=testing`. System mode retains the native user agent and OS password-store/keychain integration; basic/mock keychain flags are restricted to testing mode. Includes persistent employee/shared profiles, session leases, agent/user handoff, network policy, screenshots as workspace FileRefs and authenticated `/ws/browser` live viewing. Plugin-owned installation is lazy (`_install_chrome.py`, `_install_bu.py`); importing or shutting down the plugin never installs it. Replaces the former agent-browser and separate `browserHarness` implementations. |
| **[Browser Workspace](./docs-internal/browser_workspace.md)** | Home and Dev share `WorkspaceTabs` and `BrowserWorkspace`: Browser / Canvas / Android, capability-based discovery, binary JPEG frames, bounded frame credit and decoding, Take control / Hand back, visibility cleanup and payload-free opt-in diagnostics. Android remains a placeholder. |
| **[WhatsApp Business Service](./docs-internal/whatsapp_business_service.md)** | Official Meta Cloud API plugin in [`server/nodes/whatsapp_business/`](./server/nodes/whatsapp_business/) — **distinct from `nodes/whatsapp/`**, which is a personal account over an unofficial Go bridge; they share no node type, credential or palette group. Four nodes: `whatsappBusinessSend` (10 ops — Meta models message type as a *field* on one `/messages` endpoint, so text / media / template / interactive are operations, not nodes), `whatsappBusinessMedia` (the one genuinely separate endpoint family), and the `Receive` / `Status` triggers (kept separate because a canary trigger registers exactly one CloudEvents type). `phone_number_id` is deliberately **absent from Params** — on a dual-purpose ActionNode `execute_as_tool` merges `{**node_params, **tool_args}`, so a declared field is model-settable and a prompt injection could choose the sending identity; it comes from the credential only. Webhook via `register_webhook_source` on the shared catch-all, `X-Hub-Signature-256` HMAC failing closed, composite `wamid:status` dedup ids so `sent→delivered→read` don't collapse. |
| **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth via `stripe login --non-interactive` + `--complete <url>` (URL extracted from `next_step` shell command via `shlex.split`) + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + CloudEvents-shaped `broadcast_credential_event("credential.oauth.connected" \| ".disconnected", provider=...)` — zero per-provider hardcoding in the frontend. Daemon stdout/stderr ingested via `ProcessService`'s `line_handler` callback (no log-file tailing); credential gate routed through `await self.has_credential()` so non-api-key auth (`is_logged_in()`) plugs in via subclass override. |
@@ -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. Historical browser-image setup used Debian Chromium and `AGENT_BROWSER_EXECUTABLE_PATH` for agent-browser; that variable does not configure the current managed Browser runtime. Pinned Chrome for Testing/browser-use installation and 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_CHROME_PATH=/usr/bin/chromium` and `BROWSER_HEADLESS=true`; the browser extra supplies Chromium. This explicitly overrides the desktop-visible default. 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
@@ -2777,7 +2777,7 @@ This function:
- **Telegram owner detection — three layers** (f746ddf): the bot owner is captured by THREE independent paths so the realistic setup flows all converge to a working state. (1) **Explicit field**: secondary `FieldDef` in the credentials modal lets the user paste their Telegram user ID directly (recommended; works without DM'ing the bot). (2) **Pre-poll peek** in `connect()` via `_capture_owner_from_pending_updates()` — calls `bot.get_updates(timeout=0)` BEFORE `start_polling(drop_pending_updates=True)` discards the queue, scans for any historical private DM, captures + persists atomically. (3) **Atomic write-through in `_on_message_received`** — persists FIRST, sets in-memory ONLY on success. Invariant: "in-memory has owner ⇒ DB has owner" so a process restart can re-capture cleanly. Failure logged at `ERROR` with `exc_info=True` (was `WARNING` previously, masking persist failures). The lazy fallback in `telegram_send.py` (read DB → `service.set_owner`) sits on top of all three.
- **Supervisor Job Object loud-failure (cli/tree.py + cli/supervisor.py)** (8a64eb9): the Windows process-tree mechanism depends entirely on a Job Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` (no fallback — `start_new_session` is POSIX-only). `pywin32>=308` is a hard supervisor dependency on Windows; the declaration in the root `pyproject.toml` (where `opencompany-cli` lives — `cli/pyproject.toml` was removed as a stale duplicate) carries an inline comment so future maintainers don't drop it. `_JobObject.__init__` splits failures into explicit `ImportError` (with reinstall command) and `Exception` (with `repr`) branches — both write to `stderr` instead of swallowing. `_JobObject.add()` verifies enrollment via `win32job.IsProcessInJob(handle, self._handle)` after assignment; on mismatch it queries `IsProcessInJob(handle, None)` so the warning explicitly names the wrapper-job hypothesis (npm / bun / conhost wrappers occasionally place us in their own non-nesting Job). `supervisor._spawn_once` checks `add_to_job` return value and emits a yellow `WARN: pid=N not enrolled in Job Object` per child if False. Without these guards, a stale pywin32 install or a wrapping Job Object silently leaks orphan Python processes on every Ctrl-C and they accumulate to the point of holding SQLite locks that block subsequent backend startup.
- **Credentials envelope-shape invariant** (dc94cde): the `useCredentialPanel` query stores `{values: CredentialFormValues, hadStored: boolean}` (an envelope, NOT a flat dict). The earlier `writeValues` called `setQueryData<CredentialFormValues>` with a spread `(prev) => ({...prev, [key]: value})`, which at runtime merged the typed character at the envelope level next to `values` and `hadStored` instead of inside `.values` — the input selector `panel.values[field.key]` re-rendered with the original (server) value on every keystroke and the input felt frozen. Fix: `writeValues` now preserves the envelope shape and updates only the inner `values` dict; `hadStored` is preserved verbatim (it reflects real server state, not local edits). When introducing other queries shaped as `{data, meta}` envelopes, follow the same pattern — never spread `prev` as if it were the inner payload.
-- **`core.paths` is the SSOT for on-disk locations**: only generic helpers (`data_path` / `packages_dir` / `package_dir(name)` / `daemons_dir` / `workspaces_dir` / `workspace_dir(workflow_id)` / `example_workflows_dir`). Plugin-specific subpaths are composed inline at the plugin's call site — adding a new package never requires touching `core.paths`. Reference subtree under `opencompany_root()` (= `~/.opencompany/` per default `DATA_DIR`): `workspaces/<slug>/` (per-workflow scratch), `daemons/` (supervised event-source daemon cwds — `stripe listen` etc.; shared root by default, no per-namespace subdir), `claude/` (Claude Code's `CLAUDE_CONFIG_DIR` state — composed as `data_path("claude")` in `nodes/agent/claude_code_agent/_oauth.py`), `packages/` (OpenCompany-managed install root). `packages/` holds a **single shared, bun-managed packages tree** — one `package.json` + `bun.lock` + `node_modules/` covering every OpenCompany-managed npm-registry package (`@anthropic-ai/claude-code`, `edgymeow`, `cf`, `vercel`). Each plugin's `_install.py` calls `core.js_runtime.add_package(spec, trust=...)`, which runs `bun add --cwd <packages_dir> --no-progress [--trust] <spec>` and extends the shared tree idempotently (`ensure_shared_tree()` writes the minimal private manifest first); `bun_binary()` resolves bun from `OPENCOMPANY_BUN_BIN` or PATH, and `shared_tree_bin(name)` returns the shim at `node_modules/.bin/<name>` on POSIX or `<name>.exe` (plus a `<name>.bunx` file) on Windows. The shims run on the bun runtime — no Node or npm anywhere on this path (bun ignores a package's `engines.node`, and shims `node` for the lifecycle scripts it is allowed to run). bun blocks dependency lifecycle scripts unless trusted, so `trust=True` is passed only where a postinstall materialises something the plugin needs: claude-code (stages its native launcher), edgymeow (downloads the Go binary). The Browser runtime does not use this npm tree: its plugin-owned installers use `packages/chrome-for-testing/` and `packages/browser-use/` (see [Browser](./docs-internal/browser.md)). Binaries that are not npm-registry packages (Stripe CLI, Temporal CLI) sit under sibling subdirs `packages/stripe/`, `packages/temporal/` via `package_dir(name)`. Also under `<DATA_DIR>/`: `whatsapp/` (WhatsApp session DB), `credentials.db` / `workflow.db` / `temporal.db`, and the model-registry caches `local_models.json` (models registered from the user's own LLM servers) / `litellm_models.json` (LiteLLM's model table, RFC-0003 D16). Pre-fix `packages_dir()` routed through `platformdirs.user_cache_path("OpenCompany")` (`~/.cache/OpenCompany/` etc.) and the Temporal CLI sat in its own `pooch.os_cache("opencompany-temporal")` namespace — operators reported both as "not local". The WhatsApp Go bridge (`edgymeow`) used to be a top-level pnpm dep at `<repo>/node_modules/edgymeow/`; now OpenCompany-managed via `nodes/whatsapp/_install.py` like the other CLIs. Daemon cwds used to live under `workspaces/_<namespace>/` and polluted per-workflow scratch with framework state. Out of scope: globally-installed binaries (Himalaya — system package manager). Shipped seed workflows are the lone exception — `example_workflows_dir()` is hardcoded to `<repo>/.opencompany/workflows/` (git-tracked seeds, NOT under `DATA_DIR`) so they survive `company clean` and stay at the same path across `DATA_DIR=~/.opencompany` vs `DATA_DIR=.opencompany` configs.
+- **`core.paths` is the SSOT for on-disk locations**: only generic helpers (`data_path` / `packages_dir` / `package_dir(name)` / `daemons_dir` / `workspaces_dir` / `workspace_dir(workflow_id)` / `example_workflows_dir`). Plugin-specific subpaths are composed inline at the plugin's call site — adding a new package never requires touching `core.paths`. Reference subtree under `opencompany_root()` (= `~/.opencompany/` per default `DATA_DIR`): `workspaces/<slug>/` (per-workflow scratch), `daemons/` (supervised event-source daemon cwds — `stripe listen` etc.; shared root by default, no per-namespace subdir), `claude/` (Claude Code's `CLAUDE_CONFIG_DIR` state — composed as `data_path("claude")` in `nodes/agent/claude_code_agent/_oauth.py`), `packages/` (OpenCompany-managed install root). `packages/` holds a **single shared, bun-managed packages tree** — one `package.json` + `bun.lock` + `node_modules/` covering every OpenCompany-managed npm-registry package (`@anthropic-ai/claude-code`, `edgymeow`, `cf`, `vercel`). Each plugin's `_install.py` calls `core.js_runtime.add_package(spec, trust=...)`, which runs `bun add --cwd <packages_dir> --no-progress [--trust] <spec>` and extends the shared tree idempotently (`ensure_shared_tree()` writes the minimal private manifest first); `bun_binary()` resolves bun from `OPENCOMPANY_BUN_BIN` or PATH, and `shared_tree_bin(name)` returns the shim at `node_modules/.bin/<name>` on POSIX or `<name>.exe` (plus a `<name>.bunx` file) on Windows. The shims run on the bun runtime — no Node or npm anywhere on this path (bun ignores a package's `engines.node`, and shims `node` for the lifecycle scripts it is allowed to run). bun blocks dependency lifecycle scripts unless trusted, so `trust=True` is passed only where a postinstall materialises something the plugin needs: claude-code (stages its native launcher), edgymeow (downloads the Go binary). The Browser runtime does not use this npm tree: its CLI installer uses `packages/browser-use/`; only explicit testing mode installs Chrome under `packages/chrome-for-testing/` (see [Browser](./docs-internal/browser.md)). Binaries that are not npm-registry packages (Stripe CLI, Temporal CLI) sit under sibling subdirs `packages/stripe/`, `packages/temporal/` via `package_dir(name)`. Also under `<DATA_DIR>/`: `whatsapp/` (WhatsApp session DB), `credentials.db` / `workflow.db` / `temporal.db`, and the model-registry caches `local_models.json` (models registered from the user's own LLM servers) / `litellm_models.json` (LiteLLM's model table, RFC-0003 D16). Pre-fix `packages_dir()` routed through `platformdirs.user_cache_path("OpenCompany")` (`~/.cache/OpenCompany/` etc.) and the Temporal CLI sat in its own `pooch.os_cache("opencompany-temporal")` namespace — operators reported both as "not local". The WhatsApp Go bridge (`edgymeow`) used to be a top-level pnpm dep at `<repo>/node_modules/edgymeow/`; now OpenCompany-managed via `nodes/whatsapp/_install.py` like the other CLIs. Daemon cwds used to live under `workspaces/_<namespace>/` and polluted per-workflow scratch with framework state. Out of scope: globally-installed binaries (Himalaya — system package manager). Shipped seed workflows are the lone exception — `example_workflows_dir()` is hardcoded to `<repo>/.opencompany/workflows/` (git-tracked seeds, NOT under `DATA_DIR`) so they survive `company clean` and stay at the same path across `DATA_DIR=~/.opencompany` vs `DATA_DIR=.opencompany` configs.
- **`company clean` preserves `.opencompany/{workflows,deploy,packages}/`**: `cli/commands/clean.py` iterates the canonical `<repo>/.opencompany/` and pre-rebrand `<repo>/.machina/` roots and skips anything in `_OPENCOMPANY_KEEP = frozenset({"workflows", "deploy", "packages"})`. Wipes `claude/`, `workspaces/`, `*.db` as before. `workflows/` holds the shipped seed JSONs (git-tracked); `deploy/` holds Terraform state for LIVE cloud resources (only `company deploy destroy` removes it); `packages/` holds the OpenCompany-managed binaries (Temporal CLI ~114 MB, Stripe CLI, the shared bun packages tree) — re-fetchable but expensive, so clean+build cycles stay offline-safe cache hits. Test `cli/tests/test_clean.py::test_opencompany_keep_preserves_workflows_deploy_and_packages` locks the keep-list.
- **No raw `print()` outside three sanctioned helpers**: `main._startup_log` (pre-logger boot markers), `core.container._clog` (DI-bootstrap markers), and `nodes.code.python_executor.captured_print` (the sandbox builtin handed to user code). Everything else goes through `logger = get_logger(__name__)`. The supervisor prefixes every aggregated line with `[HH:MM:SS.fff]` so no inner `TimeStamper` is needed; structlog console mode is deliberately timestamp-less. Test `server/tests/test_no_raw_prints.py` AST-walks the tree and flags any unsanctioned `print(...)` call.
- **`configure_logging(settings)` must run BEFORE plugin self-registration imports**: in `main.py`, `Settings()` + `configure_logging(settings)` + `init_tracing()` + `get_logger(__name__)` happen ahead of `from core.container import container` and `from routers import …`. Otherwise plugin folders that register on import call `logger.debug(...)` while structlog is still on its default processor chain (which includes `TimeStamper` + no `filter_by_level`) — symptom is double timestamps + debug records leaking despite `LOG_LEVEL=INFO`.
diff --git a/README.md b/README.md
index 3908063b..1543798a 100644
--- a/README.md
+++ b/README.md
@@ -131,7 +131,7 @@ Nothing here is a black box. What an employee learns lives in its memory, its no
- **Connections** to Gmail, Google Calendar, Drive, Sheets, Tasks, Contacts, Microsoft 365, any email account, WhatsApp, WhatsApp Business, Telegram, Discord, X, Stripe, GitHub, Vercel, Cloudflare, Google Cloud, your Android phone, a browser, web search, scrapers, and a knowledge base: 140+ tools in all.
- **Models** from OpenAI, Anthropic, Google, xAI, DeepSeek, Kimi, Mistral, Groq, Cerebras, Sarvam, and OpenRouter, or run local models for free with Ollama, LM Studio, or any OpenAI-compatible server such as llama.cpp or vLLM.
-- **A live browser workspace** in Home and Dev mode: watch an employee browse, take control to sign in or help, then hand control back. Browser profiles keep sessions between tasks. [Browser runtime](docs-internal/browser.md) | [Workspace interface](docs-internal/browser_workspace.md).
+- **A live browser workspace** in Home and Dev mode: watch an employee browse, take control to sign in or help, then hand control back. It opens your installed Chrome, Edge or Chromium in a dedicated OpenCompany profile, keeping sessions between tasks without using your personal profile. [Browser runtime](docs-internal/browser.md) | [Workspace interface](docs-internal/browser_workspace.md).
- **Speech and translation**, so employees can listen, talk, and work in other languages.
- **78 skills** that ship ready to use, and a place to drop your own.
- **Built to keep running.** Employees survive restarts, pause and resume from Home or the canvas, and catch up on missed schedules. Your API keys are stored encrypted on your machine. Add a login for shared or cloud use; one command deploys to Google Cloud.
diff --git a/docker-compose.yml b/docker-compose.yml
index 0be6cda2..dae7801f 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -15,7 +15,7 @@ services:
args:
# Optional tools, space separated; the default image has none
# (docs-internal/docker.md). Then rebuild: docker compose up -d --build
- # browser Chromium for the browser node, uv for browser-harness
+ # browser Chromium and uv for the native Browser node
# git git for the Claude Code and Codex agent nodes
EXTRAS: ""
image: opencompany:local
diff --git a/docker/Dockerfile b/docker/Dockerfile
index fbf1ff86..a58e1c1f 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -11,7 +11,7 @@
# The default image carries no optional tools. EXTRAS adds them, space
# separated:
# browser Chromium, fonts and Xvfb for the browser node, and uv, which
-# the browser-harness node installs itself with
+# installs the Browser node's browser-use CLI
# git git, for the Claude Code and Codex agent nodes (they work in git
# worktrees)
#
@@ -113,8 +113,8 @@ COPY --from=build /data /data
# Runtime settings; everything else keeps its .env.template default.
# HOME lives on the volume so CLI logins (gh, stripe, cf, codex) and caches
-# survive upgrades. AGENT_BROWSER_EXECUTABLE_PATH points agent-browser at the
-# system Chromium of the browser extra, which the browser node needs.
+# survive upgrades. Browser system mode selects the browser extra's Chromium;
+# this server image has no desktop display, so use explicit headless mode.
ENV DATA_DIR=/data \
HOME=/data/home \
OPENCOMPANY_ENV_FILE=/data/opencompany.env \
@@ -122,7 +122,9 @@ ENV DATA_DIR=/data \
VITE_AUTH_ENABLED=true \
NODEJS_EXECUTOR_HOST=127.0.0.1 \
NODEJS_USER_PACKAGES_DIR=/data/nodejs-user-packages \
- AGENT_BROWSER_EXECUTABLE_PATH=/usr/bin/chromium \
+ BROWSER_RUNTIME=system \
+ BROWSER_CHROME_PATH=/usr/bin/chromium \
+ BROWSER_HEADLESS=true \
PYTHONUNBUFFERED=1
WORKDIR /app/server
diff --git a/docs-internal/browser.md b/docs-internal/browser.md
index 8025403f..9525c3bb 100644
--- a/docs-internal/browser.md
+++ b/docs-internal/browser.md
@@ -1,6 +1,8 @@
# Native browser runtime
-The `browser` node runs a managed Chrome for Testing profile. Agents use the
+The `browser` node launches installed Chrome, Edge or Chromium in an
+OpenCompany-owned profile. The default opens a visible browser window; it
+does not attach to or copy your personal browser profile. Agents use the
browser-use CLI for ordinary browser operations; people watch and control the
same Chrome through the [Browser workspace](./browser_workspace.md). The old
agent-browser driver and separate `browserHarness` node are retired.
@@ -22,16 +24,21 @@ session. Normal and Dev modes use the same viewer component.
## Installation and configuration
-[`server/config/browser_runtime.json`](../server/config/browser_runtime.json)
-is the version source of truth for Chrome for Testing, supported platforms,
-download checksums and the browser-use CLI. The runtime ensures both tools
-before launching a new Chrome process. Installation is shared and can outlive
-the finite open request; the workspace polls installation status while waiting.
-
-Chrome is installed under `<DATA_DIR>/packages/chrome-for-testing/`.
-The CLI uses an isolated uv tool installation under
-`<DATA_DIR>/packages/browser-use/`; it is not part of the shared Bun package
-tree. `uv` must be available on PATH or through `OPENCOMPANY_UV_BIN`.
+The default `BROWSER_RUNTIME=system` discovers installed Chrome first, then
+Edge/Chromium. `BROWSER_CHROME_PATH` selects an explicit executable. If none
+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
+automation or permit a login; Take control remains available for human steps.
+
+`BROWSER_RUNTIME=testing` explicitly selects pinned Chrome for Testing. Its
+version, platform checksums and the browser-use CLI pin live in
+[`server/config/browser_runtime.json`](../server/config/browser_runtime.json).
+Only testing mode installs Chrome under `<DATA_DIR>/packages/chrome-for-testing/`.
+Both modes install the pinned browser-use CLI through an isolated uv tool
+installation under `<DATA_DIR>/packages/browser-use/`, outside the shared Bun
+package tree. `uv` must be on PATH or selected by `OPENCOMPANY_UV_BIN`.
+Installation can outlive the open request; the workspace reports progress.
Runtime settings are declared in
[`server/core/config.py`](../server/core/config.py); stream diagnostics reads
@@ -39,7 +46,9 @@ its opt-in flag directly from the process environment:
| Setting | Default | Purpose |
| --- | --- | --- |
-| `BROWSER_CHROME_PATH` | Empty | Use a supplied Chrome/Chromium executable instead of downloading the pinned browser |
+| `BROWSER_RUNTIME` | `system` | Installed browser discovery; `testing` explicitly enables pinned Chrome for Testing |
+| `BROWSER_HEADLESS` | `false` | Visible browser by default; set `true` explicitly for containers or unattended hosts |
+| `BROWSER_CHROME_PATH` | Empty | Explicit Chrome/Edge/Chromium executable override |
| `BROWSER_MAX_INSTANCES` | `3` | Bound simultaneously running browser profiles |
| `BROWSER_IDLE_TIMEOUT_MS` | `600000` | Reap idle profiles; attached viewers and pending user work count as busy |
| `BROWSER_INSTALL_TIMEOUT_SECONDS` | `900` | Bound installer work |
@@ -60,6 +69,12 @@ directory IDs rather than user-supplied names. A saved `profile_id` selects an
owner-scoped profile; leaving it empty creates/reuses the workflow's profile.
The CLI receives its own per-profile home, runtime and temporary directories.
+The profile version guard checks the browser executable actually selected, not
+the testing pin. A browser older than the version that last wrote the profile
+is rejected with actionable guidance. OpenCompany neither deletes that profile
+nor silently creates a replacement; select a compatible browser or explicitly
+choose a different profile. This protects saved sessions during runtime changes.
+
The server derives identity from the authenticated caller and the saved
workflow. Browser discovery uses the plugin's `isBrowserPanel` hint, not a
second frontend list of browser type names. The node's profile, read-only mode,
@@ -120,4 +135,5 @@ Backend regression tests live in `server/tests/nodes/browser/`; viewer and
workspace tests live beside their client components. The
[local benchmark](./browser_workspace.md#reproducible-local-benchmark) exercises
real Chrome/CDP and production stream code with an isolated reference canvas.
-Its recorded Chrome 153 results are not a full React or pinned-Chrome benchmark.
+Its recorded Chrome 153 results describe the prior benchmark configuration,
+not a full React test or validation of the current default runtime selection.
diff --git a/docs-internal/browser_harness.md b/docs-internal/browser_harness.md
index ca02699a..68437504 100644
--- a/docs-internal/browser_harness.md
+++ b/docs-internal/browser_harness.md
@@ -8,8 +8,8 @@ Current documentation:
- [Browser node flow](node-logic-flows/web_automation/browser.md): operations, operator settings, dispatch, outputs and legacy migration.
- [Browser workspace](browser_workspace.md): live viewing, frame delivery, direct input and human control.
-The current runtime manages its own Chrome rather than requiring an already running, logged-in personal Chrome. Agent/workflow operations use generated scripts through the isolated, pinned browser-use CLI and its persistent daemon; WebMCP and live viewer capture/control have native CDP paths. The presence of browser-harness machinery inside that dependency is separate from the retired OpenCompany node.
+The current runtime launches installed Chrome/Edge/Chromium in a dedicated OpenCompany profile with a visible window by default; it neither attaches to nor copies an already running, logged-in personal profile. Chrome for Testing is available only through explicit `BROWSER_RUNTIME=testing`; headless operation requires `BROWSER_HEADLESS=true`. Agent/workflow operations use generated scripts through the isolated, pinned browser-use CLI and its persistent daemon; WebMCP and live viewer capture/control have native CDP paths. The presence of browser-harness machinery inside that dependency is separate from the retired OpenCompany node.
[Saved-workflow migration](../server/services/workflow_migrations.py) renames `browserHarness` to `browser` and maps `goto` to `navigate`, `js` to `evaluate`, `doctor` to `diagnose`, and `tabs` to tab listing. Existing Python code is retained with a helper-compatibility warning. `evaluate` and `run_python` are now workflow-only; duplicate Browser tool edges created by migration are removed with a warning. See the node flow for complete parameter compatibility behavior.
-Do not use the old service paths, installation commands, remote-debugging setup or Python helper examples from this document's history as current setup instructions. Runtime dependency pins are maintained in [`server/config/browser_runtime.json`](../server/config/browser_runtime.json).
+Do not use the old service paths, installation commands, remote-debugging setup or Python helper examples from this document's history as current setup instructions. Testing-browser and CLI dependency pins are maintained in [`server/config/browser_runtime.json`](../server/config/browser_runtime.json).
diff --git a/docs-internal/browser_workspace.md b/docs-internal/browser_workspace.md
index ca684a73..d6ba841d 100644
--- a/docs-internal/browser_workspace.md
+++ b/docs-internal/browser_workspace.md
@@ -2,7 +2,10 @@
For installation, profiles, policy and agent execution, see the
[native browser runtime](./browser.md). This document describes the shared
-workspace surface and its live-stream contract.
+workspace surface and its live-stream contract. By default the runtime opens
+installed Chrome/Edge/Chromium in a dedicated OpenCompany profile and a visible
+window. It does not attach to your personal profile. Headless operation requires
+`BROWSER_HEADLESS=true`; Chrome for Testing requires `BROWSER_RUNTIME=testing`.
Normal mode and Dev mode share `components/workspace/WorkspaceTabs.tsx`
(Browser, Canvas, Android) and `components/browser/BrowserWorkspace.tsx`.
@@ -138,9 +141,10 @@ fixture does not validate WAN latency, large third-party pages, the browser-use
CLI/agent path, production ownership checks or all human-control races. Those
remain separate correctness and end-to-end checks.
-### Local measurements, 2026-09-26
+### Historical local measurements, 2026-09-26
-The final paired runs used installed **Chrome 153.0.8010.53**, not the runtime's
+These measurements predate the installed-browser/default-visible runtime change.
+The final paired runs used installed **Chrome 153.0.8010.53**, not the then-default
pinned Chrome 154. Chrome 153's live `/json/protocol` did not advertise
`Page.startScreencast.sendLastFrame`; the implementation requests that optional
field, but these results do not establish its behavior on pinned Chrome 154.
@@ -169,7 +173,7 @@ one missed deadline at 30 fps, although that counter eventually appeared.
Earlier pilot and intermediate runs also varied substantially. The table
measures the completed capture-credit change; it does not justify a production
latency guarantee. Repeat alternating comparisons and test the production
-React renderer and pinned browser before making that claim.
+React renderer and selected runtime before making that claim.
The four raw JSON reports were emitted with labels `baseline-paired`,
`current-paired`, `baseline-paired-fps10`, and `current-paired-fps10`. The
diff --git a/docs-internal/desktop_host_contract.md b/docs-internal/desktop_host_contract.md
index d1de0492..4893a131 100644
--- a/docs-internal/desktop_host_contract.md
+++ b/docs-internal/desktop_host_contract.md
@@ -178,9 +178,10 @@ plugin installers that `bun add` into the shared `<DATA_DIR>/packages/` tree
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 separately
-installs and supervises Chrome for Testing, with `BROWSER_CHROME_PATH` as the
-explicit executable override. See [browser.md](./browser.md) and
+uses `<DATA_DIR>/packages/browser-use/{tools,bin}`. OpenCompany supervises installed Chrome/Edge/Chromium in a dedicated profile,
+opening a visible window by default. `BROWSER_CHROME_PATH` overrides discovery;
+`BROWSER_HEADLESS=true` is explicit. 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`
keep bun's own cache and global state under the app's data dir rather than a
dev install's `~/.bun`. There is no Node in the bundle and nothing looks for
diff --git a/docs-internal/docker.md b/docs-internal/docker.md
index abea84a4..37092110 100644
--- a/docs-internal/docker.md
+++ b/docs-internal/docker.md
@@ -29,7 +29,7 @@ The default image has no browser, git or uv. Add them through the `EXTRAS` build
| `browser` | Chromium, fonts, Xvfb, uv | The current Browser node needs uv to install its pinned browser-use CLI; Chromium can be selected explicitly as described below |
| `git` | git | The Claude Code and Codex agent nodes, which work in git worktrees |
-Without the `browser` extra, the runtime image has no uv for the Browser node's tool installer or system Chromium and its libraries. The current node normally downloads its pinned Chrome for Testing; the image's legacy browser setting does not select system Chromium. Without the `git` extra, Claude Code and Codex tasks can fail with `working_directory_not_git_repo`.
+Without the `browser` extra, the runtime image has no uv for the Browser node's tool installer or system Chromium and its libraries. The default `BROWSER_RUNTIME=system` needs an installed Chrome/Edge/Chromium executable and never falls back to a download. Use `BROWSER_RUNTIME=testing` only when pinned Chrome for Testing is intended. Without the `git` extra, Claude Code and Codex tasks can fail with `working_directory_not_git_repo`.
The current runtime is documented in [browser.md](./browser.md), with live viewing and control in [browser_workspace.md](./browser_workspace.md). `browserHarness` is retired; browser-use is a dependency of the single `browser` node, not a second workflow node.
@@ -67,16 +67,18 @@ The image sets these on top of the template:
| `VITE_AUTH_ENABLED` | `true` | Login required |
| `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 |
-| `AGENT_BROWSER_EXECUTABLE_PATH` | `/usr/bin/chromium` | Legacy value still present in the Dockerfile; the current Browser runtime does not read it |
+| `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_HEADLESS` | `true` | Explicit container override of the desktop-visible default |
| `PYTHONUNBUFFERED` | `1` | Log lines reach `docker compose logs` as they are written |
-**Browser configuration mismatch:** `docker/Dockerfile` still sets `AGENT_BROWSER_EXECUTABLE_PATH`, while `nodes/browser/_install_chrome.py` reads `BROWSER_CHROME_PATH`. To use the `browser` extra's Chromium, explicitly set `BROWSER_CHROME_PATH=/usr/bin/chromium` under compose `environment:`. Otherwise the runtime downloads its pinned Chrome for Testing. This documents the current image; it does not mean the Dockerfile has been migrated or the current browser runtime has been validated in that image.
+**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 explicitly overrides the application's desktop-visible default, which requires a display. 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.
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.
With the `browser` extra: Chrome refuses to run as root with its sandbox on, so the image adds `--no-sandbox` through a drop-in, `/etc/chromium.d/no-sandbox`. Debian's launcher reads flags only from that directory and ignores a `CHROMIUM_FLAGS` environment variable. Debian's own `dev-shm` drop-in already adds `--disable-dev-shm-usage` when Docker's `/dev/shm` is small.
-Those drop-ins apply to Debian's Chromium launcher. The current runtime launches headless Chrome itself, detects sandbox/shared-memory constraints, and supplies its own launch flags; it does not use the former agent-browser/Xvfb startup path.
+Those drop-ins apply to Debian's Chromium launcher. OpenCompany supplies its runtime launch flags and detects sandbox/shared-memory constraints. The image already sets `BROWSER_HEADLESS=true` for displayless operation; do not rely on the former agent-browser/Xvfb startup path.
Leave `HOST` and `PORT` at their template values. The backend uses `HOST` to reach itself; the published bind comes from the entrypoint's `--host 0.0.0.0`. `PORT` is repeated in the Dockerfile's `EXPOSE` and the compose mapping, which do not follow a change made in `/data/opencompany.env`. Publish only the app port: the code sidecar, the WhatsApp bridge and Temporal listen on internal ports without authentication.
@@ -106,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 still carries the legacy executable setting and Xvfb. Unless `BROWSER_CHROME_PATH` is supplied, the current node downloads and runs its pinned Chrome for Testing despite system Chromium being installed. The pinned browser-use CLI is installed separately with uv. Validate the current runtime and its required Linux libraries in the built image; adding the extra alone is not evidence of an end-to-end browser check.
+- **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.
- **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/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.md
index 2ceba50d..85a74e45 100644
--- a/docs-internal/frontend_architecture.md
+++ b/docs-internal/frontend_architecture.md
@@ -500,7 +500,7 @@ See [media_transport.md](./media_transport.md).
## Browser workspace live view
-Home and Dev share [WorkspaceTabs](../client/src/components/workspace/WorkspaceTabs.tsx) and [BrowserWorkspace](../client/src/components/browser/BrowserWorkspace.tsx). Browser nodes are discovered through the backend `isBrowserPanel` capability; viewing attaches to a saved workflow/node without launching Chrome. The Browser tab supports server-authorized Take control / Hand back for navigation, mouse, keyboard, paste and login. Canvas retains its renderer; Android remains an explanatory placeholder.
+Home and Dev share [WorkspaceTabs](../client/src/components/workspace/WorkspaceTabs.tsx) and [BrowserWorkspace](../client/src/components/browser/BrowserWorkspace.tsx). Browser nodes are discovered through the backend `isBrowserPanel` capability; viewing attaches to a saved workflow/node without launching Chrome. The runtime defaults to installed Chrome/Edge/Chromium with a dedicated profile and visible window; headless and testing-browser modes are explicit server settings. The Browser tab supports server-authorized Take control / Hand back for navigation, mouse, keyboard, paste and login. Canvas retains its renderer; Android remains an explanatory placeholder.
The viewer uses a separate authenticated same-origin `/ws/browser` socket, not the general `WebSocketContext` frame stream. Binary JPEG envelopes are decoded sequentially with a two-frame local bound; consumed/skipped frames are acknowledged. Canvas dimensions change only when image dimensions change, and input coordinates use the metadata of the frame actually painted. Hidden, disposed or obsolete frames cannot restore a stale picture. Blur, pointer cancellation, hiding and unmount release user control; the server owns the release barrier and lease checks.
diff --git a/docs-internal/node-logic-flows/web_automation/browser.md b/docs-internal/node-logic-flows/web_automation/browser.md
index e822e4ad..72beba64 100644
--- a/docs-internal/node-logic-flows/web_automation/browser.md
+++ b/docs-internal/node-logic-flows/web_automation/browser.md
@@ -1,6 +1,6 @@
# Browser (`browser`)
-The Browser node drives OpenCompany-managed Chrome and exposes the same profile to the live browser workspace. It runs as a workflow step or as the agent tool named `browser`. The old `agent-browser` integration and separate `browserHarness` node have been replaced.
+The Browser node launches installed Chrome/Edge/Chromium in a dedicated OpenCompany profile, visible by default, and exposes that profile to the live browser workspace. `BROWSER_RUNTIME=testing` explicitly selects Chrome for Testing; `BROWSER_HEADLESS=true` explicitly hides the window. It never attaches to a personal browser profile. It runs as a workflow step or as the agent tool named `browser`. The old `agent-browser` integration and separate `browserHarness` node have been replaced.
See [native browser architecture](../../browser.md) for runtime installation, profile storage, networking and lifecycle, and [browser workspace](../../browser_workspace.md) for the viewer and UI protocol.
@@ -46,7 +46,7 @@ Refs resolve against a backend-node-ID map held per target, not against model-pr
1. Read operator configuration. For agent calls, reread the saved node settings so tool arguments cannot override the profile, policy, timeouts or executable code.
2. Reject workflow-only operations from agent calls and operations prohibited by `interaction`. Refuse automatic retries of operations in the node's `MUTATING` set when Temporal reports attempt greater than one; the previous action may already have occurred.
3. Resolve the owner's profile: explicit `profile_id`, otherwise the workflow's persistent default profile. Unsaved runs have a separate fallback. Register a session identified by owner, workflow and node, associated with that profile.
-4. Handle `close` and `diagnose` without opening a new runtime. Other operations open or reuse the profile runtime, installing managed dependencies on first use if needed.
+4. Handle `close` and `diagnose` without opening a new runtime. Other operations open or reuse the profile runtime, discovering the installed browser and installing the pinned CLI on first use if needed. Testing mode may also install pinned Chrome. The actual selected browser version must be compatible with the saved profile; downgrade errors never delete or replace the profile automatically.
5. `request_user` enters the human-handoff flow. Other operations acquire the profile's agent-operation lease/lock; human control blocks agent work.
6. `webmcp_list` reads the native tracker's tool cache; `webmcp_call` invokes through the native CDP integration. Remaining operations use a generated Python script sent to the isolated browser-use CLI, whose daemon persists across calls and connects to managed Chrome.
7. Update active target, URL/title and snapshot refs from the result. Map output to the node schema and emit page/session changes. CLI daemon failure permits one retry for operations outside `MUTATING`; operations inside that set are not retried by this wrapper.
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index 4292065f..ce77ab40 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -519,9 +519,9 @@ Queue distribution (live count via
| `triggers-event` | Push-based triggers | 100 |
| `triggers-poll` | Polling triggers (Gmail, etc.) | 100 |
| `code-exec` | Python / JS / TS sandboxes | 10 |
-| `browser` | Managed Chrome / browser-use / CDP | 4 |
+| `browser` | Installed Chrome/Edge/Chromium / browser-use / CDP | 4 |
-The current Browser plugin owns managed Chrome profiles, browser-use tool execution and the CDP live view. See [browser.md](./browser.md) and [browser_workspace.md](./browser_workspace.md); the retired `browserHarness` node is not a second active plugin.
+The current Browser plugin launches installed Chrome/Edge/Chromium in dedicated profiles with visible windows by default, owns browser-use tool execution and the CDP live view, and offers Chrome for Testing only through explicit testing mode. See [browser.md](./browser.md) and [browser_workspace.md](./browser_workspace.md); the retired `browserHarness` node is not a second active plugin.
Env overrides: `TEMPORAL_<QUEUE>_CONCURRENCY` (e.g.
`TEMPORAL_AI_HEAVY_CONCURRENCY=8`).
diff --git a/server/config/browser_runtime.json b/server/config/browser_runtime.json
index 300712be..2d091460 100644
--- a/server/config/browser_runtime.json
+++ b/server/config/browser_runtime.json
@@ -1,5 +1,5 @@
{
- "_comment": "Pins for the Browser node's runtime: the Chrome for Testing build OpenCompany downloads and launches, and the browser-use CLI that drives it. Bump both with `uv run python -m nodes.browser._pin` from server/ (it rewrites this file); never edit a version by hand without its checksums.",
+ "_comment": "Browser runtime download pins: Chrome for Testing is used only with BROWSER_RUNTIME=testing; installed Chrome/Edge/Chromium is the default. min_major also gates installed browsers. The browser-use CLI drives either provider. Bump pins with `uv run python -m nodes.browser._pin` from server/; never edit a version by hand without its checksums.",
"chrome_for_testing": {
"version": "154.0.8037.57",
"min_major": 150,
diff --git a/server/core/config.py b/server/core/config.py
index c5aa5f5d..beb21752 100644
--- a/server/core/config.py
+++ b/server/core/config.py
@@ -451,16 +451,20 @@ class Settings(BaseSettings):
# least recently used idle profile before another would exceed it; the
# idle timeout (ms) stops a profile's Chrome after that long with no
# agent step, viewer or login; 0 disables. The install timeout bounds
- # the first-use download of Chrome and the browser-use CLI. Sandbox:
+ # 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. chrome_path points at a Chrome of your own instead of the
- # pinned download (musl hosts, mirrors). Downloads a page starts are
+ # start. system discovers installed Chrome/Edge/Chromium; testing opts into
+ # the pinned download. chrome_path selects an explicit executable.
+ # Desktop browsers are visible unless headless is explicitly enabled.
+ # Downloads a page starts are
# capped at download_max_mb each.
browser_max_instances: int = Field(default=3, env="BROWSER_MAX_INSTANCES", ge=1, le=50)
browser_idle_timeout_ms: int = Field(default=600_000, env="BROWSER_IDLE_TIMEOUT_MS", ge=0)
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_runtime: str = Field(default="system", env="BROWSER_RUNTIME", pattern="^(system|testing)$")
+ browser_headless: bool = Field(default=False, env="BROWSER_HEADLESS")
browser_download_max_mb: int = Field(default=200, env="BROWSER_DOWNLOAD_MAX_MB", ge=1)
# Compaction Configuration. Threshold = model context_length ×
diff --git a/server/nodes/README.md b/server/nodes/README.md
index cccb6f89..e40f482f 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -145,7 +145,7 @@ tool/ — calculatorTool / currentTimeTool / writeTodos / taskManager
utility/ — console / httpRequest / webhookResponse / processManager / team_monitor
workflow/ — start
skill/ — simpleMemory / masterSkill
-browser/ — browser (managed Chrome for Testing + browser-use CLI, profiles, live view and user takeover)
+browser/ — browser (installed Chrome/Edge/Chromium + browser-use CLI; Chrome for Testing opt-in, profiles, live view and user takeover)
stripe/ — Stripe (CLI passthrough action + signed-webhook trigger)
vercel/ — Vercel (CLI deploy / inspect / list / custom passthrough)
github/ — GitHub (gh CLI: clone / PRs / issues / custom; palette group "vcs")
diff --git a/server/nodes/browser/_chrome.py b/server/nodes/browser/_chrome.py
index 31117e7b..33eb9ed2 100644
--- a/server/nodes/browser/_chrome.py
+++ b/server/nodes/browser/_chrome.py
@@ -1,10 +1,10 @@
"""Launching and stopping one profile's Chrome.
-Chrome runs ``--headless=new`` (full Chrome, not the old headless shell)
-with its own ``--user-data-dir``, a debugging port chosen by the OS
+An installed browser opens a visible window by default, with explicit headless
+mode available for servers. It uses its own ``--user-data-dir`` and a debugging port chosen by the OS
(``--remote-debugging-port=0``; the real port is read back from the
``DevToolsActivePort`` file), and every request routed through the egress
-proxy. The user sees it only through the in-app live view.
+proxy. The same browser is also available through the in-app live view.
Never passed: ``--remote-allow-origins=*`` (it would let web pages talk to
the debugging port), ``--enable-automation`` (the "controlled by automated
@@ -73,6 +73,9 @@ _ENV_ALLOWLIST = (
"LC_ALL",
"TZ",
"DISPLAY",
+ "WAYLAND_DISPLAY",
+ "XAUTHORITY",
+ "DBUS_SESSION_BUS_ADDRESS",
"XDG_RUNTIME_DIR",
"FONTCONFIG_PATH",
"FONTCONFIG_FILE",
@@ -105,6 +108,8 @@ def build_chrome_argv(
small_shm: bool,
platform: Optional[str] = None,
downloads_dir: Optional[Path] = None,
+ headless: bool = False,
+ override_user_agent: bool = False,
) -> List[str]:
platform = platform or sys.platform
argv = [
@@ -112,18 +117,15 @@ def build_chrome_argv(
f"--user-data-dir={user_data_dir}",
"--remote-debugging-address=127.0.0.1",
"--remote-debugging-port=0",
- "--headless=new",
"--no-first-run",
"--no-default-browser-check",
"--disable-sync",
- "--disable-component-update",
"--no-pings",
"--hide-crash-restore-bubble",
"--disable-renderer-backgrounding",
"--disable-backgrounding-occluded-windows",
"--disable-background-timer-throttling",
f"--window-size={VIEWPORT_WIDTH},{VIEWPORT_HEIGHT}",
- f"--user-agent={user_agent(major, platform)}",
f"--proxy-server=http://127.0.0.1:{proxy_port}",
# Chrome sends loopback requests direct by default; this removes that
# rule so localhost goes through the egress proxy's policy too.
@@ -133,9 +135,13 @@ def build_chrome_argv(
"--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
"--enable-features=" + ",".join(ENABLED_FEATURES),
]
- if platform.startswith("linux"):
+ if headless:
+ argv.append("--headless=new")
+ if override_user_agent:
+ argv.extend([f"--user-agent={user_agent(major, platform)}", "--disable-component-update"])
+ if override_user_agent and platform.startswith("linux"):
argv.append("--password-store=basic")
- elif platform == "darwin":
+ elif override_user_agent and platform == "darwin":
argv.append("--use-mock-keychain")
if no_sandbox:
argv.append("--no-sandbox")
@@ -255,6 +261,8 @@ class ChromeProcess(BaseProcessSupervisor):
major: int,
no_sandbox: bool,
small_shm: bool,
+ headless: bool = False,
+ override_user_agent: bool = False,
) -> None:
super().__init__()
self.name = f"browser-chrome:{profile_id}"
@@ -266,6 +274,8 @@ class ChromeProcess(BaseProcessSupervisor):
self._major = major
self._no_sandbox = no_sandbox
self._small_shm = small_shm
+ self._headless = headless
+ self._override_user_agent = override_user_agent
self._profile_lock = ProfileLock(profile_root / "oc.lock")
self._locked = False
self.port: Optional[int] = None
@@ -289,6 +299,8 @@ class ChromeProcess(BaseProcessSupervisor):
major=self._major,
no_sandbox=self._no_sandbox,
small_shm=self._small_shm,
+ headless=self._headless,
+ override_user_agent=self._override_user_agent,
)
def env(self) -> Dict[str, str]:
@@ -318,6 +330,8 @@ class ChromeProcess(BaseProcessSupervisor):
async def launch(self) -> CDPConnection:
"""Start Chrome, wait for its debugging port, connect over CDP."""
+ if sys.platform.startswith("linux") and not self._headless and not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
+ raise NodeUserError("A visible browser needs a desktop display. Set BROWSER_HEADLESS=true for a server without a display.")
register_supervisor(self)
try:
await self.start()
diff --git a/server/nodes/browser/_config.py b/server/nodes/browser/_config.py
index cfd21d36..dc84b4f3 100644
--- a/server/nodes/browser/_config.py
+++ b/server/nodes/browser/_config.py
@@ -1,9 +1,10 @@
"""Typed access to ``server/config/browser_runtime.json``.
The JSON is the single source of truth for what the Browser node downloads:
-the Chrome for Testing build (version, per-platform checksum, size and
+the opt-in Chrome for Testing build (version, per-platform checksum, size and
executable path), the Linux libraries that build needs, and the pinned
-browser-use CLI. ``_pin.py`` rewrites it; nothing else hardcodes a version.
+browser-use CLI. Installed browsers are selected by default; their minimum
+supported major is also recorded here. ``_pin.py`` rewrites the download pins.
"""
from __future__ import annotations
diff --git a/server/nodes/browser/_install.py b/server/nodes/browser/_install.py
index 32372a80..44418e95 100644
--- a/server/nodes/browser/_install.py
+++ b/server/nodes/browser/_install.py
@@ -1,9 +1,9 @@
"""Install the Browser node's runtime ahead of first use.
-Normally the pinned Chrome for Testing and the browser-use CLI are fetched
-the first time a Browser node runs (``_install_chrome.py``,
-``_install_bu.py``). This entry point fetches both now, for an image or a
-machine that should not download on first use::
+Normally the installed browser is selected and the browser-use CLI is fetched
+the first time a Browser node runs. This entry point validates that browser
+and installs the CLI ahead of time. With explicit ``BROWSER_RUNTIME=testing``,
+it also downloads the pinned Chrome for Testing build::
uv run python -m nodes.browser._install # from server/
"""
diff --git a/server/nodes/browser/_install_chrome.py b/server/nodes/browser/_install_chrome.py
index f988ee7e..fc9fdf5f 100644
--- a/server/nodes/browser/_install_chrome.py
+++ b/server/nodes/browser/_install_chrome.py
@@ -1,4 +1,9 @@
-"""Download and unpack the pinned Chrome for Testing build.
+"""Select installed Chrome/Edge/Chromium, or explicitly install a testing build.
+
+The default system provider never downloads Chrome. ``BROWSER_CHROME_PATH``
+overrides discovery in either provider, and the selected binary's actual
+version is checked before a profile is opened. ``BROWSER_RUNTIME=testing``
+opts into the downloader described below.
The version and each platform's MD5 and size come from
``server/config/browser_runtime.json``. The build lands under
@@ -54,12 +59,13 @@ class InstallState:
failures: int = 0
failed_at: float = 0.0
exe: Optional[str] = None
+ source: str = ""
bytes_done: int = 0
bytes_total: int = 0
cancel: threading.Event = field(default_factory=threading.Event)
def snapshot(self) -> dict:
- return {"phase": self.phase, "percent": self.percent, "version": self.version, "error": self.error, "exe": self.exe}
+ return {"phase": self.phase, "percent": self.percent, "version": self.version, "error": self.error, "exe": self.exe, "source": self.source}
class _Progress:
@@ -145,22 +151,6 @@ class ChromeInstaller:
)
return plat
- def _override(self) -> Optional[Path]:
- from core.container import container
-
- raw = str(getattr(container.settings(), "browser_chrome_path", "") or "").strip()
- if not raw:
- return None
- path = Path(raw).expanduser()
- if "/snap/" in path.as_posix():
- raise NodeUserError(
- "BROWSER_CHROME_PATH points at a snap package; snap confinement hides OpenCompany's data folder from it. "
- "Use a Chrome installed from a .deb or tarball."
- )
- if not path.is_file():
- raise NodeUserError(f"BROWSER_CHROME_PATH does not exist: {path}")
- return path
-
def installed_exe(self) -> Optional[Path]:
"""The pinned build's executable if it is fully installed, without installing."""
plat = self.platform()
@@ -172,32 +162,61 @@ class ChromeInstaller:
def status(self) -> dict:
snap = self.state.snapshot()
- snap["version"] = snap.get("version") or self.pin.version
+ snap["provider"] = self.provider()
return snap
+ def provider(self) -> str:
+ from core.container import container
+
+ provider = str(getattr(container.settings(), "browser_runtime", "system") or "system").lower()
+ if provider not in {"system", "testing"}:
+ raise NodeUserError("BROWSER_RUNTIME must be system or testing.")
+ return provider
+
+ async def _selected(self, exe: Path, source: str) -> 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.")
+ self.state.phase, self.state.exe, self.state.version = "ready", str(exe), version
+ self.state.source, self.state.error = source, None
+ return exe
+
# -- install ----------------------------------------------------------
async def ensure(self, *, wait: float) -> Path:
- """Path to a runnable Chrome, installing it if needed.
+ """Path to a supported browser; only testing mode may download it.
- Waits at most ``wait`` seconds; the install itself keeps running in
- the background when the caller gives up.
+ Testing downloads wait at most ``wait`` seconds and keep running in
+ the background when the caller gives up. Version preflight is separate.
"""
- override = self._override()
- if override is not None:
- return override
+ from core.container import container
+
+ from ._system_browser import discover_browser
+
+ provider = 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)
+ except Exception as exc:
+ self.state.phase, self.state.error = "failed", str(exc)
+ self.state.version, self.state.exe, self.state.source = "", None, ""
+ raise
exe = self.installed_exe()
if exe is not None:
- self.state.phase, self.state.exe = "ready", str(exe)
- return exe
+ return await self._selected(exe, "testing")
task = await self._start()
try:
- return await asyncio.wait_for(asyncio.shield(task), timeout=max(0.0, wait))
+ exe = await asyncio.wait_for(asyncio.shield(task), timeout=max(0.0, wait))
except asyncio.TimeoutError:
pct = self.state.percent
progress = 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")
async def _start(self) -> asyncio.Task:
async with self._lock:
diff --git a/server/nodes/browser/_runtime.py b/server/nodes/browser/_runtime.py
index 7d34b32a..f4c8a8d0 100644
--- a/server/nodes/browser/_runtime.py
+++ b/server/nodes/browser/_runtime.py
@@ -1,7 +1,8 @@
"""The fleet of running profile browsers.
-:class:`BrowserRuntime` (one per backend process) installs the pinned Chrome
-and browser-use CLI on first use, starts a profile's Chrome when a Browser
+:class:`BrowserRuntime` (one per backend process) selects an installed browser
+(or explicitly opted-in testing build), installs the browser-use CLI on first
+use, starts a profile's Chrome when a Browser
node or a viewer needs it, stops it when it has been idle for
``BROWSER_IDLE_TIMEOUT_MS``, and keeps at most ``BROWSER_MAX_INSTANCES``
running by stopping the least recently used idle one.
@@ -10,7 +11,7 @@ For each running profile a :class:`ProfileRuntime` holds the Chrome process,
its egress proxy, the backend's CDP connection, the CLI bound to it, the
WebMCP tracker and the :class:`~._session.ProfileController`. On the backend
connection every page is auto-attached (paused until configured) so the
-user-agent override, WebMCP tracking and tab tracking are in place before a
+WebMCP tracking and tab tracking are in place before a
page, or a popup, runs a line of script.
"""
@@ -21,7 +22,6 @@ import ipaddress
import sys
import time
from dataclasses import dataclass, replace
-from pathlib import Path
from typing import Any, Dict, FrozenSet, List, Optional
from core.logging import get_logger
@@ -38,6 +38,7 @@ from ._install_chrome import get_chrome_installer
from ._netpolicy import NetPolicy, own_ports_from_env
from ._profiles import Profile, profile_dir, user_data_dir
from ._session import BrowserSession, ControlState, ProfileController
+from ._system_browser import version_major
from ._webmcp import WebMcpTracker
logger = get_logger(__name__)
@@ -93,6 +94,7 @@ class ProfileRuntime:
cli: BrowserUseCli
webmcp: WebMcpTracker
full_version: str = ""
+ provider: str = "system"
started_at: float = 0.0
@property
@@ -224,15 +226,17 @@ class BrowserRuntime:
async def _start(self, profile: Profile) -> ProfileRuntime:
settings = self._settings()
pin = get_config().chrome
- if profile.chrome_major and profile.chrome_major > pin.major:
+ installer = get_chrome_installer()
+ exe = await installer.ensure(wait=float(settings.browser_install_timeout_seconds))
+ selected_version = installer.state.version
+ selected_major = version_major(selected_version)
+ if profile.chrome_major and profile.chrome_major > selected_major:
raise NodeUserError(
f"The profile {profile.name!r} was last opened by a newer Chrome ({profile.chrome_major}); this install "
- f"has Chrome {pin.major}. Update OpenCompany, or use another profile."
+ f"has browser {selected_major}. Update your browser or select another profile."
)
- exe, bu_paths = await asyncio.gather(
- get_chrome_installer().ensure(wait=float(settings.browser_install_timeout_seconds)),
- get_browser_use_installer().ensure(wait=float(settings.browser_install_timeout_seconds)),
- )
+ provider = installer.provider()
+ bu_paths = await get_browser_use_installer().ensure(wait=float(settings.browser_install_timeout_seconds))
await self._make_room(exclude=profile.id)
controller = self.controller_for(profile)
@@ -253,13 +257,18 @@ class BrowserRuntime:
profile_root=profile_dir(profile.id),
user_data_dir=user_data_dir(profile.id),
proxy_port=proxy_port,
- major=pin.major,
+ major=selected_major,
no_sandbox=no_sandbox,
small_shm=shm_small(),
+ headless=bool(getattr(settings, "browser_headless", False)),
+ override_user_agent=provider == "testing",
)
self._chromes[profile.id] = chrome
else:
chrome._exe, chrome._proxy_port = exe, proxy_port
+ chrome._major = selected_major
+ chrome._headless = bool(getattr(settings, "browser_headless", False))
+ chrome._override_user_agent = provider == "testing"
cli = BrowserUseCli(
cli_path=bu_paths["cli"], python_path=bu_paths["python"], profile_id=profile.id, cdp_http_url="http://127.0.0.1:0"
@@ -270,11 +279,14 @@ class BrowserRuntime:
cli.cdp_http_url = f"http://127.0.0.1:{chrome.port}"
webmcp = WebMcpTracker()
runtime = ProfileRuntime(
- profile=profile, controller=controller, chrome=chrome, proxy=proxy, cdp=cdp, cli=cli, webmcp=webmcp, started_at=time.monotonic()
+ profile=profile, controller=controller, chrome=chrome, proxy=proxy, cdp=cdp, cli=cli, webmcp=webmcp, started_at=time.monotonic(), provider=provider
)
try:
version = await cdp.send("Browser.getVersion")
- runtime.full_version = str(version.get("product", "")).split("/", 1)[-1] or pin.version
+ runtime.full_version = str(version.get("product", "")).split("/", 1)[-1]
+ actual_major = version_major(runtime.full_version)
+ if actual_major < pin.min_major or (profile.chrome_major and actual_major < profile.chrome_major):
+ raise NodeUserError("The launched browser is older than this profile or the minimum supported browser version. Update the selected browser or use another profile.")
await self._wire(runtime)
except BaseException:
await chrome.shutdown()
@@ -287,7 +299,8 @@ class BrowserRuntime:
from ._profiles import ProfileStore
- await ProfileStore(get_database()).record_chrome_major(profile.id, pin.major)
+ await ProfileStore(get_database()).record_chrome_major(profile.id, actual_major)
+ runtime.profile = replace(profile, chrome_major=actual_major)
except Exception: # noqa: BLE001 - the downgrade guard is advisory
logger.debug("[browser] could not record the Chrome version on the profile", exc_info=True)
logger.info("[browser] profile %s (%s) running Chrome %s on port %s", profile.id, profile.name, runtime.full_version, chrome.port)
@@ -295,14 +308,15 @@ class BrowserRuntime:
async def _wire(self, runtime: ProfileRuntime) -> None:
cdp, controller = runtime.cdp, runtime.controller
- major = int(runtime.full_version.split(".", 1)[0]) if runtime.full_version[:1].isdigit() else get_config().chrome.major
+ major = version_major(runtime.full_version)
ua = user_agent(major)
metadata = _ua_metadata(major, runtime.full_version)
async def configure(session: CDPSession, target: Dict[str, Any], waiting: bool) -> None:
try:
if target.get("type") == "page":
- await session.send("Network.setUserAgentOverride", {"userAgent": ua, "userAgentMetadata": metadata}, timeout=10)
+ if runtime.provider == "testing":
+ await session.send("Network.setUserAgentOverride", {"userAgent": ua, "userAgentMetadata": metadata}, timeout=10)
await session.send("Page.enable", timeout=10)
await runtime.webmcp.attach(session.target_id, session)
except (CDPError, CDPDisconnected, TimeoutError):
@@ -445,7 +459,7 @@ class BrowserRuntime:
"chrome": get_chrome_installer().status(),
"cli": get_browser_use_installer().status(),
"running": [
- {"profile_id": pid, "name": r.profile.name, "state": r.controller.state.value, "port": r.chrome.port}
+ {"profile_id": pid, "name": r.profile.name, "state": r.controller.state.value, "port": r.chrome.port, "version": r.full_version, "provider": r.provider}
for pid, r in self._profiles.items()
if r.running
],
diff --git a/server/nodes/browser/_system_browser.py b/server/nodes/browser/_system_browser.py
new file mode 100644
index 00000000..b820f985
--- /dev/null
+++ b/server/nodes/browser/_system_browser.py
@@ -0,0 +1,98 @@
+"""Discover an installed browser without opening a personal browser session."""
+
+from __future__ import annotations
+
+import asyncio
+import ctypes
+import os
+from pathlib import Path
+import re
+import shutil
+import sys
+
+from services.plugin.base import NodeUserError
+
+
+def version_major(version: str) -> int:
+ match = re.search(r"\b(\d+)\.\d+\.\d+\.\d+\b", version)
+ if not match:
+ raise NodeUserError(f"Could not determine the installed browser version: {version!r}")
+ return int(match.group(1))
+
+
+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")):
+ 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")):
+ for root in (Path("/Applications"), Path.home() / "Applications"):
+ yield root / f"{app}.app/Contents/MacOS/{binary}", name
+ else:
+ for name, commands in (("chrome", ("google-chrome", "google-chrome-stable")), ("edge", ("microsoft-edge", "microsoft-edge-stable")), ("chromium", ("chromium", "chromium-browser"))):
+ for command in commands:
+ found = shutil.which(command)
+ if found:
+ yield Path(found), name
+
+
+def discover_browser(override: str = "") -> tuple[Path, str]:
+ if override.strip():
+ path = Path(override).expanduser()
+ if not path.is_file():
+ raise NodeUserError(f"BROWSER_CHROME_PATH does not exist: {path}")
+ candidates = [(path, "override")]
+ else:
+ candidates = _candidates()
+ for path, source in candidates:
+ if not path.is_file():
+ continue
+ if "/snap/" in path.as_posix() or "/snap/" in path.resolve().as_posix():
+ 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
+ raise 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 _windows_version(path: Path) -> str:
+ # chrome.exe --version can open a GUI on Windows. Read VERSIONINFO instead.
+ from ctypes import wintypes
+
+ dll = ctypes.WinDLL("version", use_last_error=True)
+ dll.GetFileVersionInfoSizeW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(wintypes.DWORD)]
+ dll.GetFileVersionInfoSizeW.restype = wintypes.DWORD
+ dll.GetFileVersionInfoW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p]
+ dll.VerQueryValueW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.UINT)]
+ size = dll.GetFileVersionInfoSizeW(str(path), None)
+ if not size:
+ raise NodeUserError(f"Cannot read browser version metadata: {path}")
+ data = ctypes.create_string_buffer(size)
+ pointer, length = ctypes.c_void_p(), wintypes.UINT()
+ if not dll.GetFileVersionInfoW(str(path), 0, size, data) or not dll.VerQueryValueW(data, "\\", ctypes.byref(pointer), ctypes.byref(length)) or length.value < 16:
+ raise NodeUserError(f"Cannot read browser version metadata: {path}")
+ info = ctypes.cast(pointer, ctypes.POINTER(wintypes.DWORD))
+ if info[0] != 0xFEEF04BD:
+ raise NodeUserError(f"Invalid browser version metadata: {path}")
+ ms, ls = info[2], info[3]
+ return f"{ms >> 16}.{ms & 65535}.{ls >> 16}.{ls & 65535}"
+
+
+async def browser_version(path: Path) -> str:
+ if sys.platform == "win32":
+ return await asyncio.to_thread(_windows_version, path)
+ process = await asyncio.create_subprocess_exec(str(path), "--version", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
+ try:
+ stdout, _ = await asyncio.wait_for(process.communicate(), timeout=5)
+ except BaseException:
+ if process.returncode is None:
+ process.kill()
+ await process.wait()
+ raise
+ match = re.search(r"\b\d+\.\d+\.\d+\.\d+\b", stdout.decode(errors="replace"))
+ if process.returncode or not match:
+ raise NodeUserError(f"Cannot determine browser version from {path}; check BROWSER_CHROME_PATH.")
+ return match.group(0)
diff --git a/server/nodes/browser/browser/__init__.py b/server/nodes/browser/browser/__init__.py
index 4f838162..1c7c2e4a 100644
--- a/server/nodes/browser/browser/__init__.py
+++ b/server/nodes/browser/browser/__init__.py
@@ -1,6 +1,6 @@
"""Browser — a real Chrome the agent drives, and the owner can watch and take over.
-OpenCompany launches a pinned Chrome for Testing per browser profile and the
+OpenCompany launches installed Chrome/Edge/Chromium per dedicated browser profile and the
agent drives it through the browser-use CLI: it reads pages through the
accessibility tree (``snapshot`` returns ``[e12]``-style refs), acts on refs
(``click``, ``type``, ``select``), calls the tools a page offers through
diff --git a/server/tests/nodes/browser/test_browser_runtime_units.py b/server/tests/nodes/browser/test_browser_runtime_units.py
index c28d535a..19c7fe57 100644
--- a/server/tests/nodes/browser/test_browser_runtime_units.py
+++ b/server/tests/nodes/browser/test_browser_runtime_units.py
@@ -56,15 +56,36 @@ def test_a_script_error_is_reported_not_raised():
def test_chrome_flags(tmp_path):
argv = build_chrome_argv(Path("chrome"), user_data_dir=tmp_path, proxy_port=4000, major=154, no_sandbox=False, small_shm=False, platform="linux")
- assert "--headless=new" in argv and "--remote-debugging-port=0" in argv
+ assert "--headless=new" not in argv and "--remote-debugging-port=0" in argv
assert "--proxy-server=http://127.0.0.1:4000" in argv and "--proxy-bypass-list=<-loopback>" in argv
- assert "--password-store=basic" in argv and "--no-sandbox" not in argv
+ assert "--password-store=basic" not in argv and "--no-sandbox" not in argv
+ assert not any(a.startswith("--user-agent=") for a in argv)
+ assert "--disable-component-update" not in argv
assert sum(a.startswith("--enable-features=") for a in argv) == 1
assert not any(a.startswith("--remote-allow-origins") or a == "--enable-automation" for a in argv)
assert "HeadlessChrome" not in " ".join(argv) and "Chrome/154.0.0.0" in user_agent(154, "win32")
root = build_chrome_argv(Path("chrome"), user_data_dir=tmp_path, proxy_port=1, major=154, no_sandbox=True, small_shm=True, platform="linux")
assert "--no-sandbox" in root and "--disable-dev-shm-usage" in root
- assert "--use-mock-keychain" in build_chrome_argv(Path("c"), user_data_dir=tmp_path, proxy_port=1, major=1, no_sandbox=False, small_shm=False, platform="darwin")
+ mac = build_chrome_argv(Path("c"), user_data_dir=tmp_path, proxy_port=1, major=1, no_sandbox=False, small_shm=False, platform="darwin")
+ assert "--use-mock-keychain" not in mac
+
+
+def test_testing_browser_flags_are_explicit(tmp_path):
+ argv = build_chrome_argv(Path("chrome"), user_data_dir=tmp_path, proxy_port=4000, major=154, no_sandbox=False, small_shm=False, platform="linux", headless=True, override_user_agent=True)
+ assert "--headless=new" in argv and "--password-store=basic" in argv
+ assert any(a.startswith("--user-agent=") for a in argv)
+
+
+async def test_visible_browser_requires_linux_display(monkeypatch, tmp_path):
+ from nodes.browser._chrome import ChromeProcess
+ from services.plugin.base import NodeUserError
+
+ monkeypatch.setattr("nodes.browser._chrome.sys.platform", "linux")
+ monkeypatch.delenv("DISPLAY", raising=False)
+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)
+ chrome = ChromeProcess(profile_id="test", exe=Path("chrome"), profile_root=tmp_path, user_data_dir=tmp_path / "profile", proxy_port=1, major=154, no_sandbox=False, small_shm=False)
+ with pytest.raises(NodeUserError, match="BROWSER_HEADLESS=true"):
+ await chrome.launch()
def test_the_cli_gets_no_secrets_and_no_telemetry(monkeypatch, tmp_path):
diff --git a/server/tests/nodes/browser/test_system_browser.py b/server/tests/nodes/browser/test_system_browser.py
new file mode 100644
index 00000000..026e3233
--- /dev/null
+++ b/server/tests/nodes/browser/test_system_browser.py
@@ -0,0 +1,185 @@
+"""System provider selection and startup guards; never launch an installed browser."""
+
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from nodes.browser import _system_browser as system
+from nodes.browser._install_chrome import ChromeInstaller
+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.__dict__.update(values)
+ monkeypatch.setattr(container, "settings", lambda: result)
+ return result
+
+
+def test_explicit_browser_wins_and_invalid_override_never_falls_back(monkeypatch):
+ monkeypatch.setattr(Path, "is_file", lambda p: str(p) == "chosen.exe")
+ monkeypatch.setattr(system, "_candidates", Mock(side_effect=AssertionError("must not discover")))
+ assert system.discover_browser("chosen.exe") == (Path("chosen.exe"), "override")
+ with pytest.raises(NodeUserError, match="does not exist"):
+ system.discover_browser("missing.exe")
+
+
+def test_discovery_order_and_missing_message(monkeypatch):
+ monkeypatch.setattr(system, "_candidates", lambda: [(Path("chrome"), "chrome"), (Path("edge"), "edge"), (Path("chromium"), "chromium")])
+ monkeypatch.setattr(Path, "is_file", lambda p: p.name in {"edge", "chromium"})
+ assert system.discover_browser() == (Path("edge"), "edge")
+ monkeypatch.setattr(Path, "is_file", lambda p: False)
+ with pytest.raises(NodeUserError, match="BROWSER_RUNTIME=testing"):
+ system.discover_browser()
+
+
[email protected]("platform", ["win32", "darwin", "linux"])
+def test_platform_candidates_prefer_chrome_then_edge_then_chromium(monkeypatch, platform):
+ monkeypatch.setattr(system.sys, "platform", platform)
+ monkeypatch.setenv("PROGRAMFILES", "Programs")
+ monkeypatch.setenv("PROGRAMFILES(X86)", "Programs86")
+ monkeypatch.setenv("LOCALAPPDATA", "Local")
+ monkeypatch.setattr(system.shutil, "which", lambda command: command)
+ names = [name for _, name in system._candidates()]
+ assert names and names == sorted(names, key={"chrome": 0, "edge": 1, "chromium": 2}.get)
+
+
+async def test_windows_version_reads_metadata_without_launch(monkeypatch):
+ monkeypatch.setattr(system.sys, "platform", "win32")
+ monkeypatch.setattr(system, "_windows_version", lambda path: "151.2.3.4")
+ monkeypatch.setattr(system.asyncio, "create_subprocess_exec", Mock(side_effect=AssertionError("no GUI probe")))
+ assert await system.browser_version(Path("chrome.exe")) == "151.2.3.4"
+
+
+async def test_posix_version_timeout_kills_and_reaps(monkeypatch):
+ monkeypatch.setattr(system.sys, "platform", "linux")
+ process = SimpleNamespace(returncode=None, communicate=AsyncMock(side_effect=TimeoutError), kill=Mock(), wait=AsyncMock())
+ monkeypatch.setattr(system.asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
+ with pytest.raises(TimeoutError):
+ await system.browser_version(Path("chrome"))
+ process.kill.assert_called_once()
+ process.wait.assert_awaited_once()
+
+
+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, "browser_version", AsyncMock(return_value="151.2.3.4"))
+ monkeypatch.setattr(installer, "_start", AsyncMock(side_effect=AssertionError("no download")))
+ assert installer.status()["version"] == ""
+ assert await installer.ensure(wait=10) == Path("edge")
+ assert installer.status() == {"phase": "ready", "percent": None, "version": "151.2.3.4", "error": None, "exe": "edge", "source": "edge", "provider": "system"}
+
+
+async 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")))
+ download = AsyncMock(side_effect=AssertionError("no fallback"))
+ monkeypatch.setattr(installer, "_start", download)
+ with pytest.raises(NodeUserError, match="install a browser"):
+ await installer.ensure(wait=10)
+ download.assert_not_called()
+ assert installer.status()["phase"] == "failed"
+
+
+async def test_minimum_browser_gate(monkeypatch):
+ settings(monkeypatch)
+ installer = ChromeInstaller()
+ monkeypatch.setattr(system, "discover_browser", 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)
+
+
+async def test_testing_provider_is_explicit_and_override_still_wins(monkeypatch):
+ config = settings(monkeypatch, browser_runtime="testing")
+ installer = ChromeInstaller()
+ monkeypatch.setattr(installer, "installed_exe", lambda: Path("testing"))
+ monkeypatch.setattr(system, "browser_version", AsyncMock(return_value="154.0.1.2"))
+ 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"))
+ assert await installer.ensure(wait=10) == Path("custom")
+ assert installer.status()["source"] == "override"
+
+
+async def test_downgrade_guard_uses_selected_browser_before_launch(monkeypatch):
+ from nodes.browser import _runtime as module
+ from nodes.browser._profiles import Profile
+
+ config = settings(monkeypatch)
+ runtime = module.BrowserRuntime()
+ monkeypatch.setattr(runtime, "_settings", lambda: config)
+ installer = SimpleNamespace(ensure=AsyncMock(return_value=Path("chrome")), state=SimpleNamespace(version="151.0.0.0"))
+ monkeypatch.setattr(module, "get_chrome_installer", lambda: installer)
+ monkeypatch.setattr(module, "ChromeProcess", Mock(side_effect=AssertionError("must not launch")))
+ profile = Profile("id", "owner", "saved", "custom", None, 152)
+ with pytest.raises(NodeUserError, match="browser 151"):
+ await runtime._start(profile)
+
+
[email protected]("provider,expected", [("system", False), ("testing", True)])
+async def test_runtime_preserves_system_user_agent(monkeypatch, provider, expected):
+ from nodes.browser import _runtime as module
+
+ session = SimpleNamespace(send=AsyncMock(), target_id="t")
+ cdp = SimpleNamespace(on=Mock(), send=AsyncMock(), page_targets=AsyncMock(return_value=[{"targetId": "t", "type": "page"}]), attach=AsyncMock(return_value=session))
+ controller = SimpleNamespace(tabs={}, active_target_id=None)
+ profile_runtime = SimpleNamespace(cdp=cdp, controller=controller, full_version="151.1.2.3", provider=provider, webmcp=SimpleNamespace(attach=AsyncMock()))
+ await module.BrowserRuntime()._wire(profile_runtime)
+ methods = [call.args[0] for call in session.send.await_args_list]
+ assert ("Network.setUserAgentOverride" in methods) is expected
+
+
+async def test_start_records_connected_version_and_passes_actual_major(monkeypatch):
+ import asyncio
+
+ from nodes.browser import _profiles, _runtime as module
+ from services.plugin import deps
+
+ config = settings(monkeypatch)
+ runtime = module.BrowserRuntime()
+ monkeypatch.setattr(runtime, "_settings", lambda: config)
+ monkeypatch.setattr(runtime, "_make_room", AsyncMock())
+ monkeypatch.setattr(runtime, "_wire", AsyncMock())
+ monkeypatch.setattr(runtime, "_watch", AsyncMock())
+ monkeypatch.setattr(module, "profile_dir", lambda p: Path("profiles") / p)
+ monkeypatch.setattr(module, "user_data_dir", lambda p: Path("profiles") / p / "user-data")
+ installer = SimpleNamespace(ensure=AsyncMock(return_value=Path("chrome")), state=SimpleNamespace(version="151.0.0.0"), provider=lambda: "system")
+ monkeypatch.setattr(module, "get_chrome_installer", lambda: installer)
+ monkeypatch.setattr(module, "get_browser_use_installer", lambda: SimpleNamespace(ensure=AsyncMock(return_value={"cli": Path("cli"), "python": Path("py")})))
+ proxy = SimpleNamespace(start=Mock(return_value=5000), port=5000)
+ monkeypatch.setattr(module, "EgressProxy", Mock(return_value=proxy))
+ cdp = SimpleNamespace(send=AsyncMock(return_value={"product": "Chrome/152.1.2.3"}))
+ chrome = SimpleNamespace(launch=AsyncMock(return_value=cdp), port=9000)
+ constructor = Mock(return_value=chrome)
+ monkeypatch.setattr(module, "ChromeProcess", constructor)
+ monkeypatch.setattr(module, "BrowserUseCli", Mock(return_value=SimpleNamespace(stop_daemon=Mock())))
+ record = AsyncMock()
+ monkeypatch.setattr(_profiles, "ProfileStore", lambda db: SimpleNamespace(record_chrome_major=record))
+ monkeypatch.setattr(deps, "get_database", lambda: object())
+ profile = _profiles.Profile("id", "owner", "saved", "custom", None, 150)
+ running = await runtime._start(profile)
+ await asyncio.sleep(0)
+ assert constructor.call_args.kwargs["major"] == 151
+ assert constructor.call_args.kwargs["headless"] is False
+ assert constructor.call_args.kwargs["override_user_agent"] is False
+ assert running.full_version == "152.1.2.3"
+ assert running.profile.chrome_major == 152
+ record.assert_awaited_once_with("id", 152)