The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): real-profile review round 3 — overlay-ordering race, torn-copy marker, consent cleanup, active-only copy
Teknium6e854595e2d9
diff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.pyindex 599b15a4596..2d17019e5e7 100644--- a/hermes_cli/browser_connect.py+++ b/hermes_cli/browser_connect.py@@ -575,14 +575,25 @@ def _mirror_profile_auth(src: str, dst: str, source_profile: str) -> None:logger.debug("real-profile auth mirror: skipped %s: %s", rel, e)+_SNAPSHOT_DONE_MARKER = ".hermes-snapshot-complete"++def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | None, str | None]:- """Snapshot ``browser``'s real profile into the hermes copy dir.+ """Snapshot ``browser``'s real ACTIVE profile into the hermes copy dir.++ Copies only what the launched browser needs: the user-data-dir's+ ``Local State`` plus the auth-bearing files of the profile the user+ actually browses (``Local State → profile.last_used``, e.g. ``Profile 6``),+ mirrored into the copy's ``Default`` — which is what agent-browser opens.+ We deliberately do NOT copy every profile dir: non-active profiles are+ unused here and would just be stale credential copies sitting on disk.++ A ``.hermes-snapshot-complete`` marker is written only after a copy fully+ succeeds; a torn/interrupted first copy (disk full, Ctrl+C) therefore never+ looks "already populated" on the next run — it is redone from scratch.- Full copy (minus caches) when the copy doesn't exist; otherwise only the- auth-bearing files (cookies, login data, preferences) are re-synced so- fresh logins from the user's own browsing show up in the agent session.- Locked-file copy errors are tolerated best-effort: SQLite journals make a- mid-write copy readable, and a stale cookie jar beats a failed launch.+ Auth files are re-synced on every call so fresh logins from the user's own+ browsing show up. Locked-file copy errors are tolerated best-effort.Returns ``(copy_dir, None)`` on success, ``(None, error)`` on failure."""@@ -594,22 +605,41 @@ def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | N)dst = real_profile_copy_dir(browser)source_profile = _last_used_profile(src)- fresh = not os.path.isdir(os.path.join(dst, "Default"))+ marker = os.path.join(dst, _SNAPSHOT_DONE_MARKER)+ # Only a copy that previously COMPLETED counts as populated. A half-written+ # tree (no marker) is treated as absent and rebuilt — otherwise a torn first+ # copy poisons freshness forever and only ever gets auth overlays.+ populated = os.path.isfile(marker)try:os.makedirs(dst, exist_ok=True)# Secure the snapshot dir AND its browser-profile parent on EVERY- # launch (not only first-create): a failed first attempt or an- # older-build dir must still converge to owner-only perms, and the- # parent enumerates every browser we hold cookies for.+ # launch: a failed first attempt or an older-build dir must still+ # converge to owner-only perms; the parent enumerates every browser we+ # hold cookies for.parent = os.path.dirname(dst)if parent:_secure_snapshot_root(parent)_secure_snapshot_root(dst)- if fresh:++ # Base user-data-dir file the browser reads at startup. Cheap; always+ # re-synced so last_used etc. stay current.+ ls_src = os.path.join(src, "Local State")+ if os.path.isfile(ls_src):+ try:+ shutil.copy2(ls_src, os.path.join(dst, "Local State"))+ except OSError as e:+ logger.debug("real-profile snapshot: skipped Local State: %s", e)++ if not populated:+ # Fresh (or torn-and-rebuilding): drop any partial Default and copy+ # the ACTIVE profile's full dir (minus caches) into the copy's+ # Default. Only the active profile is copied — never the others.+ dst_default = os.path.join(dst, "Default")try:+ shutil.rmtree(dst_default, ignore_errors=True)shutil.copytree(- src,- dst,+ os.path.join(src, source_profile),+ dst_default,dirs_exist_ok=True,symlinks=False,ignore=shutil.ignore_patterns(*_SNAPSHOT_IGNORES),@@ -618,33 +648,46 @@ def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | Nexcept shutil.Error as multi:# Per-file failures (browser mid-write) are non-fatal.logger.info(- "real-profile snapshot: %d file(s) skipped while copying %s",- len(multi.args[0]) if multi.args else 0, src,+ "real-profile snapshot: %d file(s) skipped copying %s/%s",+ len(multi.args[0]) if multi.args else 0, src, source_profile,)else:- # Refresh: re-sync Local State so last_used stays current.- ls_src = os.path.join(src, "Local State")- if os.path.isfile(ls_src):- try:- shutil.copy2(ls_src, os.path.join(dst, "Local State"))- except OSError as e:- logger.debug("real-profile refresh: skipped Local State: %s", e)- # Both paths: mirror the ACTIVE source profile's auth into the copy's- # Default so the launched browser (which opens Default) is signed in.- # On a fresh full copy this overwrites Default's auth with the- # last_used profile's; on refresh it re-syncs fresh logins.- _mirror_profile_auth(src, dst, source_profile)+ # Already populated: re-sync just the active profile's auth files+ # into Default so fresh logins show up (no full recopy).+ _mirror_profile_auth(src, dst, source_profile)+# Never carry live-instance leftovers into the copy.for leftover in ("SingletonLock", "SingletonSocket", "SingletonCookie"):try:os.unlink(os.path.join(dst, leftover))except OSError:pass+ # Mark complete only after everything above succeeded.+ try:+ with open(marker, "w", encoding="utf-8") as fh:+ fh.write(source_profile)+ except OSError as e:+ logger.debug("real-profile snapshot: could not write done marker: %s", e)except OSError as e:return None, f"could not snapshot the '{browser}' profile into {dst}: {e}"return dst, None+def cleanup_real_profile_snapshots() -> None:+ """Delete the whole real-profile snapshot store (all copied credentials).++ Called when consent is OFF: the copied Cookies / Login Data must not+ outlive the toggle. Best-effort and idempotent — missing dir is fine.+ """+ root = str(get_hermes_home() / "browser-profile")+ try:+ if os.path.isdir(root):+ shutil.rmtree(root, ignore_errors=True)+ logger.info("real-profile: removed snapshot store %s (consent off)", root)+ except OSError as e:+ logger.debug("real-profile cleanup failed for %s: %s", root, e)++def get_chrome_debug_candidates(system: str) -> list[str]:candidates: list[str] = []seen: set[str] = set()diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex eee52189bc3..526a2f7f3df 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -578,16 +578,19 @@ DEFAULT_CONFIG = {# Consent to browse with the user's REAL logins for local browsing.# When true, local browsing (the Browser Use CLI, or the built-in# browser tools) runs on a Hermes-managed SNAPSHOT of the user's- # default-Chromium profile — cookies, logins and preferences copied in,- # re-synced from the real profile on each launch — driven by Hermes'- # packaged Chromium. The snapshot is a non-default dir, so it sidesteps- # Chrome 136+'s block on debugging the default profile and never- # contends with the user's running browser. Only Chromium-family- # default browsers are supported (Chrome, Edge, Brave, Chromium); a- # non-Chromium default (e.g. Firefox) fails closed with a clear- # message. Default false. Also gates the browser_exec ``local``- # argument, which forces a real-profile local session even under a- # cloud browser backend. Toggle in the desktop Settings → Browser section.+ # ACTIVE default-Chromium profile (Local State -> profile.last_used) —+ # its cookies, logins and preferences copied in and re-synced when a+ # fresh session launches — driven by Hermes' packaged Chromium. Only+ # the active profile is copied. The snapshot is a non-default dir, so it+ # sidesteps Chrome 136+'s block on debugging the default profile and+ # never contends with the user's running browser. Turning this back off+ # deletes the snapshot store (~/.hermes/browser-profile/) so copied+ # credentials don't outlive consent. Only Chromium-family default+ # browsers are supported (Chrome, Edge, Brave, Chromium); a non-Chromium+ # default (e.g. Firefox) fails closed with a clear message. Default+ # false. Also gates the browser_exec ``local`` argument, which forces a+ # real-profile local session even under a cloud browser backend. Toggle+ # in the desktop Settings → Browser section."use_real_profile": False,"allow_unsafe_evaluate": False, # Legacy override: when true, browser_console(expression=...) bypasses the restrict_evaluate denylist entirely"restrict_evaluate": False, # Opt-in denylist blocking sensitive JS primitives (cookies/storage/clipboard/network/form values) in browser_console(expression=...)diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.pyindex a3c706815e3..a570afaed6e 100644--- a/tests/tools/test_browser_real_profile.py+++ b/tests/tools/test_browser_real_profile.py@@ -637,3 +637,125 @@ class TestReviewBugFixes:assert err and "lightpanda" in err.lower() and "browser.engine" in err.lower()det.assert_not_called() # guard fires before detectionbt._real_profile_cdp_cache.clear()+++class TestReviewRound3:+ """Regressions for the round-3 review findings (Adolanium + kshitij)."""++ 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 / "Default" / "Cookies").write_text("default-signed-out")+ (root / "Profile 6" / "Cookies").write_text("PROFILE6-SESSION")+ (root / "Profile 6" / "Preferences").write_text("{}")+ return root++ # ── ② torn first copy must not poison freshness ──+ def test_done_marker_gates_fresh(self, tmp_path, monkeypatch):+ import hermes_cli.browser_connect as bc+ src = self._multi(tmp_path / "real")+ home = tmp_path / "hh"+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)+ dst, err = bc.snapshot_real_profile("chrome", src=str(src))+ assert err is None+ assert os.path.isfile(os.path.join(dst, bc._SNAPSHOT_DONE_MARKER))++ def test_torn_copy_is_redone_not_overlaid(self, tmp_path, monkeypatch):+ import hermes_cli.browser_connect as bc+ src = self._multi(tmp_path / "real")+ home = tmp_path / "hh"+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)+ 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")+ d, err = bc.snapshot_real_profile("chrome", src=str(src))+ assert err is None+ # Rebuilt from the active profile, not treated as populated.+ assert (home / "browser-profile" / "chrome" / "Default" / "Cookies").read_text() == "PROFILE6-SESSION"+ assert os.path.isfile(os.path.join(dst, bc._SNAPSHOT_DONE_MARKER))++ # ── ④ only the active profile is copied, never the others ──+ def test_only_active_profile_copied(self, tmp_path, monkeypatch):+ import hermes_cli.browser_connect as bc+ src = self._multi(tmp_path / "real")+ # Add a non-active profile with its own cookies — must NOT be copied.+ (src / "Profile 3").mkdir()+ (src / "Profile 3" / "Cookies").write_text("PROFILE3-SHOULD-NOT-COPY")+ home = tmp_path / "hh"+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)+ dst, err = bc.snapshot_real_profile("chrome", src=str(src))+ assert err is None+ copy = home / "browser-profile" / "chrome"+ # Active profile (Profile 6) landed in Default; other profiles absent.+ assert (copy / "Default" / "Cookies").read_text() == "PROFILE6-SESSION"+ assert not (copy / "Profile 3").exists()+ assert not (copy / "Profile 6").exists()++ # ── ③ consent-off deletes the snapshot store ──+ def test_cleanup_removes_store(self, tmp_path, monkeypatch):+ import hermes_cli.browser_connect as bc+ home = tmp_path / "hh"+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)+ store = home / "browser-profile" / "chrome" / "Default"+ store.mkdir(parents=True)+ (store / "Cookies").write_text("secret")+ bc.cleanup_real_profile_snapshots()+ assert not (home / "browser-profile").exists()++ def test_cleanup_idempotent_when_absent(self, tmp_path, monkeypatch):+ import hermes_cli.browser_connect as bc+ monkeypatch.setattr(bc, "get_hermes_home", lambda: tmp_path / "hh")+ bc.cleanup_real_profile_snapshots() # no raise++ def test_consent_off_triggers_cleanup(self, tmp_path, monkeypatch):+ import tools.browser_tool as bt+ called = {"n": 0}+ with patch.object(bt, "_use_real_profile", return_value=False), \+ patch("hermes_cli.browser_connect.cleanup_real_profile_snapshots",+ side_effect=lambda: called.__setitem__("n", called["n"] + 1)):+ cdp, err = bt._real_profile_cdp()+ assert cdp is None and err is None+ assert called["n"] == 1++ # ── ① overlay must not run before the reuse check (live-browser safety) ──+ def test_reuse_skips_snapshot_overlay(self, tmp_path):+ """When a live session on our copy dir is reused, snapshot_real_profile+ must NOT be called — otherwise it rewrites cookie DBs under a live+ browser."""+ import tools.browser_tool as bt+ bt._real_profile_cdp_cache.clear()+ with patch.object(bt, "_use_real_profile", return_value=True), \+ patch.object(bt, "_using_lightpanda_engine", return_value=False), \+ patch("hermes_cli.browser_connect.detect_default_chromium", return_value="chrome"), \+ patch("hermes_cli.browser_connect.real_profile_copy_dir", return_value=str(tmp_path)), \+ patch.object(bt, "_agent_browser_get_cdp", return_value="http://127.0.0.1:9251"), \+ patch.object(bt, "_cdp_http_ready", return_value=True), \+ patch.object(bt, "_cdp_on_data_dir", return_value=True), \+ patch("hermes_cli.browser_connect.snapshot_real_profile") as snap:+ cdp, err = bt._real_profile_cdp()+ assert cdp == "http://127.0.0.1:9251" and err is None+ snap.assert_not_called() # ← the fix: no overlay while a live browser owns the dir+ bt._real_profile_cdp_cache.clear()++ def test_relaunch_path_does_snapshot(self, tmp_path):+ """When there's no reusable session, the overlay DOES run (relaunch)."""+ import tools.browser_tool as bt+ bt._real_profile_cdp_cache.clear()+ proc = Mock(returncode=0, stdout="", stderr="")+ with patch.object(bt, "_use_real_profile", return_value=True), \+ patch.object(bt, "_using_lightpanda_engine", return_value=False), \+ patch("hermes_cli.browser_connect.detect_default_chromium", return_value="chrome"), \+ patch("hermes_cli.browser_connect.real_profile_copy_dir", return_value=str(tmp_path)), \+ patch("hermes_cli.browser_connect.snapshot_real_profile",+ return_value=(str(tmp_path), None)) as snap, \+ patch.object(bt, "_agent_browser_get_cdp",+ side_effect=[None, "http://127.0.0.1:9251"]), \+ patch.object(bt, "_find_agent_browser", return_value="/usr/bin/agent-browser"), \+ patch.object(bt.subprocess, "run", return_value=proc), \+ patch.object(bt, "_is_headed_mode", return_value=False):+ cdp, err = bt._real_profile_cdp()+ assert err is None+ snap.assert_called_once()+ bt._real_profile_cdp_cache.clear()diff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex c0ba3157b98..d1b7ab6cf02 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -1552,6 +1552,17 @@ def _real_profile_cdp() -> tuple:``(None, None)`` when consent is off."""if not _use_real_profile():+ # Consent is off. If a snapshot store from a previous consented run is+ # still on disk, it holds copies of the user's cookies/logins — delete+ # it so revoking consent actually removes the credential copies. Cheap+ # (one isdir check) and idempotent.+ try:+ from hermes_cli.browser_connect import cleanup_real_profile_snapshots++ cleanup_real_profile_snapshots()+ except Exception as e:+ logger.debug("real-profile cleanup-on-consent-off failed: %s", e)+ _real_profile_cdp_cache.pop("cdp", None)return None, None# Lightpanda cannot load a Chromium profile — agent-browser rejects@@ -1570,6 +1581,7 @@ def _real_profile_cdp() -> tuple:from hermes_cli.browser_connect import (UNSUPPORTED_CHANNEL,detect_default_chromium,+ real_profile_copy_dir,snapshot_real_profile,)@@ -1600,22 +1612,32 @@ def _real_profile_cdp() -> tuple:"real-profile browsing does not support. Set your default to a ""stable Chrome / Edge / Brave / Chromium, or turn the toggle off.")- copy_dir, err = snapshot_real_profile(browser)- if err or not copy_dir:- return None, f"browser.use_real_profile is on, but {err}"- # A shared session may already be up from a previous hermes process,- # but ONLY reuse it when it is actually driving our copy dir — a stale- # session from an earlier/failed launch can be attached to a throwaway- # temp profile (agent-browser falls back to one when a launch races),- # which would serve zero real cookies. Verify, else close and relaunch.+ # Reuse BEFORE writing anything. A shared copy-browser may already be up+ # from a previous hermes process; if it is driving OUR copy dir, hand it+ # back untouched. CRITICAL: the snapshot overlay (which truncates and+ # rewrites Cookies / Login Data) must NOT run while that browser holds+ # the user-data-dir open — doing so corrupts the live databases (torn+ # reads, locked transactions, phantom logouts). So resolve the copy dir+ # as a PATH only (no copy), probe reuse, and return early on a hit. The+ # snapshot/overlay happens solely on the relaunch path below, when no+ # live browser owns the dir.+ copy_dir = real_profile_copy_dir(browser)existing = _agent_browser_get_cdp(_REAL_PROFILE_SESSION)if existing and _cdp_http_ready(existing) and _cdp_on_data_dir(existing, copy_dir):_real_profile_cdp_cache["cdp"] = existingreturn existing, Noneif existing:+ # Stale/wrong-dir session (throwaway-temp fallback, or an old copy):+ # close it so nothing holds the dir open before we overlay + relaunch._agent_browser_close_session(_REAL_PROFILE_SESSION)+ # No live browser owns the dir now — safe to (re)snapshot + overlay.+ snap_dir, err = snapshot_real_profile(browser)+ if err or not snap_dir:+ return None, f"browser.use_real_profile is on, but {err}"+ copy_dir = snap_dir+# Launch agent-browser's packaged Chromium on the profile COPY. This is# the same launch path Hermes' built-in local browsing already uses,# just pointed at the copied user-data-dir — no bespoke Chrome launch.diff --git a/website/docs/user-guide/features/browser.md b/website/docs/user-guide/features/browser.mdindex 1403518ac35..0788c55dab6 100644--- a/website/docs/user-guide/features/browser.md+++ b/website/docs/user-guide/features/browser.md@@ -170,15 +170,21 @@ browser:use_real_profile: true```-When enabled, Hermes copies your default browser's profile — cookies, saved+When enabled, Hermes copies your default browser's **active** profile — the one+you actually browse (`Local State → profile.last_used`), with its cookies, savedlogins, and preferences — into a managed snapshot under`~/.hermes/browser-profile/<browser>/`, then drives that snapshot with itspackaged Chromium. Your live browser profile is **never opened directly**: thesnapshot is a separate directory, so it doesn't fight your running browser forthe profile lock and it sidesteps Chrome 136+'s block on remote-debugging thedefault profile directory. The auth files (cookies/logins/preferences) are-re-synced from your real profile on every launch, so logins you do in your own-browser show up in the agent's session.+re-synced from your real profile whenever a fresh session is launched, so logins+you do in your own browser show up in the agent's session. Only the active+profile is copied — other Chrome profiles are never snapshotted.++When you turn the toggle back off, Hermes deletes the snapshot store+(`~/.hermes/browser-profile/`) on the next browser use, so the copied+credentials don't linger after you revoke consent.- **Supported browsers:** Chrome, Edge, Brave, Chromium (whichever is your OSdefault). A non-Chromium default (e.g. Firefox) fails closed with a clear