Skip to content

The agent that grows with you

fix(browser): exit reloads an owned harness daemon only while its name still publishes our pid

kshitijk4poorea08389a2d0b
diff --git a/tests/tools/test_browser_use_cli_owned_daemon.py b/tests/tools/test_browser_use_cli_owned_daemon.py
index c98525714d0..8487e87878e 100644
--- a/tests/tools/test_browser_use_cli_owned_daemon.py
+++ b/tests/tools/test_browser_use_cli_owned_daemon.py
@@ -130,13 +130,23 @@ def test_stopping_the_daemons_releases_their_groups(monkeypatch, registered):
assert browser_use_cli._owned_daemon_groups == {}
-def test_the_exit_path_stops_only_the_daemons_this_process_owns(monkeypatch, registered):
- ours = browser_use_cli.daemon_identity({"BU_NAME": "ours"})
- theirs = browser_use_cli.daemon_identity({"BU_NAME": "theirs"}) # another live Hermes started it
+def _shared_runtime(tmp_path) -> tuple[Path, dict]:
+ """A runtime dir shared between names (``bu-<BU_NAME>.pid``) and the env naming it, so a daemon
+ identity built from that env carries the dir."""
+ runtime = tmp_path / "runtime"
+ runtime.mkdir()
+ return runtime, {"BH_RUNTIME_DIR": str(runtime), "BH_RUNTIME_DIR_SHARED": "1"}
+
+
+def test_the_exit_path_stops_only_the_daemons_this_process_owns(monkeypatch, tmp_path, registered):
+ runtime, dirs = _shared_runtime(tmp_path)
+ ours = browser_use_cli.daemon_identity({**dirs, "BU_NAME": "ours"})
+ theirs = browser_use_cli.daemon_identity({**dirs, "BU_NAME": "theirs"}) # another live Hermes started it
browser_use_cli._owned_daemon_groups.update({ours: 4242})
monkeypatch.setattr(browser_use_cli, "_driven_daemons", {ours: "home", theirs: "home"})
monkeypatch.setattr(browser_use_cli, "_find_cli", lambda: ["browser-harness"])
monkeypatch.setattr(browser_use_cli, "_base_subprocess_env", dict)
+ _publish(runtime, "bu-ours", 4242)
reloaded = []
monkeypatch.setattr(browser_use_cli, "_run_cli_killing_process_group",
lambda cmd, code, env, timeout: reloaded.append(env["BU_NAME"]))
@@ -154,6 +164,36 @@ def test_the_exit_path_stops_only_the_daemons_this_process_owns(monkeypatch, reg
assert browser_use_cli._driven_daemons == {theirs: "home"}
+def test_exit_never_reloads_a_name_another_hermes_republished_after_ours_exited(monkeypatch, tmp_path, registered):
+ """--reload goes by name: once our daemon exited and another live Hermes started its replacement
+ under the same name, exiting here must leave that replacement running and just release ours."""
+ runtime, dirs = _shared_runtime(tmp_path)
+ ours = browser_use_cli.daemon_identity({**dirs, "BU_NAME": "work"})
+ browser_use_cli._owned_daemon_groups.update({ours: 4242})
+ monkeypatch.setattr(browser_use_cli, "_driven_daemons", {ours: "home"})
+ monkeypatch.setattr(browser_use_cli, "_find_cli", lambda: ["browser-harness"])
+ monkeypatch.setattr(browser_use_cli, "_base_subprocess_env", dict)
+ _publish(runtime, "bu-work", 4242)
+ reloaded = []
+ monkeypatch.setattr(browser_use_cli, "_run_cli_killing_process_group",
+ lambda cmd, code, env, timeout: reloaded.append(env["BU_NAME"]))
+ with monkeypatch.context() as m: # control: while the name still publishes our pid, it is reloaded
+ m.setattr(browser_use_cli, "_owned_daemon_groups", {ours: 4242})
+ m.setattr(browser_use_cli, "_driven_daemons", {})
+ browser_use_cli.stop_owned_harness_daemons()
+ assert reloaded == ["work"]
+ registered.clear()
+
+ _publish(runtime, "bu-work", 5151) # ours exited; the other Hermes's daemon now holds the name
+ reloaded.clear()
+
+ browser_use_cli.stop_owned_harness_daemons()
+
+ assert reloaded == []
+ assert registered == [("unregister", [4242])]
+ assert browser_use_cli._owned_daemon_groups == {}
+
+
# The daemon reparents to init once its owner dies, so cleanup leaves this test's subtree.
@pytest.mark.live_system_guard_bypass
def test_a_sigkilled_owner_takes_its_harness_daemon_with_it(tmp_path):
diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.py
index 878f153b420..ece400cd30b 100644
--- a/tools/browser_use_cli.py
+++ b/tools/browser_use_cli.py
@@ -644,11 +644,29 @@ def stop_owned_harness_daemons() -> None:
stop_harness_daemons()
return
with _owned_daemon_groups_lock:
- owned = sorted(_owned_daemon_groups)
+ owned = dict(_owned_daemon_groups)
with _driven_daemons_lock:
for key in owned:
_driven_daemons.pop(key, None)
- _reload_daemons(owned)
+ # --reload stops a daemon by name, and one of ours that exited may since have been replaced under
+ # that name by another live Hermes: only a name whose published pid is still ours is reloaded.
+ env = _base_subprocess_env() if owned else {}
+ current = [key for key, pid in owned.items() if _published_daemon_pid(daemon_env(env, key)) == pid]
+ for key in owned.keys() - set(current):
+ with _owned_daemon_groups_lock:
+ _owned_daemon_groups.pop(key, None)
+ release_process_group_once_empty(owned[key], timeout=0) # a survivor of ours stays covered
+ _reload_daemons(sorted(current))
+
+
+def _published_daemon_pid(env: dict) -> Optional[int]:
+ """The pid the harness published for the daemon ``env`` drives (``harness_pid_file``: JSON
+ ``{"pid", "started"}`` or a bare pid), or None when there is none."""
+ try:
+ raw = harness_pid_file(env).read_text(encoding="utf-8-sig").strip()
+ return int(json.loads(raw)["pid"]) if raw.startswith("{") else int(raw.split()[0])
+ except (OSError, ValueError, KeyError, TypeError, IndexError):
+ return None
def _reload_daemons(daemons) -> None: # each ``daemon_identity`` daemon, with its own dirs
@@ -687,9 +705,11 @@ def _own_harness_daemon(env: dict) -> None:
import psutil
daemon = daemon_identity(env)
+ pid = _published_daemon_pid(env)
+ if pid is None:
+ logger.debug("browser_exec: no harness daemon pid published for %s", daemon[-1])
+ return
try:
- raw = harness_pid_file(env).read_text(encoding="utf-8-sig").strip()
- pid = int(json.loads(raw)["pid"]) if raw.startswith("{") else int(raw.split()[0])
with _owned_daemon_groups_lock:
if _owned_daemon_groups.get(daemon) == pid:
return
@@ -700,7 +720,7 @@ def _own_harness_daemon(env: dict) -> None:
return
if not spawned_by_this_process(pid):
return # another Hermes on the same BU_NAME started it: that Hermes owns it
- except (OSError, ValueError, KeyError, TypeError, IndexError, psutil.Error) as exc:
+ except (OSError, ValueError, IndexError, psutil.Error) as exc:
logger.debug("browser_exec: no harness daemon to supervise for %s: %s", daemon[-1], exc)
return
with _owned_daemon_groups_lock: