import asyncio import pytest import ai_chess.coordinator as coord_mod from ai_chess.chess_game import ChessGame from ai_chess.coordinator import Coordinator from ai_chess.sides import Side from ai_chess.state import AppState, AgentBinding @pytest.fixture(autouse=True) def _isolated_games_dir(tmp_path, monkeypatch): """Redirect save_game writes into a tmp directory so tests don't pollute games/.""" monkeypatch.setattr(coord_mod, "GAMES_DIR", tmp_path / "games") class FakeTmux: def __init__(self): self.calls: list[tuple] = [] async def submit(self, pane: int, text: str): self.calls.append(("submit", pane, text)) async def send_keys(self, pane: int, keys): self.calls.append(("send_keys", pane, list(keys))) @pytest.mark.asyncio async def test_first_prompt_white_on_start(): state = AppState() state.game = ChessGame(game_id="t1") state.bindings[Side.WHITE] = AgentBinding(Side.WHITE, "claude", "opus", "max") state.bindings[Side.BLACK] = AgentBinding(Side.BLACK, "codex", "gpt-5.5", "xhigh") fake = FakeTmux() coord = Coordinator(state, tmux=fake, pane_for={"white": 0, "black": 1}) await coord.dispatch_first_prompt() assert any(call[0] == "submit" and call[1] == 0 for call in fake.calls) text = next(c[2] for c in fake.calls if c[0] == "submit" and c[1] == 0) assert "белыми" in text @pytest.mark.asyncio async def test_on_move_sends_to_opponent(): state = AppState() state.game = ChessGame(game_id="t1") state.bindings[Side.WHITE] = AgentBinding(Side.WHITE, "claude", "opus", "max") state.bindings[Side.BLACK] = AgentBinding(Side.BLACK, "codex", "gpt-5.5", "xhigh") fake = FakeTmux() coord = Coordinator(state, tmux=fake, pane_for={"white": 0, "black": 1}) await coord.run_subscriber_step_once({ "type": "move", "side": "white", "san": "e4", "comment": "готовься", "fen": state.game.board.fen(), "ascii": str(state.game.board), }) assert any(c[0] == "submit" and c[1] == 1 for c in fake.calls) text = next(c[2] for c in fake.calls if c[0] == "submit" and c[1] == 1) assert "e4" in text assert "готовься" in text @pytest.mark.asyncio async def test_game_over_sends_summary_to_both(): state = AppState() state.game = ChessGame(game_id="t1") state.bindings[Side.WHITE] = AgentBinding(Side.WHITE, "claude", "opus", "max") state.bindings[Side.BLACK] = AgentBinding(Side.BLACK, "codex", "gpt-5.5", "xhigh") fake = FakeTmux() coord = Coordinator(state, tmux=fake, pane_for={"white": 0, "black": 1}) state.game.try_move(Side.WHITE, "f3") state.game.try_move(Side.BLACK, "e5") state.game.try_move(Side.WHITE, "g4") state.game.try_move(Side.BLACK, "Qh4") await coord.run_subscriber_step_once({ "type": "game_over", "result": "0-1", "termination": "checkmate", }) panes = sorted({c[1] for c in fake.calls if c[0] == "submit"}) assert panes == [0, 1]