The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): a long first browser command owns its daemon while it still runs
kshitijk4poor2b36e8cd5821
diff --git a/hermes_cli/process_identity.py b/hermes_cli/process_identity.pyindex a7b4a3b5ed6..63ab2465e55 100644--- a/hermes_cli/process_identity.py+++ b/hermes_cli/process_identity.py@@ -12,6 +12,7 @@ Hermes process that reaps the owned children's process groups the moment Hermesfrom __future__ import annotations+import contextlibimport functoolsimport hashlibimport json@@ -905,6 +906,30 @@ def release_process_group_once_empty(pgid: int, *, proc=None, timeout: float = 1time.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 oncereleased. Members that outlived a crashed leader (a router's model children) keep the group, anddiff --git a/tests/hermes_cli/test_process_identity_supervisor.py b/tests/hermes_cli/test_process_identity_supervisor.pyindex ed0e3875a0c..6adbfab2b3d 100644--- a/tests/hermes_cli/test_process_identity_supervisor.py+++ b/tests/hermes_cli/test_process_identity_supervisor.py@@ -843,3 +843,23 @@ 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/tests/tools/test_browser_use_cli_owned_daemon.py b/tests/tools/test_browser_use_cli_owned_daemon.pyindex 8487e87878e..00155b9b0a0 100644--- a/tests/tools/test_browser_use_cli_owned_daemon.py+++ b/tests/tools/test_browser_use_cli_owned_daemon.py@@ -262,3 +262,38 @@ def test_a_daemon_another_live_hermes_started_on_the_same_name_is_never_registerdaemon.wait(timeout=10)other_hermes.stdin.close()other_hermes.wait(timeout=10)+++def test_a_long_first_browser_exec_owns_its_daemon_before_the_call_returns(monkeypatch):+ """The first call starts the daemon and may run for minutes (navigation, user code). Its daemon+ must reach the supervisor during the call, or a Hermes killed mid-call leaves it running."""+ import threading+ from tools import browser_tool_cloud as cloud+ from tools import browser_tool_session as session++ owned_during_call = threading.Event()+ running = threading.Event()+ monkeypatch.setattr(browser_use_cli, "_own_harness_daemon",+ lambda env: running.is_set() and owned_during_call.set())++ def run_cli(*_args):+ running.set()+ owned_during_call.wait(10) # the CLI is still "running" until the daemon was owned+ running.clear()+ return subprocess.CompletedProcess([], 0, "ok", "")++ monkeypatch.setattr(browser_use_cli, "_find_cli", lambda: ["browser-use"])+ monkeypatch.setattr(browser_use_cli, "_base_subprocess_env", dict)+ monkeypatch.setattr(browser_use_cli, "_real_profile_consented", lambda: False)+ monkeypatch.setattr(browser_use_cli, "_resolve_lightpanda_cdp", lambda *a: None)+ monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")+ monkeypatch.setattr("tools.browser_tool._get_open_command_timeout", lambda **_kw: 5)+ monkeypatch.setattr(cloud, "_get_cloud_provider", lambda: None)+ monkeypatch.setattr(session, "_run_browser_command", lambda *_a, **_kw: {+ "success": True, "data": {"cdpUrl": "http://127.0.0.1:9222"}})+ monkeypatch.setattr(browser_use_cli, "_attach_vault_supervisor", lambda *a: None)+ monkeypatch.setattr(browser_use_cli, "_run_cli_killing_process_group", run_cli)+ monkeypatch.setattr(browser_use_cli, "_driven_daemons", {})++ browser_use_cli.browser_exec("print(page_info())", task_id="long-first-call")+ assert owned_during_call.is_set(), "the daemon was only owned after the CLI call returned"diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex ece400cd30b..1b0e4f1bef2 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -24,7 +24,8 @@ from pathlib import Pathfrom typing import Any, Callable, Dict, List, NamedTuple, Optionalfrom hermes_cli.process_identity import (- own_process_groups, register_child, release_process_group_once_empty, spawn_env, spawned_by_this_process)+ own_process_groups, register_child, registering_meanwhile, release_process_group_once_empty, spawn_env,+ spawned_by_this_process)from hermes_constants import get_hermes_home, hermes_home_keyfrom tools.browser_harness_dirs import (daemon_env, daemon_identity, fit_default_socket_dir, harness_pid_file,namespace_harness_dirs)@@ -845,7 +846,10 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUTdaemon = daemon_identity(env)_driven_daemons[daemon] = hermes_home_key()try:- return {"proc": _run_cli_killing_process_group(cmd, code, env, timeout)}+ # 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)}except subprocess.TimeoutExpired:return {"error_result": tool_error(f"browser-use exec timed out after {timeout}s. The daemon may still be working; retry "