Skip to content
Open
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
30 changes: 30 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,36 @@ _Notes on the upcoming release will go here._

Local watch mode, the editor and CI use ty 0.0.113. CI checks the minimum supported Python version and its matrix target. ([#936](https://github.com/tmux-python/libtmux/pull/936))

### What's new

#### Reconstruct pane terminal state (#934)

Install `libtmux[vt]` on Python 3.12 and later to inspect pane screens through
{mod}`libtmux.vt` and [libvt](https://libvt.git-pull.com) while keeping core
`libtmux` dependency-free on Python 3.11 and later.
{meth}`~libtmux.Pane.capture_vt` returns viewport and scrollback cells, styles,
cursor state, and active terminal modes, paired with
{func}`~libtmux.vt.assert_pane_screen` and
{func}`~libtmux.vt.assert_pane_screen_box` for test assertions; the surface is
provisional while `libvt` is pre-`0.1`. See {ref}`vt` for details.

#### Stream live pane updates over control mode (#934)

{meth}`~libtmux.Session.observe_vt`, {meth}`~libtmux.Pane.observe_vt`, and the
{fixture}`vt_observer` `pytest` fixture synchronize live pane state over control
mode ({class}`~libtmux.vt.VtSessionObserver` and
{class}`~libtmux.vt.VtPaneHandle`) with tear-free
{meth}`~libtmux.vt.VtPaneHandle.wait_until` snapshots and
{meth}`~libtmux.vt.VtPaneHandle.resync`.

#### Encode mode-aware pane input (#934)

{meth}`~libtmux.Pane.send_vt_input` and
{meth}`~libtmux.vt.VtPaneHandle.send_input` encode key chords, mouse events,
bracketed paste, and focus events for a pane's active modes. Without a live
observer, bracketed paste requires tmux 3.7+ and focus events require tmux 3.8+,
raising {exc}`~libtmux.exc.VersionTooLow` on earlier releases.

## libtmux 0.70.0 (2026-11-28)

libtmux 0.70.0 moves static type checking from mypy to strict
Expand Down
40 changes: 40 additions & 0 deletions capabilities.json
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,46 @@
"command": "new-pane"
}
]
},
{
"id": "bracket-paste-format",
"name": "Bracketed-paste format token",
"summary": "Detect a pane's bracketed-paste mode in a one-shot format query without a live control-mode observer.",
"since": "3.7",
"handling": "refuse",
"error": "libtmux.exc.VersionTooLow",
"apis": [
"libtmux.Pane.send_vt_input",
"libtmux.vt.send_pane_vt_input"
],
"commands": [
{
"command": "display-message",
"flags": [
"-p"
]
}
]
},
{
"id": "pane-private-modes-format",
"name": "Private-mode format token",
"summary": "Detect a pane's focus-event mode in a one-shot format query without a live control-mode observer.",
"since": "3.8",
"handling": "refuse",
"error": "libtmux.exc.VersionTooLow",
"apis": [
"libtmux.Pane.send_vt_input",
"libtmux.vt.send_pane_vt_input"
],
"commands": [
{
"command": "display-message",
"flags": [
"-p"
]
}
]
}
],
"workarounds": []
Expand Down
8 changes: 8 additions & 0 deletions docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ Format strings and constants.
Exception hierarchy.
:::

