The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): a real profile that can't load falls back to a fresh browser
Teknium80f4f989d3ab
diff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.pyindex 91330c32ec6..a58329fca92 100644--- a/hermes_cli/browser_connect.py+++ b/hermes_cli/browser_connect.py@@ -494,7 +494,8 @@ def _mirror_profile_auth(src: str, dst: str, source_profile: str) -> dict[str, sif session_db:failed[rel] = reasonelse:- logger.info("real-profile snapshot: skipped %s (%s); session cookies still copied", rel, reason)+ why = "the running browser holds a write lock on it" if reason == _AUTH_DB_LOCKED else reason+ logger.info("real-profile snapshot: skipped %s (%s); session cookies still copied", rel, why)return faileddiff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 93e0ea6e986..0407a6be401 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -449,20 +449,20 @@ DEFAULT_CONFIG = {# prefs copied and re-synced per fresh session) driven by Hermes' packaged Chromium. The# snapshot dir sidesteps Chrome 136+'s default-profile debugging block and never contends# with the running browser. Turning off deletes ~/.hermes/browser-profile/ so credentials- # don't outlive consent. Chromium-family only (Chrome, Edge, Brave, Brave Origin, Chromium);- # Firefox etc. fails closed. Also gates the browser_exec `local` argument (real-profile- # local session even under a cloud backend). Desktop Settings -> Browser.+ # don't outlive consent. Chromium-family only; a profile that can't be copied (Firefox default,+ # Windows browser holding its cookies) gives a fresh, signed-out browser plus a note saying why.+ # Also gates the browser_exec `local` arg (real-profile session under a cloud backend). Desktop Settings -> Browser."use_real_profile": False,# Windows only: a running Chrome/Edge/Brave locks its cookie DB, so the profile can't be- # copied. When on, a locked profile still blocks and the agent ASKS first; on approval it+ # copied (the session runs on a fresh browser). When on, the agent ASKS first; on approval it# runs `hermes browser close-profile` (kills that profile's browser tree, unsaved tabs lost)- # and retries once; still locked -> stays blocked, no auto-kill. No effect on macOS/Linux,- # where a running browser instead makes the Login Data / Web Data SQLite backups miss- # their deadline; quit the browser by hand there.+ # so a new session can copy it; no auto-kill. No effect on macOS/Linux, where a running+ # browser only locks the password/autofill DBs, which are skipped (cookies still copy)."real_profile_autoclose": False,# Pin WHICH source profile directory is snapshotted for real-profile browsing (e.g. "Profile# 2"). Empty = browser's last-used profile, which on multi-profile machines can hand the- # agent the wrong identity. A pin naming a missing directory FAILS CLOSED.+ # agent the wrong identity. A pin naming a missing directory never falls back to another+ # profile: the session gets a fresh browser without the user's logins."real_profile_pin": "",# restrict_evaluate: opt-in denylist blocking sensitive JS primitives (cookies/storage/# clipboard/network/form values) in browser_console(expression=...); allow_unsafe_evaluatediff --git a/tests/hermes_cli/test_browser_connect_real_profile_snapshot_errors.py b/tests/hermes_cli/test_browser_connect_real_profile_snapshot_errors.pyindex 1e763abfc2a..fbf53123d21 100644--- a/tests/hermes_cli/test_browser_connect_real_profile_snapshot_errors.py+++ b/tests/hermes_cli/test_browser_connect_real_profile_snapshot_errors.py@@ -18,8 +18,8 @@ _LOCKED = ("Login Data", "Login Data For Account", "Web Data")def _fake_profile(root):(root / "Default" / "Network").mkdir(parents=True)- (root / "Local State").write_text(json.dumps({"profile": {"last_used": "Default"}}))- (root / "Default" / "Preferences").write_text("{}")+ (root / "Local State").write_text(json.dumps({"profile": {"last_used": "Default"}}), encoding="utf-8")+ (root / "Default" / "Preferences").write_text("{}", encoding="utf-8")for name in ("Cookies", *_LOCKED):con = sqlite3.connect(root / "Default" / name)con.execute("create table t(x)")diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.pyindex 31c95006c3f..354bcae0f0c 100644--- a/tests/tools/test_browser_real_profile.py+++ b/tests/tools/test_browser_real_profile.py@@ -53,14 +53,14 @@ class TestSnapshotRealProfile:(root / "Default" / "Cache" / "Cache_Data").mkdir(parents=True)(root / "Code Cache" / "js").mkdir(parents=True)(root / "Crashpad").mkdir()- (root / "Local State").write_text('{"os_crypt": {}}')+ (root / "Local State").write_text('{"os_crypt": {}}', encoding="utf-8")_auth_db((root / "Default" / "Cookies"), "sqlite-cookies")_auth_db((root / "Default" / "Network" / "Cookies"), "sqlite-net-cookies")_auth_db((root / "Default" / "Login Data"), "sqlite-logins")- (root / "Default" / "Preferences").write_text("{}")- (root / "Default" / "Cache" / "Cache_Data" / "big").write_text("x" * 1000)- (root / "Code Cache" / "js" / "blob").write_text("y" * 1000)- (root / "Crashpad" / "dump").write_text("z")+ (root / "Default" / "Preferences").write_text("{}", encoding="utf-8")+ (root / "Default" / "Cache" / "Cache_Data" / "big").write_text("x" * 1000, encoding="utf-8")+ (root / "Code Cache" / "js" / "blob").write_text("y" * 1000, encoding="utf-8")+ (root / "Crashpad" / "dump").write_text("z", encoding="utf-8")# Live-instance leftovers that must never reach the copyos.symlink("dead-target-1", root / "SingletonLock")return root@@ -97,12 +97,12 @@ class TestSnapshotRealProfile:# copy has drifted state that must survive (History not in refresh set)._auth_db((src / "Default" / "Cookies"), "sqlite-cookies-v2")copy_history = home / "browser-profile" / "chrome" / "Default" / "History"- copy_history.write_text("agent-session-history")+ copy_history.write_text("agent-session-history", encoding="utf-8")dst2, err2 = bc.snapshot_real_profile("chrome", src=str(src))assert err2 is None and dst2 == dstassert _auth_db(home / "browser-profile" / "chrome" / "Default" / "Cookies") == "sqlite-cookies-v2"- assert copy_history.read_text() == "agent-session-history"+ assert copy_history.read_text(encoding="utf-8-sig") == "agent-session-history"def test_missing_source_fails_closed(self, tmp_path, monkeypatch):import hermes_cli.browser_connect as bc@@ -256,7 +256,7 @@ class TestRealProfileCdpLaunch:def fake_popen(argv, **kw):captured["chrome_argv"] = argv- (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n")+ (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")return FakeChrome()with patch.object(bt_cloud, "_use_real_profile", return_value=True), \@@ -281,7 +281,7 @@ class TestRealProfileCdpLaunch:# process, and never self-terminates (Chrome is ours, not the daemon's).socket_dir = captured["env"]["AGENT_BROWSER_SOCKET_DIR"]assert socket_dir == str(tmp_path / f"agent-browser-{bt._REAL_PROFILE_SESSION}")- assert (tmp_path / f"agent-browser-{bt._REAL_PROFILE_SESSION}" / f"{bt._REAL_PROFILE_SESSION}.owner_pid").read_text() == str(os.getpid())+ assert (tmp_path / f"agent-browser-{bt._REAL_PROFILE_SESSION}" / f"{bt._REAL_PROFILE_SESSION}.owner_pid").read_text(encoding="utf-8-sig") == str(os.getpid())assert "AGENT_BROWSER_IDLE_TIMEOUT_MS" not in captured["env"]self._reset()@@ -297,7 +297,7 @@ class TestRealProfileCdpLaunch:return Nonedef fake_popen(argv, **kw):- (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n")+ (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")return FakeChrome()with patch.object(bt_cloud, "_use_real_profile", return_value=True), \@@ -326,7 +326,7 @@ class TestRealProfileCdpLaunch:A DevToolsActivePort left by a crash whose port was recycled by ANOTHER CDP server(browser id mismatch) must not be attached to; the normal launch path runs."""self._reset()- (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n")+ (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")version = Mock()version.json.return_value = {"webSocketDebuggerUrl": f"ws://127.0.0.1:41000{live_browser_id}"}with patch.object(bt_cloud, "_use_real_profile", return_value=True), \@@ -348,7 +348,7 @@ class TestRealProfileCdpLaunch:self._reset()def test_cdp_on_data_dir_matches_devtoolsactiveport(self, tmp_path):- (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n")+ (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")assert bt_real_profile._cdp_on_data_dir("http://127.0.0.1:41000", str(tmp_path))assert not bt_real_profile._cdp_on_data_dir("http://127.0.0.1:9999", str(tmp_path))@@ -373,7 +373,7 @@ class TestAgentBrowserCliCapture:import timestub = tmp_path / "agent_browser_daemon_stub.py"- stub.write_text(self.STUB_GRANDCHILD)+ stub.write_text(self.STUB_GRANDCHILD, encoding="utf-8")with patch.object(bt_install, "_find_agent_browser", return_value=str(stub)), \patch.object(bt_session, "_agent_browser_argv", return_value=[sys.executable, str(stub)]), \patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):@@ -397,7 +397,7 @@ class TestAgentBrowserCliCapture:import sysstub = tmp_path / "agent_browser_daemon_stub.py"- stub.write_text(self.STUB_GRANDCHILD)+ stub.write_text(self.STUB_GRANDCHILD, encoding="utf-8")with patch.object(bt_install, "_find_agent_browser", return_value=str(stub)), \patch.object(bt_session, "_agent_browser_argv", return_value=[sys.executable, str(stub)]), \patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):@@ -430,7 +430,7 @@ class TestAgentBrowserCliCapture:import timestub = tmp_path / "agent_browser_sleep_stub.py"- stub.write_text("import time; time.sleep(30)\n")+ stub.write_text("import time; time.sleep(30)\n", encoding="utf-8")with patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):start = time.monotonic()with pytest.raises(subprocess.TimeoutExpired):@@ -455,7 +455,7 @@ class TestAgentBrowserCliCapture:import sysstub = tmp_path / "agent_browser_sleep_stub.py"- stub.write_text("import time; time.sleep(30)\n")+ stub.write_text("import time; time.sleep(30)\n", encoding="utf-8")with patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):with pytest.raises(subprocess.TimeoutExpired):bt_real_profile._capture_agent_browser_cli(@@ -494,10 +494,15 @@ class TestLocalSessionRealProfile:assert info["features"]["real_profile"] is Trueassert info["session_name"].startswith("rp_")- def test_local_session_fails_closed_on_error(self):+ def test_local_session_falls_back_to_a_fresh_browser_on_error(self):+ """A real profile that can't load (Chrome holding its cookies, non-Chromium default) must+ not leave the user with no browser: a fresh one serves and carries the reason."""with patch.object(bt_real_profile, "_real_profile_cdp", return_value=(None, "no chromium")):- with pytest.raises(RuntimeError, match="no chromium"):- bt_session._create_local_session("t1")+ info = bt_session._create_local_session("t1")+ assert info["cdp_url"] is None and info["session_name"].startswith("h_")+ assert "real_profile" not in info["features"]+ assert "no chromium" in info["real_profile_unavailable"]+ assert "without the user's logins" in info["real_profile_unavailable"]def test_local_session_without_consent_is_throwaway(self):with patch.object(bt_real_profile, "_real_profile_cdp", return_value=(None, None)):@@ -564,6 +569,23 @@ class TestBrowserExecLocalArg:assert err == "chrome exited"assert "BU_CDP_URL" not in env+ def test_browser_exec_route_falls_back_and_keeps_the_fallback(self):+ """browser_exec: a failed real profile routes to the normal backend with the reason on the+ sentinel; once a route fell back it skips the real profile, so a task never swaps browsers."""+ import tools.browser_use_cli as bu+ env = self._env()+ rp = Mock(return_value=(None, "chrome holds the Cookies"))+ with patch.object(bu, "_real_profile_consented", return_value=True), \+ patch.object(bu, "_read_browser_cfg", return_value={}), \+ patch("tools.browser_tool_cdp._get_cdp_override_raw", return_value=""), \+ patch("tools.browser_tool_cloud._get_cloud_provider", return_value=None), \+ patch("tools.browser_tool_real_profile._real_profile_cdp", rp), \+ patch.object(bu, "_resolve_backend_cdp", return_value=None) as normal:+ assert bu._route_backend(env, "", "t1", False) is None+ assert env[bu._REAL_PROFILE_FALLBACK_SENTINEL] == "chrome holds the Cookies"+ assert bu._route_backend({}, "", "t1", False, real_profile=False) is None+ assert rp.call_count == 1 and normal.call_count == 2+def test_explicit_bu_env_override_wins(self):import tools.browser_use_cli as buenv = {"BU_CDP_WS": "ws://operator-override"}@@ -691,7 +713,7 @@ class TestSnapshotIsCredentialStore:home = tmp_path / ".hermes"(home / "browser-profile" / "chrome" / "Default").mkdir(parents=True)cookies = home / "browser-profile" / "chrome" / "Default" / "Cookies"- cookies.write_text("secret-cookie-db")+ cookies.write_text("secret-cookie-db", encoding="utf-8")monkeypatch.setenv("HERMES_HOME", str(home))err = fs.get_read_block_error(str(cookies))assert err@@ -702,7 +724,7 @@ class TestSnapshotIsCredentialStore:home.mkdir(parents=True)monkeypatch.setenv("HERMES_HOME", str(home))normal = tmp_path / "notes.txt"- normal.write_text("hello")+ normal.write_text("hello", encoding="utf-8")assert fs.get_read_block_error(str(normal)) is None@@ -722,7 +744,7 @@ class TestReviewBugFixes:_auth_db((root / "Default" / "Cookies"), "default-tracking-only")_auth_db((root / "Profile 6" / "Cookies"), "PROFILE6-SESSION-AUTH")_auth_db((root / "Profile 6" / "Login Data"), "profile6-logins")- (root / "Profile 6" / "Preferences").write_text("{}")+ (root / "Profile 6" / "Preferences").write_text("{}", encoding="utf-8")return rootdef test_last_used_profile_lands_in_copy_default(self, tmp_path, monkeypatch):@@ -741,7 +763,7 @@ class TestReviewBugFixes:import hermes_cli.browser_connect as bcroot = tmp_path / "d"(root / "Default").mkdir(parents=True)- (root / "Local State").write_text('{"profile": {"last_used": "Profile 9"}}') # not present+ (root / "Local State").write_text('{"profile": {"last_used": "Profile 9"}}', encoding="utf-8") # not presentassert bc._last_used_profile(str(root)) == "Default"@@ -802,10 +824,10 @@ class TestReviewRound3:def _multi(self, root):for prof in ("Default", "Profile 6"):(root / prof / "Network").mkdir(parents=True)- (root / "Local State").write_text('{"profile": {"last_used": "Profile 6"}}')+ (root / "Local State").write_text('{"profile": {"last_used": "Profile 6"}}', encoding="utf-8")_auth_db((root / "Default" / "Cookies"), "default-signed-out")_auth_db((root / "Profile 6" / "Cookies"), "PROFILE6-SESSION")- (root / "Profile 6" / "Preferences").write_text("{}")+ (root / "Profile 6" / "Preferences").write_text("{}", encoding="utf-8")return root# ── ② torn first copy must not poison freshness ──@@ -818,7 +840,7 @@ class TestReviewRound3:dst = bc.real_profile_copy_dir("chrome")# Simulate a torn first copy: Default exists but NO done marker.os.makedirs(os.path.join(dst, "Default"))- open(os.path.join(dst, "Default", "Cookies"), "w").write("HALF-COPY-GARBAGE")+ open(os.path.join(dst, "Default", "Cookies"), "w", encoding="utf-8").write("HALF-COPY-GARBAGE") # windows-footgun: ok — write mode, not a read_d, err = bc.snapshot_real_profile("chrome", src=str(src))assert err is None# Rebuilt from the active profile, not treated as populated.@@ -849,7 +871,7 @@ class TestReviewRound3:monkeypatch.setattr(bc, "get_hermes_home", lambda: home)store = home / "browser-profile" / "chrome" / "Default"store.mkdir(parents=True)- (store / "Cookies").write_text("secret")+ (store / "Cookies").write_text("secret", encoding="utf-8")bc.cleanup_real_profile_snapshots()assert not (home / "browser-profile").exists()@@ -992,8 +1014,8 @@ class TestWindowsLockedProfileCopy:def _locked_src(self, root):import sqlite3(root / "Default" / "Network").mkdir(parents=True)- (root / "Local State").write_text(json.dumps({"profile": {"last_used": "Default"}}))- (root / "Default" / "Preferences").write_text("{}")+ (root / "Local State").write_text(json.dumps({"profile": {"last_used": "Default"}}), encoding="utf-8")+ (root / "Default" / "Preferences").write_text("{}", encoding="utf-8")ck = str(root / "Default" / "Cookies")con = sqlite3.connect(ck)con.execute("create table cookies(host_key, name)")@@ -1114,10 +1136,10 @@ class TestWindowsLockedProfileCopy:def test_copy_auth_file_plain_for_non_db(self, tmp_path):import hermes_cli.browser_connect as bc- src = str(tmp_path / "Preferences"); open(src, "w").write('{"k":1}')+ src = str(tmp_path / "Preferences"); open(src, "w", encoding="utf-8").write('{"k":1}')dst = str(tmp_path / "out" / "Preferences")assert bc._copy_auth_file(src, dst) is None- assert open(dst).read() == '{"k":1}'+ assert open(dst, encoding="utf-8-sig").read() == '{"k":1}'def test_fail_closed_when_db_unreadable(self, tmp_path, monkeypatch):"""If even the online-backup can't read the DB, snapshot fails closed@@ -1125,9 +1147,9 @@ class TestWindowsLockedProfileCopy:import hermes_cli.browser_connect as bcroot = tmp_path / "real"(root / "Default").mkdir(parents=True)- (root / "Local State").write_text(json.dumps({"profile": {"last_used": "Default"}}))- (root / "Default" / "Cookies").write_text("not-a-db")- (root / "Default" / "Preferences").write_text("{}")+ (root / "Local State").write_text(json.dumps({"profile": {"last_used": "Default"}}), encoding="utf-8")+ (root / "Default" / "Cookies").write_text("not-a-db", encoding="utf-8")+ (root / "Default" / "Preferences").write_text("{}", encoding="utf-8")home = tmp_path / "hh"monkeypatch.setattr(bc, "get_hermes_home", lambda: home)# Force both sqlite-backup and raw copy to fail for the DB.diff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex 4a665e38c63..1e1ecd9db6e 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -791,6 +791,8 @@ def browser_navigate(url: str, task_id: Optional[str] = None) -> str:features = session_info.get("features") or {}if features.get("real_profile"): # auditability: this ran on the user's real-profile copy-browserresponse["used_real_profile"] = True+ elif is_first_nav and session_info.get("real_profile_unavailable"):+ response["real_profile_unavailable"] = session_info["real_profile_unavailable"]# Only a successful, non-blocked navigation becomes the task owner: failed opens# and blocked redirects must not retarget follow-up clicks to an irrelevant session._last_active_session_key[effective_task_id] = nav_session_keydiff --git a/tools/browser_tool_real_profile.py b/tools/browser_tool_real_profile.pyindex 291f9e7d00f..2ad6a1410c6 100644--- a/tools/browser_tool_real_profile.py+++ b/tools/browser_tool_real_profile.py@@ -150,8 +150,16 @@ _REAL_PROFILE_CHROME_FLAGS = ()+def real_profile_fallback_note(err: str) -> str:+ """Tool-result note when the real profile can't load and a fresh browser serves instead: the+ browser keeps working (a consented user is never left with no browser), and the model is told+ it is signed out so it can say so rather than act as if the user's accounts were there."""+ return (f"{err} Using a fresh browser without the user's logins for this session instead; "+ "tell the user if the task needs their accounts.")++def _real_profile_unsupported_reason(browser) -> Optional[str]:- """Fail-closed message when the default browser can't be used, else None.+ """Why the default browser's profile can't be used (the session falls back to a fresh browser), else None.A pre-release channel lives in a profile dir we don't resolve; normalizing to the stablefamily would drive a DIFFERENT profile/account (wrong-principal bug), so refuse rather than guess.@@ -173,7 +181,8 @@ def _real_profile_snapshot_error(err: str) -> str:from hermes_cli.browser_connect import _PROFILE_LOCKED_PREFIXif err and err.startswith(_PROFILE_LOCKED_PREFIX):return (err[len(_PROFILE_LOCKED_PREFIX):] + " To close it (only after the user approves — it "- "quits their browser and loses unsaved tabs), run: `hermes browser close-profile`, then retry.")+ "quits their browser and loses unsaved tabs), run: `hermes browser close-profile`; the next "+ "browser session then uses the profile.")return f"{_RP}{err}"@@ -257,7 +266,8 @@ def _real_profile_cdp() -> tuple:Snapshot -> launch real binary on the copy -> return its HTTP CDP endpoint. The copy is anon-default dir, so it sidesteps the Chrome >=136 default-profile remote-debugging block andnever contends with the user's running browser. One shared agent-browser session is reused- across calls (cached, re-validated). ``(None, message)`` fail-closed; ``(None, None)`` when consent is off.+ across calls (cached, re-validated). ``(None, message)`` when it can't (callers fall back to a fresh+ browser and report the message); ``(None, None)`` when consent is off."""_bt = _origin()if not _cloud._use_real_profile():diff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.pyindex 8472668cf08..36e4151a3f8 100644--- a/tools/browser_tool_session.py+++ b/tools/browser_tool_session.py@@ -267,16 +267,19 @@ def _session_record(prefix: str, cdp_url: Optional[str], features: dict[str, Anydef _create_local_session(task_id: str, allow_real_profile: bool = True) -> dict[str, str]:"""Local Chromium session; consented real-profile CDP attach when allowed.- Real-profile fails closed on resolver/launch errors (a consented user must never be- silently downgraded to a throwaway). The hybrid private-URL sidecar passes- ``allow_real_profile=False``: the user's cookie jar must not reach an arbitrary- internal host the model chose.+ When the real profile can't be loaded (browser holding its cookies, non-Chromium default,+ launch failure) the session falls back to a fresh browser and carries the reason as+ ``real_profile_unavailable`` so the first navigation tells the model it is signed out. The+ hybrid private-URL sidecar passes ``allow_real_profile=False``: the user's cookie jar must+ not reach an arbitrary internal host the model chose."""+ fallback_note = Noneif allow_real_profile:cdp_url, err = _real_profile._real_profile_cdp()if err:- raise RuntimeError(err)- if cdp_url:+ _bt.logger.warning("real-profile unavailable for task %s, using a fresh browser: %s", task_id, err)+ fallback_note = _real_profile.real_profile_fallback_note(err)+ elif cdp_url:info = _session_record("rp", _cdp._resolve_cdp_override(cdp_url), {"local": True, "real_profile": True})_bt.logger.info("Created real-profile local session %s for task %s", info["session_name"], task_id)return info@@ -284,10 +287,12 @@ def _create_local_session(task_id: str, allow_real_profile: bool = True) -> dict# Browser Use mode + ``browser.engine: lightpanda`` drives a Hermes-spawned# ``lightpanda serve`` (the built-in tools are hidden in that mode).if _bt._is_browser_use_cli_mode() and _lp._using_lightpanda_engine():- return _create_lightpanda_session(task_id)-- info = _session_record("h", None, {"local": True})- _bt.logger.info("Created local browser session %s for task %s", info["session_name"], task_id)+ info = _create_lightpanda_session(task_id)+ else:+ info = _session_record("h", None, {"local": True})+ _bt.logger.info("Created local browser session %s for task %s", info["session_name"], task_id)+ if fallback_note:+ info["real_profile_unavailable"] = fallback_notereturn infodiff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 6cf86d1b8db..c5144fb35a3 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -36,6 +36,8 @@ _PRIVATE_BROWSER_SENTINEL = "_HERMES_BU_PRIVATE_BROWSER"# Internal route provenance: this exec resolved to a browser on the Bot Desktop display and must use# the same human-control lease fence as the built-in browser tools. Popped before launching the CLI._BOT_DESKTOP_BROWSER_SENTINEL = "_HERMES_BU_BOT_DESKTOP_BROWSER"+# Why the consented real profile could not load this call (the route fell back). Popped before launch.+_REAL_PROFILE_FALLBACK_SENTINEL = "_HERMES_BU_REAL_PROFILE_FALLBACK"# Prepended to the model's code for named sessions on SHARED browsers (a /browser connect CDP override): the# harness daemon attaches to the first existing page at startup, so two fresh named daemons can land on the@@ -543,8 +545,8 @@ def _resolve_real_profile_cdp(env: dict, force_local: bool) -> Optional[str]:profile, hermes_cli.browser_connect) when consented. Two ways in: the effective backend is already local(no provider, CDP override, or legacy BU cloud config) → silent upgrade; or ``force_local`` (consent-gated``local`` arg) → the user's browser even under a cloud backend. Operator overrides (BU_CDP_* env,- /browser connect, ``browser.cdp_url``) own the session either way. Fail closed: a launch error is- returned so a consented user is never silently downgraded."""+ /browser connect, ``browser.cdp_url``) own the session either way. A launch error is returned;+ ``_route_backend`` then falls back to the normal backend and reports it, never silently."""if not _real_profile_consented() or _has_cdp_env(env):return Nonetry:@@ -586,7 +588,7 @@ def _attach_vault_supervisor(env: dict, task_id: Optional[str]) -> None:def _route_backend(env: dict, session: str, task_id: Optional[str], local: bool,- force_local_sidecar: bool = False) -> Optional[str]:+ force_local_sidecar: bool = False, real_profile: bool = True) -> Optional[str]:"""Resolve where the harness connects; returns an error string or None. Real-profile consent runsBEFORE provider resolution so a hit short-circuits the cloud path via the BU_CDP_* env contract. Namedsessions compose with the backend: BU_NAME namespaces the harness daemon (IPC socket, log, pid) and on@@ -594,9 +596,13 @@ def _route_backend(env: dict, session: str, task_id: Optional[str], local: bool,``force_local_sidecar`` (a call carrying a private URL) declines the cloud provider for the hybrid localsidecar; unlike ``local`` (the consent-gated real-profile browser) it never touches the user's profile."""- rp_err = _resolve_real_profile_cdp(env, force_local=local)+ # A real profile that can't load falls back to the normal backend: the reason rides out on+ # the env sentinel (popped by browser_exec), and ``real_profile=False`` keeps that route on+ # the fallback browser instead of swapping browsers mid-task once the profile frees up.+ rp_err = _resolve_real_profile_cdp(env, force_local=local) if real_profile else Noneif rp_err:- return rp_err+ logger.warning("browser_exec: real-profile unavailable, using the normal backend: %s", rp_err)+ env[_REAL_PROFILE_FALLBACK_SENTINEL] = rp_err# local=True is only served by the real-profile route; consent off must not pretend.if local and not _has_cdp_env(env) and not _real_profile_consented():return ("local=true was requested but browser.use_real_profile is off. Enable it in config.yaml "@@ -673,6 +679,8 @@ _driven_daemons: set = set()_driven_daemons_lock = threading.Lock()# Route cache key -> whether its last browser_exec ran on the hybrid local sidecar._exec_route_is_sidecar: dict[str, bool] = {}+# Route cache key -> the note from its real-profile fallback; that route stays on the fallback browser.+_real_profile_fallback: dict[str, str] = {}def stop_harness_daemons() -> None:@@ -690,6 +698,20 @@ def stop_harness_daemons() -> None:_run_cli_killing_process_group([*cmd, "--reload"], "", {**env, "BU_NAME": name}, 15)+def _route_exec(env: dict, session: str, task_id: Optional[str], local: bool, local_sidecar: bool,+ route_key: str) -> tuple[Optional[str], dict]:+ """``_route_backend`` for one browser_exec call, plus the result fields when the real profile+ fell back this call. A route that fell back once stays on the fallback browser."""+ route_err = _route_backend(env, session, task_id, local, force_local_sidecar=local_sidecar,+ real_profile=route_key not in _real_profile_fallback)+ reason = env.pop(_REAL_PROFILE_FALLBACK_SENTINEL, None)+ if not reason:+ return route_err, {}+ from tools.browser_tool_real_profile import real_profile_fallback_note+ note = _real_profile_fallback[route_key] = real_profile_fallback_note(reason)+ return route_err, {"real_profile_unavailable": note}++def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUT_S,task_id: Optional[str] = None, local: bool = False):"""Run Python code through the browser-use CLI, and return its output"""@@ -719,7 +741,7 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUTreturn tool_error(f"Invalid session name {session!r}: use 1-64 letters, digits, ""dashes, or underscores (e.g. 'r7k2').")env["BU_NAME"] = session- route_err = _route_backend(env, session, task_id, bool(local), force_local_sidecar=local_sidecar)+ route_err, rp_extra = _route_exec(env, session, task_id, bool(local), local_sidecar, route_key)if route_err:return tool_error(route_err)if local_sidecar:@@ -782,6 +804,7 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUTresult["workspace"] = workspaceif session:result["session"] = session+ result.update(rp_extra)stderr = redact_sensitive_text((proc.stderr or "").strip(), force=True)if len(stderr) > _STDERR_CAP_CHARS:stderr = stderr[:_STDERR_CAP_CHARS] + "\n… (stderr truncated)"diff --git a/website/docs/user-guide/features/browser.md b/website/docs/user-guide/features/browser.mdindex f2867da33a3..ceb479de101 100644--- a/website/docs/user-guide/features/browser.md+++ b/website/docs/user-guide/features/browser.md@@ -210,51 +210,47 @@ browser:real_profile_pin: "Profile 2" # directory name under the browser's user-data dir```-A pin naming a profile directory that doesn't exist fails closed with a-fixable message — it never silently falls back to the last-used profile.+A pin naming a profile directory that doesn't exist never silently falls back to+the last-used profile: the agent gets a fresh browser without your logins and a+message naming the bad pin.When you turn the toggle back off, Hermes deletes the snapshot store(`~/.hermes/browser-profile/`) on the next browser use, so the copiedcredentials don't linger after you revoke consent.-:::note A running browser can block the login/autofill databases-On Windows a running Chrome/Edge/Brave holds its cookie and login databases with-an exclusive (deny-all) lock, so Hermes cannot copy them while the browser is-open — it fails fast with a "fully quit the browser and retry" message rather-than hang or produce a signed-out session. Real-profile browsing on Windows-therefore requires the browser **fully quit**, including any background/tray-instance (Chrome's "continue running background apps when closed" keeps a-`chrome.exe` alive after you close the window).--On macOS and Linux the profile is not file-locked, but each authentication-database is snapshotted through SQLite's online backup with a five-second-budget, and a running Chrome typically holds `Login Data`, `Login Data For-Account` and `Web Data` with a hot write lock that never yields within that-budget (`Cookies` usually snapshots fine). When that happens Hermes stops the-launch and names the databases it could not read — for example "chrome is-running and holds the profile's Login Data, Login Data For Account, Web Data-with a write lock" — so in practice **quit the browser before launching a-real-profile session on macOS/Linux too**. You can reopen it once the session is-up (the snapshot is a separate directory), but the auth files are re-synced on-every fresh session launch, so a browser left running then hits the same lock.-Hermes preserves committed-WAL data through SQLite rather than falling back to a raw file copy, which could-silently lose recent logins. Unreadable or corrupt databases also stop the-launch, with the SQLite error named in the message.+:::note When your profile can't be copied, the browser still works+Real-profile browsing never takes the browser away. If Hermes can't copy your+profile, the agent gets a fresh browser **without your logins** for that session,+and its first browser result says why (`real_profile_unavailable`), so it can tell+you instead of acting as if it were signed in. That happens when:++- **Windows:** a running Chrome/Edge/Brave holds its cookie database with an+ exclusive (deny-all) lock. To browse as you, **fully quit** the browser first,+ including any background/tray instance (Chrome's "continue running background+ apps when closed" keeps a `chrome.exe` alive after you close the window).+- **Your default browser isn't a supported Chromium** (Firefox, a Beta/Dev/Canary+ channel), or the pinned profile doesn't exist.+- **The cookie database is unreadable or corrupt**: the message names it and the+ SQLite error.++On macOS and Linux a running Chrome holds `Login Data`, `Login Data For Account`+and `Web Data` (saved passwords and autofill) with a write lock, but `Cookies`+still copies, and cookies are what keep you signed in to sites. Hermes copies the+cookies and skips the locked password/autofill files, so you can keep your browser+open. Each database is copied through SQLite's online backup (never a raw file+copy, which could lose recent logins).Set `browser.real_profile_autoclose: true` to let Hermes **offer to close the-browser for you** when it's holding the profile lock (the Windows case). Even with this on, Hermes never-closes it automatically — when the profile is locked it always stops and the-agent asks you first; only on your approval does it run `hermes browser-close-profile` (terminates the browser process tree bound to that profile,-losing unsaved tabs), then retries. If the profile is still locked after that-(e.g. a background/tray instance relaunched), Hermes stays blocked and tells you-to fully quit the browser — it won't loop or kill again on its own.+browser for you** when it's holding the profile lock (the Windows case). Even with+this on, Hermes never closes it automatically: the agent asks you first, and only on+your approval runs `hermes browser close-profile` (terminates the browser process+tree bound to that profile, losing unsaved tabs). A new browser session then picks+up your profile.:::- **Supported browsers:** Chrome, Edge, Brave, Brave Origin, Chromium (whichever is your OS- default). A non-Chromium default (e.g. Firefox) fails closed with a clear- message rather than guessing.+ default). A non-Chromium default (e.g. Firefox) gets a fresh browser and a clear+ message rather than a guess at which profile to use.- **Works on any backend.** On a local backend it's automatic once the toggleis on. Under a **cloud** browser backend, the agent can still open areal-profile local session on demand via the `browser_exec` tool's `local`@@ -292,8 +288,9 @@ Three things to set up before scheduling one:is what carries a run after your own session has expired.**Windows prerequisite:** the browser has to be fully quit before a snapshot can-be taken at all, so a scheduled tick needs it closed beforehand — Hermes never-closes it without asking you first (see the note above).+be taken, so a scheduled tick needs it closed beforehand; otherwise the tick runs+on a fresh, signed-out browser. Hermes never closes it without asking you first+(see the note above).The bundled `product-price-monitor` skill is a worked example of the recurringshape — a JSON watch contract written during setup, then one scheduled tick that