fix: backend lifespan tears down tmux 'chess' session
Agents that outlive the backend desync with state.game (in-memory only) — they keep calling MCP move on a server that has no idea what game is being played. Simpler than persisting game state across restarts: backend startup kills any leftover 'chess' tmux session, backend shutdown kills the current one. start.sh will spawn fresh agents that are aligned with the empty server state on each launch.
This commit is contained in:
@@ -28,6 +28,18 @@ def build_app(state: state_mod.AppState) -> FastAPI:
|
|||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
session = TmuxSession("chess")
|
session = TmuxSession("chess")
|
||||||
|
# Tear down any leftover tmux session from a prior run. Agents that
|
||||||
|
# outlive the backend will desync with state.game (which lives only
|
||||||
|
# in-process) and end up calling MCP move on a game the server no
|
||||||
|
# longer knows about. Cleanest fix: kill them at startup so start.sh
|
||||||
|
# spawns fresh ones aligned with the empty server state.
|
||||||
|
try:
|
||||||
|
if await session.exists():
|
||||||
|
print("[lifespan] killing stale tmux session 'chess'", flush=True)
|
||||||
|
await session.kill()
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[lifespan] startup session.kill failed: {e}", flush=True)
|
||||||
|
|
||||||
coord = Coordinator(state, tmux=session, pane_for={"white": 0, "black": 1})
|
coord = Coordinator(state, tmux=session, pane_for={"white": 0, "black": 1})
|
||||||
tailer = TmuxTailer(state, session, pane_for={"white": 0, "black": 1})
|
tailer = TmuxTailer(state, session, pane_for={"white": 0, "black": 1})
|
||||||
eng = StockfishEngine()
|
eng = StockfishEngine()
|
||||||
@@ -117,6 +129,14 @@ def build_app(state: state_mod.AppState) -> FastAPI:
|
|||||||
await coord.stop()
|
await coord.stop()
|
||||||
await tailer.stop()
|
await tailer.stop()
|
||||||
await eng.stop()
|
await eng.stop()
|
||||||
|
# Tear down the tmux session so claude/codex die with us. Without
|
||||||
|
# this they keep running with stale conversation context that no
|
||||||
|
# longer matches the next backend's state.
|
||||||
|
try:
|
||||||
|
await session.kill()
|
||||||
|
print("[lifespan] tmux session 'chess' killed on shutdown", flush=True)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[lifespan] shutdown session.kill failed: {e}", flush=True)
|
||||||
|
|
||||||
app = FastAPI(title="ai-chess", lifespan=lifespan)
|
app = FastAPI(title="ai-chess", lifespan=lifespan)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user