Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ $ uvx --from 'libtmux' --prerelease allow python
_Notes on the upcoming release will go here._
<!-- END PLACEHOLDER - ADD NEW CHANGELOG ENTRIES BELOW THIS LINE -->

### What's new

#### Retained pane observations (#810)

Retain immutable pane text and capture details with
{meth}`PaneObservation.capture() <libtmux.PaneObservation.capture>`, even after
the pane changes or disappears. These sampled values remain readable without
another tmux query.

### Documentation

#### Cleaner `from_env` examples (#719)
Expand All @@ -59,6 +68,10 @@ it.

### Development

#### Ruff 0.17.3 for development (#810)

Minimum `ruff>=0.17.3` (was `>=0.17.1`) for development and CI lint checks.

#### CI recovers from incompatible tmux caches (#835)

CI rebuilds incompatible cached tmux installations before running tests.
Expand Down
1 change: 1 addition & 0 deletions docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ Window <libtmux.window>
Pane <libtmux.pane>
Client <libtmux.client>
Common <libtmux.common>
Retained observations <libtmux.observation>
Neo <libtmux.neo>
Options <libtmux.options>
Hooks <libtmux.hooks>
Expand Down
49 changes: 49 additions & 0 deletions docs/api/libtmux.observation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Retained pane observations

{meth}`PaneObservation.capture() <libtmux.PaneObservation.capture>` keeps
decoded pane text and its capture command in a frozen value. Read it after
redraw or pane removal without querying tmux again. The pane and server remain
borrowed.

```python
>>> from libtmux import PaneObservation
>>> observed = PaneObservation.capture(pane)
>>> observed.pane_id == pane.pane_id
True
>>> isinstance(observed.lines, tuple)
True
>>> observed.text == "\n".join(observed.lines)
True
>>> observed.target_lifetime_verified is None
True
```

Use `start`, `end`, and `join_wrapped` to select text with tmux's ordinary
capture semantics. The result retains the selection, actual command argv, and
the controller's monotonic capture interval in nanoseconds. Text uses the
existing command decoder and trailing-empty-line policy. It contains no raw
byte or terminal-column positions.

`max_text_codepoints` bounds admitted decoded text, including LF between lines.
It counts Python Unicode code points. Oversized text raises `ValueError`;
tmux failures raise instead of becoming successful empty observations. The
limit applies after the existing transport returns, so it does not bound
transport memory. The call keeps the selected backend's blocking behavior.

The legacy pane ID cannot prove which daemon or pane lifetime supplied a
capture after replacement; `target_lifetime_verified` remains unknown. The
interval describes one sampled command, without an atomic metadata/content
checkpoint. Retained text remains readable after observer or server loss while
you retain the value. Process exit loses the in-memory value. No serializer or
persistent record is supplied.

A later capture can recover then-visible text, not omitted output, erased
history, or hidden terminal state. Visible text and echoed commands do not
prove application completion. A cooperating producer can signal an
application-defined milestone; the signal proves only that milestone.

```{eval-rst}
.. autoclass:: libtmux.PaneObservation
:members:
:member-order: bysource
```
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ dev = [
"coverage",
"pytest-cov",
# Lint
"ruff>=0.17.1",
"ruff>=0.17.3",
"mypy",
]

Expand All @@ -95,7 +95,7 @@ coverage =[
]
lint = [
"typing-extensions; python_version < '3.11'",
"ruff>=0.17.1",
"ruff>=0.17.3",
"mypy",
]

