The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): bound the Git Bash startup probe's timeout cleanup (#73403)
teknium1edae76fecd30
diff --git a/tests/acp_adapter/test_permissions.py b/tests/acp_adapter/test_permissions.pyindex 625edca505a..8cc4bcbe0b0 100644--- a/tests/acp_adapter/test_permissions.py+++ b/tests/acp_adapter/test_permissions.py@@ -262,3 +262,14 @@ class TestPermissionRequestToolCallReachesATerminalStatus:requested = request_permission.call_args.kwargs["tool_call"]assert decisions == [True]assert [(u.tool_call_id, u.status) for u in sent] == [(requested.tool_call_id, "completed")]+++def test_default_permission_timeout_follows_approvals_config(monkeypatch):+ """No explicit timeout → the ACP bridge waits ``approvals.timeout`` like every other+ surface, instead of a hardcoded 60 s the host cannot raise (#73403)."""+ from acp_adapter import permissions+ from tools import approval_context++ monkeypatch.setattr(approval_context, "_get_approval_config", lambda: {"timeout": 900})+ assert permissions.resolve_permission_timeout(None) == 900.0+ assert permissions.resolve_permission_timeout(0.5) == 0.5diff --git a/tests/tools/test_find_shell.py b/tests/tools/test_find_shell.pyindex 2fb3e31abbc..4b4ec5071ba 100644--- a/tests/tools/test_find_shell.py+++ b/tests/tools/test_find_shell.py@@ -7,7 +7,9 @@ when ``~/.bash_profile`` contained ``exec /bin/zsh -l``.import osimport platform+import shutilimport subprocess+import timefrom unittest.mock import patchimport pytest@@ -15,6 +17,18 @@ import pytestfrom tools.environments.local import _find_bash, _find_shell+def _pid_alive(pid: int) -> bool:+ try:+ import psutil+ return psutil.pid_exists(pid) and psutil.Process(pid).status() != psutil.STATUS_ZOMBIE+ except ImportError:+ try:+ os.kill(pid, 0) # windows-footgun: ok — psutil fallback only on POSIX hosts without it+ except OSError:+ return False+ return True++class TestFindShellPrefersUserShell:"""_find_shell should prefer $SHELL over bash on POSIX."""@@ -138,25 +152,54 @@ class TestGitBashExternalProgramProbe:def test_probe_runs_external_msys_programs(self, monkeypatch):"""``_bash_starts`` builds the same external-program probe argv on- every host, so this stays on the Linux runner with ``subprocess.run``- mocked — no platform faking needed."""- import tools.environments.local as local_mod+ every host and routes it through the deadlock-safe ``bounded_probe_run``+ (own Popen, tree-kill + bounded drain on timeout, ``stdin=DEVNULL`` for+ #78820) — never ``subprocess.run`` whose Windows post-timeout cleanup is an+ unbounded ``communicate()`` (#73403)."""from tools.environments import local_gitbash_probe as gitbash_probegitbash_probe._bash_starts_cache.clear()gitbash_probe._bash_probe_details_cache.clear()calls = []- def fake_run(argv, **kwargs):+ def fake_bounded_run(argv, **kwargs):calls.append((argv, kwargs))return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")- monkeypatch.setattr(local_mod.subprocess, "run", fake_run)+ monkeypatch.setattr(gitbash_probe, "bounded_probe_run", fake_bounded_run)assert gitbash_probe._bash_starts(r"C:\Git\bin\bash.exe") is Trueassert calls[0][0][-1] == "/usr/bin/true; /usr/bin/cat --version >/dev/null"- # #78820: the probe must not inherit the TUI gateway's stdin pipe (MSYS flips it to PIPE_NOWAIT).- assert calls[0][1].get("stdin") is subprocess.DEVNULL+ assert calls[0][1]["timeout"] == gitbash_probe._BASH_PROBE_TIMEOUT++ def test_probe_timeout_is_bounded_and_kills_the_grandchild(self, monkeypatch, tmp_path):+ """A probe whose grandchild keeps the captured pipes open past the timeout+ (the MSYS ``true``/``cat`` shape) returns within the bound, records a+ timeout verdict, and leaves no orphaned pipe-holder behind."""+ from tools.environments import local_gitbash_probe as gitbash_probe++ bash = shutil.which("bash")+ if bash is None:+ pytest.skip("no bash on this host")+ gitbash_probe._bash_starts_cache.clear()+ gitbash_probe._bash_probe_details_cache.clear()+ stamp = tmp_path / "grandchild.pid"+ monkeypatch.setattr(gitbash_probe, "_BASH_PROBE_TIMEOUT", 1.0)+ monkeypatch.setattr(gitbash_probe, "_BASH_EXTERNAL_PROGRAM_PROBE",+ f"sleep 30 & echo $! > '{stamp}'; wait")++ t0 = time.monotonic()+ ok = gitbash_probe._bash_starts(bash)+ elapsed = time.monotonic() - t0++ assert ok is False+ assert elapsed < 8.0, f"probe cleanup took {elapsed:.1f}s — pipe drain not bounded"+ assert "timed out" in gitbash_probe._bash_probe_details_cache[bash]+ grandchild = int(stamp.read_text(encoding="utf-8").strip())+ deadline = time.monotonic() + 3.0+ while time.monotonic() < deadline and _pid_alive(grandchild):+ time.sleep(0.05)+ assert not _pid_alive(grandchild), "grandchild survived the probe's tree-kill"@pytest.mark.windows_onlydef test_aslr_failure_surfaces_targeted_windows_command(diff --git a/tools/environments/local_gitbash_probe.py b/tools/environments/local_gitbash_probe.pyindex ac7dabf27e0..1d54ef19775 100644--- a/tools/environments/local_gitbash_probe.py+++ b/tools/environments/local_gitbash_probe.py@@ -8,7 +8,7 @@ import platformimport shutilimport subprocess-from hermes_cli._subprocess_compat import windows_hide_flags+from hermes_cli._subprocess_compat import bounded_probe_run, windows_hide_flags_IS_WINDOWS = platform.system() == "Windows"@@ -18,6 +18,7 @@ logger = logging.getLogger("tools.environments.local")_bash_starts_cache: dict[str, bool] = {}_bash_probe_details_cache: dict[str, str] = {}_mandatory_aslr_enabled_cache: "bool | None" = None+_BASH_PROBE_TIMEOUT = 15.0# External ``true`` and ``cat`` are intentional: a builtin-only ``exit 0`` probe# misses Git-for-Windows fork/spawn failures under system-wide Mandatory ASLR.@@ -87,14 +88,18 @@ def _bash_starts(bash: str) -> bool:if bash in _bash_starts_cache:return _bash_starts_cache[bash]try:- result = subprocess.run(+ # bounded_probe_run, not subprocess.run: on Windows run()'s post-timeout cleanup is an+ # unbounded communicate(), and the MSYS children of the probe (true/cat) can outlive the+ # killed bash holding the pipe write ends — the ACP host then wedged for minutes (#73403).+ # The probe's tree is killed and the drain bounded, so a slow host fails the probe fast+ # and _find_bash falls through to its last-resort candidate instead of hanging.+ result = bounded_probe_run([bash, "--noprofile", "--norc", "-c", _BASH_EXTERNAL_PROGRAM_PROBE],- capture_output=True, text=True, encoding="utf-8", errors="replace",- timeout=15, creationflags=windows_hide_flags() if _IS_WINDOWS else 0,- stdin=subprocess.DEVNULL) # #78820: never hand the TUI gateway's stdin pipe to MSYS bash- ok = result.returncode == 0+ timeout=_BASH_PROBE_TIMEOUT, raise_on_spawn_failure=True)+ ok = result is not None and result.returncode == 0if not ok:- combined = f"{result.stdout or ''}{result.stderr or ''}".strip()+ combined = (f"{result.stdout or ''}{result.stderr or ''}".strip() if result is not None+ else f"probe timed out after {_BASH_PROBE_TIMEOUT:g}s")_bash_probe_details_cache[bash] = combined[:2000]logger.debug("bash probe failed for %s: %s", bash, combined[:200])except Exception as exc: