Skip to content

The agent that grows with you

refactor(browser): the in-command ownership checks run on the shared periodic scheduler

kshitijk4poor95438a7a97d7
diff --git a/hermes_cli/process_identity.py b/hermes_cli/process_identity.py
index 63ab2465e55..a7b4a3b5ed6 100644
--- a/hermes_cli/process_identity.py
+++ b/hermes_cli/process_identity.py
@@ -12,7 +12,6 @@ Hermes process that reaps the owned children's process groups the moment Hermes
from __future__ import annotations
-import contextlib
import functools
import hashlib
import json
@@ -906,30 +905,6 @@ def release_process_group_once_empty(pgid: int, *, proc=None, timeout: float = 1
time.sleep(0.05)
-def registering_meanwhile(register, *, every: float = 0.5):
- """Run ``register()`` every ``every`` seconds on a helper thread while the block runs, so a detached
- daemon a long-running command starts (a browser daemon on the first command, while it navigates or
- runs user code) reaches the supervisor while that command still runs, not only once it returns."""
- done = threading.Event()
-
- def loop():
- while not done.wait(every):
- try:
- register()
- except Exception: # best-effort; the caller registers again once the command returns
- logger.debug("owned-daemon registration during a command failed", exc_info=True)
-
- # health: allow HX012 -- register() resolves its target from arguments it closed over, not from profile scope
- worker = threading.Thread(target=loop, name="owned-daemon-registrar", daemon=True)
- worker.start()
- try:
- yield
- finally:
- done.set()
- worker.join(timeout=5) # never two registrations racing: the caller's own runs next
-
-
def stop_owned_group_survivors(pgid: int, *, proc=None, grace: float = 3.0) -> bool:
"""Stop what is left of owned group ``pgid`` after its leader exited, then release it; True once
released. Members that outlived a crashed leader (a router's model children) keep the group, and
diff --git a/tests/hermes_cli/test_process_identity_supervisor.py b/tests/hermes_cli/test_process_identity_supervisor.py
index 6adbfab2b3d..ed0e3875a0c 100644
--- a/tests/hermes_cli/test_process_identity_supervisor.py
+++ b/tests/hermes_cli/test_process_identity_supervisor.py
@@ -843,23 +843,3 @@ def test_a_released_supervisor_leaves_no_zombie_child():
finally:
_kill(child.pid)
child.wait(timeout=10)
-
-
-def test_registering_meanwhile_runs_while_the_block_runs_and_stops_with_it():
- """A long first browser command must hand its daemon over while it still runs; nothing may
- register after the block exits (the caller's own registration runs next, never concurrently)."""
- calls = []
- with process_identity.registering_meanwhile(lambda: calls.append(time.monotonic()), every=0.05):
- wait_until(lambda: len(calls) >= 2, timeout=10, what="registrations during the block")
- after = len(calls)
- time.sleep(0.2) # health: allow HX013 -- the absence of calls over 4 intervals IS the behaviour under test
- assert len(calls) == after, "kept registering after the block exited"
-
- failures = []
-
- def boom():
- failures.append(1)
- raise OSError("pid file vanished")
-
- with process_identity.registering_meanwhile(boom, every=0.01): # best-effort: never raises out
- wait_until(lambda: len(failures) >= 2, timeout=10, what="registration retried after a failure")
diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.py
index 1b0e4f1bef2..f8f4aec3cb5 100644
--- a/tools/browser_use_cli.py
+++ b/tools/browser_use_cli.py
@@ -24,8 +24,7 @@ from pathlib import Path
from typing import Any, Callable, Dict, List, NamedTuple, Optional
from hermes_cli.process_identity import (
- own_process_groups, register_child, registering_meanwhile, release_process_group_once_empty, spawn_env,
- spawned_by_this_process)
+ own_process_groups, register_child, release_process_group_once_empty, spawn_env, spawned_by_this_process)
from hermes_constants import get_hermes_home, hermes_home_key
from tools.browser_harness_dirs import (daemon_env, daemon_identity, fit_default_socket_dir, harness_pid_file,
namespace_harness_dirs)
@@ -612,6 +611,8 @@ def _run_cli_killing_process_group(cmd, code, env, timeout):
return subprocess.CompletedProcess(cmd, proc.returncode, stdout, stderr)
+# How often a running browser_exec re-checks for the daemon its first call starts.
+_OWN_DURING_CALL_S = 0.5
# Harness daemons this process drove: each latches BU_CDP_* at start and outlives every call, so a backend
# swap (/browser connect|disconnect) leaves later calls in the old browser until these are stopped.
_driven_daemons: dict[tuple[str, ...], str] = {} # daemon identity -> home
@@ -845,11 +846,12 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUT
with _driven_daemons_lock:
daemon = daemon_identity(env)
_driven_daemons[daemon] = hermes_home_key()
+ # The first call starts the daemon and may run long (navigation, user code): own it as soon as
+ # it publishes its pid, so a Hermes killed mid-call takes it along (the call's end owns it too).
+ from agent.periodic_scheduler import schedule
+ owning = schedule(lambda: _own_harness_daemon(env), _OWN_DURING_CALL_S)
try:
- # The first call starts the daemon and may run long (navigation, user code): own it as
- # soon as it publishes its pid, so a Hermes killed mid-call takes it along.
- with registering_meanwhile(lambda: _own_harness_daemon(env)):
- return {"proc": _run_cli_killing_process_group(cmd, code, env, timeout)}
+ return {"proc": _run_cli_killing_process_group(cmd, code, env, timeout)}
except subprocess.TimeoutExpired:
return {"error_result": tool_error(
f"browser-use exec timed out after {timeout}s. The daemon may still be working; retry "
@@ -858,6 +860,8 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUT
)}
except OSError as e:
return {"error_result": tool_error(f"Failed to launch browser-use CLI: {e}")}
+ finally:
+ owning.cancel(wait=5) # an in-flight check finishes before the post-call one runs
if bot_desktop_browser:
from tools.browser_session import run_fenced