:::{grid-item-card} VT Integration
:link: libtmux.vt
:link-type: doc
Optional [libvt](https://libvt.git-pull.com) capture, live `tmux -C` sync,
mode-aware input, and screen assertions.
:::

::::

## Testing
Expand Down Expand Up @@ -179,4 +186,5 @@ Hooks <libtmux.hooks>
Constants <libtmux.constants>
Formats <libtmux.formats>
Exceptions <libtmux.exc>
VT Integration <libtmux.vt>
```
266 changes: 266 additions & 0 deletions docs/api/libtmux.vt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
(vt)=

# VT Integration (`libtmux.vt`)

{mod}`libtmux.vt` pairs `libtmux` with [libvt](https://libvt.git-pull.com) on
Python 3.12+ to reconstruct pane screens, immutable `Snapshot` grids, and `SGR`
styles via {meth}`~libtmux.Pane.capture_vt`, stream live `tmux -C` updates via
{meth}`~libtmux.Session.observe_vt`, {meth}`~libtmux.Pane.observe_vt`, and
{fixture}`vt_observer`, encode mode-aware input via
{meth}`~libtmux.Pane.send_vt_input`, and check screens with
{func}`~libtmux.vt.assert_pane_screen` and
{func}`~libtmux.vt.assert_pane_screen_box`.

Install with the `vt` extra:

```console
$ uv add "libtmux[vt]"
```

```{note}
{mod}`libtmux.vt`, {meth}`~libtmux.Pane.capture_vt`,
{meth}`~libtmux.Pane.observe_vt`, {meth}`~libtmux.Pane.send_vt_input`,
{meth}`~libtmux.Session.observe_vt`, and {fixture}`vt_observer` are provisional
while `libvt` is pre-`0.1` and may change across minor releases.
```

## Capture a pane and inspect its `Snapshot` grid

For synchronous inspection without opening a `tmux -C` client, call
{meth}`~libtmux.Pane.capture_vt`, {meth}`~libtmux.Pane.send_vt_input`, and
{func}`~libtmux.vt.assert_pane_screen` directly on a {class}`~libtmux.Pane`.
`captured.snapshot` is an immutable 2D `libvt.Snapshot` whose cells, soft-wrap
markers (`│W`), cursor coordinates, and `SGR` spans render directly as boxed
diagrams. Stop here if you only need one-shot captures:

```python
>>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE
>>> import shlex
>>> import sys
>>> from libvt.testing import format_screen_box, serialize_vt_snapshot
>>> from libtmux.test.retry import retry_until
>>> from libtmux.vt import assert_pane_screen
>>> writer = (
... "import sys; "
... "sys.stdout.write("
... "'\\x1b[2J\\x1b[H\\x1b[1;32mPASS\\x1b[0m suite=core_vt\\r\\n"
... "\\x1b[7m> rerun\\x1b[0m'"
... "); "
... "sys.stdout.flush(); sys.stdin.read(1)"
... )
>>> quick_session = server.new_session(
... session_name="vt-quick",
... x=16,
... y=3,
... window_command=f"{shlex.quote(sys.executable)} -u -c {shlex.quote(writer)}",
... )
>>> quick_pane = quick_session.active_pane
>>> assert quick_pane is not None
>>> retry_until(lambda: "rerun" in quick_pane.capture_vt(history_lines=0).snapshot.text)
True
>>> captured = quick_pane.capture_vt(history_lines=0)
>>> snap = captured.snapshot
>>> print(format_screen_box(snap))
┌────────────────┐
│PASS suite=core_│W
│vt │
│> rerun │
└────────────────┘
>>> print(serialize_vt_snapshot(snap))
size=16x3 cursor=(2,7,vis=True) alt=False modes=[]
┌────────────────┐
│PASS suite=core_│W
│vt │
│> rerun │
└────────────────┘
styles:
r0[0..4]: bold fg=green
r2[0..7]: reverse
>>> snap[0, 0].text, snap[0, 0].style.bold, snap[2, 0].style.reverse
('P', True, True)
>>> print(serialize_vt_snapshot(snap[0:2, 0:4]))
size=4x2 region=True
┌────┐
│PASS│
│vt │
└────┘
styles:
r0[0..4]: bold fg=green
>>> assert_pane_screen(captured, "PASS suite=core_\nvt\n> rerun", cursor=(2, 7))
>>> _ = quick_pane.send_vt_input("enter")
```

## Page through captured scrollback (`snap.viewport()`)

When `history_lines` retains primary scrollback (`None` for full history or a
positive row count), `snap.viewport(offset=...)` returns a rectangular view
shifted upward into scrollback without mutating the pane or terminal:

```python
>>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE
>>> import shlex
>>> import sys
>>> from libvt.testing import serialize_vt_snapshot
>>> from libtmux.test.retry import retry_until
>>> log_writer = (
... "import sys; "
... "sys.stdout.write('step 1\\r\\nstep 2\\r\\nstep 3\\r\\nstep 4'); "
... "sys.stdout.flush(); sys.stdin.read(1)"
... )
>>> hist_session = server.new_session(
... session_name="vt-history",
... x=12,
... y=2,
... window_command=f"{shlex.quote(sys.executable)} -u -c {shlex.quote(log_writer)}",
... )
>>> hist_pane = hist_session.active_pane
>>> assert hist_pane is not None
>>> retry_until(lambda: "step 4" in hist_pane.capture_vt().snapshot.text)
True
>>> hist_snap = hist_pane.capture_vt().snapshot
>>> print(serialize_vt_snapshot(hist_snap.viewport(offset=0)))
size=12x2 region=True
┌────────────┐
│step 3 │
│step 4 │
└────────────┘
>>> print(serialize_vt_snapshot(hist_snap.viewport(offset=2)))
size=12x2 region=True
┌────────────┐
│step 1 │
│step 2 │
└────────────┘
>>> _ = hist_pane.send_vt_input("enter")
```

## Test an interactive terminal application running in tmux

For interactive TUIs that switch into the alternate screen (`?1049`), repaint on
key presses, or emit synchronized frames (`?2026`), attach a
{class}`~libtmux.vt.VtSessionObserver`, await tear-free `Snapshot` checkpoints
from {meth}`~libtmux.vt.VtPaneHandle.wait_until`, send structured input with
{meth}`~libtmux.vt.VtPaneHandle.send_input`, diff consecutive frames with
`vt_screen(..., diff=...)`, inspect timeout diagnostics, and verify
primary-screen restoration before closing the observer:

```python
>>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE
>>> import asyncio
>>> import shlex
>>> import sys
>>> from libvt.input import KeyEvent
>>> from libvt.testing import format_screen_box, serialize_vt_snapshot, vt_screen
>>> from libtmux.vt import assert_pane_screen_box
>>> menu_app = (
... "import sys, termios, tty; "
... "fd = sys.stdin.fileno(); old = termios.tcgetattr(fd); tty.setraw(fd); "
... "items = ['api', 'worker']; idx = 0\n"
... "def draw():\n"
... " rows = ['Select service:'] + [\n"
... " f'\\x1b[7m> {it}\\x1b[0m' if i == idx else f' {it}'\n"
... " for i, it in enumerate(items)\n"
... " ]\n"
... " sys.stdout.write("
... "'\\x1b[?1049h\\x1b[?25l\\x1b[2J\\x1b[H' + '\\r\\n'.join(rows)"
... ")\n"
... " sys.stdout.flush()\n"
... "draw()\n"
... "while True:\n"
... " b = sys.stdin.buffer.read(1)\n"
... " if b == b'\\x1b':\n"
... " seq = sys.stdin.buffer.read(2)\n"
... " if seq in (b'[B', b'OB'):\n"
... " idx = (idx + 1) % len(items); draw()\n"
... " elif b in (b'\\r', b'\\n'):\n"
... " termios.tcsetattr(fd, termios.TCSADRAIN, old)\n"
... " sys.stdout.write("
... "f'\\x1b[?25h\\x1b[?1049lselected={items[idx]}\\r\\n'"
... ")\n"
... " sys.stdout.flush()\n"
... " sys.stdin.buffer.read(1)\n"
... " break\n"
... )
>>> tui_session = server.new_session(
... session_name="tui-recipe",
... x=20,
... y=4,
... window_command=f"{shlex.quote(sys.executable)} -u -c {shlex.quote(menu_app)}",
... )
>>> tui_pane = tui_session.active_pane
>>> assert tui_pane is not None
>>> async def exercise_menu() -> None:
... async with tui_session.observe_vt(history_lines=0) as observer:
... handle = await observer.watch_pane(tui_pane)
... initial = await handle.wait_until(
... lambda snap: snap.active_is_alt and "worker" in snap.text
... )
... print(serialize_vt_snapshot(initial))
...
... await handle.send_input(KeyEvent("down"))
... moved = await handle.wait_until(lambda snap: snap[2, 0].style.reverse)
... assert_pane_screen_box(
... moved,
... """
... ┌────────────────────┐
... │Select service: │
... │ api │
... │> worker │
... │ │
... └────────────────────┘
... """,
... )
... print(serialize_vt_snapshot(vt_screen(moved, diff=initial)))
...
... try:
... await handle.wait_until("unreachable", timeout=0.05)
... except TimeoutError as err:
... assert "> worker" in str(err)
... assert "recent_bytes" in str(err)
...
... await handle.send_input(KeyEvent("enter"))
... done = await handle.wait_until(
... lambda snap: not snap.active_is_alt and "selected=worker" in snap.text
... )
... assert done.cursor.visible is True
... print(format_screen_box(done))
>>> asyncio.run(exercise_menu())
size=20x4 cursor=(2,8,vis=False) alt=True modes=[]
┌────────────────────┐
│Select service: │
│> api │
│ worker │
│ │
└────────────────────┘
styles:
r1[0..5]: reverse
row 1 cols 0..1: '>' -> ' '
row 2 cols 0..1: ' ' -> '>'
styles: [' r1[0..5]: reverse'] -> [' r2[0..8]: reverse']
size=20x4 cursor=(2,8,vis=False) alt=True modes=[]
┌────────────────────┐
│Select service: │
- │> api │
+ │ api │
│^ │
- │ worker │
+ │> worker │
│^ │
│ │
└────────────────────┘
styles:
- r1[0..5]: reverse
+ r2[0..8]: reverse
┌────────────────────┐
│selected=worker │
│ │
│ │
│ │
└────────────────────┘
```

## API Reference

```{eval-rst}
.. automodule:: libtmux.vt
:members:
```
3 changes: 3 additions & 0 deletions docs/api/testing/pytest-plugin/fixtures.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ True
| {fixture}`session_params` | Session creation override |
| {fixture}`TestServer` | Factory for extra isolated servers |
| {fixture}`control_mode` | Attached client factory |
| {fixture}`vt_observer` | Async `libtmux[vt]` control-mode observer factory |
| {fixture}`clear_env` | Minimal test environment |

---
Expand Down Expand Up @@ -90,6 +91,8 @@ Override these in your project's `conftest.py` to customise the test environment

.. autofixture:: libtmux.pytest_plugin.control_mode

.. autofixture:: libtmux.pytest_plugin.vt_observer

```

## Low-Level / Rarely Needed
Expand Down
Loading
Loading