diff --git a/src/ai_chess/tmux.py b/src/ai_chess/tmux.py new file mode 100644 index 0000000..8b36304 --- /dev/null +++ b/src/ai_chess/tmux.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import asyncio +import os +import tempfile +from typing import Iterable + + +class TmuxError(RuntimeError): + pass + + +async def _run(*args: str) -> tuple[int, str, str]: + proc = await asyncio.create_subprocess_exec( + *args, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + out, err = await proc.communicate() + return proc.returncode or 0, out.decode("utf-8", "replace"), err.decode("utf-8", "replace") + + +class TmuxSession: + def __init__(self, name: str): + self.name = name + + async def exists(self) -> bool: + code, _, _ = await _run("tmux", "has-session", "-t", self.name) + return code == 0 + + async def kill(self) -> None: + await _run("tmux", "kill-session", "-t", self.name) + + async def create_window_with_cmd(self, cmd: str, *, width: int = 220, height: int = 60) -> None: + if await self.exists(): + raise TmuxError(f"session {self.name!r} already exists") + code, _, err = await _run( + "tmux", "new-session", "-d", + "-s", self.name, + "-x", str(width), "-y", str(height), + cmd, + ) + if code != 0: + raise TmuxError(f"new-session failed: {err}") + + async def split_pane(self, *, vertical: bool, target_pane: int, cmd: str, percentage: int = 50) -> None: + flag = "-v" if vertical else "-h" + code, _, err = await _run( + "tmux", "split-window", + flag, + "-p", str(percentage), + "-t", f"{self.name}:0.{target_pane}", + cmd, + ) + if code != 0: + raise TmuxError(f"split-window failed: {err}") + + async def select_layout(self, layout: str) -> None: + await _run("tmux", "select-layout", "-t", f"{self.name}:0", layout) + + async def send_keys(self, pane: int, keys: Iterable[str]) -> None: + cmd = ["tmux", "send-keys", "-t", f"{self.name}:0.{pane}"] + cmd.extend(keys) + code, _, err = await _run(*cmd) + if code != 0: + raise TmuxError(f"send-keys failed: {err}") + + async def paste_text(self, pane: int, text: str) -> None: + """Load text into a tmux buffer and paste it into the pane. + + Uses a temp file so multiline / special chars / UTF-8 survive intact. + """ + with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False) as f: + f.write(text) + tmp = f.name + try: + buf = f"aichess-{os.getpid()}-{pane}" + code, _, err = await _run("tmux", "load-buffer", "-b", buf, tmp) + if code != 0: + raise TmuxError(f"load-buffer failed: {err}") + code, _, err = await _run("tmux", "paste-buffer", "-b", buf, "-t", f"{self.name}:0.{pane}") + if code != 0: + raise TmuxError(f"paste-buffer failed: {err}") + await _run("tmux", "delete-buffer", "-b", buf) + finally: + try: + os.unlink(tmp) + except OSError: + pass + + async def submit(self, pane: int, text: str) -> None: + """Paste text and press Enter to submit.""" + await self.paste_text(pane, text) + await self.send_keys(pane, ["Enter"]) + + async def capture_pane(self, pane: int, *, escape: bool = True, history: int = 0) -> str: + args = ["tmux", "capture-pane", "-p", "-t", f"{self.name}:0.{pane}"] + if escape: + args.insert(2, "-e") + if history > 0: + args.extend(["-S", f"-{history}"]) + code, out, err = await _run(*args) + if code != 0: + raise TmuxError(f"capture-pane failed: {err}") + return out diff --git a/tests/test_tmux.py b/tests/test_tmux.py new file mode 100644 index 0000000..014800e --- /dev/null +++ b/tests/test_tmux.py @@ -0,0 +1,54 @@ +import asyncio +import os +import tempfile + +import pytest + +from ai_chess.tmux import TmuxSession + + +@pytest.mark.asyncio +async def test_create_kill_session(): + s = TmuxSession("aichess-test-create") + try: + await s.kill() # idempotent + await s.create_window_with_cmd("cat > /tmp/aichess-test.out") + assert await s.exists() + finally: + await s.kill() + assert not await s.exists() + + +@pytest.mark.asyncio +async def test_paste_multiline(): + out = tempfile.NamedTemporaryFile(mode="w", suffix=".out", delete=False) + out.close() + s = TmuxSession("aichess-test-paste") + try: + await s.kill() + await s.create_window_with_cmd(f"cat > {out.name}") + await asyncio.sleep(0.2) + await s.paste_text(pane=0, text='многострочный\nтест с "кавычками" и $vars\nthird') + await s.send_keys(pane=0, keys=["C-d"]) + await asyncio.sleep(0.2) + with open(out.name) as f: + data = f.read() + assert "многострочный" in data + assert 'тест с "кавычками" и $vars' in data + assert "third" in data + finally: + await s.kill() + os.unlink(out.name) + + +@pytest.mark.asyncio +async def test_capture_pane(): + s = TmuxSession("aichess-test-capture") + try: + await s.kill() + await s.create_window_with_cmd("printf 'hello world\\n'; sleep 5") + await asyncio.sleep(0.4) + text = await s.capture_pane(pane=0) + assert "hello world" in text + finally: + await s.kill()