feat: prompt presets, setup dialog, /games + leaderboard, one-game gate
Backend:
- prompts.py: 5 personality presets (уличный_гопник default, профессор,
поэт, молчун, шут). Each provides voice + label + description.
build_system_prompt accepts `preset` parameter; the MCP-tools section
+ must-call-move rule is shared common tail.
- coordinator: `start_new_game` now accepts `overrides` ({white: {agent,
model, prompt}, black: {...}}) — missing fields filled randomly.
MODEL_OPTIONS published per agent.
- AppState.prompts tracks the preset id per side; persisted into game's
agents dict and PGN.
- AppState.eval_cache cleared on new_game (was per-life-of-process before).
- persistence.save_game now stores full history (with comments) and the
per-position eval cache in the game JSON.
- ChessGame.abort() — manual game termination with result='*' and
Termination='aborted'.
- New endpoints:
• GET /api/options — agents, models per agent, prompt presets.
• GET /api/stats — leaderboard aggregated from games/*.json:
per (agent, model) and per persona, with score = wins + 0.5*draws.
• POST /api/abort-game — force-end current game.
- POST /api/new-game now returns 409 when a game is in progress.
- GET /api/games[/{id}[/pgn]] also 409 while in progress — gallery is
hidden behind the one-game-at-a-time rule.
Frontend:
- New setup dialog: per-side agent / model / persona selects, swap +
random shortcuts, persona description preview, abort button inline
when current game blocks the start.
- 'games & stats' link in the board footer; greyed out while a game is
active.
- /games page reworked: leaderboard (player × model + by persona),
games table with persona labels, replay panel showing eval per ply
with prev/next/first/last + arrow-key nav.
- chess.js loadPgn → load_pgn fix consolidated; replay prefers saved
history (comments + side) over PGN parse when available.
This commit is contained in:
+107
-2
@@ -104,12 +104,18 @@ def build_app(state: state_mod.AppState) -> FastAPI:
|
||||
"evals": evals,
|
||||
}
|
||||
|
||||
def _require_no_active_game() -> None:
|
||||
if state.game is not None and not state.game.is_game_over():
|
||||
raise HTTPException(409, "current game is in progress; abort it first")
|
||||
|
||||
@app.get("/api/games")
|
||||
async def games_list() -> list[dict[str, Any]]:
|
||||
_require_no_active_game()
|
||||
return list_games(state_mod.GAMES_DIR)
|
||||
|
||||
@app.get("/api/games/{game_id}")
|
||||
async def game_get(game_id: str) -> dict[str, Any]:
|
||||
_require_no_active_game()
|
||||
try:
|
||||
return load_game(state_mod.GAMES_DIR, game_id)
|
||||
except FileNotFoundError:
|
||||
@@ -117,6 +123,7 @@ def build_app(state: state_mod.AppState) -> FastAPI:
|
||||
|
||||
@app.get("/api/games/{game_id}/pgn")
|
||||
async def game_pgn(game_id: str) -> Any:
|
||||
_require_no_active_game()
|
||||
try:
|
||||
data = load_game(state_mod.GAMES_DIR, game_id)
|
||||
except FileNotFoundError:
|
||||
@@ -134,10 +141,108 @@ def build_app(state: state_mod.AppState) -> FastAPI:
|
||||
return state.settings.model_dump()
|
||||
|
||||
@app.post("/api/new-game")
|
||||
async def new_game_post() -> dict[str, Any]:
|
||||
await start_new_game(state)
|
||||
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.
|
||||
if state.game is not None and not state.game.is_game_over():
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="current game is in progress; abort it first",
|
||||
)
|
||||
overrides = (body or {}).get("overrides") if isinstance(body, dict) else None
|
||||
await start_new_game(state, overrides=overrides)
|
||||
return state.game.get_state() # type: ignore[union-attr]
|
||||
|
||||
@app.post("/api/abort-game")
|
||||
async def abort_game() -> dict[str, Any]:
|
||||
if state.game is None:
|
||||
return {"ok": False, "reason": "no_active_game"}
|
||||
if state.game.is_game_over():
|
||||
return {"ok": False, "reason": "already_over",
|
||||
"result": state.game.result,
|
||||
"termination": state.game.termination}
|
||||
out = state.game.abort()
|
||||
if out.get("ok"):
|
||||
await state.events.publish({
|
||||
"type": "game_over",
|
||||
"result": state.game.result,
|
||||
"termination": state.game.termination,
|
||||
})
|
||||
return out
|
||||
|
||||
@app.get("/api/options")
|
||||
async def options() -> dict[str, Any]:
|
||||
from ai_chess.coordinator import AGENTS, MODEL_OPTIONS
|
||||
from ai_chess.prompts import list_prompt_presets, DEFAULT_PROMPT
|
||||
return {
|
||||
"agents": AGENTS,
|
||||
"models": MODEL_OPTIONS,
|
||||
"prompts": list_prompt_presets(),
|
||||
"defaults": {"prompt": DEFAULT_PROMPT},
|
||||
}
|
||||
|
||||
@app.get("/api/stats")
|
||||
async def stats() -> dict[str, Any]:
|
||||
from collections import defaultdict
|
||||
games = list_games(state_mod.GAMES_DIR)
|
||||
# Aggregate per (agent, model) and per (agent, model, prompt)
|
||||
per_player: dict[tuple, dict[str, int]] = defaultdict(
|
||||
lambda: {"games": 0, "wins": 0, "losses": 0, "draws": 0, "as_white": 0, "as_black": 0}
|
||||
)
|
||||
per_prompt: dict[str, dict[str, int]] = defaultdict(
|
||||
lambda: {"games": 0, "wins": 0, "losses": 0, "draws": 0}
|
||||
)
|
||||
|
||||
for g in games:
|
||||
result = g.get("result")
|
||||
ag = g.get("agents") or {}
|
||||
w = ag.get("white") or {}
|
||||
b = ag.get("black") or {}
|
||||
wkey = (w.get("agent", "?"), w.get("model", "?"))
|
||||
bkey = (b.get("agent", "?"), b.get("model", "?"))
|
||||
per_player[wkey]["games"] += 1
|
||||
per_player[wkey]["as_white"] += 1
|
||||
per_player[bkey]["games"] += 1
|
||||
per_player[bkey]["as_black"] += 1
|
||||
wprompt = w.get("prompt")
|
||||
bprompt = b.get("prompt")
|
||||
|
||||
if result == "1-0":
|
||||
per_player[wkey]["wins"] += 1
|
||||
per_player[bkey]["losses"] += 1
|
||||
if wprompt: per_prompt[wprompt]["wins"] += 1
|
||||
if bprompt: per_prompt[bprompt]["losses"] += 1
|
||||
elif result == "0-1":
|
||||
per_player[wkey]["losses"] += 1
|
||||
per_player[bkey]["wins"] += 1
|
||||
if wprompt: per_prompt[wprompt]["losses"] += 1
|
||||
if bprompt: per_prompt[bprompt]["wins"] += 1
|
||||
elif result == "1/2-1/2":
|
||||
per_player[wkey]["draws"] += 1
|
||||
per_player[bkey]["draws"] += 1
|
||||
if wprompt: per_prompt[wprompt]["draws"] += 1
|
||||
if bprompt: per_prompt[bprompt]["draws"] += 1
|
||||
if wprompt: per_prompt[wprompt]["games"] += 1
|
||||
if bprompt: per_prompt[bprompt]["games"] += 1
|
||||
|
||||
def _row(key, stats_):
|
||||
agent, model = key
|
||||
score = stats_["wins"] + 0.5 * stats_["draws"]
|
||||
return {"agent": agent, "model": model, **stats_, "score": score}
|
||||
players = sorted(
|
||||
(_row(k, v) for k, v in per_player.items()),
|
||||
key=lambda r: (-r["score"], -r["wins"], r["losses"]),
|
||||
)
|
||||
prompts_rows = sorted(
|
||||
({"prompt": k, **v, "score": v["wins"] + 0.5 * v["draws"]}
|
||||
for k, v in per_prompt.items()),
|
||||
key=lambda r: (-r["score"], -r["wins"]),
|
||||
)
|
||||
return {
|
||||
"total_games": len(games),
|
||||
"players": players,
|
||||
"prompts": prompts_rows,
|
||||
}
|
||||
|
||||
@app.post("/api/dispatch-first")
|
||||
async def dispatch_first() -> dict[str, Any]:
|
||||
runtime = getattr(state, "runtime", None)
|
||||
|
||||
Reference in New Issue
Block a user