Skip to content

The agent that grows with you

fix(browser): reuse the last real-profile snapshot when the live profile is locked

Tekniume3cb7995f8f6
diff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.py
index a58329fca92..aec30d6a94b 100644
--- a/hermes_cli/browser_connect.py
+++ b/hermes_cli/browser_connect.py
@@ -710,11 +710,39 @@ def _copy_profile_tree(src: str, dst: str, source_profile: str) -> None:
len(multi.args[0]) if multi.args else 0, src, source_profile)
+def _drop_singleton_leftovers(dst: str) -> None:
+ """Never carry live-instance leftovers into the copy (they make Chrome think it's open)."""
+ for leftover in ("SingletonLock", "SingletonSocket", "SingletonCookie"):
+ with contextlib.suppress(OSError):
+ os.unlink(os.path.join(dst, leftover))
+
+
+def _snapshot_source(marker: str) -> str | None:
+ """Source profile name a completed snapshot was taken from (the done marker's content)."""
+ try:
+ with open(marker, encoding="utf-8") as fh:
+ return fh.read().strip() or None
+ except OSError:
+ return None
+
+
+def _reuse_snapshot(browser: str, dst: str) -> tuple[str, None]:
+ """Serve the last completed snapshot as-is when the live profile is locked. Its logins are as
+ fresh as that copy; the next launch with the browser closed re-syncs them. Refusing instead
+ would drop the session to a signed-out browser although a usable copy is on disk."""
+ _drop_singleton_leftovers(dst)
+ logger.info("real-profile: %s holds its profile lock; reusing the last snapshot in %s "
+ "(logins as of that copy)", browser, dst)
+ return dst, None
+
+
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; returns ``(dst, err)``.
Copies ``Local State`` plus the active profile's auth files into the copy's ``Default``. The
completion marker is written only after full success, so a torn first copy (disk full, Ctrl+C)
- never looks "already populated" — it is redone from scratch."""
+ never looks "already populated" — it is redone from scratch. A locked live profile (Windows,
+ browser running) reuses a completed snapshot of the same source profile without re-syncing;
+ only a missing or other-profile snapshot fails with the locked error."""
src = src or real_profile_data_dir(browser)
if not src or not os.path.isdir(src):
return None, (
@@ -724,15 +752,17 @@ def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | N
if resolve_err or not source_profile:
return None, resolve_err
dst = real_profile_copy_dir(browser)
+ marker = os.path.join(dst, _SNAPSHOT_DONE_MARKER)
+ # Only a copy that previously COMPLETED counts as populated; a half-written tree is
+ # rebuilt — otherwise a torn first copy poisons freshness forever.
+ populated = os.path.isfile(marker)
# 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, where a running browser only locks the
# password/autofill DBs, which ``_mirror_profile_auth`` skips.
if _profile_is_locked(src, source_profile):
+ if populated and _snapshot_source(marker) == source_profile:
+ return _reuse_snapshot(browser, dst)
return None, _locked_profile_error(browser)
- marker = os.path.join(dst, _SNAPSHOT_DONE_MARKER)
- # Only a copy that previously COMPLETED counts as populated; a half-written tree is
- # rebuilt — otherwise a torn first copy poisons freshness forever.
- populated = os.path.isfile(marker)
try:
os.makedirs(dst, exist_ok=True)
# Secure the snapshot dir AND its browser-profile parent on EVERY launch so a failed
@@ -746,10 +776,7 @@ def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | N
failed_dbs = _mirror_profile_auth(src, dst, source_profile)
if failed_dbs: # no session cookies: a "real profile" launch would be signed out
return None, _unavailable_auth_dbs_error(browser, failed_dbs)
- # Never carry live-instance leftovers into the copy.
- for leftover in ("SingletonLock", "SingletonSocket", "SingletonCookie"):
- with contextlib.suppress(OSError):
- os.unlink(os.path.join(dst, leftover))
+ _drop_singleton_leftovers(dst)
# Mark complete only after everything above succeeded.
try:
with open(marker, "w", encoding="utf-8") as fh:
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index d322935c326..2bb375bff35 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -453,7 +453,8 @@ DEFAULT_CONFIG = {
# 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 (the session runs on a fresh browser). When on, the agent ASKS first; on approval it
+ # copied (the last snapshot is reused; with none yet, 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)
# 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).
diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.py
index 29066c38138..59703605d11 100644
--- a/tests/tools/test_browser_real_profile.py
+++ b/tests/tools/test_browser_real_profile.py
@@ -946,6 +946,42 @@ class TestReviewRound3:
assert err and err.startswith(bc._PROFILE_LOCKED_PREFIX)
assert killed["n"] == 0 # snapshot must NOT invoke the killer itself
+ def test_locked_profile_reuses_completed_snapshot(self, tmp_path, monkeypatch):
+ """A completed snapshot of the same source profile is served as-is when the live
+ profile is locked — not refused into a signed-out fallback. No re-sync runs."""
+ 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)
+ first, err = bc.snapshot_real_profile("chrome", src=str(src))
+ assert err is None
+ _auth_db((src / "Profile 6" / "Cookies"), "NEWER-SESSION")
+ open(os.path.join(first, "SingletonLock"), "w", encoding="utf-8").close() # windows-footgun: ok — write mode, not a read
+ monkeypatch.setattr(bc, "_profile_is_locked", lambda s, p: True)
+ monkeypatch.setattr(bc, "_mirror_profile_auth",
+ lambda *a: pytest.fail("must not touch the locked live profile"))
+ dst, err = bc.snapshot_real_profile("chrome", src=str(src))
+ assert (dst, err) == (first, None)
+ assert _auth_db(home / "browser-profile" / "chrome" / "Default" / "Cookies") == "PROFILE6-SESSION"
+ assert not os.path.exists(os.path.join(dst, "SingletonLock"))
+
+ def test_locked_profile_refuses_snapshot_of_another_profile(self, tmp_path, monkeypatch):
+ """A completed snapshot taken from a DIFFERENT source profile is another account's
+ logins: a locked live profile still fails rather than serving it."""
+ 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)
+ first, err = bc.snapshot_real_profile("chrome", src=str(src))
+ assert err is None
+ with open(os.path.join(first, bc._SNAPSHOT_DONE_MARKER), "w", encoding="utf-8") as fh:
+ fh.write("Default")
+ monkeypatch.setattr(bc, "_profile_is_locked", lambda s, p: True)
+ monkeypatch.setattr(bc, "_real_profile_autoclose", lambda: False)
+ dst, err = bc.snapshot_real_profile("chrome", src=str(src))
+ assert dst is None
+ assert err and err.startswith(bc._PROFILE_LOCKED_PREFIX)
+
def test_processes_holding_profile_identity_binding(self, tmp_path, monkeypatch):
"""The process matcher requires BOTH a browser binary AND this exact
user-data-dir in the cmdline — never a same-name process on another dir."""
diff --git a/website/docs/user-guide/features/browser.md b/website/docs/user-guide/features/browser.md
index ceb479de101..ea41675bdd1 100644
--- a/website/docs/user-guide/features/browser.md
+++ b/website/docs/user-guide/features/browser.md
@@ -224,10 +224,13 @@ 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).
+- **Windows, first use only:** a running Chrome/Edge/Brave holds its cookie
+ database with an exclusive (deny-all) lock, so the first copy needs 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). After one successful copy, a later launch with the browser open
+ reuses that copy instead: your logins are as of the last copy, and they refresh
+ the next time Hermes starts its browser while yours is closed.
- **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
@@ -287,9 +290,9 @@ Three things to set up before scheduling one:
the [credential vault's](./credential-vault.md#headless-sessions) job, and it
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, 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
+**Windows prerequisite:** the browser has to be fully quit for the first snapshot.
+After that, a tick that runs while it is open reuses the last snapshot (logins as of
+that copy); with no snapshot yet, 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 recurring