The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): launcher state lives in a private per-profile dir
Teknium1bf137e99479
diff --git a/tests/tools/test_browser_launcher.py b/tests/tools/test_browser_launcher.pyindex 5644285101c..90d6175857b 100644--- a/tests/tools/test_browser_launcher.py+++ b/tests/tools/test_browser_launcher.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport jsonimport osimport signal+import statimport subprocessimport sysimport textwrap@@ -54,15 +55,20 @@ def fake_chromium(tmp_path, monkeypatch):script.chmod(0o755)monkeypatch.setattr(launcher, "_resolve_executable", lambda: str(script))monkeypatch.setattr(launcher, "needs_chromium_sandbox_bypass", lambda: False)- records = tmp_path / "records"- records.mkdir()- monkeypatch.setattr(launcher, "_records_dir", lambda: records)monkeypatch.setattr("tools.browser_session_cloud.chromium_args", list)monkeypatch.setattr("tools.browser_session_cloud.is_headed_mode", lambda: False)yield scriptlauncher.stop_all_browsers()+def _records() -> Path:+ """The test profile's launch records dir (created private, as the launcher creates it)."""+ from hermes_constants import get_hermes_home+ path = Path(get_hermes_home()) / "cache" / "browser" / "chromium-records"+ path.mkdir(mode=0o700, parents=True, exist_ok=True)+ return path++def _argv(browser) -> list[str]:return json.loads(Path(browser.user_data_dir, "argv.json").read_text())@@ -84,6 +90,23 @@ def test_launch_reads_devtools_port_and_runs_headless_on_an_ephemeral_home_profiassert argv[-1] == "about:blank"[email protected]("posix")[email protected]_system_guard_bypass # the fake browser's reparented helper is ours to stop+def test_launch_record_lives_in_the_profiles_private_state_dir(fake_chromium):+ """Launcher state lives in a private per-profile dir: the record under ``<HERMES_HOME>/cache/browser/+ chromium-records`` (0700) and the throwaway profile under the 0700 ephemeral root beside it."""+ from hermes_constants import get_hermes_home+ browser, err = launcher.launch_chromium("recorded", env=dict(os.environ))+ assert err is None+ state = Path(get_hermes_home()) / "cache" / "browser"+ assert stat.S_IMODE((state / "chromium-records").stat().st_mode) == 0o700+ assert stat.S_IMODE((state / "chromium").stat().st_mode) == 0o700+ [record] = (state / "chromium-records").glob("*.json")+ assert json.loads(record.read_text())["pid"] == browser.pid+ launcher.stop_browser("recorded")+ assert not list((state / "chromium-records").glob("*.json"))++@pytest.mark.platforms("posix")@pytest.mark.live_system_guard_bypass # the fake browser's reparented helper is ours to stopdef test_one_browser_per_key_and_separate_browsers_for_separate_keys(fake_chromium):@@ -157,7 +180,7 @@ def _write_orphan_record(records: Path, pid: int, udd: str) -> Path:def test_orphan_reap_refuses_a_pid_whose_cmdline_lacks_the_recorded_user_data_dir(tmp_path, fake_chromium):stranger = subprocess.Popen(["sleep", "3001"])try:- record = _write_orphan_record(launcher._records_dir(), stranger.pid, str(tmp_path / "some-profile"))+ record = _write_orphan_record(_records(), stranger.pid, str(tmp_path / "some-profile"))assert launcher.reap_orphaned_browsers() == 0assert stranger.poll() is None # never signalledassert not record.exists() # the stale record is dropped@@ -174,7 +197,7 @@ def test_orphan_reap_stops_a_crashed_owners_browser(tmp_path, fake_chromium):deadline = time.monotonic() + 10while not (udd / "DevToolsActivePort").exists() and time.monotonic() < deadline:time.sleep(0.05)- _write_orphan_record(launcher._records_dir(), proc.pid, str(udd))+ _write_orphan_record(_records(), proc.pid, str(udd))assert launcher.reap_orphaned_browsers() == 1proc.wait(timeout=10)@@ -185,7 +208,7 @@ def test_records_of_a_live_owner_are_left_alone(tmp_path, fake_chromium):launcher.launch_chromium("mine", env=dict(os.environ))assert launcher.reap_orphaned_browsers() == 0assert launcher.get_browser("mine") is not None- assert list(launcher._records_dir().glob("*.json"))+ assert list(_records().glob("*.json"))@pytest.mark.parametrize("headed,display,expect_headless", [diff --git a/tests/tools/test_browser_orphan_reaper.py b/tests/tools/test_browser_orphan_reaper.pyindex 85d610f0983..6b9474459b1 100644--- a/tests/tools/test_browser_orphan_reaper.py+++ b/tests/tools/test_browser_orphan_reaper.py@@ -1,10 +1,13 @@"""Tests for the browser orphan reaper: Chromium launched by a Hermes process that exited without-cleaning up is found through the launcher's host-wide records and stopped, but only after its+cleaning up is found through the launcher's per-profile records and stopped, but only after itsidentity is proven (``tools.browser_launcher.reap_orphaned_browsers``, driven by``browser_session_lifecycle.reap_orphaned_browser_sessions``)."""import jsonimport os+import subprocess+import sys+import timefrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import patch@@ -20,16 +23,20 @@ _LIVE_OTHER_OWNER = 88888@pytest.fixture-def records(tmp_path, monkeypatch):- """Host-wide launch records in a temp dir; no real process is ever probed or signalled."""- path = tmp_path / "records"- path.mkdir()- monkeypatch.setattr(launcher, "_records_dir", lambda: path)+def records(monkeypatch):+ """The test profile's launch records dir; nothing is ever signalled (``_terminate`` only records)."""+ from hermes_constants import get_hermes_home+ home = Path(get_hermes_home())+ path = home / "cache" / "browser" / "chromium-records"+ path.mkdir(mode=0o700, parents=True)+ monkeypatch.setattr(launcher, "_records_dir", lambda *_home: path) # this profile's dir, from any caller+ monkeypatch.setattr(launcher, "_served_homes", set(), raising=False)monkeypatch.setattr(launcher, "_browsers", {})monkeypatch.setattr(launcher, "_procs", {})terminated = []monkeypatch.setattr(launcher, "_terminate", lambda pid, start_time, proc: terminated.append(pid))- return SimpleNamespace(dir=path, terminated=terminated)+ return SimpleNamespace(dir=path, terminated=terminated,+ ephemeral=lambda name: str(home / "cache" / "browser" / "chromium" / name))def _record(records, *, pid: int, udd: str, owner_pid: int = _DEAD_OWNER, start_time=777,@@ -75,7 +82,7 @@ class TestReapOrphanedBrowserSessions:A PID whose identity cannot be pinned could be recycled between the verify and thetree-kill, so it must be left alone."""- _record(records, pid=12345, udd=str(tmp_path / "p"), start_time=None)+ _record(records, pid=12345, udd=records.ephemeral("p"), start_time=None)monkeypatch.setattr(launcher, "_pid_alive", _alive(12345))monkeypatch.setattr(launcher, "_start_time", lambda pid: None)monkeypatch.setattr(launcher, "_cmdline_names_dir", lambda pid, udd: True)@@ -107,7 +114,7 @@ class TestOwnerPidCrossProcess:This is the core cross-process safety check: Process B scanning while Process A is using abrowser must not kill A's browser."""- rec = _record(records, pid=12345, udd=str(tmp_path / "p"), owner_pid=_LIVE_OTHER_OWNER)+ rec = _record(records, pid=12345, udd=records.ephemeral("p"), owner_pid=_LIVE_OTHER_OWNER)monkeypatch.setattr(launcher, "_pid_alive", _alive(12345, _LIVE_OTHER_OWNER))monkeypatch.setattr(launcher, "_start_time", lambda pid: 777)monkeypatch.setattr(launcher, "_cmdline_names_dir", lambda pid, udd: True)@@ -171,7 +178,7 @@ class TestLeakedBrowserOfThisProcess:this process still tracks is never reaped, however old."""def test_untracked_own_browser_is_reaped(self, records, tmp_path, monkeypatch):- rec = _record(records, pid=12345, udd=str(tmp_path / "p"), owner_pid=os.getpid())+ rec = _record(records, pid=12345, udd=records.ephemeral("p"), owner_pid=os.getpid())monkeypatch.setattr(launcher, "_pid_alive", _alive(12345, os.getpid()))monkeypatch.setattr(launcher, "_start_time", lambda pid: 777)monkeypatch.setattr(launcher, "_cmdline_names_dir", lambda pid, udd: True)@@ -181,7 +188,7 @@ class TestLeakedBrowserOfThisProcess:assert not rec.exists()def test_tracked_own_browser_is_spared(self, records, tmp_path, monkeypatch):- udd = str(tmp_path / "p")+ udd = records.ephemeral("p")rec = _record(records, pid=12345, udd=udd, owner_pid=os.getpid())launcher._browsers["mine"] = launcher.LaunchedBrowser(key="mine", pid=12345, start_time=777, cdp_url="ws://127.0.0.1:1/devtools/browser/x",@@ -196,7 +203,7 @@ class TestLeakedBrowserOfThisProcess:def test_identity_guard_still_gates_the_leak_path(self, records, tmp_path, monkeypatch):"""The leak path must not bypass the argv identity check."""- _record(records, pid=12345, udd=str(tmp_path / "p"), owner_pid=os.getpid())+ _record(records, pid=12345, udd=records.ephemeral("p"), owner_pid=os.getpid())monkeypatch.setattr(launcher, "_pid_alive", _alive(12345, os.getpid()))monkeypatch.setattr(launcher, "_start_time", lambda pid: 777)monkeypatch.setattr(launcher, "_cmdline_names_dir", lambda pid, udd: False)@@ -205,6 +212,87 @@ class TestLeakedBrowserOfThisProcess:assert records.terminated == []+class TestPrivatePerProfileRecords:+ """Launcher state lives in a private per-profile dir: a records dir that is not a real directory of this+ user closed to other writers is never read, and the reaper deletes nothing outside the profile's+ ephemeral root (``<HERMES_HOME>/cache/browser/chromium/``)."""++ @staticmethod+ def _orphan(records, monkeypatch, pid=12345):+ rec = _record(records, pid=pid, udd=records.ephemeral("p"))+ monkeypatch.setattr(launcher, "_pid_alive", _alive(pid))+ monkeypatch.setattr(launcher, "_start_time", lambda pid: 777)+ monkeypatch.setattr(launcher, "_cmdline_names_dir", lambda pid, udd: True)+ return rec++ @pytest.mark.platforms("posix")+ def test_records_dir_writable_by_others_is_not_read(self, records, monkeypatch):+ rec = self._orphan(records, monkeypatch)+ records.dir.chmod(0o777)++ assert launcher.reap_orphaned_browsers() == 0+ assert records.terminated == [] and rec.exists()++ @pytest.mark.platforms("posix")+ def test_symlinked_records_dir_is_not_read(self, records, tmp_path, monkeypatch):+ real = tmp_path / "elsewhere"+ records.dir.rename(real)+ records.dir.symlink_to(real, target_is_directory=True)+ rec = self._orphan(records, monkeypatch)++ assert launcher.reap_orphaned_browsers() == 0+ assert records.terminated == [] and rec.exists()++ @pytest.mark.platforms("posix")+ @pytest.mark.live_system_guard_bypass # the stand-in process is our own child+ def test_ephemeral_record_outside_the_ephemeral_root_is_neither_signalled_nor_deleted(self, records, tmp_path):+ """A live process carrying the recorded ``--user-data-dir=`` token with a matching start time: still+ refused when the "ephemeral" dir is not one the launcher creates."""+ outside = tmp_path / "not-a-launcher-profile"+ (outside / "Default").mkdir(parents=True)+ proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)", f"--user-data-dir={outside}"])+ try:+ deadline = time.monotonic() + 10+ while launcher._start_time(proc.pid) is None and time.monotonic() < deadline:+ time.sleep(0.05)+ _record(records, pid=proc.pid, udd=str(outside), start_time=launcher._start_time(proc.pid))++ assert launcher.reap_orphaned_browsers() == 0+ assert records.terminated == []+ assert (outside / "Default").is_dir()+ assert proc.poll() is None+ finally:+ proc.kill()+ proc.wait()++[email protected]("posix")+def test_records_of_every_served_profile_are_reaped(tmp_path, monkeypatch):+ """One process serves many profiles; the janitor/atexit reap runs outside any profile scope. Each served+ home's records are read by path: the launch profile's and a live session's owning profile's."""+ from hermes_constants import get_hermes_home+ home_a, home_b = Path(get_hermes_home()), tmp_path / "profile-b"+ monkeypatch.setattr(launcher, "_browsers", {})+ monkeypatch.setattr(launcher, "_served_homes", set(), raising=False)+ terminated = []+ monkeypatch.setattr(launcher, "_terminate", lambda pid, start_time, proc: terminated.append(pid))+ monkeypatch.setattr(launcher, "_pid_alive", _alive(1111, 2222))+ monkeypatch.setattr(launcher, "_start_time", lambda pid: 777)+ monkeypatch.setattr(launcher, "_cmdline_names_dir", lambda pid, udd: True)+ monkeypatch.setattr("tools.browser_lightpanda.reap_orphaned_lightpanda", lambda: 0)+ for home, pid in ((home_a, 1111), (home_b, 2222)):+ rec_dir = home / "cache" / "browser" / "chromium-records"+ rec_dir.mkdir(mode=0o700, parents=True)+ udd = home / "cache" / "browser" / "chromium" / f"orphan-{pid}"+ udd.mkdir(parents=True)+ _record(SimpleNamespace(dir=rec_dir), pid=pid, udd=str(udd))+ monkeypatch.setitem(bs._session_owner_homes, "task-on-b", str(home_b))++ assert lifecycle.reap_orphaned_browser_sessions() == 2+ assert sorted(terminated) == [1111, 2222]+ assert not (home_b / "cache" / "browser" / "chromium" / "orphan-2222").exists()++class TestPeriodicOrphanReap:"""The reaper must run repeatedly, not only at cleanup-thread startup.diff --git a/tests/tools/test_browser_pm.py b/tests/tools/test_browser_pm.pyindex 4b7a91d4e64..453a0eecfd2 100644--- a/tests/tools/test_browser_pm.py+++ b/tests/tools/test_browser_pm.py@@ -175,7 +175,7 @@ def test_exact_pm_child_receives_composed_scrubbed_environment(browser_store, mochromium = publish("chromium", _FAKE_PM_CHROMIUM.format(python=sys.executable))records = tmp_path / "records"records.mkdir()- monkeypatch.setattr(launcher, "_records_dir", lambda: records)+ monkeypatch.setattr(launcher, "_records_dir", lambda _home: records)monkeypatch.setattr(launcher, "needs_chromium_sandbox_bypass", lambda: False)monkeypatch.setattr("tools.browser_session_cloud.chromium_args", list)monkeypatch.setattr("tools.browser_session_cloud.is_headed_mode", lambda: False)diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.pyindex 60e856faf63..3b174c2a8b3 100644--- a/tests/tools/test_browser_real_profile.py+++ b/tests/tools/test_browser_real_profile.py@@ -248,7 +248,7 @@ class TestRealProfileCdpLaunch:(copy_dir / "Default" / "Cookies").write_text("copied-cookies", encoding="utf-8")records = tmp_path / "records"records.mkdir()- monkeypatch.setattr(launcher, "_records_dir", lambda: records)+ monkeypatch.setattr(launcher, "_records_dir", lambda _home: records)monkeypatch.setattr(launcher, "_start_time", lambda pid: None)monkeypatch.setattr("tools.browser_session_cloud.chromium_args", list)monkeypatch.setattr(launcher, "needs_chromium_sandbox_bypass", lambda: True)diff --git a/tests/tools/test_browser_session_profile_keys.py b/tests/tools/test_browser_session_profile_keys.pyindex 6ffc3b5621b..bd4f847f6a5 100644--- a/tests/tools/test_browser_session_profile_keys.py+++ b/tests/tools/test_browser_session_profile_keys.py@@ -35,7 +35,7 @@ def two_profiles(tmp_path, monkeypatch):monkeypatch.setattr(launcher, "needs_chromium_sandbox_bypass", lambda: False)records = tmp_path / "records"records.mkdir()- monkeypatch.setattr(launcher, "_records_dir", lambda: records)+ monkeypatch.setattr(launcher, "_records_dir", lambda _home: records)homes = {}for name in ("a", "b"):home = tmp_path / f"home-{name}"diff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex c325705bd62..334ed6eec8a 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -85,9 +85,11 @@ hybrid `::local` sidecar > cloud provider (failure → local session marked `falreal profile (consented) > Lightpanda > the packaged Chromium from `browser_launcher.launch_chromium`(one browser per cache key, `--remote-debugging-port=0` + `DevToolsActivePort`). State lives in`browser_session.py`; siblings late-import it inside functions. Every launched Chromium is stopped-parent-first and recorded host-wide so a later process reaps a crashed owner's browser after checking-pid + start time + its `--user-data-dir` argv token. `browser_tool.py` and `browser_tool_install.py`-are frozen old-updater stubs only (see their docstrings); never grow them.+parent-first and recorded per profile (`<HERMES_HOME>/cache/browser/chromium-records`, a private 0700+dir) so a later process serving that profile reaps a crashed owner's browser after checking pid + start+time + its `--user-data-dir` argv token; the reaper walks every home the process serves.+`browser_tool.py` and `browser_tool_install.py` are frozen old-updater stubs only (see their+docstrings); never grow them.## Backends and providers inside tools/diff --git a/tools/browser_launcher.py b/tools/browser_launcher.pyindex e5d48a0a234..156e9268637 100644--- a/tools/browser_launcher.py+++ b/tools/browser_launcher.py@@ -3,8 +3,9 @@One browser per launcher key (the session layer's cache key, or ``profile:<dir>`` for a persistentprofile shared by every key). Chromium picks its own DevTools port (``--remote-debugging-port=0``)and writes it to ``<user-data-dir>/DevToolsActivePort``; the CDP URL comes from that file, so there-is no port race. Every owned launch leaves a host-wide record so a later Hermes process can reap-the Chromium of an owner that crashed, after proving the pid is still that browser.+is no port race. Every owned launch leaves a record in its profile's private launcher state dir+(``<HERMES_HOME>/cache/browser/chromium-records``, 0700) so a later Hermes process serving that profile+can reap the Chromium of an owner that crashed, after proving the pid is still that browser.Stop is always parent-first (``ProcessRegistry._terminate_host_pid``): Chromium reaps its ownzygotes and renderers on SIGTERM, and killing a zygote first turns a clean exit into a crash dump.@@ -17,6 +18,7 @@ import jsonimport loggingimport osimport shutil+import statimport subprocessimport sysimport threading@@ -76,6 +78,9 @@ _procs: dict[str, subprocess.Popen] = {}_key_locks: dict[str, threading.Lock] = {}_lock = threading.RLock()_autoinstall_attempted = False+# Profile homes (``hermes_home_key``) this process launched or attached a browser for: the reaper reads+# each one's records, since one process serves many profiles.+_served_homes: set[str] = set()# ── Host facts ───────────────────────────────────────────────────────────────────────────────────────@@ -168,9 +173,8 @@ def chromium_ready() -> tuple[bool, str]:# ── Launch ───────────────────────────────────────────────────────────────────────────────────────────def _default_user_data_dir(key: str, home_key: str) -> str:- from hermes_constants import get_hermes_homedigest = hashlib.sha256(f"{home_key}\0{key}".encode()).hexdigest()[:16]- return str(Path(get_hermes_home()) / "cache" / "browser" / "chromium" / digest)+ return str(_ephemeral_root(home_key) / digest)def _launch_timeout(timeout: Optional[float]) -> float:@@ -334,6 +338,7 @@ def _make_browser(key: str, port: int, path: str, *, pid, start_time, user_data_def _prepare_dir(user_data_dir: str, ephemeral: bool) -> None:if ephemeral:+ Path(user_data_dir).parent.mkdir(mode=0o700, parents=True, exist_ok=True) # the private ephemeral rootshutil.rmtree(user_data_dir, ignore_errors=True) # fresh profile per launchos.makedirs(user_data_dir, mode=0o700, exist_ok=True)try:@@ -378,6 +383,8 @@ def launch_chromium(key: str, *, executable: Optional[str] = None, user_data_dirif existing is not None:return existing, Nonehome_key = hermes_home_key()+ with _lock:+ _served_homes.add(home_key)packaged = executable is Noneif packaged:ok, hint = chromium_ready()@@ -515,21 +522,48 @@ def browser_keys() -> list[str]:return list(_browsers)-# ── Host-wide records + orphan reap ──────────────────────────────────────────────────────────────────+# ── Per-profile records + orphan reap ────────────────────────────────────────────────────────────────-def _records_dir() -> Path:- """Host-wide (every profile, every Hermes process of this user): a crashed owner's Chromium is reaped- by whichever Hermes runs next. Socket-safe tmp root, mode 0700."""- from hermes_constants import socket_safe_tmpdir- uid = os.getuid() if hasattr(os, "getuid") else 0- path = Path(socket_safe_tmpdir()) / f"hermes-chromium-{uid}"- path.mkdir(mode=0o700, parents=True, exist_ok=True)- return path+def _ephemeral_root(home: str) -> Path:+ """Where ``home``'s throwaway profiles live; the reaper deletes nothing outside it."""+ return Path(home) / "cache" / "browser" / "chromium"-def _record_path(browser: LaunchedBrowser) -> Path:+def _records_dir(home: str) -> Path:+ """Per-profile (``home``'s, not the process's): a crashed owner's Chromium is reaped by the next Hermes+ process serving that profile. Read only after ``_private_dir`` vouches for it."""+ return Path(home) / "cache" / "browser" / "chromium-records"+++def _is_private_dir(path: Path) -> bool:+ """A real directory (not a symlink) owned by this user and closed to group/other writes. Windows has no+ uid and synthesizes the mode bits, so there only the directory check applies."""+ try:+ st = path.lstat()+ except OSError:+ return False+ if not stat.S_ISDIR(st.st_mode):+ return False+ return not hasattr(os, "getuid") or (st.st_uid == os.getuid() and not st.st_mode & 0o022)+++def _private_dir(path: Path) -> Optional[Path]:+ """``path``, created 0700 when missing; None (logged) when an existing one is not private to this user."""+ path.parent.mkdir(parents=True, exist_ok=True)+ try:+ path.mkdir(mode=0o700)+ except FileExistsError:+ pass+ if _is_private_dir(path):+ return path+ logger.debug("browser: not using %s for launcher state: not a private directory of this user", path)+ return None+++def _record_path(browser: LaunchedBrowser) -> Optional[Path]:+ records = _private_dir(_records_dir(browser.home_key))digest = hashlib.sha256(browser.user_data_dir.encode()).hexdigest()[:16]- return _records_dir() / f"{digest}-{browser.pid}.json"+ return records / f"{digest}-{browser.pid}.json" if records is not None else Nonedef _write_record(browser: LaunchedBrowser) -> None:@@ -538,14 +572,18 @@ def _write_record(browser: LaunchedBrowser) -> None:"start_time": browser.start_time, "user_data_dir": browser.user_data_dir,"home_key": browser.home_key, "ephemeral": browser.ephemeral}try:- atomic_json_write(_record_path(browser), record, indent=None)+ path = _record_path(browser)+ if path is not None:+ atomic_json_write(path, record, indent=None)except OSError as exc:logger.debug("browser: could not write launch record for pid %s: %s", browser.pid, exc)def _remove_record(browser: LaunchedBrowser) -> None:try:- _record_path(browser).unlink(missing_ok=True)+ path = _record_path(browser)+ if path is not None:+ path.unlink(missing_ok=True)except OSError as exc:logger.debug("browser: could not remove launch record for pid %s: %s", browser.pid, exc)@@ -570,10 +608,21 @@ def _cmdline_names_dir(pid: int, user_data_dir: str) -> bool:for tok in argv)-def _is_recorded_browser(record: dict) -> bool:+def _inside_ephemeral_root(user_data_dir: str, home: str) -> bool:+ try:+ rel = Path(user_data_dir).resolve().relative_to(_ephemeral_root(home).resolve())+ except (OSError, ValueError):+ return False+ return bool(rel.parts)+++def _is_recorded_browser(record: dict, home: str) -> bool:pid, udd = record.get("pid"), record.get("user_data_dir")if not isinstance(pid, int) or not isinstance(udd, str) or not _pid_alive(pid):return False+ if record.get("ephemeral") and not _inside_ephemeral_root(udd, home):+ logger.debug("browser: ignoring launch record for pid %s: %s is not a launcher profile dir", pid, udd)+ return Falseexpected = record.get("start_time")if expected is None or _start_time(pid) != expected:return False # no recorded fingerprint, or a recycled pid: never signal on argv alone@@ -588,36 +637,66 @@ def _tracked_here(record: dict) -> bool:return any(b.pid == record.get("pid") for b in _browsers.values())-def _reap_record(path: Path) -> bool:+def _load_record(path: Path) -> Optional[dict]:+ """The record, or None (a corrupt one is removed)."""try:record = json.loads(path.read_text(encoding="utf-8-sig"))- if not isinstance(record, dict):- raise ValueError("not a JSON object")+ if isinstance(record, dict):+ return recordexcept (OSError, ValueError):- path.unlink(missing_ok=True)- return False+ pass+ path.unlink(missing_ok=True)+ return None+++def _record_in_use(record: dict) -> bool:if record.get("owner_pid") == os.getpid():- if _tracked_here(record):- return False- elif _owner_alive(record):+ return _tracked_here(record)+ return _owner_alive(record)+++def _reap_record(path: Path, home: str) -> bool:+ record = _load_record(path)+ if record is None or _record_in_use(record):return False- reaped = False- if _is_recorded_browser(record):+ reaped = _is_recorded_browser(record, home)+ if reaped:_terminate(record["pid"], record.get("start_time"), None)logger.info("browser: reaped orphaned Chromium pid %s (%s)", record["pid"], record["user_data_dir"])- reaped = True- if reaped and record.get("ephemeral") and isinstance(record.get("user_data_dir"), str):- shutil.rmtree(record["user_data_dir"], ignore_errors=True)+ if record.get("ephemeral"):+ shutil.rmtree(record["user_data_dir"], ignore_errors=True)path.unlink(missing_ok=True)return reaped-def reap_orphaned_browsers() -> int:- """Stop Chromium processes whose owning Hermes process is gone; returns the count. A pid is signalled- only after its start time AND its ``--user-data-dir`` argv token match the record."""+def _reap_home(home: str) -> int:+ records = _records_dir(home)+ if not os.path.lexists(records):+ return 0+ if not _is_private_dir(records):+ logger.debug("browser: not reaping from %s: not a private directory of this user", records)+ return 0try:- records = sorted(_records_dir().glob("*.json"))+ paths = sorted(records.glob("*.json"))except OSError as exc:- logger.debug("browser: launch records unavailable: %s", exc)+ logger.debug("browser: launch records unavailable in %s: %s", records, exc)return 0- return sum(1 for path in records if _reap_record(path))+ return sum(1 for path in paths if _reap_record(path, home))+++def _served_home_keys(homes) -> set[str]:+ """The launch profile, every profile this process launched a browser for, and ``homes``."""+ from hermes_constants import get_process_hermes_home, hermes_home_key+ with _lock:+ keys = set(_served_homes)+ keys.add(hermes_home_key(get_process_hermes_home()))+ keys.update(hermes_home_key(home) for home in homes)+ return keys+++def reap_orphaned_browsers(homes=()) -> int:+ """Stop Chromium processes whose owning Hermes process is gone, in every profile this process serves+ (``_served_home_keys``; the janitor and atexit run outside any profile scope, so each home's records+ are read by path); returns the count. A pid is signalled only after its start time AND its+ ``--user-data-dir`` argv token match the record."""+ return sum(_reap_home(home) for home in sorted(_served_home_keys(homes)))diff --git a/tools/browser_session_lifecycle.py b/tools/browser_session_lifecycle.pyindex 038cfa697b4..583bc1b8ca9 100644--- a/tools/browser_session_lifecycle.py+++ b/tools/browser_session_lifecycle.py@@ -243,15 +243,20 @@ def emergency_cleanup_all_sessions() -> None:def reap_orphaned_browser_sessions() -> int:- """Stop Chromium / ``lightpanda serve`` processes whose owning Hermes process is gone."""+ """Stop Chromium / ``lightpanda serve`` processes whose owning Hermes process is gone (Chromium: in every+ profile this process serves, incl. each live session's owning home)."""from tools.browser_launcher import reap_orphaned_browsersfrom tools.browser_lightpanda import reap_orphaned_lightpanda+ bs = _bs()+ with bs._cleanup_lock:+ session_homes = list(bs._session_owner_homes.values())reaped = 0- for reap in (reap_orphaned_lightpanda, reap_orphaned_browsers):+ for name, reap in (("lightpanda", reap_orphaned_lightpanda),+ ("chromium", lambda: reap_orphaned_browsers(session_homes))):try:reaped += reap()except OSError as exc:- logger.debug("orphan reap (%s) failed: %s", reap.__name__, exc)+ logger.debug("orphan reap (%s) failed: %s", name, exc)if reaped:logger.info("Reaped %d orphaned browser process(es) from previous run(s)", reaped)return reaped