diff --git a/CHANGES b/CHANGES index fe2afd8e12..00d58fd003 100644 --- a/CHANGES +++ b/CHANGES @@ -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 diff --git a/capabilities.json b/capabilities.json index de93c793bd..dd7ce5f3e6 100644 --- a/capabilities.json +++ b/capabilities.json @@ -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": [] diff --git a/docs/api/index.md b/docs/api/index.md index 8e8dadcfc3..c3f8be7a08 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -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 @@ -179,4 +186,5 @@ Hooks Constants Formats Exceptions +VT Integration ``` diff --git a/docs/api/libtmux.vt.md b/docs/api/libtmux.vt.md new file mode 100644 index 0000000000..dcf8a6b5d4 --- /dev/null +++ b/docs/api/libtmux.vt.md @@ -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: +``` diff --git a/docs/api/testing/pytest-plugin/fixtures.md b/docs/api/testing/pytest-plugin/fixtures.md index eac1891b08..c3453c95c1 100644 --- a/docs/api/testing/pytest-plugin/fixtures.md +++ b/docs/api/testing/pytest-plugin/fixtures.md @@ -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 | --- @@ -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 diff --git a/pyproject.toml b/pyproject.toml index e5f9b2dc15..51cff539a7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,6 +48,11 @@ Documentation = "https://libtmux.git-pull.com" Repository = "https://github.com/tmux-python/libtmux" Changes = "https://github.com/tmux-python/libtmux/blob/master/CHANGES" +[project.optional-dependencies] +vt = [ + "libvt>=0.0.1a4,<0.1; python_version >= '3.12'", +] + [dependency-groups] dev = [ # Docs (via gp-sphinx) @@ -135,12 +140,17 @@ sphinx-gp-sitemap = false sphinx-gp-theme = false sphinx-ux-autodoc-layout = false sphinx-ux-badges = false +libvt = false # Adopt ty releases immediately, bypassing the global cooldown. ty = false [tool.ty.environment] python-version = "3.11" +[tool.ty.analysis] +# libvt is an optional Python 3.12+ extra (`libtmux[vt]`), absent in 3.11 and core environments +allowed-unresolved-imports = ["libvt", "libvt.**"] + [tool.ty.src] include = [ "src", @@ -292,6 +302,10 @@ convention = "numpy" # `Server.is_alive` maps any unreachable-daemon failure to False — https://docs.astral.sh/ruff/rules/blind-except/ "BLE001", ] +"src/libtmux/vt.py" = [ + # Background `tmux -C` reader loop records unexpected decode/sync errors onto the observer — https://docs.astral.sh/ruff/rules/blind-except/ + "BLE001", +] [tool.pytest.ini_options] addopts = [ diff --git a/src/libtmux/_internal/support/capabilities.py b/src/libtmux/_internal/support/capabilities.py index cb457d99ac..6c05565983 100644 --- a/src/libtmux/_internal/support/capabilities.py +++ b/src/libtmux/_internal/support/capabilities.py @@ -204,6 +204,32 @@ def to_manifest(self) -> dict[str, t.Any]: commands=(Command("new-pane"),), error="libtmux.exc.LibTmuxException", ), + Capability( + 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", + apis=("libtmux.Pane.send_vt_input", "libtmux.vt.send_pane_vt_input"), + commands=(Command("display-message", ("-p",)),), + error="libtmux.exc.VersionTooLow", + ), + Capability( + 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", + apis=("libtmux.Pane.send_vt_input", "libtmux.vt.send_pane_vt_input"), + commands=(Command("display-message", ("-p",)),), + error="libtmux.exc.VersionTooLow", + ), ) _BY_ID: dict[str, Capability] = { diff --git a/src/libtmux/pane.py b/src/libtmux/pane.py index cdc49fbc0c..9f8c6a3790 100644 --- a/src/libtmux/pane.py +++ b/src/libtmux/pane.py @@ -41,10 +41,17 @@ from libtmux.options import OptionsMixin if t.TYPE_CHECKING: + import contextlib import types from typing import Never, Self + from libvt.config import Limits, Policy, Profile + from libvt.contrib.tmux.capture import TmuxCaptureResult + from libvt.input import InputEvent + from libvt.terminal import Snapshot, Terminal + from libtmux.formats import Format + from libtmux.vt import VtPaneHandle from .server import Server from .session import Session @@ -2929,6 +2936,252 @@ def at_right(self) -> bool: """ return self.pane_at_right == "1" + # + # VT integration (optional libtmux[vt] extra on Python 3.12+) + # + def capture_vt( + self, + *, + history_lines: int | None = None, + include_saved_primary: bool = True, + scrollback: int | None = None, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + timeout: float | _UnsetType | None = _UNSET, + ) -> TmuxCaptureResult: + r"""Capture pane cells, styles, cursor, and metadata into a ``libvt`` result. + + Requires Python 3.12+ and ``libtmux[vt]`` (``pip install "libtmux[vt]"``). + + Parameters + ---------- + history_lines : int or None, optional + Maximum scrollback lines above the viewport (``None`` for full + history, ``0`` for viewport-only ``-S 0``, or ``N > 0`` for + ``-S -N``). + include_saved_primary : bool, default True + Include ``capture-pane -a -q`` sections to preserve primary + scrollback while ``?1049`` alternate screen is active. + scrollback : int or None, optional + Explicit scrollback line capacity for the reconstructed terminal. + profile : Profile or None, optional + Optional ``libvt`` terminal profile override. + policy : Policy or None, optional + Optional ``libvt`` security/reply policy override. + limits : Limits or None, optional + Optional ``libvt`` parser/buffer limits override. + timeout : float or None, optional + Subprocess timeout in seconds; inherits :attr:`Server.timeout` when + omitted. + + Returns + ------- + TmuxCaptureResult + Reconstructed ``libvt`` terminal, snapshot, metadata, line flags, + and capture completeness report. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libvt.testing import serialize_vt_snapshot + >>> from libtmux.test.retry import retry_until + >>> py = shlex.quote(sys.executable) + >>> cmd = ( + ... "import sys; " + ... "sys.stdout.write(" + ... "'\\x1b[2J\\x1b[H\\x1b[1;32mVT_OK\\x1b[0m\\r\\ndone'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="pane-cap-vt", + ... x=12, + ... y=2, + ... window_command=f"{py} -u -c {shlex.quote(cmd)}", + ... ) + >>> p = s.active_pane + >>> assert p is not None + >>> retry_until(lambda: "done" in p.capture_vt(history_lines=0).snapshot.text) + True + >>> print(serialize_vt_snapshot(p.capture_vt(history_lines=0).snapshot)) + size=12x2 cursor=(1,4,vis=True) alt=False modes=[] + ┌────────────┐ + │VT_OK │ + │done │ + └────────────┘ + styles: + r0[0..5]: bold fg=green + >>> _ = p.send_vt_input("enter") + """ + from libtmux.vt import capture_pane_vt + + return capture_pane_vt( + self, + history_lines=history_lines, + include_saved_primary=include_saved_primary, + scrollback=scrollback, + profile=profile, + policy=policy, + limits=limits, + timeout=timeout, + ) + + def observe_vt( + self, + *, + history_lines: int | None = None, + scrollback: int = 2_000, + ignore_size: bool = True, + attach_timeout: float = 5.0, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + ) -> contextlib.AbstractAsyncContextManager[VtPaneHandle]: + r"""Open a live ``tmux -C`` VT observer context for this pane. + + Requires Python 3.12+ and ``libtmux[vt]``. + + Parameters + ---------- + history_lines : int or None, optional + Maximum scrollback lines requested on attach and resync. + scrollback : int, default 2000 + Scrollback line capacity on the live ``Terminal``. + ignore_size : bool, default True + Pass ``-f ignore-size`` on ``attach-session`` so passive observation + does not alter window geometry. + attach_timeout : float, default 5.0 + Maximum seconds for the initial two-phase pause + capture + continue + handshake. + profile : Profile or None, optional + Optional ``libvt`` terminal profile override. + policy : Policy or None, optional + Optional ``libvt`` security/reply policy override. + limits : Limits or None, optional + Optional ``libvt`` parser/buffer limits override. + + Returns + ------- + AsyncContextManager[:class:`~libtmux.vt.VtPaneHandle`] + Async context manager yielding a live-synchronized handle. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import asyncio, shlex, sys + >>> from libvt.testing import format_screen_box + >>> py = shlex.quote(sys.executable) + >>> cmd = ( + ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[Hlive_ready'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="pane-obs-vt", + ... x=12, + ... y=2, + ... window_command=f"{py} -u -c {shlex.quote(cmd)}", + ... ) + >>> p = s.active_pane + >>> assert p is not None + >>> async def check_live() -> str: + ... async with p.observe_vt(history_lines=0) as handle: + ... snap = await handle.wait_until("live_ready") + ... await handle.send_input("enter") + ... return format_screen_box(snap) + >>> print(asyncio.run(check_live())) + ┌────────────┐ + │live_ready │ + │ │ + └────────────┘ + """ + from libtmux.vt import observe_pane_vt + + return observe_pane_vt( + self, + history_lines=history_lines, + scrollback=scrollback, + ignore_size=ignore_size, + attach_timeout=attach_timeout, + profile=profile, + policy=policy, + limits=limits, + ) + + def send_vt_input( + self, + event: InputEvent | str, + *, + terminal: ( + Terminal | Snapshot | TmuxCaptureResult | VtPaneHandle | None + ) = None, + timeout: float | _UnsetType | None = _UNSET, + ) -> bytes: + r"""Encode *event* for active pane VT modes and dispatch via ``send-keys -H``. + + Requires Python 3.12+ and ``libtmux[vt]``. + + Parameters + ---------- + event : InputEvent or str + ``libvt`` ``KeyEvent``, ``MouseEvent``, ``FocusEvent``, or + ``PasteEvent``, or a key chord string parsed via + ``KeyEvent.parse()`` (such as ``"up"``, ``"ctrl+c"``). + terminal : Terminal, Snapshot, TmuxCaptureResult, VtPaneHandle, or None + Pre-captured or live terminal state: ``Terminal``, + ``TmuxCaptureResult``, and ``VtPaneHandle`` supply active DEC modes, + ``modifyOtherKeys``, Kitty keyboard flags, and ``?1016`` cell pixel + dimensions, while ``Snapshot`` supplies active DEC modes and + alternate-screen state; when ``None``, captures viewport metadata + first. + timeout : float or None, optional + Subprocess timeout in seconds; inherits :attr:`Server.timeout` when + omitted. + + Returns + ------- + bytes + Exact wire bytes sent to the pane (``b""`` if suppressed by active + modes). + + Raises + ------ + :exc:`~libtmux.exc.VersionTooLow` + When *terminal* is ``None`` and *event* is a ``PasteEvent`` on + ``tmux < 3.7`` or a ``FocusEvent`` on ``tmux < 3.8``. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libtmux.test.retry import retry_until + >>> py = shlex.quote(sys.executable) + >>> cmd = ( + ... "import sys; sys.stdout.write('\\x1b[?1hready'); " + ... "sys.stdout.flush(); sys.stdin.buffer.read(3)" + ... ) + >>> s = server.new_session( + ... session_name="pane-inp-vt", + ... x=10, + ... y=2, + ... window_command=f"{py} -u -c {shlex.quote(cmd)}", + ... ) + >>> p = s.active_pane + >>> assert p is not None + >>> retry_until(lambda: "ready" in p.capture_vt(history_lines=0).snapshot.text) + True + >>> p.send_vt_input("up") + b'\x1bOA' + """ + from libtmux.vt import send_pane_vt_input + + return send_pane_vt_input( + self, + event, + terminal=terminal, + timeout=timeout, + ) + # # Legacy: Redundant stuff we want to remove # diff --git a/src/libtmux/pytest_plugin.py b/src/libtmux/pytest_plugin.py index f9cdf0a670..b490099ebe 100644 --- a/src/libtmux/pytest_plugin.py +++ b/src/libtmux/pytest_plugin.py @@ -20,7 +20,10 @@ from libtmux.test.random import get_test_session_name, namer if t.TYPE_CHECKING: + from libvt.config import Limits, Policy, Profile + from libtmux.session import Session + from libtmux.vt import VtSessionObserver logger = logging.getLogger(__name__) USING_ZSH = "zsh" in os.getenv("SHELL", "") @@ -325,6 +328,54 @@ def _make_control_mode() -> ControlMode: return _make_control_mode +class VtObserverFactory(t.Protocol): + """Callable factory for session-bound ``VtSessionObserver`` contexts.""" + + def __call__( + self, + *, + history_lines: int | None = None, + scrollback: int = 2_000, + ignore_size: bool = True, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + ) -> VtSessionObserver: + """Create a :class:`~libtmux.vt.VtSessionObserver` bound to ``session``.""" + ... + + +@pytest.fixture +def vt_observer( + session: Session, +) -> VtObserverFactory: + """Return a factory creating :class:`~libtmux.vt.VtSessionObserver` contexts. + + Lazily imports :mod:`libtmux.vt` only when invoked so test collection and + non-VT suites do not require ``libtmux[vt]`` or Python 3.12+. + """ + + def _make_vt_observer( + *, + history_lines: int | None = None, + scrollback: int = 2_000, + ignore_size: bool = True, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + ) -> VtSessionObserver: + return session.observe_vt( + history_lines=history_lines, + scrollback=scrollback, + ignore_size=ignore_size, + profile=profile, + policy=policy, + limits=limits, + ) + + return _make_vt_observer + + class ServerFactory(t.Protocol): """Callable factory for temporary :class:`~libtmux.Server` instances.""" diff --git a/src/libtmux/session.py b/src/libtmux/session.py index cb8f191f6b..9fc5b24055 100644 --- a/src/libtmux/session.py +++ b/src/libtmux/session.py @@ -44,6 +44,10 @@ import types from typing import Never, Self + from libvt.config import Limits, Policy, Profile + + from libtmux.vt import VtSessionObserver + from .server import Server @@ -1391,6 +1395,89 @@ def name(self) -> str | None: """ return self.session_name + # + # VT integration (optional libtmux[vt] extra on Python 3.12+) + # + def observe_vt( + self, + *, + history_lines: int | None = None, + scrollback: int = 2_000, + ignore_size: bool = True, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + ) -> VtSessionObserver: + r"""Create a session-scoped async ``tmux -C`` VT observer. + + Requires Python 3.12+ and ``libtmux[vt]``. A single + :class:`~libtmux.vt.VtSessionObserver` multiplexes any number of panes + in the session over one ``tmux -C attach-session`` subprocess. + + Parameters + ---------- + history_lines : int or None, optional + Default scrollback line bound for watched panes. + scrollback : int, default 2000 + Default scrollback capacity in lines for watched panes. + ignore_size : bool, default True + Pass ``-f ignore-size`` on ``attach-session`` so passive observation + does not alter window geometry. + profile : Profile or None, optional + Optional ``libvt`` terminal profile override. + policy : Policy or None, optional + Optional ``libvt`` security/reply policy override. + limits : Limits or None, optional + Optional ``libvt`` parser/buffer limits override. + + Returns + ------- + :class:`~libtmux.vt.VtSessionObserver` + Async context manager multiplexing + :meth:`~libtmux.vt.VtSessionObserver.watch_pane` handles. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import asyncio, shlex, sys + >>> from libvt.testing import format_screen_box + >>> py = shlex.quote(sys.executable) + >>> cmd = ( + ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[Hsession_ok'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="sess-obs-vt", + ... x=12, + ... y=2, + ... window_command=f"{py} -u -c {shlex.quote(cmd)}", + ... ) + >>> p = s.active_pane + >>> assert p is not None + >>> async def observe_one() -> str: + ... async with s.observe_vt(history_lines=0) as observer: + ... handle = await observer.watch_pane(p) + ... snap = await handle.wait_until("session_ok") + ... await handle.send_input("enter") + ... return format_screen_box(snap) + >>> print(asyncio.run(observe_one())) + ┌────────────┐ + │session_ok │ + │ │ + └────────────┘ + """ + from libtmux.vt import VtSessionObserver + + return VtSessionObserver( + self, + history_lines=history_lines, + scrollback=scrollback, + ignore_size=ignore_size, + profile=profile, + policy=policy, + limits=limits, + ) + # # Legacy: Redundant stuff we want to remove # diff --git a/src/libtmux/vt.py b/src/libtmux/vt.py new file mode 100644 index 0000000000..09091da71b --- /dev/null +++ b/src/libtmux/vt.py @@ -0,0 +1,1264 @@ +"""Optional ``libvt`` terminal capture, control-mode sync, and input bridge. + +Requires Python 3.12+ and the ``libtmux[vt]`` extra +(``pip install "libtmux[vt]"``). Importing :mod:`libtmux` or :mod:`libtmux.vt` +does not load ``libvt`` until a VT helper is called. + +Note +---- +This module is provisional while ``libvt`` is pre-``0.1`` and may evolve across +minor releases. +""" + +from __future__ import annotations + +import asyncio +import collections +import collections.abc +import contextlib +import importlib +import logging +import shutil +import sys +import time +import typing as t +from dataclasses import dataclass + +from libtmux import exc +from libtmux._compat import _UNSET, _UnsetType +from libtmux._internal.log_context import command_extra, object_extra +from libtmux._internal.support.capabilities import capability_since +from libtmux.common import ( + _raise_if_unusable_tmux, + get_version_str, + has_gte_version, + raise_if_stderr, +) + +if t.TYPE_CHECKING: + import types + from typing import Self + + from libvt.config import Limits, Policy, Profile + from libvt.contrib.tmux.capture import TmuxCaptureResult + from libvt.contrib.tmux.control import ( + TmuxCommandBlock, + TmuxControlEvent, + TmuxControlParser, + TmuxPaneSync, + ) + from libvt.input import InputEvent + from libvt.terminal import ( + FlightRecorder, + ScreenDelta, + Snapshot, + SyncToken, + Terminal, + ) + + from libtmux.pane import Pane + from libtmux.session import Session + +logger = logging.getLogger(__name__) + +_TERMINATE_TIMEOUT_SECONDS = 5.0 +_READ_CHUNK_BYTES = 65_536 + + +def _require_libvt() -> types.ModuleType: + """Validate Python >= 3.12 and import :mod:`libvt` lazily.""" + if sys.version_info < (3, 12): + msg = "VT integration requires Python 3.12 or later." + raise RuntimeError(msg) + try: + return importlib.import_module("libvt") + except ModuleNotFoundError as error: + msg = ( + "libvt is required for VT integration; " + 'install with: pip install "libtmux[vt]"' + ) + raise ModuleNotFoundError(msg) from error + + +def capture_pane_vt( + pane: Pane, + *, + history_lines: int | None = None, + include_saved_primary: bool = True, + scrollback: int | None = None, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + timeout: float | _UnsetType | None = _UNSET, +) -> TmuxCaptureResult: + r"""Capture *pane* into a reconstructed ``TmuxCaptureResult``. + + Executes the single-batch ``display-message`` + ``capture-pane`` command + built by ``build_tmux_capture_command()`` through :meth:`~libtmux.Server.cmd`, + preserving socket path validation, command timeouts, structured ``DEBUG`` + logging, and trailing blank viewport rows. + + Parameters + ---------- + pane : :class:`~libtmux.Pane` + Target tmux pane. + history_lines : int or None, optional + Maximum scrollback lines above the viewport (``None`` for full history, + ``0`` for viewport-only ``-S 0``, or ``N > 0`` for ``-S -N``). + include_saved_primary : bool, default True + Include ``capture-pane -a -q`` sections so saved primary scrollback is + preserved while an alternate-screen TUI (``?1049``) is active. + scrollback : int or None, optional + Explicit scrollback line capacity for the reconstructed terminal; + defaults to ``metadata.history_limit`` when ``None``. + profile : Profile or None, optional + Explicit terminal profile override; defaults to ``tmux_profile()`` for + the server's ``tmux`` version. + policy : Policy or None, optional + Explicit security/reply policy override. + limits : Limits or None, optional + Explicit parser/buffer resource limits override. + timeout : float or None, optional + Subprocess timeout in seconds; inherits :attr:`~libtmux.Server.timeout` + when omitted. + + Returns + ------- + TmuxCaptureResult + Reconstructed terminal, immutable snapshot, metadata, line flags, and + capture completeness report. + + Raises + ------ + ValueError + When ``pane.pane_id`` is unset or *history_lines* is negative. + TypeError + When *history_lines* is not ``int`` or ``None``. + :exc:`~libtmux.exc.LibTmuxException` + When ``tmux`` reports an error (such as a missing pane). + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libvt.testing import serialize_vt_snapshot + >>> from libtmux.test.retry import retry_until + >>> from libtmux.vt import capture_pane_vt + >>> cmd = ( + ... "import sys; " + ... "sys.stdout.write('\\x1b[2J\\x1b[H\\x1b[1;36mINFO\\x1b[0m ok'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="fn-cap-vt", + ... x=12, + ... y=2, + ... window_command=f"{shlex.quote(sys.executable)} -u -c {shlex.quote(cmd)}", + ... ) + >>> p = s.active_pane + >>> assert p is not None + >>> retry_until(lambda: "INFO" in capture_pane_vt(p, history_lines=0).snapshot.text) + True + >>> print(serialize_vt_snapshot(capture_pane_vt(p, history_lines=0).snapshot)) + size=12x2 cursor=(0,7,vis=True) alt=False modes=[] + ┌────────────┐ + │INFO ok │ + │ │ + └────────────┘ + styles: + r0[0..4]: bold fg=cyan + >>> _ = p.send_vt_input("enter") + """ + _require_libvt() + from libvt.config import DEFAULT_LIMITS + from libvt.contrib.tmux.capture import build_tmux_capture_command + from libvt.contrib.tmux.profile import TMUX_CAPTURE_POLICY, tmux_profile + + if pane.pane_id is None: + msg = "Pane must have a pane_id to capture VT state" + raise ValueError(msg) + + ver_str = get_version_str(pane.server.tmux_bin) + cap_cmd = build_tmux_capture_command( + pane.pane_id, + tmux_version=ver_str, + include_saved_primary=include_saved_primary, + history_lines=history_lines, + ) + proc = pane.server.cmd(*cap_cmd.argv, timeout=timeout) + if proc.stderr: + raise_if_stderr(proc, "capture-pane") + + eff_profile = tmux_profile(ver_str) if profile is None else profile + eff_policy = TMUX_CAPTURE_POLICY if policy is None else policy + eff_limits = DEFAULT_LIMITS if limits is None else limits + return cap_cmd.parse( + proc.stdout, + scrollback=scrollback, + profile=eff_profile, + policy=eff_policy, + limits=eff_limits, + ) + + +def _encode_for_terminal_target( + event: InputEvent | str, + target: Terminal | Snapshot | TmuxCaptureResult | VtPaneHandle, +) -> bytes: + """Encode *event* against *target*'s active modes and keyboard state.""" + from libvt.contrib.tmux.capture import TmuxCaptureResult + from libvt.input import KeyEvent, encode_input + from libvt.modes import ModeState + from libvt.terminal import Terminal + + ev = KeyEvent.parse(event) if isinstance(event, str) else event + unwrapped = ( + target.terminal + if isinstance(target, (TmuxCaptureResult, VtPaneHandle)) + else target + ) + if isinstance(unwrapped, Terminal): + encoded = unwrapped.encode(ev) + else: + encoded = encode_input( + ev, + modes=ModeState(set(unwrapped.modes)), + active_is_alt=unwrapped.active_is_alt, + ) + assert isinstance(encoded, bytes) + return encoded + + +def send_pane_vt_input( + pane: Pane, + event: InputEvent | str, + *, + terminal: Terminal | Snapshot | TmuxCaptureResult | VtPaneHandle | None = None, + timeout: float | _UnsetType | None = _UNSET, +) -> bytes: + """Encode *event* for *pane*'s active VT modes and send via ``send-keys -H``. + + Parameters + ---------- + pane : :class:`~libtmux.Pane` + Target tmux pane. + event : InputEvent or str + Structured ``KeyEvent``, ``MouseEvent``, ``FocusEvent``, or + ``PasteEvent``, or a key chord string parsed via ``KeyEvent.parse()`` + (for example ``"up"``, ``"ctrl+c"``, ``"shift+tab"``). + terminal : Terminal, Snapshot, TmuxCaptureResult, VtPaneHandle, or None + Pre-captured or live terminal state: ``Terminal``, + ``TmuxCaptureResult``, and ``VtPaneHandle`` supply active DEC modes, + ``modifyOtherKeys``, Kitty keyboard flags, and ``?1016`` cell pixel + dimensions, while ``Snapshot`` supplies active DEC modes and + alternate-screen state. When ``None``, captures viewport metadata from + *pane* first (``history_lines=0``). + timeout : float or None, optional + Subprocess timeout in seconds; inherits :attr:`~libtmux.Server.timeout` + when omitted. + + Returns + ------- + bytes + Exact wire bytes sent to the pane (``b""`` when suppressed by active + modes, such as an unreported mouse move). + + Raises + ------ + :exc:`~libtmux.exc.VersionTooLow` + When *terminal* is ``None`` and *event* is a ``PasteEvent`` on + ``tmux < 3.7`` or a ``FocusEvent`` on ``tmux < 3.8``, where one-shot + format metadata does not expose the corresponding mode flag. + """ + _require_libvt() + from libvt.input import FocusEvent, PasteEvent + + if pane.pane_id is None: + msg = "Pane must have a pane_id to send VT input" + raise ValueError(msg) + + if terminal is None: + if isinstance(event, PasteEvent): + paste_since = capability_since("bracket-paste-format") + if not has_gte_version(paste_since, tmux_bin=pane.server.tmux_bin): + msg = ( + f"one-shot PasteEvent requires tmux {paste_since}+; " + "pass terminal= from observe_vt()" + ) + raise exc.VersionTooLow(msg) + elif isinstance(event, FocusEvent): + focus_since = capability_since("pane-private-modes-format") + if not has_gte_version(focus_since, tmux_bin=pane.server.tmux_bin): + msg = ( + f"one-shot FocusEvent requires tmux {focus_since}+; " + "pass terminal= from observe_vt()" + ) + raise exc.VersionTooLow(msg) + + eff_target: Terminal | Snapshot | TmuxCaptureResult | VtPaneHandle = ( + capture_pane_vt( + pane, + history_lines=0, + include_saved_primary=False, + timeout=timeout, + ).terminal + if terminal is None + else terminal + ) + payload = _encode_for_terminal_target(event, eff_target) + if payload: + proc = pane.cmd( + "send-keys", + "-H", + *(f"{b:02x}" for b in payload), + timeout=timeout, + ) + raise_if_stderr(proc, "send-keys") + return payload + + +class VtPaneHandle: + """Live-synchronized VT view of one ``tmux`` pane on :class:`VtSessionObserver`. + + Attributes + ---------- + pane_id : str + Target ``%`` pane identifier. + sync : TmuxPaneSync + Underlying sans-I/O two-phase pane synchronization state machine. + recorder : FlightRecorder + Bounded raw-byte ring buffer capturing recent ``%output`` bytes for + timeout diagnostics. + """ + + def __init__( + self, + observer: VtSessionObserver, + pane_id: str, + sync: TmuxPaneSync, + ) -> None: + from libvt.terminal import FlightRecorder + + self._observer = observer + self.pane_id = pane_id + self.sync = sync + self.recorder: FlightRecorder = FlightRecorder() + + @property + def terminal(self) -> Terminal: + """Return the live passive-observer ``Terminal``.""" + term = self.sync.terminal + if term is None: + msg = f"Pane {self.pane_id} has not completed initial attach" + raise RuntimeError(msg) + return term + + @property + def capture_result(self) -> TmuxCaptureResult: + """Return the latest baseline or resync ``TmuxCaptureResult``.""" + res = self.sync.capture_result + if res is None: + msg = f"Pane {self.pane_id} has no completed capture result" + raise RuntimeError(msg) + return res + + def snapshot(self) -> Snapshot: + """Capture an immutable point-in-time ``Snapshot``.""" + return self.terminal.snapshot() + + def sync_token(self) -> SyncToken: + """Return an opaque watermark token for :meth:`changes_since`.""" + return self.terminal.sync_token() + + def changes_since(self, token: SyncToken) -> ScreenDelta: + """Compute dirty-row or full-resync delta since *token*.""" + return self.terminal.changes_since(token) + + async def wait_until( + self, + predicate: collections.abc.Callable[[Snapshot], object] | str, + *, + timeout: float = 5.0, + sync_timeout: float = 1.0, + ) -> Snapshot: + """Wait until *predicate* matches on ``terminal.committed`` and return it. + + Parameters + ---------- + predicate : Callable[[Snapshot], object] or str + Condition evaluated on the tear-free committed ``Snapshot`` after + each batch of control-mode events, or a plain substring checked + against ``snapshot.text``. + timeout : float, default 5.0 + Maximum seconds to wait before raising :exc:`TimeoutError` with a + boxed visual render and flight-recorder diagnostic. + sync_timeout : float, default 1.0 + Maximum seconds to hold a stalled ``?2026`` synchronized-output + frame before expiring the hold automatically. + + Returns + ------- + Snapshot + Tear-free committed snapshot that satisfied *predicate*. + + Raises + ------ + TimeoutError + When *timeout* elapses before *predicate* returns a truthy value. + :exc:`~libtmux.exc.LibTmuxException` + When the underlying ``tmux -C`` client exits before *predicate* + matches. + """ + from libvt.codec import format_explain + from libvt.testing import format_flight_recorder, format_screen_box + + check: collections.abc.Callable[[Snapshot], object] = ( + (lambda snap: predicate in snap.text) + if isinstance(predicate, str) + else predicate + ) + deadline = time.monotonic() + timeout + sync_started_at: float | None = None + sync_gen_tracked: int | None = None + async with self._observer._cond: + while True: + term = self.terminal + now = time.monotonic() + if term.synchronized: + cur_gen = term.committed_generation + assert isinstance(cur_gen, int) + if sync_gen_tracked != cur_gen or sync_started_at is None: + sync_gen_tracked = cur_gen + sync_started_at = now + elif now - sync_started_at >= sync_timeout: + term.expire_synchronized_output() + sync_started_at = None + sync_gen_tracked = None + else: + sync_started_at = None + sync_gen_tracked = None + + snap = term.committed + if check(snap): + return snap + self._observer._raise_if_closed() + + remaining = deadline - now + if remaining <= 0: + if term.synchronized: + term.expire_synchronized_output() + snap = term.committed + if check(snap): + return snap + break + wait_slice = ( + min(remaining, max(0.0, sync_started_at + sync_timeout - now)) + if (term.synchronized and sync_started_at is not None) + else remaining + ) + with contextlib.suppress(TimeoutError): + async with asyncio.timeout(wait_slice): + await self._observer._cond.wait() + + self.terminal.expire_synchronized_output() + box = format_screen_box(self.terminal) + recorder = format_flight_recorder(self.terminal) + if self.recorder.total_bytes > 0: + tail = self.recorder.tail(256) + extra = [ + f" recent_bytes ({len(tail)}/{self.recorder.total_bytes}B): {tail!r}" + ] + explained = format_explain(tail) + if explained: + extra.extend(f" {ln}" for ln in explained.splitlines()[-12:]) + recorder = f"{recorder}\n" + "\n".join(extra) + msg = ( + f"Timed out after {timeout}s waiting on pane {self.pane_id}:\n" + f"{box}\n{recorder}" + ) + raise TimeoutError(msg) + + async def resync(self, *, timeout: float = 5.0) -> TmuxCaptureResult: + """Trigger an explicit two-phase resynchronization in place. + + Preserves ``handle.terminal`` object identity while advancing its epoch + so held ``SyncToken`` watermarks report ``full_resync=True``. + """ + return await self._observer._resync_pane(self.pane_id, timeout=timeout) + + async def send_input( + self, + event: InputEvent | str, + *, + timeout: float = 5.0, + ) -> bytes: + """Encode *event* for :attr:`terminal` modes and send over ``tmux -C``.""" + payload = _encode_for_terminal_target(event, self.terminal) + if payload: + hex_bytes = " ".join(f"{b:02x}" for b in payload) + await self._observer._execute_command( + f"send-keys -H -t '{self.pane_id}' {hex_bytes}", + timeout=timeout, + ) + return payload + + +_FutureT = t.TypeVar("_FutureT") + + +def _silence_orphan_future(fut: asyncio.Future[_FutureT]) -> None: + """Mark background-shielded future exceptions retrieved if outer wait cancelled.""" + if not fut.cancelled(): + fut.exception() + + +@dataclass(slots=True) +class _HandshakeOp: + pane_id: str + is_resync: bool + future: asyncio.Future[TmuxCaptureResult] | None + + +@dataclass(slots=True) +class _CommandOp: + command_line: str + future: asyncio.Future[TmuxCommandBlock] | None + + +_ControlOp: t.TypeAlias = _HandshakeOp | _CommandOp + + +class VtSessionObserver: + """Async ``tmux -C`` client multiplexing :class:`VtPaneHandle` observers. + + Spawns ``tmux -C attach-session`` with raw ``bytes`` pipes so multi-byte + UTF-8 sequences split across ``%output`` notifications are reassembled + losslessly by ``TmuxControlParser``. + + Attributes + ---------- + session : :class:`~libtmux.Session` + Session attached by this ``tmux -C`` client. + history_lines : int or None + Default scrollback line bound for panes watched on this observer. + scrollback : int + Default scrollback capacity in lines for panes watched on this observer. + ignore_size : bool + Whether ``-f ignore-size`` is passed to ``attach-session``. + """ + + def __init__( + self, + session: Session, + *, + history_lines: int | None = None, + scrollback: int = 2_000, + ignore_size: bool = True, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + ) -> None: + _require_libvt() + if session.session_id is None: + msg = "Session must have a session_id to observe VT state" + raise ValueError(msg) + self.session = session + self.history_lines = history_lines + self.scrollback = scrollback + self.ignore_size = ignore_size + self._profile = profile + self._policy = policy + self._limits = limits + + self._cond = asyncio.Condition() + self._proc: asyncio.subprocess.Process | None = None + self._reader_task: asyncio.Task[None] | None = None + self._stderr_task: asyncio.Task[None] | None = None + self._stderr_chunks: list[bytes] = [] + self._stderr_bytes: int = 0 + self._parser: TmuxControlParser | None = None + self._handles: dict[str, VtPaneHandle] = {} + self._attach_future: asyncio.Future[None] | None = None + self._active_op: _ControlOp | None = None + self._op_queue: collections.deque[_ControlOp] = collections.deque() + self._close_error: exc.LibTmuxException | None = None + self._attached: bool = False + self._closed: bool = False + self._tmux_version_str: str = "" + self._log_extra: dict[str, object] = {} + + async def __aenter__(self) -> Self: + """Spawn the raw-byte ``tmux -C`` client and start its event reader.""" + from libvt.contrib.tmux.control import TmuxControlParser + + assert self.session.session_id is not None + server = self.session.server + resolved = server.tmux_bin or shutil.which("tmux") + if not resolved: + msg = "tmux executable not found on PATH" + raise exc.TmuxCommandNotFound(msg) + + self._tmux_version_str = get_version_str(server.tmux_bin) + size_flags = ["-f", "ignore-size"] if self.ignore_size else [] + cmd = [ + resolved, + *server._socket_args(), + "-C", + "attach-session", + *size_flags, + "-t", + self.session.session_id, + ] + if logger.isEnabledFor(logging.DEBUG): + self._log_extra = { + **command_extra(cmd), + **object_extra( + "attach-session", + socket=server.socket_path or server.socket_name, + session=self.session.session_id, + ), + } + logger.debug("vt control client started", extra=self._log_extra) + + try: + self._proc = await asyncio.create_subprocess_exec( + *cmd, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + except OSError as error: + _raise_if_unusable_tmux(error) + raise + + loop = asyncio.get_running_loop() + self._parser = TmuxControlParser() + self._attach_future = asyncio.Future[None](loop=loop) + self._attach_future.add_done_callback(_silence_orphan_future) + self._close_error = None + self._attached = False + self._closed = False + self._stderr_chunks = [] + self._stderr_bytes = 0 + self._stderr_task = asyncio.create_task(self._drain_stderr()) + self._reader_task = asyncio.create_task(self._read_loop()) + try: + await self._wait_until_attached() + except BaseException: + await self.aclose() + raise + return self + + async def _wait_until_attached(self) -> None: + assert self._attach_future is not None + async with asyncio.timeout(_TERMINATE_TIMEOUT_SECONDS): + await asyncio.shield(self._attach_future) + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> None: + """Close the ``tmux -C`` client and reap its subprocess.""" + await self.aclose() + + def _fail_pending_ops(self, error: exc.LibTmuxException) -> None: + if self._close_error is None: + self._close_error = error + self._closed = True + if self._attach_future is not None and not self._attach_future.done(): + self._attach_future.set_exception(self._close_error) + pending: list[_ControlOp] = [] + if self._active_op is not None: + pending.append(self._active_op) + self._active_op = None + while self._op_queue: + pending.append(self._op_queue.popleft()) + for op in pending: + if isinstance(op, _HandshakeOp) and not op.is_resync: + h = self._handles.get(op.pane_id) + if h is not None and h.sync.terminal is None: + self._handles.pop(op.pane_id, None) + if op.future is not None and not op.future.done(): + op.future.set_exception(self._close_error) + + async def aclose(self) -> None: + """Shut down the ``tmux -C`` subprocess and wake any waiting callers.""" + proc = self._proc + if proc is None: + return + self._proc = None + self._fail_pending_ops(exc.LibTmuxException("tmux -C control client closed")) + for handle in self._handles.values(): + if handle.sync.terminal is not None: + handle.sync.terminal.expire_synchronized_output() + + if proc.stdin is not None: + proc.stdin.close() + with contextlib.suppress(OSError, BrokenPipeError, ConnectionResetError): + await proc.stdin.wait_closed() + + if self._reader_task is not None: + self._reader_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await self._reader_task + self._reader_task = None + + if self._stderr_task is not None: + self._stderr_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await self._stderr_task + self._stderr_task = None + + if proc.returncode is None: + with contextlib.suppress(ProcessLookupError): + proc.terminate() + try: + await asyncio.wait_for(proc.wait(), timeout=_TERMINATE_TIMEOUT_SECONDS) + except TimeoutError: + logger.warning( + "vt control client killed after timeout", + extra=self._log_extra, + ) + with contextlib.suppress(ProcessLookupError): + proc.kill() + await proc.wait() + + async with self._cond: + self._cond.notify_all() + + def _raise_if_closed(self) -> None: + if self._closed: + if self._close_error is not None: + raise self._close_error + msg = "tmux -C control client closed" + raise exc.LibTmuxException(msg) + + async def _write_line(self, command_line: str) -> None: + proc = self._proc + if proc is None or proc.stdin is None or self._closed: + self._raise_if_closed() + msg = "tmux -C control client is not running" + raise exc.LibTmuxException(msg) + try: + proc.stdin.write(command_line.encode("ascii") + b"\n") + await proc.stdin.drain() + except (BrokenPipeError, ConnectionResetError, OSError) as error: + err = self._close_error or exc.LibTmuxException( + f"tmux -C control pipe closed: {error}" + ) + self._fail_pending_ops(err) + raise err from error + + async def _kick_next_op(self) -> None: + from libvt.contrib.tmux.control import TmuxAttachPhase + + while ( + self._attached + and not self._closed + and self._active_op is None + and self._op_queue + ): + op = self._op_queue.popleft() + if isinstance(op, _CommandOp): + self._active_op = op + try: + await self._write_line(op.command_line) + except exc.LibTmuxException as error: + self._active_op = None + if op.future is not None and not op.future.done(): + op.future.set_exception(error) + continue + return + + handle = self._handles.get(op.pane_id) + if handle is None: + if op.future is not None and not op.future.done(): + op.future.set_exception( + exc.LibTmuxException(f"Pane {op.pane_id} is no longer watched") + ) + continue + if not op.is_resync and handle.sync.phase == TmuxAttachPhase.LIVE: + if op.future is not None and not op.future.done(): + op.future.set_result(handle.capture_result) + continue + self._active_op = op + cmd_line = ( + handle.sync.resync() if op.is_resync else handle.sync.begin_attach() + ) + try: + await self._write_line(cmd_line) + except exc.LibTmuxException as error: + self._active_op = None + if not op.is_resync and handle.sync.terminal is None: + self._handles.pop(op.pane_id, None) + if op.future is not None and not op.future.done(): + op.future.set_exception(error) + continue + return + + async def _execute_command( + self, + command_line: str, + *, + timeout: float, + ) -> TmuxCommandBlock: + from libvt.contrib.tmux.control import TmuxCommandBlock + + self._raise_if_closed() + loop = asyncio.get_running_loop() + fut = asyncio.Future[TmuxCommandBlock](loop=loop) + fut.add_done_callback(_silence_orphan_future) + self._op_queue.append(_CommandOp(command_line=command_line, future=fut)) + await self._kick_next_op() + async with asyncio.timeout(timeout): + return await asyncio.shield(fut) + + async def _enqueue_handshake( + self, + pane_id: str, + *, + is_resync: bool, + background: bool = False, + ) -> asyncio.Future[TmuxCaptureResult] | None: + from libvt.contrib.tmux.capture import TmuxCaptureResult + + loop = asyncio.get_running_loop() + if ( + isinstance(self._active_op, _HandshakeOp) + and self._active_op.pane_id == pane_id + and self._active_op.is_resync == is_resync + ): + if not background and self._active_op.future is None: + fut = asyncio.Future[TmuxCaptureResult](loop=loop) + fut.add_done_callback(_silence_orphan_future) + self._active_op.future = fut + return self._active_op.future + + for queued in self._op_queue: + if ( + isinstance(queued, _HandshakeOp) + and queued.pane_id == pane_id + and queued.is_resync == is_resync + ): + if not background and queued.future is None: + fut = asyncio.Future[TmuxCaptureResult](loop=loop) + fut.add_done_callback(_silence_orphan_future) + queued.future = fut + return queued.future + + fut_opt: asyncio.Future[TmuxCaptureResult] | None = None + if not background: + fut_opt = asyncio.Future[TmuxCaptureResult](loop=loop) + fut_opt.add_done_callback(_silence_orphan_future) + self._op_queue.append( + _HandshakeOp(pane_id=pane_id, is_resync=is_resync, future=fut_opt) + ) + await self._kick_next_op() + return fut_opt + + async def watch_pane( + self, + pane: Pane | str, + *, + history_lines: int | None = None, + scrollback: int | None = None, + timeout: float = 5.0, + ) -> VtPaneHandle: + """Attach to *pane* on this ``tmux -C`` client and wait until ``LIVE``. + + Parameters + ---------- + pane : :class:`~libtmux.Pane` or str + Target :class:`~libtmux.Pane` or ``"%"`` pane ID string. + history_lines : int or None, optional + Per-pane scrollback line bound override; defaults to + :attr:`VtSessionObserver.history_lines`. + scrollback : int or None, optional + Per-pane scrollback capacity override; defaults to + :attr:`VtSessionObserver.scrollback`. + timeout : float, default 5.0 + Maximum seconds to complete the two-phase pause + capture + continue + handshake. + + Returns + ------- + :class:`VtPaneHandle` + Live-synchronized handle whose ``terminal`` updates automatically. + """ + from libvt.contrib.tmux.control import TmuxAttachPhase, TmuxPaneSync + + self._raise_if_closed() + pane_id = pane if isinstance(pane, str) else pane.pane_id + if pane_id is None: + msg = "Pane must have a pane_id to watch" + raise ValueError(msg) + + handle = self._handles.get(pane_id) + if handle is not None and handle.sync.phase == TmuxAttachPhase.LIVE: + return handle + + if handle is None: + eff_hist = self.history_lines if history_lines is None else history_lines + eff_sb = self.scrollback if scrollback is None else scrollback + sync = TmuxPaneSync( + pane_id, + tmux_version=self._tmux_version_str, + scrollback=eff_sb, + history_lines=eff_hist, + profile=self._profile, + policy=self._policy, + limits=self._limits, + ) + handle = VtPaneHandle(self, pane_id, sync) + self._handles[pane_id] = handle + + fut = await self._enqueue_handshake(pane_id, is_resync=False) + assert fut is not None + async with asyncio.timeout(timeout): + await asyncio.shield(fut) + return handle + + async def _resync_pane( + self, + pane_id: str, + *, + timeout: float = 5.0, + ) -> TmuxCaptureResult: + self._raise_if_closed() + handle = self._handles.get(pane_id) + if handle is None: + msg = f"Pane {pane_id} is not watched by this observer" + raise KeyError(msg) + fut = await self._enqueue_handshake(pane_id, is_resync=True) + assert fut is not None + async with asyncio.timeout(timeout): + return await asyncio.shield(fut) + + async def _dispatch_event(self, event: TmuxControlEvent) -> None: + from libvt.contrib.tmux.control import ( + TmuxAttachPhase, + TmuxCommandBlock, + TmuxContinue, + TmuxExit, + TmuxExtendedOutput, + TmuxOutput, + ) + + if isinstance(event, TmuxExit): + reason = ( + f"tmux -C exited: {event.reason}" if event.reason else "tmux -C exited" + ) + self._fail_pending_ops(exc.LibTmuxException(reason)) + return + + if isinstance(event, TmuxContinue): + handle = self._handles.get(event.pane_id) + if handle is not None and handle.sync.phase == TmuxAttachPhase.PAUSED: + await self._enqueue_handshake( + event.pane_id, + is_resync=True, + background=True, + ) + return + + if isinstance(event, TmuxCommandBlock): + if not self._attached: + self._attached = True + if event.is_error: + msg = b"\n".join(event.lines).decode("utf-8", errors="replace") + err = exc.LibTmuxException(msg or "tmux -C attach-session failed") + self._fail_pending_ops(err) + return + if self._attach_future is not None and not self._attach_future.done(): + self._attach_future.set_result(None) + await self._kick_next_op() + return + + if event.flags != 1: + return + + active_op = self._active_op + if active_op is None: + return + + if isinstance(active_op, _CommandOp): + self._active_op = None + if event.is_error: + msg = ( + b"\n".join(event.lines).decode("utf-8", errors="replace") + or "tmux -C command failed" + ) + if active_op.future is not None and not active_op.future.done(): + active_op.future.set_exception(exc.LibTmuxException(msg)) + elif active_op.future is not None and not active_op.future.done(): + active_op.future.set_result(event) + await self._kick_next_op() + return + + active_handle = self._handles.get(active_op.pane_id) + if active_handle is None: + self._active_op = None + if active_op.future is not None and not active_op.future.done(): + active_op.future.set_exception( + exc.LibTmuxException( + f"Pane {active_op.pane_id} is no longer watched" + ) + ) + await self._kick_next_op() + return + + needs_continue = active_handle.sync.phase in ( + TmuxAttachPhase.PAUSING, + TmuxAttachPhase.CAPTURING, + ) + try: + follow_up = active_handle.sync.handle_event(event) + except Exception as error: + err = exc.LibTmuxException(str(error)) + if not event.is_error: + # Non-%error ProtocolError (such as a truncated capture block) + # leaves trailing batch replies in flight; close the pipe so + # subsequent operations cannot consume misaligned blocks. + self._fail_pending_ops(err) + if self._proc is not None and self._proc.stdin is not None: + self._proc.stdin.close() + return + self._active_op = None + if not active_op.is_resync and active_handle.sync.terminal is None: + self._handles.pop(active_op.pane_id, None) + if needs_continue: + resume_cmd = f"refresh-client -A '{active_op.pane_id}:continue'" + self._op_queue.appendleft( + _CommandOp(command_line=resume_cmd, future=None) + ) + if active_op.future is not None and not active_op.future.done(): + active_op.future.set_exception(err) + await self._kick_next_op() + return + + if follow_up is not None: + await self._write_line(follow_up) + if active_handle.sync.phase == TmuxAttachPhase.LIVE: + self._active_op = None + if active_op.future is not None and not active_op.future.done(): + active_op.future.set_result(active_handle.capture_result) + await self._kick_next_op() + return + + if isinstance(event, (TmuxOutput, TmuxExtendedOutput)): + out_handle = self._handles.get(event.pane_id) + if out_handle is not None: + out_handle.recorder.record(event.data) + + for handle in list(self._handles.values()): + follow_up = handle.sync.handle_event(event) + if follow_up is not None: + await self._write_line(follow_up) + + async def _drain_stderr(self) -> None: + proc = self._proc + if proc is None or proc.stderr is None: + return + while True: + chunk = await proc.stderr.read(4096) + if not chunk: + break + if self._stderr_bytes < 8192: + take = chunk[: 8192 - self._stderr_bytes] + self._stderr_chunks.append(take) + self._stderr_bytes += len(take) + + async def _read_loop(self) -> None: + proc = self._proc + parser = self._parser + if proc is None or proc.stdout is None or parser is None: + return + close_err: exc.LibTmuxException | None = None + try: + while True: + chunk = await proc.stdout.read(_READ_CHUNK_BYTES) + if not chunk: + break + events = parser.feed(chunk) + if not events: + continue + for ev in events: + await self._dispatch_event(ev) + async with self._cond: + self._cond.notify_all() + except asyncio.CancelledError: + raise + except Exception as error: + close_err = ( + error + if isinstance(error, exc.LibTmuxException) + else exc.LibTmuxException(str(error)) + ) + finally: + if close_err is None and not self._closed: + if self._stderr_task is not None and not self._stderr_task.done(): + with contextlib.suppress(TimeoutError, asyncio.CancelledError): + await asyncio.wait_for( + asyncio.shield(self._stderr_task), + timeout=0.05, + ) + stderr_msg = ( + b"".join(self._stderr_chunks) + .decode("utf-8", errors="replace") + .strip() + ) + if stderr_msg: + close_err = exc.LibTmuxException( + f"tmux -C control client closed: {stderr_msg}" + ) + self._fail_pending_ops( + close_err or exc.LibTmuxException("tmux -C control client closed") + ) + async with self._cond: + self._cond.notify_all() + + +@contextlib.asynccontextmanager +async def observe_pane_vt( + pane: Pane, + *, + history_lines: int | None = None, + scrollback: int = 2_000, + ignore_size: bool = True, + attach_timeout: float = 5.0, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, +) -> collections.abc.AsyncGenerator[VtPaneHandle]: + """Open a single-pane :class:`VtSessionObserver` yielding :class:`VtPaneHandle`.""" + async with VtSessionObserver( + pane.session, + history_lines=history_lines, + scrollback=scrollback, + ignore_size=ignore_size, + profile=profile, + policy=policy, + limits=limits, + ) as observer: + yield await observer.watch_pane(pane, timeout=attach_timeout) + + +def _resolve_screen_target( + target: Pane | VtPaneHandle | TmuxCaptureResult | Terminal | Snapshot, +) -> Terminal | Snapshot: + """Extract a ``Terminal`` or ``Snapshot`` from *target*.""" + _require_libvt() + from libvt.contrib.tmux.capture import TmuxCaptureResult + from libvt.terminal import Snapshot, Terminal + + if isinstance(target, (Terminal, Snapshot)): + return target + if isinstance(target, TmuxCaptureResult): + return target.terminal + if isinstance(target, VtPaneHandle): + return target.terminal + return capture_pane_vt( + target, + history_lines=0, + include_saved_primary=False, + ).terminal + + +def assert_pane_screen( + target: Pane | VtPaneHandle | TmuxCaptureResult | Terminal | Snapshot, + expected: str | collections.abc.Sequence[str], + *, + cursor: tuple[int, int] | None = None, +) -> None: + r"""Assert that *target*'s visible text (and optional *cursor*) matches *expected*. + + Accepts a :class:`~libtmux.Pane` directly (capturing its active viewport via + :func:`capture_pane_vt`), a live :class:`VtPaneHandle`, a + ``TmuxCaptureResult``, or a ``libvt`` ``Terminal`` / ``Snapshot``. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libtmux.test.retry import retry_until + >>> from libtmux.vt import assert_pane_screen + >>> cmd = ( + ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[Hready\\r\\ndone'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="assert-scr-vt", + ... x=10, + ... y=2, + ... window_command=f"{shlex.quote(sys.executable)} -u -c {shlex.quote(cmd)}", + ... ) + >>> p = s.active_pane + >>> assert p is not None + >>> retry_until(lambda: "done" in p.capture_vt(history_lines=0).snapshot.text) + True + >>> assert_pane_screen(p, "ready\ndone", cursor=(1, 4)) + >>> _ = p.send_vt_input("enter") + """ + resolved = _resolve_screen_target(target) + from libvt.testing import assert_screen + + assert_screen(resolved, expected, cursor=cursor) + + +def assert_pane_screen_box( + target: Pane | VtPaneHandle | TmuxCaptureResult | Terminal | Snapshot, + expected: str, + *, + cursor: tuple[int, int] | None = None, +) -> None: + r"""Assert that *target* matches a column-exact ``┌──┐`` / ``│..│`` boxed diagram. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libtmux.test.retry import retry_until + >>> from libtmux.vt import assert_pane_screen_box + >>> cmd = ( + ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[H日本ok\\r\\ndone'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="assert-box-vt", + ... x=8, + ... y=2, + ... window_command=f"{shlex.quote(sys.executable)} -u -c {shlex.quote(cmd)}", + ... ) + >>> p = s.active_pane + >>> assert p is not None + >>> retry_until(lambda: "done" in p.capture_vt(history_lines=0).snapshot.text) + True + >>> assert_pane_screen_box( + ... p, + ... ''' + ... ┌────────┐ + ... │日本ok │ + ... │done │ + ... └────────┘ + ... ''', + ... cursor=(1, 4), + ... ) + >>> _ = p.send_vt_input("enter") + """ + resolved = _resolve_screen_target(target) + from libvt.testing import assert_screen_box + + assert_screen_box(resolved, expected, cursor=cursor) + + +__all__ = ( + "VtPaneHandle", + "VtSessionObserver", + "assert_pane_screen", + "assert_pane_screen_box", + "capture_pane_vt", + "observe_pane_vt", + "send_pane_vt_input", +) diff --git a/tests/test_capabilities.py b/tests/test_capabilities.py index 7a4e1724a9..f31b80b2db 100644 --- a/tests/test_capabilities.py +++ b/tests/test_capabilities.py @@ -105,6 +105,20 @@ def _paste_without_vis(session: Session) -> None: _pane(session).paste_buffer(no_vis=True) +def _send_vt_paste_oneshot(session: Session) -> None: + pytest.importorskip("libvt") + from libvt.input import PasteEvent + + _pane(session).send_vt_input(PasteEvent("gate")) + + +def _send_vt_focus_oneshot(session: Session) -> None: + pytest.importorskip("libvt") + from libvt.input import FocusEvent + + _pane(session).send_vt_input(FocusEvent(focused=True)) + + GATE_CASES: list[GateCase] = [ GateCase( "run_shell_cwd", @@ -188,6 +202,18 @@ def _paste_without_vis(session: Session) -> None: lambda session: _pane(session).new_pane(), None, ), + GateCase( + "send_vt_paste_oneshot", + "bracket-paste-format", + _send_vt_paste_oneshot, + None, + ), + GateCase( + "send_vt_focus_oneshot", + "pane-private-modes-format", + _send_vt_focus_oneshot, + None, + ), ] diff --git a/tests/test_docs_capabilities.py b/tests/test_docs_capabilities.py index c0dfa732dd..d9a7ee5786 100644 --- a/tests/test_docs_capabilities.py +++ b/tests/test_docs_capabilities.py @@ -142,7 +142,9 @@ def test_html_matrix_links_documented_sphinx_apis( ".. py:class:: libtmux.Pane\n\n" " .. py:method:: capture_pane()\n" " .. py:method:: paste_buffer()\n" - " .. py:method:: new_pane()\n\n" + " .. py:method:: new_pane()\n" + " .. py:method:: send_vt_input()\n\n" + ".. py:function:: libtmux.vt.send_pane_vt_input()\n" ".. py:exception:: libtmux.exc.LibTmuxException\n" ".. py:exception:: libtmux.exc.VersionTooLow\n" "```\n" diff --git a/tests/test_vt.py b/tests/test_vt.py new file mode 100644 index 0000000000..50c6e6b589 --- /dev/null +++ b/tests/test_vt.py @@ -0,0 +1,476 @@ +"""Functional tests for optional ``libtmux[vt]`` integration.""" + +from __future__ import annotations + +import asyncio +import logging +import shlex +import subprocess +import sys +import typing as t + +import pytest + +from libtmux import exc +from libtmux.test.retry import retry_until +from libtmux.vt import ( + VtSessionObserver, + _require_libvt, + assert_pane_screen, + assert_pane_screen_box, +) + +if t.TYPE_CHECKING: + from libtmux.pane import Pane + from libtmux.pytest_plugin import VtObserverFactory + from libtmux.server import Server + from libtmux.session import Session + + +def _spawn_vt_writer( + session: Session, + name: str, + *, + height: int, + width: int, + payload: bytes, + sentinel: str, +) -> Pane: + """Create an exact ``(height, width)`` pane and emit *payload* deterministically.""" + hex_data = payload.hex() + script = ( + "import sys, tty; tty.setraw(0); " + "sys.stdout.buffer.write(b'BOOT'); sys.stdout.buffer.flush(); " + "sys.stdin.buffer.read(1); " + "sys.stdout.buffer.write(b'\\x1b[2J\\x1b[3J\\x1b[H'); " + f"sys.stdout.buffer.write(bytes.fromhex('{hex_data}')); " + "sys.stdout.buffer.flush(); sys.stdin.buffer.read(1)" + ) + win = session.new_window( + window_name=name, + window_shell=f"{shlex.quote(sys.executable)} -u -c {shlex.quote(script)}", + ) + pane = win.active_pane + assert pane is not None + retry_until(lambda: "BOOT" in "\n".join(pane.capture_pane())) + win.resize(height=height, width=width) + pane.send_keys("g", enter=False, literal=True) + retry_until(lambda: sentinel in "\n".join(pane.capture_pane())) + return pane + + +def test_vt_packaging_lazy_import_and_runtime_guards( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Core imports stay lazy; Python 3.11 and missing ``libvt`` raise clear errors.""" + probe = subprocess.run( + [ + sys.executable, + "-c", + ( + "import sys, libtmux, libtmux.pytest_plugin; " + "assert 'libvt' not in sys.modules, list(sys.modules); " + "import libtmux.vt; " + "assert 'libvt' not in sys.modules" + ), + ], + check=True, + capture_output=True, + text=True, + ) + assert probe.returncode == 0 + + monkeypatch.setattr(sys, "version_info", (3, 11, 9, "final", 0)) + with pytest.raises(RuntimeError, match=r"Python 3\.12 or later"): + _require_libvt() + + monkeypatch.undo() + monkeypatch.setattr(sys, "version_info", (3, 12, 0, "final", 0)) + monkeypatch.setitem(sys.modules, "libvt", None) + with pytest.raises(ModuleNotFoundError, match=r'pip install "libtmux\[vt\]"'): + _require_libvt() + + +def test_pane_capture_vt_cells_styles_history_alt_screen_and_logging( + session: Session, + caplog: pytest.LogCaptureFixture, +) -> None: + """``Pane.capture_vt`` reconstructs cells, styles, history, ``?1049``, and logs.""" + pytest.importorskip("libvt") + from libvt.modes import Mode + from libvt.screen import CursorShape + from libvt.style import AnsiColor + + pane = _spawn_vt_writer( + session, + "vt-cap", + height=4, + width=12, + payload=( + b"H0\r\nH1\r\nH2\r\n\x1b[1;32mOK\x1b[0m " + + "日本\r\n".encode() + + b"\x1b[?1049h\x1b[H\x1b[6 q\x1b[?25lALT_TOP" + ), + sentinel="ALT_TOP", + ) + + with caplog.at_level(logging.DEBUG, logger="libtmux.common"): + caplog.clear() + res = pane.capture_vt(include_saved_primary=True) + + cap_completed = [ + r + for r in caplog.records + if r.message == "tmux command completed" + and getattr(r, "tmux_subcommand", None) == "display-message" + ] + assert len(cap_completed) == 1 + assert getattr(cap_completed[0], "tmux_exit_code", None) == 0 + + assert res.metadata.alternate_on is True + assert res.snapshot.active_is_alt is True + assert res.snapshot.display_lines[0] == "ALT_TOP " + assert res.snapshot.display_lines[3] == " " + assert res.terminal.cursor.visible is False + if res.metadata.cursor_shape is not None: + assert res.terminal.cursor.shape == CursorShape.BAR + assert res.terminal.modes.is_set(Mode.ALT_SCREEN) + + prim_lines = [r.text for r in res.terminal.screens.primary.history] + list( + res.terminal.screens.primary.lines + ) + joined_primary = "\n".join(prim_lines) + assert "H0" in joined_primary + assert "OK 日本" in joined_primary + + pane2 = _spawn_vt_writer( + session, + "vt-primary", + height=2, + width=10, + payload=b"S0\r\nS1\r\nS2\r\nS3\r\n\x1b[1;32mREADY\x1b[0m " + "日本".encode(), + sentinel="READY", + ) + + bounded = pane2.capture_vt(history_lines=2) + assert len(bounded.snapshot.history) == 2 + cell = bounded.terminal[1, 0] + assert cell.text == "R" + assert cell.style.bold is True + assert cell.style.fg == AnsiColor.GREEN + assert bounded.terminal[1, 6].text == "日" + assert bounded.snapshot.viewport(2).lines[0].startswith("S") + + pane2.kill() + with pytest.raises(exc.LibTmuxException): + pane2.capture_vt() + + +def test_vt_session_observer_multiplex_resize_resync_and_logging( + session: Session, + vt_observer: VtObserverFactory, + caplog: pytest.LogCaptureFixture, +) -> None: + """``VtSessionObserver`` multiplexes panes, tracks resizes, and resyncs in place.""" + pytest.importorskip("libvt") + from libvt.terminal import ResyncReason + + w1 = session.new_window(window_name="obs-1", window_shell="cat") + p1 = w1.active_pane + assert p1 is not None + p2 = w1.split(shell="cat") + + async def _exercise() -> None: + with caplog.at_level(logging.DEBUG, logger="libtmux.vt"): + caplog.clear() + async with vt_observer(history_lines=10) as obs: + started = [ + r + for r in caplog.records + if r.message == "vt control client started" + ] + assert len(started) == 1 + assert getattr(started[0], "tmux_session", None) == session.session_id + + h1, h2 = await asyncio.gather( + obs.watch_pane(p1), + obs.watch_pane(p2), + ) + orig_term1 = h1.terminal + tok0 = h1.sync_token() + + p1.send_keys("café 日本\x1b[6n\x1b[c", enter=True) + p2.send_keys("SECOND_PANE_OK", enter=True) + + snap1 = await h1.wait_until(lambda snap: "café 日本" in snap.text) + snap2 = await h2.wait_until(lambda snap: "SECOND_PANE_OK" in snap.text) + assert "café 日本" in snap1.text + assert "SECOND_PANE_OK" in snap2.text + + # Passive observation must never synthesize terminal query replies. + assert h1.terminal.drain_replies() == b"" + + delta1 = h1.changes_since(tok0) + assert delta1.dirty_rows or delta1.full_resync + + target_cols = h1.terminal.cols + 6 + w1.resize(height=30, width=target_cols) + await h1.wait_until(lambda snap: snap.cols == target_cols) + await h2.wait_until(lambda snap: snap.cols == target_cols) + + tok_pre_resync = h1.sync_token() + resync_res = await h1.resync() + assert h1.terminal is orig_term1 + assert resync_res.terminal is orig_term1 + delta_resync = h1.changes_since(tok_pre_resync) + assert delta_resync.full_resync is True + assert delta_resync.resync_reason == ResyncReason.EPOCH_CHANGED + + asyncio.run(_exercise()) + + +def test_send_vt_input_mode_aware_keys_paste_and_mouse( + session: Session, +) -> None: + """``Pane.send_vt_input`` and ``VtPaneHandle.send_input`` honor active VT modes.""" + pytest.importorskip("libvt") + from libvt.exc import UnsafePasteError + from libvt.input import ( + FocusEvent, + MouseAction, + MouseButton, + MouseEvent, + PasteEvent, + ) + from libvt.modes import Mode + + from libtmux.common import has_gte_version + + reader_script = ( + "import os, sys, tty; " + "fd = sys.stdin.fileno(); " + "tty.setraw(fd); " + "os.write(1, b'BOOT\\r\\n'); " + "os.read(fd, 1); " + "os.write(1, b'\\x1b[?1h\\x1b[?2004h\\x1b[?1000h\\x1b[?1006hREADY\\r\\n'); " + "buf = b''; " + "\nwhile b'STOP' not in buf:\n" + " ch = os.read(fd, 64)\n" + " if not ch:\n" + " break\n" + " buf += ch\n" + " os.write(1, b'HEX:' + buf.hex().encode('ascii') + b'\\r\\n')\n" + ) + reader_cmd = f"{shlex.quote(sys.executable)} -u -c {shlex.quote(reader_script)}" + win = session.new_window(window_name="vt-input", window_shell=reader_cmd) + pane = win.active_pane + assert pane is not None + retry_until(lambda: "BOOT" in "\n".join(pane.capture_pane())) + + async def _exercise() -> None: + async with pane.observe_vt(history_lines=0) as handle: + pane.send_keys("G", enter=False, literal=True) + await handle.wait_until( + lambda snap: "READY" in snap.text and Mode.DECCKM in snap.modes + ) + sent_up = pane.send_vt_input("up", terminal=handle) + assert sent_up == b"\x1bOA" + await handle.wait_until(lambda snap: "1b4f41" in snap.text) + + with pytest.raises(UnsafePasteError): + pane.send_vt_input( + PasteEvent("hi\x1b[201~x"), + terminal=handle, + ) + sent_paste = pane.send_vt_input( + PasteEvent("line1\nline2"), + terminal=handle, + ) + assert sent_paste == b"\x1b[200~line1\nline2\x1b[201~" + await handle.wait_until( + lambda snap: sent_paste.hex() in snap.text.replace("\n", "") + ) + + sent_mouse = await handle.send_input( + MouseEvent( + button=MouseButton.LEFT, + action=MouseAction.PRESS, + row=1, + col=2, + ) + ) + assert sent_mouse == b"\x1b[<0;3;2M" + await handle.wait_until( + lambda snap: sent_mouse.hex() in snap.text.replace("\n", "") + ) + + if has_gte_version("3.7", tmux_bin=session.server.tmux_bin): + oneshot_paste = pane.send_vt_input(PasteEvent("ok")) + assert oneshot_paste == b"\x1b[200~ok\x1b[201~" + else: + with pytest.raises(exc.VersionTooLow, match=r"requires tmux 3\.7"): + pane.send_vt_input(PasteEvent("ok")) + + if has_gte_version("3.8", tmux_bin=session.server.tmux_bin): + assert pane.send_vt_input(FocusEvent(focused=True)) == b"" + else: + with pytest.raises(exc.VersionTooLow, match=r"requires tmux 3\.8"): + pane.send_vt_input(FocusEvent(focused=True)) + + from libvt.config import Profile, ScreenBehavior + from libvt.terminal import Terminal + + px_term = Terminal( + rows=4, + cols=10, + profile=Profile( + screen=ScreenBehavior(cell_width_px=8, cell_height_px=16) + ), + ) + px_term.feed(b"\x1b[?1000h\x1b[?1016h") + px_sent = pane.send_vt_input( + MouseEvent( + button=MouseButton.LEFT, + action=MouseAction.PRESS, + row=1, + col=2, + ), + terminal=px_term, + ) + assert px_sent == b"\x1b[<0;20;24M" + + pane.send_keys("STOP", enter=False, literal=True) + + asyncio.run(_exercise()) + + +def test_assert_pane_screen_and_box_helpers( + session: Session, +) -> None: + """``assert_pane_screen`` and ``assert_pane_screen_box`` validate pane layouts.""" + pytest.importorskip("libvt") + from libvt.exc import ScreenAssertionError + + pane = _spawn_vt_writer( + session, + "vt-assert", + height=3, + width=8, + payload="日本 OK\r\nrow-2".encode(), + sentinel="row-2", + ) + + assert_pane_screen(pane, "日本 OK\nrow-2", cursor=(1, 5)) + assert_pane_screen_box( + pane, + """ + ┌────────┐ + │日本 OK │ + │row-2 │ + │ │ + └────────┘ + """, + cursor=(1, 5), + ) + + with pytest.raises(ScreenAssertionError, match="Screen state mismatch"): + assert_pane_screen_box( + pane, + """ + ┌────────┐ + │WRONG │ + │row-2 │ + │ │ + └────────┘ + """, + ) + + +def test_vt_observer_error_attribution_and_cleanup( + server: Server, +) -> None: + """Errors route to the failing caller without poisoning sibling panes.""" + pytest.importorskip("libvt") + + isolated = server.new_session(session_name="vt-err-attrib", detach=True) + live_script = ( + "import sys, tty; tty.setraw(0); " + "sys.stdout.buffer.write(b'BOOT'); sys.stdout.buffer.flush(); " + "ch = sys.stdin.buffer.read(1); " + "sys.stdout.buffer.write(b'\\r\\nAFTER_ERR:' + ch); " + "sys.stdout.buffer.flush(); " + "sys.stdin.buffer.read(1); " + "sys.stdout.buffer.write(" + "b'\\x1b[?2026h\\x1b[2J\\x1b[HCOMMITTED_FRAME\\x1b[?2026l'" + "b'\\x1b[?2026h\\x1b[2J\\x1b[HTORN_NEXT'" + "); sys.stdout.buffer.flush(); " + "sys.stdin.buffer.read(1)" + ) + live_win = isolated.new_window( + window_name="vt-live", + window_shell=f"{shlex.quote(sys.executable)} -u -c {shlex.quote(live_script)}", + ) + live_pane = live_win.active_pane + assert live_pane is not None + retry_until(lambda: "BOOT" in "\n".join(live_pane.capture_pane())) + doomed_pane = _spawn_vt_writer( + isolated, + "vt-doomed", + height=3, + width=20, + payload=b"DOOMED", + sentinel="DOOMED", + ) + + async def _exercise() -> None: + async with VtSessionObserver(isolated, history_lines=0) as observer: + live_handle = await observer.watch_pane(live_pane) + doomed_handle = await observer.watch_pane(doomed_pane) + + waiter_task = asyncio.create_task( + live_handle.wait_until("AFTER_ERR", timeout=5.0) + ) + await asyncio.sleep(0) + + with pytest.raises(exc.LibTmuxException, match="%99999"): + await observer.watch_pane("%99999", timeout=1.5) + assert "%99999" not in observer._handles + assert not waiter_task.done() + + doomed_pane.cmd("kill-pane") + with pytest.raises(exc.LibTmuxException): + await doomed_handle.send_input("x") + assert not waiter_task.done() + + await live_handle.send_input("k") + snap = await waiter_task + assert "AFTER_ERR:k" in snap.text + await live_handle.resync() + + await live_handle.send_input("s") + tear_free = await live_handle.wait_until( + lambda s: "COMMITTED_FRAME" in s.text, + timeout=5.0, + ) + assert "COMMITTED_FRAME" in tear_free.text + assert "TORN_NEXT" not in tear_free.text + expired = await live_handle.wait_until( + "TORN_NEXT", + timeout=2.0, + sync_timeout=0.05, + ) + assert "TORN_NEXT" in expired.text + + with pytest.raises(TimeoutError, match="recent_bytes"): + await live_handle.wait_until("UNREACHABLE_TOKEN", timeout=0.02) + + w1 = asyncio.create_task(live_handle.wait_until("NEVER_1", timeout=5.0)) + w2 = asyncio.create_task(live_handle.wait_until("NEVER_2", timeout=5.0)) + await asyncio.sleep(0) + isolated.kill() + with pytest.raises(exc.LibTmuxException): + await w1 + with pytest.raises(exc.LibTmuxException): + await w2 + + asyncio.run(_exercise()) diff --git a/uv.lock b/uv.lock index 0987627f81..a6d7ecde9a 100644 --- a/uv.lock +++ b/uv.lock @@ -3,7 +3,8 @@ revision = 5 requires-python = ">=3.11, <4.0" resolution-markers = [ "python_full_version >= '3.15'", - "python_full_version >= '3.11.5' and python_full_version < '3.15'", + "python_full_version >= '3.12' and python_full_version < '3.15'", + "python_full_version >= '3.11.5' and python_full_version < '3.12'", "python_full_version < '3.11.5'", ] @@ -15,6 +16,7 @@ exclude-newer-span = "P3D" gp-furo-theme = false gp-libs = false gp-sphinx = false +libvt = false sphinx-autodoc-api-style = false sphinx-autodoc-argparse = false sphinx-autodoc-docutils = false @@ -527,6 +529,11 @@ name = "libtmux" version = "0.70.0" source = { editable = "." } +[package.optional-dependencies] +vt = [ + { name = "libvt", marker = "python_full_version >= '3.12'" }, +] + [package.dev-dependencies] coverage = [ { name = "codecov" }, @@ -570,6 +577,8 @@ testing = [ ] [package.metadata] +requires-dist = [{ name = "libvt", marker = "python_full_version >= '3.12' and extra == 'vt'", specifier = ">=0.0.1a4,<0.1" }] +provides-extras = ["vt"] [package.metadata.requires-dev] coverage = [ @@ -613,6 +622,15 @@ testing = [ { name = "pytest-watcher" }, ] +[[package]] +name = "libvt" +version = "0.0.1a4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/e3/2aef4116c9773807fa09e5bc716a18a2d449e3ae5c4c5767b1b524021330/libvt-0.0.1a4.tar.gz", hash = "sha256:35c879576ca71e65d55d246e62e212fe910fc4918ed0ba1783c713617fccabde", size = 355784, upload-time = "2026-11-29T22:17:39.524Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0f/3e/94566d78ca6923f4d8a8de31b64bfff9c9bc716c51e6a1ebd1f496d883bb/libvt-0.0.1a4-py3-none-any.whl", hash = "sha256:ede0a8484b3d617d8dd75f22ab3e0f479d1086ae5beebd63c68c77223f42ce90", size = 217260, upload-time = "2026-11-29T22:17:38.109Z" }, +] + [[package]] name = "linkify-it-py" version = "2.2.0" @@ -1068,7 +1086,8 @@ version = "4.1.3" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", - "python_full_version >= '3.11.5' and python_full_version < '3.15'", + "python_full_version >= '3.12' and python_full_version < '3.15'", + "python_full_version >= '3.11.5' and python_full_version < '3.12'", ] sdist = { url = "https://files.pythonhosted.org/packages/82/77/d59ca6aa338bdd8d880234d15b7c466cb176e44502899a9df81ba2e13cd0/soupsieve-4.1.3.tar.gz", hash = "sha256:13f70186c8f40bf8d0ff7bbab09a18fb149600b465269207b5e5b588f55fda08", size = 181564, upload-time = "2026-11-20T12:58:27.613Z" } wheels = [