Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`) |
Expand Down
14 changes: 14 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
7 changes: 7 additions & 0 deletions docs/api/contrib/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -30,5 +36,6 @@ fixture (`libvt[syrupy]`).
:maxdepth: 2
tmux/index
subprocess
syrupy
```
125 changes: 125 additions & 0 deletions docs/api/contrib/subprocess.md
Original file line number Diff line number Diff line change
@@ -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:
```
6 changes: 6 additions & 0 deletions docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions docs/project/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions docs/topics/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading
Loading