The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): capture real-profile agent-browser CLI output via temp files, not pipes
liuhao102415485e0c8df3
diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.pyindex 60073b03b2d..c4bc7a1decf 100644--- a/tests/tools/test_browser_real_profile.py+++ b/tests/tools/test_browser_real_profile.py@@ -212,10 +212,10 @@ class TestRealProfileCdpLaunch:proc = Mock(return_value=None, returncode=0, stdout="", stderr="")captured = {}- def fake_run(argv, **kw):+ def fake_agent_browser_spawn(argv, env, socket_dir, tag):captured["argv"] = argv- captured["env"] = kw["env"]- return proc+ captured["env"] = env+ return Mock(wait=Mock(return_value=0), returncode=0)class FakeChrome:def poll(self):@@ -234,7 +234,7 @@ class TestRealProfileCdpLaunch:patch.object(bt_real_profile, "_agent_browser_get_cdp",side_effect=[None, "http://127.0.0.1:41000"]), \patch.object(bt_install, "_find_agent_browser", return_value="/usr/bin/agent-browser"), \- patch.object(bt.subprocess, "run", side_effect=fake_run), \+ patch.object(bt_session, "_popen_agent_browser", side_effect=fake_agent_browser_spawn), \patch.object(bt, "_socket_safe_tmpdir", return_value=str(tmp_path)), \patch.object(bt_cloud, "_is_headed_mode", return_value=False):bt_real_profile._real_profile_cdp()@@ -279,7 +279,7 @@ class TestRealProfileCdpLaunch:patch.object(bt_real_profile, "_agent_browser_close_session",side_effect=lambda s: closed.__setitem__("n", closed["n"] + 1)), \patch.object(bt_install, "_find_agent_browser", return_value="/usr/bin/agent-browser"), \- patch.object(bt.subprocess, "run", return_value=proc), \+ patch.object(bt_real_profile, "_capture_agent_browser_cli", return_value=proc), \patch.object(bt_cloud, "_is_headed_mode", return_value=False):cdp, err = bt_real_profile._real_profile_cdp()assert closed["n"] == 1 # stale wrong-dir session was closed@@ -320,6 +320,81 @@ class TestRealProfileCdpLaunch:assert not bt_real_profile._cdp_on_data_dir("http://127.0.0.1:9999", str(tmp_path))+class TestAgentBrowserCliCapture:+ """#96731: agent-browser's resident daemon inherits the caller's stdio and+ outlives the CLI, so pipe-based capture never sees EOF after the CLI+ exits. Capture must go through temp files and wait only for the CLI."""++ STUB_GRANDCHILD = (+ "import subprocess, sys\n"+ # A grandchild that inherits stdout and outlives the CLI — exactly+ # what agent-browser's first-use daemon spawn does.+ "subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])\n"+ "sys.stdout.write('ws://127.0.0.1:41022/devtools/browser/stub\\n')\n"+ "sys.stderr.write('daemon warm\\n')\n"+ )++ def test_get_cdp_returns_despite_grandchild_holding_stdio(self, tmp_path):+ """The blocking frame from the #96731 py-spy capture: get cdp-url."""+ import sys+ import time++ stub = tmp_path / "agent_browser_daemon_stub.py"+ stub.write_text(self.STUB_GRANDCHILD)+ with patch.object(bt_install, "_find_agent_browser", return_value=str(stub)), \+ patch.object(bt_session, "_agent_browser_argv", return_value=[sys.executable, str(stub)]), \+ patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):+ start = time.monotonic()+ cdp = bt_real_profile._agent_browser_get_cdp("hermes-real-profile")+ elapsed = time.monotonic() - start++ assert cdp == "http://127.0.0.1:41022"+ # Pipe capture would stall here for the full 15s timeout on POSIX and+ # hang past the outer tool deadline on Windows.+ assert elapsed < 10, f"get cdp-url stalled {elapsed:.1f}s behind a grandchild"+ # The capture temp files are cleaned up after the call.+ assert not list(tmp_path.glob("_std*_rp-*"))++ def test_capture_cli_surfaces_stdout_stderr_and_exit_code(self, tmp_path):+ import sys++ stub = tmp_path / "agent_browser_echo_stub.py"+ stub.write_text(+ "import sys\n"+ "sys.stdout.write('out-42\\n')\n"+ "sys.stderr.write('err-7\\n')\n"+ "sys.exit(3)\n"+ )+ with patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):+ proc = bt_real_profile._capture_agent_browser_cli(+ [sys.executable, str(stub)], timeout=15, tag="rp-test",+ )+ assert proc.returncode == 3+ assert proc.stdout == "out-42"+ assert proc.stderr == "err-7"++ def test_capture_cli_timeout_kills_cli_and_cleans_files(self, tmp_path):+ import subprocess+ import sys+ import time++ stub = tmp_path / "agent_browser_sleep_stub.py"+ stub.write_text("import time; time.sleep(30)\n")+ with patch.object(bt_real_profile, "_real_profile_daemon_env", return_value=({}, str(tmp_path))):+ start = time.monotonic()+ with pytest.raises(subprocess.TimeoutExpired):+ bt_real_profile._capture_agent_browser_cli(+ [sys.executable, str(stub)], timeout=2, tag="rp-timeout",+ )+ elapsed = time.monotonic() - start++ # The CLI itself is killed at the deadline instead of draining pipes+ # behind a daemon grandchild forever.+ assert elapsed < 10, f"timeout path stalled {elapsed:.1f}s"+ assert not (tmp_path / "_stdout_rp-timeout").exists()+ assert not (tmp_path / "_stderr_rp-timeout").exists()++class TestConsentConfigRead:"""Unmocked config read: _use_real_profile against a real config.yaml."""diff --git a/tools/browser_tool_real_profile.py b/tools/browser_tool_real_profile.pyindex 8871a99b578..67faf51d0c1 100644--- a/tools/browser_tool_real_profile.py+++ b/tools/browser_tool_real_profile.py@@ -37,16 +37,43 @@ def _cdp_http_ready(http_cdp: str) -> bool:return _cdp_ready(http_cdp, timeout=1.0)-def _real_profile_daemon_env() -> dict:+def _real_profile_daemon_env() -> tuple:"""Reaper-visible socket dir + ``owner_pid`` claim like every other lane (agent-browser'sdefault dir is invisible to the reaper — #100855). The daemon-side idle timeout is dropped:Chrome is launched by Hermes, not the daemon, so a self-exiting daemon would leave Chrome- holding the copy dir under the next snapshot overlay."""+ holding the copy dir under the next snapshot overlay. Returns ``(env, socket_dir)``."""_bt = _origin()socket_dir = _session._prepare_session_socket_dir(_bt._REAL_PROFILE_SESSION)env = _session._agent_browser_command_env(socket_dir)env.pop("AGENT_BROWSER_IDLE_TIMEOUT_MS", None)- return env+ return env, socket_dir+++def _capture_agent_browser_cli(argv: list, timeout: float, tag: str) -> subprocess.CompletedProcess:+ """Run an agent-browser CLI argv once, capturing output through temp files (not pipes).++ The CLI forks a resident daemon that inherits its stdio and outlives the CLI, so with+ pipe capture the CLI can exit while its output never reaches EOF: POSIX burns the whole+ timeout draining pipes on every call, and Windows' ``TimeoutExpired`` cleanup re-drains+ with no timeout, blocking past the outer tool deadline (#96731). Same pattern as+ ``_popen_agent_browser``: wait for the CLI alone — a grandchild holding the inherited+ file handles is harmless. Raises ``TimeoutExpired`` after killing the CLI."""+ env, socket_dir = _real_profile_daemon_env()+ stdout_path = os.path.join(socket_dir, f"_stdout_{tag}")+ stderr_path = os.path.join(socket_dir, f"_stderr_{tag}")+ proc = _session._popen_agent_browser(argv, env, socket_dir, tag)+ timed_out = False+ try:+ proc.wait(timeout=timeout)+ except subprocess.TimeoutExpired:+ timed_out = True+ proc.kill()+ proc.wait()+ stdout, stderr = _session._read_command_output_files(stdout_path, stderr_path)+ _session._unlink_command_output_files(stdout_path, stderr_path)+ if timed_out:+ raise subprocess.TimeoutExpired(argv, timeout)+ return subprocess.CompletedProcess(argv, proc.returncode, stdout=stdout, stderr=stderr)def _agent_browser_session_cmd(session_name: str, *cmd: str, log_label: str) -> Optional[subprocess.CompletedProcess]:@@ -57,9 +84,10 @@ def _agent_browser_session_cmd(session_name: str, *cmd: str, log_label: str) ->except FileNotFoundError:return Nonetry:- return subprocess.run([*_session._agent_browser_argv(browser_cmd), "--session", session_name, *cmd],- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15,- env=_real_profile_daemon_env(), stdin=subprocess.DEVNULL)+ return _capture_agent_browser_cli(+ [*_session._agent_browser_argv(browser_cmd), "--session", session_name, *cmd],+ timeout=15, tag=f"rp-{log_label.replace(' ', '-')}",+ )except (subprocess.SubprocessError, OSError) as e:_bt.logger.debug("real-profile %s failed: %s", log_label, e)return None@@ -204,9 +232,9 @@ def _attach_agent_browser_to_real_profile(port: int, copy_dir: str) -> Tuple[Optargv = [*_session._agent_browser_argv(browser_cmd), "--session", _bt._REAL_PROFILE_SESSION,"--cdp", str(port), "open", "about:blank"]try:- proc = subprocess.run(argv, capture_output=True, text=True, encoding="utf-8", errors="replace",- timeout=_bt._get_open_command_timeout(first_open=True), env=_real_profile_daemon_env(),- stdin=subprocess.DEVNULL)+ proc = _capture_agent_browser_cli(+ argv, timeout=_bt._get_open_command_timeout(first_open=True), tag="rp-open",+ )except subprocess.TimeoutExpired:return None, _RP + "the real-profile browser took too long to start. Retry, or turn the toggle off."except (subprocess.SubprocessError, OSError) as e: