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:
ai-chess
2026-05-15 00:40:35 +03:00
parent 0657cec846
commit 37bac9b0f6
12 changed files with 952 additions and 124 deletions
+164 -45
View File
@@ -2,65 +2,184 @@ import { Chess } from "/static/vendor/chess.min.js";
import { Chessground } from "/static/vendor/chessground.min.js";
const $ = (id) => document.getElementById(id);
const tbody = document.querySelector("#games-table tbody");
let cg = null, chess = null, history = [], ply = 0;
let cg = null;
let replay = { history: [], evals: new Map(), ply: 0 };
function renderReplay() {
chess = new Chess();
for (let i = 0; i < ply; i++) chess.move(history[i].san);
cg.set({ fen: chess.fen() });
$("ply").textContent = `ply ${ply}/${history.length}`;
const ol = $("replay-history");
ol.innerHTML = "";
history.forEach((h, i) => {
const li = document.createElement("li");
li.textContent = h.san + (h.comment ? " «" + h.comment + "»" : "");
if (i === ply - 1) li.style.background = "#444";
ol.appendChild(li);
});
function fenKey(fen) { return fen.split(" ").slice(0, 3).join(" "); }
// ---------- gating ----------
async function checkBlocked() {
try {
const r = await fetch("/api/state");
const s = await r.json();
return !!(s.game && !s.game.status?.result);
} catch (e) { return false; }
}
// ---------- leaderboard ----------
function renderLeaderboard(stats) {
$("games-count").textContent = `${stats.total_games} games`;
const tb = document.querySelector("#leaderboard tbody");
tb.innerHTML = "";
for (const p of stats.players) {
const wr = p.games ? Math.round(100 * (p.wins + 0.5 * p.draws) / p.games) : 0;
const tr = document.createElement("tr");
tr.innerHTML = `
<td><strong>${p.agent}</strong> / ${p.model}</td>
<td>${p.games}</td>
<td>${p.wins}</td>
<td>${p.draws}</td>
<td>${p.losses}</td>
<td>${p.score.toFixed(1)}</td>
<td>${wr}%</td>`;
tb.appendChild(tr);
}
const tp = document.querySelector("#leaderboard-prompts tbody");
tp.innerHTML = "";
for (const p of stats.prompts) {
const tr = document.createElement("tr");
tr.innerHTML = `
<td>${p.prompt}</td>
<td>${p.games}</td>
<td>${p.wins}</td>
<td>${p.draws}</td>
<td>${p.losses}</td>
<td>${p.score.toFixed(1)}</td>`;
tp.appendChild(tr);
}
}
// ---------- games list ----------
function renderGames(games) {
const tb = document.querySelector("#games-table tbody");
tb.innerHTML = "";
for (const g of games) {
const w = g.agents?.white || {};
const b = g.agents?.black || {};
const tr = document.createElement("tr");
const result = g.result || "*";
tr.innerHTML = `
<td><a href="#" data-id="${g.id}">${(g.id || "?").slice(0, 10)}…</a></td>
<td>${w.agent || "?"}/${w.model || "?"}<br><span class="persona">${w.prompt || ""}</span></td>
<td>${b.agent || "?"}/${b.model || "?"}<br><span class="persona">${b.prompt || ""}</span></td>
<td class="result-${result.replace(/\//g, "_")}">${result}</td>
<td>${g.termination || ""}</td>
<td>${g.moves_count ?? 0}</td>
<td><a href="/api/games/${g.id}/pgn">pgn</a></td>`;
tr.querySelector("a[data-id]").addEventListener("click", (e) => {
e.preventDefault();
openReplay(g.id);
});
tb.appendChild(tr);
}
}
// ---------- replay ----------
async function openReplay(id) {
const data = await (await fetch(`/api/games/${id}`)).json();
const meta = data.meta;
const w = meta.agents?.white || {};
const b = meta.agents?.black || {};
$("replay-title").textContent =
`${id} — ${w.agent || "?"}/${w.model || "?"} vs ${b.agent || "?"}/${b.model || "?"} → ${meta.result || "*"}`;
chess = new Chess();
chess.load_pgn(data.pgn);
// chess.js 0.13.4: history({verbose:true}) returns [{san, ...}, ...]
history = chess.history({ verbose: true }).map(m => ({ san: m.san, comment: null }));
ply = 0;
if (!cg) cg = Chessground($("replay-board"), { viewOnly: true, fen: "start" });
$("replay-wrap").style.display = "block";
`${id.slice(0,10)}… — ${w.agent||"?"}/${w.model||"?"} (${w.prompt||"?"}) vs ${b.agent||"?"}/${b.model||"?"} (${b.prompt||"?"}) → ${meta.result || "*"}`;
// Prefer saved history (with comments) if present in meta
let history = [];
if (Array.isArray(meta.history) && meta.history.length) {
history = meta.history.filter(h => h.san);
} else {
// fallback to PGN parse
const c = new Chess();
c.load_pgn(data.pgn);
history = c.history({ verbose: true }).map(m => ({
san: m.san, uci: m.from + m.to + (m.promotion || ""), comment: null, side: m.color === "w" ? "white" : "black",
}));
}
replay.history = history;
replay.evals.clear();
for (const e of (meta.evals || [])) {
const sideToMove = (e.fen || "").split(" ")[1] || "w";
const flip = sideToMove === "b";
replay.evals.set(fenKey(e.fen), {
cp: e.cp == null ? null : (flip ? -e.cp : e.cp),
mate: e.mate == null ? null : (flip ? -e.mate : e.mate),
best_uci: e.best_uci,
pv: e.pv,
});
}
replay.ply = 0;
if (!cg) {
cg = Chessground($("replay-board"), { viewOnly: true, fen: "start" });
}
$("replay-wrap").hidden = false;
renderReplay();
$("replay-wrap").scrollIntoView({ behavior: "smooth", block: "nearest" });
}
function renderReplay() {
const c = new Chess();
for (let i = 0; i < replay.ply; i++) c.move(replay.history[i].san);
const fen = c.fen();
const e = replay.evals.get(fenKey(fen));
const shapes = (e?.best_uci && e.best_uci.length >= 4)
? [{ orig: e.best_uci.slice(0,2), dest: e.best_uci.slice(2,4), brush: "green" }] : [];
cg.set({ fen, drawable: { autoShapes: shapes } });
$("replay-ply").textContent = `ply ${replay.ply}/${replay.history.length}`;
$("replay-eval").textContent = e
? (e.mate != null ? `#${e.mate}` : (e.cp != null ? ((e.cp/100).toFixed(2)) : "—"))
: "—";
const ol = $("replay-history");
ol.innerHTML = "";
replay.history.forEach((h, i) => {
const li = document.createElement("li");
li.className = `replay-row bubble bubble-${h.side}`;
if (i === replay.ply - 1) li.classList.add("active");
const meta = document.createElement("div");
meta.className = "bubble-meta";
meta.innerHTML = `<span>${h.side}</span><span class="bubble-san">${Math.floor(i/2)+1}${h.side==="white"?".":"..."} ${h.san}</span>`;
const body = document.createElement("div");
body.className = "bubble-body" + (h.comment ? "" : " bubble-empty");
body.textContent = h.comment || "—";
li.append(meta, body);
li.addEventListener("click", () => { replay.ply = i + 1; renderReplay(); });
ol.appendChild(li);
});
const activeRow = ol.querySelector(".replay-row.active");
if (activeRow) activeRow.scrollIntoView({ behavior: "smooth", block: "nearest" });
}
$("replay-first").addEventListener("click", () => { replay.ply = 0; renderReplay(); });
$("replay-prev").addEventListener("click", () => { if (replay.ply > 0) { replay.ply--; renderReplay(); } });
$("replay-next").addEventListener("click", () => { if (replay.ply < replay.history.length) { replay.ply++; renderReplay(); } });
$("replay-last").addEventListener("click", () => { replay.ply = replay.history.length; renderReplay(); });
$("replay-close").addEventListener("click", () => { $("replay-wrap").hidden = true; });
window.addEventListener("keydown", (e) => {
if ($("replay-wrap").hidden) return;
if (e.key === "ArrowLeft" && replay.ply > 0) { replay.ply--; renderReplay(); }
else if (e.key === "ArrowRight" && replay.ply < replay.history.length) { replay.ply++; renderReplay(); }
});
// ---------- bootstrap ----------
async function main() {
const games = await (await fetch("/api/games")).json();
for (const g of games) {
const w = g.agents?.white || {};
const b = g.agents?.black || {};
const tr = document.createElement("tr");
tr.innerHTML = `
<td><a href="#" data-id="${g.id}">${(g.id || "?").slice(0, 10)}…</a></td>
<td>${w.agent || "?"}/${w.model || "?"}</td>
<td>${b.agent || "?"}/${b.model || "?"}</td>
<td>${g.result || "*"}</td>
<td>${g.termination || ""}</td>
<td>${g.moves_count ?? 0}</td>
<td><a href="/api/games/${g.id}/pgn">pgn</a></td>
`;
tr.querySelector("a[data-id]").addEventListener("click", (e) => {
e.preventDefault();
openReplay(g.id);
});
tbody.appendChild(tr);
const blocked = await checkBlocked();
if (blocked) {
$("blocked-banner").hidden = false;
document.getElementById("page-grid").style.opacity = "0.4";
document.getElementById("page-grid").style.pointerEvents = "none";
// refresh every 5s — when game finishes, unblock
const intv = setInterval(async () => {
if (!(await checkBlocked())) {
clearInterval(intv);
location.reload();
}
}, 5000);
return;
}
const [games, stats] = await Promise.all([
fetch("/api/games").then(r => r.json()),
fetch("/api/stats").then(r => r.json()),
]);
renderGames(games);
renderLeaderboard(stats);
}
main();
$("prev").addEventListener("click", () => { if (ply > 0) { ply--; renderReplay(); } });
$("next").addEventListener("click", () => { if (ply < history.length) { ply++; renderReplay(); } });