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
+165 -2
View File
@@ -251,6 +251,7 @@ function applySnapshot(s) {
STATE.evalByFen.clear();
for (const e of (s.evals || [])) storeEval(e);
renderBoard(); renderChat(); renderHistory(); renderStatus();
refreshGamesLink();
}
function connect() {
@@ -285,6 +286,9 @@ function connect() {
STATE.game.status.termination = ev.termination;
}
renderStatus();
refreshGamesLink();
// unlock the setup dialog if it was open and waiting
try { refreshSetupGate(); } catch (e) {}
log(`game over: ${ev.result} (${ev.termination})`);
return;
}
@@ -298,8 +302,167 @@ connect();
// ---------- controls ----------
$("live-btn").addEventListener("click", goLive);
$("new-game").addEventListener("click", async () => {
await fetch("/api/new-game", { method: "POST" });
// ---------- new game setup dialog ----------
let OPTIONS = null;
async function loadOptions() {
if (OPTIONS) return OPTIONS;
OPTIONS = await (await fetch("/api/options")).json();
return OPTIONS;
}
function fillModelOptions(side) {
const agent = document.querySelector(`[name="${side}-agent"]`).value;
const models = OPTIONS.models[agent] || [];
const sel = document.querySelector(`[name="${side}-model"]`);
sel.innerHTML = "";
for (const m of models) {
const o = document.createElement("option");
o.value = m; o.textContent = m;
sel.appendChild(o);
}
}
function fillPromptOptions(side) {
const sel = document.querySelector(`[name="${side}-prompt"]`);
sel.innerHTML = "";
for (const p of OPTIONS.prompts) {
const o = document.createElement("option");
o.value = p.id; o.textContent = p.label; o.dataset.desc = p.description;
sel.appendChild(o);
}
if (OPTIONS.defaults?.prompt) sel.value = OPTIONS.defaults.prompt;
updatePromptDesc(side);
}
function updatePromptDesc(side) {
const sel = document.querySelector(`[name="${side}-prompt"]`);
const target = document.querySelector(`.setup-promptdesc[data-for="${side}"]`);
if (!sel || !target) return;
const opt = sel.options[sel.selectedIndex];
target.textContent = opt?.dataset?.desc || "";
}
function isGameInProgress() {
return !!(STATE.game && !STATE.game.status?.result);
}
function refreshGamesLink() {
const link = $("games-link");
if (!link) return;
if (isGameInProgress()) {
link.classList.add("disabled");
link.title = "finish or abort the current game to open games & stats";
link.removeAttribute("href");
} else {
link.classList.remove("disabled");
link.removeAttribute("title");
link.setAttribute("href", "/games");
}
}
function refreshSetupGate() {
const blocked = isGameInProgress();
$("setup-warning").hidden = !blocked;
$("setup-start").disabled = blocked;
}
async function openSetupDialog() {
await loadOptions();
// Populate agent selects
for (const side of ["white", "black"]) {
const sel = document.querySelector(`[name="${side}-agent"]`);
if (!sel.children.length) {
for (const a of OPTIONS.agents) {
const o = document.createElement("option");
o.value = a; o.textContent = a;
sel.appendChild(o);
}
}
}
// Seed defaults from current bindings if available
const b = STATE.bindings || {};
for (const side of ["white", "black"]) {
const agent = b[side]?.agent || OPTIONS.agents[(side === "white") ? 0 : 1];
document.querySelector(`[name="${side}-agent"]`).value = agent;
fillModelOptions(side);
const curModel = b[side]?.model;
if (curModel && OPTIONS.models[agent]?.includes(curModel)) {
document.querySelector(`[name="${side}-model"]`).value = curModel;
}
fillPromptOptions(side);
}
refreshSetupGate();
$("setup-dialog").showModal();
}
document.addEventListener("click", (e) => {
if (e.target?.id === "abort-now") {
fetch("/api/abort-game", { method: "POST" })
.then(() => setTimeout(refreshSetupGate, 100));
}
});
$("new-game").addEventListener("click", () => openSetupDialog());
// Agent change → repopulate models
for (const side of ["white", "black"]) {
document.querySelector(`[name="${side}-agent"]`).addEventListener("change", () => {
fillModelOptions(side);
});
document.querySelector(`[name="${side}-prompt"]`).addEventListener("change", () => {
updatePromptDesc(side);
});
}
// Swap white/black selections
$("swap-sides").addEventListener("click", () => {
for (const field of ["agent", "model", "prompt"]) {
const w = document.querySelector(`[name="white-${field}"]`);
const b = document.querySelector(`[name="black-${field}"]`);
const tmp = w.value; w.value = b.value; b.value = tmp;
}
// Reset model lists for new agent values
fillModelOptions("white"); fillModelOptions("black");
updatePromptDesc("white"); updatePromptDesc("black");
});
// Randomize: pick random agent/model/prompt per side, agents on opposite sides if possible
$("randomize").addEventListener("click", () => {
const agents = [...OPTIONS.agents].sort(() => Math.random() - 0.5);
const prompts = OPTIONS.prompts.map(p => p.id);
const sides = ["white", "black"];
for (let i = 0; i < sides.length; i++) {
const side = sides[i];
const agent = agents[i % agents.length];
document.querySelector(`[name="${side}-agent"]`).value = agent;
fillModelOptions(side);
const models = OPTIONS.models[agent];
document.querySelector(`[name="${side}-model"]`).value = models[Math.floor(Math.random() * models.length)];
document.querySelector(`[name="${side}-prompt"]`).value = prompts[Math.floor(Math.random() * prompts.length)];
updatePromptDesc(side);
}
});
// Submit
$("setup-start").addEventListener("click", async (e) => {
e.preventDefault();
const overrides = {};
for (const side of ["white", "black"]) {
overrides[side] = {
agent: document.querySelector(`[name="${side}-agent"]`).value,
model: document.querySelector(`[name="${side}-model"]`).value,
prompt: document.querySelector(`[name="${side}-prompt"]`).value,
};
}
await fetch("/api/new-game", {
method: "POST",
headers: {"content-type": "application/json"},
body: JSON.stringify({ overrides }),
});
// tell coordinator to inject the first prompt right away
fetch("/api/dispatch-first", { method: "POST" }).catch(() => {});
$("setup-dialog").close();
});
const dialog = $("settings-dialog");