The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): snapshot real profile while Chrome is running
cmaldonado80460f9bacda88
diff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.pyindex 585cedbbf84..91330c32ec6 100644--- a/hermes_cli/browser_connect.py+++ b/hermes_cli/browser_connect.py@@ -431,15 +431,21 @@ _SQLITE_AUTH_DBS = frozenset({"Cookies", "Login Data", "Login Data For Account",_AUTH_BACKUP_DEADLINE_S = 5.0_AUTH_DB_LOCKED = ("SQLite backup made no progress within five seconds — ""a running browser holds a write lock on it")+# Session cookies keep the copy signed in. Login Data / Web Data are saved passwords and+# autofill, which a running Chrome on macOS/Linux holds with a write lock even when Cookies+# copy in milliseconds; failing the snapshot over them forced users to quit Chrome before+# every browser session. They get a short best-effort budget and are skipped when locked.+_SESSION_AUTH_DBS = frozenset({"Cookies"})+_OPTIONAL_AUTH_BACKUP_DEADLINE_S = 0.5-def _copy_auth_file(src_file: str, dst_file: str) -> str | None:+def _copy_auth_file(src_file: str, dst_file: str, *, deadline_s: float | None = None) -> str | None:"""Copy auth state; returns None on success, else WHY the file could not be snapshotted.A DB that cannot be backed up consistently within the deadline is refused, never raw-copied."""os.makedirs(os.path.dirname(dst_file), exist_ok=True)try:if os.path.basename(src_file) in _SQLITE_AUTH_DBS:- deadline = time.monotonic() + _AUTH_BACKUP_DEADLINE_S+ deadline = time.monotonic() + (_AUTH_BACKUP_DEADLINE_S if deadline_s is None else deadline_s)last_remaining: list[int | None] = [None]def check_deadline(_status: int, remaining: int, total: int) -> None:@@ -472,23 +478,29 @@ def _copy_auth_file(src_file: str, dst_file: str) -> str | None:def _mirror_profile_auth(src: str, dst: str, source_profile: str) -> dict[str, str]:"""Mirror ``source_profile``'s auth files into the copy's ``Default`` (agent-browser opens it);- returns ``{relative name: reason}`` for the DB auth files that could NOT be copied ({} = clean)."""+ returns ``{relative name: reason}`` for the session-cookie DBs that could NOT be copied ({} =+ the signed-in state is usable). Locked password/autofill DBs are logged and skipped."""failed: dict[str, str] = {}for rel in _AUTH_REFRESH_PROFILE_FILES:s = os.path.join(src, source_profile, rel)if not os.path.isfile(s):continue- reason = _copy_auth_file(s, os.path.join(dst, "Default", rel))- if reason and os.path.basename(rel) in _SQLITE_AUTH_DBS:+ base = os.path.basename(rel)+ session_db = base in _SESSION_AUTH_DBS+ reason = _copy_auth_file(s, os.path.join(dst, "Default", rel),+ deadline_s=None if session_db else _OPTIONAL_AUTH_BACKUP_DEADLINE_S)+ if not reason or base not in _SQLITE_AUTH_DBS:+ continue+ if session_db:failed[rel] = reason+ else:+ logger.info("real-profile snapshot: skipped %s (%s); session cookies still copied", rel, reason)return faileddef _unavailable_auth_dbs_error(browser: str, failed: dict[str, str]) -> str:- """Fail-closed message naming WHICH auth databases could not be snapshotted and WHY. On- macOS/Linux a running browser typically lets Cookies back up but holds Login Data / Login Data- For Account / Web Data with a write lock, so the message must not read as "close the browser"- when the real cause is an unreadable file (and vice versa)."""+ """Message naming WHICH session-cookie databases could not be snapshotted and WHY, so it never+ reads as "close the browser" when the real cause is an unreadable file (and vice versa)."""names = ", ".join(failed)if all(reason == _AUTH_DB_LOCKED for reason in failed.values()):return (f"{browser} is running and holds the profile's {names} with a write lock, so their "@@ -712,8 +724,8 @@ def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | Nreturn None, resolve_errdst = real_profile_copy_dir(browser)# Fast lock probe BEFORE any copy: a blocking file op on a Windows-locked cookie DB can- # hang the launch for minutes. Never trips on POSIX; there a running browser surfaces later as- # auth DB backups that miss their deadline (``_unavailable_auth_dbs_error``).+ # hang the launch for minutes. Never trips on POSIX, where a running browser only locks the+ # password/autofill DBs, which ``_mirror_profile_auth`` skips.if _profile_is_locked(src, source_profile):return None, _locked_profile_error(browser)marker = os.path.join(dst, _SNAPSHOT_DONE_MARKER)@@ -731,7 +743,7 @@ def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | N_copy_profile_tree(src, dst, source_profile)# Both paths: lock-aware auth DB copy into Default — also the per-launch re-sync.failed_dbs = _mirror_profile_auth(src, dst, source_profile)- if failed_dbs: # even online-backup failed: never launch a silently signed-out session+ if failed_dbs: # no session cookies: a "real profile" launch would be signed outreturn None, _unavailable_auth_dbs_error(browser, failed_dbs)# Never carry live-instance leftovers into the copy.for leftover in ("SingletonLock", "SingletonSocket", "SingletonCookie"):diff --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 b7aa74a9429..1e763abfc2a 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@@ -1,9 +1,9 @@-"""Real-profile snapshot error names the auth databases it could not read and why.+"""Real-profile snapshot while the browser runs, and the error when cookies can't be read.A running Chrome on macOS/Linux lets ``Cookies`` back up but holds ``Login Data`` /-``Login Data For Account`` / ``Web Data`` with a write lock, so their SQLite online backup misses-its deadline. The launch must fail closed with the database NAMES and the lock reason, never a-bare "3 database(s) unavailable" count (#111647).+``Login Data For Account`` / ``Web Data`` with a write lock. Cookies alone keep the copy signed+in, so those three are skipped and the snapshot succeeds. When the cookie DB itself can't be+read, the error names it and the reason, never a bare count (#111647)."""import jsonimport os@@ -28,44 +28,41 @@ def _fake_profile(root):con.close()-def test_mirror_profile_auth_reports_locked_dbs_by_name(tmp_path, monkeypatch):- """Exclusive writers on the three login/autofill DBs → each is reported with the lock reason;- the unlocked Cookies DB still lands in the snapshot (no all-or-nothing regression)."""- root, dst = tmp_path / "real", tmp_path / "copy"+def test_snapshot_succeeds_while_the_browser_locks_password_and_autofill_dbs(tmp_path, monkeypatch):+ """Exclusive writers on the three login/autofill DBs (what a running Chrome holds) no longer+ fail the snapshot: the cookie DB lands, the locked ones are skipped quickly."""+ root = tmp_path / "real"_fake_profile(root)- monkeypatch.setattr(bc, "_AUTH_BACKUP_DEADLINE_S", 0.3) # keep the test fast; 5 s in prod+ monkeypatch.setattr(bc, "get_hermes_home", lambda: tmp_path / "hh")holders = []for name in _LOCKED:h = sqlite3.connect(root / "Default" / name)h.execute("begin exclusive")holders.append(h)try:- failed = bc._mirror_profile_auth(str(root), str(dst), "Default")+ dst, err = bc.snapshot_real_profile("chrome", src=str(root))finally:for h in holders:h.rollback()h.close()- assert failed == {name: bc._AUTH_DB_LOCKED for name in _LOCKED}- assert os.path.isfile(dst / "Default" / "Cookies")- # Locks released → clean re-sync.- assert bc._mirror_profile_auth(str(root), str(dst), "Default") == {}+ assert err is None and dst+ assert os.path.isfile(os.path.join(dst, "Default", "Cookies"))@pytest.mark.parametrize("reason, expect", [- (None, ("is running and holds the profile's Login Data, Login Data For Account, Web Data "- "with a write lock", "Fully quit chrome")),- ("file is not a database", ("Login Data: file is not a database", "Close chrome")),+ (None, ("is running and holds the profile's Cookies with a write lock", "Fully quit chrome")),+ ("file is not a database", ("Cookies: file is not a database", "Close chrome")),])def test_snapshot_error_names_databases_and_reason(tmp_path, monkeypatch, reason, expect):- """The user-facing snapshot error carries the failed DB names plus the reason: the lock- wording when every failure is the backup deadline, the SQLite error otherwise."""+ """An unreadable cookie DB fails the snapshot with the DB name plus the reason: the lock+ wording when the failure is the backup deadline, the SQLite error otherwise."""root = tmp_path / "real"_fake_profile(root)monkeypatch.setattr(bc, "get_hermes_home", lambda: tmp_path / "hh")locked_reason = reason or bc._AUTH_DB_LOCKED- def fake_copy(src, dst_file):- return locked_reason if os.path.basename(src) in _LOCKED else None+ def fake_copy(src, dst_file, **_kw):+ return locked_reason if os.path.basename(src) == "Cookies" else Nonemonkeypatch.setattr(bc, "_copy_auth_file", fake_copy)dst, err = bc.snapshot_real_profile("chrome", src=str(root))@@ -73,4 +70,4 @@ def test_snapshot_error_names_databases_and_reason(tmp_path, monkeypatch, reasonfor fragment in expect:assert fragment in err, errassert "database(s) unavailable" not in err- assert "Cookies" not in err # only the databases that actually failed are named+ assert "Login Data" not in err # only the databases that actually failed are nameddiff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.pyindex a586c7f5291..31c95006c3f 100644--- a/tests/tools/test_browser_real_profile.py+++ b/tests/tools/test_browser_real_profile.py@@ -1132,7 +1132,7 @@ class TestWindowsLockedProfileCopy:monkeypatch.setattr(bc, "get_hermes_home", lambda: home)# Force both sqlite-backup and raw copy to fail for the DB.monkeypatch.setattr(bc, "_copy_auth_file",- lambda s, d: "file is not a database" if os.path.basename(s) in bc._SQLITE_AUTH_DBS else None)+ lambda s, d, **_kw: "file is not a database" if os.path.basename(s) in bc._SQLITE_AUTH_DBS else None)dst, err = bc.snapshot_real_profile("chrome", src=str(root))assert dst is Noneassert err