diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 7ec0a213..62bf1dd7 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -11,7 +11,9 @@ jobs: strategy: matrix: python-version: ['3.14'] - tmux-version: ['3.2a', '3.3a', '3.4', '3.5', '3.6', 'master'] + tmux-version: ['3.3a', '3.4', '3.5', '3.6', '3.7a', '3.8', 'master'] + env: + TMUX_TMPDIR: /tmp/libtmux-mcp-test steps: - uses: actions/checkout@v7 @@ -78,6 +80,7 @@ jobs: sudo apt install libevent-2.1-7 export PATH=$HOME/tmux-builds/tmux-${{ matrix.tmux-version }}/bin:$PATH ls $HOME/tmux-builds/tmux-${{ matrix.tmux-version }}/bin + mkdir -p "$TMUX_TMPDIR" tmux -V uv run py.test --cov=./ --cov-append --cov-report=xml -n auto --verbose env: @@ -88,6 +91,33 @@ jobs: with: token: ${{ secrets.CODECOV_TOKEN }} + unsupported-versions: + runs-on: ubuntu-latest + env: + TMUX_TMPDIR: /tmp/libtmux-mcp-test + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10.2.0 + - run: uv python install 3.14 + - run: uv sync --all-extras --dev + - name: Build supported and rejected native endpoints + run: | + sudo apt-get update + sudo apt-get install -y libevent-dev libncurses-dev bison + mkdir -p "$TMUX_TMPDIR" "$RUNNER_TEMP/tmux-versions" + for version in 3.2a 3.3 3.3a; do + git clone --quiet --depth=1 --branch "$version" https://github.com/tmux/tmux.git "$RUNNER_TEMP/tmux-versions/$version" + cd "$RUNNER_TEMP/tmux-versions/$version" + sh autogen.sh + ./configure --prefix="$RUNNER_TEMP/tmux-versions/$version/install" + make -j2 + make install + done + echo "LIBTMUX_TEST_MINIMUM_TMUX=$RUNNER_TEMP/tmux-versions/3.3a/install/bin/tmux" >> "$GITHUB_ENV" + echo "LIBTMUX_TEST_UNSUPPORTED_TMUX=$RUNNER_TEMP/tmux-versions/3.2a/install/bin/tmux" >> "$GITHUB_ENV" + echo "LIBTMUX_TEST_UNPATCHED_TMUX=$RUNNER_TEMP/tmux-versions/3.3/install/bin/tmux" >> "$GITHUB_ENV" + - run: uv run pytest tests/test_tmux_versions.py --reruns=0 -q + release: runs-on: ubuntu-latest needs: build diff --git a/CHANGES b/CHANGES index 56917243..2869aa57 100644 --- a/CHANGES +++ b/CHANGES @@ -6,6 +6,18 @@ _Notes on upcoming releases will be added here_ +### Compatibility + +Core operations require tmux 3.3a and libtmux 0.63.0 or newer. +Connected daemons, cold startup, owned subprocesses and generated completion +helpers are checked before requested effects. Subprocess version checks remember the daemon's release per endpoint and shares the +operation deadline and cancellation reaps the owned child. The version probe +runs no user hooks, and a failed probe or backend check is an expected tool +error. An unsupported default endpoint no longer stops startup: each tool +checks the endpoint it uses. CI retains 3.3a and tests rejection of native 3.2a +and unpatched 3.3. The development backend source pin remains in place until +libtmux 0.63.0 is released. + ## libtmux-mcp 0.1.0a22 (2026-09-06) libtmux-mcp 0.1.0a22 runs on FastMCP 4, which brings MCP Python SDK v2 with diff --git a/README.md b/README.md index 9116ee47..230245da 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,8 @@ commands, read output, orchestrate panes. ## Quickstart -**Requirements:** Python 3.10+, tmux >= 3.2a on `$PATH`. +**Requirements:** Python 3.10+, tmux >= 3.3a on `$PATH`, and libtmux 0.63.0 or newer, as described in +[compatibility](docs/reference/compatibility.md). The distribution is `libtmux-mcp`, the import is `libtmux_mcp`, and the installed executable is `libtmux-mcp`. diff --git a/docs/installation.md b/docs/installation.md index 68059a01..0cb4ab30 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -5,7 +5,8 @@ ## Requirements - Python 3.10+ -- tmux >= 3.2a +- tmux >= 3.3a, including the patch letter +- libtmux 0.63.0 or newer, described in {ref}`compatibility` - [uv](https://github.com/astral-sh/uv) ([install](https://docs.astral.sh/uv/getting-started/installation/)) or [pipx](https://github.com/pypa/pipx) ([install](https://pipx.pypa.io/stable/installation/)) — for running without a persistent install ## Run without installing @@ -53,11 +54,15 @@ $ cd libtmux-mcp ``` ```console -$ uv pip install -e "." +$ uv sync --all-extras --dev ``` Code changes take effect immediately — no reinstall needed. +This branch requires libtmux 0.63.0 or newer and pins a development revision +in `uv.lock` until that release exists. Ordinary package installers do not use +uv's source override and select the released package. + ## Running the server ```console diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.md index a11b5f05..e62467d5 100644 --- a/docs/reference/compatibility.md +++ b/docs/reference/compatibility.md @@ -17,17 +17,42 @@ | tmux | Status | |------|--------| -| >= 3.2a | Supported | -| < 3.2a | Not supported (libtmux requirement) | +| >= 3.3a | Core operations supported | +| 3.3 and earlier | Refused before requested effects | + +Commands validate the selected daemon, including when the client executable is +newer. An absent endpoint validates the executable before startup. Owned raw +subprocesses and generated completion helpers retain a native release guard; +live dispatch cannot start a replacement daemon after losing the one it checked. +Unknown release reports are refused. `command-alias` redefinitions of the +library's metadata and guard built-ins remain outside this qualification. + +The version check uses the operation's remaining subprocess budget. Cancelling an owned +async subprocess kills and reaps its metadata or effect child. Parent libtmux +calls delegated through worker threads retain their existing cancellation +semantics; this does not make those threads interruptible. + +Higher requirements for individual features are documented separately from +the core minimum. Baseline polling does not require control mode. ## Dependencies | Package | Required version | |---------|-----------------| -| [libtmux](https://libtmux.git-pull.com/) | >= 0.62.0, < 1.0 | +| [libtmux](https://libtmux.git-pull.com/) | >= 0.63.0, < 1.0 | | [FastMCP](https://github.com/jlowin/fastmcp) | >= 4.0.2, < 5.0.0 | | [regex](https://github.com/mrabarnett/mrab-regex) | >= 2024.11.6 | +The libtmux backend must publish `libtmux._internal.support`, which first ships in +libtmux 0.63.0; the dependency range names that release, so an installer never +selects the 0.62 series. Until libtmux 0.63.0 is released, this branch's uv +source override pins the implementation from +[Python core PR779](https://github.com/tmux-python/libtmux/pull/779) for +development; ordinary package installers ignore that override. Startup and tool +dispatch refuse a backend without that module. Release libtmux first, +then drop the source override and merge this change. Use +`uv sync --all-extras --dev` for the development pair. + ## MCP clients | Client | Tested | Transport | diff --git a/pyproject.toml b/pyproject.toml index b54ee574..4ce15372 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,7 +40,7 @@ include = [ ] dependencies = [ - "libtmux>=0.62.0,<1.0", + "libtmux>=0.63.0,<1.0", "fastmcp>=4.0.2,<5.0.0", "regex>=2024.11.6", ] @@ -115,6 +115,10 @@ lint = [ requires = ["hatchling"] build-backend = "hatchling.build" +[tool.uv.sources] +# Coordinated version-check backend, pending its package release. +libtmux = { git = "https://github.com/tmux-python/libtmux.git", rev = "f6e4630a15f342382487a60e1e1477abcd52294d" } + [tool.uv.exclude-newer-package] # git-pull packages release in lockstep with their workspaces, so a # fresh release blocking on the 3-day cooldown blocks every diff --git a/src/libtmux_mcp/_tmux_proc.py b/src/libtmux_mcp/_tmux_proc.py index 9bf169a7..8042651a 100644 --- a/src/libtmux_mcp/_tmux_proc.py +++ b/src/libtmux_mcp/_tmux_proc.py @@ -25,7 +25,16 @@ import asyncio import contextlib +import getopt +import importlib +import os +import subprocess +import time +import types import typing as t +import uuid + +from libtmux import exc #: Bound on the post-kill reap. Short because it is best effort: the #: loop's child watcher reaps the pid whether or not we wait. @@ -62,7 +71,7 @@ async def _kill_and_reap( await asyncio.wait_for(proc.wait(), timeout=_TMUX_REAP_SECONDS) -async def _run_tmux_bounded( +async def _run_tmux_unchecked( argv: list[str], *, timeout: float ) -> tuple[int, bytes, bytes]: """Run one tmux argv under a hard bound, killing it on cancellation. @@ -89,6 +98,7 @@ async def _run_tmux_bounded( Re-raised after the child has been killed and reaped, so a cancelled call never orphans tmux. """ + deadline = time.monotonic() + timeout proc = await asyncio.create_subprocess_exec( *argv, stdout=asyncio.subprocess.PIPE, @@ -103,7 +113,9 @@ async def _run_tmux_bounded( # when cancelling it can actually succeed. task = asyncio.ensure_future(proc.communicate()) try: - done, _pending = await asyncio.wait({task}, timeout=timeout) + done, _pending = await asyncio.wait( + {task}, timeout=max(0, deadline - time.monotonic()) + ) if not done: await _kill_and_reap(proc, task) raise TimeoutError @@ -119,3 +131,237 @@ async def _run_tmux_bounded( raise assert proc.returncode is not None return proc.returncode, stdout, stderr + + +_MINIMUM_TMUX = "3.3a" + + +def _backend() -> types.ModuleType: + """Require a libtmux that publishes the daemon-first version check.""" + try: + support = importlib.import_module("libtmux._internal.support") + except ImportError as error: + msg = ( + "Unsupported libtmux backend: libtmux 0.63 or newer is required " + "for the tmux 3.3a version check" + ) + raise exc.LibTmuxException(msg) from error + if not all( + callable(getattr(support, name, None)) + for name in ("require_version", "check_fence") + ) or not isinstance(getattr(support, "MINIMUM", None), str): + msg = "Unsupported libtmux backend: the tmux version check is unavailable" + raise exc.LibTmuxException(msg) + support.require_version(support.MINIMUM, minimum=_MINIMUM_TMUX) + return support + + +def _parts(argv: list[str]) -> tuple[list[str], list[str]]: + options, commands = getopt.getopt(argv[1:], "L:S:uN") + selectors: list[str] = [] + for flag, value in options: + if flag in {"-L", "-S"}: + selectors.extend((flag, value)) + return selectors, commands + + +def _absent(returncode: int, stderr: bytes) -> bool: + if returncode == 0: + return False + detail = stderr.decode("utf-8", errors="backslashreplace") + return "no server running" in detail or ( + "error connecting to" in detail + and any( + reason in detail + for reason in ("No such file or directory", "Connection refused") + ) + ) + + +def _version( + stdout: bytes, stderr: bytes, returncode: int, *, binary: str | None +) -> str: + report = stdout.decode("utf-8", errors="backslashreplace") + if binary is not None: + name = ( + os.fsencode(binary) + .rsplit(b"/", 1)[-1] + .decode("utf-8", errors="backslashreplace") + ) + prefix = next( + (item for item in (name + " ", "tmux ") if report.startswith(item)), + None, + ) + report = report[len(prefix) :] if prefix is not None else "" + if returncode or not report: + detail = stderr.decode("utf-8", errors="backslashreplace").strip() + msg = f"tmux version check failed: {detail or 'no version report'}" + raise exc.LibTmuxException(msg) + return report.strip() + + +def _probe(binary: str, selectors: list[str]) -> tuple[list[str], str]: + """Build the hook-free live version probe and its private marker. + + ``run-shell`` has no after-hook, and with ``-C`` it fails while parsing its + own output, so neither ``after-*`` nor ``command-error`` hooks fire. + """ + marker = "libtmux-mcp-version-" + uuid.uuid4().hex + "-" + return [binary, *selectors, "-N", "run-shell", "-C", marker + "#{version}"], marker + + +def _live_version(stderr: bytes, returncode: int, marker: str) -> str: + detail = stderr.decode("utf-8", errors="backslashreplace") + prefix = f"unknown command: {marker}" + reports = [ + line[len(prefix) :] for line in detail.splitlines() if line.startswith(prefix) + ] + if returncode != 1 or len(reports) != 1: + msg = f"tmux version check failed: {detail.strip() or 'no version report'}" + raise exc.LibTmuxException(msg) + return reports[0] + + +#: Checked release per live endpoint. The ``if-shell -F`` fence in every +#: dispatched command catches a replaced daemon, so a release only needs a new +#: probe after a refusal or when the daemon is gone. Absent endpoints are never +#: cached. +_VERSION_CACHE: dict[tuple[str, tuple[str, ...], str, str], str] = {} + + +def _endpoint_key( + binary: str, selectors: list[str] +) -> tuple[str, tuple[str, ...], str, str]: + env = os.environ + return (binary, tuple(selectors), env.get("TMUX_TMPDIR", ""), env.get("TMUX", "")) + + +def _forget(binary: str, selectors: list[str]) -> None: + _VERSION_CACHE.pop(_endpoint_key(binary, selectors), None) + + +def _remaining(deadline: float) -> float: + result = deadline - time.monotonic() + if result <= 0: + raise TimeoutError + return result + + +def _fence(argv: list[str], version: str, live: bool) -> tuple[list[str], str | None]: + _backend().require_version(version, minimum=_MINIMUM_TMUX) + _, commands = _parts(argv) + prefix = argv[: len(argv) - len(commands)] if commands else argv + marker = "libtmux-mcp-version-" + uuid.uuid4().hex + # These callers select one native command; preserve literal terminal text. + literal = [item[:-1] + "\\;" if item.endswith(";") else item for item in commands] + return [ + *prefix, + "-u", + *(["-N"] if live else []), + "if-shell", + "-F", + "#{==:#{version}," + version + "}", + "", + marker, + ";", + *literal, + ], marker + + +async def _prepare_bounded( + argv: list[str], deadline: float +) -> tuple[list[str], str | None]: + _backend() + selectors, _commands = _parts(argv) + cached = _VERSION_CACHE.get(_endpoint_key(argv[0], selectors)) + if cached is not None: + return _fence(argv, cached, True) + probe, marker = _probe(argv[0], selectors) + code, output, error = await _run_tmux_unchecked(probe, timeout=_remaining(deadline)) + live = not _absent(code, error) + if live: + version = _live_version(error, code, marker) + _VERSION_CACHE[_endpoint_key(argv[0], selectors)] = version + else: + code, output, error = await _run_tmux_unchecked( + [argv[0], "-V"], timeout=_remaining(deadline) + ) + version = _version(output, error, code, binary=argv[0]) + return _fence(argv, version, live) + + +async def _run_tmux_bounded( + argv: list[str], *, timeout: float +) -> tuple[int, bytes, bytes]: + """Check the version and dispatch within one cancellable process budget.""" + deadline = time.monotonic() + timeout + selectors, _ = _parts(argv) + for attempt in (0, 1): + prepared, marker = await _prepare_bounded(argv, deadline) + result = await _run_tmux_unchecked(prepared, timeout=_remaining(deadline)) + stderr = result[2] + if attempt == 0 and _absent(result[0], stderr): + # The cached daemon vanished; nothing ran, so check the version again. + _forget(argv[0], selectors) + continue + try: + _backend().check_fence( + stderr.decode("utf-8", errors="backslashreplace"), marker + ) + except exc.VersionTooLow: + _forget(argv[0], selectors) + raise + break + return result + + +def _run_tmux_sync_bounded( + argv: list[str], *, timeout: float, check: bool = True +) -> subprocess.CompletedProcess[bytes]: + """Check the version and run a synchronous child within one remaining budget.""" + policy = _backend() + deadline = time.monotonic() + timeout + selectors, _commands = _parts(argv) + + def run(command: list[str]) -> subprocess.CompletedProcess[bytes]: + budget = deadline - time.monotonic() + if budget <= 0: + raise subprocess.TimeoutExpired(argv, timeout) + return subprocess.run(command, capture_output=True, timeout=budget, check=False) + + for attempt in (0, 1): + cached = _VERSION_CACHE.get(_endpoint_key(argv[0], selectors)) + if cached is not None: + version, live = cached, True + else: + command, probe_marker = _probe(argv[0], selectors) + probe = run(command) + live = not _absent(probe.returncode, probe.stderr) + if live: + version = _live_version(probe.stderr, probe.returncode, probe_marker) + _VERSION_CACHE[_endpoint_key(argv[0], selectors)] = version + else: + probe = run([argv[0], "-V"]) + version = _version( + probe.stdout, probe.stderr, probe.returncode, binary=argv[0] + ) + prepared, marker = _fence(argv, version, live) + result = run(prepared) + if ( + attempt == 0 + and cached is not None + and _absent(result.returncode, result.stderr) + ): + _forget(argv[0], selectors) + continue + try: + policy.check_fence( + result.stderr.decode("utf-8", errors="backslashreplace"), marker + ) + except exc.VersionTooLow: + _forget(argv[0], selectors) + raise + break + if check: + result.check_returncode() + return result diff --git a/src/libtmux_mcp/_utils.py b/src/libtmux_mcp/_utils.py index 3b9950c3..25b189e8 100644 --- a/src/libtmux_mcp/_utils.py +++ b/src/libtmux_mcp/_utils.py @@ -21,6 +21,8 @@ from libtmux._internal.query_list import LOOKUP_NAME_MAP from libtmux.server import Server +from libtmux_mcp._tmux_proc import _backend + if t.TYPE_CHECKING: from libtmux.pane import Pane from libtmux.session import Session @@ -582,6 +584,7 @@ def _get_server( Server A cached libtmux Server instance. """ + _backend() if socket_name is None: socket_name = os.environ.get("LIBTMUX_SOCKET") if socket_path is None: @@ -591,11 +594,7 @@ def _get_server( cache_key = (socket_name, socket_path, tmux_bin) with _server_cache_lock: - if cache_key in _server_cache: - cached = _server_cache[cache_key] - if not cached.is_alive(): - del _server_cache[cache_key] - + # Cache configuration only; every operation checks the current daemon's version. if cache_key not in _server_cache: kwargs: dict[str, t.Any] = {} if socket_name is not None: @@ -1139,6 +1138,7 @@ def handle_tool_errors( @functools.wraps(fn) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: try: + _backend() return fn(*args, **kwargs) except ToolError: raise @@ -1168,6 +1168,7 @@ def handle_tool_errors_async( @functools.wraps(fn) async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: try: + _backend() return await fn(*args, **kwargs) except ToolError: raise diff --git a/src/libtmux_mcp/server.py b/src/libtmux_mcp/server.py index 6168dca8..4b61dd25 100644 --- a/src/libtmux_mcp/server.py +++ b/src/libtmux_mcp/server.py @@ -6,24 +6,30 @@ from __future__ import annotations import contextlib +import logging import os import shutil +import time import typing as t from fastmcp import FastMCP from fastmcp.server.middleware.timing import TimingMiddleware +from libtmux import exc from libtmux_mcp.__about__ import __version__ from libtmux_mcp._history import ( _configure_history_defaults, _resolve_suppress_history, ) +from libtmux_mcp._tmux_proc import _backend, _prepare_bounded from libtmux_mcp._utils import ( TOOLSET_EXECUTE, TOOLSET_INSPECT, TOOLSET_MANAGE, VALID_TOOLSETS, + _get_server, _server_cache, + _tmux_argv, ) from libtmux_mcp._wait_policy import ( WAIT_MAX_SECONDS_ENV, @@ -136,6 +142,8 @@ {TOOLSET_INSPECT, TOOLSET_MANAGE, TOOLSET_EXECUTE} ) +logger = logging.getLogger(__name__) + def _build_instructions( toolsets: frozenset[str] = DEFAULT_TOOLSETS, @@ -344,10 +352,11 @@ async def _lifespan(_app: FastMCP) -> t.AsyncIterator[None]: Startup ------- Validates named tool includes and exclusions against the transformed - catalog, then verifies that a ``tmux`` binary is on ``PATH``. Without - the binary probe, tools fail at first call with a generic - ``TmuxCommandNotFound`` deep inside libtmux. Failing at server start - instead surfaces a clear cold-start error before tool traffic arrives. + catalog, then checks the coordinated libtmux backend and selected tmux + endpoint. The connected daemon, or the executable at an unused endpoint, + should report at least tmux 3.3a before tool traffic arrives. This bounded + probe starts no daemon. An unsupported default endpoint only logs a + warning: tools take their own socket and check it on every call. Shutdown -------- @@ -371,10 +380,25 @@ async def _lifespan(_app: FastMCP) -> t.AsyncIterator[None]: msg = f"{variable} names unknown tools: {', '.join(unknown)}" raise RuntimeError(msg) - if shutil.which("tmux") is None: - msg = "tmux binary not found on PATH" + _backend() + binary = os.environ.get("LIBTMUX_TMUX_BIN") or "tmux" + if shutil.which(binary) is None: + msg = f"tmux binary not found: {binary}" raise RuntimeError(msg) try: + try: + await _prepare_bounded( + _tmux_argv(_get_server(), "list-sessions"), time.monotonic() + 5.0 + ) + except (exc.LibTmuxException, TimeoutError, OSError) as error: + # Every tool takes its own socket and checks it per call, so one + # unsupported or unreachable default endpoint must not stop the + # server from serving the others. + logger.warning( + "default tmux endpoint is not usable; tools check each endpoint " + "on use: %s", + error, + ) yield finally: _server_cache.clear() diff --git a/src/libtmux_mcp/tools/buffer_tools.py b/src/libtmux_mcp/tools/buffer_tools.py index 0707214e..b9626ec8 100644 --- a/src/libtmux_mcp/tools/buffer_tools.py +++ b/src/libtmux_mcp/tools/buffer_tools.py @@ -34,6 +34,7 @@ import typing as t import uuid +from libtmux_mcp._tmux_proc import _run_tmux_sync_bounded from libtmux_mcp._utils import ( ANNOTATIONS_AMBIENT_UNKNOWN, TOOLSET_EXECUTE, @@ -217,7 +218,7 @@ def load_buffer( f.write(content) argv = _tmux_argv(server, "load-buffer", "-b", buffer_name, tmppath) try: - subprocess.run(argv, check=True, capture_output=True, timeout=5.0) + _run_tmux_sync_bounded(argv, timeout=5.0) except subprocess.TimeoutExpired as e: msg = f"load-buffer timeout after 5s for {buffer_name!r}" raise ExpectedToolError(msg) from e @@ -315,12 +316,7 @@ def show_buffer( cname = _validate_buffer_name(buffer_name) argv = _tmux_argv(server, "show-buffer", "-b", cname) try: - completed = subprocess.run( - argv, - check=True, - capture_output=True, - timeout=5.0, - ) + completed = _run_tmux_sync_bounded(argv, timeout=5.0) except subprocess.TimeoutExpired as e: msg = f"show-buffer timeout after 5s for {cname!r}" raise ExpectedToolError(msg) from e @@ -366,7 +362,7 @@ def delete_buffer( cname = _validate_buffer_name(buffer_name) argv = _tmux_argv(server, "delete-buffer", "-b", cname) try: - subprocess.run(argv, check=True, capture_output=True, timeout=5.0) + _run_tmux_sync_bounded(argv, timeout=5.0) except subprocess.TimeoutExpired as e: msg = f"delete-buffer timeout after 5s for {cname!r}" raise ExpectedToolError(msg) from e diff --git a/src/libtmux_mcp/tools/pane_tools/io.py b/src/libtmux_mcp/tools/pane_tools/io.py index e534c876..68358f57 100644 --- a/src/libtmux_mcp/tools/pane_tools/io.py +++ b/src/libtmux_mcp/tools/pane_tools/io.py @@ -14,8 +14,14 @@ import uuid from fastmcp.exceptions import ToolError +from libtmux import exc -from libtmux_mcp._tmux_proc import _run_tmux_bounded +from libtmux_mcp._tmux_proc import ( + _prepare_bounded, + _remaining, + _run_tmux_bounded, + _run_tmux_sync_bounded, +) from libtmux_mcp._utils import ( ExpectedToolError, _get_server, @@ -58,12 +64,7 @@ def _run_timed_send_keys_argv( ) -> None: """Run one ``tmux send-keys`` argv within the batch deadline.""" try: - subprocess.run( - argv, - check=True, - capture_output=True, - timeout=_remaining_timeout(deadline, timeout), - ) + _run_tmux_sync_bounded(argv, timeout=_remaining_timeout(deadline, timeout)) except subprocess.TimeoutExpired as e: raise ExpectedToolError(_batch_timeout_error(timeout)) from e except subprocess.CalledProcessError as e: @@ -395,6 +396,8 @@ async def run_command( msg = "timeout must be positive" raise ExpectedToolError(msg) effective_timeout = min(timeout, _wait_ceiling_seconds()) + started = time.monotonic() + deadline = started + effective_timeout server = _get_server(socket_name=socket_name) pane = _resolve_pane( @@ -411,10 +414,17 @@ async def run_command( if target_pane_id is None: msg = "resolved pane has no pane_id" raise ExpectedToolError(msg) - status_cmd = shlex.join( - _tmux_argv(server, "set-option", "-p", "-t", target_pane_id, status_option) + # These are library-owned child commands, so they carry the version check too. + status_argv, status_marker = await _prepare_bounded( + _tmux_argv(server, "set-option", "-p", "-t", target_pane_id, status_option), + deadline, ) - signal_cmd = shlex.join(_tmux_argv(server, "wait-for", "-S", channel)) + signal_argv, signal_marker = await _prepare_bounded( + _tmux_argv(server, "wait-for", "-S", channel), deadline + ) + fences = [marker for marker in (status_marker, signal_marker) if marker] + status_cmd = shlex.join(status_argv) + signal_cmd = shlex.join(signal_argv) history_prefix = " " if suppress_history else "" payload = "\n".join( ( @@ -424,7 +434,7 @@ async def run_command( ) ) - started = time.monotonic() + _remaining(deadline) await asyncio.to_thread(pane.send_keys, payload, enter=True, literal=True) timed_out = False @@ -442,7 +452,7 @@ async def run_command( stderr_bytes = b"" try: returncode, _stdout, stderr_bytes = await _run_tmux_bounded( - wait_argv, timeout=effective_timeout + wait_argv, timeout=_remaining(deadline) ) except TimeoutError: timed_out = True @@ -460,6 +470,7 @@ async def run_command( try: exit_status = int(status_text) except ValueError as e: + await _raise_if_fence_refused(pane, fences) msg = f"run_command could not read exit status from {status_option!r}" raise ExpectedToolError(msg) from e with contextlib.suppress(Exception): @@ -469,6 +480,8 @@ async def run_command( # filter's exact-marker match survives a wide prompt; it also strips # sync fragments that still wrap across rows. raw_lines = await asyncio.to_thread(pane.capture_pane, join_wrapped=True) + if timed_out: + _raise_if_fenced_refusal(raw_lines, fences) visible_lines = _filter_run_command_internal_lines( raw_lines, channel=channel, @@ -487,6 +500,26 @@ async def run_command( ) +def _raise_if_fenced_refusal(lines: list[str], fences: list[str]) -> None: + """Raise VersionTooLow if a typed, version-fenced command was refused. + + The fenced status and signal commands are typed into the pane, so a daemon + replaced before the user's command finished makes tmux print + ``unknown command: `` there and run neither: no status is stored + and the channel is never signalled. Without this check the caller sees an + ordinary timeout. + """ + refused = {f"unknown command: {marker}" for marker in fences} + if any(line.strip() in refused for line in lines): + msg = "tmux daemon changed before run_command could report its result" + raise exc.VersionTooLow(msg) + + +async def _raise_if_fence_refused(pane: Pane, fences: list[str]) -> None: + lines = await asyncio.to_thread(pane.capture_pane, join_wrapped=True) + _raise_if_fenced_refusal(lines, fences) + + #: Default line cap applied to :func:`capture_pane` and similar scrollback #: readers. Large enough to cover typical prompt + a few screens of output, #: small enough that a pathological pane (e.g. 50K lines of ``tail -f``) @@ -786,7 +819,7 @@ def paste_text( load_args = _tmux_argv(server, "load-buffer", "-b", buffer_name, tmppath) try: - subprocess.run(load_args, check=True, capture_output=True, timeout=5.0) + _run_tmux_sync_bounded(load_args, timeout=5.0) except subprocess.TimeoutExpired as e: msg = f"load-buffer timeout after 5s for {buffer_name!r}" raise ExpectedToolError(msg) from e diff --git a/src/libtmux_mcp/tools/wait_for_tools.py b/src/libtmux_mcp/tools/wait_for_tools.py index f987facc..2395610d 100644 --- a/src/libtmux_mcp/tools/wait_for_tools.py +++ b/src/libtmux_mcp/tools/wait_for_tools.py @@ -35,9 +35,7 @@ from __future__ import annotations -import asyncio import re -import subprocess import typing as t from libtmux_mcp._tmux_proc import _run_tmux_bounded @@ -282,32 +280,21 @@ async def signal_channel( server = _get_server(socket_name=socket_name) cname = _validate_channel_name(channel) argv = _tmux_argv(server, "wait-for", "-S", cname) - # Deliberately still a worker thread, unlike every other tmux call - # in this package. The orphan-on-cancel defect that pushed the - # waits onto ``_run_tmux_bounded`` needs a child that blocks for a - # caller-chosen duration; ``wait-for -S`` does not block, so the - # worst case here is a 5 s child - # against an already-wedged tmux — and that bound is ours, not the - # caller's. Converting it would buy nothing and change this tool's - # error messages. try: - await asyncio.to_thread( - subprocess.run, - argv, - check=True, - capture_output=True, - timeout=_SIGNAL_TIMEOUT_SECONDS, + returncode, _stdout, stderr_bytes = await _run_tmux_bounded( + argv, timeout=_SIGNAL_TIMEOUT_SECONDS ) - except subprocess.TimeoutExpired as e: + except TimeoutError as e: msg = ( f"signal-channel timeout after {_SIGNAL_TIMEOUT_SECONDS}s: " f"channel {cname!r}" ) raise ExpectedToolError(msg) from e - except subprocess.CalledProcessError as e: - stderr = e.stderr.decode(errors="replace").strip() if e.stderr else "" - msg = f"signal-channel failed for channel {cname!r}: {stderr or e}" - raise ExpectedToolError(msg) from e + if returncode != 0: + stderr = stderr_bytes.decode(errors="replace").strip() + detail = stderr or f"exit {returncode}" + msg = f"signal-channel failed for channel {cname!r}: {detail}" + raise ExpectedToolError(msg) return f"Channel {cname!r} signalled" diff --git a/tests/test_history.py b/tests/test_history.py index ebc99e69..b3258d15 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -829,7 +829,7 @@ def _run(argv: list[str], **kwargs: t.Any) -> subprocess.CompletedProcess[str]: pane = FakePane() monkeypatch.setattr(io, "_get_server", lambda **kwargs: FakeServer()) monkeypatch.setattr(io, "_resolve_pane", lambda *args, **kwargs: pane) - monkeypatch.setattr("libtmux_mcp.tools.pane_tools.io.subprocess.run", _run) + monkeypatch.setattr(io, "_run_tmux_sync_bounded", _run) async def _exercise() -> None: async with Client(_history_server("1")) as client: @@ -910,9 +910,10 @@ def _run(argv: list[str], **kwargs: t.Any) -> subprocess.CompletedProcess[str]: pane = FakePane() monkeypatch.setattr(io, "_get_server", lambda **kwargs: server) monkeypatch.setattr(io, "_resolve_pane", lambda *args, **kwargs: pane) - monkeypatch.setattr("libtmux_mcp.tools.pane_tools.io.subprocess.run", _run) + monkeypatch.setattr(io, "_run_tmux_sync_bounded", _run) monkeypatch.setattr(buffer_tools, "_get_server", lambda **kwargs: server) monkeypatch.setattr(buffer_tools, "_resolve_pane", lambda *args, **kwargs: pane) + monkeypatch.setattr(buffer_tools, "_run_tmux_sync_bounded", _run) raw_text = "C-c\npartial TUI text\n" existing_buffer = f"libtmux_mcp_{'a' * 32}_buf" diff --git a/tests/test_pane_tools.py b/tests/test_pane_tools.py index d898b1a9..8745060b 100644 --- a/tests/test_pane_tools.py +++ b/tests/test_pane_tools.py @@ -407,7 +407,7 @@ def timed_send_keys( return subprocess.CompletedProcess(args=["tmux"], returncode=0) monkeypatch.setattr( - "libtmux_mcp.tools.pane_tools.io.subprocess.run", + "libtmux_mcp.tools.pane_tools.io._run_tmux_sync_bounded", timed_send_keys, ) @@ -456,7 +456,9 @@ def timed_out_run(*args: t.Any, **kwargs: t.Any) -> t.NoReturn: raise subprocess.TimeoutExpired(cmd="tmux", timeout=timeout) monkeypatch.setattr(Pane, "send_keys", stalled_send_keys) - monkeypatch.setattr("libtmux_mcp.tools.pane_tools.io.subprocess.run", timed_out_run) + monkeypatch.setattr( + "libtmux_mcp.tools.pane_tools.io._run_tmux_sync_bounded", timed_out_run + ) result = send_keys_batch( operations=[ @@ -534,6 +536,48 @@ def test_run_command_reports_exit_status( assert any(expected_output in line for line in result.output) +def test_run_command_surfaces_a_fence_refusal_as_version_too_low( + mcp_server: Server, mcp_pane: Pane, monkeypatch: pytest.MonkeyPatch +) -> None: + """A refused typed fence reads as a version error, not as a timeout.""" + import asyncio + + from libtmux_mcp._tmux_proc import _prepare_bounded as prepare + from libtmux_mcp.tools.pane_tools import run_command + + async def refused(argv: list[str], deadline: float) -> tuple[list[str], str | None]: + prepared, marker = await prepare(argv, deadline) + # Make the typed command fail its version condition, as a replaced + # daemon would. + return [ + item.replace("#{==:#{version},", "#{==:#{version},replaced-") + for item in prepared + ], marker + + monkeypatch.setattr("libtmux_mcp.tools.pane_tools.io._prepare_bounded", refused) + with pytest.raises(ToolError, match="changed before run_command"): + asyncio.run( + run_command( + command="true", + pane_id=mcp_pane.pane_id, + timeout=1.5, + socket_name=mcp_server.socket_name, + ) + ) + + +def test_fenced_refusal_lines_raise_version_too_low() -> None: + """Only the private markers of this call's fenced commands count.""" + from libtmux import exc + + from libtmux_mcp.tools.pane_tools.io import _raise_if_fenced_refusal + + marker = "libtmux-mcp-version-abc" + _raise_if_fenced_refusal(["unknown command: other", "$"], [marker]) + with pytest.raises(exc.VersionTooLow, match="changed before run_command"): + _raise_if_fenced_refusal(["$ ", f"unknown command: {marker} "], [marker]) + + def test_run_command_timeout_reports_without_killing_shell( mcp_server: Server, mcp_pane: Pane ) -> None: @@ -624,8 +668,8 @@ def _run_command_wait_pids(socket_name: str) -> list[int]: mints a random ``r_`` channel per call, hence the prefix match rather than an exact name. - The argv must be the whole five-token vector and ``/proc//exe`` - must resolve to tmux, so a shell (or pytest) whose command line + The argv must select this socket and end in its wait command; + ``/proc//exe`` must resolve to tmux, so a shell whose command line merely mentions the socket cannot register as a hit; this process is skipped outright for the same reason. Reaped children are gone from ``/proc`` and zombies have an empty ``cmdline``, so neither @@ -645,9 +689,13 @@ def _run_command_wait_pids(socket_name: str) -> list[int]: except OSError: continue # process exited, or not ours to inspect argv = [chunk.decode(errors="replace") for chunk in raw.split(b"\0") if chunk] - if len(argv) != 5 or argv[1:4] != ["-L", socket_name, "wait-for"]: + if len(argv) < 5 or argv[1:3] != ["-L", socket_name]: continue - if not argv[4].startswith("r_") or exe.name != "tmux": + if ( + argv[-2] != "wait-for" + or not argv[-1].startswith("r_") + or exe.name != "tmux" + ): continue pids.append(pid) return pids @@ -1948,12 +1996,12 @@ def test_respawn_pane_preserves_pane_id_and_refreshes_pid( def test_respawn_pane_replaces_shell(mcp_server: Server, mcp_session: Session) -> None: """respawn_pane with ``shell`` relaunches with the new command.""" window = mcp_session.active_window - new_pane = window.split(shell="sleep 3600") + new_pane = window.split(shell="exec sleep 3600") assert new_pane.pane_id is not None result = respawn_pane( pane_id=new_pane.pane_id, - shell="sleep 7200", + shell="exec sleep 7200", socket_name=mcp_server.socket_name, ) assert result.pane_id == new_pane.pane_id @@ -3020,7 +3068,7 @@ class WaitForTextFixture(t.NamedTuple): # Regression for #45: pre-existing scrollback must NOT match. WaitForTextFixture( test_id="stale_scrollback_does_not_match", - pre_command="echo WAIT_MARKER_stale", + pre_command=r"printf '\nWAIT_MARKER_stale\n'", patterns=["WAIT_MARKER_stale"], timeout=0.5, expected_found=False, @@ -4973,7 +5021,16 @@ def test_run_tmux_lines_happy_path_returns_without_kill( from libtmux_mcp.tools.pane_tools import wait as wait_mod stub = tmp_path / "tmux" - stub.write_text("#!/bin/sh\nprintf 'alpha\\nbeta\\n'\n") + stub.write_text( + "#!/bin/sh\n" + "for argument do\n" + " case \"$argument\" in *'#{version}')\n" + " printf 'unknown command: %s3.7d\\n' \"${argument%'#{version}'}\" >&2\n" + " exit 1;;\n" + " esac\n" + "done\n" + "printf 'alpha\\nbeta\\n'\n" + ) stub.chmod(0o755) class _StubServer: diff --git a/tests/test_server.py b/tests/test_server.py index 8050e336..efa252d4 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -1110,6 +1110,36 @@ async def _enter() -> None: asyncio.run(_enter()) +def test_lifespan_unsupported_default_endpoint_only_warns( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """Tools check each endpoint per call, so startup must not stop the server.""" + import asyncio + + from libtmux import exc + + from libtmux_mcp import server as server_module + from libtmux_mcp.server import _lifespan, mcp + + async def unsupported(*args: object, **kwargs: object) -> t.NoReturn: + msg = "libtmux requires tmux 3.3a or newer; endpoint reports '3.2a'" + raise exc.VersionTooLow(msg) + + monkeypatch.setattr(server_module, "_prepare_bounded", unsupported) + entered = False + + async def run() -> None: + nonlocal entered + async with _lifespan(mcp): + entered = True + + with caplog.at_level("WARNING", logger="libtmux_mcp.server"): + asyncio.run(run()) + assert entered + assert "default tmux endpoint is not usable" in caplog.text + assert "3.2a" in caplog.text + + def test_lifespan_clears_server_cache_on_exit() -> None: """Clean lifespan exit drops cached clients without touching tmux.""" import asyncio diff --git a/tests/test_server_tools.py b/tests/test_server_tools.py index 525668d0..a9784258 100644 --- a/tests/test_server_tools.py +++ b/tests/test_server_tools.py @@ -2,7 +2,6 @@ from __future__ import annotations -import os import pathlib import typing as t @@ -421,12 +420,10 @@ def test_list_servers_extra_socket_paths_surfaces_custom_path( """ from libtmux_mcp.models import ServerInfo - monkeypatch.setenv("TMUX_TMPDIR", str(tmp_path)) - fixture_socket = ( - pathlib.Path("/tmp") - / f"tmux-{os.geteuid()}" - / (mcp_server.socket_name or "default") + fixture_socket = pathlib.Path( + mcp_server.cmd("display-message", "-p", "#{socket_path}").stdout[0] ) + monkeypatch.setenv("TMUX_TMPDIR", str(tmp_path)) assert fixture_socket.is_socket(), "fixture socket must exist for the test" results = list_servers(extra_socket_paths=[str(fixture_socket)]) diff --git a/tests/test_tmux_versions.py b/tests/test_tmux_versions.py new file mode 100644 index 00000000..4eaaca4f --- /dev/null +++ b/tests/test_tmux_versions.py @@ -0,0 +1,342 @@ +"""Version checks for MCP-owned tmux subprocesses, replacement and cancellation.""" + +from __future__ import annotations + +import asyncio +import os +import pathlib +import shlex +import shutil +import subprocess +import sys +import time +import types + +import pytest +from libtmux import exc + +from libtmux_mcp import _tmux_proc + + +@pytest.fixture(autouse=True) +def _fresh_version_cache() -> None: + """Start each test without a remembered release.""" + _tmux_proc._VERSION_CACHE.clear() + + +def _binary(variable: str, expected: str) -> str: + value = os.environ.get(variable) + if value is None: + pytest.skip(f"set {variable} to native tmux {expected}") + report = subprocess.run([value, "-V"], capture_output=True, timeout=5, check=True) + assert report.stdout == f"tmux {expected}\n".encode() + return value + + +def _native( + binary: str, socket: pathlib.Path, *argv: str +) -> subprocess.CompletedProcess[bytes]: + return subprocess.run( + [binary, "-N", "-S", str(socket), *argv], + capture_output=True, + timeout=5, + check=False, + ) + + +def _start(binary: str, socket: pathlib.Path) -> None: + result = subprocess.run( + [ + binary, + "-f", + "/dev/null", + "-S", + str(socket), + "new-session", + "-d", + "exec sleep 120", + ], + capture_output=True, + timeout=5, + check=False, + ) + assert result.returncode == 0, result.stderr + + +@pytest.mark.parametrize("name", ["tmux with spaces", " tmux with spaces"]) +def test_native_minimum_owned_subprocesses(tmp_path: pathlib.Path, name: str) -> None: + """Both owned lanes retain native output and a literal trailing semicolon.""" + binary = _binary("LIBTMUX_TEST_MINIMUM_TMUX", "3.3a") + renamed = tmp_path / name + renamed.symlink_to(binary) + socket = tmp_path / "s" + try: + result = _tmux_proc._run_tmux_sync_bounded( + [str(renamed), "-S", str(socket), "new-session", "-d", "exec sleep 120"], + timeout=3, + ) + assert result.returncode == 0 + argv = [str(renamed), "-S", str(socket), "display-message", "-p", "literal;"] + assert ( + _tmux_proc._run_tmux_sync_bounded(argv, timeout=3).stdout == b"literal;\n" + ) + assert asyncio.run(_tmux_proc._run_tmux_bounded(argv, timeout=3)) == ( + 0, + b"literal;\n", + b"", + ) + finally: + _native(binary, socket, "kill-server") + + +@pytest.mark.parametrize("source", ["minimum", "path"]) +def test_version_check_fires_no_user_hooks(tmp_path: pathlib.Path, source: str) -> None: + """Neither owned lane lets the version probe run a user's hooks.""" + if source == "minimum": + binary = os.environ.get("LIBTMUX_TEST_MINIMUM_TMUX") + else: + binary = shutil.which("tmux") + if binary is None: + pytest.skip(f"no tmux for the {source} lane") + socket = tmp_path / "s" + _start(binary, socket) + + def native(*argv: str) -> subprocess.CompletedProcess[bytes]: + return _native(binary, socket, *argv) + + try: + assert ( + native("set-hook", "-g", "after-display-message", "set -ag @a x").returncode + == 0 + ) + # command-error only exists on 3.5+; older releases refuse the hook. + has_error = ( + native("set-hook", "-g", "command-error", "set -ag @e y").returncode == 0 + ) + argv = [binary, "-S", str(socket), "list-sessions"] + _tmux_proc._run_tmux_sync_bounded(argv, timeout=3) + asyncio.run(_tmux_proc._run_tmux_bounded(argv, timeout=3)) + + # Hooks run in order, so a control fired after the probes shows that + # none of them left a mark: each sentinel holds exactly one letter. + native("display-message", "-p", "control") + if has_error: + assert native("kill-session", "-t", "=missing").returncode != 0 + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + after = native("show-options", "-gqv", "@a").stdout.strip() + error = native("show-options", "-gqv", "@e").stdout.strip() + if after == b"x" and (error == b"y" or not has_error): + break + time.sleep(0.05) + assert native("show-options", "-gqv", "@a").stdout.strip() == b"x" + if has_error: + assert native("show-options", "-gqv", "@e").stdout.strip() == b"y" + finally: + native("kill-server") + + +@pytest.mark.parametrize( + ("variable", "release"), + [ + ("LIBTMUX_TEST_UNSUPPORTED_TMUX", "3.2a"), + ("LIBTMUX_TEST_UNPATCHED_TMUX", "3.3"), + ], +) +def test_old_daemon_refuses_owned_writes( + tmp_path: pathlib.Path, variable: str, release: str +) -> None: + """A newer executable cannot authorize writes on an older live daemon.""" + binary = _binary("LIBTMUX_TEST_MINIMUM_TMUX", "3.3a") + old = _binary(variable, release) + socket = tmp_path / "s" + _start(old, socket) + argv = [binary, "-S", str(socket), "set-option", "-g", "@forbidden", "changed"] + try: + with pytest.raises(exc.VersionTooLow): + _tmux_proc._run_tmux_sync_bounded(argv, timeout=3) + with pytest.raises(exc.VersionTooLow): + asyncio.run(_tmux_proc._run_tmux_bounded(argv, timeout=3)) + assert _native(old, socket, "show-options", "-gqv", "@forbidden").stdout == b"" + finally: + _native(old, socket, "kill-server") + + +@pytest.mark.parametrize( + ("variable", "release"), + [ + ("LIBTMUX_TEST_UNSUPPORTED_TMUX", "3.2a"), + ("LIBTMUX_TEST_UNPATCHED_TMUX", "3.3"), + ], +) +def test_old_executable_does_not_start_an_endpoint( + tmp_path: pathlib.Path, variable: str, release: str +) -> None: + """A cold version check preserves patch letters before new-session can run.""" + old = _binary(variable, release) + socket = tmp_path / "s" + argv = [old, "-S", str(socket), "new-session", "-d", "exec sleep 120"] + with pytest.raises(exc.VersionTooLow): + _tmux_proc._run_tmux_sync_bounded(argv, timeout=3) + with pytest.raises(exc.VersionTooLow): + asyncio.run(_tmux_proc._run_tmux_bounded(argv, timeout=3)) + assert not socket.exists() + + +def test_incompatible_backend_refuses_before_spawning( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An uncoordinated package cannot authorize either owned process lane.""" + monkeypatch.setitem( + sys.modules, + "libtmux._internal.support", + types.ModuleType("libtmux._internal.support"), + ) + + def forbidden(*args: object, **kwargs: object) -> None: + pytest.fail("incompatible backend reached subprocess creation") + + monkeypatch.setattr(subprocess, "run", forbidden) + monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden) + with pytest.raises(exc.LibTmuxException, match="Unsupported libtmux backend"): + _tmux_proc._run_tmux_sync_bounded(["tmux", "list-sessions"], timeout=1) + with pytest.raises(exc.LibTmuxException, match="Unsupported libtmux backend"): + asyncio.run(_tmux_proc._run_tmux_bounded(["tmux", "list-sessions"], timeout=1)) + + +def test_probe_failure_is_a_library_exception(monkeypatch: pytest.MonkeyPatch) -> None: + """A failed probe is an expected tool error, not an unexpected RuntimeError.""" + + async def failing(argv: list[str], *, timeout: float) -> tuple[int, bytes, bytes]: + return 1, b"", b"permission denied\n" + + monkeypatch.setattr(_tmux_proc, "_run_tmux_unchecked", failing) + with pytest.raises(exc.LibTmuxException, match="permission denied"): + asyncio.run(_tmux_proc._run_tmux_bounded(["tmux", "list-sessions"], timeout=1)) + + def failing_sync( + argv: list[str], **kwargs: object + ) -> subprocess.CompletedProcess[bytes]: + return subprocess.CompletedProcess(argv, 1, b"", b"permission denied\n") + + monkeypatch.setattr(subprocess, "run", failing_sync) + with pytest.raises(exc.LibTmuxException, match="permission denied"): + _tmux_proc._run_tmux_sync_bounded(["tmux", "list-sessions"], timeout=1) + + +def test_replacement_after_probe_preserves_state( + tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The final native guard refuses a replacement before the requested effect.""" + binary = _binary("LIBTMUX_TEST_MINIMUM_TMUX", "3.3a") + old = _binary("LIBTMUX_TEST_UNSUPPORTED_TMUX", "3.2a") + socket = tmp_path / "s" + _start(binary, socket) + original = asyncio.create_subprocess_exec + replaced = False + + async def replace(*argv: str, **kwargs: object) -> asyncio.subprocess.Process: + nonlocal replaced + if "set-option" in argv: + assert not replaced + replaced = True + _native(binary, socket, "kill-server") + _start(old, socket) + return await original(*argv, **kwargs) # type: ignore[arg-type] + + monkeypatch.setattr(asyncio, "create_subprocess_exec", replace) + try: + argv = [binary, "-S", str(socket), "set-option", "-g", "@forbidden", "changed"] + with pytest.raises(exc.VersionTooLow): + asyncio.run(_tmux_proc._run_tmux_bounded(argv, timeout=3)) + assert replaced + assert _native(old, socket, "show-options", "-gqv", "@forbidden").stdout == b"" + finally: + _native(binary, socket, "kill-server") + _native(old, socket, "kill-server") + + +@pytest.mark.parametrize("cancel", [False, True]) +def test_version_check_budget_and_cancellation_reap_child( + tmp_path: pathlib.Path, cancel: bool +) -> None: + """Slow metadata consumes the same budget and remains owned on cancellation.""" + wrapper = tmp_path / "blocked-probe" + pid_file = tmp_path / "pid" + wrapper.write_text( + f'#!/bin/sh\nprintf "%s" "$$" > {shlex.quote(str(pid_file))}\nexec sleep 120\n' + ) + wrapper.chmod(0o700) + + async def drive() -> None: + started = time.monotonic() + task = asyncio.create_task( + _tmux_proc._run_tmux_bounded( + [str(wrapper), "list-sessions"], timeout=0.2 if not cancel else 3 + ) + ) + if cancel: + deadline = time.monotonic() + 2 + while not pid_file.exists() or not pid_file.read_text(): + assert time.monotonic() < deadline, "metadata child did not start" + await asyncio.sleep(0.005) + task.cancel() + with pytest.raises(asyncio.CancelledError if cancel else TimeoutError): + await task + assert time.monotonic() - started < 1.5 + pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + os.kill(pid, 0) + + asyncio.run(drive()) + + +def test_checked_release_is_probed_once_per_endpoint( + tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Later calls reuse the release; a refusal or a gone daemon probes again.""" + binary = _binary("LIBTMUX_TEST_MINIMUM_TMUX", "3.3a") + socket = tmp_path / "s" + _start(binary, socket) + probes: list[list[str]] = [] + real = subprocess.run + + def counted(argv: list[str], *args: object, **kwargs: object) -> object: + if "run-shell" in argv and "-C" in argv: + probes.append(argv) + return real(argv, *args, **kwargs) # type: ignore[call-overload] + + monkeypatch.setattr(subprocess, "run", counted) + argv = [binary, "-S", str(socket), "list-sessions"] + try: + for _ in range(3): + _tmux_proc._run_tmux_sync_bounded(argv, timeout=3) + assert asyncio.run(_tmux_proc._run_tmux_bounded(argv, timeout=3))[0] == 0 + assert len(probes) == 1 + _native(binary, socket, "kill-server") + # The cached daemon is gone: the call checks the version again instead + # of failing with a stale release, and the endpoint is not cached while + # absent. + result = _tmux_proc._run_tmux_sync_bounded(argv, timeout=3, check=False) + assert result.returncode != 0 + assert not _tmux_proc._VERSION_CACHE + finally: + _native(binary, socket, "kill-server") + + +def test_stale_cached_release_is_refused_and_forgotten(tmp_path: pathlib.Path) -> None: + """A cached release that no longer matches the daemon fails the fence.""" + binary = _binary("LIBTMUX_TEST_MINIMUM_TMUX", "3.3a") + socket = tmp_path / "s" + _start(binary, socket) + argv = [binary, "-S", str(socket), "set-option", "-g", "@stale", "ran"] + try: + _tmux_proc._VERSION_CACHE[ + _tmux_proc._endpoint_key(binary, ["-S", str(socket)]) + ] = "3.99" + with pytest.raises(exc.VersionTooLow): + _tmux_proc._run_tmux_sync_bounded(argv, timeout=3) + assert not _tmux_proc._VERSION_CACHE + assert _native(binary, socket, "show-options", "-gqv", "@stale").stdout == b"" + finally: + _native(binary, socket, "kill-server") diff --git a/tests/test_utils.py b/tests/test_utils.py index 2e0222ca..03b4d9d6 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -45,8 +45,7 @@ def test_get_server_caches(monkeypatch: pytest.MonkeyPatch) -> None: """_get_server returns the same instance for the same socket.""" _server_cache.clear() s1 = _get_server(socket_name="test_cache") - # Simulate a live server so the cache is not evicted - monkeypatch.setattr(s1, "is_alive", lambda: True) + monkeypatch.setattr(s1, "is_alive", lambda: pytest.fail("cache lookup probed tmux")) s2 = _get_server(socket_name="test_cache") assert s1 is s2 # Verify 3-tuple cache key includes tmux_bin @@ -143,14 +142,15 @@ def test_serialize_pane(mcp_pane: Pane) -> None: assert data.session_id is not None -def test_get_server_evicts_dead(monkeypatch: pytest.MonkeyPatch) -> None: - """_get_server evicts cached server when is_alive returns False.""" +def test_get_server_retains_configuration_without_liveness_probe( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Cached configuration stays pure; dispatch owns the endpoint version check.""" _server_cache.clear() s1 = _get_server(socket_name="test_evict") - # Patch is_alive to return False to simulate a dead server - monkeypatch.setattr(s1, "is_alive", lambda: False) + monkeypatch.setattr(s1, "is_alive", lambda: pytest.fail("cache lookup probed tmux")) s2 = _get_server(socket_name="test_evict") - assert s1 is not s2 + assert s1 is s2 def test_invalidate_server() -> None: diff --git a/tests/test_wait_for_tools.py b/tests/test_wait_for_tools.py index d0aa70f3..24b42b9c 100644 --- a/tests/test_wait_for_tools.py +++ b/tests/test_wait_for_tools.py @@ -428,9 +428,8 @@ def _tmux_wait_pids(socket_name: str, channel: str) -> list[int]: produce a false positive. Reaped children are absent from ``ps`` and zombies render as ``[tmux] ``, which does not match. """ - want = ["tmux", "-L", socket_name, "wait-for", channel] listing = subprocess.run( - ["ps", "-eo", "pid=,args="], + ["ps", "-eww", "-o", "pid=,args="], capture_output=True, text=True, check=True, @@ -441,13 +440,21 @@ def _tmux_wait_pids(socket_name: str, channel: str) -> list[int]: pid_field, _, args = line.strip().partition(" ") if not pid_field.isdigit() or int(pid_field) == me: continue - if args.split() == want: + argv = args.split() + if ( + len(argv) >= 5 + and pathlib.Path(argv[0]).name == "tmux" + and argv[1:3] == ["-L", socket_name] + and argv[-2:] == ["wait-for", channel] + ): pids.append(int(pid_field)) return pids @pytest.mark.usefixtures("mcp_session") -def test_wait_for_channel_kills_tmux_child_on_cancel(mcp_server: Server) -> None: +def test_wait_for_channel_kills_tmux_child_on_cancel( + mcp_server: Server, monkeypatch: pytest.MonkeyPatch +) -> None: """A cancelled wait must not leave its ``tmux wait-for`` child running. ``asyncio.to_thread(subprocess.run, ...)`` is uninterruptible: the @@ -465,6 +472,7 @@ def test_wait_for_channel_kills_tmux_child_on_cancel(mcp_server: Server) -> None what this asserts. """ channel = "wf_cancel_reap_test" + monkeypatch.setenv("COLUMNS", "80") socket_name = mcp_server.socket_name assert socket_name is not None @@ -476,7 +484,9 @@ async def _drive() -> list[int]: socket_name=socket_name, ) ) - await asyncio.sleep(0.5) + deadline = time.monotonic() + 4.0 + while time.monotonic() < deadline and not _tmux_wait_pids(socket_name, channel): + await asyncio.sleep(0.01) assert _tmux_wait_pids(socket_name, channel), ( "no tmux wait-for child observed before the cancel — the probe " "is broken, so a later 'no survivors' result would be vacuous" diff --git a/uv.lock b/uv.lock index 81cc1cd3..260a8a00 100644 --- a/uv.lock +++ b/uv.lock @@ -4,8 +4,8 @@ requires-python = ">=3.10, <4.0" resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", "python_full_version < '3.11'", ] @@ -70,8 +70,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", ] dependencies = [ @@ -224,8 +224,8 @@ version = "0.22.9" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", "python_full_version < '3.11'", ] @@ -307,8 +307,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", ] sdist = { url = "https://files.pythonhosted.org/packages/56/51/bd8b64bf700f5b1a956a60bb62276b79a094e8cd0ddc60b1b61c3edd496f/caio-0.12.9.tar.gz", hash = "sha256:99e99419b44ab5511f7468c6a452887dd125b8e4042672a7589f0cf01d254ea8", size = 84084, upload-time = "2026-09-26T09:51:49.433Z" } @@ -900,8 +900,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", ] dependencies = [ @@ -1124,8 +1124,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", ] sdist = { url = "https://files.pythonhosted.org/packages/2b/27/b55f1a5278918be765fb2fd8b20966bc72bbdd3f789f031937cceea7834a/griffelib-2.3.2.tar.gz", hash = "sha256:df00c7a0dee3d86268d76788997a1859272cb1fb7b865658e043d2c0c3d52e60", size = 234729, upload-time = "2026-10-06T09:54:37.222Z" } @@ -1492,11 +1492,7 @@ wheels = [ [[package]] name = "libtmux" version = "0.62.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0c/b8/0410c8487f7673926d141a5aaaf60133984a564b3c90eb4f3f99e92e7740/libtmux-0.62.0.tar.gz", hash = "sha256:41e9e80602b2656fd119b13253b27bad46af5cfef32099be53cdd391e2936b61", size = 571757, upload-time = "2026-07-12T21:48:02.781Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/87/96/471ac01844ee157fe794446e17568e9bf219d323575c2acc7957a9a2d8c9/libtmux-0.62.0-py3-none-any.whl", hash = "sha256:626aa6fae45e3a423e1acc81604efafa63b7262b1d67b2c7a8778b1ad691456b", size = 127700, upload-time = "2026-07-12T21:48:01.52Z" }, -] +source = { git = "https://github.com/tmux-python/libtmux.git?rev=f6e4630a15f342382487a60e1e1477abcd52294d#f6e4630a15f342382487a60e1e1477abcd52294d" } [[package]] name = "libtmux-mcp" @@ -1562,7 +1558,7 @@ testing = [ [package.metadata] requires-dist = [ { name = "fastmcp", specifier = ">=4.0.2,<5.0.0" }, - { name = "libtmux", specifier = ">=0.62.0,<1.0" }, + { name = "libtmux", git = "https://github.com/tmux-python/libtmux.git?rev=f6e4630a15f342382487a60e1e1477abcd52294d" }, { name = "regex", specifier = ">=2024.11.6" }, ] @@ -1646,8 +1642,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", ] dependencies = [ @@ -1973,8 +1969,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", ] dependencies = [ @@ -2826,8 +2822,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", ] sdist = { url = "https://files.pythonhosted.org/packages/42/68/3bd46b8a5e01d3c2ebdf9c5e9497912e3fe0cde02bac21a7130ca866e403/rpds_py-2026.9.1.tar.gz", hash = "sha256:4793ef7f78268b124b73fa933440f01d258bbae01de9fa53e9080c9ab0425a12", size = 63948, upload-time = "2026-10-04T16:32:36.469Z" } @@ -3055,8 +3051,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", ] dependencies = [ @@ -3110,8 +3106,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", ] dependencies = [ @@ -3219,8 +3215,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", ] dependencies = [ @@ -3794,8 +3790,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", ] sdist = { url = "https://files.pythonhosted.org/packages/01/89/3f825ab71c242fffb62ea8fe638741c290f62f8d7aadf8125ff897747af3/websockets-17.2.tar.gz", hash = "sha256:36c2fb94c990cc2545143b12690e2de6c16300f9dbe5b4f33fa300cf57dc8792", size = 188355, upload-time = "2026-10-03T14:56:53.5Z" }