From c2d3a47d4bf6e31075498cf1a72361d9eaa18e4f Mon Sep 17 00:00:00 2001 From: ai-chess Date: Fri, 15 May 2026 01:31:55 +0300 Subject: [PATCH] feat: docker container + deploy on chess.danosito.com MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Container: - Dockerfile: python:3.12-slim with stockfish + tmux apt; src copied before pip install -e so the editable wheel actually finds ai_chess. fetch-vendor.sh runs at build time so the image is self-contained. - docker-compose.yml: two networks (default + caddy-network), alias 'chessai' on caddy-network, AI_CHESS_HOST=0.0.0.0 env so uvicorn listens on all interfaces (Caddy reverse-proxies over the network), volumes for games/, logs/, config/ to persist across rebuilds. - __main__.py reads AI_CHESS_HOST + AI_CHESS_PORT from env (falls back to 127.0.0.1:7833 for local dev). - .dockerignore excludes .git, .venv, runtime dirs, screenshots. - deploy/chess.danosito.com.caddy: site snippet, imports header_common, reverse_proxy chessai:7833. Live game UX fixes that landed alongside the deploy: - Snap viewPly to null on every move event so an accidental history-scrub no longer leaves the board locked; previously the only way out was a hard refresh. - movable.events.after wired in chessground constructor (instead of top-level events.move) so user moves are submitted only when they pass chessground's own legality check. - Hide stockfish entirely in human-vs-AI: no eval bar, no best-move arrow, no pv string. AI-vs-AI keeps the full spectator HUD. Coordinator / tmux: - New-game rebuilds the 'chess' tmux session from scratch so pane-agent.sh picks up the new bindings (different agent on a side / human side) instead of running with stale state. - /api/dispatch-first now queues the dispatch in a background task and sleeps 12 s first to let claude/codex finish booting inside the panes — paste-buffer was landing on a still-booting bash before. --- .dockerignore | 15 +++++++++ Dockerfile | 39 +++++++++++++++++++++++ deploy/chess.danosito.com.caddy | 4 +++ docker-compose.yml | 24 ++++++++++++++ public/app.js | 52 ++++++++++++++++++++---------- src/ai_chess/__main__.py | 6 +++- src/ai_chess/app.py | 56 +++++++++++++++++++++++++++++---- 7 files changed, 172 insertions(+), 24 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 deploy/chess.danosito.com.caddy create mode 100644 docker-compose.yml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..d292c8f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,15 @@ +.git +.venv +__pycache__ +*.pyc +*.pyo +.pytest_cache +games +logs +config +public/vendor +.playwright-mcp +.claude +*.png +*.log +node_modules diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5500335 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,39 @@ +# syntax=docker/dockerfile:1.7 +FROM python:3.12-slim AS base + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 + +# Runtime deps: stockfish for eval, tmux for the agent panes, curl for the +# in-container vendor fetch step. +RUN apt-get update && apt-get install -y --no-install-recommends \ + stockfish \ + tmux \ + curl \ + ca-certificates \ + procps \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app + +# Copy everything first — pip install -e needs src/ai_chess to exist at +# build time so the editable wheel can find the package. +COPY pyproject.toml README.md ./ +COPY src ./src +COPY public ./public +COPY scripts ./scripts +COPY docs ./docs + +# Python deps (editable install of the project itself + dev tools) +RUN pip install hatchling \ + && pip install -e ".[dev]" + +# Vendor JS/CSS at build time so the container is fully self-contained. +RUN chmod +x scripts/*.sh && ./scripts/fetch-vendor.sh + +# Runtime artefacts (games/, logs/, config/) — keep as named mountable dirs. +RUN mkdir -p games logs config + +EXPOSE 7833 +CMD ["python", "-m", "ai_chess"] diff --git a/deploy/chess.danosito.com.caddy b/deploy/chess.danosito.com.caddy new file mode 100644 index 0000000..c5a0376 --- /dev/null +++ b/deploy/chess.danosito.com.caddy @@ -0,0 +1,4 @@ +chess.danosito.com { + import header_common + reverse_proxy chessai:7833 +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..77aef6b --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,24 @@ +services: + chessai: + build: . + image: chessai:latest + container_name: chessai + restart: unless-stopped + environment: + AI_CHESS_HOST: "0.0.0.0" # listen on all interfaces inside the container + AI_CHESS_PORT: "7833" + networks: + default: + caddy-network: + aliases: + - chessai + # Persistent runtime data — survives container rebuilds. + volumes: + - ./games:/app/games + - ./logs:/app/logs + - ./config:/app/config + +networks: + caddy-network: + external: true + name: caddy-network diff --git a/public/app.js b/public/app.js index e4024d7..80175cc 100644 --- a/public/app.js +++ b/public/app.js @@ -40,18 +40,21 @@ const cg = Chessground($("board"), { viewOnly: false, fen: "start", orientation: "white", - movable: { free: false, color: undefined, dests: new Map(), showDests: true }, + movable: { + free: false, color: undefined, dests: new Map(), showDests: true, + events: { + after: (orig, dest) => { + // movable.events.after fires only on LEGAL completed user moves — + // perfect for submitting a human move to the server. + submitHumanMove(orig, dest); + }, + }, + }, draggable: { enabled: true, showGhost: true }, selectable: { enabled: true }, drawable: { enabled: true, visible: true }, - events: { - move: (orig, dest) => { - // Only used in human-vs-AI mode; AI-vs-AI sets movable.color to undefined, - // making this unreachable. - submitHumanMove(orig, dest); - }, - }, }); +window.cg = cg; // for debugging // ---------- responsive board sizing ---------- function fitBoard() { @@ -123,12 +126,6 @@ function renderBoard() { const uci = moves[idx].uci || ""; if (uci.length >= 4) lastMove = [uci.slice(0, 2), uci.slice(2, 4)]; } - const e = STATE.evalByFen.get(fenKey(fen)); - const shapes = (e && e.best_uci && e.best_uci.length >= 4) - ? [{ orig: e.best_uci.slice(0, 2), dest: e.best_uci.slice(2, 4), brush: "green" }] - : []; - - // Human-vs-AI: enable board moves only on the human's turn at the live FEN. const hSide = humanSide(); const sideToMove = STATE.game.side_to_move; const isHumanTurn = ( @@ -137,8 +134,16 @@ function renderBoard() { && !STATE.game.status?.result ); + // Stockfish hints are NOT shown to a human player — eval bar + best-move + // arrow would be cheating. They stay on for spectator (AI-vs-AI) games. + const showHints = !hSide; + const e = showHints ? STATE.evalByFen.get(fenKey(fen)) : null; + const shapes = (e && e.best_uci && e.best_uci.length >= 4) + ? [{ orig: e.best_uci.slice(0, 2), dest: e.best_uci.slice(2, 4), brush: "green" }] + : []; + const movable = isHumanTurn - ? { free: false, color: hSide, dests: legalDestsForFen(fen), showDests: true, events: {} } + ? { free: false, color: hSide, dests: legalDestsForFen(fen), showDests: true } : { free: false, color: undefined, dests: new Map(), showDests: false }; cg.set({ @@ -151,7 +156,14 @@ function renderBoard() { viewOnly: !isHumanTurn, }); $("live-btn").hidden = STATE.viewPly === null; - applyEvalForFen(fen); + if (showHints) { + applyEvalForFen(fen); + } else { + // Wipe any leftover eval visual from a prior spectator session. + $("eval-text").textContent = ""; + $("eval-fill").style.height = "50%"; + $("sf-pv").textContent = ""; + } } function renderChat() { @@ -345,6 +357,9 @@ function applySnapshot(s) { STATE.viewPly = null; STATE.evalByFen.clear(); for (const e of (s.evals || [])) storeEval(e); + // Hide the eval bar in human-vs-AI to avoid cheating. + const evalCol = $("eval-col"); + if (evalCol) evalCol.style.display = humanSide() ? "none" : ""; renderBoard(); renderChat(); renderHistory(); renderStatus(); refreshGamesLink(); } @@ -374,13 +389,16 @@ function connect() { if (!ev.status?.result) { STATE.game.side_to_move = ev.side === "white" ? "black" : "white"; } + // Always snap back to live on a new move — otherwise an accidental + // history-scrub leaves the board locked into a past position and the + // user can't make their next move without reloading. + STATE.viewPly = null; // think timer: mover finished, opponent starts if (THINK.startedAt != null && THINK.side === ev.side) { THINK.lastMs[ev.side] = Date.now() - THINK.startedAt; } THINK.startedAt = ev.status?.result ? null : Date.now(); THINK.side = ev.status?.result ? null : (ev.side === "white" ? "black" : "white"); - // stay live unless user clicked back renderBoard(); renderChat(); renderHistory(); renderStatus(); renderThinking(); log(`${ev.side} ${ev.san} «${ev.comment || ""}»`); return; diff --git a/src/ai_chess/__main__.py b/src/ai_chess/__main__.py index 7867cb1..3c19220 100644 --- a/src/ai_chess/__main__.py +++ b/src/ai_chess/__main__.py @@ -1,5 +1,7 @@ from __future__ import annotations +import os + import uvicorn from ai_chess.app import build_app @@ -7,8 +9,10 @@ from ai_chess.state import state def main() -> None: + host = os.environ.get("AI_CHESS_HOST", "127.0.0.1") + port = int(os.environ.get("AI_CHESS_PORT", "7833")) app = build_app(state) - uvicorn.run(app, host="127.0.0.1", port=7833, log_level="info") + uvicorn.run(app, host=host, port=port, log_level="info") if __name__ == "__main__": diff --git a/src/ai_chess/app.py b/src/ai_chess/app.py index 8e64c66..3260fd4 100644 --- a/src/ai_chess/app.py +++ b/src/ai_chess/app.py @@ -192,6 +192,36 @@ def build_app(state: state_mod.AppState) -> FastAPI: await state.events.publish({"type": "settings", "settings": state.settings.model_dump()}) return state.settings.model_dump() + async def _rebuild_tmux_panes() -> None: + """(Re)create the 'chess' tmux session with white + black + log panes. + Kills any existing session so pane-agent.sh re-runs with the new + bindings. Idempotent on subsequent calls.""" + runtime = getattr(state, "runtime", None) or {} + session = runtime.get("session") + if session is None: + return + try: + if await session.exists(): + await session.kill() + except Exception as e: + 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" + 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, + ) + print("[tmux] session 'chess' (re)created with fresh panes", + flush=True) + except Exception as e: + print(f"[tmux] create failed: {e}", flush=True) + @app.post("/api/new-game") async def new_game_post(body: dict[str, Any] | None = None) -> dict[str, Any]: # One game at a time — refuse if the current game hasn't finished. @@ -202,6 +232,11 @@ def build_app(state: state_mod.AppState) -> FastAPI: ) overrides = (body or {}).get("overrides") if isinstance(body, dict) else None await start_new_game(state, overrides=overrides) + # Always tear down + recreate the tmux session so pane-agent.sh + # picks up the new bindings (different agent on a side, human side, + # etc.). Backend lifespan also kills any leftover session on startup; + # this covers the run-time case. + await _rebuild_tmux_panes() return state.game.get_state() # type: ignore[union-attr] @app.post("/api/human-move") @@ -318,15 +353,24 @@ def build_app(state: state_mod.AppState) -> FastAPI: } @app.post("/api/dispatch-first") - async def dispatch_first() -> dict[str, Any]: + async def dispatch_first(body: dict[str, Any] | None = None) -> dict[str, Any]: + """Kick the first prompt to the white pane in the background. Returns + immediately; the dispatch sleeps `agent_boot_delay` seconds first to + let pane-agent.sh exec claude/codex and the TUI to finish booting.""" runtime = getattr(state, "runtime", None) if not runtime or not runtime.get("coord"): return {"ok": False, "reason": "coordinator_not_running"} - try: - await runtime["coord"].dispatch_first_prompt() - return {"ok": True} - except Exception as e: - return {"ok": False, "reason": "dispatch_failed", "detail": str(e)} + delay = float((body or {}).get("delay", 12.0)) if isinstance(body, dict) else 12.0 + + async def _later(): + try: + await asyncio.sleep(delay) + await runtime["coord"].dispatch_first_prompt() + except Exception as e: + print(f"[dispatch-first] failed: {e}", flush=True) + + asyncio.create_task(_later()) + return {"ok": True, "queued": True, "delay": delay} @app.get("/api/agent-binding/{side}") async def agent_binding(side: str) -> dict[str, Any]: