From 2038ec95c99e3623a6cd2e7d8f4e4dcd763c2ac3 Mon Sep 17 00:00:00 2001 From: ai-chess Date: Fri, 15 May 2026 02:33:26 +0300 Subject: [PATCH] fix(tmux): non-blocking subprocess + stable pane indexing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two issues kept the deployed container from finishing the tmux rebuild: 1. asyncio's subprocess.communicate() blocked forever on `tmux new-session` and `tmux split-window` because the spawned pane child (pane-agent.sh → claude/codex) inherited the wrapper's stdout/stderr pipe fds and kept them open. _run() now uses DEVNULL for stdin/stdout/stderr by default (capture_stdout=True for the lone capture-pane call), and stderr is no longer collected — exit code is enough for upstream. 2. tmux re-indexes panes in layout-traversal order after every split, so the original 'split black off white horizontally, then split log off white vertically' sequence ended with indices 0=white, 1=log, 2=black — but the coordinator's pane_for hardcoded black=1, so prompts to codex landed on the log pane instead. Reorder: split log off the bottom of white FIRST (gives 0=white,1=log), THEN split black off the right of white (now indices 0=white,1=black,2=log, matching the hardcoded map). Plus a small docker-compose change: ~/.codex needs to be writable so codex can persist its history/session state — without rw the CLI exits immediately with 'Read-only file system'. --- docker-compose.yml | 4 +++- src/ai_chess/app.py | 13 +++++++++---- src/ai_chess/tmux.py | 31 ++++++++++++++++++++++++------- 3 files changed, 36 insertions(+), 12 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 24a121c..4cf77b5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -23,7 +23,9 @@ services: - ./config:/app/config # codex config + auth lives in /opt/chessai/secrets/codex on the host # and is mapped into the container's $CODEX_HOME (= ~/.codex by default). - - ./secrets/codex:/home/chess/.codex:ro + # codex writes its own session/history/logs inside ~/.codex, so the + # mount has to be rw — the auth.json itself is never rewritten. + - ./secrets/codex:/home/chess/.codex networks: caddy-network: diff --git a/src/ai_chess/app.py b/src/ai_chess/app.py index 3260fd4..db63e7f 100644 --- a/src/ai_chess/app.py +++ b/src/ai_chess/app.py @@ -207,16 +207,21 @@ def build_app(state: state_mod.AppState) -> FastAPI: print(f"[tmux] kill failed: {e}", flush=True) pane_script = str(state_mod.ROOT / "scripts" / "pane-agent.sh") log_file = state_mod.LOGS_DIR / "backend.log" + # NB: tmux assigns pane indices in layout traversal order (left→right, + # top→bottom). We want indices to settle as 0=white, 1=black, 2=log so + # the coordinator's pane_for={"white":0,"black":1} matches. To get + # that, split the LOG pane off the bottom *first*, then split white + # horizontally to add black to its right. try: await session.create_window_with_cmd(f"{pane_script} white") - await session.split_pane( - vertical=False, target_pane=0, - cmd=f"{pane_script} black", percentage=50, - ) await session.split_pane( vertical=True, target_pane=0, cmd=f"tail -F {log_file}", percentage=15, ) + await session.split_pane( + vertical=False, target_pane=0, + cmd=f"{pane_script} black", percentage=50, + ) print("[tmux] session 'chess' (re)created with fresh panes", flush=True) except Exception as e: diff --git a/src/ai_chess/tmux.py b/src/ai_chess/tmux.py index 9ca34fb..aaafcdc 100644 --- a/src/ai_chess/tmux.py +++ b/src/ai_chess/tmux.py @@ -10,14 +10,28 @@ class TmuxError(RuntimeError): pass -async def _run(*args: str) -> tuple[int, str, str]: +async def _run(*args: str, capture_stdout: bool = False) -> tuple[int, str, str]: + """Run a tmux command. tmux new-session and split-window leak inherited + fds into the pane's child process; if we attach pipes for stdout/stderr, + claude/codex keeps them open and communicate() blocks forever. Default + every fd to DEVNULL so the wait returns as soon as the tmux command + itself exits. Only capture-pane needs stdout (opt in via capture_stdout) + and we still don't read stderr — `code != 0` is enough signal upstream. + """ + stdout = asyncio.subprocess.PIPE if capture_stdout else asyncio.subprocess.DEVNULL proc = await asyncio.create_subprocess_exec( *args, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, + stdin=asyncio.subprocess.DEVNULL, + stdout=stdout, + stderr=asyncio.subprocess.DEVNULL, ) - out, err = await proc.communicate() - return proc.returncode or 0, out.decode("utf-8", "replace"), err.decode("utf-8", "replace") + out_b = b"" + if capture_stdout: + out_b = await proc.stdout.read() # type: ignore[union-attr] + await proc.wait() + return (proc.returncode or 0, + out_b.decode("utf-8", "replace"), + "") class TmuxSession: @@ -44,11 +58,14 @@ class TmuxSession: raise TmuxError(f"new-session failed: {err}") async def split_pane(self, *, vertical: bool, target_pane: int, cmd: str, percentage: int = 50) -> None: + # tmux ≥3.4 removed `-p N` in favour of `-l N%` / `-l N` ; on older + # tmux `-l` with a percentage form works too. The simpler portable + # call is `-l N%`. flag = "-v" if vertical else "-h" code, _, err = await _run( "tmux", "split-window", flag, - "-p", str(percentage), + "-l", f"{percentage}%", "-t", f"{self.name}:0.{target_pane}", cmd, ) @@ -109,7 +126,7 @@ class TmuxSession: args.insert(2, "-e") if history > 0: args.extend(["-S", f"-{history}"]) - code, out, err = await _run(*args) + code, out, err = await _run(*args, capture_stdout=True) if code != 0: raise TmuxError(f"capture-pane failed: {err}") return out