rewrite: TS monorepo — pi SDK stateless agents, Postgres+pg-boss, SvelteKit themed UI; legacy moved to legacy/

This commit is contained in:
ai-chess
2026-10-18 15:32:39 +03:00
parent e23a07f07b
commit 5be4bd1da4
321 changed files with 37840 additions and 158 deletions
+643
View File
@@ -0,0 +1,643 @@
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(" ");
}
async function submitHumanMove(orig, dest, prom) {
const uci = orig + dest + (prom ? prom : "");
try {
await fetch("/api/human-move", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ move: uci }),
});
} catch (e) {
console.warn("human-move failed", e);
}
}
const cg = Chessground($("board"), {
viewOnly: false,
fen: "start",
orientation: "white",
movable: {
free: false, color: undefined, dests: new Map(), showDests: true,
events: {
after: (orig, dest) => {
// movable.events.after fires only on LEGAL completed user moves —
// perfect for submitting a human move to the server.
submitHumanMove(orig, dest);
},
},
},
draggable: { enabled: true, showGhost: true },
selectable: { enabled: true },
drawable: { enabled: true, visible: true },
});
window.cg = cg; // for debugging
// ---------- 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 humanSide() {
const b = STATE.bindings || {};
if (b.white?.agent === "human") return "white";
if (b.black?.agent === "human") return "black";
return null;
}
function legalDestsForFen(fen) {
// Build a Map<from, to[]> of legal moves at this position. Used to let
// chessground accept only legal squares for the human side.
const c = new Chess(fen);
const dests = new Map();
for (const m of c.moves({ verbose: true })) {
if (!dests.has(m.from)) dests.set(m.from, []);
dests.get(m.from).push(m.to);
}
return dests;
}
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)];
}
const hSide = humanSide();
const sideToMove = STATE.game.side_to_move;
const isHumanTurn = (
hSide && hSide === sideToMove
&& STATE.viewPly === null
&& !STATE.game.status?.result
);
// Stockfish hints are NOT shown to a human player — eval bar + best-move
// arrow would be cheating. They stay on for spectator (AI-vs-AI) games.
const showHints = !hSide;
const e = showHints ? STATE.evalByFen.get(fenKey(fen)) : null;
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" }]
: [];
const movable = isHumanTurn
? { free: false, color: hSide, dests: legalDestsForFen(fen), showDests: true }
: { free: false, color: undefined, dests: new Map(), showDests: false };
cg.set({
fen, lastMove,
orientation: hSide === "black" ? "black" : "white",
movable,
draggable: { enabled: !!isHumanTurn, showGhost: true },
selectable: { enabled: !!isHumanTurn },
drawable: { enabled: true, visible: true, autoShapes: shapes },
viewOnly: !isHumanTurn,
});
$("live-btn").hidden = STATE.viewPly === null;
if (showHints) {
applyEvalForFen(fen);
} else {
// Wipe any leftover eval visual from a prior spectator session.
$("eval-text").textContent = "";
$("eval-fill").style.height = "50%";
$("sf-pv").textContent = "";
}
}
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");
if (!e) {
txt.textContent = "—";
bar.style.height = "50%";
col.classList.remove("advantage-black", "advantage-white");
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);
}
// ---------- thinking timer ----------
const THINK = {
startedAt: null, // ms timestamp when current side started thinking
side: null, // "white" | "black" | null
lastMs: { white: 0, black: 0 },
};
function fmtMmSs(ms) {
if (ms == null || ms < 0) return "0:00";
const s = Math.floor(ms / 1000);
return `${Math.floor(s / 60)}:${(s % 60).toString().padStart(2, "0")}`;
}
function renderThinking() {
const el = $("think-meter");
if (!el) return;
// No live thinking while viewing history or after game-over.
const live = STATE.viewPly === null && THINK.side && !STATE.game?.status?.result;
if (!live) {
// Show last completed move's think time when in live + game-over,
// otherwise stay quiet.
if (STATE.game?.status?.result) {
el.innerHTML = "";
} else if (STATE.viewPly !== null) {
el.innerHTML = "";
} else {
el.innerHTML = "";
}
return;
}
const elapsed = Date.now() - (THINK.startedAt || Date.now());
const who = agentDisplay(THINK.side);
el.innerHTML = `<span class="think-dot"></span><span class="think-who">${who}</span> думает <span class="think-time">${fmtMmSs(elapsed)}</span>`;
}
setInterval(renderThinking, 1000);
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);
// Hide the eval bar in human-vs-AI to avoid cheating.
const evalCol = $("eval-col");
if (evalCol) evalCol.style.display = humanSide() ? "none" : "";
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;
THINK.startedAt = Date.now();
THINK.side = "white";
THINK.lastMs = { white: 0, black: 0 };
renderBoard(); renderChat(); renderHistory(); renderStatus();
refreshGamesLink();
renderThinking();
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";
}
// Always snap back to live on a new move — otherwise an accidental
// history-scrub leaves the board locked into a past position and the
// user can't make their next move without reloading.
STATE.viewPly = null;
// think timer: mover finished, opponent starts
if (THINK.startedAt != null && THINK.side === ev.side) {
THINK.lastMs[ev.side] = Date.now() - THINK.startedAt;
}
THINK.startedAt = ev.status?.result ? null : Date.now();
THINK.side = ev.status?.result ? null : (ev.side === "white" ? "black" : "white");
renderBoard(); renderChat(); renderHistory(); renderStatus(); renderThinking();
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;
}
THINK.startedAt = null;
THINK.side = null;
renderStatus();
renderThinking();
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");
const abortBtn = $("abort-game");
const inProgress = isGameInProgress();
if (link) {
if (inProgress) {
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");
}
}
if (abortBtn) abortBtn.hidden = !inProgress;
}
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());
$("abort-game").addEventListener("click", async () => {
if (!confirm("Прервать текущую партию?")) return;
await fetch("/api/abort-game", { method: "POST" });
});
// 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();
}
});
+92
View File
@@ -0,0 +1,92 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<title>ai-chess — games & stats</title>
<link rel="stylesheet" href="/static/vendor/chessground.base.css" />
<link rel="stylesheet" href="/static/vendor/chessground.brown.css" />
<link rel="stylesheet" href="/static/vendor/chessground.cburnett.css" />
<link rel="stylesheet" href="/static/style.css" />
</head>
<body>
<main id="games-page">
<header id="games-page-header">
<a id="back-link" href="/">← back to live</a>
<h1>games & stats</h1>
<span id="games-count"></span>
</header>
<div id="blocked-banner" hidden>
<strong>Game in progress.</strong> Finish or abort it on the
<a href="/">main page</a> before browsing past games.
</div>
<div id="page-grid">
<section id="stats-pane">
<header class="col-header"><span>leaderboard (player × model)</span></header>
<table id="leaderboard">
<thead>
<tr>
<th>agent / model</th>
<th>games</th>
<th>wins</th>
<th>draws</th>
<th>losses</th>
<th>score</th>
<th>winrate</th>
</tr>
</thead>
<tbody></tbody>
</table>
<header class="col-header"><span>by persona</span></header>
<table id="leaderboard-prompts">
<thead>
<tr><th>persona</th><th>games</th><th>wins</th><th>draws</th><th>losses</th><th>score</th></tr>
</thead>
<tbody></tbody>
</table>
</section>
<section id="games-pane">
<header class="col-header"><span>games</span></header>
<table id="games-table">
<thead>
<tr>
<th>id</th>
<th>white</th>
<th>black</th>
<th>result</th>
<th>termination</th>
<th>moves</th>
<th>pgn</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div id="replay-wrap" hidden>
<header class="col-header"><span id="replay-title">replay</span>
<button id="replay-close" type="button">close</button>
</header>
<div id="replay-layout">
<div id="replay-board"></div>
<aside id="replay-side">
<div id="replay-controls">
<button id="replay-first">⏮</button>
<button id="replay-prev">←</button>
<button id="replay-next">→</button>
<button id="replay-last">⏭</button>
<span id="replay-ply">ply 0/0</span>
<span id="replay-eval"></span>
</div>
<ol id="replay-history"></ol>
</aside>
</div>
</div>
</section>
</div>
</main>
<script src="/static/games.js" type="module"></script>
</body>
</html>
+185
View File
@@ -0,0 +1,185 @@
import { Chess } from "/static/vendor/chess.min.js";
import { Chessground } from "/static/vendor/chessground.min.js";
const $ = (id) => document.getElementById(id);
let cg = null;
let replay = { history: [], evals: new Map(), ply: 0 };
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.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 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();
+113
View File
@@ -0,0 +1,113 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<title>ai-chess</title>
<link rel="stylesheet" href="/static/vendor/chessground.base.css" />
<link rel="stylesheet" href="/static/vendor/chessground.brown.css" />
<link rel="stylesheet" href="/static/vendor/chessground.cburnett.css" />
<link rel="stylesheet" href="/static/style.css" />
</head>
<body>
<main id="layout">
<section id="board-col">
<div id="board-row">
<div id="eval-col" title="stockfish eval">
<div id="eval-fill"></div>
<div id="eval-text">0.00</div>
</div>
<div id="board"></div>
</div>
<div id="board-footer">
<span id="status-line">…</span>
<span id="think-meter"></span>
<button id="live-btn" hidden>live</button>
<a id="games-link" href="/games">games & stats</a>
<button id="abort-game" hidden>abort game</button>
<button id="new-game">new game</button>
<button id="settings-btn" title="settings">⚙</button>
</div>
<div id="moves-floating">
<span class="moves-label">moves</span>
<ol id="history-list"></ol>
</div>
</section>
<aside id="chat-col">
<header class="col-header">
<span>chat</span>
<span id="chat-counter"></span>
</header>
<div id="chat-list"></div>
</aside>
</main>
<dialog id="settings-dialog">
<form method="dialog" id="settings-form">
<h3>settings</h3>
<label><input type="checkbox" name="allow_draw_resign" /> allow draw / resign</label>
<label><input type="checkbox" name="allow_illegal_moves" /> allow illegal moves</label>
<label>stockfish depth: <input type="number" name="stockfish_depth" min="6" max="30" /></label>
<menu>
<button value="cancel">cancel</button>
<button value="save" id="settings-save">save</button>
</menu>
</form>
</dialog>
<dialog id="setup-dialog">
<form method="dialog" id="setup-form">
<header class="setup-header">
<h3>new game</h3>
<div class="setup-actions">
<button type="button" id="swap-sides" title="swap white/black">⇄ swap</button>
<button type="button" id="randomize" title="randomize">🎲 random</button>
</div>
</header>
<div class="setup-grid">
<fieldset class="setup-side setup-white">
<legend>WHITE</legend>
<label>agent
<select name="white-agent"></select>
</label>
<label>model
<select name="white-model"></select>
</label>
<label>persona
<select name="white-prompt"></select>
</label>
<p class="setup-promptdesc" data-for="white"></p>
</fieldset>
<fieldset class="setup-side setup-black">
<legend>BLACK</legend>
<label>agent
<select name="black-agent"></select>
</label>
<label>model
<select name="black-model"></select>
</label>
<label>persona
<select name="black-prompt"></select>
</label>
<p class="setup-promptdesc" data-for="black"></p>
</fieldset>
</div>
<p id="setup-warning" hidden>
⚠ Current game is in progress.
<button type="button" id="abort-now">abort current game</button>
to enable a new one.
</p>
<menu>
<button value="cancel">cancel</button>
<button value="start" id="setup-start">start game</button>
</menu>
</form>
</dialog>
<script src="/static/app.js" type="module"></script>
</body>
</html>
+493
View File
@@ -0,0 +1,493 @@
/* ====================================================================
ai-chess MENU — fight-club / tournament bulletin aesthetic
palette
ink #0a0a0c (background bottom)
paper #15151a (panels)
bone #e7e4d8 (primary text)
ash #6a6a72 (muted text)
gold #c0a060 (rule / decisions / accept)
crimson #c04040 (fight / abort)
gold-dim #6b5a35
crimson-dim #6b2222
==================================================================== */
:root {
--ink: #0a0a0c;
--paper: #15151a;
--paper-2: #1d1d23;
--bone: #e7e4d8;
--bone-dim: #b8b4a3;
--ash: #6a6a72;
--rule: #2a2a30;
--gold: #c0a060;
--gold-dim: #6b5a35;
--crimson: #c04040;
--crimson-dim:#6b2222;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
html, body {
margin: 0;
background: radial-gradient(ellipse at 50% -10%, #1e1e24 0%, var(--ink) 60%) fixed;
color: var(--bone);
font-family: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, monospace;
font-weight: 400;
line-height: 1.4;
min-height: 100vh;
}
/* fine grain / film texture */
.grain {
position: fixed; inset: 0; pointer-events: none; z-index: 100;
opacity: 0.06;
background-image:
repeating-linear-gradient(0deg, transparent 0 2px, rgba(255,255,255,0.05) 2px 3px),
repeating-linear-gradient(90deg, transparent 0 2px, rgba(255,255,255,0.04) 2px 3px);
mix-blend-mode: overlay;
}
/* ---------- TOPBAR ---------- */
.topbar {
display: flex; justify-content: space-between; align-items: baseline;
padding: 22px 36px;
font-size: 11px; letter-spacing: 0.16em; text-transform: uppercase;
color: var(--ash);
border-bottom: 1px solid var(--rule);
}
.brand {
color: var(--gold);
font-weight: 800;
letter-spacing: 0.22em;
font-size: 12px;
}
.topbar-meta { display: flex; gap: 10px; align-items: baseline; }
.topbar-meta .sep { opacity: 0.4; }
.topbar-meta .ver { color: var(--gold); }
/* ---------- HERO ---------- */
.hero {
max-width: 1180px;
margin: 0 auto;
padding: 36px 36px 80px;
}
.badge-row {
display: flex; align-items: center; gap: 14px;
font-size: 10px; letter-spacing: 0.32em; color: var(--gold);
text-transform: uppercase;
margin-bottom: 16px;
}
.badge-line { flex: 1; height: 1px; background: linear-gradient(90deg, transparent, var(--gold-dim), transparent); }
.badge { white-space: nowrap; }
.title {
font-family: "Major Mono Display", "JetBrains Mono", monospace;
font-size: clamp(56px, 9vw, 132px);
line-height: 0.9;
letter-spacing: 0.04em;
margin: 0 0 18px;
text-align: center;
color: var(--bone);
text-shadow: 0 0 60px rgba(192,160,96,0.18);
font-weight: 400;
display: flex;
justify-content: center;
align-items: baseline;
gap: 0.18em;
flex-wrap: nowrap;
white-space: nowrap;
}
.title .t1, .title .t2 { color: var(--bone); white-space: nowrap; }
.title .t-dot {
color: var(--crimson);
display: inline-block;
transform: translateY(-0.08em);
animation: pulse-dot 2s ease-in-out infinite;
}
@keyframes pulse-dot {
0%,100% { opacity: 0.7; text-shadow: 0 0 18px var(--crimson-dim); }
50% { opacity: 1; text-shadow: 0 0 36px var(--crimson); }
}
.tagline {
text-align: center;
color: var(--bone-dim);
font-size: 14px;
letter-spacing: 0.02em;
margin: 0 auto 56px;
max-width: 620px;
font-style: italic;
}
/* ---------- ACTIVE GAME CARD (in-progress) ---------- */
.active-card {
position: relative;
background:
linear-gradient(180deg, rgba(192,160,96,0.08) 0%, rgba(15,15,18,0) 70%),
var(--paper);
border: 1px solid var(--gold-dim);
border-radius: 6px;
padding: 26px 28px 22px;
margin-bottom: 32px;
box-shadow: 0 30px 80px -40px rgba(192,160,96,0.45);
overflow: hidden;
animation: setup-in 0.35s ease both;
}
.active-card::after {
content: "LIVE";
position: absolute;
top: 14px; right: -36px;
background: var(--crimson); color: #fff;
font-size: 10px; font-weight: 800; letter-spacing: 0.4em;
padding: 3px 40px;
transform: rotate(35deg);
box-shadow: 0 6px 14px -6px var(--crimson);
}
.active-head {
display: flex; align-items: baseline; gap: 12px;
border-bottom: 1px dashed var(--rule);
padding-bottom: 14px; margin-bottom: 18px;
font-size: 11px; letter-spacing: 0.32em; text-transform: uppercase;
color: var(--gold);
}
.active-pulse {
display: inline-block; width: 8px; height: 8px;
background: var(--crimson); border-radius: 50%;
animation: pulse-dot 1.4s ease-in-out infinite;
align-self: center;
}
.active-meta { margin-left: auto; opacity: 0.55; letter-spacing: 0.16em; color: var(--bone-dim); font-size: 11px; }
.active-vs {
display: grid;
grid-template-columns: 1fr 96px 1fr;
gap: 18px; align-items: stretch;
margin-bottom: 22px;
}
.seat {
display: flex; flex-direction: column; gap: 4px;
padding: 14px 18px;
border: 1px solid var(--rule);
border-radius: 4px;
background: rgba(0,0,0,0.18);
position: relative;
}
.seat-white { border-left: 3px solid var(--bone); }
.seat-black { border-right: 3px solid var(--bone-dim); text-align: right; }
.seat-pip {
position: absolute; top: 14px; font-size: 14px; opacity: 0.7;
}
.seat-white .seat-pip { left: 18px; color: var(--bone); }
.seat-black .seat-pip { right: 18px; color: var(--bone-dim); }
.seat-name {
font-size: 22px; font-weight: 800; letter-spacing: 0.06em;
text-transform: uppercase;
margin-left: 20px; /* under the pip */
}
.seat-black .seat-name { margin-left: 0; margin-right: 20px; }
.seat-sub {
font-size: 11px; color: var(--gold); letter-spacing: 0.08em;
margin-left: 20px;
}
.seat-black .seat-sub { margin-left: 0; margin-right: 20px; }
.seat-persona {
font-size: 11px; color: var(--bone-dim); opacity: 0.7;
margin-top: 2px;
margin-left: 20px;
font-style: italic;
}
.seat-black .seat-persona { margin-left: 0; margin-right: 20px; }
.active-divider {
display: flex; flex-direction: column; align-items: center; justify-content: center;
gap: 8px;
}
.active-vs-label {
font-size: 28px; font-weight: 800; color: var(--crimson);
letter-spacing: 0.1em;
}
.active-turn {
font-size: 10px; letter-spacing: 0.18em; text-transform: uppercase;
color: var(--bone-dim); text-align: center;
}
.active-actions {
display: flex; gap: 16px; align-items: center;
margin-top: 8px;
}
.watch-btn {
display: inline-flex; align-items: center; gap: 14px;
background: var(--gold); color: #1a1410;
text-decoration: none;
padding: 12px 32px;
font-size: 15px; font-weight: 800; letter-spacing: 0.2em;
border-radius: 3px;
transition: filter 0.15s, transform 0.1s;
box-shadow: 0 8px 28px -10px var(--gold);
}
.watch-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }
.watch-btn .kbd {
font-size: 11px; opacity: 0.7;
border: 1px solid rgba(0,0,0,0.3); padding: 1px 6px; border-radius: 2px;
}
.active-abort {
background: transparent; border: 1px solid var(--crimson-dim);
color: var(--crimson); padding: 8px 16px;
font-size: 11px; letter-spacing: 0.18em; text-transform: uppercase;
cursor: pointer; border-radius: 3px;
font-family: inherit;
transition: background 0.15s, color 0.15s;
}
.active-abort:hover { background: var(--crimson-dim); color: #ffe5e5; }
.active-foot {
margin: 18px 0 0; padding-top: 14px;
border-top: 1px dashed var(--rule);
font-size: 11px; color: var(--ash);
letter-spacing: 0.04em; font-style: italic;
}
/* ---------- MODE CARDS ---------- */
.modes {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 14px;
margin-bottom: 32px;
}
.mode {
position: relative;
background: var(--paper);
border: 1px solid var(--rule);
border-radius: 4px;
padding: 26px 22px 22px;
cursor: pointer;
text-align: left;
color: var(--bone);
font-family: inherit;
font-size: 13px;
display: flex; flex-direction: column; gap: 8px;
min-height: 168px;
transition: transform 0.18s ease, border-color 0.18s, background 0.18s, box-shadow 0.18s;
text-decoration: none;
overflow: hidden;
}
.mode::before {
content: "";
position: absolute; inset: 0;
background:
repeating-linear-gradient(45deg, transparent 0 6px, rgba(255,255,255,0.012) 6px 12px);
pointer-events: none;
}
.mode:hover {
transform: translateY(-2px);
border-color: var(--bone-dim);
background: var(--paper-2);
}
.mode-num {
font-size: 10px;
color: var(--ash);
letter-spacing: 0.3em;
}
.mode-name {
font-size: 22px;
font-weight: 800;
letter-spacing: 0.04em;
margin-top: 2px;
}
.mode-name .x { color: var(--crimson); margin: 0 4px; font-weight: 400; }
.mode-desc {
color: var(--bone-dim);
font-size: 12px;
line-height: 1.5;
flex: 1;
}
.mode-tag {
align-self: flex-start;
padding: 2px 8px;
font-size: 9px;
letter-spacing: 0.25em;
border: 1px solid currentColor;
border-radius: 2px;
text-transform: uppercase;
}
.tag-gold { color: var(--gold); }
.tag-crimson { color: var(--crimson); }
.tag-neutral { color: var(--ash); }
/* Selected card */
.mode[aria-pressed="true"] {
border-color: var(--gold);
box-shadow: 0 0 0 1px var(--gold), 0 20px 60px -30px rgba(192,160,96,0.4);
background: var(--paper-2);
}
.mode[aria-pressed="true"][data-mode="human_vs_ai"] {
border-color: var(--crimson);
box-shadow: 0 0 0 1px var(--crimson), 0 20px 60px -30px rgba(192,64,64,0.4);
}
/* ---------- SETUP ---------- */
.setup {
background: var(--paper);
border: 1px solid var(--rule);
border-radius: 4px;
padding: 24px 24px 18px;
margin-bottom: 28px;
animation: setup-in 0.3s ease both;
}
@keyframes setup-in {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: none; }
}
.setup-head {
display: flex; align-items: center; gap: 14px;
border-bottom: 1px dashed var(--rule);
padding-bottom: 12px; margin-bottom: 18px;
}
.setup-step {
font-size: 10px; letter-spacing: 0.3em; color: var(--gold);
text-transform: uppercase;
}
.setup-title {
font-size: 12px; letter-spacing: 0.06em; color: var(--bone-dim);
}
.setup-tools { margin-left: auto; display: flex; gap: 6px; }
.tool {
background: transparent; color: var(--bone-dim); border: 1px solid var(--rule);
padding: 3px 10px; font-size: 11px; font-family: inherit; cursor: pointer;
border-radius: 3px; letter-spacing: 0.05em;
}
.tool:hover { border-color: var(--bone-dim); color: var(--bone); }
.sides {
display: grid;
grid-template-columns: 1fr 56px 1fr;
gap: 14px;
align-items: stretch;
}
.side {
border: 1px solid var(--rule);
border-radius: 4px;
padding: 18px 16px 16px;
background: rgba(0,0,0,0.18);
margin: 0;
display: flex; flex-direction: column; gap: 12px;
position: relative;
}
.side legend {
display: flex; align-items: center; gap: 8px;
padding: 0 8px;
font-size: 11px; letter-spacing: 0.3em; font-weight: 800;
}
.legend-pip {
display: inline-block; width: 8px; height: 8px;
background: var(--bone); border-radius: 50%;
}
.side-white legend { color: var(--bone); }
.side-white .legend-pip { background: var(--bone); }
.side-black legend { color: var(--bone-dim); }
.side-black .legend-pip { background: #1a1a1a; box-shadow: inset 0 0 0 1px var(--bone-dim); }
.field {
display: flex; flex-direction: column; gap: 4px;
font-size: 10px; letter-spacing: 0.18em; text-transform: uppercase;
color: var(--ash);
}
.field select {
background: var(--paper-2); color: var(--bone);
border: 1px solid var(--rule); border-radius: 3px;
padding: 6px 8px;
font-family: inherit; font-size: 13px; letter-spacing: 0;
text-transform: none;
appearance: none;
background-image:
linear-gradient(45deg, transparent 50%, var(--bone-dim) 50%),
linear-gradient(-45deg, transparent 50%, var(--bone-dim) 50%);
background-position: calc(100% - 12px) 12px, calc(100% - 7px) 12px;
background-size: 5px 5px, 5px 5px;
background-repeat: no-repeat;
}
.field select:focus { outline: 1px solid var(--gold); border-color: var(--gold); }
.persona-desc {
font-size: 11px; line-height: 1.5; color: var(--bone-dim);
margin: 4px 0 0; min-height: 2.4em; font-style: italic;
}
.human-note {
font-size: 11px; color: var(--crimson); margin: 0;
border: 1px dashed var(--crimson-dim); padding: 8px 10px; border-radius: 3px;
}
.vs {
display: flex; align-items: center; justify-content: center;
font-size: 28px; font-weight: 800; color: var(--crimson);
letter-spacing: 0.1em;
position: relative;
}
.vs::before, .vs::after {
content: ""; position: absolute; left: 50%; transform: translateX(-50%);
width: 1px; height: 28%; background: var(--rule);
}
.vs::before { top: 0; }
.vs::after { bottom: 0; }
/* warning + footer */
#setup-warning {
margin-top: 16px;
background: rgba(192,64,64,0.08);
border: 1px solid var(--crimson-dim);
color: #e0a0a0;
padding: 10px 14px;
font-size: 12px; letter-spacing: 0.04em;
border-radius: 3px;
}
.link-abort {
background: transparent; border: none; color: var(--crimson);
text-decoration: underline; cursor: pointer; font: inherit; padding: 0;
}
.setup-foot {
display: flex; align-items: center; justify-content: space-between;
margin-top: 18px; padding-top: 16px; border-top: 1px dashed var(--rule);
}
.back {
color: var(--ash); text-decoration: none; font-size: 12px;
}
.back:hover { color: var(--bone); }
.start {
display: inline-flex; align-items: center; gap: 12px;
background: var(--gold); color: #1a1410;
border: none; padding: 10px 26px;
font-family: inherit; font-size: 14px; font-weight: 800; letter-spacing: 0.16em;
cursor: pointer;
border-radius: 3px;
transition: filter 0.15s, transform 0.1s;
box-shadow: 0 6px 24px -10px var(--gold);
}
.start:hover:not(:disabled) { filter: brightness(1.08); transform: translateY(-1px); }
.start:active:not(:disabled) { transform: translateY(0); }
.start:disabled { background: var(--rule); color: var(--ash); cursor: not-allowed; box-shadow: none; }
.start .kbd {
font-size: 11px; opacity: 0.7;
border: 1px solid rgba(0,0,0,0.3); padding: 1px 6px; border-radius: 2px;
}
.setup[data-mode="human_vs_ai"] .start { background: var(--crimson); color: #fff; box-shadow: 0 6px 24px -10px var(--crimson); }
/* ---------- HUD footer ---------- */
.hud {
display: flex; gap: 26px; justify-content: center;
margin-top: 32px;
font-size: 10px; letter-spacing: 0.2em; color: var(--ash);
text-transform: uppercase;
border-top: 1px solid var(--rule); padding-top: 16px;
}
.hud code {
font-family: inherit; color: var(--gold); letter-spacing: 0.02em; text-transform: none;
}
/* ---------- responsive ---------- */
@media (max-width: 880px) {
.modes { grid-template-columns: 1fr; }
.sides { grid-template-columns: 1fr; }
.vs { padding: 8px 0; }
}
+175
View File
@@ -0,0 +1,175 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<title>ai-chess</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@200;400;700;800&family=Major+Mono+Display&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/menu.css" />
</head>
<body>
<div class="grain"></div>
<header class="topbar">
<div class="brand">AI·CHESS</div>
<div class="topbar-meta">
<span>two llm. one crown.</span>
<span class="sep">·</span>
<span>stockfish-judged</span>
<span class="sep">·</span>
<span class="ver">v0.1</span>
</div>
</header>
<main class="hero">
<div class="badge-row">
<span class="badge-line"></span>
<span class="badge">UNDERGROUND TOURNAMENT</span>
<span class="badge-line"></span>
</div>
<h1 class="title">
<span class="t1">AI</span><span class="t-dot">·</span><span class="t2">CHESS</span>
</h1>
<p class="tagline">две LLM выходят на доску. одна возвращается. без подсказок, без коучей, всё — на трэш-токе.</p>
<!-- Shown when a game is currently in progress: skip the picker and
offer to drop into the live view. -->
<section class="active-card" id="active-card" hidden>
<header class="active-head">
<span class="active-pulse"></span>
<span class="active-label">ROUND IN PROGRESS</span>
<span class="active-meta" id="active-meta"></span>
</header>
<div class="active-vs">
<div class="seat seat-white">
<div class="seat-pip">●</div>
<div class="seat-name" id="active-white-agent">…</div>
<div class="seat-sub" id="active-white-model">…</div>
<div class="seat-persona" id="active-white-persona">…</div>
</div>
<div class="active-divider">
<span class="active-vs-label">VS</span>
<span class="active-turn" id="active-turn">…</span>
</div>
<div class="seat seat-black">
<div class="seat-pip">○</div>
<div class="seat-name" id="active-black-agent">…</div>
<div class="seat-sub" id="active-black-model">…</div>
<div class="seat-persona" id="active-black-persona">…</div>
</div>
</div>
<div class="active-actions">
<a class="watch-btn" id="watch-btn" href="/ai-vs-ai">
<span>WATCH LIVE</span>
<span class="kbd">↩</span>
</a>
<button type="button" class="active-abort" id="active-abort">
abort current round
</button>
</div>
<p class="active-foot">
новая партия откроется когда эта закончится — мат / резигн / абort.
</p>
</section>
<section class="modes" id="modes">
<button class="mode" data-mode="ai_vs_ai" type="button">
<div class="mode-num">01</div>
<div class="mode-name">AI <span class="x">×</span> AI</div>
<div class="mode-desc">Две модели режутся за тебя. Выбираешь персонажей, ставишь на коне, смотришь.</div>
<div class="mode-tag tag-gold">LIVE</div>
</button>
<button class="mode" data-mode="human_vs_ai" type="button">
<div class="mode-num">02</div>
<div class="mode-name">HUMAN <span class="x">×</span> AI</div>
<div class="mode-desc">Сам садишься напротив. Шах, мат и в чате её мордой по доске.</div>
<div class="mode-tag tag-crimson">FIGHT</div>
</button>
<a class="mode mode-link" href="/games">
<div class="mode-num">03</div>
<div class="mode-name">GAMES <span class="x">·</span> STATS</div>
<div class="mode-desc">Архив прошлых драк, лидерборд персонажей, реплеи с эвалами.</div>
<div class="mode-tag tag-neutral">ARCHIVE</div>
</a>
</section>
<section class="setup" id="setup" hidden>
<div class="setup-head">
<span class="setup-step">step 02</span>
<span class="setup-title" id="setup-title">configure the fight</span>
<div class="setup-tools">
<button id="btn-swap" type="button" class="tool">⇄ swap</button>
<button id="btn-random" type="button" class="tool">🎲 random</button>
</div>
</div>
<div class="sides">
<fieldset class="side side-white" data-side="white">
<legend><span class="legend-pip"></span>WHITE</legend>
<label class="field">
<span>agent</span>
<select name="agent"></select>
</label>
<label class="field" data-when="ai">
<span>model</span>
<select name="model"></select>
</label>
<label class="field" data-when="ai">
<span>persona</span>
<select name="prompt"></select>
</label>
<p class="persona-desc" data-when="ai"></p>
<p class="human-note" data-when="human" hidden>controlled by you — moves via the board, no trash-talk wiring (yet).</p>
</fieldset>
<div class="vs">VS</div>
<fieldset class="side side-black" data-side="black">
<legend><span class="legend-pip"></span>BLACK</legend>
<label class="field">
<span>agent</span>
<select name="agent"></select>
</label>
<label class="field" data-when="ai">
<span>model</span>
<select name="model"></select>
</label>
<label class="field" data-when="ai">
<span>persona</span>
<select name="prompt"></select>
</label>
<p class="persona-desc" data-when="ai"></p>
<p class="human-note" data-when="human" hidden>controlled by you — moves via the board, no trash-talk wiring (yet).</p>
</fieldset>
</div>
<div id="setup-warning" hidden>
⚠ A game is currently in progress.
<button type="button" id="abort-current" class="link-abort">abort it</button>
to start a new one.
</div>
<div class="setup-foot">
<a class="back" href="#" id="back-link">← change mode</a>
<button id="start-btn" class="start" type="button">
<span>START</span>
<span class="kbd">↵</span>
</button>
</div>
</section>
<footer class="hud">
<span class="hud-cell">tmux: <code id="hud-tmux">…</code></span>
<span class="hud-cell">stockfish: <code id="hud-sf">…</code></span>
<span class="hud-cell">games played: <code id="hud-games">…</code></span>
</footer>
</main>
<script src="/static/menu.js" type="module"></script>
</body>
</html>
+335
View File
@@ -0,0 +1,335 @@
const $ = (id) => document.getElementById(id);
const STATE = {
options: null,
mode: null, // "ai_vs_ai" | "human_vs_ai" | null
inProgress: false,
game: null, // current game payload (only set when in progress)
bindings: null,
};
const SIDES = ["white", "black"];
function elSelect(side, name) {
return document.querySelector(`fieldset[data-side="${side}"] select[name="${name}"]`);
}
function elField(side, when) {
return document.querySelectorAll(`fieldset[data-side="${side}"] [data-when="${when}"]`);
}
// ---------- option loaders ----------
function fillAgentSelect(sel, agents) {
sel.innerHTML = "";
for (const a of agents) {
const o = document.createElement("option");
o.value = a;
o.textContent = a === "human" ? "you (human)" : a;
sel.appendChild(o);
}
}
function fillModelSelect(side) {
const agent = elSelect(side, "agent").value;
const sel = elSelect(side, "model");
sel.innerHTML = "";
if (agent === "human") return;
for (const m of (STATE.options.models[agent] || [])) {
const o = document.createElement("option");
o.value = m; o.textContent = m;
sel.appendChild(o);
}
}
function fillPromptSelect(side) {
const sel = elSelect(side, "prompt");
sel.innerHTML = "";
for (const p of STATE.options.prompts) {
const o = document.createElement("option");
o.value = p.id; o.textContent = p.label; o.dataset.desc = p.description;
sel.appendChild(o);
}
if (STATE.options.defaults?.prompt) sel.value = STATE.options.defaults.prompt;
updatePersonaDesc(side);
}
function updatePersonaDesc(side) {
const sel = elSelect(side, "prompt");
const target = document.querySelector(`fieldset[data-side="${side}"] .persona-desc`);
if (!sel || !target) return;
target.textContent = sel.options[sel.selectedIndex]?.dataset?.desc || "";
}
function refreshSide(side) {
const agent = elSelect(side, "agent").value;
fillModelSelect(side);
fillPromptSelect(side);
for (const el of elField(side, "ai")) el.hidden = (agent === "human");
for (const el of elField(side, "human")) el.hidden = (agent !== "human");
}
// ---------- mode selection ----------
function setMode(mode) {
STATE.mode = mode;
document.querySelectorAll(".mode").forEach((m) => {
m.setAttribute("aria-pressed", m.dataset.mode === mode ? "true" : "false");
});
const setup = $("setup");
setup.hidden = false;
setup.dataset.mode = mode;
$("setup-title").textContent =
mode === "ai_vs_ai" ? "configure the fight" : "you vs the silicon hustler";
// Set defaults per mode
const whiteAgentSel = elSelect("white", "agent");
const blackAgentSel = elSelect("black", "agent");
if (mode === "ai_vs_ai") {
fillAgentSelect(whiteAgentSel, STATE.options.agents);
fillAgentSelect(blackAgentSel, STATE.options.agents);
whiteAgentSel.value = STATE.options.agents[0];
blackAgentSel.value = STATE.options.agents[1] || STATE.options.agents[0];
} else if (mode === "human_vs_ai") {
// Default: human plays white, an AI plays black.
fillAgentSelect(whiteAgentSel, STATE.options.all_agents);
fillAgentSelect(blackAgentSel, STATE.options.all_agents);
whiteAgentSel.value = "human";
blackAgentSel.value = STATE.options.agents[0];
}
refreshSide("white");
refreshSide("black");
// scroll to setup
setTimeout(() => setup.scrollIntoView({ behavior: "smooth", block: "start" }), 60);
refreshGate();
}
// ---------- gating ----------
async function loadInProgress() {
try {
const s = await (await fetch("/api/state")).json();
STATE.inProgress = !!(s.game && !s.game.status?.result);
STATE.game = STATE.inProgress ? s.game : null;
STATE.bindings = STATE.inProgress ? s.bindings : null;
} catch (e) {
STATE.inProgress = false;
STATE.game = null;
STATE.bindings = null;
}
}
function refreshGate() {
$("setup-warning").hidden = !STATE.inProgress;
$("start-btn").disabled = STATE.inProgress;
}
// ---------- active game card ----------
function renderActiveCard() {
const card = $("active-card");
const modes = $("modes");
const setup = $("setup");
if (!STATE.inProgress) {
card.hidden = true;
modes.hidden = false;
return;
}
// Hide picker + setup, show the live card.
card.hidden = false;
modes.hidden = true;
setup.hidden = true;
const g = STATE.game || {};
const b = STATE.bindings || {};
const promptLabel = (id) => {
if (!id) return "";
const p = (STATE.options?.prompts || []).find(x => x.id === id);
return p ? p.label : id;
};
// Pull prompt out of game.agents (the dict committed by start_new_game) —
// bindings may not carry it.
const wA = g.agents?.white || {};
const bA = g.agents?.black || {};
$("active-white-agent").textContent = (wA.agent || "?");
$("active-white-model").textContent = wA.agent === "human" ? "controlled by you" : (wA.model || "?");
$("active-white-persona").textContent = wA.agent === "human" ? "" : promptLabel(wA.prompt);
$("active-black-agent").textContent = (bA.agent || "?");
$("active-black-model").textContent = bA.agent === "human" ? "controlled by you" : (bA.model || "?");
$("active-black-persona").textContent = bA.agent === "human" ? "" : promptLabel(bA.prompt);
// current state strip
const moves = (g.history || []).filter(h => h.san).length;
$("active-meta").textContent = `move ${Math.ceil(moves/2) + (g.side_to_move === "white" ? 0 : 0)} · ${moves} half-moves · ${g.id ? g.id.slice(0,10) : ""}…`;
const sideRu = g.side_to_move === "white" ? "белые" : "чёрные";
const moverAgent = (g.side_to_move === "white" ? wA.agent : bA.agent) || "?";
$("active-turn").textContent = `${moverAgent} (${sideRu}) thinks…`;
// Pick the right destination for watch
const watchHref = (wA.agent === "human" || bA.agent === "human") ? "/play" : "/ai-vs-ai";
$("watch-btn").setAttribute("href", watchHref);
}
// ---------- HUD ----------
async function refreshHud() {
try {
const s = await (await fetch("/api/state")).json();
$("hud-sf").textContent = `depth ${s.settings?.stockfish_depth ?? "?"}`;
if (s.game && !s.game.status?.result) {
$("hud-tmux").textContent = "session ‘chess’ running";
} else {
$("hud-tmux").textContent = "idle";
}
} catch (e) { /* ignore */ }
try {
// games count is allowed only when no active game.
const r = await fetch("/api/stats");
if (r.ok) {
const j = await r.json();
$("hud-games").textContent = String(j.total_games);
} else {
$("hud-games").textContent = "—";
}
} catch (e) {
$("hud-games").textContent = "—";
}
}
// ---------- start ----------
function readOverrides() {
const overrides = { white: {}, black: {} };
for (const side of SIDES) {
const agent = elSelect(side, "agent").value;
overrides[side].agent = agent;
if (agent !== "human") {
overrides[side].model = elSelect(side, "model").value;
overrides[side].prompt = elSelect(side, "prompt").value;
}
}
return overrides;
}
async function start() {
const overrides = readOverrides();
const r = await fetch("/api/new-game", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ overrides }),
});
if (r.status === 409) {
STATE.inProgress = true;
refreshGate();
return;
}
if (!r.ok) {
const detail = await r.text();
alert("Failed to start: " + detail);
return;
}
// Kick off the first prompt for AI side(s)
fetch("/api/dispatch-first", { method: "POST" }).catch(() => {});
// Route to the right gameplay page
const isHumanGame = (
overrides.white.agent === "human" || overrides.black.agent === "human"
);
location.href = isHumanGame ? "/play" : "/ai-vs-ai";
}
// ---------- wiring ----------
async function init() {
STATE.options = await (await fetch("/api/options")).json();
await loadInProgress();
renderActiveCard();
refreshHud();
setInterval(refreshHud, 5000);
// Poll the active-card payload so the meta strip ('move N · whose turn')
// updates without a page reload. Skipped while no game is live.
setInterval(async () => {
const before = STATE.inProgress;
await loadInProgress();
renderActiveCard();
// Game just ended? Unblock the picker.
if (before && !STATE.inProgress) {
$("modes").hidden = false;
}
}, 3000);
// Mode picker
document.querySelectorAll(".mode[data-mode]").forEach((el) => {
el.addEventListener("click", () => setMode(el.dataset.mode));
});
// Side change handlers
for (const side of SIDES) {
elSelect(side, "agent").addEventListener("change", () => refreshSide(side));
elSelect(side, "prompt").addEventListener("change", () => updatePersonaDesc(side));
}
// Swap & randomize
$("btn-swap").addEventListener("click", () => {
for (const name of ["agent", "model", "prompt"]) {
const w = elSelect("white", name);
const b = elSelect("black", name);
if (!w || !b) continue;
const tmp = w.value; w.value = b.value; b.value = tmp;
}
refreshSide("white"); refreshSide("black");
});
$("btn-random").addEventListener("click", () => {
const pool = (STATE.mode === "human_vs_ai")
? [...STATE.options.agents] // randomize only the AI agent (keep human side)
: [...STATE.options.agents];
pool.sort(() => Math.random() - 0.5);
if (STATE.mode === "ai_vs_ai") {
elSelect("white", "agent").value = pool[0];
elSelect("black", "agent").value = pool[1] || pool[0];
} else {
// Find which side is currently AI and randomize that one
for (const side of SIDES) {
if (elSelect(side, "agent").value !== "human") {
elSelect(side, "agent").value = pool[Math.floor(Math.random() * pool.length)];
}
}
}
refreshSide("white"); refreshSide("black");
// Random model + prompt for AI sides
for (const side of SIDES) {
const agent = elSelect(side, "agent").value;
if (agent === "human") continue;
const models = STATE.options.models[agent];
elSelect(side, "model").value = models[Math.floor(Math.random() * models.length)];
const prompts = STATE.options.prompts.map(p => p.id);
elSelect(side, "prompt").value = prompts[Math.floor(Math.random() * prompts.length)];
updatePersonaDesc(side);
}
});
// Back link → close setup
$("back-link").addEventListener("click", (e) => {
e.preventDefault();
$("setup").hidden = true;
STATE.mode = null;
document.querySelectorAll(".mode").forEach((m) => m.setAttribute("aria-pressed", "false"));
});
// Abort current (inside the setup dialog warning)
$("abort-current").addEventListener("click", async () => {
await fetch("/api/abort-game", { method: "POST" });
setTimeout(async () => {
await loadInProgress(); refreshGate(); refreshHud(); renderActiveCard();
}, 200);
});
// Abort current from the active-card (visible only when a game is live)
$("active-abort").addEventListener("click", async () => {
if (!confirm("Прервать текущую партию?")) return;
await fetch("/api/abort-game", { method: "POST" });
setTimeout(async () => { await loadInProgress(); renderActiveCard(); refreshHud(); }, 200);
});
// Start
$("start-btn").addEventListener("click", start);
// Enter starts the game when setup is open and not blocked
window.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !$("setup").hidden && !$("start-btn").disabled) {
e.preventDefault(); start();
}
});
}
init();
+294
View File
@@ -0,0 +1,294 @@
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
background: #0f0f12;
color: #e7e5e4;
font-size: 13px;
}
/* ============ layout: 2 columns ============ */
#layout {
display: grid;
grid-template-columns: minmax(440px, min(900px, 60vw)) minmax(380px, 1fr);
grid-template-rows: 1fr;
grid-template-areas: "board chat";
height: 100vh;
width: 100vw;
gap: 20px;
padding: 14px;
overflow: hidden;
}
#board-col { grid-area: board; min-width: 0; min-height: 0; overflow: hidden; display: flex; flex-direction: column; gap: 10px; }
#chat-col { grid-area: chat; min-width: 0; min-height: 0; overflow: hidden; }
/* ============ board area ============ */
#board-row {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 12px;
flex: 1 1 auto;
min-height: 0;
min-width: 0;
}
#board {
/* size set imperatively by fitBoard() */
background: #444;
border-radius: 4px;
overflow: hidden;
flex: 0 0 auto;
}
#board cg-container { width: 100% !important; height: 100% !important; }
#board-footer {
display: flex; gap: 10px; align-items: center;
padding: 4px 2px;
font-size: 12.5px;
}
#status-line { flex: 0 0 auto; opacity: 0.85; }
#think-meter {
flex: 1;
font-size: 12px;
opacity: 0.75;
display: inline-flex;
align-items: baseline;
gap: 4px;
letter-spacing: 0.01em;
}
.think-dot {
display: inline-block;
width: 6px; height: 6px;
border-radius: 50%;
background: #c0a060;
animation: think-pulse 1.4s ease-in-out infinite;
align-self: center;
margin-right: 4px;
}
.think-who { color: #d8d4c8; font-weight: 600; }
.think-time {
font-variant-numeric: tabular-nums;
color: #f0d090;
font-weight: 600;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
@keyframes think-pulse {
0%, 100% { opacity: 0.3; transform: scale(0.9); }
50% { opacity: 1; transform: scale(1.1); }
}
/* ============ eval bar ============ */
#eval-col {
position: relative;
width: 36px;
flex: 0 0 36px;
background: #2a2a30; /* BLACK half on top */
border-radius: 4px;
overflow: hidden;
box-shadow: inset 0 0 0 1px #3a3a40;
}
#eval-col::after { /* 50/50 reference line */
content: "";
position: absolute;
left: 0; right: 0; top: 50%;
height: 1px; background: rgba(255,255,255,0.12);
pointer-events: none; z-index: 2;
}
#eval-fill { /* WHITE half from bottom */
position: absolute;
left: 0; right: 0; bottom: 0;
height: 50%;
background: linear-gradient(180deg, #fafafa 0%, #e0ddd5 100%);
transition: height 0.4s ease;
z-index: 1;
}
#eval-text {
position: absolute;
left: 0; right: 0;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
font-size: 10.5px;
font-weight: 700;
letter-spacing: -0.03em;
text-align: center;
font-variant-numeric: tabular-nums;
pointer-events: none; z-index: 3;
transition: color 0.2s, top 0.4s, bottom 0.4s;
/* default — slight white or even: text near bottom on white half, dark */
bottom: 4px; top: auto;
color: #1a1a1a;
}
#eval-col.advantage-black #eval-text {
bottom: auto; top: 4px;
color: #e7e5e4;
}
/* ============ floating moves panel (below board) ============ */
#moves-floating {
display: flex; align-items: flex-start; gap: 8px;
background: #15151a;
border: 1px solid #2a2a30;
border-radius: 8px;
padding: 6px 10px;
max-height: 84px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
}
.moves-label {
font-size: 10px; opacity: 0.45; text-transform: uppercase;
letter-spacing: 0.1em; padding-top: 2px; flex: 0 0 auto;
}
#history-list {
list-style: none; padding: 0; margin: 0;
display: flex; flex-wrap: wrap; gap: 2px 8px;
font-size: 12.5px; overflow-y: auto; flex: 1;
font-variant-numeric: tabular-nums;
}
#history-list li { padding: 1px 4px; border-radius: 3px; cursor: pointer; }
#history-list li.ply-num { opacity: 0.4; cursor: default; padding-right: 2px; }
#history-list li:not(.ply-num):hover { background: #25252b; }
#history-list li.active { background: #3d342a; color: #f0d090; }
/* ============ chat panel (right, full height) ============ */
#chat-col { display: flex; flex-direction: column; background: #15151a; border-radius: 8px; overflow: hidden; border: 1px solid #2a2a30; }
.col-header {
display: flex; justify-content: space-between; align-items: center;
padding: 6px 10px; opacity: 0.6; font-size: 10px; text-transform: uppercase;
letter-spacing: 0.1em; border-bottom: 1px solid #2a2a30;
}
#chat-list {
flex: 1; overflow-y: auto; padding: 10px;
display: flex; flex-direction: column; gap: 8px;
}
.bubble {
padding: 7px 10px 9px;
border-radius: 9px;
border: 1px solid transparent;
cursor: pointer;
line-height: 1.4;
word-wrap: break-word;
transition: outline-color 0.1s ease;
outline: 1px solid transparent;
outline-offset: 2px;
}
.bubble:hover { outline-color: #555; }
.bubble.active { outline-color: #c0a060; }
.bubble-white { background: #f0eee6; color: #16161a; align-self: flex-start; max-width: 92%; }
.bubble-black { background: #1f1e22; color: #e7e5e4; align-self: flex-end; max-width: 92%; border-color: #2a2a30; }
.bubble-meta {
font-size: 10px; opacity: 0.65; margin-bottom: 3px;
display: flex; justify-content: space-between; gap: 6px; align-items: center;
}
.bubble-san { font-weight: 700; opacity: 0.95; }
.bubble-body { font-size: 13px; }
.bubble-empty { font-style: italic; opacity: 0.5; }
/* ============ buttons + dialog ============ */
button {
background: #25252b; color: #e7e5e4; border: 1px solid #34343a;
padding: 4px 10px; cursor: pointer; border-radius: 4px; font-size: 12px;
}
button:hover { background: #2e2e36; }
#live-btn { background: #3d342a; color: #f0d090; }
#abort-game { background: #3a2222; color: #e09080; border-color: #5a3030; }
#abort-game:hover { background: #4a2a2a; }
dialog {
background: #15151a; color: #e7e5e4; border: 1px solid #2a2a30;
padding: 16px; border-radius: 8px;
box-shadow: 0 10px 30px rgba(0,0,0,0.6);
}
dialog::backdrop { background: rgba(0,0,0,0.55); }
dialog form { display: flex; flex-direction: column; gap: 12px; min-width: 320px; }
dialog menu { display: flex; gap: 8px; justify-content: flex-end; padding: 0; margin: 0; }
dialog h3 { margin: 0; font-size: 14px; letter-spacing: 0.06em; text-transform: uppercase; opacity: 0.85; }
dialog select, dialog input[type="number"], dialog input[type="text"] {
background: #1f1f25; color: #e7e5e4; border: 1px solid #34343a;
border-radius: 4px; padding: 4px 6px; font-size: 12px;
}
/* setup dialog */
#setup-dialog { min-width: 580px; }
.setup-header { display: flex; justify-content: space-between; align-items: center; }
.setup-actions { display: flex; gap: 8px; }
.setup-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
.setup-side {
border: 1px solid #34343a; border-radius: 6px; padding: 10px 12px;
display: flex; flex-direction: column; gap: 8px;
background: #1a1a20;
}
.setup-side legend { padding: 0 6px; font-size: 11px; letter-spacing: 0.1em; opacity: 0.8; }
.setup-white legend { color: #e7e5e4; }
.setup-black legend { color: #c0a060; }
.setup-side label {
display: flex; flex-direction: column; gap: 3px;
font-size: 10px; opacity: 0.55; text-transform: uppercase; letter-spacing: 0.08em;
}
.setup-side select { font-size: 13px; opacity: 1; text-transform: none; letter-spacing: 0; }
.setup-promptdesc {
margin: 4px 0 0; font-size: 11px; opacity: 0.55; line-height: 1.4;
min-height: 2.4em;
}
#setup-warning { background: #3a2a1a; border: 1px solid #5a4020; color: #f0c080; padding: 8px 10px; border-radius: 4px; font-size: 12px; margin: 0; }
#setup-start { background: #3d342a; color: #f0d090; }
#games-link { font-size: 12px; color: #c0a060; text-decoration: none; margin-right: 4px; }
#games-link:hover { text-decoration: underline; }
#games-link.disabled { color: #555; cursor: not-allowed; }
#games-link.disabled:hover { text-decoration: none; }
/* ============ /games page ============ */
#games-page {
max-width: 1500px; margin: 0 auto; padding: 24px;
display: flex; flex-direction: column; gap: 18px;
}
#games-page-header {
display: flex; align-items: baseline; gap: 16px;
border-bottom: 1px solid #2a2a30; padding-bottom: 12px;
}
#games-page-header h1 { margin: 0; font-size: 18px; letter-spacing: 0.05em; }
#games-count { opacity: 0.55; font-size: 12px; }
#back-link { color: #c0a060; text-decoration: none; }
#back-link:hover { text-decoration: underline; }
#blocked-banner {
background: #3a2a1a; border: 1px solid #5a4020; color: #f0c080;
padding: 12px 14px; border-radius: 6px;
}
#blocked-banner a { color: #f0d090; }
#page-grid {
display: grid; grid-template-columns: 420px 1fr; gap: 18px;
}
#stats-pane, #games-pane {
background: #15151a; border: 1px solid #2a2a30; border-radius: 8px;
overflow: hidden;
}
#stats-pane table, #games-pane table {
width: 100%; border-collapse: collapse; font-size: 12.5px;
}
#stats-pane th, #stats-pane td, #games-pane th, #games-pane td {
padding: 6px 10px; text-align: left; border-bottom: 1px solid #1f1f24;
}
#stats-pane th, #games-pane th {
font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em;
opacity: 0.55; font-weight: 600;
}
#stats-pane td:nth-child(n+2), #games-pane td:nth-child(n+4) { font-variant-numeric: tabular-nums; }
.persona { font-size: 10px; opacity: 0.5; }
.result-1-0 { color: #f0eee6; font-weight: 700; }
.result-0-1 { color: #c0a060; font-weight: 700; }
.result-1_2-1_2 { color: #88c0a0; font-weight: 700; }
.result-_ { opacity: 0.4; }
/* replay */
#replay-wrap { border-top: 1px solid #2a2a30; padding: 14px; }
#replay-layout { display: grid; grid-template-columns: 360px 1fr; gap: 16px; }
#replay-board { width: 360px; aspect-ratio: 1/1; }
#replay-side { display: flex; flex-direction: column; gap: 10px; min-height: 0; }
#replay-controls { display: flex; gap: 6px; align-items: center; font-size: 12px; }
#replay-controls button { padding: 2px 8px; }
#replay-ply { opacity: 0.6; margin-left: 8px; }
#replay-eval { margin-left: auto; font-weight: 700; color: #f0d090; }
#replay-history { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 6px; max-height: 540px; overflow-y: auto; }
.replay-row { font-size: 12px; }
#replay-close { background: #25252b; }