The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): bound the Windows stdout drain with PeekNamedPipe (#105865)
joaomarcose7a82eadeda1
diff --git a/tests/tools/test_drain_fd_windows.py b/tests/tools/test_drain_fd_windows.pynew file mode 100644index 00000000000..690d29c986e--- /dev/null+++ b/tests/tools/test_drain_fd_windows.py@@ -0,0 +1,61 @@+"""Windows stdout drain: bounded when a grandchild keeps the pipe's write handle open.++``select()`` cannot poll pipe fds on Windows, so the drain used a blocking+``os.read`` loop that waited for true EOF — a backgrounded grandchild that+inherited the write end kept the terminal tool hung for its whole lifetime.+The ``PeekNamedPipe`` drain mirrors the POSIX ``select`` loop's post-exit bound.+"""++import codecs+import os+import time+from unittest.mock import MagicMock++import pytest++from tools.environments.base_output import _BoundedOutputCollector, _drain_fd_windows++[email protected]_only+def test_drain_fd_windows_returns_promptly_when_writer_remains_open():+ """Data already in the pipe is captured; the drain stops shortly after the+ process reports exit even though the write end is still open."""+ r, w = os.pipe()+ try:+ os.write(w, b"hello from child process\n")+ proc = MagicMock()+ proc.poll.return_value = 0 # bash exited; ``w`` (the grandchild's copy) is still open++ output = _BoundedOutputCollector(1000)+ decoder = codecs.getincrementaldecoder("utf-8")("replace")++ t0 = time.monotonic()+ _drain_fd_windows(proc, r, output, decoder)+ elapsed = time.monotonic() - t0++ assert "hello from child process" in output.render()+ assert elapsed < 2.0, f"drain hung for {elapsed:.2f}s instead of bounding after exit"+ finally:+ os.close(r)+ os.close(w)++[email protected]_only+def test_local_environment_returns_while_background_grandchild_holds_pipe(tmp_path):+ """End-to-end on Git Bash: ``execute()`` returns promptly with the marker while a+ backgrounded grandchild still holds the stdout pipe (issues #105865 / #67362)."""+ from tools.environments.local import LocalEnvironment++ env = LocalEnvironment(cwd=str(tmp_path))+ try:+ marker = "windows_drain_e2e_marker"+ cmd = f'python -c "import time; time.sleep(30)" & echo {marker}'+ t0 = time.monotonic()+ result = env.execute(cmd, timeout=15)+ elapsed = time.monotonic() - t0++ assert elapsed < 10.0, f"LocalEnvironment.execute hung for {elapsed:.2f}s on Windows"+ assert result["returncode"] == 0+ assert marker in result["output"]+ finally:+ env.cleanup()diff --git a/tools/environments/base_output.py b/tools/environments/base_output.pyindex bdd800a6361..a5ceca2432f 100644--- a/tools/environments/base_output.py+++ b/tools/environments/base_output.py@@ -349,7 +349,7 @@ def _drain_stdout(proc: ProcessHandle, output: _BoundedOutputCollector, stop: "t``errors="replace"`` buffers partial sequences across chunks. Streams without a realinteger ``fileno()`` (mocks, in-memory adapters) are iterated to EOF instead — otherwisethe thread would die silently and lose all output. ``select()`` does not work on pipe fds- on Windows, so a blocking ``os.read`` loop is used there.+ on Windows, so :func:`_drain_fd_windows` polls ``PeekNamedPipe`` there instead."""stream = proc.stdoutif stream is None:@@ -379,8 +379,7 @@ def _drain_stdout(proc: ProcessHandle, output: _BoundedOutputCollector, stop: "tif piece is not None:output.append(decoder.decode(piece) if isinstance(piece, bytes) else str(piece))elif os.name == "nt":- while chunk := os.read(fd, 4096):- output.append(decoder.decode(chunk))+ _drain_fd_windows(proc, fd, output, decoder, stop)else:_drain_fd_select(proc, fd, output, decoder, stop)except Exception:@@ -423,6 +422,54 @@ def _drain_fd_select(proc, fd: int, output: _BoundedOutputCollector, decoder, streturn+def _drain_fd_windows(proc, fd: int, output: _BoundedOutputCollector, decoder, stop=None) -> None:+ """Windows drain: poll ``PeekNamedPipe`` because ``select`` cannot poll pipes.++ ``os.read`` on a Windows pipe blocks until data is available or every writer+ closes the pipe. A backgrounded grandchild can retain a writer indefinitely,+ so use the Win32 pipe API to check availability before reading and apply the+ same post-exit idle bound as the POSIX drain.+ """+ import ctypes+ import msvcrt++ try:+ raw_handle = msvcrt.get_osfhandle(fd)+ except OSError:+ return+ if raw_handle in (-1, 0):+ return++ handle = ctypes.c_void_p(raw_handle)+ kernel32 = ctypes.windll.kernel32+ available = ctypes.c_ulong(0)+ idle_after_exit = 0+ while True:+ if stop is not None and stop.is_set():+ return+ try:+ ok = kernel32.PeekNamedPipe(handle, None, 0, None, ctypes.byref(available), None)+ except OSError:+ return+ if not ok:+ return+ if available.value:+ try:+ chunk = os.read(fd, min(int(available.value), 4096))+ except (ValueError, OSError):+ return+ if not chunk:+ return+ output.append(decoder.decode(chunk))+ idle_after_exit = 0+ continue+ if proc.poll() is not None:+ idle_after_exit += 1+ if idle_after_exit >= 3:+ return+ time.sleep(0.1)++def _start_drain_thread(proc: ProcessHandle, output: _BoundedOutputCollector, stop: "threading.Event | None" = None,) -> threading.Thread: