From ff20d29c33c1e019a666a863f59434e6e8b050a2 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 28 Nov 2026 20:10:04 -0600 Subject: [PATCH] tmux(feat[sync]): Add metadata, resize, resync (#60) why: Live tmux pane observers and libtmux[vt] need complete pane state capture, bounded history limits, %layout-change resize tracking, and in-place resynchronization that preserves SyncToken watermarks. what: - Extend TMUX_METADATA_FORMAT and TmuxPaneMetadata with cursor_shape, cursor_blinking, keypad_flag, and modify_other_keys, exposed on TmuxCaptureResult - Add bounded history_lines (-S 0 / -S -N) and tmux >= 3.7 -F detection (including master and - versions) across capture and sync - Resize live panes from V1 and V2 JSON %layout-change notifications and add in-place TmuxPaneSync.resync() --- CHANGES | 17 ++ docs/topics/migrating-from-pyte.md | 8 +- src/libvt/contrib/tmux/capture.py | 173 +++++++++++++-- src/libvt/contrib/tmux/control.py | 176 ++++++++++++++- src/libvt/contrib/tmux/profile.py | 8 +- tests/test_tmux.py | 334 +++++++++++++++++++++++++++++ 6 files changed, 688 insertions(+), 28 deletions(-) diff --git a/CHANGES b/CHANGES index 17e557d..716df7a 100644 --- a/CHANGES +++ b/CHANGES @@ -48,6 +48,23 @@ retained primary scrollback by `offset` rows without mutating live terminal state or blending primary history into alternate-screen snapshots. See {ref}`topics-migrating-from-pyte` for details. +#### Extended `tmux` pane metadata, layout resize, and in-place resync (#60) + +{data}`~libvt.contrib.tmux.capture.TMUX_METADATA_FORMAT` and +{class}`~libvt.contrib.tmux.capture.TmuxPaneMetadata` capture `cursor_shape`, +`cursor_blinking`, `keypad_flag`, and `modify_other_keys` (`pane_key_mode`); +{class}`~libvt.contrib.tmux.capture.TmuxCaptureResult` exposes `metadata` and +`post_metadata`; {func}`~libvt.contrib.tmux.capture.build_tmux_capture_command`, +{func}`~libvt.contrib.tmux.capture.decode_tmux_capture`, and +{class}`~libvt.contrib.tmux.control.TmuxPaneSync` accept bounded `history_lines` +(`-S 0` / `-S -N`) and enable `capture-pane -F` on `tmux >= 3.7` (with +{func}`~libvt.contrib.tmux.profile.parse_tmux_version` accepting `"master"` and +`-` tags). `TmuxPaneSync` resizes live panes from V1 and V2 JSON +`%layout-change` notifications and adds +{meth}`~libvt.contrib.tmux.control.TmuxPaneSync.resync` (also triggered on +`%pause` / `%continue` recovery) updating `sync.terminal` in place while +advancing its epoch for {class}`~libvt.terminal.SyncToken` consumers. + ### Documentation - Expand {ref}`topics-migrating-from-pyte` with a `pyte` compatibility matrix, diff --git a/docs/topics/migrating-from-pyte.md b/docs/topics/migrating-from-pyte.md index d50f3b0..62aaf0c 100644 --- a/docs/topics/migrating-from-pyte.md +++ b/docs/topics/migrating-from-pyte.md @@ -258,9 +258,11 @@ When observing a `tmux` pane via {mod}`libvt.contrib.tmux` {func}`~libvt.contrib.tmux.profile.tmux_profile` sets {attr}`DeccolmBehavior.CLEAR_ONLY ` and {data}`~libvt.contrib.tmux.profile.TMUX_OBSERVER_POLICY` sets -`emit_replies=False`. `tmux` remains authoritative for pane geometry across live -attachment, and passive observation never writes duplicate query replies back to -the application. +`emit_replies=False`. `tmux` remains authoritative for pane geometry across +`%layout-change` notifications and +{meth}`TmuxPaneSync.resync `, +and passive observation never writes duplicate query replies back to the +application. ## Compatibility matrix and documented omissions diff --git a/src/libvt/contrib/tmux/capture.py b/src/libvt/contrib/tmux/capture.py index 11b6331..673244e 100644 --- a/src/libvt/contrib/tmux/capture.py +++ b/src/libvt/contrib/tmux/capture.py @@ -7,7 +7,7 @@ import enum import re import secrets -from dataclasses import dataclass +from dataclasses import dataclass, field from libvt._grid import WidthRole, _Row, raw_width_bits from libvt.config import ( @@ -24,7 +24,7 @@ from libvt.events import PromptKind, PromptZone from libvt.modes import DEC_PRIVATE_MASK, Mode from libvt.parser import CsiParams, Parser, _parse_ascii_int, _parse_ascii_uint -from libvt.screen import Screen, ScrollRegion +from libvt.screen import CursorShape, Screen, ScrollRegion from libvt.style import DEFAULT_STYLE from libvt.terminal import Snapshot, Terminal @@ -41,6 +41,7 @@ "#{mouse_all_flag}\t#{mouse_sgr_flag}\t#{pane_private_modes}\t" "#{pane_tabs}\t#{history_size}\t#{history_limit}\t" "#{synchronized_output_flag}\t#{pane_output_generation}\t" + "#{cursor_shape}\t#{cursor_blinking}\t#{keypad_flag}\t#{pane_key_mode}\t" "#{pane_current_path}\t#{pane_title}" ) @@ -64,7 +65,7 @@ class TmuxLineFlags(enum.IntFlag): - """Per-line flags emitted by ``tmux capture-pane -F`` (``tmux >= 3.8``).""" + """Per-line flags emitted by ``tmux capture-pane -F`` (``tmux >= 3.7``).""" #: No per-line flags set (``-``). NONE = 0 @@ -237,6 +238,16 @@ class TmuxPaneMetadata: (``#{synchronized_output_flag}``). output_generation : int | None ``#{pane_output_generation}`` counter on ``tmux >= 3.8``, else ``None``. + cursor_shape : CursorShape | None + ``DECSCUSR`` cursor shape from ``#{cursor_shape}`` (``None`` when + unexposed by ``tmux``). + cursor_blinking : bool | None + Cursor blink flag from ``#{cursor_blinking}`` (``None`` when unexposed). + keypad_flag : bool + ``DECKPAM`` application keypad mode (``#{keypad_flag}``). + modify_other_keys : int + ``XTMODKEYS`` ``modifyOtherKeys`` level ``0``..``2`` mapped from + ``#{pane_key_mode}`` (``"VT10x"``, ``"Ext 1"``, ``"Ext 2"``). cwd : str ``#{pane_current_path}``, if available. title : str @@ -269,6 +280,10 @@ class TmuxPaneMetadata: history_limit: int = 2_000 synchronized: bool = False output_generation: int | None = None + cursor_shape: CursorShape | None = None + cursor_blinking: bool | None = None + keypad_flag: bool = False + modify_other_keys: int = 0 cwd: str = "" title: str = "" @@ -320,12 +335,49 @@ def from_format_line(cls, line: str) -> TmuxPaneMetadata: (80, 24, 3, 1) """ cleaned = line.rstrip("\r\n") - parts = cleaned.split("\t", 26) - if len(parts) < 27: - parts.extend([""] * (27 - len(parts))) + cursor_shape_raw = "" + cursor_blink_raw = "" + keypad_raw = "" + key_mode_raw = "" + if cleaned.count("\t") >= 30: + cand = cleaned.split("\t", 30) + if cand[25].strip() in ("", "default", "block", "underline", "bar"): + parts = cand + cursor_shape_raw = parts[25].strip() + cursor_blink_raw = parts[26].strip() + keypad_raw = parts[27] + key_mode_raw = parts[28].strip() + cwd_val = parts[29] + title_val = parts[30] + else: + parts = cleaned.split("\t", 26) + cwd_val = parts[25] + title_val = parts[26] + else: + parts = cleaned.split("\t", 26) + if len(parts) < 27: + parts.extend([""] * (27 - len(parts))) + cwd_val = parts[25] + title_val = parts[26] cols = min(_TMUX_MAX_DIM, max(1, _opt_int(parts[0], 80))) rows = min(_TMUX_MAX_DIM, max(1, _opt_int(parts[1], 24))) + c_shape: CursorShape | None = None + if cursor_shape_raw in ("block", "default"): + c_shape = CursorShape.BLOCK + elif cursor_shape_raw == "underline": + c_shape = CursorShape.UNDERLINE + elif cursor_shape_raw == "bar": + c_shape = CursorShape.BAR + + c_blink: bool | None = None + if cursor_blink_raw in ("0", "1"): + c_blink = cursor_blink_raw == "1" + + mod_keys = ( + 2 if key_mode_raw == "Ext 2" else (1 if key_mode_raw == "Ext 1" else 0) + ) + priv_raw = parts[19].strip() priv_modes: set[int] = set() focus_on = False @@ -380,8 +432,12 @@ def from_format_line(cls, line: str) -> TmuxPaneMetadata: history_limit=max(0, min(_TMUX_MAX_HISTORY, _opt_int(parts[22], 2_000))), synchronized=_opt_bool(parts[23]) or (2026 in priv_modes), output_generation=out_gen, - cwd=parts[25], - title=parts[26], + cursor_shape=c_shape, + cursor_blinking=c_blink, + keypad_flag=_opt_bool(keypad_raw), + modify_other_keys=mod_keys, + cwd=cwd_val, + title=title_val, ) @@ -428,12 +484,18 @@ class TmuxCaptureResult: line_flags : tuple[TmuxLineFlags, ...] Per-line flags across ``history + viewport`` (all ``NONE`` when ``flagged=False``). + metadata : TmuxPaneMetadata + Parsed pre-capture pane metadata applied during reconstruction. + post_metadata : TmuxPaneMetadata | None + Optional post-capture pane metadata sample when bracketed. """ terminal: Terminal snapshot: Snapshot completeness: CaptureCompleteness line_flags: tuple[TmuxLineFlags, ...] + metadata: TmuxPaneMetadata = field(default_factory=TmuxPaneMetadata) + post_metadata: TmuxPaneMetadata | None = None def _rewrite_tmux_overline_sgr(params: CsiParams) -> CsiParams: @@ -1040,6 +1102,18 @@ def _populate_screen_from_lines( return tuple(flags_list), exact_wraps, zones, saw_tab +def _validate_history_lines(history_lines: int | None) -> int | None: + if history_lines is None: + return 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) + return min(_TMUX_MAX_HISTORY, history_lines) + + def decode_tmux_capture( captured: CaptureInput, *, @@ -1047,6 +1121,7 @@ def decode_tmux_capture( rows: int = 24, cols: int = 80, scrollback: int | None = None, + history_lines: int | None = None, flagged: bool = False, trim_trailing: bool = False, joined_capture: CaptureInput | None = None, @@ -1088,6 +1163,10 @@ def decode_tmux_capture( scrollback : int | None Explicit scrollback line cap; when ``None``, defaults to ``metadata.history_limit`` if *metadata* is provided, else ``2000``. + history_lines : int | None + Maximum scrollback lines requested via ``capture-pane -S`` (``None`` + for full history ``-S -``, ``0`` for viewport-only ``-S 0``, or ``N`` + for ``-S -N``). flagged : bool ``True`` when *captured* includes ``capture-pane -F`` line prefixes. trim_trailing : bool @@ -1139,6 +1218,7 @@ def decode_tmux_capture( >>> res.snapshot.lines ('ready', 'done') """ + eff_hist_req = _validate_history_lines(history_lines) fallback_sb = 2_000 if scrollback is None else scrollback if isinstance(metadata, str): meta = TmuxPaneMetadata.from_format_line(metadata) @@ -1181,14 +1261,19 @@ def decode_tmux_capture( raw_lines = _split_capture_lines(captured) stripped_trailing = 0 + expected_hist = ( + meta.history_size + if eff_hist_req is None + else min(meta.history_size, eff_hist_req) + ) if ( metadata is not None and not flagged - and meta.history_size > 0 - and len(raw_lines) >= meta.history_size - and len(raw_lines) < meta.history_size + eff_rows + and expected_hist > 0 + and len(raw_lines) >= expected_hist + and len(raw_lines) < expected_hist + eff_rows ): - stripped_trailing = meta.history_size + eff_rows - len(raw_lines) + stripped_trailing = expected_hist + eff_rows - len(raw_lines) raw_lines.extend([""] * stripped_trailing) saw_tabs = False if meta.alternate_on: @@ -1333,6 +1418,26 @@ def decode_tmux_capture( for z in zones: term._prompt_zones.append(z) + if ( + metadata is not None + and meta.history_size > term.screens.primary._scrolled_total + ): + offset_delta = meta.history_size - term.screens.primary._scrolled_total + term.screens.primary._scrolled_total += offset_delta + term.screens.primary._evicted_total += offset_delta + if term._prompt_zones: + shifted = [ + PromptZone( + kind=z.kind, + abs_row=z.abs_row + offset_delta, + col=z.col, + exit_code=z.exit_code, + ) + for z in term._prompt_zones + ] + term._prompt_zones.clear() + term._prompt_zones.extend(shifted) + active = term.screens.active sr_top = max(0, min(eff_rows - 1, meta.scroll_region_upper)) sr_bot_raw = ( @@ -1351,6 +1456,7 @@ def decode_tmux_capture( term.modes.set_mode(Mode.DECOM, enabled=meta.origin_flag) term.modes.set_mode(Mode.DECTCEM, enabled=meta.cursor_visible) term.modes.set_mode(Mode.DECCKM, enabled=meta.keypad_cursor_flag) + term.modes.set_mode(Mode.APPLICATION_KEYPAD, enabled=meta.keypad_flag) term.modes.set_mode(Mode.BRACKETED_PASTE, enabled=meta.bracketed_paste_flag) term.modes.set_mode(Mode.MOUSE_VT200, enabled=meta.mouse_standard_flag) term.modes.set_mode(Mode.MOUSE_BUTTON_EVENT, enabled=meta.mouse_button_flag) @@ -1359,6 +1465,7 @@ def decode_tmux_capture( term.modes.set_mode(Mode.FOCUS_EVENT, enabled=meta.focus_events_flag) for priv_code in meta.private_modes: if 0 <= priv_code < DEC_PRIVATE_MASK and priv_code not in ( + 3, 47, 1047, 1049, @@ -1369,9 +1476,14 @@ def decode_tmux_capture( term.modes.set_mode(Mode(raw_m), enabled=True) active._cur_visible = meta.cursor_visible + if meta.cursor_shape is not None: + active._cur_shape = meta.cursor_shape + if meta.cursor_blinking is not None: + active._cur_blinking = meta.cursor_blinking active._cur_row = meta.clamped_cursor_row active._cur_col = meta.clamped_cursor_col active._pending_wrap = meta.pending_wrap + active._modify_other_keys = meta.modify_other_keys term._g_sets = ["B", profile.screen.default_g1_charset, "B", "B"] term._gl = 0 @@ -1397,6 +1509,8 @@ def decode_tmux_capture( uncalibrated_tabs = saw_tabs and meta.pane_tabs is None unexposed = set(_BASE_UNEXPOSED_FIELDS) + if meta.cursor_shape is not None: + unexposed.discard("cursor_shape") if uncalibrated_tabs: unexposed.add("pane_tabs") if not exact_wraps: @@ -1427,6 +1541,8 @@ def decode_tmux_capture( snapshot=term.snapshot(), completeness=completeness, line_flags=line_flags, + metadata=meta, + post_metadata=post_meta, ) @@ -1444,14 +1560,17 @@ class TmuxCaptureCommand: nonce : str Boundary sentinel token bracketing each output section. flagged : bool - ``True`` when ``capture-pane -F`` is included (``tmux >= 3.8``). + ``True`` when ``capture-pane -F`` is included (``tmux >= 3.7``). trim_trailing : bool ``True`` when ``capture-pane -T`` is included (``tmux >= 3.4``). has_joined : bool ``True`` when companion ``capture-pane -J`` sections are included - (``tmux < 3.8``). + (``tmux < 3.7``). include_saved_primary : bool ``True`` when ``capture-pane -a -q`` sections are included. + history_lines : int | None + Requested scrollback bound (``None`` for full history, ``0`` for + viewport-only, or ``N`` for ``-S -N``). """ argv: tuple[str, ...] @@ -1460,6 +1579,7 @@ class TmuxCaptureCommand: trim_trailing: bool has_joined: bool include_saved_primary: bool + history_lines: int | None = None def parse( self, @@ -1596,6 +1716,7 @@ def parse( metadata=pre_meta, post_metadata=post_meta, scrollback=scrollback, + history_lines=self.history_lines, flagged=self.flagged, trim_trailing=self.trim_trailing, joined_capture=joined_lines, @@ -1626,13 +1747,14 @@ def build_tmux_capture_command( *, tmux_version: tuple[int, int] | str = "3.8a", include_saved_primary: bool = True, + history_lines: int | None = None, nonce: str | None = None, ) -> TmuxCaptureCommand: r"""Build a single-invocation ``tmux`` command chaining metadata and capture. Chains ``display-message`` and ``capture-pane -S - -E - -e -p -N -T -F`` on - ``tmux >= 3.8`` (falling back to ``-e -p -N -T`` + ``-e -p -J`` on - ``3.4``-``3.7`` and ``-e -p -N`` + ``-e -p -J`` on ``3.3a``) inside one + ``tmux >= 3.7`` (falling back to ``-e -p -N -T`` + ``-e -p -J`` on + ``3.4``-``3.6`` and ``-e -p -N`` + ``-e -p -J`` on ``3.3a``) inside one atomic ``tmux`` command-queue batch so pane output cannot drift between commands and trailing blank viewport rows are preserved ahead of the closing ``POST`` footer. @@ -1644,10 +1766,14 @@ def build_tmux_capture_command( omitted so ``tmux`` targets the current pane. tmux_version : tuple[int, int] | str Target ``tmux`` version as ``(major, minor)`` or ``tmux -V`` string - (e.g. ``"3.8a"``, ``"3.6"``, ``"3.3a"``). + (e.g. ``"3.8a"``, ``"3.7"``, ``"3.6"``, ``"3.3a"``). include_saved_primary : bool Include ``capture-pane -a -q`` sections to restore backgrounded primary history when ``alternate_on`` is active. + history_lines : int | None + Maximum scrollback lines to capture above the viewport (``None`` for + ``-S -`` full history, ``0`` for ``-S 0`` viewport-only, or ``N > 0`` + for ``-S -N``). nonce : str | None Explicit ASCII boundary token matching ``[0-9A-Za-z_-]{8,128}``; generated via :func:`secrets.token_hex` when ``None``. @@ -1660,8 +1786,10 @@ def build_tmux_capture_command( Raises ------ + TypeError + If *history_lines* is not an ``int`` or ``None``. ValueError - If *target*, *tmux_version*, or *nonce* is invalid. + If *target*, *tmux_version*, *history_lines*, or *nonce* is invalid. References ---------- @@ -1680,6 +1808,7 @@ def build_tmux_capture_command( ): msg = f"invalid tmux target {target[:64]!r}" raise ValueError(msg) + eff_hist = _validate_history_lines(history_lines) eff_nonce = f"__LIBVT_CAP_{secrets.token_hex(16)}__" if nonce is None else nonce if _NONCE_RE.match(eff_nonce) is None: msg = ( @@ -1689,20 +1818,21 @@ def build_tmux_capture_command( raise ValueError(msg) ver = parse_tmux_version(tmux_version) - flagged = ver >= (3, 8) + flagged = ver >= (3, 7) trim_trailing = ver >= (3, 4) has_joined = not flagged t_args: tuple[str, ...] = ( ("-t", _escape_tmux_arg(target)) if target is not None else () ) + start_arg = "-" if eff_hist is None else ("0" if eff_hist == 0 else f"-{eff_hist}") - cap_flags: list[str] = ["-S", "-", "-E", "-", "-e", "-p", "-N"] + cap_flags: list[str] = ["-S", start_arg, "-E", "-", "-e", "-p", "-N"] if trim_trailing: cap_flags.append("-T") if flagged: cap_flags.append("-F") - joined_flags = ["-S", "-", "-E", "-", "-e", "-p", "-J"] + joined_flags = ["-S", start_arg, "-E", "-", "-e", "-p", "-J"] argv: list[str] = [ "display-message", @@ -1781,6 +1911,7 @@ def build_tmux_capture_command( trim_trailing=trim_trailing, has_joined=has_joined, include_saved_primary=include_saved_primary, + history_lines=eff_hist, ) diff --git a/src/libvt/contrib/tmux/control.py b/src/libvt/contrib/tmux/control.py index 581562c..1bdb82f 100644 --- a/src/libvt/contrib/tmux/control.py +++ b/src/libvt/contrib/tmux/control.py @@ -3,7 +3,9 @@ from __future__ import annotations import collections.abc +import dataclasses import enum +import json import os import re import typing as t @@ -19,6 +21,119 @@ _GUARD_LINE_RE = re.compile(rb"^%(begin|end|error) (-?[0-9]+) ([0-9]+) ([0-9]+)\Z") _DCS_CC_PREFIX = b"\x1bP1000p" _SAFE_TMUX_ARG_RE = re.compile(r"\A[A-Za-z0-9_./-]+\Z") +_V1_PANE_CELL_RE = re.compile( + r"(?:^|[,\[{])([0-9]+)x([0-9]+),-?[0-9]+,-?[0-9]+,([0-9]+)(?=[,\]}]|\Z)", + re.ASCII, +) +_MAX_LAYOUT_DIM = 10_000 + + +def _search_v2_layout_node(node: object, pane_id: str) -> tuple[int, int] | None: + if isinstance(node, dict): + if node.get("t") == "p" and node.get("I") == pane_id: + w = node.get("w") + h = node.get("h") + if ( + not isinstance(w, bool) + and not isinstance(h, bool) + and isinstance(w, int) + and isinstance(h, int) + and 1 <= w <= _MAX_LAYOUT_DIM + and 1 <= h <= _MAX_LAYOUT_DIM + ): + return (h, w) + return None + children = node.get("c") + if isinstance(children, list): + for child in children: + found = _search_v2_layout_node(child, pane_id) + if found is not None: + return found + for sub_key in ("L", "F"): + sub = node.get(sub_key) + if sub is not None: + found = _search_v2_layout_node(sub, pane_id) + if found is not None: + return found + elif isinstance(node, list): + for item in node: + found = _search_v2_layout_node(item, pane_id) + if found is not None: + return found + return None + + +def _parse_layout_pane_size(layout: str, pane_id: str) -> tuple[int, int] | None: + """Extract ``(rows, cols)`` for *pane_id* from a V1 or V2 ``tmux`` layout.""" + if not layout or not pane_id.startswith("%"): + return None + stripped = layout.strip() + if stripped.startswith("{"): + try: + doc = json.loads(stripped) + except ValueError: + return None + return _search_v2_layout_node(doc, pane_id) + target_num = pane_id[1:] + for match in _V1_PANE_CELL_RE.finditer(stripped): + if match.group(3) == target_num: + cols = int(match.group(1)) + rows = int(match.group(2)) + if 1 <= rows <= _MAX_LAYOUT_DIM and 1 <= cols <= _MAX_LAYOUT_DIM: + return (rows, cols) + return None + return None + + +def _adopt_terminal_state(dst: Terminal, src: Terminal) -> None: + """Replace *dst* screen/mode/parser state from *src* in place and advance epoch.""" + dst._screens = src._screens + dst._screens._on_mutate = dst._on_screen_mutate + dst._screens.primary._on_mutate = dst._on_screen_mutate + dst._screens.alternate._on_mutate = dst._on_screen_mutate + dst._modes._enabled = set(src._modes._enabled) + dst._parser = src._parser + dst._docs_utf8_active = src._docs_utf8_active + dst._saved_docs_charset = src._saved_docs_charset + dst._passthrough_parser = src._passthrough_parser + dst._style = src._style + dst._protected = src._protected + dst._hyperlink = src._hyperlink + dst._sync_pen_cache() + dst._g_sets = list(src._g_sets) + dst._gl = src._gl + dst._single_shift = src._single_shift + dst._saved_primary = src._saved_primary + dst._saved_alt = src._saved_alt + dst._saved_decsc = src._saved_decsc + dst._saved_private_modes = dict(src._saved_private_modes) + dst._has_alt_saved = src._has_alt_saved + dst._last_printed = src._last_printed + dst._last_printed_pos = src._last_printed_pos + dst._cluster_state = src._cluster_state + dst._cluster_len = src._cluster_len + dst._pending_prepend = src._pending_prepend + dst._title = src._title + dst._icon_title = src._icon_title + dst._window_name = src._window_name + dst._cwd = src._cwd + dst._cwd_uri = src._cwd_uri + dst._prompt_zones.clear() + dst._prompt_zones.extend(src._prompt_zones) + dst._last_prompt_osc_code = src._last_prompt_osc_code + dst._last_prompt_zone = src._last_prompt_zone + dst._sync_hold_pending = src._sync_hold_pending + dst._held_snapshot = None + dst._held_sync_token = None + if src.synchronized: + dst._sync_generation += 1 + dst._cached_appearance = None + dst._appearance_revision += 1 + dst._aux_revision += 1 + dst._cached_snapshot = None + dst._epoch += 1 + dst._generation += 1 + dst._committed_generation += 1 def _tmux_quote(arg: str) -> str: @@ -689,6 +804,9 @@ class TmuxPaneSync: Target ``tmux`` version string or ``(major, minor)`` tuple. scrollback : int, default 2_000 Scrollback capacity for the reconstructed :class:`~libvt.terminal.Terminal`. + history_lines : int | None, default None + Maximum scrollback lines requested on each capture/resync (``None`` for + full history, ``0`` for viewport-only, or ``N`` for ``-S -N``). profile : Profile | None, default None Optional inner-pane profile (defaults to ``tmux_profile(tmux_version)``). policy : Policy | None, default None @@ -704,6 +822,8 @@ class TmuxPaneSync: Configured ``tmux`` version. scrollback : int Configured scrollback capacity in lines. + history_lines : int | None + Configured scrollback line bound for capture commands. capture_result : TmuxCaptureResult | None Completed baseline capture result once :attr:`phase` reaches ``LIVE``. terminal : Terminal | None @@ -741,6 +861,7 @@ class TmuxPaneSync: "_policy", "_profile", "capture_result", + "history_lines", "pane_id", "scrollback", "terminal", @@ -753,6 +874,7 @@ def __init__( *, tmux_version: tuple[int, int] | str = "3.8a", scrollback: int = 2_000, + history_lines: int | None = None, profile: Profile | None = None, policy: Policy | None = None, limits: Limits | None = None, @@ -764,12 +886,23 @@ def __init__( ): msg = f"pane_id must be '%', got {pane_id!r}" raise ValueError(msg) + if history_lines is not None: + if isinstance(history_lines, bool) or not isinstance(history_lines, int): + msg = ( + "history_lines must be int or None, got " + f"{type(history_lines).__name__}" + ) + raise TypeError(msg) + if history_lines < 0: + msg = f"history_lines must be >= 0, got {history_lines}" + raise ValueError(msg) from libvt.contrib.tmux.profile import parse_tmux_version parse_tmux_version(tmux_version) self.pane_id = pane_id self.tmux_version = tmux_version self.scrollback = scrollback + self.history_lines = history_lines self._profile = profile self._policy = policy self._limits = limits @@ -818,12 +951,29 @@ def begin_attach(self) -> str: f"display-message -p -t '{self.pane_id}' '{marker}'" ) + def resync(self) -> str: + r"""Trigger an explicit two-phase resynchronization in place. + + Re-runs the atomic pause barrier + ``capture-pane`` + ``-P -p -C`` + + ``continue`` sequence and updates any existing + :attr:`~libvt.contrib.tmux.control.TmuxPaneSync.terminal` in place + (incrementing its epoch so existing :class:`~libvt.terminal.SyncToken` + consumers receive :attr:`~libvt.terminal.ResyncReason.EPOCH_CHANGED`). + + Returns + ------- + str + ``;``-chained Phase 1 pause command line to send on ``tmux -C`` stdin. + """ + return self.begin_attach() + def _build_capture_batch(self) -> str: from libvt.contrib.tmux.capture import build_tmux_capture_command cap_cmd = build_tmux_capture_command( self.pane_id, tmux_version=self.tmux_version, + history_lines=self.history_lines, ) self._capture_cmd_obj = cap_cmd subcmds: list[list[str]] = [[]] @@ -888,7 +1038,21 @@ def handle_event(self, event: TmuxControlEvent) -> str | None: if isinstance(event, TmuxContinue): if event.pane_id == self.pane_id and self._phase == TmuxAttachPhase.PAUSED: - self._phase = TmuxAttachPhase.LIVE + return self.resync() + return None + + if isinstance(event, TmuxLayoutChange): + if self._phase == TmuxAttachPhase.LIVE and self.terminal is not None: + size = _parse_layout_pane_size(event.visible_layout, self.pane_id) + if size is None: + size = _parse_layout_pane_size(event.layout, self.pane_id) + if size is not None: + new_rows, new_cols = size + if (new_rows, new_cols) != ( + self.terminal.rows, + self.terminal.cols, + ): + self.terminal.resize(rows=new_rows, cols=new_cols) return None if not isinstance(event, TmuxCommandBlock) or event.flags != 1: @@ -958,8 +1122,16 @@ def handle_event(self, event: TmuxControlEvent) -> str | None: pending_raw = unescape_tmux_control_output(b"".join(pend_block.lines)) if pending_raw: res.terminal.feed(pending_raw) + if self.terminal is not None: + _adopt_terminal_state(self.terminal, res.terminal) + res = dataclasses.replace( + res, + terminal=self.terminal, + snapshot=self.terminal.snapshot(), + ) + else: + self.terminal = res.terminal self.capture_result = res - self.terminal = res.terminal self._collected_blocks.clear() self._expected_blocks = 0 self._phase = TmuxAttachPhase.LIVE diff --git a/src/libvt/contrib/tmux/profile.py b/src/libvt/contrib/tmux/profile.py index fad72a9..7cdef53 100644 --- a/src/libvt/contrib/tmux/profile.py +++ b/src/libvt/contrib/tmux/profile.py @@ -16,8 +16,10 @@ UnicodeBehavior, ) +_TMUX_MASTER_RE = re.compile(r"^\s*(?:tmux\s+)?master\s*\Z", re.ASCII) _TMUX_VERSION_RE = re.compile( - r"^\s*(?:tmux\s+)?(?:next-)?([0-9]{1,3})\.([0-9]{1,3})(?:[a-z]|-rc[0-9]{0,3})?\s*\Z", + r"^\s*(?:tmux\s+)?(?:next-)?([0-9]{1,3})\.([0-9]{1,3})" + r"(?:[a-z]|-[A-Za-z0-9._-]+)?\s*\Z", re.ASCII, ) @@ -70,6 +72,8 @@ def parse_tmux_version(version: tuple[int, int] | str) -> tuple[int, int]: if not isinstance(version, str): msg = f"invalid tmux version type {type(version).__name__}" raise TypeError(msg) + if _TMUX_MASTER_RE.match(version) is not None: + return (3, 9) m = _TMUX_VERSION_RE.match(version) if m is None: msg = ( @@ -164,9 +168,9 @@ def tmux_profile( xtsave_enabled=False, separate_alt_save_cursor=True, ris_alt_screen=RisAltScreenBehavior.KEEP_ACTIVE_SCREEN, - deccolm=DeccolmBehavior.CLEAR_ONLY, allow_esc_k_title=True, sixel_erase_policy="cell_mask" if at_least_3_9 else "whole_image", + deccolm=DeccolmBehavior.CLEAR_ONLY, ), input=InputBehavior( kitty_keyboard_enabled=False, diff --git a/tests/test_tmux.py b/tests/test_tmux.py index db64557..8194e7d 100644 --- a/tests/test_tmux.py +++ b/tests/test_tmux.py @@ -409,6 +409,25 @@ def test_capture_overline_scoping_ntf_wraps_and_command_bundle() -> None: assert cmd_38.trim_trailing is True assert cmd_38.has_joined is False + cmd_37 = build_tmux_capture_command( + "%1", + tmux_version="3.7-openbsd", + history_lines=25, + nonce="NONCE_37", + ) + assert cmd_37.flagged is True + assert cmd_37.has_joined is False + assert cmd_37.history_lines == 25 + assert cmd_37.argv[ + cmd_37.argv.index("capture-pane") + 1 : cmd_37.argv.index("capture-pane") + 3 + ] == ("-S", "-25") + cmd_zero = build_tmux_capture_command("%1", history_lines=0, nonce="NONCE_Z0") + assert cmd_zero.argv[ + cmd_zero.argv.index("capture-pane") + 1 : cmd_zero.argv.index("capture-pane") + + 3 + ] == ("-S", "0") + assert tmux_profile("tmux master").queries.decrqss_enabled is True + cmd_36 = build_tmux_capture_command("%1", tmux_version="3.6", nonce="NONCE_36") assert "-T" in cmd_36.argv assert "-F" not in cmd_36.argv @@ -764,3 +783,318 @@ def test_tmux_control_live_pane_sync_with_pending_escape() -> None: check=False, capture_output=True, ) + + +def test_tmux_metadata_cursor_keys_history_bounds_layout_resize_and_resync() -> None: + """Extended metadata, ``history_lines``, ``%layout-change``, and ``resync``.""" + from libvt.contrib.tmux import ( + TmuxAttachPhase, + TmuxCommandBlock, + TmuxContinue, + TmuxLayoutChange, + TmuxPaneSync, + TmuxPause, + ) + from libvt.screen import CursorShape + from libvt.terminal import ResyncReason + + # 31-field TMUX_METADATA_FORMAT with cursor_shape, cursor_blinking, keypad_flag, + # pane_key_mode, and tab-containing pane_title: + ext_line = ( + "10\t4\t2\t1\t1\t0\t4294967295\t4294967295\t0\t3\t" + "0\t0\t1\t0\t1\t0\t0\t0\t0\t\t\t50\t2000\t0\t12\t" + "bar\t0\t1\tExt 2\t/work/repo\tmy\ttitle" + ) + meta = TmuxPaneMetadata.from_format_line(ext_line) + assert meta.cursor_shape == CursorShape.BAR + assert meta.cursor_blinking is False + assert meta.keypad_flag is True + assert meta.modify_other_keys == 2 + assert meta.cwd == "/work/repo" + assert meta.title == "my\ttitle" + + # Bounded history_lines=2 with history_size=50 and stripped bottom rows: + bounded = decode_tmux_capture( + ["H48", "H49", "V0", "V1"], + metadata=meta, + post_metadata=meta, + history_lines=2, + ) + assert bounded.metadata == meta + assert bounded.post_metadata == meta + assert "cursor_shape" not in bounded.completeness.unexposed_fields + assert bounded.terminal.cursor.shape == CursorShape.BAR + assert bounded.terminal.cursor.blinking is False + assert bounded.terminal.modes.is_set(Mode.APPLICATION_KEYPAD) + assert bounded.terminal.modify_other_keys == 2 + assert [r.text for r in bounded.snapshot.history] == ["H48", "H49"] + assert bounded.snapshot.lines == ("V0", "V1", "", "") + assert (bounded.snapshot.scrolled_total, bounded.snapshot.evicted_total) == (50, 48) + assert bounded.snapshot.viewport(2).lines == ("H48", "H49", "V0", "V1") + + with pytest.raises(ValueError, match="history_lines"): + decode_tmux_capture(["V0"], history_lines=-1) + with pytest.raises(TypeError, match="history_lines"): + build_tmux_capture_command("%0", history_lines=True) # type: ignore[arg-type] + + # TmuxPaneSync: attach -> %layout-change V1/V2 -> %pause -> in-place resync. + sync = TmuxPaneSync("%1", tmux_version="3.8a", history_lines=5) + cmd1 = sync.begin_attach() + marker1 = cmd1.rsplit("'", 2)[1].encode("ascii") + cmd2 = sync.handle_event( + TmuxCommandBlock(timestamp=1, command_number=1, flags=1, lines=(marker1,)) + ) + assert cmd2 is not None and "-S -5" in cmd2 + nonce1 = cmd2.split(":PRE:", 1)[0].rsplit("'", 1)[1] + pre1 = ( + "8\t2\t3\t0\t1\t0\t4294967295\t4294967295\t0\t1\t" + "0\t0\t1\t0\t0\t0\t0\t0\t0\t\t\t0\t200\t0\t1\t" + "block\t1\t0\tVT10x\t/tmp\tt1" + ) + blocks1 = [ + [f"{nonce1}:PRE:{pre1}".encode()], + [f"{nonce1}:CAPTURE".encode()], + [b"- abc", b"- "], + [f"{nonce1}:SAVED".encode()], + [b""], + [f"{nonce1}:POST:{pre1}".encode()], + [], + [], + ] + for i, lines_b in enumerate(blocks1, start=2): + assert ( + sync.handle_event( + TmuxCommandBlock( + timestamp=1, + command_number=i, + flags=1, + lines=tuple(lines_b), + ) + ) + is None + ) + assert sync.phase == TmuxAttachPhase.LIVE + live_term = sync.terminal + assert live_term is not None + assert (live_term.rows, live_term.cols) == (2, 8) + + # V1 layout change (visible_layout zoomed to 20x5 while unzoomed layout is 10x2): + sync.handle_event( + TmuxLayoutChange( + window_id="@1", + layout="a1b2,20x5,0,0{9x5,0,0,0,10x5,10,0,1}", + visible_layout="c3d4,20x5,0,0,1", + raw_flags="*Z", + ) + ) + assert (live_term.rows, live_term.cols) == (5, 20) + + # V2 JSON layout change (tmux >= 3.8 new-layouts): + v2_layout = ( + '{"V":2,"L":{"t":"h","w":30,"h":6,"x":0,"y":0,"c":[' + '{"t":"p","w":14,"h":6,"x":0,"y":0,"i":0,"I":"%0"},' + '{"t":"p","w":15,"h":6,"x":15,"y":0,"a":true,"i":1,"I":"%1"}]}}' + ) + sync.handle_event( + TmuxLayoutChange(window_id="@1", layout=v2_layout, visible_layout=v2_layout) + ) + assert (live_term.rows, live_term.cols) == (6, 15) + + # Flow-control %pause -> %continue resyncs while preserving live_term identity: + tok_before = live_term.sync_token() + sync.handle_event(TmuxPause(pane_id="%1")) + assert sync.phase == TmuxAttachPhase.PAUSED + resync_cmd1 = sync.handle_event(TmuxContinue(pane_id="%1")) + assert resync_cmd1 is not None and sync.phase == TmuxAttachPhase.PAUSING + marker2 = resync_cmd1.rsplit("'", 2)[1].encode("ascii") + resync_cmd2 = sync.handle_event( + TmuxCommandBlock(timestamp=2, command_number=20, flags=1, lines=(marker2,)) + ) + assert resync_cmd2 is not None and sync.phase == TmuxAttachPhase.CAPTURING + nonce2 = resync_cmd2.split(":PRE:", 1)[0].rsplit("'", 1)[1] + pre2 = ( + "12\t3\t6\t0\t1\t0\t4294967295\t4294967295\t0\t2\t" + "0\t0\t1\t0\t0\t0\t0\t0\t0\t\t\t0\t200\t0\t9\t" + "underline\t0\t0\tVT10x\t/tmp\tt2" + ) + blocks2 = [ + [f"{nonce2}:PRE:{pre2}".encode()], + [f"{nonce2}:CAPTURE".encode()], + [b"- RESYNC", b"- ROW2", b"- "], + [f"{nonce2}:SAVED".encode()], + [b""], + [f"{nonce2}:POST:{pre2}".encode()], + [b"!"], + [], + ] + for i, lines_b in enumerate(blocks2, start=21): + sync.handle_event( + TmuxCommandBlock( + timestamp=2, + command_number=i, + flags=1, + lines=tuple(lines_b), + ) + ) + assert sync.phase == TmuxAttachPhase.LIVE + assert sync.terminal is live_term + assert sync.capture_result is not None and sync.capture_result.terminal is live_term + assert (live_term.rows, live_term.cols) == (3, 12) + assert live_term.lines == ("RESYNC!", "ROW2", "") + assert live_term.cursor.shape == CursorShape.UNDERLINE + delta = live_term.changes_since(tok_before) + assert delta.full_resync is True + assert delta.resync_reason == ResyncReason.EPOCH_CHANGED + + +@pytest.mark.integration +@pytest.mark.skipif(shutil.which("tmux") is None, reason="tmux binary not installed") +def test_live_tmux_capture_and_control_checkpoint_agreement() -> None: + """Live ``capture-pane`` and ``TmuxPaneSync`` agree across resize and resync.""" + from libvt.contrib.tmux import ( + TmuxAttachPhase, + TmuxControlParser, + TmuxPaneSync, + ) + + sock = f"libvt-test-{zlib.crc32(b'tmux-checkpoints')}" + proc: subprocess.Popen[bytes] | None = None + try: + ver_out = subprocess.run( + ["tmux", "-V"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + subprocess.run( + [ + "tmux", + "-L", + sock, + "-f", + "/dev/null", + "new-session", + "-d", + "-x", + "14", + "-y", + "3", + "sh", + "-c", + "printf 'H0\\r\\n\\033[32mCK1\\033[0m'; sleep 30", + ], + check=True, + ) + for _ in range(100): + chk = subprocess.run( + ["tmux", "-L", sock, "capture-pane", "-p"], + check=True, + capture_output=True, + text=True, + ) + if "CK1" in chk.stdout: + break + time.sleep(0.01) + else: + pytest.fail("timed out waiting for CK1") + + proc = subprocess.Popen( + ["tmux", "-L", sock, "-C", "attach-session"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + ) + assert proc.stdin is not None and proc.stdout is not None + cc_parser = TmuxControlParser() + sync = TmuxPaneSync("%0", tmux_version=ver_out) + proc.stdin.write(sync.begin_attach().encode("ascii") + b"\n") + proc.stdin.flush() + + def _pump_until(pred: object, timeout: float = 3.0) -> None: + assert ( + proc is not None and proc.stdin is not None and proc.stdout is not None + ) + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + line = proc.stdout.readline() + if not line: + break + for ev in cc_parser.feed(line): + nxt = sync.handle_event(ev) + if nxt is not None: + proc.stdin.write(nxt.encode("ascii") + b"\n") + proc.stdin.flush() + if callable(pred) and pred(): + return + pytest.fail("timed out waiting for tmux -C checkpoint") + + _pump_until(lambda: sync.phase == TmuxAttachPhase.LIVE) + assert sync.terminal is not None + orig_term = sync.terminal + + # Checkpoint 1: compare live-attached terminal against fresh capture bundle. + cap_cmd = build_tmux_capture_command("%0", tmux_version=ver_out) + cap1 = cap_cmd.parse( + subprocess.run( + ["tmux", "-L", sock, *cap_cmd.argv], + check=True, + capture_output=True, + text=True, + ).stdout + ) + assert sync.terminal.display_lines == cap1.snapshot.display_lines + assert sync.terminal.cursor.row == cap1.snapshot.cursor.row + assert sync.terminal.cursor.col == cap1.snapshot.cursor.col + + # Checkpoint 2: resize window via control client and resync in place. + proc.stdin.write(b"resize-window -t @0 -x 18 -y 4\n") + proc.stdin.flush() + _pump_until( + lambda: ( + sync.terminal is not None + and (sync.terminal.rows, sync.terminal.cols) == (4, 18) + ) + ) + + subprocess.run( + [ + "tmux", + "-L", + sock, + "run-shell", + "-t", + "%0", + "true", + ], + check=True, + ) + # Explicit resync preserves Terminal identity and zero passive query replies: + sync.terminal.feed(b"\x1b[6n\x1b[c") + assert sync.terminal.drain_replies() == b"" + proc.stdin.write(sync.resync().encode("ascii") + b"\n") + proc.stdin.flush() + _pump_until(lambda: sync.phase == TmuxAttachPhase.LIVE) + assert sync.terminal is orig_term + + cap2 = cap_cmd.parse( + subprocess.run( + ["tmux", "-L", sock, *cap_cmd.argv], + check=True, + capture_output=True, + text=True, + ).stdout + ) + assert sync.terminal.display_lines == cap2.snapshot.display_lines + assert (sync.terminal.rows, sync.terminal.cols) == ( + cap2.snapshot.rows, + cap2.snapshot.cols, + ) + assert sync.terminal.drain_replies() == b"" + finally: + if proc is not None: + proc.kill() + proc.wait() + subprocess.run( + ["tmux", "-L", sock, "kill-server"], + check=False, + capture_output=True, + )