fix(tmux): non-blocking subprocess + stable pane indexing

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'.
This commit is contained in:
ai-chess
2026-05-15 02:33:26 +03:00
parent 51e63a8c7a
commit 2038ec95c9
3 changed files with 36 additions and 12 deletions
+3 -1
View File
@@ -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:
+9 -4
View File
@@ -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:
+24 -7
View File
@@ -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