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.
508 lines
17 KiB
JavaScript
508 lines
17 KiB
JavaScript
import { Chess } from "/static/vendor/chess.min.js";
|
|
import { Chessground } from "/static/vendor/chessground.min.js";
|
|
|
|
const wsUrl = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/ws`;
|
|
const $ = (id) => document.getElementById(id);
|
|
|
|
const STATE = {
|
|
game: null,
|
|
settings: null,
|
|
bindings: null, // {white: {agent, model, ...}, black: {...}}
|
|
viewPly: null, // null = live; otherwise integer ply (1-based)
|
|
evalByFen: new Map(), // fenKey → eval payload (cp, mate, best_uci, pv) — from white's POV
|
|
};
|
|
window._STATE = STATE; // for debugging
|
|
|
|
// chess.js and python-chess can disagree on the en-passant field of a FEN
|
|
// (the former drops it when no pawn can legally capture; the latter always
|
|
// sets it after a 2-square pawn move). Key the eval cache by just
|
|
// position + side-to-move + castling rights so both producers agree.
|
|
function fenKey(fen) {
|
|
if (!fen) return "";
|
|
const parts = fen.split(" ");
|
|
return parts.slice(0, 3).join(" ");
|
|
}
|
|
|
|
const cg = Chessground($("board"), {
|
|
viewOnly: true,
|
|
fen: "start",
|
|
orientation: "white",
|
|
movable: { free: false },
|
|
drawable: { enabled: true, visible: true },
|
|
});
|
|
|
|
// ---------- responsive board sizing ----------
|
|
function fitBoard() {
|
|
const row = $("board-row");
|
|
const evalCol = $("eval-col");
|
|
const board = $("board");
|
|
if (!row || !board || !evalCol) return;
|
|
// 10px = gap between eval-col and board in #board-row (CSS).
|
|
const w = row.clientWidth - evalCol.offsetWidth - 10;
|
|
const h = row.clientHeight;
|
|
const side = Math.max(120, Math.floor(Math.min(w, h)));
|
|
board.style.width = side + "px";
|
|
board.style.height = side + "px";
|
|
evalCol.style.height = side + "px";
|
|
// Let chessground recompute internal layout.
|
|
if (cg && cg.redrawAll) cg.redrawAll();
|
|
}
|
|
const _ro = new ResizeObserver(fitBoard);
|
|
_ro.observe($("board-row"));
|
|
window.addEventListener("resize", fitBoard);
|
|
requestAnimationFrame(fitBoard);
|
|
|
|
// ---------- agent labels ----------
|
|
function agentOfSide(side) {
|
|
return STATE.bindings?.[side]?.agent || "?";
|
|
}
|
|
function agentDisplay(side) {
|
|
const b = STATE.bindings?.[side];
|
|
if (!b) return side;
|
|
return `${b.agent} (${side})`;
|
|
}
|
|
|
|
// ---------- rendering ----------
|
|
function currentFen() {
|
|
if (!STATE.game) return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
|
|
const moves = (STATE.game.history || []).filter(h => h.san);
|
|
if (STATE.viewPly === null) return STATE.game.fen;
|
|
const c = new Chess();
|
|
for (let i = 0; i < STATE.viewPly; i++) c.move(moves[i].san);
|
|
return c.fen();
|
|
}
|
|
|
|
function renderBoard() {
|
|
if (!STATE.game) return;
|
|
const moves = (STATE.game.history || []).filter(h => h.san);
|
|
const fen = currentFen();
|
|
let lastMove = undefined;
|
|
const idx = STATE.viewPly === null ? moves.length - 1 : STATE.viewPly - 1;
|
|
if (idx >= 0 && moves[idx]) {
|
|
const uci = moves[idx].uci || "";
|
|
if (uci.length >= 4) lastMove = [uci.slice(0, 2), uci.slice(2, 4)];
|
|
}
|
|
// Pass shapes via set() to atomically replace last move + arrow.
|
|
// Arrow comes from stored eval for this FEN, if any.
|
|
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" }]
|
|
: [];
|
|
cg.set({ fen, lastMove, drawable: { autoShapes: shapes } });
|
|
$("live-btn").hidden = STATE.viewPly === null;
|
|
applyEvalForFen(fen);
|
|
}
|
|
|
|
function renderChat() {
|
|
const list = $("chat-list");
|
|
list.innerHTML = "";
|
|
const moves = (STATE.game?.history || []).filter(h => h.san);
|
|
const counter = $("chat-counter");
|
|
counter.textContent = moves.length ? `${moves.length} moves` : "";
|
|
const activePly = STATE.viewPly === null ? moves.length : STATE.viewPly;
|
|
|
|
let activeDiv = null;
|
|
moves.forEach((h, i) => {
|
|
const ply = i + 1;
|
|
const side = h.side;
|
|
const div = document.createElement("div");
|
|
div.className = `bubble bubble-${side}`;
|
|
if (ply === activePly) { div.classList.add("active"); activeDiv = div; }
|
|
const moveNum = Math.floor(i / 2) + 1;
|
|
const moveLabel = side === "white" ? `${moveNum}.` : `${moveNum}...`;
|
|
const meta = document.createElement("div");
|
|
meta.className = "bubble-meta";
|
|
const left = document.createElement("span");
|
|
left.textContent = agentDisplay(side);
|
|
const right = document.createElement("span");
|
|
right.className = "bubble-san";
|
|
right.textContent = `${moveLabel} ${h.san}`;
|
|
meta.append(left, right);
|
|
const body = document.createElement("div");
|
|
body.className = "bubble-body";
|
|
if (h.comment) body.textContent = h.comment;
|
|
else { body.classList.add("bubble-empty"); body.textContent = "(без реплики)"; }
|
|
div.append(meta, body);
|
|
div.addEventListener("click", () => setView(ply));
|
|
list.appendChild(div);
|
|
});
|
|
|
|
// Scroll the active bubble into view (smooth at live tail, instant elsewhere).
|
|
if (activeDiv) {
|
|
requestAnimationFrame(() => activeDiv.scrollIntoView({
|
|
behavior: "smooth", block: "nearest",
|
|
}));
|
|
}
|
|
}
|
|
|
|
function renderHistory() {
|
|
const list = $("history-list");
|
|
list.innerHTML = "";
|
|
const moves = (STATE.game?.history || []).filter(h => h.san);
|
|
const activePly = STATE.viewPly === null ? moves.length : STATE.viewPly;
|
|
let activeLi = null;
|
|
|
|
let row = 0;
|
|
for (let i = 0; i < moves.length; i += 2) {
|
|
row++;
|
|
const num = document.createElement("li");
|
|
num.className = "ply-num";
|
|
num.textContent = `${row}.`;
|
|
list.appendChild(num);
|
|
|
|
const w = document.createElement("li");
|
|
w.textContent = moves[i]?.san || "";
|
|
if (i + 1 === activePly) { w.classList.add("active"); activeLi = w; }
|
|
w.addEventListener("click", () => setView(i + 1));
|
|
list.appendChild(w);
|
|
|
|
const b = document.createElement("li");
|
|
b.textContent = moves[i + 1]?.san || "";
|
|
if (moves[i + 1]) {
|
|
if (i + 2 === activePly) { b.classList.add("active"); activeLi = b; }
|
|
b.addEventListener("click", () => setView(i + 2));
|
|
}
|
|
list.appendChild(b);
|
|
}
|
|
if (activeLi) {
|
|
requestAnimationFrame(() => activeLi.scrollIntoView({
|
|
behavior: "smooth", block: "nearest",
|
|
}));
|
|
}
|
|
}
|
|
|
|
function renderStatus() {
|
|
const g = STATE.game;
|
|
if (!g) { $("status-line").textContent = "no game"; return; }
|
|
const r = g.status?.result;
|
|
if (r) {
|
|
$("status-line").textContent = `game over: ${r} (${g.status.termination})`;
|
|
} else {
|
|
$("status-line").textContent = `${agentDisplay(g.side_to_move)} to move`;
|
|
}
|
|
}
|
|
|
|
function storeEval(e) {
|
|
if (!e || !e.fen) return;
|
|
// Normalize cp/mate to WHITE's POV. Stockfish reports from side-to-move.
|
|
// If FEN says black to move, flip the sign.
|
|
const sideToMove = e.fen.split(" ")[1] || "w";
|
|
const flip = sideToMove === "b";
|
|
const norm = {
|
|
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 || null,
|
|
pv: e.pv || [],
|
|
fen: e.fen,
|
|
};
|
|
STATE.evalByFen.set(fenKey(e.fen), norm);
|
|
}
|
|
|
|
function applyEvalForFen(fen) {
|
|
const e = STATE.evalByFen.get(fenKey(fen));
|
|
const col = $("eval-col"), bar = $("eval-fill"), txt = $("eval-text"), pv = $("sf-pv");
|
|
if (!e) {
|
|
txt.textContent = "—";
|
|
pv.textContent = "";
|
|
bar.style.height = "50%";
|
|
col.classList.remove("advantage-black");
|
|
return;
|
|
}
|
|
let pct = 50;
|
|
if (e.mate != null) {
|
|
pct = e.mate > 0 ? 100 : 0;
|
|
txt.textContent = (e.mate > 0 ? "+M" : "-M") + Math.abs(e.mate);
|
|
} else if (e.cp != null) {
|
|
pct = Math.max(2, Math.min(98, 50 + e.cp / 16));
|
|
const v = (e.cp / 100);
|
|
txt.textContent = (v > 0 ? "+" : "") + v.toFixed(2);
|
|
} else {
|
|
txt.textContent = "—";
|
|
}
|
|
bar.style.height = `${pct}%`;
|
|
col.classList.toggle("advantage-black", pct < 50);
|
|
col.classList.toggle("advantage-white", pct > 50);
|
|
pv.textContent = e.pv && e.pv.length ? "pv: " + e.pv.slice(0, 6).join(" ") : "";
|
|
}
|
|
|
|
function applyEval(e) {
|
|
storeEval(e);
|
|
// If we're currently looking at this fen, refresh the visuals.
|
|
if (currentFen() === e.fen) renderBoard();
|
|
}
|
|
|
|
function setView(ply) {
|
|
STATE.viewPly = ply;
|
|
renderBoard(); renderChat(); renderHistory();
|
|
}
|
|
|
|
function goLive() {
|
|
STATE.viewPly = null;
|
|
renderBoard(); renderChat(); renderHistory();
|
|
}
|
|
|
|
function log(_line) { /* log strip removed; keep no-op to preserve callsites */ }
|
|
|
|
function applySnapshot(s) {
|
|
STATE.game = s.game;
|
|
STATE.settings = s.settings;
|
|
STATE.bindings = s.bindings;
|
|
STATE.viewPly = null;
|
|
STATE.evalByFen.clear();
|
|
for (const e of (s.evals || [])) storeEval(e);
|
|
renderBoard(); renderChat(); renderHistory(); renderStatus();
|
|
refreshGamesLink();
|
|
}
|
|
|
|
function connect() {
|
|
const ws = new WebSocket(wsUrl);
|
|
ws.addEventListener("message", (m) => {
|
|
const ev = JSON.parse(m.data);
|
|
if (ev.type === "snapshot") return applySnapshot(ev);
|
|
if (ev.type === "new_game") {
|
|
STATE.game = ev.game;
|
|
STATE.viewPly = null;
|
|
renderBoard(); renderChat(); renderHistory(); renderStatus();
|
|
log(`new game: ${ev.game?.id || "?"}`);
|
|
return;
|
|
}
|
|
if (ev.type === "move") {
|
|
if (!STATE.game) return;
|
|
STATE.game.history = ev.history;
|
|
STATE.game.fen = ev.fen;
|
|
STATE.game.status = ev.status;
|
|
if (!ev.status?.result) {
|
|
STATE.game.side_to_move = ev.side === "white" ? "black" : "white";
|
|
}
|
|
// stay live unless user clicked back
|
|
renderBoard(); renderChat(); renderHistory(); renderStatus();
|
|
log(`${ev.side} ${ev.san} «${ev.comment || ""}»`);
|
|
return;
|
|
}
|
|
if (ev.type === "eval") return applyEval(ev);
|
|
if (ev.type === "game_over") {
|
|
if (STATE.game?.status) {
|
|
STATE.game.status.result = ev.result;
|
|
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;
|
|
}
|
|
if (ev.type === "settings") { STATE.settings = ev.settings; return; }
|
|
// term_chunk + others — ignore
|
|
});
|
|
ws.addEventListener("close", () => setTimeout(connect, 1000));
|
|
ws.addEventListener("error", () => {});
|
|
}
|
|
connect();
|
|
|
|
// ---------- controls ----------
|
|
$("live-btn").addEventListener("click", goLive);
|
|
// ---------- 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");
|
|
$("settings-btn").addEventListener("click", async () => {
|
|
const s = STATE.settings || (await (await fetch("/api/settings")).json());
|
|
dialog.querySelector('[name="allow_draw_resign"]').checked = s.allow_draw_resign;
|
|
dialog.querySelector('[name="allow_illegal_moves"]').checked = s.allow_illegal_moves;
|
|
dialog.querySelector('[name="stockfish_depth"]').value = s.stockfish_depth;
|
|
dialog.showModal();
|
|
});
|
|
$("settings-save").addEventListener("click", async (e) => {
|
|
e.preventDefault();
|
|
const form = $("settings-form");
|
|
const patch = {
|
|
allow_draw_resign: form.allow_draw_resign.checked,
|
|
allow_illegal_moves: form.allow_illegal_moves.checked,
|
|
stockfish_depth: parseInt(form.stockfish_depth.value, 10),
|
|
};
|
|
await fetch("/api/settings", {
|
|
method: "POST",
|
|
headers: {"content-type": "application/json"},
|
|
body: JSON.stringify(patch),
|
|
});
|
|
dialog.close();
|
|
});
|
|
|
|
// Keyboard nav: ← prev ply, → next ply, Space = live
|
|
window.addEventListener("keydown", (e) => {
|
|
const moves = (STATE.game?.history || []).filter(h => h.san);
|
|
if (e.key === "ArrowLeft") {
|
|
const cur = STATE.viewPly === null ? moves.length : STATE.viewPly;
|
|
if (cur > 0) setView(cur - 1);
|
|
} else if (e.key === "ArrowRight") {
|
|
const cur = STATE.viewPly === null ? moves.length : STATE.viewPly;
|
|
if (cur < moves.length) {
|
|
if (cur + 1 === moves.length) goLive();
|
|
else setView(cur + 1);
|
|
}
|
|
} else if (e.key === " ") {
|
|
e.preventDefault(); goLive();
|
|
}
|
|
});
|