From 8144b250d17cbc903dc00bf170579435c3a71f78 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Mon, 30 Nov 2026 19:07:30 -0600 Subject: [PATCH 1/6] Window(feat[vt]): Add multi-pane window VT capture why: Let callers capture split tmux windows into a single composited Snapshot with dividers, junctions, border status labels, and cursor coordinates, or composite watched panes over a live tmux -C observer. what: - Add capture_window_vt, Window.capture_vt, assert_window_screen, and assert_window_screen_box - Add VtSessionObserver.snapshot_window over control mode - Add split-pane, border-status, zoom, error, and observer parity tests --- src/libtmux/vt.py | 394 +++++++++++++++++++++++++++++++++++++++++- src/libtmux/window.py | 112 ++++++++++++ tests/test_vt.py | 221 +++++++++++++++++++++++ 3 files changed, 726 insertions(+), 1 deletion(-) diff --git a/src/libtmux/vt.py b/src/libtmux/vt.py index 8c4b6b0c07..8db394070e 100644 --- a/src/libtmux/vt.py +++ b/src/libtmux/vt.py @@ -47,6 +47,7 @@ TmuxControlParser, TmuxPaneSync, ) + from libvt.contrib.tmux.window import TmuxWindowCaptureResult from libvt.input import InputEvent from libvt.terminal import ( FlightRecorder, @@ -58,6 +59,7 @@ from libtmux.pane import Pane from libtmux.session import Session + from libtmux.window import Window logger = logging.getLogger(__name__) @@ -201,6 +203,166 @@ def capture_pane_vt( ) +def capture_window_vt( + window: Window, + *, + history_lines: int | None = 0, + include_saved_primary: bool = False, + scrollback: int | None = None, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + timeout: float | _UnsetType | None = _UNSET, +) -> TmuxWindowCaptureResult: + r"""Capture *window* and composite all visible panes into a ``Snapshot``. + + Queries live window geometry, border styles, and ``pane-border-format`` + via ``build_tmux_window_list_command()``, captures every pane in one + command batch via ``build_tmux_window_capture_command()``, and composites + pane cells, box-drawing dividers and junctions, ``pane-border-status`` + labels, and the active pane's cursor into a single window ``Snapshot``. + + Parameters + ---------- + window : :class:`~libtmux.Window` + Target tmux window. + history_lines : int or None, default 0 + Maximum scrollback lines captured per pane (``0`` for viewport-only + ``-S 0``, ``None`` for full history, or ``N > 0`` for ``-S -N``). + include_saved_primary : bool, default False + Include ``capture-pane -a -q`` sections on each pane so saved primary + scrollback is available in ``result.panes[pane_id]``. + scrollback : int or None, optional + Explicit per-pane scrollback line capacity override. + 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 + ------- + TmuxWindowCaptureResult + Composited window ``snapshot``, per-pane ``panes`` mapping, parsed + ``layout``, ``zoomed`` state, and ``layout_stable`` check. + + Raises + ------ + ValueError + When ``window.window_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 window). + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libvt.testing import serialize_vt_snapshot + >>> from libtmux.constants import PaneDirection + >>> from libtmux.test.retry import retry_until + >>> from libtmux.vt import capture_window_vt + >>> py = shlex.quote(sys.executable) + >>> left_cmd = ( + ... "import sys; " + ... "sys.stdout.write('\\x1b[2J\\x1b[H\\x1b[1;36mapi\\x1b[0m\\r\\nok'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> right_cmd = ( + ... "import sys; " + ... "sys.stdout.write('\\x1b[2J\\x1b[H\\x1b[32mworker\\x1b[0m\\r\\nidle'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="fn-win-vt", + ... x=15, + ... y=3, + ... window_command=f"{py} -u -c {shlex.quote(left_cmd)}", + ... ) + >>> w = s.active_window + >>> _ = w.set_option("pane-border-style", "default") + >>> _ = w.set_option("pane-active-border-style", "fg=green") + >>> p_right = w.split( + ... direction=PaneDirection.Right, + ... attach=True, + ... shell=f"{py} -u -c {shlex.quote(right_cmd)}", + ... size=7, + ... ) + >>> def _ready() -> bool: + ... txt = capture_window_vt(w).snapshot.text + ... return "ok" in txt and "idle" in txt + >>> retry_until(_ready) + True + >>> print(serialize_vt_snapshot(capture_window_vt(w).snapshot)) + size=15x3 cursor=(1,12,vis=True) alt=False modes=[] + ┌───────────────┐ + │api │worker │ + │ok │idle │ + │ │ │ + └───────────────┘ + styles: + r0[0..3]: bold fg=cyan + r0[8..14]: fg=green + r2[7..8]: fg=green + >>> for p in w.panes: + ... _ = p.send_vt_input("enter") + """ + _require_libvt() + from libvt.config import DEFAULT_LIMITS + from libvt.contrib.tmux.profile import TMUX_CAPTURE_POLICY, tmux_profile + from libvt.contrib.tmux.window import ( + build_tmux_window_capture_command, + build_tmux_window_list_command, + ) + + if window.window_id is None: + msg = "Window must have a window_id to capture VT state" + raise ValueError(msg) + if history_lines is not None: + if isinstance(history_lines, bool) or not isinstance(history_lines, int): + msg = ( + f"history_lines must be int or None, got {type(history_lines).__name__}" + ) + raise TypeError(msg) + if history_lines < 0: + msg = f"history_lines must be >= 0, got {history_lines}" + raise ValueError(msg) + + ver_str = get_version_str(window.server.tmux_bin) + list_cmd = build_tmux_window_list_command(window.window_id) + list_proc = window.server.cmd(*list_cmd.argv, timeout=timeout) + if list_proc.stderr: + raise_if_stderr(list_proc, "list-panes") + layout = list_cmd.parse(list_proc.stdout) + + cap_cmd = build_tmux_window_capture_command( + layout, + tmux_version=ver_str, + include_saved_primary=include_saved_primary, + history_lines=history_lines, + ) + cap_proc = window.server.cmd(*cap_cmd.argv, timeout=timeout) + if cap_proc.stderr: + raise_if_stderr(cap_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( + cap_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, @@ -907,6 +1069,101 @@ async def watch_pane( self._discard_pane_future(pane_id, fut) return handle + async def snapshot_window( + self, + window: Window | str, + *, + watch_missing: bool = True, + timeout: float = 5.0, + ) -> Snapshot: + """Composite a multi-pane *window* ``Snapshot`` over ``tmux -C``. + + Queries live window layout, border styles, and ``pane-border-format`` + on this control client and composites tear-free ``committed`` snapshots + from watched :class:`VtPaneHandle` instances. + + Parameters + ---------- + window : :class:`~libtmux.Window` or str + Target :class:`~libtmux.Window` or ``"@"`` window ID string. + watch_missing : bool, default True + Automatically attach any panes in *window* not yet watched on this + observer before compositing. + timeout : float, default 5.0 + Maximum seconds for layout queries and any initial pane handshakes. + + Returns + ------- + Snapshot + Composited window ``Snapshot`` with pane cells, borders, junctions, + ``pane-border-status``, and active-pane cursor. + """ + from libvt.contrib.tmux.control import TmuxAttachPhase + from libvt.contrib.tmux.profile import tmux_profile + from libvt.contrib.tmux.window import ( + TMUX_WINDOW_METADATA_FORMAT, + TMUX_WINDOW_PANE_FORMAT, + TmuxPaneSource, + TmuxWindowLayout, + composite_tmux_window, + ) + + self._raise_if_closed() + window_id = window if isinstance(window, str) else window.window_id + if window_id is None: + msg = "Window must have a window_id to snapshot" + raise ValueError(msg) + if ( + not window_id.startswith("@") + or not window_id[1:].isascii() + or not window_id[1:].isdigit() + ): + msg = f"window_id must be '@', got {window_id!r}" + raise ValueError(msg) + + pane_prefix = "__LIBTMUX_WIN_PANE__:" + async with asyncio.timeout(timeout): + win_block = await self._execute_command( + f"display-message -p -t '{window_id}' '{TMUX_WINDOW_METADATA_FORMAT}'", + timeout=timeout, + ) + panes_block = await self._execute_command( + f"list-panes -t '{window_id}' -F " + f"'{pane_prefix}{TMUX_WINDOW_PANE_FORMAT}'", + timeout=timeout, + ) + win_raw = b"\n".join(win_block.lines).decode("utf-8", errors="replace") + pane_raws: list[str] = [] + for raw_ln in panes_block.lines: + ln = raw_ln.decode("utf-8", errors="replace") + if ln.startswith(pane_prefix): + pane_raws.append(ln[len(pane_prefix) :]) + elif pane_raws: + pane_raws[-1] = f"{pane_raws[-1]}\n{ln}" + layout = TmuxWindowLayout.from_format_lines(win_raw, pane_raws) + + sources: dict[str, TmuxPaneSource] = {} + for wp in layout.panes: + handle = self._handles.get(wp.pane_id) + if ( + handle is None or handle.sync.phase != TmuxAttachPhase.LIVE + ) and watch_missing: + handle = await self.watch_pane(wp.pane_id, timeout=timeout) + if handle is not None and handle.sync.terminal is not None: + sources[wp.pane_id] = handle.terminal.committed + + eff_profile = ( + tmux_profile(self._tmux_version_str) + if self._profile is None + else self._profile + ) + return composite_tmux_window( + layout, + sources, + tmux_version=self._tmux_version_str, + profile=eff_profile, + ) + async def _resync_pane( self, pane_id: str, @@ -1131,19 +1388,34 @@ async def observe_pane_vt( def _resolve_screen_target( - target: Pane | VtPaneHandle | TmuxCaptureResult | Terminal | Snapshot, + target: ( + Pane + | Window + | VtPaneHandle + | TmuxCaptureResult + | TmuxWindowCaptureResult + | Terminal + | Snapshot + ), ) -> Terminal | Snapshot: """Extract a ``Terminal`` or ``Snapshot`` from *target*.""" _require_libvt() from libvt.contrib.tmux.capture import TmuxCaptureResult + from libvt.contrib.tmux.window import TmuxWindowCaptureResult from libvt.terminal import Snapshot, Terminal + from libtmux.window import Window + if isinstance(target, (Terminal, Snapshot)): return target if isinstance(target, TmuxCaptureResult): return target.terminal + if isinstance(target, TmuxWindowCaptureResult): + return target.snapshot if isinstance(target, VtPaneHandle): return target.terminal + if isinstance(target, Window): + return capture_window_vt(target).snapshot return capture_pane_vt( target, history_lines=0, @@ -1238,12 +1510,132 @@ def assert_pane_screen_box( assert_screen_box(resolved, expected, cursor=cursor) +def assert_window_screen( + target: Window | TmuxWindowCaptureResult | Snapshot, + expected: str | collections.abc.Sequence[str], + *, + cursor: tuple[int, int] | None = None, +) -> None: + r"""Assert that *target*'s composited window text matches *expected*. + + Accepts a :class:`~libtmux.Window` directly (capturing and compositing all + panes via :func:`capture_window_vt`), a ``TmuxWindowCaptureResult``, or a + composited ``Snapshot``. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libtmux.constants import PaneDirection + >>> from libtmux.test.retry import retry_until + >>> from libtmux.vt import assert_window_screen + >>> py = shlex.quote(sys.executable) + >>> left_cmd = ( + ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[Hleft'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> right_cmd = ( + ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[Hright'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="assert-win-vt", + ... x=11, + ... y=1, + ... window_command=f"{py} -u -c {shlex.quote(left_cmd)}", + ... ) + >>> w = s.active_window + >>> _ = w.split( + ... direction=PaneDirection.Right, + ... attach=True, + ... shell=f"{py} -u -c {shlex.quote(right_cmd)}", + ... size=5, + ... ) + >>> def _ready() -> bool: + ... txt = w.capture_vt().snapshot.text + ... return "left" in txt and "right" in txt + >>> retry_until(_ready) + True + >>> assert_window_screen(w, "left │right") + >>> for p in w.panes: + ... _ = p.send_vt_input("enter") + """ + resolved = _resolve_screen_target(target) + from libvt.testing import assert_screen + + assert_screen(resolved, expected, cursor=cursor) + + +def assert_window_screen_box( + target: Window | TmuxWindowCaptureResult | Snapshot, + expected: str, + *, + cursor: tuple[int, int] | None = None, +) -> None: + r"""Assert that *target* matches a column-exact composited window box diagram. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libtmux.constants import PaneDirection + >>> from libtmux.test.retry import retry_until + >>> from libtmux.vt import assert_window_screen_box + >>> py = shlex.quote(sys.executable) + >>> left_cmd = ( + ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[H日本\\r\\nok'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> right_cmd = ( + ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[Hgo\\r\\n42'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="assert-wbox-vt", + ... x=11, + ... y=2, + ... window_command=f"{py} -u -c {shlex.quote(left_cmd)}", + ... ) + >>> w = s.active_window + >>> _ = w.split( + ... direction=PaneDirection.Right, + ... attach=True, + ... shell=f"{py} -u -c {shlex.quote(right_cmd)}", + ... size=5, + ... ) + >>> def _ready() -> bool: + ... txt = w.capture_vt().snapshot.text + ... return "ok" in txt and "42" in txt + >>> retry_until(_ready) + True + >>> assert_window_screen_box( + ... w, + ... ''' + ... ┌───────────┐ + ... │日本 │go │ + ... │ok │42 │ + ... └───────────┘ + ... ''', + ... cursor=(1, 8), + ... ) + >>> for p in w.panes: + ... _ = 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", + "assert_window_screen", + "assert_window_screen_box", "capture_pane_vt", + "capture_window_vt", "observe_pane_vt", "send_pane_vt_input", ) diff --git a/src/libtmux/window.py b/src/libtmux/window.py index 75b25dcc8c..d0406cf15b 100644 --- a/src/libtmux/window.py +++ b/src/libtmux/window.py @@ -44,6 +44,9 @@ import types from typing import Never, Self + from libvt.config import Limits, Policy, Profile + from libvt.contrib.tmux.window import TmuxWindowCaptureResult + from libtmux.formats import Format from libtmux.options import OptionValue @@ -1870,6 +1873,115 @@ def width(self) -> str | None: """ return self.window_width + # + # VT integration (optional libtmux[vt] extra on Python 3.12+) + # + def capture_vt( + self, + *, + history_lines: int | None = 0, + include_saved_primary: bool = False, + scrollback: int | None = None, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + timeout: float | _UnsetType | None = _UNSET, + ) -> TmuxWindowCaptureResult: + r"""Capture and composite all visible panes in this window into a ``Snapshot``. + + Requires Python 3.12+ and ``libtmux[vt]`` (``pip install "libtmux[vt]"``). + + Parameters + ---------- + history_lines : int or None, default 0 + Maximum scrollback lines captured per pane (``0`` for viewport-only + ``-S 0``, ``None`` for full history, or ``N > 0`` for ``-S -N``). + include_saved_primary : bool, default False + Include ``capture-pane -a -q`` sections on each pane so saved + primary scrollback is available in ``result.panes[pane_id]``. + scrollback : int or None, optional + Explicit per-pane scrollback line capacity override. + 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 + ------- + TmuxWindowCaptureResult + Composited window ``snapshot``, per-pane ``panes`` mapping, parsed + ``layout``, ``zoomed`` state, and ``layout_stable`` check. + + Examples + -------- + >>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE + >>> import shlex, sys + >>> from libvt.testing import serialize_vt_snapshot + >>> from libtmux.constants import PaneDirection + >>> from libtmux.test.retry import retry_until + >>> py = shlex.quote(sys.executable) + >>> left_cmd = ( + ... "import sys; " + ... "sys.stdout.write('\\x1b[2J\\x1b[H\\x1b[1;36mapi\\x1b[0m\\r\\nok'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> right_cmd = ( + ... "import sys; " + ... "sys.stdout.write('\\x1b[2J\\x1b[H\\x1b[32mworker\\x1b[0m\\r\\nidle'); " + ... "sys.stdout.flush(); sys.stdin.read(1)" + ... ) + >>> s = server.new_session( + ... session_name="win-cap-vt", + ... x=15, + ... y=3, + ... window_command=f"{py} -u -c {shlex.quote(left_cmd)}", + ... ) + >>> w = s.active_window + >>> _ = w.set_option("pane-border-style", "default") + >>> _ = w.set_option("pane-active-border-style", "fg=green") + >>> _ = w.split( + ... direction=PaneDirection.Right, + ... attach=True, + ... shell=f"{py} -u -c {shlex.quote(right_cmd)}", + ... size=7, + ... ) + >>> def _ready() -> bool: + ... txt = w.capture_vt().snapshot.text + ... return "ok" in txt and "idle" in txt + >>> retry_until(_ready) + True + >>> print(serialize_vt_snapshot(w.capture_vt().snapshot)) + size=15x3 cursor=(1,12,vis=True) alt=False modes=[] + ┌───────────────┐ + │api │worker │ + │ok │idle │ + │ │ │ + └───────────────┘ + styles: + r0[0..3]: bold fg=cyan + r0[8..14]: fg=green + r2[7..8]: fg=green + >>> for p in w.panes: + ... _ = p.send_vt_input("enter") + """ + from libtmux.vt import capture_window_vt + + return capture_window_vt( + self, + history_lines=history_lines, + include_saved_primary=include_saved_primary, + scrollback=scrollback, + profile=profile, + policy=policy, + limits=limits, + timeout=timeout, + ) + # # Legacy: Redundant stuff we want to remove # diff --git a/tests/test_vt.py b/tests/test_vt.py index eab6a2cf2b..a31c0b0224 100644 --- a/tests/test_vt.py +++ b/tests/test_vt.py @@ -14,12 +14,16 @@ from libtmux import exc from libtmux.common import has_gte_version +from libtmux.constants import PaneDirection from libtmux.test.retry import retry_until from libtmux.vt import ( VtSessionObserver, _require_libvt, assert_pane_screen, assert_pane_screen_box, + assert_window_screen, + assert_window_screen_box, + capture_window_vt, ) if t.TYPE_CHECKING: @@ -725,3 +729,220 @@ async def _exercise() -> None: ) asyncio.run(_exercise()) + + +def test_window_capture_vt_splits_border_status_zoom_and_errors( + session: Session, +) -> None: + """``Window.capture_vt`` composites split borders, status labels, and zoom.""" + pytest.importorskip("libvt") + from libvt.exc import ScreenAssertionError + from libvt.style import AnsiColor + + py = shlex.quote(sys.executable) + + def _hold_cmd(payload: bytes, *, wait_go: bool = False) -> str: + hex_data = payload.hex() + pre = ( + "import 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'); " + if wait_go + else "" + ) + script = ( + "import sys; " + + pre + + f"sys.stdout.buffer.write(bytes.fromhex('{hex_data}')); " + "sys.stdout.buffer.flush(); sys.stdin.buffer.read(1)" + ) + return f"{py} -u -c {shlex.quote(script)}" + + win = session.new_window( + window_name="vt-win-cap", + window_shell=_hold_cmd( + b"\x1b]2;api\x07S0\r\nH0\r\nH1\r\nH2\r\n\x1b[1;32m200 OK\x1b[0m\r\n" + + "日本".encode(), + wait_go=True, + ), + ) + p_left = win.active_pane + assert p_left is not None + retry_until(lambda: "BOOT" in "\n".join(p_left.capture_pane())) + win.resize(height=6, width=23) + win.set_option("pane-border-status", "top") + win.set_option("pane-border-format", " #{pane_index}:#{pane_title} ") + win.set_option("pane-border-style", "fg=blue") + win.set_option("pane-active-border-style", "fg=green") + p_left.send_keys("g", enter=False, literal=True) + p_top_right = win.split( + direction=PaneDirection.Right, + attach=True, + shell=_hold_cmd(b"\x1b]2;db\x07\x1b[2J\x1b[H\x1b[36mpg:ready\x1b[0m"), + size=11, + ) + p_bot_right = win.split( + direction=PaneDirection.Below, + attach=True, + shell=_hold_cmd(b"\x1b]2;jobs\x07\x1b[2J\x1b[Hq=0"), + size=2, + ) + + def _all_rendered() -> bool: + snap = win.capture_vt().snapshot + txt = snap.text + return ( + "0:api" in txt + and "1:db" in txt + and "2:jobs" in txt + and "日本" in txt + and "pg:ready" in txt + and "q=0" in txt + ) + + retry_until(_all_rendered) + + res = win.capture_vt(history_lines=2) + assert res.zoomed is False + assert res.layout_stable is True + assert len(res.panes) == 3 + assert p_left.pane_id is not None + assert p_top_right.pane_id is not None + assert p_bot_right.pane_id is not None + assert len(res.panes[p_left.pane_id].snapshot.history) >= 1 + + snap = res.snapshot + assert (snap.rows, snap.cols) == (6, 23) + assert snap[0, 11].text == "┬" + assert snap[3, 11].text == "├" + assert snap[3, 11].style.fg == AnsiColor.GREEN + assert snap[0, 0].style.fg == AnsiColor.BLUE + assert snap[1, 12].style.fg == AnsiColor.CYAN + assert snap.cursor.visible is True + assert (snap.cursor.row, snap.cursor.col) == (4, 15) + + assert_window_screen(win, "\n".join(snap.lines), cursor=(4, 15)) + assert_window_screen_box( + res, + """ + ┌───────────────────────┐ + │── 0:api ──┬── 1:db ───│ + │H0 │pg:ready │ + │H1 │ │ + │H2 ├── 2:jobs ─│ + │200 OK │q=0 │ + │日本 │ │ + └───────────────────────┘ + """, + cursor=(4, 15), + ) + + with pytest.raises(ScreenAssertionError, match="Screen state mismatch"): + assert_window_screen_box( + res, + """ + ┌───────────────────────┐ + │── WRONG ──┬── 1:db ───│ + │H0 │pg:ready │ + │H1 │ │ + │H2 ├── 2:jobs ─│ + │200 OK │q=0 │ + │日本 │ │ + └───────────────────────┘ + """, + ) + + win.cmd("resize-pane", "-Z") + zoom_res = capture_window_vt(win) + assert zoom_res.zoomed is True + assert (zoom_res.snapshot.rows, zoom_res.snapshot.cols) == (6, 23) + assert "q=0" in zoom_res.snapshot.text + assert "pg:ready" not in zoom_res.snapshot.text + win.cmd("resize-pane", "-Z") + + with pytest.raises(ValueError, match="history_lines must be >= 0"): + capture_window_vt(win, history_lines=-1) + with pytest.raises(TypeError, match="history_lines must be int or None"): + capture_window_vt(win, history_lines=True) + + for p in (p_left, p_top_right, p_bot_right): + p.send_vt_input("enter") + win.kill() + with pytest.raises(exc.LibTmuxException): + win.capture_vt() + + +def test_vt_observer_snapshot_window_live_parity( + session: Session, + vt_observer: VtObserverFactory, +) -> None: + """``VtSessionObserver.snapshot_window`` matches ``Window.capture_vt``.""" + pytest.importorskip("libvt") + from libvt.testing import serialize_vt_snapshot + + py = shlex.quote(sys.executable) + + def _hold_cmd(payload: bytes) -> str: + hex_data = payload.hex() + script = ( + "import sys; " + f"sys.stdout.buffer.write(bytes.fromhex('{hex_data}')); " + "sys.stdout.buffer.flush(); sys.stdin.buffer.read(1)" + ) + return f"{py} -u -c {shlex.quote(script)}" + + win = session.new_window( + window_name="vt-obs-win", + window_shell=_hold_cmd(b"\x1b[2J\x1b[H\x1b[1;35mLEFT_OK\x1b[0m\r\nrow2"), + ) + win.resize(height=3, width=19) + win.set_option("pane-border-style", "default") + win.set_option("pane-active-border-style", "fg=green") + p1 = win.active_pane + assert p1 is not None + p2 = win.split( + direction=PaneDirection.Right, + attach=True, + shell=_hold_cmd(b"\x1b[2J\x1b[H\x1b[33mRIGHT\x1b[0m\r\n" + "日本".encode()), + size=9, + ) + + retry_until( + lambda: ( + "row2" in win.capture_vt().snapshot.text + and "日本" in win.capture_vt().snapshot.text + ) + ) + + async def _exercise() -> None: + async with vt_observer(history_lines=0) as obs: + h1 = await obs.watch_pane(p1) + await h1.wait_until("row2") + + # p2 is attached automatically when watch_missing=True. + live_snap = await obs.snapshot_window(win) + assert p2.pane_id in obs._handles + oneshot_snap = win.capture_vt().snapshot + + assert live_snap.display_lines == oneshot_snap.display_lines + assert (live_snap.cursor.row, live_snap.cursor.col) == ( + oneshot_snap.cursor.row, + oneshot_snap.cursor.col, + ) + assert serialize_vt_snapshot(live_snap) == serialize_vt_snapshot( + oneshot_snap + ) + + with pytest.raises(ValueError, match="window_id must be"): + await obs.snapshot_window("not-a-window-id") + with pytest.raises(exc.LibTmuxException): + await obs.snapshot_window("@99999", timeout=1.5) + + # Observer stays usable after a failed window query. + again = await obs.snapshot_window(win) + assert again.display_lines == oneshot_snap.display_lines + + asyncio.run(_exercise()) + for p in (p1, p2): + p.send_vt_input("enter") From ec61d34a6bb2fcde3e0d48096d7e905b8d3a3365 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 10:43:21 -0600 Subject: [PATCH 2/6] docs(vt): Document window VT capture why: Show tested multi-pane Snapshot grids in the VT guide. what: - Add a 3-pane split window doctest to docs/api/libtmux.vt.md --- docs/api/libtmux.vt.md | 104 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 97 insertions(+), 7 deletions(-) diff --git a/docs/api/libtmux.vt.md b/docs/api/libtmux.vt.md index 35c5e13f86..d1c180ebc6 100644 --- a/docs/api/libtmux.vt.md +++ b/docs/api/libtmux.vt.md @@ -3,13 +3,17 @@ # 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 +Python 3.12+ to reconstruct pane and multi-pane window screens, immutable +`Snapshot` grids, and `SGR` styles via {meth}`~libtmux.Pane.capture_vt` and +{meth}`~libtmux.Window.capture_vt`, stream live `tmux -C` updates via +{meth}`~libtmux.Session.observe_vt`, {meth}`~libtmux.Pane.observe_vt`, +{meth}`~libtmux.vt.VtSessionObserver.snapshot_window`, 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`. +{func}`~libtmux.vt.assert_pane_screen`, +{func}`~libtmux.vt.assert_pane_screen_box`, +{func}`~libtmux.vt.assert_window_screen`, and +{func}`~libtmux.vt.assert_window_screen_box`. Install with the `vt` extra: @@ -20,8 +24,9 @@ $ 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. +{meth}`~libtmux.Window.capture_vt`, {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 @@ -97,6 +102,91 @@ means disabled. When tmux omits the state, the flag is `None` and On those servers, attach with {meth}`~libtmux.Pane.observe_vt` before the application enables `?2004` to observe the mode change. +## Capture a multi-pane window (`Window.capture_vt`) + +When a window holds split panes, {meth}`~libtmux.Window.capture_vt` captures +every pane in one `tmux` command batch and composites their cells, box-drawing +dividers and junctions (`│`, `─`, `├`), `pane-border-status` labels, and the +active pane's cursor into a single window `Snapshot` (alongside each pane's +individual capture in `win_captured.panes`): + +```python +>>> import pytest; _ = pytest.importorskip("libvt") # doctest: +HIDE +>>> import shlex +>>> import sys +>>> from libvt.testing import serialize_vt_snapshot +>>> from libtmux.constants import PaneDirection +>>> from libtmux.test.retry import retry_until +>>> from libtmux.vt import assert_window_screen_box +>>> py = shlex.quote(sys.executable) +>>> def _pane_cmd(title: str, body: str) -> str: +... script = ( +... "import sys; " +... f"sys.stdout.write({title!r} + '\\x1b[2J\\x1b[H' + {body!r}); " +... "sys.stdout.flush(); sys.stdin.read(1)" +... ) +... return f"{py} -u -c {shlex.quote(script)}" +>>> win_session = server.new_session( +... session_name="vt-window", +... x=21, +... y=5, +... window_command=_pane_cmd("\x1b]2;api\x07", "\x1b[1;32m200 OK\x1b[0m\r\nready"), +... ) +>>> split_win = win_session.active_window +>>> _ = split_win.set_option("pane-border-style", "default") +>>> _ = split_win.set_option("pane-active-border-style", "fg=green") +>>> right_top = split_win.split( +... direction=PaneDirection.Right, +... attach=True, +... shell=_pane_cmd("\x1b]2;db\x07", "\x1b[36mpg:up\x1b[0m"), +... size=10, +... ) +>>> right_bot = split_win.split( +... direction=PaneDirection.Below, +... attach=True, +... shell=_pane_cmd("\x1b]2;jobs\x07", "q=0"), +... size=2, +... ) +>>> def _win_ready() -> bool: +... txt = split_win.capture_vt().snapshot.text +... return "ready" in txt and "pg:up" in txt and "q=0" in txt +>>> retry_until(_win_ready) +True +>>> win_captured = split_win.capture_vt() +>>> print(serialize_vt_snapshot(win_captured.snapshot)) +size=21x5 cursor=(3,14,vis=True) alt=False modes=[] +┌─────────────────────┐ +│200 OK │pg:up │ +│ready │ │ +│ ├──────────│ +│ │q=0 │ +│ │ │ +└─────────────────────┘ +styles: + r0[0..6]: bold fg=green + r0[11..16]: fg=cyan + r2[10..21]: fg=green + r3[10..11]: fg=green + r4[10..11]: fg=green +>>> assert_window_screen_box( +... win_captured, +... """ +... ┌─────────────────────┐ +... │200 OK │pg:up │ +... │ready │ │ +... │ ├──────────│ +... │ │q=0 │ +... │ │ │ +... └─────────────────────┘ +... """, +... cursor=(3, 14), +... ) +>>> len(win_captured.panes), win_captured.zoomed, win_captured.layout_stable +(3, False, True) +>>> for p in split_win.panes: +... _ = p.send_vt_input("enter") +``` + ## Page through captured scrollback (`snap.viewport()`) When `history_lines` retains primary scrollback (`None` for full history or a From d112c3168073af7d889cee6f402c087be324aae1 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Mon, 30 Nov 2026 19:13:48 -0600 Subject: [PATCH 3/6] tests(vt): Kill test window before pane exit why: Sending enter to every pane lets tmux reap the window before win.kill() runs under faster scheduling. what: - Call win.kill() directly in test_window_capture_vt_splits_border_status_zoom_and_errors --- tests/test_vt.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/test_vt.py b/tests/test_vt.py index a31c0b0224..411c5c2b27 100644 --- a/tests/test_vt.py +++ b/tests/test_vt.py @@ -866,8 +866,6 @@ def _all_rendered() -> bool: with pytest.raises(TypeError, match="history_lines must be int or None"): capture_window_vt(win, history_lines=True) - for p in (p_left, p_top_right, p_bot_right): - p.send_vt_input("enter") win.kill() with pytest.raises(exc.LibTmuxException): win.capture_vt() From 63f34d71279c7bd60539699a3c9a7a8042e72171 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 10:43:21 -0600 Subject: [PATCH 4/6] Window(fix[vt]): Refresh layout inline and test focus switches why: libvt checks active-pane stability in WIN_POST, sizes 3.3a-3.5 border-status spans to wp.width - 4, and derives default parse profiles from tmux_version. what: - Pass include_layout=True and forward profile directly in capture_window_vt - Shorten pane 2 title to fit 3.3a-3.5 border-status width and test focus switches --- src/libtmux/vt.py | 6 +++--- tests/test_vt.py | 20 ++++++++++++++++---- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/libtmux/vt.py b/src/libtmux/vt.py index 8db394070e..6ce119ae03 100644 --- a/src/libtmux/vt.py +++ b/src/libtmux/vt.py @@ -315,7 +315,7 @@ def capture_window_vt( """ _require_libvt() from libvt.config import DEFAULT_LIMITS - from libvt.contrib.tmux.profile import TMUX_CAPTURE_POLICY, tmux_profile + from libvt.contrib.tmux.profile import TMUX_CAPTURE_POLICY from libvt.contrib.tmux.window import ( build_tmux_window_capture_command, build_tmux_window_list_command, @@ -346,18 +346,18 @@ def capture_window_vt( tmux_version=ver_str, include_saved_primary=include_saved_primary, history_lines=history_lines, + include_layout=True, ) cap_proc = window.server.cmd(*cap_cmd.argv, timeout=timeout) if cap_proc.stderr: raise_if_stderr(cap_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( cap_proc.stdout, scrollback=scrollback, - profile=eff_profile, + profile=profile, policy=eff_policy, limits=eff_limits, ) diff --git a/tests/test_vt.py b/tests/test_vt.py index 411c5c2b27..2a1420006a 100644 --- a/tests/test_vt.py +++ b/tests/test_vt.py @@ -785,7 +785,7 @@ def _hold_cmd(payload: bytes, *, wait_go: bool = False) -> str: p_bot_right = win.split( direction=PaneDirection.Below, attach=True, - shell=_hold_cmd(b"\x1b]2;jobs\x07\x1b[2J\x1b[Hq=0"), + shell=_hold_cmd(b"\x1b]2;job\x07\x1b[2J\x1b[Hq=0"), size=2, ) @@ -795,7 +795,7 @@ def _all_rendered() -> bool: return ( "0:api" in txt and "1:db" in txt - and "2:jobs" in txt + and "2:job" in txt and "日本" in txt and "pg:ready" in txt and "q=0" in txt @@ -821,6 +821,18 @@ def _all_rendered() -> bool: assert snap[1, 12].style.fg == AnsiColor.CYAN assert snap.cursor.visible is True assert (snap.cursor.row, snap.cursor.col) == (4, 15) + assert res.panes[p_left.pane_id].terminal.profile.identity.xtversion.startswith( + "tmux " + ) + + p_left.select() + switched_res = win.capture_vt() + assert switched_res.layout_stable is True + assert (switched_res.snapshot.cursor.row, switched_res.snapshot.cursor.col) == ( + 5, + 4, + ) + p_bot_right.select() assert_window_screen(win, "\n".join(snap.lines), cursor=(4, 15)) assert_window_screen_box( @@ -830,7 +842,7 @@ def _all_rendered() -> bool: │── 0:api ──┬── 1:db ───│ │H0 │pg:ready │ │H1 │ │ - │H2 ├── 2:jobs ─│ + │H2 ├── 2:job ──│ │200 OK │q=0 │ │日本 │ │ └───────────────────────┘ @@ -846,7 +858,7 @@ def _all_rendered() -> bool: │── WRONG ──┬── 1:db ───│ │H0 │pg:ready │ │H1 │ │ - │H2 ├── 2:jobs ─│ + │H2 ├── 2:job ──│ │200 OK │q=0 │ │日本 │ │ └───────────────────────┘ From 305a8ab7051f1642556c9b66b3adf479a0c6f9eb Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Mon, 30 Nov 2026 20:43:19 -0600 Subject: [PATCH 5/6] docs(vt): Avoid ED2 cleared-cell reflow race on split why: Writing CSI 2 J before Window.split fills the initial full-width row with tmux GRID_FLAG_CLEARED spaces, causing grid_reflow_split to wrap cleared trailing cells and push row 0 into scrollback if python writes before split-window shrinks the pane. what: Omit redundant CSI 2 J / CSI H prefixes on freshly spawned split-window doctest and test commands so row cellused matches visible text width. --- docs/api/libtmux.vt.md | 2 +- src/libtmux/vt.py | 12 ++++++------ src/libtmux/window.py | 4 ++-- tests/test_vt.py | 4 ++-- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/api/libtmux.vt.md b/docs/api/libtmux.vt.md index d1c180ebc6..743e347496 100644 --- a/docs/api/libtmux.vt.md +++ b/docs/api/libtmux.vt.md @@ -122,7 +122,7 @@ individual capture in `win_captured.panes`): >>> def _pane_cmd(title: str, body: str) -> str: ... script = ( ... "import sys; " -... f"sys.stdout.write({title!r} + '\\x1b[2J\\x1b[H' + {body!r}); " +... f"sys.stdout.write({title!r} + {body!r}); " ... "sys.stdout.flush(); sys.stdin.read(1)" ... ) ... return f"{py} -u -c {shlex.quote(script)}" diff --git a/src/libtmux/vt.py b/src/libtmux/vt.py index 6ce119ae03..b29568dcfc 100644 --- a/src/libtmux/vt.py +++ b/src/libtmux/vt.py @@ -271,12 +271,12 @@ def capture_window_vt( >>> py = shlex.quote(sys.executable) >>> left_cmd = ( ... "import sys; " - ... "sys.stdout.write('\\x1b[2J\\x1b[H\\x1b[1;36mapi\\x1b[0m\\r\\nok'); " + ... "sys.stdout.write('\\x1b[1;36mapi\\x1b[0m\\r\\nok'); " ... "sys.stdout.flush(); sys.stdin.read(1)" ... ) >>> right_cmd = ( ... "import sys; " - ... "sys.stdout.write('\\x1b[2J\\x1b[H\\x1b[32mworker\\x1b[0m\\r\\nidle'); " + ... "sys.stdout.write('\\x1b[32mworker\\x1b[0m\\r\\nidle'); " ... "sys.stdout.flush(); sys.stdin.read(1)" ... ) >>> s = server.new_session( @@ -1531,11 +1531,11 @@ def assert_window_screen( >>> from libtmux.vt import assert_window_screen >>> py = shlex.quote(sys.executable) >>> left_cmd = ( - ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[Hleft'); " + ... "import sys; sys.stdout.write('left'); " ... "sys.stdout.flush(); sys.stdin.read(1)" ... ) >>> right_cmd = ( - ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[Hright'); " + ... "import sys; sys.stdout.write('right'); " ... "sys.stdout.flush(); sys.stdin.read(1)" ... ) >>> s = server.new_session( @@ -1583,11 +1583,11 @@ def assert_window_screen_box( >>> from libtmux.vt import assert_window_screen_box >>> py = shlex.quote(sys.executable) >>> left_cmd = ( - ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[H日本\\r\\nok'); " + ... "import sys; sys.stdout.write('日本\\r\\nok'); " ... "sys.stdout.flush(); sys.stdin.read(1)" ... ) >>> right_cmd = ( - ... "import sys; sys.stdout.write('\\x1b[2J\\x1b[Hgo\\r\\n42'); " + ... "import sys; sys.stdout.write('go\\r\\n42'); " ... "sys.stdout.flush(); sys.stdin.read(1)" ... ) >>> s = server.new_session( diff --git a/src/libtmux/window.py b/src/libtmux/window.py index d0406cf15b..a4727d521d 100644 --- a/src/libtmux/window.py +++ b/src/libtmux/window.py @@ -1927,12 +1927,12 @@ def capture_vt( >>> py = shlex.quote(sys.executable) >>> left_cmd = ( ... "import sys; " - ... "sys.stdout.write('\\x1b[2J\\x1b[H\\x1b[1;36mapi\\x1b[0m\\r\\nok'); " + ... "sys.stdout.write('\\x1b[1;36mapi\\x1b[0m\\r\\nok'); " ... "sys.stdout.flush(); sys.stdin.read(1)" ... ) >>> right_cmd = ( ... "import sys; " - ... "sys.stdout.write('\\x1b[2J\\x1b[H\\x1b[32mworker\\x1b[0m\\r\\nidle'); " + ... "sys.stdout.write('\\x1b[32mworker\\x1b[0m\\r\\nidle'); " ... "sys.stdout.flush(); sys.stdin.read(1)" ... ) >>> s = server.new_session( diff --git a/tests/test_vt.py b/tests/test_vt.py index 2a1420006a..03099feda5 100644 --- a/tests/test_vt.py +++ b/tests/test_vt.py @@ -904,7 +904,7 @@ def _hold_cmd(payload: bytes) -> str: win = session.new_window( window_name="vt-obs-win", - window_shell=_hold_cmd(b"\x1b[2J\x1b[H\x1b[1;35mLEFT_OK\x1b[0m\r\nrow2"), + window_shell=_hold_cmd(b"\x1b[1;35mLEFT_OK\x1b[0m\r\nrow2"), ) win.resize(height=3, width=19) win.set_option("pane-border-style", "default") @@ -914,7 +914,7 @@ def _hold_cmd(payload: bytes) -> str: p2 = win.split( direction=PaneDirection.Right, attach=True, - shell=_hold_cmd(b"\x1b[2J\x1b[H\x1b[33mRIGHT\x1b[0m\r\n" + "日本".encode()), + shell=_hold_cmd(b"\x1b[33mRIGHT\x1b[0m\r\n" + "日本".encode()), size=9, ) From 0f83e37c545787bf089047ade1357c4c1197b6d2 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 10:45:13 -0600 Subject: [PATCH 6/6] CHANGES(docs): Document Window.vt composition why: Record multi-pane Window.vt layout composition and borders. what: - Add unreleased 0.73.0 feature notes for #939. --- CHANGES | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGES b/CHANGES index e4d946a8da..7e67d24a09 100644 --- a/CHANGES +++ b/CHANGES @@ -26,6 +26,15 @@ cursor state, and active terminal modes, paired with {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. +#### Composite multi-pane window screens (#939) + +{meth}`~libtmux.Window.capture_vt` and +{meth}`~libtmux.vt.VtSessionObserver.snapshot_window` composite split pane +grids, box-drawing dividers and junctions, `pane-border-status` labels, and the +active pane cursor into a single window `Snapshot`, paired with +{func}`~libtmux.vt.assert_window_screen` and +{func}`~libtmux.vt.assert_window_screen_box`. See {ref}`vt`. + #### Stream live pane updates over control mode (#934) {meth}`~libtmux.Session.observe_vt`, {meth}`~libtmux.Pane.observe_vt`, and the