Skip to content

The agent that grows with you

fix(browser): real-profile review round 2 — last_used profile, sidecar isolation, macOS26 parser, perms, lightpanda

Teknium7fb52c14ba1f
diff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.py
index 5f310d15117..599b15a4596 100644
--- a/hermes_cli/browser_connect.py
+++ b/hermes_cli/browser_connect.py
@@ -357,8 +357,14 @@ def _launchservices_https_handler(dump: str) -> str | None:
low = entry.lower()
if not re.search(r'lshandlerurlscheme\s*=\s*"?https"?\s*;', low):
continue
- # The nested LSHandlerPreferredVersions block carries "-" placeholders
- # under the same key names; the real bundle id is the first non-"-".
+ # Strip the nested LSHandlerPreferredVersions block first: on macOS 26
+ # it carries a VERSION NUMBER (e.g. LSHandlerRoleAll = "7559.97";), not
+ # the "-" placeholder older releases used. Left in, the role regex below
+ # would match that version before the real bundle id sitting at the
+ # entry's own level and return "7559.97" — which maps to no browser, so
+ # detection fails on a machine whose default IS Chrome (PR #95620 review).
+ low = re.sub(r"lshandlerpreferredversions\s*=\s*\{[^}]*\}\s*;", "", low)
+ # The real bundle id is the first non-"-" role value at this level.
for role in re.findall(r'lshandlerrole(?:all|viewer)\s*=\s*"?([a-z0-9.\-]+)"?\s*;', low):
if role != "-":
return role
@@ -485,19 +491,22 @@ _SNAPSHOT_IGNORES = (
# Small, auth-bearing files re-synced from the live profile on EVERY consented
# launch (the full tree is only copied when the snapshot doesn't exist yet).
-# Paths are relative to the user-data-dir; <profile> expands per profile dir.
-_AUTH_REFRESH_FILES = (
- "Local State",
- "<profile>/Cookies",
- "<profile>/Cookies-journal",
- "<profile>/Network/Cookies",
- "<profile>/Network/Cookies-journal",
- "<profile>/Login Data",
- "<profile>/Login Data-journal",
- "<profile>/Login Data For Account",
- "<profile>/Web Data",
- "<profile>/Web Data-journal",
- "<profile>/Preferences",
+# Paths here are RELATIVE TO A PROFILE DIR (Default, "Profile 6", …) — the
+# caller resolves which source profile is active and mirrors these into the
+# copy's ``Default`` so the launched Chromium (which opens ``Default``) lands
+# on the user's real signed-in session.
+_AUTH_REFRESH_PROFILE_FILES = (
+ "Cookies",
+ "Cookies-journal",
+ "Network/Cookies",
+ "Network/Cookies-journal",
+ "Login Data",
+ "Login Data-journal",
+ "Login Data For Account",
+ "Login Data For Account-journal",
+ "Web Data",
+ "Web Data-journal",
+ "Preferences",
)
def real_profile_copy_dir(browser: str) -> str:
@@ -505,8 +514,31 @@ def real_profile_copy_dir(browser: str) -> str:
return str(get_hermes_home() / "browser-profile" / browser)
+def _last_used_profile(src: str) -> str:
+ """Return the profile dir Chrome last used (``Local State`` → profile.last_used).
+
+ Chromium opens ``Default`` inside a user-data-dir unless told otherwise, but
+ the user's signed-in session usually lives in whichever profile they
+ actually browse (``Profile 6`` etc.). We read that here and mirror its auth
+ into the copy's ``Default`` so the launched browser is signed in. Falls back
+ to ``Default`` when Local State is missing/unreadable or names a profile
+ dir that doesn't exist.
+ """
+ import json
+
+ try:
+ with open(os.path.join(src, "Local State"), encoding="utf-8", errors="replace") as fh:
+ state = json.load(fh)
+ last = ((state.get("profile") or {}).get("last_used")) or "Default"
+ except (OSError, ValueError, AttributeError):
+ last = "Default"
+ if not isinstance(last, str) or not os.path.isdir(os.path.join(src, last)):
+ return "Default"
+ return last
+
+
def _secure_snapshot_root(path: str) -> None:
- """Lock down the snapshot dir through Hermes' canonical secret-store policy.
+ """Lock down a snapshot dir through Hermes' canonical secret-store policy.
The snapshot holds copies of the user's Cookies / Login Data, so it is a
credential store and must get the same owner-only permissions (and
@@ -522,17 +554,25 @@ def _secure_snapshot_root(path: str) -> None:
logger.debug("could not secure real-profile snapshot dir %s: %s", path, e)
-def _profile_subdirs(src: str) -> list[str]:
- """Names of per-profile dirs (Default, Profile 1, ...) inside a data dir."""
- out = []
- try:
- for name in os.listdir(src):
- if name == "Default" or name.startswith("Profile "):
- if os.path.isdir(os.path.join(src, name)):
- out.append(name)
- except OSError:
- pass
- return out or ["Default"]
+def _mirror_profile_auth(src: str, dst: str, source_profile: str) -> None:
+ """Copy ``source_profile``'s auth files into the copy's ``Default`` slot.
+
+ agent-browser launches ``Default`` in the copied user-data-dir; mirroring
+ the active source profile's cookies/logins/prefs there is what makes the
+ session actually signed in (the LinkedIn/Gmail "logged out" bug when the
+ real session lives in a non-Default profile).
+ """
+ dst_default = os.path.join(dst, "Default")
+ for rel in _AUTH_REFRESH_PROFILE_FILES:
+ s = os.path.join(src, source_profile, rel)
+ if not os.path.isfile(s):
+ continue
+ d = os.path.join(dst_default, rel)
+ try:
+ os.makedirs(os.path.dirname(d), exist_ok=True)
+ shutil.copy2(s, d)
+ except OSError as e:
+ logger.debug("real-profile auth mirror: skipped %s: %s", rel, e)
def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | None, str | None]:
@@ -553,11 +593,19 @@ def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | N
"Launch that browser at least once, or turn browser.use_real_profile off."
)
dst = real_profile_copy_dir(browser)
+ source_profile = _last_used_profile(src)
fresh = not os.path.isdir(os.path.join(dst, "Default"))
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.
+ parent = os.path.dirname(dst)
+ if parent:
+ _secure_snapshot_root(parent)
+ _secure_snapshot_root(dst)
if fresh:
- os.makedirs(dst, exist_ok=True)
- _secure_snapshot_root(dst)
try:
shutil.copytree(
src,
@@ -574,22 +622,18 @@ def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | N
len(multi.args[0]) if multi.args else 0, src,
)
else:
- profiles = _profile_subdirs(src)
- for rel in _AUTH_REFRESH_FILES:
- rels = (
- [rel.replace("<profile>", p) for p in profiles]
- if "<profile>" in rel else [rel]
- )
- for r in rels:
- s = os.path.join(src, r)
- if not os.path.isfile(s):
- continue
- d = os.path.join(dst, r)
- try:
- os.makedirs(os.path.dirname(d), exist_ok=True)
- shutil.copy2(s, d)
- except OSError as e:
- logger.debug("real-profile refresh: skipped %s: %s", r, e)
+ # 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)
# Never carry live-instance leftovers into the copy.
for leftover in ("SingletonLock", "SingletonSocket", "SingletonCookie"):
try:
diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.py
index d36ae21b1a4..a3c706815e3 100644
--- a/tests/tools/test_browser_real_profile.py
+++ b/tests/tools/test_browser_real_profile.py
@@ -508,3 +508,132 @@ class TestSnapshotIsCredentialStore:
dst, err = bc.snapshot_real_profile("chrome", src=str(tmp_path / "real"))
assert err is None
assert called.get("p") == dst # secured through the canonical owner
+
+
+class TestReviewBugFixes:
+ """Regressions for the five PR #95620 review findings."""
+
+ # ── Bug 2: launch the profile the user actually browses (last_used) ──
+ def _multi_profile(self, root):
+ """Build a data-dir where the SIGNED-IN session lives in 'Profile 6'."""
+ for prof in ("Default", "Profile 6"):
+ (root / prof / "Network").mkdir(parents=True)
+ (root / "Local State").write_text(
+ '{"profile": {"last_used": "Profile 6"}}'
+ )
+ # Default is signed OUT (tracking cookies only); Profile 6 has the session.
+ (root / "Default" / "Cookies").write_text("default-tracking-only")
+ (root / "Profile 6" / "Cookies").write_text("PROFILE6-SESSION-AUTH")
+ (root / "Profile 6" / "Login Data").write_text("profile6-logins")
+ (root / "Profile 6" / "Preferences").write_text("{}")
+ return root
+
+ def test_last_used_profile_lands_in_copy_default(self, tmp_path, monkeypatch):
+ import hermes_cli.browser_connect as bc
+ src = self._multi_profile(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
+ # The copy's Default must carry PROFILE 6's session, not Default's.
+ got = (home / "browser-profile" / "chrome" / "Default" / "Cookies").read_text()
+ assert got == "PROFILE6-SESSION-AUTH"
+ assert (home / "browser-profile" / "chrome" / "Default" / "Login Data").read_text() == "profile6-logins"
+
+ def test_last_used_falls_back_to_default(self, tmp_path):
+ import hermes_cli.browser_connect as bc
+ root = tmp_path / "d"
+ (root / "Default").mkdir(parents=True)
+ (root / "Local State").write_text('{"profile": {"last_used": "Profile 9"}}') # not present
+ assert bc._last_used_profile(str(root)) == "Default"
+
+ def test_last_used_reads_local_state(self, tmp_path):
+ import hermes_cli.browser_connect as bc
+ root = tmp_path / "d"
+ (root / "Profile 6").mkdir(parents=True)
+ (root / "Local State").write_text('{"profile": {"last_used": "Profile 6"}}')
+ assert bc._last_used_profile(str(root)) == "Profile 6"
+
+ def test_refresh_remirrors_last_used(self, tmp_path, monkeypatch):
+ import hermes_cli.browser_connect as bc
+ src = self._multi_profile(tmp_path / "real")
+ home = tmp_path / "hh"
+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)
+ bc.snapshot_real_profile("chrome", src=str(src)) # fresh
+ (src / "Profile 6" / "Cookies").write_text("PROFILE6-REFRESHED")
+ dst, err = bc.snapshot_real_profile("chrome", src=str(src)) # refresh
+ assert err is None
+ assert (home / "browser-profile" / "chrome" / "Default" / "Cookies").read_text() == "PROFILE6-REFRESHED"
+
+ # ── Bug 3: private-URL sidecar must NOT carry the real profile ──
+ def test_sidecar_never_uses_real_profile(self):
+ import tools.browser_tool as bt
+ # Even with consent resolving a real-profile CDP, the sidecar path
+ # (allow_real_profile=False) must return a throwaway session.
+ with patch.object(bt, "_real_profile_cdp",
+ return_value=("http://127.0.0.1:9251", None)):
+ info = bt._create_local_session("t::local", allow_real_profile=False)
+ assert info["cdp_url"] is None
+ assert "real_profile" not in info["features"]
+ assert info["session_name"].startswith("h_")
+
+ def test_sidecar_ignores_real_profile_error(self):
+ """A real-profile resolve failure must not break private-URL routing."""
+ import tools.browser_tool as bt
+ with patch.object(bt, "_real_profile_cdp",
+ return_value=(None, "non-chromium default")):
+ info = bt._create_local_session("t::local", allow_real_profile=False)
+ assert info["cdp_url"] is None # no raise, throwaway session
+
+ def test_bare_local_still_uses_real_profile(self):
+ import tools.browser_tool as bt
+ with patch.object(bt, "_real_profile_cdp",
+ return_value=("http://127.0.0.1:9251", None)), \
+ patch.object(bt, "_resolve_cdp_override", side_effect=lambda u: u):
+ info = bt._create_local_session("t1") # allow_real_profile defaults True
+ assert info["features"].get("real_profile") is True
+
+ # ── Bug 1: macOS 26 LSHandlers parser ──
+ def test_macos26_parser_returns_bundle_not_version(self):
+ import hermes_cli.browser_connect as bc
+ dump = (
+ "( { LSHandlerPreferredVersions = { LSHandlerRoleAll = \"7559.97\"; }; "
+ "LSHandlerRoleAll = \"com.google.chrome\"; LSHandlerURLScheme = https; } )"
+ )
+ assert bc._launchservices_https_handler(dump) == "com.google.chrome"
+
+ def test_macos26_detect_returns_chrome(self):
+ import hermes_cli.browser_connect as bc
+ dump = (
+ "( { LSHandlerPreferredVersions = { LSHandlerRoleAll = \"7559.97\"; }; "
+ "LSHandlerRoleAll = \"com.google.chrome\"; LSHandlerURLScheme = https; } )"
+ )
+ with patch.object(bc.subprocess, "run", return_value=Mock(stdout=dump)):
+ assert bc._detect_default_darwin() == "chrome"
+
+ # ── Bug 4: permissions applied on refresh, not only fresh ──
+ def test_permissions_secured_on_refresh(self, tmp_path, monkeypatch):
+ import hermes_cli.browser_connect as bc
+ src = self._multi_profile(tmp_path / "real")
+ home = tmp_path / "hh"
+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)
+ bc.snapshot_real_profile("chrome", src=str(src)) # fresh
+ secured = []
+ with patch("hermes_cli.config._secure_dir", side_effect=secured.append):
+ bc.snapshot_real_profile("chrome", src=str(src)) # refresh
+ # Refresh still secures BOTH the snapshot dir and its browser-profile parent.
+ assert str(home / "browser-profile" / "chrome") in secured
+ assert str(home / "browser-profile") in secured
+
+ # ── Bug 5: lightpanda engine + consent fails with an actionable message ──
+ def test_lightpanda_engine_fails_actionably(self):
+ 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=True), \
+ patch("hermes_cli.browser_connect.detect_default_chromium") as det:
+ cdp, err = bt._real_profile_cdp()
+ assert cdp is None
+ assert err and "lightpanda" in err.lower() and "browser.engine" in err.lower()
+ det.assert_not_called() # guard fires before detection
+ bt._real_profile_cdp_cache.clear()
diff --git a/tools/browser_tool.py b/tools/browser_tool.py
index 0d4bc556166..c0ba3157b98 100644
--- a/tools/browser_tool.py
+++ b/tools/browser_tool.py
@@ -1554,6 +1554,19 @@ def _real_profile_cdp() -> tuple:
if not _use_real_profile():
return None, None
+ # Lightpanda cannot load a Chromium profile — agent-browser rejects
+ # ``--profile`` outright under that engine ("Profiles are not supported
+ # with Lightpanda"). Detect it here, BEFORE default-browser detection, so
+ # even a host with no Chromium default reports the actionable conflict (the
+ # engine setting) rather than a generic launch failure.
+ if _using_lightpanda_engine():
+ return None, (
+ "browser.use_real_profile is on, but browser.engine is set to "
+ "'lightpanda', which cannot load a real Chromium profile. Set "
+ "browser.engine to 'auto' or 'chrome' to use real-profile browsing, "
+ "or turn the toggle off."
+ )
+
from hermes_cli.browser_connect import (
UNSUPPORTED_CHANNEL,
detect_default_chromium,
@@ -2577,7 +2590,7 @@ BROWSER_TOOL_SCHEMAS = [
# Utility Functions
# ============================================================================
-def _create_local_session(task_id: str) -> Dict[str, str]:
+def _create_local_session(task_id: str, allow_real_profile: bool = True) -> Dict[str, str]:
import uuid
# Real-profile consent: instead of an agent-browser-managed throwaway
@@ -2585,20 +2598,30 @@ def _create_local_session(task_id: str) -> Dict[str, str]:
# browser running on a hermes-owned SNAPSHOT of their real profile —
# live logins/cookies included. Fail closed on resolver/launch errors:
# a consented user must never be silently downgraded to a throwaway.
- cdp_url, err = _real_profile_cdp()
- if err:
- raise RuntimeError(err)
- if cdp_url:
- session_name = f"rp_{uuid.uuid4().hex[:10]}"
- logger.info(
- "Created real-profile local session %s for task %s", session_name, task_id
- )
- return {
- "session_name": session_name,
- "bb_session_id": None,
- "cdp_url": _resolve_cdp_override(cdp_url),
- "features": {"local": True, "real_profile": True},
- }
+ #
+ # ``allow_real_profile=False`` is passed by the hybrid private-URL sidecar
+ # (``::local`` key): that path exists to keep a LAN/loopback host OFF the
+ # cloud backend, and routing the user's full authenticated cookie jar to an
+ # arbitrary internal host the model chose to visit is a strictly larger
+ # exposure than the routing rule was protecting against — and one the user
+ # never consented to for that URL. The sidecar always gets a throwaway
+ # profile. (Also keeps a real-profile resolve failure from breaking
+ # private-URL routing, which has nothing to do with the real profile.)
+ if allow_real_profile:
+ cdp_url, err = _real_profile_cdp()
+ if err:
+ raise RuntimeError(err)
+ if cdp_url:
+ session_name = f"rp_{uuid.uuid4().hex[:10]}"
+ logger.info(
+ "Created real-profile local session %s for task %s", session_name, task_id
+ )
+ return {
+ "session_name": session_name,
+ "bb_session_id": None,
+ "cdp_url": _resolve_cdp_override(cdp_url),
+ "features": {"local": True, "real_profile": True},
+ }
session_name = f"h_{uuid.uuid4().hex[:10]}"
logger.info("Created local browser session %s for task %s",
@@ -2689,7 +2712,10 @@ def _get_session_info(task_id: Optional[str] = None) -> Dict[str, Any]:
if cdp_override and not force_local:
session_info = _create_cdp_session(task_id, cdp_override)
elif force_local:
- session_info = _create_local_session(task_id)
+ # Hybrid private-URL sidecar: NEVER the real profile (see
+ # _create_local_session — presenting real cookies to an arbitrary LAN
+ # host the model routed here is unconsented exposure).
+ session_info = _create_local_session(task_id, allow_real_profile=False)
else:
provider = _get_cloud_provider()
if provider is None: