Skip to content

The agent that grows with you

fix(browser): Windows real-profile fails fast when the browser is running

Teknium931bf613b12e
diff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.py
index 9caec901fcb..f0f1e78dead 100644
--- a/hermes_cli/browser_connect.py
+++ b/hermes_cli/browser_connect.py
@@ -630,6 +630,38 @@ def _mirror_profile_auth(src: str, dst: str, source_profile: str) -> int:
_SNAPSHOT_DONE_MARKER = ".hermes-snapshot-complete"
+def _profile_cookie_db(src: str, source_profile: str) -> str | None:
+ """Path to the active profile's cookie DB (modern Network/ first)."""
+ for rel in (os.path.join("Network", "Cookies"), "Cookies"):
+ cand = os.path.join(src, source_profile, rel)
+ if os.path.isfile(cand):
+ return cand
+ return None
+
+
+def _profile_is_locked(src: str, source_profile: str) -> bool:
+ """True when the active profile's cookie DB can't be opened (browser running).
+
+ A running browser holds Cookies with a deny-all share mode on Windows
+ (proven live: even CreateFile with all share flags fails), so a plain open
+ raises PermissionError. This is a FAST probe — one open attempt, no copy —
+ used to fail closed BEFORE the heavy snapshot so a locked profile can never
+ hang the launch on a blocking file op. POSIX has no mandatory locking, so
+ the open succeeds and this returns False (copy proceeds normally).
+ """
+ db = _profile_cookie_db(src, source_profile)
+ if not db:
+ return False # nothing to lock; let the copy path handle "no cookies"
+ try:
+ with open(db, "rb"):
+ return False
+ except PermissionError:
+ return True
+ except OSError:
+ # Other errors (transient) — don't declare locked; let the copy try.
+ return False
+
+
def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | None, str | None]:
"""Snapshot ``browser``'s real ACTIVE profile into the hermes copy dir.
@@ -657,6 +689,17 @@ 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)
+ # Fast lock probe BEFORE any copy: a running browser holds the cookie DB
+ # deny-all (Windows), and a blocking file op on it can hang the launch for
+ # minutes. Bail immediately with an actionable message instead. On POSIX
+ # this never trips (no mandatory locking) so copy-while-running still works.
+ if _profile_is_locked(src, source_profile):
+ return None, (
+ f"{browser} is running and has its profile locked, so its login "
+ "data can't be copied. Fully quit the browser (including any "
+ "background/tray instance) and retry, or turn "
+ "browser.use_real_profile off."
+ )
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
diff --git a/tests/hermes_cli/test_real_profile_windows_live.py b/tests/hermes_cli/test_real_profile_windows_live.py
index fa89ba66f44..675e1f06eb3 100644
--- a/tests/hermes_cli/test_real_profile_windows_live.py
+++ b/tests/hermes_cli/test_real_profile_windows_live.py
@@ -53,19 +53,15 @@ def _raw_copy_raises_while_locked(path: str) -> bool:
return True
[email protected](reason="behavior under active revision — diagnostic drives the real fix", strict=False)
def test_locked_profile_fails_closed_not_silent(tmp_path):
- """The user-facing contract on Windows: when a running Chrome share-locks
- the cookie DB, ``snapshot_real_profile`` must FAIL CLOSED with an actionable
- 'close the browser' message — never a silent signed-out / torn copy.
-
- Live-proven fact (this runner): Chrome's share lock is strong enough that
- even a read-only SQLite open is refused by the OS, so copy-while-running is
- impossible on Windows. The honest behavior is to say so, not to launch a
- broken session. (Real-profile browsing on Windows therefore requires Chrome
- closed; Linux/macOS are unaffected. The live-drive-the-real-profile path is
- tracked separately in #95669.)
+ """Windows contract: a running Chrome holds the cookie DB deny-all (proven
+ live — even CreateFile with all share flags fails), so copy-while-running
+ is impossible. ``snapshot_real_profile`` must FAIL FAST with an actionable
+ 'fully quit the browser' message — never hang, never a silent signed-out
+ copy. (Real-profile browsing on Windows therefore requires the browser
+ fully closed incl. background/tray; the live-drive path is #95669.)
"""
+ import time as _t
chrome = _find_chrome()
if not chrome:
pytest.skip("Chrome not installed on this runner")
@@ -99,27 +95,27 @@ def test_locked_profile_fails_closed_not_silent(tmp_path):
time.sleep(1)
assert cookies is not None, "Chrome never created a Cookies DB"
- # Precondition: the DB is genuinely share-locked (raw copy fails). If a
- # future Chrome/runner stops locking, this test isn't exercising the
- # case — skip rather than assert a vacuous result.
if not _raw_copy_raises_while_locked(str(cookies)):
pytest.skip("Chrome did not share-lock the cookie DB on this runner")
- # Point the resolver at our locked user-data-dir and run the REAL
- # user-facing snapshot. It must fail closed with the actionable message.
import hermes_cli.browser_connect as bc_mod
orig = bc_mod.real_profile_data_dir
bc_mod.real_profile_data_dir = lambda browser, system=None: str(user_data)
try:
+ # Must return FAST (fail-fast lock probe), not hang. Assert both the
+ # contract and that it took well under the old 24-min hang.
+ t0 = _t.time()
dst, err = bc.snapshot_real_profile("chrome", src=str(user_data))
+ elapsed = _t.time() - t0
finally:
bc_mod.real_profile_data_dir = orig
assert dst is None, "must not return a (silently broken) copy while locked"
assert err is not None
low = err.lower()
- assert "login data" in low or "locked" in low, f"unclear error: {err}"
- assert "close" in low, f"error must tell the user to close the browser: {err}"
+ assert "locked" in low or "running" in low, f"unclear error: {err}"
+ assert "quit" in low or "close" in low, f"error must tell the user to quit: {err}"
+ assert elapsed < 30, f"snapshot hung on a locked profile ({elapsed:.0f}s) — must fail fast"
finally:
proc.terminate()
try:
diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.py
index a670be257fb..0bed49336db 100644
--- a/tests/tools/test_browser_real_profile.py
+++ b/tests/tools/test_browser_real_profile.py
@@ -709,6 +709,53 @@ class TestReviewRound3:
monkeypatch.setattr(bc, "get_hermes_home", lambda: tmp_path / "hh")
bc.cleanup_real_profile_snapshots() # no raise
+ # ── Windows lock probe (unit; the live share-lock is proven in the
+ # windows-latest E2E — here we cover the probe's contract portably) ──
+ def test_lock_probe_false_when_readable(self, tmp_path):
+ import hermes_cli.browser_connect as bc
+ (tmp_path / "Default" / "Network").mkdir(parents=True)
+ (tmp_path / "Default" / "Network" / "Cookies").write_bytes(b"db")
+ assert bc._profile_is_locked(str(tmp_path), "Default") is False
+
+ def test_lock_probe_false_when_no_cookie_db(self, tmp_path):
+ import hermes_cli.browser_connect as bc
+ (tmp_path / "Default").mkdir(parents=True)
+ assert bc._profile_is_locked(str(tmp_path), "Default") is False
+
+ def test_lock_probe_true_on_permissionerror(self, tmp_path, monkeypatch):
+ import hermes_cli.browser_connect as bc
+ (tmp_path / "Default").mkdir(parents=True)
+ (tmp_path / "Default" / "Cookies").write_bytes(b"db")
+ import builtins
+ real_open = builtins.open
+
+ def deny(path, *a, **k):
+ if str(path).endswith("Cookies"):
+ raise PermissionError("locked")
+ return real_open(path, *a, **k)
+
+ monkeypatch.setattr(builtins, "open", deny)
+ assert bc._profile_is_locked(str(tmp_path), "Default") is True
+
+ def test_snapshot_fails_fast_when_locked(self, tmp_path, monkeypatch):
+ """snapshot_real_profile bails with the actionable message when the
+ active profile's cookie DB is locked — never proceeds to a heavy copy."""
+ 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)
+ monkeypatch.setattr(bc, "_profile_is_locked", lambda s, p: True)
+ called = {"copytree": 0}
+ import shutil as _sh
+ orig_ct = _sh.copytree
+ monkeypatch.setattr(_sh, "copytree",
+ lambda *a, **k: (called.__setitem__("copytree", called["copytree"] + 1), orig_ct(*a, **k))[1])
+ dst, err = bc.snapshot_real_profile("chrome", src=str(src))
+ assert dst is None
+ assert err and ("locked" in err.lower() or "running" in err.lower())
+ assert "quit" in err.lower()
+ assert called["copytree"] == 0 # bailed before any copy
+
def test_consent_off_triggers_cleanup(self, tmp_path, monkeypatch):
import tools.browser_tool as bt
called = {"n": 0}
diff --git a/website/docs/user-guide/features/browser.md b/website/docs/user-guide/features/browser.md
index 0788c55dab6..67721d1b235 100644
--- a/website/docs/user-guide/features/browser.md
+++ b/website/docs/user-guide/features/browser.md
@@ -186,6 +186,17 @@ 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.
+:::note Windows: the browser must be fully closed
+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). macOS and Linux can copy the
+profile while the browser is running.
+:::
+
- **Supported browsers:** Chrome, Edge, Brave, Chromium (whichever is your OS
default). A non-Chromium default (e.g. Firefox) fails closed with a clear
message rather than guessing.