Expand Down
2 changes: 2 additions & 0 deletions src/libtmux/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
__version__,
)
from .client import Client
from .observation import PaneObservation
from .pane import Pane
from .server import Server
from .session import Session
Expand All @@ -25,6 +26,7 @@
__all__ = (
"Client",
"Pane",
"PaneObservation",
"Server",
"Session",
"Window",
Expand Down
150 changes: 150 additions & 0 deletions src/libtmux/observation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
"""Immutable sampled pane text and capture provenance."""

from __future__ import annotations

import time
import typing as t
from dataclasses import dataclass, field

from libtmux import exc
from libtmux.common import raise_if_stderr

if t.TYPE_CHECKING:
from libtmux.pane import Pane


@dataclass(frozen=True, slots=True)
class PaneObservation:
"""Retain decoded capture text without a live pane or server reference.

``lines`` and ``command`` are owned tuples. The interval counts controller
monotonic nanoseconds around one command; it is not a server timestamp.
``pane_id`` records the requested target. Its daemon/object lifetime remains
unknown with the legacy pane handle, so ``target_lifetime_verified`` is None.

Attributes
----------
pane_id : str
Requested tmux pane ID.
lines : tuple[str, ...]
Owned decoded text, preserving the command's trailing-empty-line policy.
command : tuple[str, ...]
Actual command argv reported by the selected backend.
start, end : int | "-" | None
Requested capture range; None leaves that endpoint at tmux's default.
join_wrapped : bool
Whether the capture requested joined physical lines with ``-J``.
started_ns, finished_ns : int
Controller monotonic nanoseconds immediately before and after the command.
target_lifetime_verified : bool | None
None: the legacy pane handle supplies no daemon or pane lifetime proof.
"""

pane_id: str
lines: tuple[str, ...] = field(repr=False)
command: tuple[str, ...] = field(repr=False)
start: t.Literal["-"] | int | None
end: t.Literal["-"] | int | None
join_wrapped: bool
started_ns: int
finished_ns: int
target_lifetime_verified: bool | None = field(default=None, init=False)

@property
def text(self) -> str:
"""Return retained lines joined with LF, without terminal-column semantics."""
return "\n".join(self.lines)

@classmethod
def capture(
cls,
pane: Pane,
*,
start: t.Literal["-"] | int | None = None,
end: t.Literal["-"] | int | None = None,
join_wrapped: bool = False,
max_text_codepoints: int = 1_048_576,
) -> PaneObservation:
"""Capture once through the supplied pane's command route.

The call retains plain decoded text using the existing command's
trailing-empty-line policy. The text limit includes LF between lines
and counts Python Unicode code points. It applies after transport
decoding; it is not a transport memory cap or command deadline.

Parameters
----------
pane : Pane
Borrowed pane providing the backend and target. No cleanup is acquired.
start, end : int | "-" | None
Requested tmux line range, using ordinary capture-pane semantics.
join_wrapped : bool
Join wrapped physical lines using tmux's capture policy.
max_text_codepoints : int
Positive admission limit for retained decoded text, including LF.

Raises
------
ValueError
Invalid selection, absent pane ID, or text exceeding the limit.
TypeError
``join_wrapped`` is not a bool.
libtmux.exc.LibTmuxException
The capture command reports stderr or a nonzero/unknown exit status.

Notes
-----
Backend exceptions propagate unchanged. Blocking defaults remain those
of ``pane.cmd``; this method adds no cancellation operation. A retained
value survives pane removal while referenced, but supplies no continuity,
durable storage, hidden terminal state, or application-completion proof.
"""
if (
isinstance(max_text_codepoints, bool)
or not isinstance(max_text_codepoints, int)
or max_text_codepoints <= 0
):
msg = "max_text_codepoints must be a positive integer"
raise ValueError(msg)
for name, value in (("start", start), ("end", end)):
if value is not None and (
isinstance(value, bool) or not (isinstance(value, int) or value == "-")
):
msg = f"{name} must be an integer, '-' or None"
raise ValueError(msg)
if not isinstance(join_wrapped, bool):
msg = "join_wrapped must be a bool"
raise TypeError(msg)
pane_id = pane.pane_id
if not pane_id:
msg = "Pane must have a pane_id to capture"
raise ValueError(msg)
args = ["-p"]
if start is not None:
args.extend(("-S", str(start)))
if end is not None:
args.extend(("-E", str(end)))
if join_wrapped:
args.append("-J")
started_ns = time.monotonic_ns()
result = pane.cmd("capture-pane", *args, target=pane_id)
finished_ns = time.monotonic_ns()
raise_if_stderr(result, "capture-pane")
if result.returncode != 0:
msg = f"command exited with status {result.returncode}"
raise exc.LibTmuxException(msg, subcommand="capture-pane")
lines = tuple(result.stdout)
text_size = sum(map(len, lines)) + max(0, len(lines) - 1)
if text_size > max_text_codepoints:
msg = "captured text exceeds max_text_codepoints"
raise ValueError(msg)
return cls(
pane_id=pane_id,
lines=lines,
command=tuple(result.cmd),
start=start,
end=end,
join_wrapped=join_wrapped,
started_ns=started_ns,
finished_ns=finished_ns,
)
Loading
Loading