diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 38ece9aadd..9f3fcbaa18 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -113,6 +113,34 @@ jobs: with: token: ${{ secrets.CODECOV_TOKEN }} + unsupported-tmux: + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository + runs-on: ubuntu-latest + env: + UV_EXCLUDE_NEWER: P3D + strategy: + matrix: + tmux-version: ['3.2a', '3.3'] + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10.2.0 + - run: uv python install 3.14 + - run: uv sync --locked --all-extras --dev + - name: Build unsupported tmux + run: | + sudo apt-get update + sudo apt-get install -y tmux libevent-dev libncurses-dev bison + git clone --depth 1 --branch '${{ matrix.tmux-version }}' https://github.com/tmux/tmux.git "$RUNNER_TEMP/old-tmux" + cd "$RUNNER_TEMP/old-tmux" + sh autogen.sh + ./configure --prefix="$RUNNER_TEMP/old-tmux-install" + make -j2 + make install + - name: Refuse before imports and callbacks + env: + TMUXP_TEST_OLD_TMUX: ${{ runner.temp }}/old-tmux-install/bin/tmux + run: uv run --locked pytest tests/test_tmux_versions.py -k unsupported --reruns=0 + release: runs-on: ubuntu-latest needs: build diff --git a/CHANGES b/CHANGES index f75552fdda..0d1b3f85f9 100644 --- a/CHANGES +++ b/CHANGES @@ -50,6 +50,35 @@ raised `KeyError(0)` in the IPython parser. CI now checks the CLI, documentation extensions, tests and build helpers with ty. ([#1120](https://github.com/tmux-python/tmuxp/pull/1120)) +### Breaking changes + +#### The tmux 3.3a minimum is checked against the server (#1092) + +Loading, freezing, and `tmuxp shell` now check the selected tmux daemon (or +cold executable when no server is running) for `tmux>=3.3a`, including its +patch letter, before workspace imports, plugins, callbacks, or scripts. A newer +`tmux` client executable no longer authorizes an older running daemon. + +Save your sessions before restarting an older daemon, or target a fresh socket: + +```console +$ tmuxp load -L new-socket workspace.yaml +``` + +Help, version information, diagnostics, workspace listing, and workspace +conversion remain available without tmux. See {doc}`project/compatibility` for +installation requirements. + +### Dependencies + +#### Coordinated `libtmux` 0.71 version check (#1092) + +Requires libtmux 0.71 or newer, whose version check covers the connected daemon +before every command (`uv.lock` pins the development revision while +`pyproject.toml` stays on `libtmux~=0.70.0` until libtmux 0.71.0 is released). +tmuxp checks a daemon once per workspace build, and a libtmux without that +module is refused before custom code runs. + ## tmuxp 1.84.0 (2026-11-28) tmuxp 1.84.0 updates libtmux to 0.70.0. `tmuxp shell` no longer writes diff --git a/MIGRATION b/MIGRATION index 0d31b4e377..103d1e828d 100644 --- a/MIGRATION +++ b/MIGRATION @@ -25,6 +25,17 @@ _Notes on the upcoming release will be added here_ +### tmux 3.3a minimum + +Upgrade tmux to 3.3a or newer before loading or freezing workspaces or opening +`tmuxp shell`. The minimum includes its patch letter. Save your sessions +before restarting an older daemon; updating the client alone does not +upgrade a running server. + +This release requires libtmux 0.71 or newer. Until libtmux 0.71 is released, +install a checkout with `uv sync --locked`. +Help, diagnostics, and configuration conversion do not require tmux. + ## tmuxp 1.18.0 (2022-10-30) **Restructuring** (#840) diff --git a/README.md b/README.md index 4260d6c627..bf27ee3bc6 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,9 @@ Session manager for tmux. Save and load your tmux sessions through declarative workspace files. Powered by [libtmux](https://github.com/tmux-python/libtmux). +Requires tmux **3.3a or newer** and Python **3.11 or newer**. The selected +daemon must meet the minimum even when a newer tmux client is installed. + [![Python Package](https://img.shields.io/pypi/v/tmuxp.svg)](https://pypi.org/project/tmuxp/) [![Docs](https://github.com/tmux-python/tmuxp/workflows/docs/badge.svg)](https://tmuxp.git-pull.com/) [![Build status](https://github.com/tmux-python/tmuxp/workflows/tests/badge.svg)](https://github.com/tmux-python/tmuxp/actions?query=workflow%3A%22tests%22) diff --git a/docs/cli/debug-info.md b/docs/cli/debug-info.md index bd3d76c6cc..54203e87bb 100644 --- a/docs/cli/debug-info.md +++ b/docs/cli/debug-info.md @@ -4,7 +4,13 @@ # tmuxp debug-info -Collect and display system information useful for debugging tmuxp issues and submitting bug reports. +Collect and display system information useful for debugging tmuxp issues and +submitting bug reports. The command remains available when tmux is missing +or the selected daemon is below the minimum. It does not start a server. + +JSON output keeps unavailable state lists empty and records the reason in +`tmux_errors`, keyed by the failed query. `tmux_version` describes the +executable, while version errors in `tmux_errors` describe the daemon. ## Command diff --git a/docs/project/compatibility.md b/docs/project/compatibility.md new file mode 100644 index 0000000000..7f8a178e91 --- /dev/null +++ b/docs/project/compatibility.md @@ -0,0 +1,50 @@ +# tmux compatibility + +tmuxp requires tmux 3.3a or newer. The patch letter matters: tmux 3.3 is below +the minimum. Ordinary workspace creation, pane splitting, input, capture, +layout, and freezing remain available on tmux 3.3a. + +The selected daemon determines compatibility when a socket is already +running. A cold socket uses the selected executable's version. Installing a +new executable does not upgrade an existing daemon. Save your sessions +before restarting an older daemon, or use a new socket name. + +Workspace loading checks the selected endpoint before importing a custom +builder or plugin. The classic builder checks a supplied session or window's +server before callbacks and scripts. `tmuxp shell` checks before executing +`-c`, importing a shell, or loading `PYTHONSTARTUP`. Later native operations +carry libtmux's command version check. They refuse a replacement daemon whose +version differs from the version checked for that command. + +`--help`, `--version`, `debug-info`, and workspace conversion remain available +without a running server or an installed tmux executable. + +## Installing this checkout + +This branch requires libtmux 0.71 or newer, the first release that carries +the daemon version check. Until that release exists, `uv.lock` pins an exact +development revision while `pyproject.toml` stays on `libtmux~=0.70.0`. +Install the checkout with its lockfile: + +```console +$ uv sync --locked +``` + +A plain package install does not apply uv's source selection and picks the +released libtmux. If the installed libtmux lacks the version check, tmuxp +refuses to load, freeze, or open a shell. Release libtmux 0.71 first, then +bump `pyproject.toml` to `libtmux~=0.71.0`, drop the source pin, and merge +this change. + +## Workspace scripts and custom code + +tmuxp sends `shell_command` text to a pane's shell. That shell executes the +operator's code. `before_script` runs a separate program, and plugins and +custom builders execute Python code. The compatibility check does not parse +or constrain those programs, their own tmux clients, or commands embedded +inside scripts. Redefining libtmux's built-in tmux commands through +`command-alias` also falls outside the managed command guarantee. + +Readiness polling and configured `sleep_before`/`sleep_after` values remain +part of workspace behavior. Raising the minimum does not make shell startup +or asynchronous terminal output immediate. diff --git a/docs/project/index.md b/docs/project/index.md index 1b796a36b2..927bd0538c 100644 --- a/docs/project/index.md +++ b/docs/project/index.md @@ -34,5 +34,6 @@ Release checklist and version policy. contributing code-style +compatibility releasing ``` diff --git a/docs/quickstart.md b/docs/quickstart.md index 8d1f418595..35820d05c0 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -9,7 +9,7 @@ takes you from nothing to a running session. ## Installation -Ensure you have at least tmux **>= 3.3a** and python **>= 3.11**. +Ensure you have at least tmux **>= 3.3a** and Python **>= 3.11**. ```console $ pip install --user tmuxp diff --git a/docs/topics/troubleshooting.md b/docs/topics/troubleshooting.md index ff90549d4d..df20f940f2 100644 --- a/docs/topics/troubleshooting.md +++ b/docs/topics/troubleshooting.md @@ -19,7 +19,10 @@ Ensure tmux is installed: $ tmux -V ``` -Minimum required version: tmux 3.3a. +Minimum required version: tmux 3.3a, including the patch letter. A running +daemon keeps its old version after you upgrade the tmux executable. Save +your work and restart that daemon, or select a new socket with `tmuxp load +-L new-socket workspace.yaml`. See {doc}`../project/compatibility`. ## Configuration errors diff --git a/pyproject.toml b/pyproject.toml index 800f245a6f..e7c56b5af8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -130,6 +130,9 @@ exclude = [ "src/tmuxp/CLAUDE.md", ] +[tool.uv.sources] +libtmux = { git = "https://github.com/tmux-python/libtmux.git", rev = "a3fdff7ca174739af0e058ea3458be9f0f27e3ef" } + [tool.uv.exclude-newer-package] ty = false # git-pull packages release in lockstep with their workspaces, so a diff --git a/src/tmuxp/cli/__init__.py b/src/tmuxp/cli/__init__.py index 24c60a01ff..8030862bfd 100644 --- a/src/tmuxp/cli/__init__.py +++ b/src/tmuxp/cli/__init__.py @@ -9,14 +9,13 @@ import typing as t from libtmux.__about__ import __version__ as libtmux_version -from libtmux.common import has_minimum_version from libtmux.exc import TmuxCommandNotFound, VersionTooLow from tmuxp import exc from tmuxp.__about__ import __version__ from tmuxp.log import setup_logger -from ._colors import build_description +from ._colors import Colors, build_description, get_color_mode from ._formatter import TmuxpHelpFormatter, create_themed_formatter from .convert import CONVERT_DESCRIPTION, command_convert, create_convert_subparser from .debug_info import ( @@ -285,20 +284,26 @@ def cli(_args: list[str] | None = None) -> None: See detailed documentation and examples at: http://tmuxp.git-pull.com/ """ - try: - has_minimum_version() - except TmuxCommandNotFound: - tmuxp_echo("tmux not found. tmuxp requires you install tmux first.") - sys.exit() - except (exc.TmuxpException, VersionTooLow) as e: - tmuxp_echo(str(e)) - sys.exit() - parser = create_parser() args = parser.parse_args(_args, namespace=ns) setup_logger(level=args.log_level.upper()) + try: + _dispatch(args, parser) + except (VersionTooLow, TmuxCommandNotFound, exc.LibtmuxCompatibilityError) as error: + colors = Colors(get_color_mode(args.color)) + detail = ( + "tmux executable not found; install tmux 3.3a or newer" + if isinstance(error, TmuxCommandNotFound) + else str(error) + ) + tmuxp_echo(colors.error("[Tmux Error]") + f" {detail}") + sys.exit(1) + + +def _dispatch(args: CLINamespace, parser: argparse.ArgumentParser) -> None: + """Run the selected subcommand after argument parsing.""" if args.subparser_name is None: parser.print_help() return diff --git a/src/tmuxp/cli/debug_info.py b/src/tmuxp/cli/debug_info.py index 4e1bf0c5d5..9ef0bb901f 100644 --- a/src/tmuxp/cli/debug_info.py +++ b/src/tmuxp/cli/debug_info.py @@ -12,7 +12,8 @@ import typing as t from libtmux.__about__ import __version__ as libtmux_version -from libtmux.common import get_version_str, tmux_cmd +from libtmux.common import tmux_cmd +from libtmux.exc import LibTmuxException from tmuxp.__about__ import __version__ from tmuxp._internal.private_path import PrivatePath, collapse_home_in_string @@ -98,6 +99,17 @@ def _private(path: pathlib.Path | str | None) -> str: return str(PrivatePath(path)) +def _executable_version(binary: str) -> str: + """Return the tmux executable's version verbatim, keeping letter suffixes.""" + response = tmux_cmd("-V", tmux_bin=binary) + report = response.stdout[0] if response.stdout else "" + if response.returncode or not report: + detail = "\n".join(response.stderr).strip() + msg = detail or "tmux version unavailable" + raise LibTmuxException(msg) + return report.removeprefix("tmux ").strip() + + def _collect_debug_info() -> dict[str, t.Any]: """Collect debug information as a structured dictionary. @@ -116,12 +128,40 @@ def _collect_debug_info() -> dict[str, t.Any]: >>> 'tmux_version' in data True """ - # Collect tmux command outputs - sessions_resp = tmux_cmd("list-sessions") - windows_resp = tmux_cmd("list-windows") - panes_resp = tmux_cmd("list-panes") - global_opts_resp = tmux_cmd("show-options", "-g") - window_opts_resp = tmux_cmd("show-window-options", "-g") + binary = shutil.which("tmux") + errors: dict[str, str] = {} + tmux_version = "not found" + if binary is not None: + try: + tmux_version = _executable_version(binary) + except LibTmuxException as error: + tmux_version = "unavailable" + errors["version"] = collapse_home_in_string( + str(error) or "tmux version unavailable" + ) + + def collect(name: str, *command: str) -> list[str]: + if binary is None: + errors[name] = "tmux executable not found" + return [] + try: + response = tmux_cmd("-N", *command, tmux_bin=binary) + except LibTmuxException as error: + errors[name] = collapse_home_in_string( + str(error) or "tmux executable not found" + ) + return [] + if response.returncode: + errors[name] = collapse_home_in_string("\n".join(response.stderr)) + return response.stdout + + tmux = { + "sessions": collect("sessions", "list-sessions"), + "windows": collect("windows", "list-windows"), + "panes": collect("panes", "list-panes"), + "global_options": collect("global_options", "show-options", "-g"), + "window_options": collect("window_options", "show-window-options", "-g"), + } return { "environment": { @@ -132,19 +172,14 @@ def _collect_debug_info() -> dict[str, t.Any]: }, "python_version": " ".join(sys.version.split("\n")), "system_path": collapse_home_in_string(os.environ.get("PATH", "")), - "tmux_version": get_version_str(), + "tmux_version": tmux_version, "libtmux_version": libtmux_version, "tmuxp_version": __version__, "tmux_path": _private(shutil.which("tmux")), "tmuxp_path": _private(tmuxp_path), "shell": _private(os.environ.get("SHELL", "")), - "tmux": { - "sessions": sessions_resp.stdout, - "windows": windows_resp.stdout, - "panes": panes_resp.stdout, - "global_options": global_opts_resp.stdout, - "window_options": window_opts_resp.stdout, - }, + "tmux": tmux, + "tmux_errors": errors, } @@ -239,6 +274,11 @@ def format_tmux_section(lines: list[str]) -> str: + format_tmux_section(tmux_data["window_options"]), ] + if errors := data.get("tmux_errors"): + output.append( + f"{colors.format_label('tmux errors')}:\n" + + "\n".join(f"\t{name}: {error}" for name, error in errors.items()) + ) return "\n".join(output) diff --git a/src/tmuxp/cli/freeze.py b/src/tmuxp/cli/freeze.py index fa26569ca7..d30b5a26de 100644 --- a/src/tmuxp/cli/freeze.py +++ b/src/tmuxp/cli/freeze.py @@ -135,6 +135,8 @@ def command_freeze( server = Server(socket_name=args.socket_name, socket_path=args.socket_path) + util._require_tmux(server) + try: if args.session_name: session = server.sessions.get(session_name=args.session_name, default=None) diff --git a/src/tmuxp/cli/load.py b/src/tmuxp/cli/load.py index d026529f7f..594d186e88 100644 --- a/src/tmuxp/cli/load.py +++ b/src/tmuxp/cli/load.py @@ -8,7 +8,6 @@ import logging import os import pathlib -import shutil import sys import typing as t @@ -600,7 +599,7 @@ def load_workspace( colors=colors, ) - shutil.which("tmux") # raise exception if tmux not found + util._require_tmux(t) # Builder resolution + creation — outside spinner so plugin prompts are safe. # Trusted import roots (absent config -> [] -> a no-op sandbox) stay on diff --git a/src/tmuxp/cli/shell.py b/src/tmuxp/cli/shell.py index 57a5ae8e4b..ea171ddf96 100644 --- a/src/tmuxp/cli/shell.py +++ b/src/tmuxp/cli/shell.py @@ -201,6 +201,7 @@ def command_shell( server = Server(socket_name=args.socket_name, socket_path=args.socket_path) + util._require_tmux(server) server.raise_if_dead() current_pane = util.get_current_pane(server=server) diff --git a/src/tmuxp/exc.py b/src/tmuxp/exc.py index c80ebe3b73..63839c08d0 100644 --- a/src/tmuxp/exc.py +++ b/src/tmuxp/exc.py @@ -15,6 +15,10 @@ class TmuxpException(Exception): """Base Exception for Tmuxp Errors.""" +class LibtmuxCompatibilityError(TmuxpException): + """Installed libtmux lacks the required version check.""" + + class WorkspaceError(TmuxpException): """Error parsing tmuxp workspace data.""" diff --git a/src/tmuxp/log.py b/src/tmuxp/log.py index 9b526d96e7..faa3319b67 100644 --- a/src/tmuxp/log.py +++ b/src/tmuxp/log.py @@ -72,6 +72,12 @@ def setup_logger( if not logger: # if no logger exists, make one logger = logging.getLogger("tmuxp") + for handler in list(logger.handlers): + if isinstance(handler, logging.StreamHandler) and getattr( + handler.stream, "closed", False + ): + logger.removeHandler(handler) + has_handlers = any(not isinstance(h, logging.NullHandler) for h in logger.handlers) if not has_handlers: # setup logger handlers diff --git a/src/tmuxp/plugin.py b/src/tmuxp/plugin.py index 2810b59d92..697917cc2d 100644 --- a/src/tmuxp/plugin.py +++ b/src/tmuxp/plugin.py @@ -3,14 +3,16 @@ from __future__ import annotations import logging +import re import typing as t import libtmux from libtmux._compat import LegacyVersion as Version -from libtmux.common import get_version +from libtmux.server import Server from .__about__ import __version__ from .exc import TmuxpPluginException +from .util import _require_backend logger = logging.getLogger(__name__) @@ -213,7 +215,9 @@ def __init__(self, **kwargs: Unpack[PluginConfigSchema]) -> None: self.plugin_name = config["plugin_name"] # Dependency versions - self.tmux_version = get_version() + self.tmux_version = Version( + re.sub(r"[a-z-]", "", _require_backend().server_version(Server())) + ) self.libtmux_version = libtmux.__about__.__version__ self.tmuxp_version = Version(__version__) diff --git a/src/tmuxp/util.py b/src/tmuxp/util.py index 152b1f6c06..401442b791 100644 --- a/src/tmuxp/util.py +++ b/src/tmuxp/util.py @@ -2,6 +2,7 @@ from __future__ import annotations +import importlib import logging import os import shlex @@ -20,11 +21,43 @@ from libtmux.session import Session from libtmux.window import Window + class _BackendSupport(t.Protocol): + MINIMUM: str + + def require_version(self, version: str, minimum: str = ...) -> None: ... + def server_version(self, server: Server) -> str: ... + + logger = logging.getLogger(__name__) PY2 = sys.version_info[0] == 2 +def _require_backend() -> _BackendSupport: + """Require a libtmux that publishes the daemon-first version check.""" + message = ( + "tmuxp requires libtmux 0.71 or newer; " + "run uv sync --locked in a checkout, or install libtmux>=0.71" + ) + try: + module = importlib.import_module("libtmux._internal.support") + except ImportError as error: + raise exc.LibtmuxCompatibilityError(message) from error + if not all( + callable(getattr(module, name, None)) + for name in ("require_version", "server_version") + ) or not isinstance(getattr(module, "MINIMUM", None), str): + raise exc.LibtmuxCompatibilityError(message) + support = t.cast("_BackendSupport", module) + support.require_version(support.MINIMUM, minimum="3.3a") + return support + + +def _require_tmux(server: Server) -> None: + """Check the selected daemon or cold executable's version before user code.""" + _require_backend().server_version(server) + + def run_before_script( script_file: str | pathlib.Path, cwd: pathlib.Path | None = None, diff --git a/src/tmuxp/workspace/builder/classic.py b/src/tmuxp/workspace/builder/classic.py index 41d748ad8b..9ee819ceca 100644 --- a/src/tmuxp/workspace/builder/classic.py +++ b/src/tmuxp/workspace/builder/classic.py @@ -16,7 +16,7 @@ from tmuxp import exc from tmuxp.log import TmuxpLoggerAdapter -from tmuxp.util import get_current_pane, run_before_script +from tmuxp.util import _require_tmux, get_current_pane, run_before_script from tmuxp.workspace.options import ( PaneReadiness, WorkspaceBuilderOptions, @@ -385,6 +385,8 @@ def __init__( # validation.validate_schema(session_config) assert isinstance(server, Server) + self._version_checked: Server | None = None + self._check_version(server) self.server = server self.session_config = session_config @@ -421,6 +423,12 @@ def session(self) -> Session: raise exc.SessionMissingWorkspaceException return self._session + def _check_version(self, server: Server) -> None: + """Check *server* once per builder; a different server is checked again.""" + if self._version_checked is not server: + _require_tmux(server) + self._version_checked = server + def session_exists(self, session_name: str) -> bool: """Return true if tmux session already exists.""" assert session_name is not None @@ -451,6 +459,7 @@ def build(self, session: Session | None = None, append: bool = False) -> None: append : bool append windows in current active session """ + self._check_version(session.server if session is not None else self.server) if not session: if not self.server: msg = ( @@ -649,6 +658,7 @@ def iter_create_windows( Newly created window, and the section from the tmuxp configuration that was used to create the window. """ + self._check_version(session.server) for window_iterator, window_config in enumerate( self.session_config["windows"], start=1, @@ -751,6 +761,7 @@ def iter_create_panes( that was used to create the pane. """ assert isinstance(window, Window) + self._check_version(window.server) pane_base_index = window.show_option("pane-base-index", global_=True) assert pane_base_index is not None @@ -888,6 +899,7 @@ def config_after_window( window_config : dict config section for window """ + self._check_version(window.server) if "options_after" in window_config and isinstance( window_config["options_after"], dict, diff --git a/src/tmuxp/workspace/freezer.py b/src/tmuxp/workspace/freezer.py index a1df02c1dc..6f993b9f12 100644 --- a/src/tmuxp/workspace/freezer.py +++ b/src/tmuxp/workspace/freezer.py @@ -5,6 +5,8 @@ import logging import typing as t +from tmuxp import util + logger = logging.getLogger(__name__) if t.TYPE_CHECKING: @@ -69,6 +71,7 @@ def freeze(session: Session) -> dict[str, t.Any]: dict tmuxp compatible workspace """ + util._require_tmux(session.server) logger.debug("freezing session", extra={"tmux_session": session.session_name}) session_config: dict[str, t.Any] = { diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index 296ed34913..1532fc08b0 100644 --- a/tests/cli/test_cli.py +++ b/tests/cli/test_cli.py @@ -8,7 +8,6 @@ import typing as t import libtmux -import libtmux.common import libtmux.exc import pytest @@ -40,14 +39,15 @@ def test_cli_reports_tmux_older_than_libtmux_supports( """cli() prints libtmux's version message instead of a traceback.""" message = "libtmux only supports tmux 3.3a and greater." - def has_minimum_version() -> bool: + def require_tmux(_server: Server) -> None: raise libtmux.exc.VersionTooLow(message) - monkeypatch.setattr(cli, "has_minimum_version", has_minimum_version) + monkeypatch.setattr("tmuxp.util._require_tmux", require_tmux) - with pytest.raises(SystemExit): - cli.cli(["ls"]) + with pytest.raises(SystemExit) as exc_info: + cli.cli(["freeze", "session"]) + assert exc_info.value.code == 1 assert message in capsys.readouterr().out @@ -61,14 +61,14 @@ def test_cli_reports_malformed_tmux_binary_without_traceback( broken_tmux.write_bytes(b"\x7fELF") broken_tmux.chmod(0o755) monkeypatch.setenv("PATH", str(tmp_path)) - libtmux.common.get_version.cache_clear() - try: - with pytest.raises(SystemExit): - cli.cli(["ls"]) - finally: - libtmux.common.get_version.cache_clear() - - assert "tmux not found." in capsys.readouterr().out + + with pytest.raises(SystemExit) as exc_info: + cli.cli(["freeze", "session"]) + + assert exc_info.value.code == 1 + output = capsys.readouterr() + assert "tmux executable not found" in output.out + assert "Traceback" not in output.err class HelpTestFixture(t.NamedTuple): diff --git a/tests/cli/test_debug_info.py b/tests/cli/test_debug_info.py index 9aba904d13..0a7203e9d3 100644 --- a/tests/cli/test_debug_info.py +++ b/tests/cli/test_debug_info.py @@ -175,14 +175,14 @@ def test_debug_info_reports_raw_tmux_version( ) -> None: """debug-info reports tmux's raw version, keeping the point-release suffix. - libtmux's ``get_version()`` strips the letter suffix (``"3.7a"`` -> ``"3.7"``) - for numeric comparison; ``get_version_str()`` keeps it. Bug reports want the - exact patch release, so debug-info reads the raw string verbatim. + Numeric comparisons strip the letter suffix (``"3.7a"`` -> ``"3.7"``). Bug + reports want the exact patch release, so debug-info reads the raw string + verbatim. """ monkeypatch.setenv("SHELL", "/bin/bash") monkeypatch.setattr( - "tmuxp.cli.debug_info.get_version_str", - lambda *args, **kwargs: "3.7a", + "tmuxp.cli.debug_info._executable_version", + lambda _binary: "3.7a", ) cli.cli(["debug-info", "--json"]) diff --git a/tests/test_log.py b/tests/test_log.py index b916b37b94..484df73f24 100644 --- a/tests/test_log.py +++ b/tests/test_log.py @@ -2,6 +2,7 @@ from __future__ import annotations +import io import logging import sys @@ -11,6 +12,7 @@ LEVEL_COLORS, DebugLogFormatter, LogFormatter, + setup_logger, tmuxp_echo, ) @@ -103,3 +105,27 @@ def test_tmuxp_echo_none_is_no_op(capsys: pytest.CaptureFixture[str]) -> None: captured = capsys.readouterr() assert captured.out == "" assert captured.err == "" + + +def test_setup_logger_replaces_closed_stream_handler( + capsys: pytest.CaptureFixture[str], +) -> None: + """setup_logger() discards closed StreamHandlers before attaching a new one.""" + test_logger = logging.getLogger("tmuxp.test.closed_stream") + test_logger.handlers.clear() + test_logger.propagate = False + closed_stream = io.StringIO() + stale_handler = logging.StreamHandler(closed_stream) + test_logger.addHandler(stale_handler) + closed_stream.close() + + try: + setup_logger(logger=test_logger, level="INFO") + test_logger.info("workspace loading") + finally: + test_logger.handlers.clear() + + captured = capsys.readouterr() + assert "--- Logging error ---" not in captured.err + assert "Traceback" not in captured.err + assert "workspace loading" in captured.err diff --git a/tests/test_tmux_versions.py b/tests/test_tmux_versions.py new file mode 100644 index 0000000000..9d6396d462 --- /dev/null +++ b/tests/test_tmux_versions.py @@ -0,0 +1,347 @@ +"""Version checks before workspace imports, callbacks, and shell setup.""" + +from __future__ import annotations + +import importlib +import json +import os +import pathlib +import subprocess +import types +import typing as t +import uuid + +import pytest +from libtmux.exc import VersionTooLow +from libtmux.server import Server +from libtmux.session import Session +from libtmux.window import Window + +from tmuxp import cli, exc +from tmuxp.cli import load, shell +from tmuxp.workspace import freezer, loader +from tmuxp.workspace.builder.classic import ClassicWorkspaceBuilder + +if t.TYPE_CHECKING: + from collections.abc import Iterator + + +def _native(binary: str, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [binary, *args], capture_output=True, text=True, timeout=5, check=False + ) + + +@pytest.fixture +def unsupported_tmux() -> str: + """Use an explicitly supplied tmux below the core floor.""" + binary = os.environ.get("TMUXP_TEST_OLD_TMUX") + if not binary: + pytest.skip("set TMUXP_TEST_OLD_TMUX to test an unsupported tmux") + report = _native(binary, "-V") + assert report.returncode == 0 + assert report.stdout.strip().endswith((" 3.2a", " 3.3")) + return binary + + +@pytest.fixture +def unsupported_endpoint(unsupported_tmux: str) -> Iterator[str]: + """Keep an old daemon alive while the configured client is supported.""" + name = "tmuxp_versions_" + uuid.uuid4().hex + started = _native( + unsupported_tmux, + "-f", + "/dev/null", + "-L", + name, + "new-session", + "-d", + "-s", + "old", + ) + assert started.returncode == 0, started.stderr + try: + yield name + finally: + _native(unsupported_tmux, "-L", name, "kill-server") + + +def _workspace( + tmp_path: pathlib.Path, + *, + workspace_builder: str | None = None, + workspace_builder_paths: list[str] | None = None, + plugins: list[str] | None = None, +) -> pathlib.Path: + window: dict[str, str | list[str]] = {"window_name": "main", "panes": ["true"]} + config: dict[str, str | list[str] | list[dict[str, str | list[str]]]] = { + "session_name": "checked", + "windows": [window], + } + if workspace_builder is not None: + config["workspace_builder"] = workspace_builder + if workspace_builder_paths is not None: + config["workspace_builder_paths"] = workspace_builder_paths + if plugins is not None: + config["plugins"] = plugins + path = tmp_path / "workspace.json" + path.write_text(json.dumps(config)) + return path + + +@pytest.mark.parametrize("kind", ["builder", "plugin"]) +def test_unsupported_endpoint_refuses_before_import( + tmp_path: pathlib.Path, + unsupported_endpoint: str, + monkeypatch: pytest.MonkeyPatch, + kind: str, +) -> None: + """A modern client cannot authorize imports on an older selected daemon.""" + marker = tmp_path / "imported" + module = "tmuxp_versions_" + uuid.uuid4().hex + body = ( + "from pathlib import Path\n" + f"Path({str(marker)!r}).touch()\n" + "from tmuxp.workspace.builder.classic import ClassicWorkspaceBuilder\n" + "class Plugin:\n pass\n" + ) + (tmp_path / f"{module}.py").write_text(body) + if kind == "builder": + path = _workspace( + tmp_path, + workspace_builder=f"{module}:ClassicWorkspaceBuilder", + workspace_builder_paths=[str(tmp_path)], + ) + else: + monkeypatch.syspath_prepend(str(tmp_path)) + path = _workspace(tmp_path, plugins=[f"{module}.Plugin"]) + with pytest.raises(VersionTooLow, match=r"3\.3a"): + load.load_workspace(path, socket_name=unsupported_endpoint, detached=True) + assert not marker.exists() + + +def test_unsupported_cold_endpoint_refuses_before_import( + tmp_path: pathlib.Path, + unsupported_tmux: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An old cold executable cannot authorize builder imports or start tmux.""" + monkeypatch.setenv("PATH", str(pathlib.Path(unsupported_tmux).parent)) + marker = tmp_path / "imported" + module = "tmuxp_versions_" + uuid.uuid4().hex + (tmp_path / f"{module}.py").write_text( + f"from pathlib import Path\nPath({str(marker)!r}).touch()\n" + ) + path = _workspace( + tmp_path, + workspace_builder=f"{module}:Builder", + workspace_builder_paths=[str(tmp_path)], + ) + name = "tmuxp_cold_" + uuid.uuid4().hex + with pytest.raises(VersionTooLow, match=r"3\.3a"): + load.load_workspace(path, socket_name=name, detached=True) + assert not marker.exists() + assert _native(unsupported_tmux, "-N", "-L", name, "list-sessions").returncode + + +def test_unsupported_cli_reports_a_nonzero_error( + tmp_path: pathlib.Path, + unsupported_endpoint: str, + capsys: pytest.CaptureFixture[str], +) -> None: + """Render version errors through the CLI without a traceback.""" + path = _workspace(tmp_path) + with pytest.raises(SystemExit) as error: + cli.cli(["load", "-L", unsupported_endpoint, "-d", str(path)]) + assert error.value.code == 1 + output = capsys.readouterr() + assert "[Tmux Error]" in output.out + assert "3.3a" in output.out + assert "Traceback" not in output.err + + +def test_unsupported_diagnostics_remains_available( + unsupported_tmux: str, + unsupported_endpoint: str, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Report an unsupported selected daemon without changing its state.""" + endpoint = _native( + unsupported_tmux, + "-L", + unsupported_endpoint, + "display-message", + "-p", + "#{socket_path},#{pid},0", + ) + assert endpoint.returncode == 0 + monkeypatch.setenv("TMUX", endpoint.stdout.strip()) + cli.cli(["debug-info", "--json"]) + data = json.loads(capsys.readouterr().out) + assert not any(data["tmux"].values()) + assert all("3.3a" in message for message in data["tmux_errors"].values()) + sessions = _native(unsupported_tmux, "-L", unsupported_endpoint, "list-sessions") + assert sessions.returncode == 0 and "old:" in sessions.stdout + + +@pytest.mark.parametrize("mode", ["command", "startup"]) +def test_unsupported_endpoint_refuses_shell_setup( + tmp_path: pathlib.Path, + unsupported_endpoint: str, + monkeypatch: pytest.MonkeyPatch, + mode: str, +) -> None: + """Refuse before command execution, Python startup, or shell imports.""" + marker = tmp_path / "executed" + code = f"from pathlib import Path; Path({str(marker)!r}).touch()" + argv = ["shell", "-L", unsupported_endpoint] + if mode == "command": + argv += ["-c", code] + else: + startup = tmp_path / "startup.py" + startup.write_text(code) + monkeypatch.setenv("PYTHONSTARTUP", str(startup)) + argv += ["--code", "--use-pythonrc"] + args = cli.create_parser().parse_args(argv, namespace=shell.CLIShellNamespace()) + with pytest.raises(VersionTooLow, match=r"3\.3a"): + shell.command_shell(args) + assert not marker.exists() + + +@pytest.mark.parametrize("entry", ["build", "windows", "panes", "options", "freeze"]) +def test_unsupported_supplied_target_refuses_before_callback( + server: Server, + unsupported_endpoint: str, + entry: str, +) -> None: + """A supplied session or window selects its own daemon before callbacks.""" + config = loader.trickle( + loader.expand({"session_name": "requested", "windows": [{"panes": ["true"]}]}) + ) + calls: list[str] = [] + builder = ClassicWorkspaceBuilder(config, server, on_progress=calls.append) + old_server = Server(socket_name=unsupported_endpoint) + session = Session(server=old_server, session_id="$0", session_name="old") + window = Window(server=old_server, session_id="$0", window_id="@0") + with pytest.raises(VersionTooLow, match=r"3\.3a"): + if entry == "build": + builder.build(session=session) + elif entry == "windows": + next(builder.iter_create_windows(session)) + elif entry == "panes": + next(builder.iter_create_panes(window, config["windows"][0])) + elif entry == "options": + builder.config_after_window(window, {"options_after": {"@effect": "yes"}}) + else: + freezer.freeze(session) + assert not calls + + +def test_builder_checks_a_server_once( + server: Server, monkeypatch: pytest.MonkeyPatch +) -> None: + """Window, pane and option hooks reuse the version check made for the build.""" + checked: list[Server] = [] + monkeypatch.setattr("tmuxp.workspace.builder.classic._require_tmux", checked.append) + config = loader.trickle( + loader.expand( + { + "session_name": "check-once", + "windows": [ + {"window_name": "one", "panes": ["true", "true"]}, + {"window_name": "two", "panes": ["true"]}, + ], + } + ) + ) + builder = ClassicWorkspaceBuilder(config, server) + builder.build() + assert checked == [server] + + +def test_missing_backend_refuses_before_import( + tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Refuse a libtmux without a version check before resolving custom builders.""" + original = importlib.import_module + calls: list[str] = [] + + def import_module(name: str, package: str | None = None) -> types.ModuleType: + calls.append(name) + if name == "libtmux._internal.support": + return types.ModuleType(name) + return original(name, package) + + monkeypatch.setattr(importlib, "import_module", import_module) + path = _workspace(tmp_path, workspace_builder="not_imported:Builder") + with pytest.raises(exc.TmuxpException, match=r"libtmux 0\.71"): + load.load_workspace(path, detached=True) + assert "not_imported" not in calls + + +@pytest.mark.parametrize("argv", [["--help"], ["--version"], ["debug-info", "--json"]]) +def test_diagnostics_without_tmux( + tmp_path: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + argv: list[str], +) -> None: + """Help, version, and diagnostics do not need a checked endpoint.""" + monkeypatch.setenv("PATH", str(tmp_path)) + try: + cli.cli(argv) + except SystemExit as error: + assert error.code == 0 + output = capsys.readouterr().out + if argv == ["--help"]: + assert "usage: tmuxp" in output + elif argv == ["--version"]: + assert "tmuxp " in output and "libtmux " in output + else: + data = json.loads(output) + assert data["tmux_version"] == "not found" + assert not any(data["tmux"].values()) + assert data["tmux_errors"]["sessions"] == "tmux executable not found" + + +def test_convert_without_tmux( + tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Configuration conversion remains available with tmux absent.""" + path = _workspace(tmp_path) + monkeypatch.setenv("PATH", str(tmp_path)) + cli.cli(["convert", "-y", str(path)]) + assert path.with_suffix(".yaml").exists() + + +def test_missing_tmux_cli_explains_the_error( + tmp_path: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Explain a missing executable while retaining a failing exit status.""" + path = _workspace(tmp_path) + monkeypatch.setenv("PATH", str(tmp_path)) + with pytest.raises(SystemExit) as error: + cli.cli(["load", "-d", str(path)]) + assert error.value.code == 1 + output = capsys.readouterr() + assert "tmux executable not found" in output.out + assert "Traceback" not in output.err + + +def test_supported_workspace_builds_and_captures( + tmp_path: pathlib.Path, server: Server +) -> None: + """Build an ordinary workspace through the installed libtmux dependency.""" + path = _workspace(tmp_path) + session = load.load_workspace( + path, socket_name=server.socket_name, detached=True, no_progress=True + ) + assert session is not None + assert session.name == "checked" + assert session.active_window.name == "main" + pane = session.active_window.active_pane + assert pane is not None + assert isinstance(pane.capture_pane(), list) diff --git a/uv.lock b/uv.lock index 59e1deebc6..c5e64eb9fb 100644 --- a/uv.lock +++ b/uv.lock @@ -803,11 +803,7 @@ wheels = [ [[package]] name = "libtmux" version = "0.70.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/51/f1/a44043193fd4c212858cdca04b8e628ce557726bf81f04fdc9765d4c2ac7/libtmux-0.70.0.tar.gz", hash = "sha256:1496d6253aea98321a99b5e414f378154967a570ffd1f5dc9f1effaa01f782c3", size = 1491548, upload-time = "2026-11-28T23:17:25.409Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/f6/9273ce6bba65485ad2c6d95eb287798913b463cfddd6c7737a01fb7587f6/libtmux-0.70.0-py3-none-any.whl", hash = "sha256:9fcdccc64bb354ca6e243e942484b58f4f950b4a14ff4a324ae2dc4005afe1b2", size = 188971, upload-time = "2026-11-28T23:17:23.977Z" }, -] +source = { git = "https://github.com/tmux-python/libtmux.git?rev=a3fdff7ca174739af0e058ea3458be9f0f27e3ef#a3fdff7ca174739af0e058ea3458be9f0f27e3ef" } [[package]] name = "linkify-it-py" @@ -1787,7 +1783,7 @@ testing = [ [package.metadata] requires-dist = [ - { name = "libtmux", specifier = "~=0.70.0" }, + { name = "libtmux", git = "https://github.com/tmux-python/libtmux.git?rev=a3fdff7ca174739af0e058ea3458be9f0f27e3ef" }, { name = "pyyaml", specifier = ">=6.0" }, ]