diff --git a/CHANGES b/CHANGES index 1c52fbf..392ffdc 100644 --- a/CHANGES +++ b/CHANGES @@ -140,6 +140,19 @@ prof = Profile( ### What's new +#### `tmux` control-mode byte parser and sans-I/O pane sync (#27) + +{mod}`libvt.contrib.tmux.control` adds +{class}`~libvt.contrib.tmux.control.TmuxControlParser` (streaming raw-byte +framing for `tmux -C` / `-CC` `%begin`/`%end`/`%error` command blocks, +`%output` / `%extended-output` octal payloads without split-UTF-8 loss, +`%pause`/`%continue`, `%layout-change`, `%subscription-changed`, and `%exit` +into {type}`~libvt.contrib.tmux.control.TmuxControlEvent` records) and +{class}`~libvt.contrib.tmux.control.TmuxPaneSync` (sans-I/O two-phase +`refresh-client -A '%N:pause'` barrier + atomic `capture-pane` / +`capture-pane -P -p -C` / `refresh-client -A '%N:continue'` handoff into live +`%output` streaming). See {ref}`topics-sync-and-asyncio` for details. + #### Desktop notifications for `OSC 9`, Kitty `OSC 99`, and `OSC 777` (#31) {class}`~libvt.terminal.Terminal` parses iTerm2 `OSC 9` (filtering ConEmu diff --git a/docs/api/contrib_tmux.md b/docs/api/contrib_tmux.md index 0d494ab..4608af4 100644 --- a/docs/api/contrib_tmux.md +++ b/docs/api/contrib_tmux.md @@ -36,4 +36,11 @@ .. automodule:: libvt.contrib.tmux.control :members: :no-private-members: + :exclude-members: TmuxControlEvent + +.. py:type:: TmuxControlEvent + :module: libvt.contrib.tmux.control + :canonical: TmuxCommandBlock | TmuxOutput | TmuxExtendedOutput | TmuxPause | TmuxContinue | TmuxLayoutChange | TmuxSubscriptionChanged | TmuxExit | TmuxNotification + + Union of typed events emitted by :meth:`~libvt.contrib.tmux.control.TmuxControlParser.feed`. ``` diff --git a/docs/api/index.md b/docs/api/index.md index 4f78005..33e52b2 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -68,7 +68,8 @@ Mode-aware `KeyEvent`, `MouseEvent`, `PasteEvent`, and VT sequence `explain`. :::{grid-item-card} `libvt.contrib.tmux` :link: contrib_tmux :link-type: doc -Decoupled `tmux_profile`, `decode_tmux_capture`, and `-CC` unescaping submodules. +Decoupled `tmux_profile`, `decode_tmux_capture`, `TmuxControlParser`, and +`TmuxPaneSync` submodules. ::: :::: diff --git a/docs/project/public-api.md b/docs/project/public-api.md index 2b88fb2..90e2004 100644 --- a/docs/project/public-api.md +++ b/docs/project/public-api.md @@ -31,7 +31,7 @@ Import specialized types and helpers from their owning submodules: {class}`~libvt.aio.AsyncSession` transports, sequence disassembly, and screen assertions - {mod}`libvt.contrib.tmux` — decoupled `tmux` inner-pane profiles, - `capture-pane` decoders, and `-CC` control-mode unescaping + `capture-pane` decoders, and `-C` / `-CC` control-mode parser and pane sync ## What Is Internal diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index 3da8864..d470922 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -111,6 +111,27 @@ Leaving `async with` or calling master descriptor, closes it, and calls {meth}`~libvt.terminal.Terminal.notify_process_exit`. +## `tmux` control mode (`-C` / `-CC`) + +{class}`~libvt.contrib.tmux.control.TmuxControlParser` frames raw `tmux -C` / +`-CC` stdout bytes into typed +{type}`~libvt.contrib.tmux.control.TmuxControlEvent` records without decoding +split multi-byte UTF-8 pane output prematurely, and +{class}`~libvt.contrib.tmux.control.TmuxPaneSync` coordinates the sans-I/O +two-phase `refresh-client -A '%N:pause'` barrier and atomic `capture-pane` + +`capture-pane -P -p -C` + `refresh-client -A '%N:continue'` handoff into live +`%output` streaming: + +```python +>>> from libvt.contrib.tmux.control import TmuxAttachPhase, TmuxControlParser, TmuxPaneSync +>>> parser = TmuxControlParser() +>>> parser.feed(b"%output %0 hello\\015\\012\n") +[TmuxOutput(pane_id='%0', data=b'hello\r\n')] +>>> sync = TmuxPaneSync("%0") +>>> "refresh-client -A '%0:pause'" in sync.begin_attach(), sync.phase +(True, ) +``` + ## Concurrency and thread ownership Every method call and attribute read on a {class}`~libvt.terminal.Terminal` diff --git a/src/libvt/contrib/tmux/__init__.py b/src/libvt/contrib/tmux/__init__.py index 6f4b405..05b5ae7 100644 --- a/src/libvt/contrib/tmux/__init__.py +++ b/src/libvt/contrib/tmux/__init__.py @@ -18,7 +18,22 @@ decode_tmux_capture, parse_flagged_line, ) - from libvt.contrib.tmux.control import unescape_tmux_control_output + from libvt.contrib.tmux.control import ( + TmuxAttachPhase, + TmuxCommandBlock, + TmuxContinue, + TmuxControlEvent, + TmuxControlParser, + TmuxExit, + TmuxExtendedOutput, + TmuxLayoutChange, + TmuxNotification, + TmuxOutput, + TmuxPaneSync, + TmuxPause, + TmuxSubscriptionChanged, + unescape_tmux_control_output, + ) from libvt.contrib.tmux.profile import ( TMUX_CAPTURE_POLICY, TMUX_OBSERVER_POLICY, @@ -34,10 +49,26 @@ "TMUX_METADATA_FORMAT": ("libvt.contrib.tmux.capture", "TMUX_METADATA_FORMAT"), "TMUX_OBSERVER_POLICY": ("libvt.contrib.tmux.profile", "TMUX_OBSERVER_POLICY"), "TMUX_PROFILE": ("libvt.contrib.tmux.profile", "TMUX_PROFILE"), + "TmuxAttachPhase": ("libvt.contrib.tmux.control", "TmuxAttachPhase"), "TmuxCaptureCommand": ("libvt.contrib.tmux.capture", "TmuxCaptureCommand"), "TmuxCaptureResult": ("libvt.contrib.tmux.capture", "TmuxCaptureResult"), + "TmuxCommandBlock": ("libvt.contrib.tmux.control", "TmuxCommandBlock"), + "TmuxContinue": ("libvt.contrib.tmux.control", "TmuxContinue"), + "TmuxControlEvent": ("libvt.contrib.tmux.control", "TmuxControlEvent"), + "TmuxControlParser": ("libvt.contrib.tmux.control", "TmuxControlParser"), + "TmuxExit": ("libvt.contrib.tmux.control", "TmuxExit"), + "TmuxExtendedOutput": ("libvt.contrib.tmux.control", "TmuxExtendedOutput"), + "TmuxLayoutChange": ("libvt.contrib.tmux.control", "TmuxLayoutChange"), "TmuxLineFlags": ("libvt.contrib.tmux.capture", "TmuxLineFlags"), + "TmuxNotification": ("libvt.contrib.tmux.control", "TmuxNotification"), + "TmuxOutput": ("libvt.contrib.tmux.control", "TmuxOutput"), "TmuxPaneMetadata": ("libvt.contrib.tmux.capture", "TmuxPaneMetadata"), + "TmuxPaneSync": ("libvt.contrib.tmux.control", "TmuxPaneSync"), + "TmuxPause": ("libvt.contrib.tmux.control", "TmuxPause"), + "TmuxSubscriptionChanged": ( + "libvt.contrib.tmux.control", + "TmuxSubscriptionChanged", + ), "build_tmux_capture_command": ( "libvt.contrib.tmux.capture", "build_tmux_capture_command", @@ -59,10 +90,23 @@ "TMUX_PROFILE", "CaptureCompleteness", "CaptureInput", + "TmuxAttachPhase", "TmuxCaptureCommand", "TmuxCaptureResult", + "TmuxCommandBlock", + "TmuxContinue", + "TmuxControlEvent", + "TmuxControlParser", + "TmuxExit", + "TmuxExtendedOutput", + "TmuxLayoutChange", "TmuxLineFlags", + "TmuxNotification", + "TmuxOutput", "TmuxPaneMetadata", + "TmuxPaneSync", + "TmuxPause", + "TmuxSubscriptionChanged", "build_tmux_capture_command", "decode_tmux_capture", "parse_flagged_line", diff --git a/src/libvt/contrib/tmux/control.py b/src/libvt/contrib/tmux/control.py index e555e99..581562c 100644 --- a/src/libvt/contrib/tmux/control.py +++ b/src/libvt/contrib/tmux/control.py @@ -1,11 +1,31 @@ -r"""``tmux -CC`` control-mode byte-stream unescaping.""" +r"""``tmux -C`` / ``-CC`` byte-oriented control-mode parser and pane sync.""" from __future__ import annotations import collections.abc +import enum +import os import re +import typing as t +from dataclasses import dataclass + +if t.TYPE_CHECKING: + from libvt.config import Limits, Policy, Profile + from libvt.contrib.tmux.capture import TmuxCaptureResult + from libvt.terminal import Terminal _OCTAL_ESCAPE_RE = re.compile(rb"\\([0-3][0-7]{2})") +_PARTIAL_OCTAL_TAIL_RE = re.compile(rb"\\(?:[0-3][0-7]?)?\Z") +_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") + + +def _tmux_quote(arg: str) -> str: + """Single-quote *arg* for ``tmux`` ``cmd-parse.y`` (including ``%`` and ``:``).""" + if _SAFE_TMUX_ARG_RE.match(arg): + return arg + return "'" + arg.replace("'", r"'\''") + "'" def unescape_tmux_control_output(data: collections.abc.Buffer | str) -> bytes: @@ -40,13 +60,927 @@ def unescape_tmux_control_output(data: collections.abc.Buffer | str) -> bytes: raw = ( data.encode("utf-8", errors="surrogateescape") if isinstance(data, str) - else bytes(data) + else bytes(memoryview(data).cast("B")) ) if b"\\" not in raw: return raw return _OCTAL_ESCAPE_RE.sub(lambda m: bytes((int(m.group(1), 8),)), raw) +@dataclass(frozen=True, slots=True, kw_only=True) +class TmuxCommandBlock: + r"""Completed ``%begin`` .. ``%end`` / ``%error`` control-mode reply block. + + Attributes + ---------- + timestamp : int + Epoch timestamp field from ``%begin ``. + command_number : int + Monotonic ``tmux`` command queue item number. + flags : int + Guard flags (``1`` for commands issued by this control client). + lines : tuple[bytes, ...] + Raw output lines emitted inside the guard block (excluding ``\n``). + is_error : bool + ``True`` when closed by ``%error`` rather than ``%end``. + truncated : bool + ``True`` when ``max_line_bytes`` or ``max_block_bytes`` truncated output. + + References + ---------- + - `tmux/tmux control.c — control_write_guard (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxCommandBlock + >>> TmuxCommandBlock(timestamp=1, command_number=2, flags=1, lines=(b"ok",)).lines + (b'ok',) + """ + + timestamp: int + command_number: int + flags: int + lines: tuple[bytes, ...] + is_error: bool = False + truncated: bool = False + + +@dataclass(frozen=True, slots=True, kw_only=True) +class TmuxOutput: + r"""Unescaped ``%output % `` byte notification. + + Attributes + ---------- + pane_id : str + Pane identifier including leading ``%`` (e.g. ``"%0"``). + data : bytes + Octal-unescaped raw pane output bytes (preserving split UTF-8). + + References + ---------- + - `tmux/tmux control.c — control_append_data (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxOutput + >>> TmuxOutput(pane_id="%0", data=b"hi").pane_id + '%0' + """ + + pane_id: str + data: bytes + + +@dataclass(frozen=True, slots=True, kw_only=True) +class TmuxExtendedOutput: + r"""Unescaped ``%extended-output % : `` notification. + + Attributes + ---------- + pane_id : str + Pane identifier including leading ``%`` (e.g. ``"%0"``). + age_ms : int + Milliseconds buffered in ``tmux`` prior to delivery. + data : bytes + Octal-unescaped raw pane output bytes following ``" : "``. + + References + ---------- + - `tmux/tmux control.c — CLIENT_CONTROL_PAUSEAFTER (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxExtendedOutput + >>> TmuxExtendedOutput(pane_id="%1", age_ms=25, data=b"x").age_ms + 25 + """ + + pane_id: str + age_ms: int + data: bytes + + +@dataclass(frozen=True, slots=True, kw_only=True) +class TmuxPause: + """``%pause %`` flow-control notification. + + Attributes + ---------- + pane_id : str + Paused pane identifier (e.g. ``"%0"``). + + References + ---------- + - `tmux/tmux control.c — control_pause_pane (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxPause + >>> TmuxPause(pane_id="%0").pane_id + '%0' + """ + + pane_id: str + + +@dataclass(frozen=True, slots=True, kw_only=True) +class TmuxContinue: + """``%continue %`` flow-control notification. + + Attributes + ---------- + pane_id : str + Resumed pane identifier (e.g. ``"%0"``). + + References + ---------- + - `tmux/tmux control.c — control_continue_pane (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxContinue + >>> TmuxContinue(pane_id="%0").pane_id + '%0' + """ + + pane_id: str + + +@dataclass(frozen=True, slots=True, kw_only=True) +class TmuxLayoutChange: + """``%layout-change @ `` notification. + + Attributes + ---------- + window_id : str + Window identifier (e.g. ``"@1"``). + layout : str + Full window layout descriptor. + visible_layout : str + Visible window layout descriptor. + raw_flags : str + Raw window flag string (``""`` on older ``tmux`` formats). + + References + ---------- + - `tmux/tmux control-notify.c — control_notify_window_layout_changed (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxLayoutChange + >>> TmuxLayoutChange(window_id="@0", layout="a", visible_layout="a").window_id + '@0' + """ + + window_id: str + layout: str + visible_layout: str + raw_flags: str = "" + + +@dataclass(frozen=True, slots=True, kw_only=True) +class TmuxSubscriptionChanged: + """``%subscription-changed $ : ``. + + Attributes + ---------- + name : str + Subscription identifier registered via ``refresh-client -B``. + session_id : str + Session identifier (e.g. ``"$0"``). + window_id : str + Window identifier (e.g. ``"@1"`` or ``"-"``). + window_index : str + Window index string (or ``"-"``). + pane_id : str + Pane identifier (e.g. ``"%0"`` or ``"-"``). + value : str + Evaluated format string after ``" : "``. + + References + ---------- + - `tmux/tmux control.c — control_Initialized / subscriptions (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxSubscriptionChanged + >>> TmuxSubscriptionChanged( + ... name="s", session_id="$0", window_id="-", window_index="-", + ... pane_id="-", value="1", + ... ).value + '1' + """ + + name: str + session_id: str + window_id: str + window_index: str + pane_id: str + value: str + + +@dataclass(frozen=True, slots=True, kw_only=True) +class TmuxExit: + """``%exit [reason]`` control client termination notification. + + Attributes + ---------- + reason : str + Optional server exit or detach reason (``""`` when clean). + + References + ---------- + - `tmux/tmux client.c — %exit notification (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxExit + >>> TmuxExit(reason="detached").reason + 'detached' + """ + + reason: str = "" + + +@dataclass(frozen=True, slots=True, kw_only=True) +class TmuxNotification: + """Fallback ``% ...`` control-mode notification record. + + Attributes + ---------- + name : str + Notification tag without leading ``%`` (e.g. ``"sessions-changed"``). + args : bytes + Raw trailing bytes on the notification line. + + References + ---------- + - `tmux/tmux control-notify.c (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxNotification + >>> TmuxNotification(name="sessions-changed", args=b"").name + 'sessions-changed' + """ + + name: str + args: bytes = b"" + + +#: Union of typed events emitted by :meth:`TmuxControlParser.feed`. +type TmuxControlEvent = ( + TmuxCommandBlock + | TmuxOutput + | TmuxExtendedOutput + | TmuxPause + | TmuxContinue + | TmuxLayoutChange + | TmuxSubscriptionChanged + | TmuxExit + | TmuxNotification +) + + +class TmuxControlParser: + r"""Streaming sans-I/O byte parser for ``tmux -C`` / ``-CC`` stdout. + + Operates strictly on raw ``bytes`` so multi-byte UTF-8 sequences split + across consecutive ``%output`` or ``%extended-output`` lines reassemble + cleanly inside :class:`~libvt.terminal.Terminal` without ``U+FFFD`` loss, + and strips optional ``tmux -CC`` ``DCS 1000p`` (``ESC P 1000p`` .. ``ST``) + framing automatically. + + Parameters + ---------- + max_line_bytes : int, default 4_194_304 + Maximum bytes buffered for a single unterminated wire line. + max_block_bytes : int, default 33_554_432 + Maximum cumulative bytes retained inside an open ``%begin`` block. + + Raises + ------ + ValueError + If *max_line_bytes* or *max_block_bytes* is less than ``64``. + + References + ---------- + - `tmux/tmux control.c (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxControlParser + >>> p = TmuxControlParser() + >>> p.feed(b"%output %0 hi\\012\n") + [TmuxOutput(pane_id='%0', data=b'hi\n')] + """ + + __slots__ = ( + "_block_bytes", + "_block_truncated", + "_line_buf", + "_line_overflow", + "_max_block_bytes", + "_max_line_bytes", + "_open_block", + ) + + def __init__( + self, + *, + max_line_bytes: int = 4_194_304, + max_block_bytes: int = 33_554_432, + ) -> None: + if max_line_bytes < 64 or max_block_bytes < 64: + msg = "max_line_bytes and max_block_bytes must be >= 64" + raise ValueError(msg) + self._max_line_bytes = max_line_bytes + self._max_block_bytes = max_block_bytes + self._line_buf = bytearray() + self._line_overflow = False + self._open_block: tuple[int, int, int, list[bytes]] | None = None + self._block_bytes = 0 + self._block_truncated = False + + @property + def at_line_boundary(self) -> bool: + """Return ``True`` when no partial wire line or open block is buffered. + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxControlParser + >>> TmuxControlParser().at_line_boundary + True + """ + return not self._line_buf and self._open_block is None + + def feed(self, data: collections.abc.Buffer) -> list[TmuxControlEvent]: + r"""Feed raw ``tmux -C`` / ``-CC`` wire bytes and return parsed events. + + Parameters + ---------- + data : collections.abc.Buffer + Arbitrary byte chunk read from ``tmux`` stdout. + + Returns + ------- + list[TmuxControlEvent] + Completed command blocks and notifications parsed from *data*. + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxControlParser + >>> p = TmuxControlParser() + >>> p.feed(b"%exit\n") + [TmuxExit(reason='')] + """ + buf: bytes | bytearray = ( + data + if isinstance(data, (bytes, bytearray)) + else bytes(memoryview(data).cast("B")) + ) + events: list[TmuxControlEvent] = [] + pos = 0 + n = len(buf) + while pos < n: + nl = buf.find(b"\n", pos) + if nl == -1: + rem_len = n - pos + if not self._line_overflow: + if len(self._line_buf) + rem_len <= self._max_line_bytes: + self._line_buf.extend(buf[pos:]) + else: + take = max(0, self._max_line_bytes - len(self._line_buf)) + if take > 0: + self._line_buf.extend(buf[pos : pos + take]) + self._line_overflow = True + if ( + self._open_block is None + and not self._line_overflow + and self._line_buf == b"\x1b\\" + ): + self._line_buf.clear() + break + + if self._line_buf or self._line_overflow: + was_truncated = self._line_overflow + if not self._line_overflow: + seg_len = nl - pos + if len(self._line_buf) + seg_len <= self._max_line_bytes: + self._line_buf.extend(buf[pos:nl]) + else: + take = max(0, self._max_line_bytes - len(self._line_buf)) + if take > 0: + self._line_buf.extend(buf[pos : pos + take]) + was_truncated = True + raw_line = bytes(self._line_buf) + self._line_buf.clear() + self._line_overflow = False + else: + seg_len = nl - pos + if seg_len <= self._max_line_bytes: + raw_line = bytes(buf[pos:nl]) + was_truncated = False + else: + raw_line = bytes(buf[pos : pos + self._max_line_bytes]) + was_truncated = True + pos = nl + 1 + + if not was_truncated and raw_line.endswith(b"\r"): + raw_line = raw_line[:-1] + ev = self._process_line(raw_line, was_truncated=was_truncated) + if ev is not None: + events.append(ev) + return events + + @staticmethod + def _unescape_payload(payload: bytes, *, was_truncated: bool) -> bytes: + if was_truncated: + payload = _PARTIAL_OCTAL_TAIL_RE.sub(b"", payload) + return unescape_tmux_control_output(payload) + + def _process_line( + self, + line: bytes, + *, + was_truncated: bool, + ) -> TmuxControlEvent | None: + if self._open_block is None: + line = line.removeprefix(_DCS_CC_PREFIX) + if line == b"\x1b\\" or not line: + return None + if not was_truncated: + m = _GUARD_LINE_RE.match(line) + if m is not None and m.group(1) == b"begin": + ts = int(m.group(2)) + num = int(m.group(3)) + fl = int(m.group(4)) + self._open_block = (ts, num, fl, []) + self._block_bytes = 0 + self._block_truncated = False + return None + else: + open_ts, open_num, open_fl, body_lines = self._open_block + if not was_truncated: + m = _GUARD_LINE_RE.match(line) + if m is not None and m.group(1) in (b"end", b"error"): + ts = int(m.group(2)) + num = int(m.group(3)) + fl = int(m.group(4)) + if (ts, num, fl) == (open_ts, open_num, open_fl): + trunc = self._block_truncated + self._open_block = None + self._block_bytes = 0 + self._block_truncated = False + return TmuxCommandBlock( + timestamp=open_ts, + command_number=open_num, + flags=open_fl, + lines=tuple(body_lines), + is_error=(m.group(1) == b"error"), + truncated=trunc, + ) + if was_truncated: + self._block_truncated = True + if self._block_bytes + len(line) <= self._max_block_bytes: + body_lines.append(line) + self._block_bytes += len(line) + else: + self._block_truncated = True + return None + + if not line.startswith(b"%"): + return None + + if line.startswith(b"%output "): + rest = line[8:] + sp = rest.find(b" ") + if sp == -1: + return TmuxOutput( + pane_id=rest.decode("ascii", errors="replace"), + data=b"", + ) + pane_id = rest[:sp].decode("ascii", errors="replace") + return TmuxOutput( + pane_id=pane_id, + data=self._unescape_payload( + rest[sp + 1 :], + was_truncated=was_truncated, + ), + ) + + if line.startswith(b"%extended-output "): + rest = line[17:] + sep = rest.find(b" : ") + if sep != -1: + hdr = rest[:sep].split(b" ") + if len(hdr) >= 2: + pane_id = hdr[0].decode("ascii", errors="replace") + try: + age = int(hdr[1]) + except ValueError: + age = 0 + return TmuxExtendedOutput( + pane_id=pane_id, + age_ms=age, + data=self._unescape_payload( + rest[sep + 3 :], + was_truncated=was_truncated, + ), + ) + + if line.startswith(b"%pause "): + return TmuxPause(pane_id=line[7:].strip().decode("ascii", errors="replace")) + + if line.startswith(b"%continue "): + return TmuxContinue( + pane_id=line[10:].strip().decode("ascii", errors="replace"), + ) + + if line.startswith(b"%layout-change "): + parts = line[15:].decode("utf-8", errors="replace").split(" ", 3) + if len(parts) >= 3: + return TmuxLayoutChange( + window_id=parts[0], + layout=parts[1], + visible_layout=parts[2], + raw_flags=parts[3] if len(parts) == 4 else "", + ) + + if line.startswith(b"%subscription-changed "): + rest = line[22:] + sep = rest.find(b" : ") + if sep != -1: + hdr_s = rest[:sep].decode("utf-8", errors="replace").split(" ") + if len(hdr_s) >= 5: + return TmuxSubscriptionChanged( + name=hdr_s[0], + session_id=hdr_s[1], + window_id=hdr_s[2], + window_index=hdr_s[3], + pane_id=hdr_s[4], + value=rest[sep + 3 :].decode("utf-8", errors="replace"), + ) + + if line == b"%exit" or line.startswith(b"%exit "): + reason = ( + line[6:].rstrip(b"\x1b\\").decode("utf-8", errors="replace") + if len(line) > 5 + else "" + ) + return TmuxExit(reason=reason) + + sp = line.find(b" ") + if sp == -1: + return TmuxNotification(name=line[1:].decode("ascii", errors="replace")) + return TmuxNotification( + name=line[1:sp].decode("ascii", errors="replace"), + args=line[sp + 1 :], + ) + + +class TmuxAttachPhase(enum.StrEnum): + """Lifecycle phase of sans-I/O two-phase :class:`TmuxPaneSync`. + + References + ---------- + - `tmux/tmux cmd-refresh-client.c — -A pause / continue (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxAttachPhase + >>> TmuxAttachPhase.LIVE.value + 'live' + """ + + UNATTACHED = "unattached" + PAUSING = "pausing" + CAPTURING = "capturing" + LIVE = "live" + PAUSED = "paused" + FAILED = "failed" + + +class TmuxPaneSync: + r"""Sans-I/O two-phase ``tmux -C`` / ``-CC`` pane-attachment coordinator. + + Implements the non-pipelined pause barrier (``refresh-client -A '%N:pause'`` + followed by a nonce-tagged ``display-message`` ack) and a single atomic + ``capture-pane`` + ``capture-pane -P -p -C`` + ``refresh-client -A + '%N:continue'`` command batch so ``tmux`` executes capture and resume in one + ``cmdq_next`` turn without dropping live PTY bytes. + + Parameters + ---------- + pane_id : str + Target ``tmux`` pane identifier (e.g. ``"%0"``). + tmux_version : tuple[int, int] | str, default "3.8a" + Target ``tmux`` version string or ``(major, minor)`` tuple. + scrollback : int, default 2_000 + Scrollback capacity for the reconstructed :class:`~libvt.terminal.Terminal`. + profile : Profile | None, default None + Optional inner-pane profile (defaults to ``tmux_profile(tmux_version)``). + policy : Policy | None, default None + Optional security/reply policy (defaults to ``TMUX_OBSERVER_POLICY``). + limits : Limits | None, default None + Optional terminal resource limits. + + Attributes + ---------- + pane_id : str + Target pane identifier (``"%"``). + tmux_version : tuple[int, int] | str + Configured ``tmux`` version. + scrollback : int + Configured scrollback capacity in lines. + capture_result : TmuxCaptureResult | None + Completed baseline capture result once :attr:`phase` reaches ``LIVE``. + terminal : Terminal | None + Live synchronized :class:`~libvt.terminal.Terminal` once ``LIVE``. + + Raises + ------ + ValueError + If *pane_id* is not ``"%"`` or *tmux_version* is invalid. + + References + ---------- + - `tmux/tmux cmd-refresh-client.c — -A pause / continue (3.8) + `__ + - `tmux/tmux cmd-capture-pane.c — -P pending escape bytes (3.8) + `__ + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxAttachPhase, TmuxPaneSync + >>> sync = TmuxPaneSync("%0") + >>> "refresh-client -A '%0:pause'" in sync.begin_attach() + True + >>> sync.phase == TmuxAttachPhase.PAUSING + True + """ + + __slots__ = ( + "_capture_cmd_obj", + "_collected_blocks", + "_expected_blocks", + "_limits", + "_pause_marker", + "_phase", + "_policy", + "_profile", + "capture_result", + "pane_id", + "scrollback", + "terminal", + "tmux_version", + ) + + def __init__( + self, + pane_id: str, + *, + tmux_version: tuple[int, int] | str = "3.8a", + scrollback: int = 2_000, + profile: Profile | None = None, + policy: Policy | None = None, + limits: Limits | None = None, + ) -> None: + if ( + not pane_id.startswith("%") + or not pane_id[1:].isascii() + or not pane_id[1:].isdigit() + ): + msg = f"pane_id must be '%', got {pane_id!r}" + 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._profile = profile + self._policy = policy + self._limits = limits + self._phase = TmuxAttachPhase.UNATTACHED + self._pause_marker = b"" + self._expected_blocks = 0 + self._collected_blocks: list[TmuxCommandBlock] = [] + self._capture_cmd_obj: object = None + self.capture_result: TmuxCaptureResult | None = None + self.terminal: Terminal | None = None + + @property + def phase(self) -> TmuxAttachPhase: + """Return current :class:`TmuxAttachPhase`. + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxPaneSync + >>> TmuxPaneSync("%0").phase.value + 'unattached' + """ + return self._phase + + def begin_attach(self) -> str: + r"""Start Phase 1 pause barrier and return the ``tmux -C`` command line. + + Returns + ------- + str + ``;``-chained ``refresh-client -A '%N:pause'`` + nonce barrier line + to write (followed by ``\n``) to the control client's stdin. + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxPaneSync + >>> TmuxPaneSync("%2").begin_attach().startswith("refresh-client -A '%2:pause'") + True + """ + marker = f"__LIBVT_PAUSED_{os.urandom(6).hex()}__" + self._pause_marker = marker.encode("ascii") + self._phase = TmuxAttachPhase.PAUSING + self._expected_blocks = 0 + self._collected_blocks.clear() + return ( + f"refresh-client -A '{self.pane_id}:pause' ; " + f"display-message -p -t '{self.pane_id}' '{marker}'" + ) + + 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, + ) + self._capture_cmd_obj = cap_cmd + subcmds: list[list[str]] = [[]] + for tok in cap_cmd.argv: + if tok == ";": + subcmds.append([]) + else: + subcmds[-1].append(tok) + subcmds = [s for s in subcmds if s] + subcmds.append(["capture-pane", "-P", "-p", "-C", "-t", self.pane_id]) + subcmds.append(["refresh-client", "-A", f"{self.pane_id}:continue"]) + self._expected_blocks = len(subcmds) + self._collected_blocks.clear() + return " ; ".join(" ".join(_tmux_quote(arg) for arg in sub) for sub in subcmds) + + def handle_event(self, event: TmuxControlEvent) -> str | None: + """Advance attachment state on *event*; return next command or ``None``. + + Parameters + ---------- + event : TmuxControlEvent + Parsed event from :meth:`TmuxControlParser.feed`. + + Returns + ------- + str | None + Next ``tmux`` command batch to send on stdin, or ``None``. + + Raises + ------ + libvt.exc.ProtocolError + If ``tmux`` returns ``%error`` or a truncated capture block during + attachment (setting :attr:`phase` to ``TmuxAttachPhase.FAILED``). + + Examples + -------- + >>> from libvt.contrib.tmux.control import TmuxCommandBlock, TmuxPaneSync + >>> sync = TmuxPaneSync("%0") + >>> cmd1 = sync.begin_attach() + >>> marker = cmd1.rsplit("'", 2)[1].encode("ascii") + >>> cmd2 = sync.handle_event( + ... TmuxCommandBlock( + ... timestamp=1, command_number=2, flags=1, lines=(marker,) + ... ) + ... ) + >>> "capture-pane" in (cmd2 or "") and ":continue" in (cmd2 or "") + True + """ + if isinstance(event, (TmuxOutput, TmuxExtendedOutput)): + if ( + event.pane_id == self.pane_id + and self._phase == TmuxAttachPhase.LIVE + and self.terminal is not None + ): + self.terminal.feed(event.data) + return None + + if isinstance(event, TmuxPause): + if event.pane_id == self.pane_id and self._phase == TmuxAttachPhase.LIVE: + self._phase = TmuxAttachPhase.PAUSED + return None + + if isinstance(event, TmuxContinue): + if event.pane_id == self.pane_id and self._phase == TmuxAttachPhase.PAUSED: + self._phase = TmuxAttachPhase.LIVE + return None + + if not isinstance(event, TmuxCommandBlock) or event.flags != 1: + return None + + if self._phase == TmuxAttachPhase.PAUSING: + if event.is_error: + from libvt.exc import ProtocolError + + self._phase = TmuxAttachPhase.FAILED + err_txt = b"\n".join(event.lines).decode("utf-8", errors="replace") + msg = f"tmux pause failed for {self.pane_id}: {err_txt}" + raise ProtocolError(msg) + if event.lines != (self._pause_marker,): + return None + self._phase = TmuxAttachPhase.CAPTURING + return self._build_capture_batch() + + if self._phase == TmuxAttachPhase.CAPTURING: + from libvt.config import DEFAULT_LIMITS + from libvt.contrib.tmux.capture import TmuxCaptureCommand + from libvt.contrib.tmux.profile import TMUX_OBSERVER_POLICY, tmux_profile + from libvt.exc import ProtocolError + + cap_cmd = t.cast("TmuxCaptureCommand", self._capture_cmd_obj) + if not self._collected_blocks: + if event.is_error: + self._phase = TmuxAttachPhase.FAILED + err_txt = b"\n".join(event.lines).decode("utf-8", errors="replace") + msg = f"tmux capture failed for {self.pane_id}: {err_txt}" + raise ProtocolError(msg) + pre_prefix = f"{cap_cmd.nonce}:PRE:".encode("ascii") + if not event.lines or not event.lines[0].startswith(pre_prefix): + return None + if event.is_error or event.truncated: + self._phase = TmuxAttachPhase.FAILED + err_txt = b"\n".join(event.lines).decode("utf-8", errors="replace") + msg = f"tmux capture incomplete/error for {self.pane_id}: {err_txt}" + raise ProtocolError(msg) + + self._collected_blocks.append(event) + if len(self._collected_blocks) < self._expected_blocks: + return None + + cap_blocks = self._collected_blocks[:-2] + pend_block = self._collected_blocks[-2] + combined_lines = [ + ln.decode("utf-8", errors="surrogateescape") + for blk in cap_blocks + for ln in blk.lines + ] + eff_profile = ( + tmux_profile(self.tmux_version) + if self._profile is None + else self._profile + ) + eff_policy = TMUX_OBSERVER_POLICY if self._policy is None else self._policy + eff_limits = DEFAULT_LIMITS if self._limits is None else self._limits + res = cap_cmd.parse( + combined_lines, + scrollback=self.scrollback, + profile=eff_profile, + policy=eff_policy, + limits=eff_limits, + ) + if pend_block.lines: + pending_raw = unescape_tmux_control_output(b"".join(pend_block.lines)) + if pending_raw: + res.terminal.feed(pending_raw) + self.capture_result = res + self.terminal = res.terminal + self._collected_blocks.clear() + self._expected_blocks = 0 + self._phase = TmuxAttachPhase.LIVE + return None + + return None + + __all__ = [ + "TmuxAttachPhase", + "TmuxCommandBlock", + "TmuxContinue", + "TmuxControlEvent", + "TmuxControlParser", + "TmuxExit", + "TmuxExtendedOutput", + "TmuxLayoutChange", + "TmuxNotification", + "TmuxOutput", + "TmuxPaneSync", + "TmuxPause", + "TmuxSubscriptionChanged", "unescape_tmux_control_output", ] diff --git a/tests/test_libvt.py b/tests/test_libvt.py index e5bed4a..06a5606 100644 --- a/tests/test_libvt.py +++ b/tests/test_libvt.py @@ -201,6 +201,20 @@ def test_contrib_tmux_decoupling_and_core_isolation() -> None: ) assert proc.returncode == 0, proc.stderr + import libvt.contrib.tmux as tmux_pkg + + assert tmux_pkg.__file__ is not None + tm_tree = ast.parse(pathlib.Path(tmux_pkg.__file__).read_text(encoding="utf-8")) + tm_tc: dict[str, tuple[str, str]] = {} + for node in tm_tree.body: + if isinstance(node, ast.If): + for stmt in node.body: + if isinstance(stmt, ast.ImportFrom) and stmt.module is not None: + for alias in stmt.names: + tm_tc[alias.asname or alias.name] = (stmt.module, alias.name) + assert tm_tc == tmux_pkg._LAZY_EXPORTS + assert set(tm_tc) == set(tmux_pkg.__all__) + def test_cross_platform_classifiers_and_ci_workflows() -> None: """Dist metadata, ``pyproject.toml``, and CI declare Linux, macOS, and Windows.""" diff --git a/tests/test_tmux.py b/tests/test_tmux.py index 4f18df7..db64557 100644 --- a/tests/test_tmux.py +++ b/tests/test_tmux.py @@ -586,3 +586,181 @@ def test_live_tmux_chained_bundle_overline_wraps_and_alt_screen() -> None: check=False, capture_output=True, ) + + +def test_tmux_control_parser_split_utf8_extended_output_and_live_sync() -> None: + """``TmuxControlParser`` preserves split UTF-8 and ``TmuxPaneSync`` attaches.""" + from libvt.contrib.tmux import ( + TmuxAttachPhase, + TmuxCommandBlock, + TmuxContinue, + TmuxControlParser, + TmuxExit, + TmuxExtendedOutput, + TmuxLayoutChange, + TmuxOutput, + TmuxPaneSync, + TmuxPause, + TmuxSubscriptionChanged, + ) + + parser = TmuxControlParser() + wire = ( + b"\x1bP1000p%begin 1700 1 1\n" + b"hello\n" + b"%begin 999 999 0\n" + b"%end 999 999 0\n" + b"%end 1700 1 1\n" + b"%output %0 A\xe4\xb8\n" + b"%extended-output %0 42 : \xad\\033[32m!\033[0m\n" + b"%pause %0\n" + b"%continue %0\n" + b"%layout-change @1 bb62,80x24,0,0,0 bb62,80x24,0,0,0 *\n" + b"%subscription-changed sub1 $0 @1 0 %0 : val : 2\n" + b"%exit server exited\n\x1b\\" + ) + events = [] + for i in range(len(wire)): + events.extend(parser.feed(wire[i : i + 1])) + assert parser.at_line_boundary is True + + blk = events[0] + assert isinstance(blk, TmuxCommandBlock) + assert blk.is_error is False and blk.truncated is False + assert blk.lines == (b"hello", b"%begin 999 999 0", b"%end 999 999 0") + + out1, out2 = events[1], events[2] + assert isinstance(out1, TmuxOutput) and out1.pane_id == "%0" + assert isinstance(out2, TmuxExtendedOutput) and out2.age_ms == 42 + term = libvt.Terminal(rows=2, cols=10) + term.feed(out1.data) + term.feed(out2.data) + assert term[0].text == "A中!" + assert term[0, 3].style.fg == AnsiColor.GREEN + + assert isinstance(events[3], TmuxPause) and events[3].pane_id == "%0" + assert isinstance(events[4], TmuxContinue) and events[4].pane_id == "%0" + assert isinstance(events[5], TmuxLayoutChange) and events[5].window_id == "@1" + assert ( + isinstance(events[6], TmuxSubscriptionChanged) + and events[6].name == "sub1" + and events[6].value == "val : 2" + ) + assert isinstance(events[7], TmuxExit) and events[7].reason == "server exited" + + # Non-byte Buffer (array('H')) and truncated partial octal tail safety: + import array + + from libvt.exc import ProtocolError + + small_p = TmuxControlParser(max_line_bytes=64, max_block_bytes=64) + u16_buf = array.array("H") + u16_buf.frombytes(b"%exit ok!\n") + assert small_p.feed(memoryview(u16_buf))[0] == TmuxExit(reason="ok!") + trunc_line = b"%output %0 " + (b"x" * 51) + b"\\033\n" + trunc_ev = small_p.feed(trunc_line)[0] + assert isinstance(trunc_ev, TmuxOutput) and trunc_ev.data == (b"x" * 51) + + # TmuxPaneSync rejects non-ASCII pane digits and raises ProtocolError on %error: + with pytest.raises(ValueError, match="ascii_digits"): + TmuxPaneSync("%\u0660") + err_sync = TmuxPaneSync("%99") + _ = err_sync.begin_attach() + with pytest.raises(ProtocolError, match="%99"): + err_sync.handle_event( + TmuxCommandBlock( + timestamp=1, + command_number=1, + flags=1, + lines=(b"can't find pane: %99",), + is_error=True, + ), + ) + assert err_sync.phase == TmuxAttachPhase.FAILED + + +@pytest.mark.integration +def test_tmux_control_live_pane_sync_with_pending_escape() -> None: + """Live ``tmux -C`` attachment captures in-flight escape bytes without a gap.""" + if shutil.which("tmux") is None: + pytest.skip("tmux is not installed") + + from libvt.contrib.tmux import ( + TmuxAttachPhase, + TmuxControlParser, + TmuxPaneSync, + ) + + sock = f"libvt-test-{zlib.crc32(b'tmux-cc-sync')}" + 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", + "12", + "-y", + "3", + "sh", + "-c", + "printf 'PRE\\033[31'; sleep 0.25; printf 'mPOST'; sleep 30", + ], + check=True, + ) + time.sleep(0.08) + 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) + # Send begin_attach() immediately; greeting %begin/%end is ignored via nonce: + cmd1 = sync.begin_attach() + assert sync.phase == TmuxAttachPhase.PAUSING + proc.stdin.write(cmd1.encode("ascii") + b"\n") + proc.stdin.flush() + + deadline = time.monotonic() + 3.0 + 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 ( + sync.phase == TmuxAttachPhase.LIVE + and sync.terminal is not None + and "PREPOST" in sync.terminal.text + ): + break + assert sync.phase == TmuxAttachPhase.LIVE + assert sync.terminal is not None + assert sync.terminal[0].text == "PREPOST" + assert sync.terminal[0, 3].style.fg == AnsiColor.RED + 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, + )