diff --git a/AGENTS.md b/AGENTS.md index ef0b8f1d..fac0de3a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,6 +24,7 @@ what was asked for. | `src/libvt/testing.py` | Zero-dependency `assert_screen`, `assert_screen_box`, `FlightRecorder` diagnostics, and boxed VT + `SGR` `vt_screen` / `serialize_vt_snapshot` / `format_vt_diff_lines` utilities | | `src/libvt/pytest_plugin.py` | Import-light `pytest11` plugin (`libvt[pytest]`): `vt_terminal`, `vt_factory`, `vt_recorder`, `vt_parser`, and `vt_pty` | | `src/libvt/contrib/syrupy.py` | Optional `syrupy` `.ambr` adapter (`libvt[syrupy]`): `VtSnapshotExtension` and conditional `vt_snapshot` `pytest11` hook | +| `src/libvt/contrib/subprocess.py` | Synchronous PTY/ConPTY subprocess driver (`open_terminal`, `run_terminal`, `TerminalProcess`, `VT`, `Capture`, `CompletedTerminal`) | | `tests/` | Functional, property-fuzz, PTY, CLI, and fixture tests organized by module under test | | `docs/` | Sphinx/MyST site: `topics/` (concepts), `api/` (autodoc), `project/` (contributing, releasing, ADRs `0001`–`0010`) | | `scripts/` | Unicode table generator (`generate_ucd.py`) and VT throughput benchmarks (`bench_vt.py`, `benchmark.py`) | diff --git a/CHANGES b/CHANGES index 453a9b1c..a5c3055b 100644 --- a/CHANGES +++ b/CHANGES @@ -8,6 +8,20 @@ _Notes on the upcoming release will go here._ ### What's new +#### Drive terminal processes synchronously (#142) + +{func}`~libvt.contrib.subprocess.open_terminal` opens an interactive child on a +POSIX PTY or Windows ConPTY, returning a +{class}`~libvt.contrib.subprocess.TerminalProcess` handle. Use +{func}`~libvt.contrib.subprocess.run_terminal` to collect a child's exit +status, final viewport, and bounded output in a +{class}`~libvt.contrib.subprocess.CompletedTerminal` result. Both +{class}`~libvt.contrib.subprocess.TerminalProcess` and +{class}`~libvt.contrib.subprocess.Capture` implement +{class}`~libvt.testing.SupportsVtTarget` for +{func}`~libvt.testing.vt_screen` and +{func}`~libvt.testing.serialize_vt_snapshot`. + #### Recorder protocol, target protocol, and state replacement (#203) Pass any {class}`~libvt.recorder.TerminalRecorder` implementation to diff --git a/README.md b/README.md index 15d18be0..19bcdc2d 100644 --- a/README.md +++ b/README.md @@ -239,6 +239,8 @@ styles: (`?2026`). - Encode keyboard, mouse, focus, and paste events according to the active terminal modes. +- Drive [terminal processes](https://libvt.git-pull.com/api/contrib/subprocess/) + synchronously on POSIX or Windows. - Run terminal programs on POSIX PTYs or connect to `asyncio` streams (see the [fzf cookbook][fzf_cookbook] for driving a live picker and verifying Enter, Escape, and Ctrl-C outcomes). diff --git a/docs/api/contrib/index.md b/docs/api/contrib/index.md index 10ab0f4f..8948cd2c 100644 --- a/docs/api/contrib/index.md +++ b/docs/api/contrib/index.md @@ -12,6 +12,12 @@ Decoupled `tmux` profiles, `capture-pane` decoders, multi-pane window compositing, and `-C` / `-CC` control-mode synchronization. ::: +:::{grid-item-card} `libvt.contrib.subprocess` +:link: subprocess +:link-type: doc +Synchronous child processes on POSIX PTYs and Windows ConPTY. +::: + :::{grid-item-card} `libvt.contrib.syrupy` :link: syrupy :link-type: doc @@ -30,5 +36,6 @@ fixture (`libvt[syrupy]`). :maxdepth: 2 tmux/index +subprocess syrupy ``` diff --git a/docs/api/contrib/subprocess.md b/docs/api/contrib/subprocess.md new file mode 100644 index 00000000..358027d5 --- /dev/null +++ b/docs/api/contrib/subprocess.md @@ -0,0 +1,125 @@ +# `libvt.contrib.subprocess` + +Use {mod}`libvt.contrib.subprocess` to drive a terminal application from +synchronous Python. The session reads merged terminal output in a background +thread while your caller waits for text, sends input, drains backpressure, or +resizes the viewport. + +```python +>>> import sys +>>> from libvt.contrib import subprocess as sp +>>> command = [ +... sys.executable, +... "-u", +... "-c", +... "print('Ready'); print('Result:', input()[::-1])", +... ] +>>> try: +... with sp.open_terminal(command, vt=sp.VT(rows=6, cols=40)) as child: +... _ = child.wait_for("Ready", timeout=8) +... child.resize(rows=8, cols=48) +... child.paste("pear") +... child.send_key("enter") +... status = child.wait(timeout=8) +... final = child.wait_eof(timeout=8) +... assert (status, final.snapshot.lines[2]) == (0, "Result: raep") +... except NotImplementedError: +... pass +``` + +For commands that finish on their own, call +{func}`~libvt.contrib.subprocess.run_terminal` with a +{class}`~libvt.contrib.subprocess.VT` geometry configuration and pass the +returned {class}`~libvt.contrib.subprocess.CompletedTerminal` directly to +{func}`~libvt.testing.vt_screen` or +{func}`~libvt.testing.serialize_vt_snapshot`: + +```python +>>> import sys +>>> from libvt.contrib import subprocess as sp +>>> from libvt.testing import serialize_vt_snapshot +>>> try: +... done = sp.run_terminal( +... [sys.executable, "-c", "print('OK')"], +... vt=sp.VT(rows=2, cols=8), +... check=True, +... timeout=8, +... ) +... assert "│OK │" in serialize_vt_snapshot(done) +... except NotImplementedError: +... pass +``` + +## Waiting, timeouts, and EOF + +{meth}`~libvt.contrib.subprocess.TerminalProcess.wait` returns the direct +child's exit status. Use +{meth}`~libvt.contrib.subprocess.TerminalProcess.wait_eof` to collect final +output after every process attached to the terminal closes its terminal +handles, since descendants can keep the terminal open after the direct child +exits. {meth}`~libvt.contrib.subprocess.TerminalProcess.drain` waits until all +queued outbound bytes flush to the terminal. Each of `wait()`, `wait_eof()`, +and `drain()` leaves the live handle open on timeout. + +Two distinct timeout exception families apply depending on which call timed +out; catching only builtin {exc}`TimeoutError` misses +{exc}`~libvt.contrib.subprocess.TerminalTimeoutExpired`: + +| Call | Timeout exception | Base classes | Failure detail | +| --- | --- | --- | --- | +| {meth}`~libvt.contrib.subprocess.TerminalProcess.wait_for` | {exc}`~libvt.exc.TerminalTimeoutError` | {exc}`TimeoutError`, {exc}`~libvt.exc.LibVtError` | Check `.eof` to distinguish an unmet predicate at terminal EOF from deadline expiry. | +| {meth}`~libvt.contrib.subprocess.TerminalProcess.wait`, {meth}`~libvt.contrib.subprocess.TerminalProcess.wait_eof`, {meth}`~libvt.contrib.subprocess.TerminalProcess.drain`, {func}`~libvt.contrib.subprocess.run_terminal` | {exc}`~libvt.contrib.subprocess.TerminalTimeoutExpired` | {exc}`subprocess.TimeoutExpired`, {exc}`~libvt.exc.LibVtError` | Inspect `.phase` (`"drain"`, `"process"`, or `"eof"`) and `.capture`. | + +{func}`~libvt.contrib.subprocess.run_terminal` waits for outbound input drain, +child exit, and terminal EOF under a shared timeout. When `check=True` and the +direct child exits nonzero, it raises +{exc}`~libvt.contrib.subprocess.CalledTerminalError` (exposing `.result`). On +timeout, it closes the terminal and reaps the direct child before raising +{exc}`~libvt.contrib.subprocess.TerminalTimeoutExpired`. Interactive commands +that wait for a prompt work with +{func}`~libvt.contrib.subprocess.open_terminal`. + +## Snapshots and output retention + +Use a live {class}`~libvt.contrib.subprocess.TerminalProcess` handle from its +creating thread and close it via `with` or +{meth}`~libvt.contrib.subprocess.TerminalProcess.close`. Call `wait_eof()` +first when descendant output matters. +{class}`~libvt.contrib.subprocess.Capture`, +{class}`~libvt.contrib.subprocess.CompletedTerminal`, and +{class}`~libvt.contrib.subprocess.TerminalProcess` implement +{class}`~libvt.testing.SupportsVtTarget`, so +{func}`~libvt.testing.vt_screen` and +{func}`~libvt.testing.serialize_vt_snapshot` accept them directly. + +Each capture holds the last committed {class}`~libvt.snapshot.Snapshot`, the +bounded `raw_tail` (up to `VT.raw_limit`; `0` disables tail retention while +still counting `raw_total`), and whether EOF was reached. Raw bytes include +terminal control sequences and native console translation. + +## Platform notes + +- **Linux / POSIX PTY**: `close()` escalates `SIGHUP`, `SIGTERM`, and `SIGKILL` + to the child process group. A descendant that ignores hangup can outlive the + terminal after the direct child exits. +- **macOS (Darwin)**: A single-trampoline helper owns the controlling PTY + session over a socketpair so direct-child exit leaves the terminal open for + descendants; `close()` terminates the direct child with `SIGKILL` and shuts + down the session leader. Opening `/dev/tty` can hold a Darwin kernel + reference until the session closes (see + [Apple's controlling-terminal driver](https://github.com/apple-oss-distributions/xnu/blob/f6217f891ac0bb64f3d375211650a4c1ff8ca1ea/bsd/kern/tty_tty.c)); + call `close()` once you have collected the output you need. +- **Windows (ConPTY)**: Requires `ReleasePseudoConsole` (Windows 11 24H2 or + Windows Server 2025, build 26100; see + [Microsoft's ReleasePseudoConsole documentation](https://learn.microsoft.com/en-us/windows/console/releasepseudoconsole)) + to observe natural EOF after the last console client exits. `close()` + terminates the child via `TerminateProcess` and closes the pseudoconsole. + Pass an absolute executable path for consistent executable lookup across + operating systems. + +## API reference + +```{eval-rst} +.. automodule:: libvt.contrib.subprocess + :members: +``` diff --git a/docs/api/index.md b/docs/api/index.md index ffb8f192..89e8f9ed 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -92,6 +92,12 @@ Import-light `vt_terminal`, `vt_factory`, `vt_recorder`, `vt_parser`, and Decoupled `tmux` `profile`, `capture`, `window`, and `control` submodules. ::: +:::{grid-item-card} `libvt.contrib.subprocess` +:link: contrib/subprocess +:link-type: doc +Synchronous child processes on POSIX PTYs and Windows ConPTY. +::: + :::{grid-item-card} `libvt.contrib.syrupy` :link: contrib/syrupy :link-type: doc diff --git a/docs/project/public-api.md b/docs/project/public-api.md index 923252f7..977ee471 100644 --- a/docs/project/public-api.md +++ b/docs/project/public-api.md @@ -45,6 +45,10 @@ Import specialized types and helpers from their owning submodules: {mod}`~libvt.contrib.tmux.control`) — decoupled `tmux` inner-pane profiles, `capture-pane` decoders, multi-pane window compositing, and `-C` / `-CC` control-mode parser and pane sync +- {mod}`libvt.contrib.subprocess` — synchronous child processes with + {func}`~libvt.contrib.subprocess.open_terminal` and + {func}`~libvt.contrib.subprocess.run_terminal` on POSIX PTYs and Windows + ConPTY - {mod}`libvt.contrib.syrupy` — optional `syrupy` `.ambr` adapter (`libvt[syrupy]`): {class}`~libvt.contrib.syrupy.VtSnapshotExtension` and conditional {fixture}`vt_snapshot` `pytest11` fixture diff --git a/docs/topics/architecture.md b/docs/topics/architecture.md index 55f8e164..77b0c4b7 100644 --- a/docs/topics/architecture.md +++ b/docs/topics/architecture.md @@ -43,8 +43,10 @@ fixture body when a test requests it. Import `libvt.aio`, `libvt.testing`, and peer integrations under `libvt.contrib` separately when needed. Importing `libvt.aio` loads `asyncio` and `libvt.terminal`, while POSIX `pty` and `termios` load inside {func}`~libvt.aio.open_pty`. Under `libvt.contrib`, -{mod}`libvt.contrib.tmux` resolves its re-exports lazily, and -{mod}`libvt.contrib.syrupy` defers importing `syrupy` and `libvt.testing`. +{mod}`libvt.contrib.tmux` resolves its re-exports lazily, +{mod}`libvt.contrib.syrupy` defers importing `syrupy` and `libvt.testing`, and +{mod}`libvt.contrib.subprocess` loads platform-specific PTY or ConPTY backends +only when a terminal process is opened. ## Configuration diff --git a/src/libvt/aio/_pty.py b/src/libvt/aio/_pty.py index 79568736..22aa411e 100644 --- a/src/libvt/aio/_pty.py +++ b/src/libvt/aio/_pty.py @@ -321,6 +321,11 @@ async def _wait_for_frame(self, wait_slice: float) -> None: with contextlib.suppress(TimeoutError): await asyncio.wait_for(self._frame_event.wait(), timeout=wait_slice) + def _start_reading(self, loop: asyncio.AbstractEventLoop) -> None: + self._loop = loop + loop.add_reader(self._master_fd, self._on_readable) + self._reader_registered = True + def _remove_reader(self) -> None: if self._loop is not None and self._reader_registered: self._reader_registered = False @@ -678,6 +683,89 @@ async def _close_pty(self) -> int: return self.process.returncode or 0 +def _resolve_python_executable( + python_executable: str | os.PathLike[str] | None, + *, + caller: str = "open_pty", +) -> str: + if python_executable is None: + if getattr(sys, "frozen", False) or not sys.executable: + msg = ( + f"{caller} requires python_executable in frozen or embedded " + "Python runtimes" + ) + raise RuntimeError(msg) + return sys.executable + return os.fspath(python_executable) + + +def _make_pty_terminal( + *, + rows: int, + cols: int, + scrollback: int, + profile: Profile, + policy: Policy, + limits: Limits, + encoding: ParserEncoding = "utf-8", + record_events: bool = False, +) -> Terminal: + recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) + eff_policy = policy + if policy.osc7_hosts is None: + fqdn = socket.gethostname().lower() + short = fqdn.partition(".")[0] + eff_policy = dataclasses.replace( + policy, + osc7_hosts=DEFAULT_OSC7_HOSTS | frozenset({fqdn, short}), + ) + return Terminal( + rows=rows, + cols=cols, + scrollback=scrollback, + profile=profile, + policy=eff_policy, + limits=limits, + encoding=encoding, + record_events=record_events, + recorder=recorder, + ) + + +def _prepare_pty_fds( + master_fd: int, + slave_fd: int, + *, + rows: int, + cols: int, + profile: Profile, + tty_mode: TtyMode = "cooked", +) -> None: + if sys.platform == "win32": + msg = "POSIX PTY setup requires termios" + raise NotImplementedError(msg) + import fcntl + import termios + import tty + + fcntl.ioctl( + slave_fd, + termios.TIOCSWINSZ, + _pack_winsize(rows, cols, profile), + ) + if tty_mode == "cbreak": + tty.setcbreak(slave_fd) + elif tty_mode == "raw": + tty.setraw(slave_fd) + os.set_blocking(master_fd, False) + + +def _child_pty_env(env: collections.abc.Mapping[str, str] | None) -> dict[str, str]: + child_env = dict(os.environ if env is None else env) + child_env.setdefault("TERM", "xterm-256color") + return child_env + + @contextlib.asynccontextmanager async def open_pty( argv: collections.abc.Sequence[str], @@ -778,44 +866,19 @@ async def open_pty( raise ValueError(msg) _validate_nonneg_seconds(sync_timeout, "sync_timeout") eff_hw, eff_max = _resolve_write_limits(write_high_water, max_write_buffer) - recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) - - if python_executable is None: - if getattr(sys, "frozen", False) or not sys.executable: - msg = ( - "open_pty requires python_executable in frozen or embedded " - "Python runtimes" - ) - raise RuntimeError(msg) - py_bin = sys.executable - else: - py_bin = os.fspath(python_executable) - - eff_policy = policy - if policy.osc7_hosts is None: - fqdn = socket.gethostname().lower() - short = fqdn.partition(".")[0] - eff_policy = dataclasses.replace( - policy, - osc7_hosts=DEFAULT_OSC7_HOSTS | frozenset({fqdn, short}), - ) - - terminal = Terminal( + py_bin = _resolve_python_executable(python_executable, caller="open_pty") + terminal = _make_pty_terminal( rows=rows, cols=cols, scrollback=scrollback, profile=profile, - policy=eff_policy, + policy=policy, limits=limits, encoding=encoding, record_events=record_events, - recorder=recorder, ) - import fcntl import pty - import termios - import tty loop = asyncio.get_running_loop() master_fd, slave_fd = pty.openpty() @@ -827,19 +890,16 @@ async def open_pty( proc: asyncio.subprocess.Process | None = None try: receiver, sender = socket.socketpair() - fcntl.ioctl( + _prepare_pty_fds( + master_fd, slave_fd, - termios.TIOCSWINSZ, - _pack_winsize(rows, cols, profile), + rows=rows, + cols=cols, + profile=profile, + tty_mode=tty_mode, ) - if tty_mode == "cbreak": - tty.setcbreak(slave_fd) - elif tty_mode == "raw": - tty.setraw(slave_fd) - os.set_blocking(master_fd, False) receiver.setblocking(False) - child_env = dict(os.environ if env is None else env) - child_env.setdefault("TERM", "xterm-256color") + child_env = _child_pty_env(env) launch_fd = sender.fileno() proc = await asyncio.create_subprocess_exec( py_bin, @@ -900,8 +960,7 @@ async def open_pty( os.close(master_fd) try: - loop.add_reader(master_fd, session._on_readable) - session._reader_registered = True + session._start_reading(loop) yield session finally: await session.aclose() diff --git a/src/libvt/contrib/_conpty.py b/src/libvt/contrib/_conpty.py new file mode 100644 index 00000000..bba23107 --- /dev/null +++ b/src/libvt/contrib/_conpty.py @@ -0,0 +1,381 @@ +"""Attach a Win32 console client and adapt its pseudoconsole pipes to libvt.""" + +from __future__ import annotations + +import asyncio +import collections.abc +import contextlib +import ctypes as c +import ctypes.wintypes as w +import subprocess +import sys +import threading +import time + +from libvt.aio import AsyncTerminalStream +from libvt.aio._pty import _make_pty_terminal +from libvt.config import DEFAULT_POLICY, DEFAULT_PROFILE, Limits + +from .subprocess import VT, _Attachment + +if sys.platform == "win32": + + class Coord(c.Structure): + _fields_ = [("X", w.SHORT), ("Y", w.SHORT)] + + class StartupInfo(c.Structure): + _fields_ = [ + ("cb", w.DWORD), + ("lpReserved", w.LPWSTR), + ("lpDesktop", w.LPWSTR), + ("lpTitle", w.LPWSTR), + ("dwX", w.DWORD), + ("dwY", w.DWORD), + ("dwXSize", w.DWORD), + ("dwYSize", w.DWORD), + ("dwXCountChars", w.DWORD), + ("dwYCountChars", w.DWORD), + ("dwFillAttribute", w.DWORD), + ("dwFlags", w.DWORD), + ("wShowWindow", w.WORD), + ("cbReserved2", w.WORD), + ("lpReserved2", c.c_void_p), + ("hStdInput", w.HANDLE), + ("hStdOutput", w.HANDLE), + ("hStdError", w.HANDLE), + ] + + class StartupInfoEx(c.Structure): + _fields_ = [("StartupInfo", StartupInfo), ("lpAttributeList", c.c_void_p)] + + class ProcessInfo(c.Structure): + _fields_ = [ + ("hProcess", w.HANDLE), + ("hThread", w.HANDLE), + ("pid", w.DWORD), + ("tid", w.DWORD), + ] + + class _Kernel: + def __init__(self) -> None: + self.error = c.WinError + self.last_error = c.get_last_error + kernel = c.WinDLL("kernel32", use_last_error=True) + + try: + self.release_console = kernel["ReleasePseudoConsole"] + except AttributeError as exc: + msg = "ConPTY EOF requires ReleasePseudoConsole (Windows build 26100)" + raise NotImplementedError(msg) from exc + self.release_console.restype = w.LONG + self.release_console.argtypes = (w.HANDLE,) + + self.create_console = kernel["CreatePseudoConsole"] + self.create_console.restype = w.LONG + self.create_console.argtypes = ( + Coord, + w.HANDLE, + w.HANDLE, + w.DWORD, + c.POINTER(w.HANDLE), + ) + + self.resize_console = kernel["ResizePseudoConsole"] + self.resize_console.restype = w.LONG + self.resize_console.argtypes = (w.HANDLE, Coord) + + self.close_console = kernel["ClosePseudoConsole"] + self.close_console.restype = None + self.close_console.argtypes = (w.HANDLE,) + + self.init_attrs = kernel["InitializeProcThreadAttributeList"] + self.init_attrs.restype = w.BOOL + self.init_attrs.argtypes = ( + c.c_void_p, + w.DWORD, + w.DWORD, + c.POINTER(c.c_size_t), + ) + + self.update_attr = kernel["UpdateProcThreadAttribute"] + self.update_attr.restype = w.BOOL + self.update_attr.argtypes = ( + c.c_void_p, + w.DWORD, + c.c_size_t, + c.c_void_p, + c.c_size_t, + c.c_void_p, + c.c_void_p, + ) + + self.delete_attrs = kernel["DeleteProcThreadAttributeList"] + self.delete_attrs.restype = None + self.delete_attrs.argtypes = (c.c_void_p,) + + self.create_process = kernel["CreateProcessW"] + self.create_process.restype = w.BOOL + self.create_process.argtypes = ( + w.LPCWSTR, + w.LPWSTR, + c.c_void_p, + c.c_void_p, + w.BOOL, + w.DWORD, + c.c_void_p, + w.LPCWSTR, + c.POINTER(StartupInfoEx), + c.POINTER(ProcessInfo), + ) + + self.wait_handle = kernel["WaitForSingleObject"] + self.wait_handle.restype = w.DWORD + self.wait_handle.argtypes = (w.HANDLE, w.DWORD) + + self.get_exit = kernel["GetExitCodeProcess"] + self.get_exit.restype = w.BOOL + self.get_exit.argtypes = (w.HANDLE, c.POINTER(w.DWORD)) + + self.terminate = kernel["TerminateProcess"] + self.terminate.restype = w.BOOL + self.terminate.argtypes = (w.HANDLE, w.UINT) + + self.close_handle = kernel["CloseHandle"] + self.close_handle.restype = w.BOOL + self.close_handle.argtypes = (w.HANDLE,) + + def check(self, value: int) -> None: + if not value: + raise self.error(self.last_error()) + + def hr_ok(value: int, name: str) -> None: + if value < 0: + msg = f"{name} failed with HRESULT 0x{value & 0xFFFFFFFF:08x}" + raise OSError(msg) + + def attach( + api: _Kernel, + console: w.HANDLE, + args: tuple[str, ...], + cwd: str | None, + env: dict[str, str] | None, + ) -> ProcessInfo: + size = c.c_size_t() + if api.init_attrs(None, 1, 0, c.byref(size)) or api.last_error() != 122: + msg = "could not size the Win32 startup attributes" + raise RuntimeError(msg) + storage = c.create_string_buffer(size.value) + api.check(api.init_attrs(storage, 1, 0, c.byref(size))) + try: + # PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE points directly at the HPCON. + api.check( + api.update_attr( + storage, 0, 0x00020016, console, c.sizeof(w.HANDLE), None, None + ) + ) + startup = StartupInfoEx() + startup.StartupInfo.cb = c.sizeof(startup) + # Null standard handles here let the new console supply all three even + # when the controller's own standard streams have been redirected. + startup.StartupInfo.dwFlags = 0x100 # STARTF_USESTDHANDLES + startup.lpAttributeList = c.addressof(storage) + environment = None + flags = 0x00080000 # EXTENDED_STARTUPINFO_PRESENT + if env is not None: + flags |= 0x400 # CREATE_UNICODE_ENVIRONMENT + pairs = sorted(env.items(), key=lambda pair: pair[0].upper()) + environment = c.create_unicode_buffer( + "\0".join(f"{k}={v}" for k, v in pairs) + "\0" + ) + info = ProcessInfo() + command = c.create_unicode_buffer(subprocess.list2cmdline(args)) + api.check( + api.create_process( + None, + command, + None, + None, + False, + flags, + environment, + cwd, + c.byref(startup), + c.byref(info), + ) + ) + return info + finally: + api.delete_attrs(storage) + + def _run_in_daemon_thread[T]( + loop: asyncio.AbstractEventLoop, + fn: collections.abc.Callable[[], T], + *, + name: str, + ) -> asyncio.Future[T]: + future: asyncio.Future[T] = loop.create_future() + + def _set_result(value: T) -> None: + if not future.done(): + future.set_result(value) + + def _set_exception(exc: BaseException) -> None: + if not future.done(): + future.set_exception(exc) + + def _worker() -> None: + try: + value = fn() + except BaseException as exc: # noqa: BLE001 - relay worker exception + with contextlib.suppress(RuntimeError): + loop.call_soon_threadsafe(_set_exception, exc) + else: + with contextlib.suppress(RuntimeError): + loop.call_soon_threadsafe(_set_result, value) + + threading.Thread(target=_worker, name=name, daemon=True).start() + return future + + class WinChild: + def __init__(self, api: _Kernel, info: ProcessInfo) -> None: + self._api = api + self.pid = info.pid + self._handle = info.hProcess + self._termination_requested = False + try: + self._api.check(self._api.close_handle(info.hThread)) + self._exit = _run_in_daemon_thread( + asyncio.get_running_loop(), + self._wait_handle, + name="libvt-conpty-wait", + ) + except BaseException: + self._api.close_handle(self._handle) + raise + + def _wait_handle(self) -> int: + if self._api.wait_handle(self._handle, 0xFFFFFFFF) != 0: + raise self._api.error(self._api.last_error()) + status = w.DWORD() + self._api.check(self._api.get_exit(self._handle, c.byref(status))) + return status.value + + @property + def returncode(self) -> int | None: + return self._exit.result() if self._exit.done() else None + + async def wait(self) -> int: + return await asyncio.shield(self._exit) + + def kill(self) -> None: + if ( + self._termination_requested + or self._api.wait_handle(self._handle, 0) == 0 + ): + return + if self._api.terminate(self._handle, 1): + # TerminateProcess returns before the handle necessarily signals. + self._termination_requested = True + else: + error = self._api.last_error() + if self._api.wait_handle(self._handle, 0) != 0: + raise self._api.error(error) + + async def close(self) -> None: + try: + self.kill() + finally: + try: + await self.wait() + finally: + if self._exit.done(): + self._api.check(self._api.close_handle(self._handle)) + + @contextlib.asynccontextmanager + async def open_conpty( + args: tuple[str, ...], options: VT, cwd: str | None, env: dict[str, str] | None + ) -> collections.abc.AsyncGenerator[_Attachment]: + import asyncio.windows_utils as winpipes + + api = _Kernel() + + def pipe( + stack: contextlib.AsyncExitStack, *, input_pipe: bool + ) -> tuple[winpipes.PipeHandle, winpipes.PipeHandle]: + # The two ConPTY ends use synchronous I/O. The host's overlapped ends + # let the Proactor drain output even while an input write is stalled. + read, write = winpipes.pipe( + duplex=input_pipe, overlapped=(not input_pipe, input_pipe) + ) + return ( + stack.enter_context(winpipes.PipeHandle(read)), + stack.enter_context(winpipes.PipeHandle(write)), + ) + + loop = asyncio.get_running_loop() + async with contextlib.AsyncExitStack() as stack: + con_in, host_out = pipe(stack, input_pipe=True) + host_in, con_out = pipe(stack, input_pipe=False) + reader = asyncio.StreamReader() + read_transport, _ = await loop.connect_read_pipe( + lambda: asyncio.StreamReaderProtocol(reader), host_in + ) + stack.callback(read_transport.close) + write_protocol = asyncio.StreamReaderProtocol(asyncio.StreamReader()) + write_transport, _ = await loop.connect_write_pipe( + lambda: write_protocol, host_out + ) + stack.callback(write_transport.close) + writer = asyncio.StreamWriter(write_transport, write_protocol, None, loop) + term = _make_pty_terminal( + rows=options.rows, + cols=options.cols, + scrollback=options.scrollback, + profile=DEFAULT_PROFILE, + policy=DEFAULT_POLICY, + limits=Limits(max_recorder_bytes=options.raw_limit), + ) + stream = AsyncTerminalStream(reader, writer, terminal=term) + pump = stream.start() + stack.push_async_callback(stream.aclose) + + console = w.HANDLE() + hr_ok( + api.create_console( + Coord(options.cols, options.rows), + con_in.fileno(), + con_out.fileno(), + 0, + c.byref(console), + ), + "CreatePseudoConsole", + ) + + async def finish_output() -> None: + await _run_in_daemon_thread( + loop, + lambda: api.close_console(console), + name="libvt-conpty-close", + ) + await asyncio.wait_for(asyncio.shield(pump), timeout=8) + term.notify_process_exit() + + stack.push_async_callback(finish_output) + try: + process = WinChild(api, attach(api, console, args, cwd, env)) + stack.push_async_callback(process.close) + hr_ok(api.release_console(console), "ReleasePseudoConsole") + finally: + con_in.close() + con_out.close() + + def resize(*, rows: int, cols: int) -> None: + hr_ok( + api.resize_console(console, Coord(cols, rows)), + "ResizePseudoConsole", + ) + term.resize(rows=rows, cols=cols) + stream._flush_terminal_replies() + stream._update_sync_timer(time.monotonic()) + + yield _Attachment(stream, process, resize) diff --git a/src/libvt/contrib/_darwin_pty.py b/src/libvt/contrib/_darwin_pty.py new file mode 100644 index 00000000..09f28165 --- /dev/null +++ b/src/libvt/contrib/_darwin_pty.py @@ -0,0 +1,303 @@ +"""Keep the controlling PTY session alive until the terminal closes.""" + +from __future__ import annotations + +import asyncio +import collections.abc +import contextlib +import errno +import os +import signal +import socket +import sys +import typing as t + +from libvt._util import _parse_ascii_int, _parse_ascii_uint +from libvt.aio._pty import ( + PtySession, + _child_pty_env, + _make_pty_terminal, + _prepare_pty_fds, + _resolve_python_executable, +) +from libvt.config import DEFAULT_POLICY, DEFAULT_PROFILE, Limits + +from .subprocess import VT, _Attachment + +# XNU revokes the slave's open descriptors when its session leader exits. +# This single trampoline becomes the session leader, acquires the controlling +# terminal, spawns the command, drops its own slave descriptors so native PTY +# EOF tracks terminal users, and relays child PID/exit over a socketpair. +_DARWIN_LEADER = ( + "stage = 'bootstrap'\n" + "control = None\n" + "child = None\n" + "try:\n" + " import errno, fcntl, os, signal, socket, subprocess, sys, termios, threading\n" + " control_fd = int(sys.argv[1])\n" + " os.set_inheritable(control_fd, False)\n" + " control = socket.socket(fileno=control_fd)\n" + " stage = 'ctty'\n" + " if hasattr(termios, 'TIOCSCTTY'):\n" + " fcntl.ioctl(0, termios.TIOCSCTTY, 0)\n" + " stage = 'signal'\n" + " signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n" + " if hasattr(signal, 'SIGXFSZ'):\n" + " signal.signal(signal.SIGXFSZ, signal.SIG_DFL)\n" + " stage = 'exec'\n" + " child = subprocess.Popen(sys.argv[2:])\n" + " for sig in (signal.SIGINT, signal.SIGQUIT, signal.SIGTSTP):\n" + " signal.signal(sig, signal.SIG_IGN)\n" + " null_fd = os.open(os.devnull, os.O_RDWR)\n" + " try:\n" + " for fd in (0, 1, 2):\n" + " os.dup2(null_fd, fd)\n" + " finally:\n" + " if null_fd > 2:\n" + " os.close(null_fd)\n" + " def receive():\n" + " while True:\n" + " try:\n" + " command = control.recv(1)\n" + " except OSError:\n" + " command = b''\n" + " if command in (b'K', b''):\n" + " try:\n" + " child.kill()\n" + " except OSError:\n" + " pass\n" + " if not command:\n" + " return\n" + " control.sendall(f'pid {child.pid}\\n'.encode())\n" + " watcher = threading.Thread(target=receive, daemon=True)\n" + " watcher.start()\n" + " try:\n" + " control.sendall(f'exit {child.wait()}\\n'.encode())\n" + " except OSError:\n" + " pass\n" + " watcher.join()\n" + "except BaseException as exc:\n" + " if child is not None:\n" + " try:\n" + " child.kill()\n" + " child.wait()\n" + " except BaseException:\n" + " pass\n" + " try:\n" + " import errno as _e\n" + " if control is not None:\n" + " code = getattr(exc, 'errno', None)\n" + " if not isinstance(code, int):\n" + " code = _e.ENOEXEC\n" + " msg = (\n" + " (getattr(exc, 'strerror', None) or str(exc))\n" + " .replace('\\r', ' ')\n" + " .replace('\\n', ' ')[:360]\n" + " )\n" + " control.sendall(\n" + " f'error {stage} {code} {msg}\\n'.encode('utf-8', 'replace')\n" + " )\n" + " except BaseException:\n" + " pass\n" + " import os as _os\n" + " _os._exit(127)\n" + "finally:\n" + " if control is not None:\n" + " control.close()\n" +) + + +async def _read_message(reader: asyncio.StreamReader) -> tuple[bytes, bytes]: + line = await reader.readline() + tag, _, rest = line.rstrip(b"\r\n").partition(b" ") + if not tag: + msg = "PTY session leader exited before reporting child status" + raise RuntimeError(msg) + return tag, rest + + +def _raise_leader_error(payload: bytes, cmd: str) -> t.NoReturn: + parts = payload.decode("utf-8", "replace").split(" ", 2) + if len(parts) >= 2: + stage, code_s = parts[0], parts[1] + err_msg = parts[2] if len(parts) == 3 else "" + else: + stage, code_s, err_msg = "exec", "", payload.decode("utf-8", "replace") + parsed_err = _parse_ascii_uint(code_s, max_val=65_535) + err_no = errno.ENOEXEC if parsed_err is None else parsed_err + target = cmd if stage == "exec" else f"open_darwin_pty({stage})" + raise OSError(err_no, err_msg or os.strerror(err_no), target) + + +def _parse_child_pid(tag: bytes, rest: bytes) -> int: + if tag != b"pid": + msg = "PTY session leader did not report a child PID" + raise RuntimeError(msg) + child_pid = _parse_ascii_uint( + rest.decode("ascii", "replace"), max_val=2_147_483_647 + ) + if child_pid is None or child_pid <= 0: + msg = "PTY session leader reported an invalid child PID" + raise RuntimeError(msg) + return child_pid + + +class _Command: + def __init__( + self, pid: int, reader: asyncio.StreamReader, writer: asyncio.StreamWriter + ) -> None: + self.pid = pid + self._writer = writer + self._exit = asyncio.create_task(self._wait_child(reader)) + + @staticmethod + async def _wait_child(reader: asyncio.StreamReader) -> int: + kind, data = await _read_message(reader) + if kind != b"exit": + msg = "PTY session leader reported an unexpected child status" + raise RuntimeError(msg) + code = _parse_ascii_int( + data.decode("ascii", "replace"), min_val=-65_535, max_val=65_535 + ) + if code is None: + msg = "PTY session leader reported an invalid child exit status" + raise RuntimeError(msg) + return code + + @property + def returncode(self) -> int | None: + return self._exit.result() if self._exit.done() else None + + async def wait(self) -> int: + return await asyncio.shield(self._exit) + + def kill(self) -> None: + if not self._exit.done() and not self._writer.is_closing(): + self._writer.write(b"K") + + +@contextlib.asynccontextmanager +async def open_darwin_pty( + args: tuple[str, ...], options: VT, cwd: str | None, env: dict[str, str] | None +) -> collections.abc.AsyncGenerator[_Attachment]: + """Launch the command under a single-trampoline POSIX PTY session owner.""" + if sys.platform == "win32": + msg = "open_darwin_pty requires POSIX pty.openpty()" + raise NotImplementedError(msg) + + import pty + + py_bin = _resolve_python_executable(None, caller="open_darwin_pty") + limits = Limits(max_recorder_bytes=options.raw_limit) + terminal = _make_pty_terminal( + rows=options.rows, + cols=options.cols, + scrollback=options.scrollback, + profile=DEFAULT_PROFILE, + policy=DEFAULT_POLICY, + limits=limits, + ) + + loop = asyncio.get_running_loop() + master_fd, slave_fd = pty.openpty() + parent_sock: socket.socket | None = None + child_sock: socket.socket | None = None + writer: asyncio.StreamWriter | None = None + slave_closed = False + master_handed_off = False + proc: asyncio.subprocess.Process | None = None + try: + parent_sock, child_sock = socket.socketpair() + _prepare_pty_fds( + master_fd, + slave_fd, + rows=options.rows, + cols=options.cols, + profile=DEFAULT_PROFILE, + ) + child_env = _child_pty_env(env) + control_fd = child_sock.fileno() + proc = await asyncio.create_subprocess_exec( + py_bin, + "-I", + "-S", + "-c", + _DARWIN_LEADER, + str(control_fd), + *args, + stdin=slave_fd, + stdout=slave_fd, + stderr=slave_fd, + cwd=cwd, + env=child_env, + start_new_session=True, + pass_fds=(control_fd,), + close_fds=True, + ) + os.close(slave_fd) + slave_closed = True + child_sock.close() + child_sock = None + + reader, writer = await asyncio.open_connection(sock=parent_sock) + parent_sock = None + + tag, rest = await _read_message(reader) + if tag == b"error": + await proc.wait() + _raise_leader_error(rest, args[0]) + child_pid = _parse_child_pid(tag, rest) + + session = PtySession( + master_fd=master_fd, + process=proc, + terminal=terminal, + write_high_water=0, + ) + session._loop = loop + master_handed_off = True + except BaseException: + if writer is not None: + writer.close() + with contextlib.suppress(OSError): + await writer.wait_closed() + writer = None + if proc is not None: + if proc.returncode is None: + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGKILL) + with contextlib.suppress(ProcessLookupError): + proc.kill() + await proc.wait() + raise + finally: + if not slave_closed: + with contextlib.suppress(OSError): + os.close(slave_fd) + if child_sock is not None: + child_sock.close() + if parent_sock is not None: + parent_sock.close() + if not master_handed_off: + with contextlib.suppress(OSError): + os.close(master_fd) + + try: + session._start_reading(loop) + child = _Command(child_pid, reader, writer) + try: + yield _Attachment(session, child, session.resize) + finally: + try: + child.kill() + await child.wait() + finally: + if not child._exit.done(): + child._exit.cancel() + with contextlib.suppress(BaseException): + await child._exit + writer.close() + with contextlib.suppress(OSError): + await writer.wait_closed() + finally: + await session.aclose() diff --git a/src/libvt/contrib/subprocess.py b/src/libvt/contrib/subprocess.py new file mode 100644 index 00000000..a6977031 --- /dev/null +++ b/src/libvt/contrib/subprocess.py @@ -0,0 +1,943 @@ +"""Drive a child through a terminal from synchronous Python.""" + +from __future__ import annotations + +import asyncio +import atexit +import collections.abc +import contextlib +import errno +import math +import os +import subprocess +import sys +import threading +import time +import typing as t +import warnings +import weakref +from dataclasses import dataclass + +from libvt._util import _byte_view +from libvt.aio import AsyncSession, open_pty +from libvt.config import Limits +from libvt.exc import LibVtError +from libvt.input import InputEvent +from libvt.recorder import find_flight_recorder +from libvt.snapshot import Snapshot + +__all__ = [ + "VT", + "CalledTerminalError", + "Capture", + "CompletedTerminal", + "TerminalProcess", + "TerminalTimeoutExpired", + "open_terminal", + "run_terminal", +] + +_INPUT_CHUNK_BYTES = 65_536 + +_owners_lock = threading.Lock() +_active_owners: set[_TerminalOwner] = set() + + +def _close_active_owners() -> None: + with _owners_lock: + owners = tuple(_active_owners) + for owner in owners: + with owner._state_lock: + already_closing = owner._closing + if not already_closing: + warnings.warn( + f"unclosed TerminalProcess for {owner.args!r}", + ResourceWarning, + stacklevel=2, + ) + with contextlib.suppress(BaseException): + owner.close(timeout=5.0) + + +atexit.register(_close_active_owners) + + +def _validate_size(rows: int, cols: int) -> None: + for name, value in (("rows", rows), ("cols", cols)): + if ( + isinstance(value, bool) + or not isinstance(value, int) + or not 1 <= value <= 32767 + ): + msg = f"{name} must be an integer from 1 to 32767" + raise ValueError(msg) + + +def _validate_timeout(timeout: float | None) -> None: + if timeout is not None and ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not math.isfinite(timeout) + or timeout < 0 + ): + msg = "timeout must be finite and nonnegative" + raise ValueError(msg) + + +def _copy_buffer(data: collections.abc.Buffer, *, name: str) -> bytes: + if isinstance(data, bytes): + return data + try: + with _byte_view(data) as view: + return view.tobytes() + except TypeError as exc: + msg = f"{name} requires a bytes-like buffer" + raise TypeError(msg) from exc + + +@dataclass(frozen=True, slots=True, kw_only=True) +class VT: + """Set initial geometry and retention limits for a terminal child. + + Attributes + ---------- + rows : int + Initial viewport height from 1 to 32767. + cols : int + Initial viewport width from 1 to 32767. + scrollback : int + Maximum retained scrollback rows. + raw_limit : int + Maximum retained output bytes (``0`` disables tail retention). + """ + + rows: int = 24 + cols: int = 80 + scrollback: int = 2000 + raw_limit: int = 4096 + + def __post_init__(self) -> None: + """Validate geometry and recorder limits.""" + _validate_size(self.rows, self.cols) + if ( + isinstance(self.scrollback, bool) + or not isinstance(self.scrollback, int) + or self.scrollback < 0 + ): + msg = "scrollback must be a nonnegative integer" + raise ValueError(msg) + if ( + isinstance(self.raw_limit, bool) + or not isinstance(self.raw_limit, int) + or self.raw_limit < 0 + ): + msg = "raw_limit must be a nonnegative integer" + raise ValueError(msg) + + +@dataclass(frozen=True, slots=True) +class Capture: + """Hold the viewport and bounded tail of merged terminal output. + + Attributes + ---------- + snapshot : Snapshot + Last committed terminal frame. + raw_tail : bytes + Most recent recorded output bytes, including terminal sequences. + raw_total : int + Number of output bytes observed, including discarded bytes. + eof : bool + Whether the session observed terminal end-of-stream before teardown. + """ + + snapshot: Snapshot + raw_tail: bytes + raw_total: int + eof: bool + + def __vt_target__(self) -> tuple[Snapshot, frozenset[str]]: + """Return ``(snapshot, frozenset())`` for :mod:`libvt.testing`.""" + return self.snapshot, frozenset() + + @property + def truncated(self) -> bool: + """Return whether earlier output bytes were discarded.""" + return self.raw_total > len(self.raw_tail) + + +@dataclass(frozen=True, slots=True) +class CompletedTerminal(Capture): + """Hold the final capture and direct child's exit status. + + Attributes + ---------- + snapshot : Snapshot + Final committed terminal frame. + raw_tail : bytes + Most recent recorded output bytes, including terminal sequences. + raw_total : int + Number of output bytes observed, including discarded bytes. + eof : bool + Whether the session observed terminal end-of-stream before teardown. + args : tuple[str, ...] + Executable and arguments passed to the child. + returncode : int + Exit status of the direct child. + """ + + args: tuple[str, ...] + returncode: int + + def check_returncode(self) -> None: + """Raise :exc:`CalledTerminalError` for a nonzero child status.""" + if self.returncode: + raise CalledTerminalError(self) + + +class CalledTerminalError(LibVtError, subprocess.CalledProcessError): + """Raised when a terminal child exits with a nonzero status. + + Attributes + ---------- + result : CompletedTerminal + Final terminal capture and exit status for the failed process. + """ + + result: CompletedTerminal + + def __init__(self, result: CompletedTerminal) -> None: + super().__init__(result.returncode, result.args, output=result.raw_tail) + self.result = result + + +class TerminalTimeoutExpired( # noqa: N818 - match subprocess.TimeoutExpired + LibVtError, subprocess.TimeoutExpired +): + """Raised when waiting for child exit, terminal EOF, or outbound drain expires. + + Attributes + ---------- + capture : Capture + Bounded capture observed at timeout (or final :class:`CompletedTerminal` + when raised by :func:`run_terminal`). + phase : Literal["process", "eof", "drain"] + Wait stage whose deadline expired. + """ + + capture: Capture + phase: t.Literal["process", "eof", "drain"] + + def __init__( + self, + args: tuple[str, ...], + timeout: float, + capture: Capture, + phase: t.Literal["process", "eof", "drain"], + ) -> None: + super().__init__(args, timeout, output=capture.raw_tail) + self.capture = capture + self.phase = phase + + def __str__(self) -> str: + """Include the timed-out phase alongside the base timeout description.""" + return f"{super().__str__()} (phase={self.phase})" + + +class _Child(t.Protocol): + @property + def pid(self) -> int: ... + + @property + def returncode(self) -> int | None: ... + + async def wait(self) -> int: ... + + def kill(self) -> None: ... + + +class _Resize(t.Protocol): + def __call__(self, *, rows: int, cols: int) -> None: ... + + +@dataclass(frozen=True, slots=True) +class _Attachment: + io: AsyncSession + process: _Child + resize: _Resize + + +@contextlib.asynccontextmanager +async def _attach( + args: tuple[str, ...], options: VT, cwd: str | None, env: dict[str, str] | None +) -> collections.abc.AsyncGenerator[_Attachment]: + if sys.platform == "win32": + from ._conpty import open_conpty + + async with open_conpty(args, options, cwd, env) as attachment: + yield attachment + elif sys.platform == "darwin": + from ._darwin_pty import open_darwin_pty + + async with open_darwin_pty(args, options, cwd, env) as attachment: + yield attachment + else: + async with open_pty( + args, + rows=options.rows, + cols=options.cols, + scrollback=options.scrollback, + cwd=cwd, + env=env, + write_high_water=0, + limits=Limits(max_recorder_bytes=options.raw_limit), + ) as pty: + yield _Attachment(pty, pty.process, pty.resize) + + +class _TerminalOwner: + """Background event-loop owner decoupled from :class:`TerminalProcess` for GC.""" + + def __init__( + self, + args: tuple[str, ...], + options: VT, + cwd: str | None, + env: dict[str, str] | None, + ) -> None: + self.args = args + self.pid = -1 + self._raw_limit = options.raw_limit + self._ready = threading.Event() + self._done = threading.Event() + self._state_lock = threading.Lock() + self._closing = False + self._loop: asyncio.AbstractEventLoop | None = None + self._stop: asyncio.Event | None = None + self._attachment: _Attachment | None = None + self._result: CompletedTerminal | None = None + self._error: BaseException | None = None + self._thread = threading.Thread( + target=self._run, + args=(_attach(args, options, cwd, env),), + name="libvt-terminal", + daemon=True, + ) + with _owners_lock: + _active_owners.add(self) + try: + self._thread.start() + except BaseException: + with _owners_lock: + _active_owners.discard(self) + raise + try: + self._ready.wait() + if self._done.is_set(): + self.result() + except BaseException: + self._ready.wait() + self.close() + raise + + @property + def is_done(self) -> bool: + return self._done.is_set() + + def result(self) -> CompletedTerminal: + self._done.wait() + if self._error is not None: + raise self._error + assert self._result is not None + return self._result + + def _run( + self, context: contextlib.AbstractAsyncContextManager[_Attachment] + ) -> None: + loop_factory = ( + asyncio.ProactorEventLoop + if sys.platform == "win32" + else asyncio.SelectorEventLoop + ) + try: + with asyncio.Runner(loop_factory=loop_factory) as runner: + self._result = runner.run(self._own(context)) + except BaseException as exc: # noqa: BLE001 - relay worker exception to caller + self._error = exc + finally: + with self._state_lock: + self._closing = True + self._loop = None + self._stop = None + self._done.set() + self._ready.set() + with _owners_lock: + _active_owners.discard(self) + + async def _own( + self, context: contextlib.AbstractAsyncContextManager[_Attachment] + ) -> CompletedTerminal: + async with context as attachment: + with self._state_lock: + self._attachment = attachment + self.pid = attachment.process.pid + self._loop = asyncio.get_running_loop() + self._stop = asyncio.Event() + if self._closing: + self._stop.set() + self._ready.set() + await self._stop.wait() + eof = attachment.io.eof + capture = self.capture_in_loop() + status = attachment.process.returncode + if status is None: + msg = "terminal closed before its child was reaped" + raise RuntimeError(msg) + return CompletedTerminal( + capture.snapshot, + capture.raw_tail, + capture.raw_total, + eof, + self.args, + status, + ) + + def capture_in_loop(self) -> Capture: + attachment = self._attachment + if attachment is None: + msg = "terminal is not attached" + raise RuntimeError(msg) + term = attachment.io.terminal + recorder = find_flight_recorder(term.recorder) + if recorder is None: + msg = "terminal recorder is missing" + raise RuntimeError(msg) + return Capture( + term.committed, + recorder.tail(self._raw_limit), + recorder.total_bytes, + attachment.io.eof, + ) + + def submit[T]( + self, + function: collections.abc.Callable[ + [], collections.abc.Coroutine[None, None, T] + ], + ) -> T: + with self._state_lock: + if self._closing or self._done.is_set() or self._loop is None: + closed = True + loop = None + else: + closed = False + loop = self._loop + if closed: + if self._done.is_set(): + self.result() + msg = "terminal is closed" + raise ValueError(msg) + assert loop is not None + coro = function() + try: + request = asyncio.run_coroutine_threadsafe(coro, loop) + except RuntimeError as exc: + coro.close() + msg = "terminal is closed" + raise ValueError(msg) from exc + try: + return request.result() + except BufferError as exc: + text = str(exc) + for marker in ("await session.drain()", "await stream.drain()"): + if marker in text: + raise BufferError(text.replace(marker, "call drain()")) from exc + raise + except BaseException: + request.cancel() + raise + + def close(self, *, timeout: float | None = None) -> None: + with self._state_lock: + self._closing = True + loop = self._loop + stop = self._stop + if loop is not None and stop is not None: + with contextlib.suppress(RuntimeError): + loop.call_soon_threadsafe(stop.set) + if self._thread.is_alive() and threading.current_thread() is not self._thread: + self._thread.join(timeout=timeout) + with _owners_lock: + _active_owners.discard(self) + + +def _finalize_owner(owner: _TerminalOwner) -> None: + if owner.is_done: + return + warnings.warn( + f"unclosed TerminalProcess for {owner.args!r}", + ResourceWarning, + stacklevel=2, + ) + with contextlib.suppress(BaseException): + owner.close(timeout=5.0) + + +class TerminalProcess: + """Control a terminal child from the thread that opened it. + + Obtain a handle from :func:`open_terminal`. Use the context manager + or call :meth:`close` to shut down the terminal and reap the child. + + Attributes + ---------- + args : tuple[str, ...] + Normalized command sequence launched in the terminal. + pid : int + Process identifier of the direct child process. + """ + + args: tuple[str, ...] + pid: int + + def __init__( + self, + args: tuple[str, ...], + options: VT, + cwd: str | None, + env: dict[str, str] | None, + ) -> None: + self.args = args + self._controller = threading.current_thread() + self._owner = _TerminalOwner(args, options, cwd, env) + self.pid = self._owner.pid + self._finalizer = weakref.finalize(self, _finalize_owner, self._owner) + + def _controller_only(self) -> None: + if threading.current_thread() is not self._controller: + msg = "use the terminal handle from its creating thread" + raise RuntimeError(msg) + + def _block[T]( + self, + function: collections.abc.Callable[ + [], collections.abc.Coroutine[None, None, T] + ], + ) -> T: + self._controller_only() + return self._owner.submit(function) + + def _call[T](self, function: collections.abc.Callable[[], T]) -> T: + async def invoke() -> T: + return function() + + return self._block(invoke) + + @property + def _attachment(self) -> _Attachment: + attachment = self._owner._attachment + if attachment is None: + msg = "terminal is not attached" + raise RuntimeError(msg) + return attachment + + def __vt_target__(self) -> tuple[Snapshot, frozenset[str]]: + """Return ``(snapshot(), frozenset())`` for :mod:`libvt.testing`.""" + return self.snapshot(), frozenset() + + def snapshot(self) -> Snapshot: + """Return the last committed viewport (safe before and after :meth:`close`).""" + self._controller_only() + if self._owner.is_done: + return self._owner.result().snapshot + return self._call(lambda: self._attachment.io.terminal.committed) + + def capture(self) -> Capture: + """Return the viewport, raw tail, byte count, and EOF state.""" + self._controller_only() + if self._owner.is_done: + return self._owner.result() + return self._call(self._owner.capture_in_loop) + + def wait_for( + self, + predicate: str | collections.abc.Callable[[Snapshot], bool], + *, + timeout: float = 2.0, + ) -> Snapshot: + """Wait for visible text or a predicate on a committed frame. + + A string *predicate* matches against + :attr:`~libvt.snapshot.Snapshot.unwrapped_text`. A callable *predicate* + runs on the reader thread and must inspect only the supplied + :class:`~libvt.snapshot.Snapshot` without calling methods on this + handle. + + Parameters + ---------- + predicate : str | Callable[[Snapshot], bool] + Substring to match or callable evaluated against each committed + frame. + timeout : float, optional + Maximum wait time in seconds (default ``2.0``). + + Returns + ------- + Snapshot + First committed frame satisfying *predicate*. + + Raises + ------ + libvt.exc.TerminalTimeoutError + If the deadline expires or the terminal reaches EOF before + *predicate* matches. + ValueError + If the handle is already closed. + RuntimeError + If called from a thread other than the handle's creating thread. + """ + return self._block( + lambda: self._attachment.io.wait_for(predicate, timeout=timeout) + ) + + def send(self, data: collections.abc.Buffer, /) -> None: + """Queue raw input bytes for delivery to the terminal. + + Raises + ------ + TypeError + If *data* does not implement the bytes-like buffer protocol. + BufferError + If the outbound write queue exceeds its limit; call :meth:`drain`. + ValueError + If the handle is closed. + """ + payload = _copy_buffer(data, name="send") + self._call(lambda: self._attachment.io.send(payload)) + + def send_event(self, event: InputEvent, /) -> None: + """Encode and queue a structured input event for current terminal modes. + + Raises + ------ + ValueError + If the handle is closed. + """ + self._call(lambda: self._attachment.io.send_event(event)) + + def send_key(self, chord: str, /) -> None: + """Queue a key chord encoded for the current terminal input modes. + + Raises + ------ + ValueError + If *chord* is invalid or the handle is closed. + """ + self._call(lambda: self._attachment.io.send_key(chord)) + + def paste(self, text: str, /, *, sanitize: bool = False) -> None: + """Queue text using the active terminal paste mode. + + Raises + ------ + libvt.exc.UnsafePasteError + If *text* contains unsafe control bytes and *sanitize* is false. + ValueError + If the handle is closed. + """ + self._call(lambda: self._attachment.io.paste(text, sanitize=sanitize)) + + def drain(self, timeout: float | None = None) -> None: + """Wait until queued outbound input bytes are written to the terminal. + + Raises + ------ + TerminalTimeoutExpired + If *timeout* expires before the outbound buffer drains + (``phase="drain"``). The handle stays live. + ValueError + If *timeout* is invalid or the handle is closed. + """ + _validate_timeout(timeout) + self._wait(self._attachment.io.drain, timeout, "drain") + + def resize(self, *, rows: int, cols: int) -> None: + """Resize both the native terminal and the libvt viewport. + + Raises + ------ + ValueError + If *rows* or *cols* is outside ``1..32767`` or the handle is closed. + """ + _validate_size(rows, cols) + self._call(lambda: self._attachment.resize(rows=rows, cols=cols)) + + def poll(self) -> int | None: + """Return the direct child's exit status, or ``None`` while it runs.""" + self._controller_only() + if self._owner.is_done: + return self._owner.result().returncode + return self._call(lambda: self._attachment.process.returncode) + + @property + def returncode(self) -> int | None: + """Return the direct child's exit status, or ``None`` while it runs.""" + return self.poll() + + def wait(self, timeout: float | None = None) -> int: + """Wait for the direct child to exit while continuing to drain output. + + On timeout, raise :exc:`TerminalTimeoutExpired` (``phase="process"``) + and keep the handle live for further interaction. Safe after + :meth:`close`, returning the final exit status. + """ + _validate_timeout(timeout) + self._controller_only() + if self._owner.is_done: + return self._owner.result().returncode + + return self._wait(self._attachment.process.wait, timeout, "process") + + def _wait[T]( + self, + operation: collections.abc.Callable[ + [], collections.abc.Coroutine[None, None, T] + ], + timeout: float | None, + phase: t.Literal["process", "eof", "drain"], + ) -> T: + async def wait_with_timeout() -> T: + scope = asyncio.timeout(timeout) + try: + async with scope: + return await operation() + except TimeoutError: + if timeout is None or not scope.expired(): + raise + raise TerminalTimeoutExpired( + self.args, timeout, self._owner.capture_in_loop(), phase + ) from None + + return self._block(wait_with_timeout) + + def wait_eof(self, timeout: float | None = None) -> Capture: + """Wait for terminal output to end, including output from descendants. + + On timeout, raise :exc:`TerminalTimeoutExpired` (``phase="eof"``) and + keep the handle live. A closed handle returns its final capture if EOF + was already observed; otherwise it raises :exc:`ValueError`. + """ + _validate_timeout(timeout) + self._controller_only() + if self._owner.is_done and (capture := self._owner.result()).eof: + return capture + + async def wait_output() -> Capture: + stream = self._attachment.io + # The session waiter wakes for EOF even if no frame changed. + # The outer wait owns the deadline, including an unbounded wait. + await stream.wait_for( + lambda _: stream.eof, timeout=sys.float_info.max, attach_note=False + ) + return self._owner.capture_in_loop() + + return self._wait(wait_output, timeout, "eof") + + def kill(self) -> None: + """Stop the direct child while keeping the terminal open. + + No-op if the direct child has already exited. Raises :exc:`ValueError` + after :meth:`close`. + """ + + def deliver() -> None: + process = self._attachment.process + if process.returncode is None: + with contextlib.suppress(ProcessLookupError): + process.kill() + + self._call(deliver) + + def close(self) -> CompletedTerminal: + """Shut down the terminal, reap the child, and return its final capture. + + Wait for :meth:`wait_eof` before closing when descendant output + matters. Repeated calls return the same result. A POSIX descendant + that ignores hangup can outlive the terminal after the direct + child has exited. + """ + self._controller_only() + self._finalizer.detach() + self._owner.close() + return self._owner.result() + + def __enter__(self) -> t.Self: + """Return the open handle.""" + return self + + def __exit__(self, *_: object) -> None: + """Close the native terminal and reap the child.""" + self.close() + + +def open_terminal( + args: collections.abc.Sequence[str], + *, + vt: VT = VT(), + cwd: str | os.PathLike[str] | None = None, + env: collections.abc.Mapping[str, str] | None = None, +) -> TerminalProcess: + """Start a child with a POSIX PTY or Windows pseudoconsole. + + Parameters + ---------- + args : collections.abc.Sequence[str] + Executable and arguments as a nonempty sequence, such as a list. + vt : VT + Terminal geometry and retention limits. + cwd : str | os.PathLike[str] | None + Child working directory. Defaults to the parent's directory. + env : collections.abc.Mapping[str, str] | None + Replacement child environment. Defaults to the parent's environment. + POSIX supplies ``TERM=xterm-256color`` when missing. + + Returns + ------- + TerminalProcess + Open handle that owns merged output and must be closed. + + Raises + ------ + TypeError + When *vt*, *args*, *cwd*, or *env* has an unsupported type. + NotImplementedError + When native terminal allocation is unavailable. + OSError + When native terminal creation or child launch fails. + ValueError + When arguments contain invalid values. + """ + if not isinstance(vt, VT): + msg = "vt must be a VT configuration" + raise TypeError(msg) + if isinstance(args, (str, bytes, bytearray)) or not isinstance( + args, collections.abc.Sequence + ): + msg = "args must be a nonempty sequence of strings" + raise TypeError(msg) + argv = tuple(args) + if ( + not argv + or not argv[0] + or any(not isinstance(word, str) or "\0" in word for word in argv) + ): + msg = "args must contain an executable and NUL-free string arguments" + raise ValueError(msg) + path = os.fspath(cwd) if cwd is not None else None + if path is not None: + if not isinstance(path, str): + msg = "cwd must be a string path" + raise TypeError(msg) + if "\0" in path: + msg = "cwd must be a text path without NUL" + raise ValueError(msg) + if env is not None and not isinstance(env, collections.abc.Mapping): + msg = "env must be a mapping of string keys and values" + raise TypeError(msg) + environment = None if env is None else dict(env) + if environment is not None: + for key, value in environment.items(): + if not isinstance(key, str) or not isinstance(value, str): + msg = "env keys and values must be strings" + raise TypeError(msg) + if not key or "=" in key or "\0" in key or "\0" in value: + msg = "invalid environment variable name or value" + raise ValueError(msg) + if sys.platform == "win32" and len({key.upper() for key in environment}) != len( + environment + ): + msg = "duplicate case-insensitive Windows environment variables" + raise ValueError(msg) + if os.name not in ("nt", "posix"): + msg = "terminal processes require POSIX or Windows" + raise NotImplementedError(msg) + return TerminalProcess(argv, vt, path, environment) + + +def run_terminal( + args: collections.abc.Sequence[str], + *, + vt: VT = VT(), + cwd: str | os.PathLike[str] | None = None, + env: collections.abc.Mapping[str, str] | None = None, + input: collections.abc.Buffer | None = None, # noqa: A002 - match subprocess.run + timeout: float | None = None, + check: bool = False, +) -> CompletedTerminal: + """Run a command through a terminal and wait for exit and terminal EOF. + + Parameters + ---------- + args : collections.abc.Sequence[str] + Executable and arguments as a nonempty sequence, such as a list. + vt : VT + Terminal geometry and retention limits. + cwd : str | os.PathLike[str] | None + Child working directory. Defaults to the parent's directory. + env : collections.abc.Mapping[str, str] | None + Replacement child environment. Defaults to the parent's environment. + input : collections.abc.Buffer | None + Bytes-like input to queue after launch. Terminal input stays open. + timeout : float | None + Shared time budget after launch for input drain, child exit, and + terminal EOF. Native cleanup may take longer. + check : bool + Raise for a nonzero exit status. + + Returns + ------- + CompletedTerminal + Final terminal capture and direct child's status. + + Raises + ------ + TypeError + When *input*, *vt*, *args*, *cwd*, or *env* has an unsupported type. + CalledTerminalError + If *check* is true and the direct child returns a nonzero status. + TerminalTimeoutExpired + If the timeout expires. The terminal closes and reaps the direct + child before raising. POSIX descendants that ignore hangup can + outlive the terminal. + """ + _validate_timeout(timeout) + payload = None if input is None else _copy_buffer(input, name="input") + child = open_terminal(args, vt=vt, cwd=cwd, env=env) + deadline = None if timeout is None else time.monotonic() + timeout + + def remaining() -> float | None: + return None if deadline is None else max(0.0, deadline - time.monotonic()) + + try: + try: + if payload is not None: + try: + for offset in range(0, len(payload), _INPUT_CHUNK_BYTES): + child.send(payload[offset : offset + _INPUT_CHUNK_BYTES]) + if offset + _INPUT_CHUNK_BYTES < len(payload): + child.drain(remaining()) + except BrokenPipeError: + pass + except OSError as exc: + if exc.errno != errno.EIO: + raise + child.wait(remaining()) + child.wait_eof(remaining()) + finally: + result = child.close() + except TerminalTimeoutExpired as exc: + assert timeout is not None + raise TerminalTimeoutExpired(result.args, timeout, result, exc.phase) from None + if check: + result.check_returncode() + return result diff --git a/tests/test_subprocess.py b/tests/test_subprocess.py new file mode 100644 index 00000000..7369e49d --- /dev/null +++ b/tests/test_subprocess.py @@ -0,0 +1,845 @@ +"""Exercise real child processes through the synchronous terminal controller.""" + +from __future__ import annotations + +import asyncio +import ctypes +import enum +import gc +import math +import os +import pathlib +import signal +import subprocess +import sys +import tempfile +import threading +import typing as t + +import pytest + +import libvt +from libvt.contrib import subprocess as sp +from libvt.contrib._darwin_pty import open_darwin_pty +from libvt.exc import LibVtError, TerminalTimeoutError +from libvt.input import MouseAction, MouseButton, MouseEvent +from libvt.testing import ( + SupportsVtTarget, + assert_screen_box, + serialize_vt_snapshot, + vt_screen, +) + + +def _command(script: str) -> list[str]: + return [sys.executable, "-u", "-c", script] + + +def test_public_exports_omit_stdlib_aliases() -> None: + """Expose only terminal subprocess symbols without stdlib re-exports.""" + assert not hasattr(sp, "Popen") + assert not hasattr(sp, "run") + assert "Popen" not in sp.__all__ + assert "run" not in sp.__all__ + assert set(sp.__all__) == { + "VT", + "CalledTerminalError", + "Capture", + "CompletedTerminal", + "TerminalProcess", + "TerminalTimeoutExpired", + "open_terminal", + "run_terminal", + } + if t.TYPE_CHECKING: + command = [sys.executable] + proc = sp.open_terminal(command) + t.assert_type(proc, sp.TerminalProcess) + result = sp.run_terminal(command) + t.assert_type(result, sp.CompletedTerminal) + t.assert_type(serialize_vt_snapshot(proc), str) + t.assert_type(serialize_vt_snapshot(result), str) + + +class _SizeEnum(enum.IntEnum): + ROWS = 6 + COLS = 32 + + +def test_vt_and_argument_validation(monkeypatch: pytest.MonkeyPatch) -> None: + """Validate VT geometry/limits, open_terminal args, run_terminal input/timeout.""" + assert sp.VT(rows=_SizeEnum.ROWS, cols=_SizeEnum.COLS).rows == 6 + assert sp.VT(raw_limit=0).raw_limit == 0 + assert sp.VT(raw_limit=1).raw_limit == 1 + assert sp.VT(raw_limit=63).raw_limit == 63 + + for bad_size in (0, -1, 32768, True, False): + with pytest.raises(ValueError, match="rows"): + sp.VT(rows=bad_size) + with pytest.raises(ValueError, match="cols"): + sp.VT(cols=bad_size) + for bad_limit in (-1, -64, True, False): + with pytest.raises(ValueError, match="scrollback"): + sp.VT(scrollback=bad_limit) + with pytest.raises(ValueError, match="raw_limit"): + sp.VT(raw_limit=bad_limit) + + with pytest.raises(TypeError, match="VT configuration"): + sp.open_terminal([sys.executable], vt=True) # ty: ignore[invalid-argument-type] + for bad_args in ("ls", b"ls", bytearray(b"ls"), 123): + with pytest.raises(TypeError, match="nonempty sequence"): + sp.open_terminal(bad_args) # ty: ignore[invalid-argument-type] + for bad_argv in ([], [""], ["ok", "bad\0arg"], [123]): + with pytest.raises(ValueError, match="NUL-free"): + sp.open_terminal(bad_argv) # ty: ignore[invalid-argument-type] + with pytest.raises(TypeError, match="cwd must be a string"): + sp.open_terminal([sys.executable], cwd=b"/tmp") # ty: ignore[invalid-argument-type] + with pytest.raises(ValueError, match="cwd must be a text path"): + sp.open_terminal([sys.executable], cwd="/tmp/bad\0dir") + with pytest.raises(TypeError, match="env must be a mapping"): + sp.open_terminal( + [sys.executable], + env=[("A", "B")], # ty: ignore[invalid-argument-type] + ) + with pytest.raises(TypeError, match="env keys and values"): + sp.open_terminal( + [sys.executable], + env={"A": 1}, # ty: ignore[invalid-argument-type] + ) + for bad_env in ({"": "v"}, {"A=B": "v"}, {"A\0": "v"}, {"A": "v\0"}): + with pytest.raises(ValueError, match="invalid environment"): + sp.open_terminal([sys.executable], env=bad_env) + + monkeypatch.setattr(sys, "platform", "win32") + with pytest.raises(ValueError, match="duplicate case-insensitive"): + sp.open_terminal([sys.executable], env={"Path": "a", "PATH": "b"}) + monkeypatch.undo() + + for bad_timeout in (-0.1, math.nan, math.inf, -math.inf, True, "1"): + with pytest.raises(ValueError, match="timeout"): + sp.run_terminal( + [sys.executable], + timeout=bad_timeout, # ty: ignore[invalid-argument-type] + ) + with pytest.raises(TypeError, match="input requires a bytes-like buffer"): + sp.run_terminal( + [sys.executable], + input="text", # ty: ignore[invalid-argument-type] + ) + assert issubclass(sp.CalledTerminalError, LibVtError) + assert issubclass(sp.TerminalTimeoutExpired, LibVtError) + + +@pytest.fixture +def _terminal_platform() -> None: + if sys.platform == "win32" and not hasattr( + ctypes.WinDLL("kernel32"), "ReleasePseudoConsole" + ): + pytest.skip("ConPTY terminal EOF requires ReleasePseudoConsole") + if os.name not in ("nt", "posix"): + pytest.skip("native terminal unavailable") + + +@pytest.mark.usefixtures("_terminal_platform") +def test_terminal_interaction() -> None: + """Change the child geometry, drive input, and support VT snapshot targets.""" + script = ( + "import os, sys; print('TTY', *(os.isatty(fd) for fd in range(3)));" + "print('DATA', input()[::-1]);" + "print('SIZE', *os.get_terminal_size());" + "print('STDERR', file=sys.stderr); sys.exit(23)" + ) + with sp.open_terminal(_command(script), vt=sp.VT(rows=8, cols=38)) as child: + before = child.wait_for("TTY True True True", timeout=8) + assert isinstance(child, SupportsVtTarget) + assert "TTY True True True" in serialize_vt_snapshot(child) + child.resize(rows=10, cols=56) + child.paste("pear") + child.send_key("enter") + assert child.wait(8) == 23 + capture = child.wait_eof(8) + assert before.cols == 38 + assert capture.eof + assert isinstance(capture, SupportsVtTarget) + rendered_capture = serialize_vt_snapshot(vt_screen(capture)) + for expected in ("DATA raep", "SIZE 56 10", "STDERR"): + assert expected in capture.snapshot.text + assert expected in rendered_capture + result = child.close() + assert child.returncode == 23 + assert result is child.close() + assert isinstance(result, SupportsVtTarget) + assert "DATA raep" in serialize_vt_snapshot(result) + assert "DATA raep" in serialize_vt_snapshot(child) + with pytest.raises(sp.CalledTerminalError) as failure: + result.check_returncode() + assert failure.value.result is result + + +@pytest.fixture +def descendant_command(tmp_path: pathlib.Path) -> list[str]: + """Return a program whose descendant retains the terminal.""" + ready = str(tmp_path / "ready") + descendant = ( + "import os, pathlib, signal, sys, threading;\n" + "if sys.platform != 'win32': signal.signal(signal.SIGHUP, signal.SIG_IGN)\n" + "watchdog = threading.Timer(15, os._exit, (3,))\n" + "watchdog.daemon = True; watchdog.start()\n" + f"pathlib.Path({ready!r}).touch();" + "print('DESCENDANT READY'); print('LATE', input()[::-1])" + ) + main = ( + "import pathlib, subprocess, sys, time;\n" + f"worker = subprocess.Popen([sys.executable, '-u', '-c', {descendant!r}])\n" + "until = time.monotonic() + 5\n" + f"while not pathlib.Path({ready!r}).exists():\n" + " if worker.poll() is not None or time.monotonic() > until: sys.exit(2)\n" + " time.sleep(0.01)\n" + "sys.exit(17)" + ) + return _command(main) + + +@pytest.mark.usefixtures("_terminal_platform") +def test_terminal_eof_after_descendant_output(descendant_command: list[str]) -> None: + """Keep serving the terminal after the process that launched it exits.""" + with sp.open_terminal(descendant_command) as child: + assert child.wait(8) == 17 + child.wait_for("DESCENDANT READY", timeout=8) + with pytest.raises(sp.TerminalTimeoutExpired) as failure: + child.wait_eof(0) + assert failure.value.phase == "eof" + assert failure.value.capture.eof is False + child.paste("pine") + child.send_key("enter") + capture = child.wait_eof(8) + assert "LATE enip" in capture.snapshot.text + + +@pytest.mark.usefixtures("_terminal_platform") +def test_run_timeout_while_descendant_holds_terminal( + descendant_command: list[str], +) -> None: + """Apply the one-shot deadline to terminal EOF after the direct child exits.""" + with pytest.raises(sp.TerminalTimeoutExpired) as failure: + sp.run_terminal(descendant_command, timeout=3) + assert failure.value.phase == "eof" + assert failure.value.timeout == 3 + result = failure.value.capture + assert isinstance(result, sp.CompletedTerminal) + assert result.returncode == 17 + assert not result.eof + + +@pytest.mark.usefixtures("_terminal_platform") +def test_run_retains_bounded_tail() -> None: + """Drain large output with bounded tail retention including raw_limit=0.""" + result = sp.run_terminal( + _command("print('x' * 100_000); print('COMPLETE')"), + vt=sp.VT(rows=4, cols=40, scrollback=2, raw_limit=128), + check=True, + timeout=20, + ) + assert result.eof + assert len(result.raw_tail) == 128 < result.raw_total + assert libvt.strip(result.raw_tail).rstrip().endswith("COMPLETE") + assert len(result.snapshot.history) <= 2 + assert result.truncated + assert "COMPLETE" in result.snapshot.text + + zero = sp.run_terminal( + _command("print('ZERO_TAIL')"), + vt=sp.VT(rows=4, cols=40, raw_limit=0), + check=True, + timeout=10, + ) + assert zero.eof + assert zero.raw_tail == b"" + assert zero.raw_total > 0 + assert zero.truncated + assert "ZERO_TAIL" in zero.snapshot.text + + +@pytest.mark.usefixtures("_terminal_platform") +def test_timeout_leaves_wait_handle_live_and_run_reaps( + tmp_path: pathlib.Path, +) -> None: + """Retry a live wait and verify run_terminal reaps a timed-out child.""" + pid_file = tmp_path / "pid" + command = _command( + f"import os, pathlib; " + f"pathlib.Path({str(pid_file)!r}).write_text(str(os.getpid()));" + "print('WAITING'); input()" + ) + with sp.open_terminal(command) as child: + child.wait_for("WAITING", timeout=8) + with pytest.raises(sp.TerminalTimeoutExpired) as failure: + child.wait(0) + assert isinstance(failure.value, LibVtError) + assert failure.value.phase == "process" + assert "phase=process" in str(failure.value) + assert child.poll() is None + child.send(bytearray(b"\r")) + assert child.wait(8) == 0 + pid_file.unlink() + with pytest.raises(sp.TerminalTimeoutExpired) as failure: + sp.run_terminal(command, timeout=0.8) + assert failure.value.phase == "process" + assert "phase=process" in str(failure.value) + assert failure.value.timeout == 0.8 + assert failure.value.cmd == tuple(command) + if os.name == "posix": + assert pid_file.exists() + reaped_pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + os.kill(reaped_pid, 0) + + +@pytest.mark.usefixtures("_terminal_platform") +def test_run_with_input_and_launch_options(tmp_path: pathlib.Path) -> None: + """Pass quoted arguments, a working directory, and a replacement environment.""" + command = _command( + "import os, sys; print('INPUT', input()); print('ARG', sys.argv[1]);" + "print('CWD', os.path.basename(os.getcwd()));" + "print('ENV', os.environ['TEST_VALUE'])" + ) + command.append('space "quote"') + result = sp.run_terminal( + command, + cwd=tmp_path, + env={**os.environ, "TEST_VALUE": "example"}, + input=b"pear\r", + timeout=10, + check=True, + ) + for expected in ( + "INPUT pear", + 'ARG space "quote"', + f"CWD {tmp_path.name}", + "ENV example", + ): + assert expected in result.snapshot.text + + +@pytest.mark.usefixtures("_terminal_platform") +def test_invalid_executable_releases_worker(tmp_path: pathlib.Path) -> None: + """Propagate native exec failure without leaving a terminal worker running.""" + before = set(threading.enumerate()) + with pytest.raises(FileNotFoundError): + sp.open_terminal([str(tmp_path / "missing-executable")]) + assert not any( + thread.name.startswith("libvt-terminal") and thread not in before + for thread in threading.enumerate() + ) + + +@pytest.mark.skipif(os.name != "posix", reason="requires POSIX terminal job control") +def test_posix_foreground_and_signal_exit() -> None: + """Deliver a terminal interrupt to the foreground and reap its session owner.""" + script = ( + "import os, signal;\n" + "signal.signal(signal.SIGINT, signal.SIG_DFL)\n" + "if os.getpid() != os.getsid(0):\n" + " os.setpgid(0, 0)\n" + " signal.signal(signal.SIGTTOU, signal.SIG_IGN)\n" + " os.tcsetpgrp(0, os.getpgrp())\n" + "with open('/dev/tty', 'rb', buffering=0) as tty:\n" + " assert os.tcgetpgrp(tty.fileno()) == os.getpgrp()\n" + "print(f'FOREGROUND {os.getpid()} {os.getsid(0)}')\n" + "signal.pause()" + ) + with sp.open_terminal(_command(script)) as child: + frame = child.wait_for("FOREGROUND", timeout=8) + pid, sid = map(int, frame.lines[0].split()[1:]) + assert child.pid == pid + child.send_key("ctrl+c") + assert child.wait(8) == -signal.SIGINT + assert child.returncode == -signal.SIGINT + with pytest.raises(ProcessLookupError): + os.kill(sid, 0) + + +@pytest.mark.skipif( + sys.platform == "win32" or os.name != "posix", + reason="requires POSIX PTY and socketpair", +) +async def test_darwin_helper_uses_socketpair_without_temp_socket( + monkeypatch: pytest.MonkeyPatch, + tmp_path: pathlib.Path, +) -> None: + """Run the Darwin single-trampoline helper over socketpair with no Unix path.""" + + def _forbid(*_args: object, **_kwargs: object) -> t.NoReturn: + msg = "Darwin helper must use socketpair, not temp files or start_unix_server" + raise AssertionError(msg) + + long_tmp = tmp_path / ("x" * 120) + long_tmp.mkdir() + monkeypatch.setenv("TMPDIR", str(long_tmp)) + monkeypatch.setattr(tempfile, "TemporaryDirectory", _forbid) + if hasattr(asyncio, "start_unix_server"): + monkeypatch.setattr(asyncio, "start_unix_server", _forbid) + + command = ( + sys.executable, + "-u", + "-c", + ( + "import os; print('ready');" + "line = input();" + "print('done', line[::-1], *os.get_terminal_size())" + ), + ) + async with open_darwin_pty( + command, sp.VT(rows=6, cols=40, raw_limit=0), None, None + ) as attached: + await attached.io.wait_for("ready", timeout=5) + attached.resize(rows=9, cols=52) + attached.io.send(b"plum\n") + snap = await attached.io.wait_for("done mulp 52 9", timeout=5) + assert snap.cols == 52 + assert await attached.process.wait() == 0 + await attached.io.wait_for(lambda _: attached.io.eof, timeout=5) + + with pytest.raises(FileNotFoundError): + async with open_darwin_pty( + (str(tmp_path / "missing-darwin-exec"),), sp.VT(), None, None + ): + pass + + monkeypatch.setattr(sys, "platform", "darwin") + result = sp.run_terminal( + _command("print('DARWIN_DISPATCH')"), + vt=sp.VT(rows=4, cols=40, raw_limit=0), + check=True, + timeout=10, + ) + assert result.eof + assert result.raw_tail == b"" + assert result.raw_total > 0 + assert "DARWIN_DISPATCH" in result.snapshot.text + + +@pytest.mark.skipif( + sys.platform == "win32" or os.name != "posix", + reason="requires POSIX PTY and socketpair", +) +async def test_darwin_helper_preserves_session_for_descendant_and_sigint( + descendant_command: list[str], +) -> None: + """Keep the Darwin session leader alive for descendants and reap it on close.""" + async with open_darwin_pty( + tuple(descendant_command), sp.VT(), None, None + ) as attached: + assert await asyncio.wait_for(attached.process.wait(), timeout=8) == 17 + await attached.io.wait_for("DESCENDANT READY", timeout=8) + assert not attached.io.eof + attached.io.paste("fig") + attached.io.send_key("enter") + await attached.io.wait_for("LATE gif", timeout=8) + await attached.io.wait_for(lambda _: attached.io.eof, timeout=8) + + fg_script = ( + "import os, signal;\n" + "signal.signal(signal.SIGINT, signal.SIG_DFL)\n" + "os.setpgid(0, 0)\n" + "signal.signal(signal.SIGTTOU, signal.SIG_IGN)\n" + "os.tcsetpgrp(0, os.getpgrp())\n" + "with open('/dev/tty', 'rb', buffering=0) as tty:\n" + " assert os.tcgetpgrp(tty.fileno()) == os.getpgrp()\n" + "print(f'DARWIN_FG {os.getpid()} {os.getsid(0)}')\n" + "signal.pause()" + ) + async with open_darwin_pty( + tuple(_command(fg_script)), sp.VT(), None, None + ) as attached: + frame = await attached.io.wait_for("DARWIN_FG", timeout=8) + pid, sid = map(int, frame.lines[0].split()[1:]) + assert attached.process.pid == pid + assert pid != sid + attached.io.send_key("ctrl+c") + assert ( + await asyncio.wait_for(attached.process.wait(), timeout=8) == -signal.SIGINT + ) + with pytest.raises(ProcessLookupError): + os.kill(sid, 0) + + +@pytest.mark.usefixtures("_terminal_platform") +def test_kill_thread_ownership_post_close_and_wait_for_errors( + descendant_command: list[str], +) -> None: + """Verify kill(), thread ownership, predicate re-entry, post-close, and wait_for.""" + # kill() stops a live child while keeping the terminal open. + with sp.open_terminal(_command("print('ALIVE'); input()")) as child: + child.wait_for("ALIVE", timeout=8) + + # Calling from another thread raises RuntimeError. + worker_errors: list[BaseException] = [] + + def probe() -> None: + try: + child.poll() + except RuntimeError as exc: + worker_errors.append(exc) + + t_other = threading.Thread(target=probe) + t_other.start() + t_other.join(timeout=5) + assert len(worker_errors) == 1 + assert isinstance(worker_errors[0], RuntimeError) + assert "creating thread" in str(worker_errors[0]) + + # Calling handle methods inside a wait_for predicate raises RuntimeError. + with pytest.raises(RuntimeError, match="creating thread"): + child.wait_for(lambda _snap: child.poll() is not None, timeout=2) + + # wait_for timeout leaves the handle live. + with pytest.raises(TerminalTimeoutError) as timeout_err: + child.wait_for("NEVER_APPEARS", timeout=0.05) + assert timeout_err.value.eof is False + assert child.poll() is None + + # Invalid send / resize arguments rejected cleanly on a live handle. + with pytest.raises(TypeError, match="bytes-like buffer"): + child.send("text") # ty: ignore[invalid-argument-type] + with pytest.raises(ValueError, match="rows"): + child.resize(rows=0, cols=40) + + # Live kill() terminates the child while keeping the terminal handle usable. + child.kill() + status = child.wait(timeout=8) + assert status != 0 + # Calling kill() again on an exited child is a safe no-op. + child.kill() + eof_cap = child.wait_eof(timeout=8) + assert eof_cap.eof is True + + # Post-close contract: read-only getters succeed; mutating/waiting calls fail. + assert child.wait() == status + assert child.poll() == status + assert child.capture().eof is True + assert child.wait_eof().eof is True + assert "ALIVE" in child.snapshot().text + for action in ( + lambda: child.send(b"x"), + lambda: child.send_event(MouseEvent(MouseButton.LEFT, MouseAction.PRESS, 0, 0)), + lambda: child.send_key("enter"), + lambda: child.paste("x"), + lambda: child.drain(), + lambda: child.resize(rows=8, cols=40), + lambda: child.wait_for("ALIVE", timeout=1), + lambda: child.kill(), + ): + with pytest.raises(ValueError, match="closed"): + action() + + # wait_eof() after close when EOF was never reached raises ValueError. + no_eof = sp.open_terminal(descendant_command) + try: + assert no_eof.wait(timeout=8) == 17 + no_eof.wait_for("DESCENDANT READY", timeout=8) + finally: + closed_no_eof = no_eof.close() + assert closed_no_eof.eof is False + with pytest.raises(ValueError, match="closed"): + no_eof.wait_eof(timeout=1) + + # wait_for premature EOF sets exc.eof = True and attaches diagnostic notes. + with sp.open_terminal(_command("print('SHORT')")) as short: + with pytest.raises(TerminalTimeoutError) as eof_err: + short.wait_for("MISSING", timeout=5) + assert eof_err.value.eof is True + assert getattr(eof_err.value, "__notes__", None) + + +@pytest.mark.usefixtures("_terminal_platform") +def test_vt_fidelity_sync_2026_wide_send_event_drain_and_buffers() -> None: + """Verify exact boxed screen, wide chars, ?2026, send_event, drain, and Buffers.""" + # Exact rows, styles, wide CJK, and ?2026 synchronized output framing. + vt_script = ( + "import sys; out = sys.stdout.buffer\n" + "out.write('OLD\\x1b[?2026h\\r\\x1b[2K\\x1b[1;32m日本OK\\x1b[0m\\x1b[?2026l'.encode())\n" + "out.flush()\n" + ) + res = sp.run_terminal( + _command(vt_script), + vt=sp.VT(rows=2, cols=10), + check=True, + timeout=8, + ) + assert_screen_box( + res.snapshot, + """ + ┌──────────┐ + │日本OK │ + │ │ + └──────────┘ + """, + cursor=(0, 6), + ) + assert "bold fg=green" in serialize_vt_snapshot(res) + + # Buffer protocol (bytearray & strided memoryview) + drain() + run_terminal input. + buf = bytearray(b"aXbYcZ\r!") + strided = memoryview(buf)[::2] + buf_res = sp.run_terminal( + _command("print('GOT', input())"), + input=strided, + check=True, + timeout=8, + ) + assert "GOT abc" in buf_res.snapshot.text + + # send_event (MouseEvent) + ?2048 in-band resize + drain() on POSIX raw terminal. + if os.name == "posix": + raw_script = ( + "import os, sys, termios, tty\n" + "old = termios.tcgetattr(0)\n" + "tty.setraw(0)\n" + "try:\n" + " os.write(1, b'\\x1b[?1000;1006;2048hRAW_OK')\n" + " data = bytearray()\n" + " while b'M' not in data or b't' not in data:\n" + " chunk = os.read(0, 64)\n" + " if not chunk:\n" + " break\n" + " data.extend(chunk)\n" + " os.write(1, b'\\r\\nGOT ' + bytes(data).replace(b'\\x1b', b'ESC'))\n" + "finally:\n" + " termios.tcsetattr(0, termios.TCSADRAIN, old)\n" + ) + with sp.open_terminal(_command(raw_script), vt=sp.VT(rows=4, cols=40)) as p: + p.wait_for("RAW_OK", timeout=8) + p.resize(rows=6, cols=44) + p.send_event(MouseEvent(MouseButton.LEFT, MouseAction.PRESS, 1, 2)) + p.drain(timeout=5) + frame = p.wait_for("GOT ", timeout=8) + assert "ESC[48;6;44;" in frame.unwrapped_text + assert "ESC[<0;3;2M" in frame.unwrapped_text + assert p.wait(timeout=8) == 0 + + +@pytest.mark.skipif( + sys.platform == "win32" or os.name != "posix", + reason="requires POSIX PTY and socketpair", +) +async def test_darwin_helper_repeated_kill_does_not_drop_session() -> None: + """Repeated kill() on Darwin helper handles ProcessLookupError cleanly.""" + async with open_darwin_pty( + tuple(_command("print('D_ALIVE'); input()")), sp.VT(), None, None + ) as attached: + await attached.io.wait_for("D_ALIVE", timeout=8) + attached.process.kill() + attached.process.kill() + assert await asyncio.wait_for(attached.process.wait(), timeout=8) != 0 + attached.process.kill() + await attached.io.wait_for(lambda _: attached.io.eof, timeout=8) + + +@pytest.mark.usefixtures("_terminal_platform") +def test_unclosed_handle_exits_promptly_and_import_isolation() -> None: + """Unclosed open_terminal() does not hang exit; lazy imports stay isolated.""" + # Clean interpreter import isolation. + iso = subprocess.run( + [ + sys.executable, + "-c", + ( + "import sys, libvt\n" + "assert 'libvt.contrib.subprocess' not in sys.modules\n" + "import libvt.contrib.subprocess\n" + "for forbidden in ('pty', 'termios', 'ctypes', 'pytest', 'syrupy'):\n" + " assert forbidden not in sys.modules, forbidden\n" + ), + ], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + assert iso.returncode == 0, iso.stdout + iso.stderr + + # Leaving an open_terminal() handle unclosed with a live child exits cleanly + # with ResourceWarning and reaps the child process. + with tempfile.TemporaryDirectory() as folder: + live_pid_file = pathlib.Path(folder) / "live.pid" + exit_check = subprocess.run( + [ + sys.executable, + "-W", + "default::ResourceWarning", + "-c", + ( + "import os, pathlib, sys\n" + "from libvt.contrib import subprocess as sp\n" + f"pid_file = pathlib.Path({str(live_pid_file)!r})\n" + "child = sp.open_terminal([\n" + " sys.executable, '-u', '-c',\n" + " 'import os, pathlib, time; '\n" + " f'pathlib.Path({str(pid_file)!r})'\n" + " '.write_text(str(os.getpid())); '\n" + " 'print(\"LIVE\"); time.sleep(60)',\n" + "])\n" + "child.wait_for('LIVE', timeout=8)\n" + ), + ], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + assert exit_check.returncode == 0, exit_check.stdout + exit_check.stderr + assert "ResourceWarning" in exit_check.stderr + if os.name == "posix": + reaped_pid = int(live_pid_file.read_text()) + with pytest.raises(ProcessLookupError): + os.kill(reaped_pid, 0) + + # Mid-process garbage collection of an unclosed live handle emits + # ResourceWarning and reaps its child process. + with tempfile.TemporaryDirectory() as folder: + gc_pid_file = pathlib.Path(folder) / "gc.pid" + child = sp.open_terminal( + _command( + f"import os, pathlib, time; " + f"pathlib.Path({str(gc_pid_file)!r}).write_text(str(os.getpid())); " + "print('GC_LIVE'); time.sleep(60)" + ) + ) + child.wait_for("GC_LIVE", timeout=8) + gc_pid = child.pid + child_ref: list[sp.TerminalProcess] = [child] + del child + + def _drop_handle() -> None: + child_ref.clear() + gc.collect() + + with pytest.warns(ResourceWarning, match="unclosed TerminalProcess"): + _drop_handle() + if os.name == "posix": + with pytest.raises(ProcessLookupError): + os.kill(gc_pid, 0) + + +@pytest.mark.usefixtures("_terminal_platform") +def test_live_capture_nonzero_run_buffer_rewrite_and_drain_backpressure( + tmp_path: pathlib.Path, +) -> None: + """Exercise live capture, check=True/False, BufferError rewrite, and drain().""" + # Live capture() before close and BufferError rewrite for both session & stream. + with sp.open_terminal(_command("print('LIVE_CAP'); input()")) as child: + child.wait_for("LIVE_CAP", timeout=8) + live = child.capture() + assert live.eof is False + assert live.raw_total > 0 + assert b"LIVE_CAP" in live.raw_tail + assert "LIVE_CAP" in live.snapshot.text + + for async_msg in ( + "PTY write buffer exceeded 10 bytes; await session.drain()", + "stream write buffer exceeded 10 bytes; await stream.drain()", + ): + + async def _raise_buffer(message: str = async_msg) -> None: + raise BufferError(message) + + with pytest.raises(BufferError, match=r"call drain\(\)") as err: + child._owner.submit(_raise_buffer) + assert "await " not in str(err.value) + child.send(b"\r") + assert child.wait(timeout=8) == 0 + + # run_terminal check=False returns nonzero; check=True raises CalledTerminalError. + nonzero = sp.run_terminal( + _command("print('FAIL_OUT'); raise SystemExit(7)"), + check=False, + timeout=8, + ) + assert nonzero.returncode == 7 + assert "FAIL_OUT" in nonzero.snapshot.text + + with pytest.raises(sp.CalledTerminalError) as called: + sp.run_terminal( + _command("print('CHECK_FAIL'); raise SystemExit(9)"), + check=True, + timeout=8, + ) + assert isinstance(called.value, LibVtError) + assert called.value.returncode == 9 + assert called.value.result.returncode == 9 + assert "CHECK_FAIL" in called.value.result.snapshot.text + + # Early-exiting child with input does not raise BrokenPipeError/EIO. + early_marker = tmp_path / "early.txt" + early = sp.run_terminal( + _command( + "import pathlib; " + f"pathlib.Path({str(early_marker)!r}).write_text('EARLY_DONE')" + ), + input=b"x" * 70_000, + check=True, + timeout=8, + ) + assert early.returncode == 0 + assert early.eof is True + assert early_marker.read_text() == "EARLY_DONE" + + # Real POSIX drain() blocks while PTY kernel buffer is full and raises + # TerminalTimeoutExpired(phase="drain"), then drains once the child reads. + if os.name == "posix": + # Multi-chunk (>64 KiB) run_terminal(input=...) exercises chunked drain(). + big_reader = ( + "import sys\n" + "count = 0\n" + "for line in sys.stdin:\n" + " if line.strip() == 'END':\n" + " break\n" + " count += 1\n" + "print(f'LINES={count}')\n" + ) + chunked = sp.run_terminal( + _command(big_reader), + input=(b"a" * 63 + b"\n") * 1250 + b"END\n", + check=True, + timeout=10, + ) + assert "LINES=1250" in chunked.snapshot.text + + # Stalled reader triggers real drain(timeout=...) phase="drain" expiry. + stalled = ( + "import os, signal, termios, tty\n" + "old = termios.tcgetattr(0)\n" + "tty.setraw(0)\n" + "go = False\n" + "def _wake(_sig, _frame):\n" + " global go\n" + " go = True\n" + "signal.signal(signal.SIGUSR1, _wake)\n" + "try:\n" + " os.write(1, b'STALL_READY\\r\\n')\n" + " while not go:\n" + " signal.pause()\n" + " total = 0\n" + " while total < 32768:\n" + " chunk = os.read(0, 4096)\n" + " if not chunk:\n" + " break\n" + " total += len(chunk)\n" + " os.write(1, f'DRAINED={total}\\r\\n'.encode())\n" + "finally:\n" + " termios.tcsetattr(0, termios.TCSADRAIN, old)\n" + ) + with sp.open_terminal(_command(stalled), vt=sp.VT(rows=4, cols=40)) as p: + p.wait_for("STALL_READY", timeout=8) + p.send(b"z" * 32_768) + with pytest.raises(sp.TerminalTimeoutExpired) as drain_err: + p.drain(timeout=0.05) + assert drain_err.value.phase == "drain" + assert "phase=drain" in str(drain_err.value) + assert p.poll() is None + os.kill(p.pid, signal.SIGUSR1) + p.drain(timeout=5) + p.wait_for("DRAINED=32768", timeout=8) + assert p.wait(timeout=8) == 0