Skip to content

Commit d577976

Browse files
authored
contrib(feat): Drive terminal subprocesses (#142)
why: Synchronous callers and test suites need a direct way to spawn interactive programs inside a POSIX PTY or Windows ConPTY, wait for committed frames, send keys or mouse events, drain backpressure, and reap children without managing an asyncio event loop. what: Add libvt.contrib.subprocess (open_terminal, run_terminal, VT, Capture, CompletedTerminal, TerminalProcess, and LibVtError-derived exceptions), platform launchers (_darwin_pty, _conpty), shared POSIX PTY helpers in libvt.aio._pty, API docs, tests, and changelog entries. Fixes #106
2 parents 974a4fa + 84b0285 commit d577976

13 files changed

Lines changed: 2734 additions & 42 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ what was asked for.
2424
| `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 |
2525
| `src/libvt/pytest_plugin.py` | Import-light `pytest11` plugin (`libvt[pytest]`): `vt_terminal`, `vt_factory`, `vt_recorder`, `vt_parser`, and `vt_pty` |
2626
| `src/libvt/contrib/syrupy.py` | Optional `syrupy` `.ambr` adapter (`libvt[syrupy]`): `VtSnapshotExtension` and conditional `vt_snapshot` `pytest11` hook |
27+
| `src/libvt/contrib/subprocess.py` | Synchronous PTY/ConPTY subprocess driver (`open_terminal`, `run_terminal`, `TerminalProcess`, `VT`, `Capture`, `CompletedTerminal`) |
2728
| `tests/` | Functional, property-fuzz, PTY, CLI, and fixture tests organized by module under test |
2829
| `docs/` | Sphinx/MyST site: `topics/` (concepts), `api/` (autodoc), `project/` (contributing, releasing, ADRs `0001`–`0010`) |
2930
| `scripts/` | Unicode table generator (`generate_ucd.py`) and VT throughput benchmarks (`bench_vt.py`, `benchmark.py`) |

‎CHANGES‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,20 @@ _Notes on the upcoming release will go here._
88

99
### What's new
1010

11+
#### Drive terminal processes synchronously (#142)
12+
13+
{func}`~libvt.contrib.subprocess.open_terminal` opens an interactive child on a
14+
POSIX PTY or Windows ConPTY, returning a
15+
{class}`~libvt.contrib.subprocess.TerminalProcess` handle. Use
16+
{func}`~libvt.contrib.subprocess.run_terminal` to collect a child's exit
17+
status, final viewport, and bounded output in a
18+
{class}`~libvt.contrib.subprocess.CompletedTerminal` result. Both
19+
{class}`~libvt.contrib.subprocess.TerminalProcess` and
20+
{class}`~libvt.contrib.subprocess.Capture` implement
21+
{class}`~libvt.testing.SupportsVtTarget` for
22+
{func}`~libvt.testing.vt_screen` and
23+
{func}`~libvt.testing.serialize_vt_snapshot`.
24+
1125
#### Recorder protocol, target protocol, and state replacement (#203)
1226

1327
Pass any {class}`~libvt.recorder.TerminalRecorder` implementation to

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,8 @@ styles:
239239
(`?2026`).
240240
- Encode keyboard, mouse, focus, and paste events according to the active
241241
terminal modes.
242+
- Drive [terminal processes](https://libvt.git-pull.com/api/contrib/subprocess/)
243+
synchronously on POSIX or Windows.
242244
- Run terminal programs on POSIX PTYs or connect to `asyncio` streams (see the
243245
[fzf cookbook][fzf_cookbook] for driving a live picker and verifying Enter,
244246
Escape, and Ctrl-C outcomes).

‎docs/api/contrib/index.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ Decoupled `tmux` profiles, `capture-pane` decoders, multi-pane window
1212
compositing, and `-C` / `-CC` control-mode synchronization.
1313
:::
1414

15+
:::{grid-item-card} `libvt.contrib.subprocess`
16+
:link: subprocess
17+
:link-type: doc
18+
Synchronous child processes on POSIX PTYs and Windows ConPTY.
19+
:::
20+
1521
:::{grid-item-card} `libvt.contrib.syrupy`
1622
:link: syrupy
1723
:link-type: doc
@@ -30,5 +36,6 @@ fixture (`libvt[syrupy]`).
3036
:maxdepth: 2
3137
3238
tmux/index
39+
subprocess
3340
syrupy
3441
```

‎docs/api/contrib/subprocess.md‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
# `libvt.contrib.subprocess`
2+
3+
Use {mod}`libvt.contrib.subprocess` to drive a terminal application from
4+
synchronous Python. The session reads merged terminal output in a background
5+
thread while your caller waits for text, sends input, drains backpressure, or
6+
resizes the viewport.
7+
8+
```python
9+
>>> import sys
10+
>>> from libvt.contrib import subprocess as sp
11+
>>> command = [
12+
... sys.executable,
13+
... "-u",
14+
... "-c",
15+
... "print('Ready'); print('Result:', input()[::-1])",
16+
... ]
17+
>>> try:
18+
... with sp.open_terminal(command, vt=sp.VT(rows=6, cols=40)) as child:
19+
... _ = child.wait_for("Ready", timeout=8)
20+
... child.resize(rows=8, cols=48)
21+
... child.paste("pear")
22+
... child.send_key("enter")
23+
... status = child.wait(timeout=8)
24+
... final = child.wait_eof(timeout=8)
25+
... assert (status, final.snapshot.lines[2]) == (0, "Result: raep")
26+
... except NotImplementedError:
27+
... pass
28+
```
29+
30+
For commands that finish on their own, call
31+
{func}`~libvt.contrib.subprocess.run_terminal` with a
32+
{class}`~libvt.contrib.subprocess.VT` geometry configuration and pass the
33+
returned {class}`~libvt.contrib.subprocess.CompletedTerminal` directly to
34+
{func}`~libvt.testing.vt_screen` or
35+
{func}`~libvt.testing.serialize_vt_snapshot`:
36+
37+
```python
38+
>>> import sys
39+
>>> from libvt.contrib import subprocess as sp
40+
>>> from libvt.testing import serialize_vt_snapshot
41+
>>> try:
42+
... done = sp.run_terminal(
43+
... [sys.executable, "-c", "print('OK')"],
44+
... vt=sp.VT(rows=2, cols=8),
45+
... check=True,
46+
... timeout=8,
47+
... )
48+
... assert "│OK │" in serialize_vt_snapshot(done)
49+
... except NotImplementedError:
50+
... pass
51+
```
52+
53+
## Waiting, timeouts, and EOF
54+
55+
{meth}`~libvt.contrib.subprocess.TerminalProcess.wait` returns the direct
56+
child's exit status. Use
57+
{meth}`~libvt.contrib.subprocess.TerminalProcess.wait_eof` to collect final
58+
output after every process attached to the terminal closes its terminal
59+
handles, since descendants can keep the terminal open after the direct child
60+
exits. {meth}`~libvt.contrib.subprocess.TerminalProcess.drain` waits until all
61+
queued outbound bytes flush to the terminal. Each of `wait()`, `wait_eof()`,
62+
and `drain()` leaves the live handle open on timeout.
63+
64+
Two distinct timeout exception families apply depending on which call timed
65+
out; catching only builtin {exc}`TimeoutError` misses
66+
{exc}`~libvt.contrib.subprocess.TerminalTimeoutExpired`:
67+
68+
| Call | Timeout exception | Base classes | Failure detail |
69+
| --- | --- | --- | --- |
70+
| {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. |
71+
| {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`. |
72+
73+
{func}`~libvt.contrib.subprocess.run_terminal` waits for outbound input drain,
74+
child exit, and terminal EOF under a shared timeout. When `check=True` and the
75+
direct child exits nonzero, it raises
76+
{exc}`~libvt.contrib.subprocess.CalledTerminalError` (exposing `.result`). On
77+
timeout, it closes the terminal and reaps the direct child before raising
78+
{exc}`~libvt.contrib.subprocess.TerminalTimeoutExpired`. Interactive commands
79+
that wait for a prompt work with
80+
{func}`~libvt.contrib.subprocess.open_terminal`.
81+
82+
## Snapshots and output retention
83+
84+
Use a live {class}`~libvt.contrib.subprocess.TerminalProcess` handle from its
85+
creating thread and close it via `with` or
86+
{meth}`~libvt.contrib.subprocess.TerminalProcess.close`. Call `wait_eof()`
87+
first when descendant output matters.
88+
{class}`~libvt.contrib.subprocess.Capture`,
89+
{class}`~libvt.contrib.subprocess.CompletedTerminal`, and
90+
{class}`~libvt.contrib.subprocess.TerminalProcess` implement
91+
{class}`~libvt.testing.SupportsVtTarget`, so
92+
{func}`~libvt.testing.vt_screen` and
93+
{func}`~libvt.testing.serialize_vt_snapshot` accept them directly.
94+
95+
Each capture holds the last committed {class}`~libvt.snapshot.Snapshot`, the
96+
bounded `raw_tail` (up to `VT.raw_limit`; `0` disables tail retention while
97+
still counting `raw_total`), and whether EOF was reached. Raw bytes include
98+
terminal control sequences and native console translation.
99+
100+
## Platform notes
101+
102+
- **Linux / POSIX PTY**: `close()` escalates `SIGHUP`, `SIGTERM`, and `SIGKILL`
103+
to the child process group. A descendant that ignores hangup can outlive the
104+
terminal after the direct child exits.
105+
- **macOS (Darwin)**: A single-trampoline helper owns the controlling PTY
106+
session over a socketpair so direct-child exit leaves the terminal open for
107+
descendants; `close()` terminates the direct child with `SIGKILL` and shuts
108+
down the session leader. Opening `/dev/tty` can hold a Darwin kernel
109+
reference until the session closes (see
110+
[Apple's controlling-terminal driver](https://github.com/apple-oss-distributions/xnu/blob/f6217f891ac0bb64f3d375211650a4c1ff8ca1ea/bsd/kern/tty_tty.c));
111+
call `close()` once you have collected the output you need.
112+
- **Windows (ConPTY)**: Requires `ReleasePseudoConsole` (Windows 11 24H2 or
113+
Windows Server 2025, build 26100; see
114+
[Microsoft's ReleasePseudoConsole documentation](https://learn.microsoft.com/en-us/windows/console/releasepseudoconsole))
115+
to observe natural EOF after the last console client exits. `close()`
116+
terminates the child via `TerminateProcess` and closes the pseudoconsole.
117+
Pass an absolute executable path for consistent executable lookup across
118+
operating systems.
119+
120+
## API reference
121+
122+
```{eval-rst}
123+
.. automodule:: libvt.contrib.subprocess
124+
:members:
125+
```

‎docs/api/index.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,12 @@ Import-light `vt_terminal`, `vt_factory`, `vt_recorder`, `vt_parser`, and
9292
Decoupled `tmux` `profile`, `capture`, `window`, and `control` submodules.
9393
:::
9494

95+
:::{grid-item-card} `libvt.contrib.subprocess`
96+
:link: contrib/subprocess
97+
:link-type: doc
98+
Synchronous child processes on POSIX PTYs and Windows ConPTY.
99+
:::
100+
95101
:::{grid-item-card} `libvt.contrib.syrupy`
96102
:link: contrib/syrupy
97103
:link-type: doc

‎docs/project/public-api.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ Import specialized types and helpers from their owning submodules:
4545
{mod}`~libvt.contrib.tmux.control`) — decoupled `tmux` inner-pane profiles,
4646
`capture-pane` decoders, multi-pane window compositing, and `-C` / `-CC`
4747
control-mode parser and pane sync
48+
- {mod}`libvt.contrib.subprocess` — synchronous child processes with
49+
{func}`~libvt.contrib.subprocess.open_terminal` and
50+
{func}`~libvt.contrib.subprocess.run_terminal` on POSIX PTYs and Windows
51+
ConPTY
4852
- {mod}`libvt.contrib.syrupy` — optional `syrupy` `.ambr` adapter
4953
(`libvt[syrupy]`): {class}`~libvt.contrib.syrupy.VtSnapshotExtension` and
5054
conditional {fixture}`vt_snapshot` `pytest11` fixture

‎docs/topics/architecture.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,10 @@ fixture body when a test requests it. Import `libvt.aio`, `libvt.testing`,
4343
and peer integrations under `libvt.contrib` separately when needed. Importing
4444
`libvt.aio` loads `asyncio` and `libvt.terminal`, while POSIX `pty` and
4545
`termios` load inside {func}`~libvt.aio.open_pty`. Under `libvt.contrib`,
46-
{mod}`libvt.contrib.tmux` resolves its re-exports lazily, and
47-
{mod}`libvt.contrib.syrupy` defers importing `syrupy` and `libvt.testing`.
46+
{mod}`libvt.contrib.tmux` resolves its re-exports lazily,
47+
{mod}`libvt.contrib.syrupy` defers importing `syrupy` and `libvt.testing`, and
48+
{mod}`libvt.contrib.subprocess` loads platform-specific PTY or ConPTY backends
49+
only when a terminal process is opened.
4850

4951
## Configuration
5052

0 commit comments

Comments
 (0)