-
- Recommended Move
- Stockfish 16
-
-
-
-
-
- ⏳
- Ready. Press "Start Analysis" or choose a Quick Test position.
-
-
-
-
-
-
-
-
-
-
-
- Ready for moves.
-
-
-
-
-
-
-
🏆
-
-
Win Mode
-
Calculates sharp, decisive, high-accuracy moves tailored to win quickly.
-
-
-
-
-
-
-
-
-
-
-
+
+
-
-
Backend API Settings
-
Configure the Railway or local FastAPI backend server URL:
-
-
Testing connection…
-
- Test Connection
- Reset Default
- Save & Close
-
-
+
Engine connection × Choose the server that analyzes your board. Leave the address empty to use this website’s server.
Server address
Test connection Reset Save
-
-
+
diff --git a/frontend/overlay.js b/frontend/overlay.js
new file mode 100644
index 0000000..923a7fe
--- /dev/null
+++ b/frontend/overlay.js
@@ -0,0 +1,64 @@
+/** Geometry shared by the camera overlay and its regression tests. */
+export function fitInside(width, height, size = 1000) {
+ const w = width >= height ? size : size * width / height;
+ const h = height >= width ? size : size * height / width;
+ return { x: (size - w) / 2, y: (size - h) / 2, width: w, height: h };
+}
+
+// Project unit board coordinates into the actual camera quadrilateral. A
+// bilinear interpolation is insufficient for a tilted/perspective board.
+export function projectPoint(corners, x, y) {
+ const [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] = corners;
+ const dx1 = x1 - x2, dx2 = x3 - x2, dx3 = x0 - x1 + x2 - x3;
+ const dy1 = y1 - y2, dy2 = y3 - y2, dy3 = y0 - y1 + y2 - y3;
+ const det = dx1 * dy2 - dx2 * dy1;
+ let g = 0, h = 0;
+ if (Math.abs(dx3) + Math.abs(dy3) > 1e-10 && Math.abs(det) > 1e-10) {
+ g = (dx3 * dy2 - dx2 * dy3) / det;
+ h = (dx1 * dy3 - dx3 * dy1) / det;
+ }
+ const a = x1 - x0 + g * x1, b = x3 - x0 + h * x3;
+ const d = y1 - y0 + g * y1, e = y3 - y0 + h * y3;
+ const denominator = g * x + h * y + 1;
+ return [(a * x + b * y + x0) / denominator, (d * x + e * y + y0) / denominator];
+}
+
+export function squarePosition(square, orientation = "w") {
+ if (!/^[a-h][1-8]$/.test(square)) throw new Error("Invalid chess square");
+ const col = square.charCodeAt(0) - 97, row = 8 - Number(square[1]);
+ return orientation === "b" ? [7 - col, 7 - row] : [col, row];
+}
+
+export function moveGeometry(uci, corners, orientation = "w") {
+ if (!/^[a-h][1-8][a-h][1-8][qrbn]?$/.test(uci)) return null;
+ const from = squarePosition(uci.slice(0, 2), orientation);
+ const to = squarePosition(uci.slice(2, 4), orientation);
+ const point = (x, y) => projectPoint(corners, x / 8, y / 8);
+ return {
+ from: point(from[0] + .5, from[1] + .5),
+ to: point(to[0] + .5, to[1] + .5),
+ target: [[0, 0], [1, 0], [1, 1], [0, 1]].map(([x, y]) => point(to[0] + x, to[1] + y)),
+ };
+}
+
+export function validCorners(corners) {
+ if (!Array.isArray(corners) || corners.length !== 4 || !corners.every(p =>
+ Array.isArray(p) && p.length === 2 && p.every(v => Number.isFinite(v) && v >= 0 && v <= 1))) return false;
+ const crosses = corners.map((p, i) => {
+ const q = corners[(i + 1) % 4], r = corners[(i + 2) % 4];
+ return (q[0] - p[0]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[0] - q[0]);
+ });
+ return crosses.every(v => v > .0001);
+}
+
+export function resolveApiBase({ origin, search = "", stored = "", fallback }) {
+ const override = new URLSearchParams(search).get("api") || stored;
+ if (override) {
+ const url = new URL(override);
+ if (!["http:", "https:"].includes(url.protocol)) throw new Error("Use an HTTP or HTTPS server URL");
+ return url.origin;
+ }
+ // Railway serves both the app and API: it must use its own deployment.
+ if (/\.up\.railway\.app$/.test(new URL(origin).hostname) || /^(localhost|127\.0\.0\.1)$/.test(new URL(origin).hostname)) return origin;
+ return fallback;
+}
diff --git a/frontend/style.css b/frontend/style.css
index 9603e67..0c744c4 100644
--- a/frontend/style.css
+++ b/frontend/style.css
@@ -1,957 +1,232 @@
-/* ═══════════════════════════════════════════════════════════
- Chess Vision Coach — Stylesheet v2.0
- Modern Dark Theme with Cyber-Emerald & Amber Accents
- ═══════════════════════════════════════════════════════════ */
-
-*, *::before, *::after {
- box-sizing: border-box;
- margin: 0;
- padding: 0;
-}
-
-:root {
- color-scheme: light dark;
- --bg-deep: #090b0e;
- --bg-card: #12161f;
- --bg-card2: #1a202c;
- --bg-card-hover: #222938;
- --border-subtle: rgba(255, 255, 255, 0.08);
- --border-focus: rgba(16, 185, 129, 0.5);
-
- --accent: #10b981;
- --accent-light: #34d399;
- --accent-glow: rgba(16, 185, 129, 0.25);
-
- --accent2: #f59e0b;
- --accent2-glow: rgba(245, 158, 11, 0.2);
-
- --primary: #6366f1;
- --danger: #ef4444;
- --text: #f9fafb;
- --text-dim: #9ca3af;
- --text-muted: #6b7280;
-
- --radius-lg: 14px;
- --radius-md: 10px;
- --radius-sm: 6px;
- --gap: 16px;
-
- accent-color: var(--accent);
- scrollbar-color: var(--bg-card2) transparent;
-}
-
-html {
- font-size: 16px;
- scroll-behavior: smooth;
-}
-
-body {
- font-family: 'Space Grotesk', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
- background: var(--bg-deep);
- background-image:
- radial-gradient(circle at 15% 15%, rgba(16, 185, 129, 0.05) 0%, transparent 40%),
- radial-gradient(circle at 85% 85%, rgba(99, 102, 241, 0.04) 0%, transparent 40%);
- background-attachment: fixed;
- color: var(--text);
- min-height: 100dvh;
- display: flex;
- flex-direction: column;
- line-height: 1.5;
-}
-
-/* ── Accessibility ───────────────────────────────── */
-.visually-hidden {
- position: absolute !important;
- clip-path: inset(50%) !important;
- overflow: hidden !important;
- width: 1px !important;
- height: 1px !important;
- margin: -1px !important;
- padding: 0 !important;
- border: 0 !important;
- white-space: nowrap !important;
-}
-
-:focus-visible {
- outline: 2px solid var(--accent);
- outline-offset: 2px;
-}
-
-/* ── Header ─────────────────────────────────────── */
-.header {
- background: rgba(18, 22, 31, 0.85);
- backdrop-filter: blur(12px);
- -webkit-backdrop-filter: blur(12px);
- border-bottom: 1px solid var(--border-subtle);
- padding: 0 24px;
- height: 64px;
- position: sticky;
- top: 0;
- z-index: 100;
-}
-
-.header-inner {
- max-width: 1140px;
- margin: 0 auto;
- height: 100%;
- display: flex;
- align-items: center;
- justify-content: space-between;
-}
-
-.logo {
- display: flex;
- align-items: center;
- gap: 12px;
-}
-
-.logo-icon {
- font-size: 1.8rem;
- line-height: 1;
- filter: drop-shadow(0 0 8px var(--accent-glow));
-}
-
-.logo-titles {
- display: flex;
- flex-direction: column;
-}
-
-.logo-text {
- font-weight: 700;
- font-size: 1.15rem;
- letter-spacing: -0.02em;
- color: var(--text);
-}
-
-.logo-badge {
- font-size: 0.68rem;
- font-weight: 600;
- text-transform: uppercase;
- letter-spacing: 0.08em;
- color: var(--accent);
-}
-
-/* Status Pill */
-.status-pill {
- display: flex;
- align-items: center;
- gap: 8px;
- background: var(--bg-card2);
- border: 1px solid var(--border-subtle);
- border-radius: 999px;
- padding: 6px 16px;
- font-size: 0.82rem;
- font-family: inherit;
- color: var(--text-dim);
- cursor: pointer;
- transition: all 0.2s ease;
-}
-
-.status-pill:hover {
- border-color: var(--accent);
- background: var(--bg-card-hover);
-}
-
-.status-dot {
- width: 9px;
- height: 9px;
- border-radius: 50%;
- background: #6b7280;
- transition: all 0.3s ease;
-}
-
-.status-pill.online .status-dot {
- background: var(--accent);
- box-shadow: 0 0 10px var(--accent);
-}
-.status-pill.online .status-label {
- color: var(--accent-light);
- font-weight: 600;
-}
-
-.status-pill.offline .status-dot {
- background: var(--danger);
- box-shadow: 0 0 8px rgba(239, 68, 68, 0.4);
-}
-.status-pill.offline .status-label {
- color: var(--danger);
-}
-
-.status-pill.connecting .status-dot {
- background: var(--accent2);
- animation: pulse 1s infinite alternate;
-}
-
-/* ── Main Layout ────────────────────────────────── */
-.main {
- flex: 1;
- max-width: 1140px;
- width: 100%;
- margin: 0 auto;
- padding: var(--gap);
- display: grid;
- grid-template-columns: 1.05fr 0.95fr;
- gap: var(--gap);
- align-items: start;
-}
-
-@media (max-width: 820px) {
- .main {
- grid-template-columns: 1fr;
- padding: 12px;
- }
-}
-
-.col {
- display: flex;
- flex-direction: column;
- gap: var(--gap);
-}
-
-/* ── Universal Cards ────────────────────────────── */
-.card {
- background: var(--bg-card);
- border: 1px solid var(--border-subtle);
- border-radius: var(--radius-lg);
- padding: 20px;
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
- transition: border-color 0.2s ease;
-}
-
-.card:hover {
- border-color: rgba(255, 255, 255, 0.12);
-}
-
-.card-label {
- font-size: 0.74rem;
- font-weight: 700;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-dim);
- margin-bottom: 14px;
- display: flex;
- align-items: center;
- justify-content: space-between;
-}
-
-/* ── Input Mode Tabs ────────────────────────────── */
-.mode-tabs-card {
- padding: 8px;
-}
-
-.tab-group {
- display: flex;
- gap: 6px;
- background: var(--bg-deep);
- padding: 4px;
- border-radius: var(--radius-md);
-}
-
-.tab-btn {
- flex: 1;
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 6px;
- background: transparent;
- border: none;
- border-radius: var(--radius-sm);
- color: var(--text-dim);
- font-family: inherit;
- font-size: 0.85rem;
- font-weight: 600;
- padding: 10px 8px;
- cursor: pointer;
- transition: all 0.2s ease;
-}
-
-.tab-btn:hover {
- color: var(--text);
- background: rgba(255, 255, 255, 0.04);
-}
-
-.tab-btn.active {
- background: var(--bg-card2);
- color: var(--accent);
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
-}
-
-/* ── Camera Card ────────────────────────────────── */
-.camera-wrapper {
- position: relative;
- background: #000;
- border-radius: var(--radius-md);
- overflow: hidden;
- aspect-ratio: 4 / 3;
- box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.8);
-}
-
-#cameraFeed {
- width: 100%;
- height: 100%;
- object-fit: cover;
- display: block;
-}
-
-.live-indicator {
- font-size: 0.68rem;
- font-weight: 700;
- color: #ef4444;
- letter-spacing: 0.05em;
- animation: pulse 1s infinite alternate;
-}
-
-.camera-overlay {
- position: absolute;
- inset: 0;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- text-align: center;
- padding: 24px;
- background: rgba(10, 14, 20, 0.88);
- color: var(--text);
- transition: opacity 0.3s;
-}
-
-.camera-overlay.hidden {
- opacity: 0;
- pointer-events: none;
-}
-
-.overlay-icon {
- font-size: 2.8rem;
- margin-bottom: 8px;
- color: var(--accent);
-}
-
-.overlay-title {
- font-size: 1rem;
- font-weight: 600;
- margin-bottom: 4px;
-}
-
-.overlay-sub {
- font-size: 0.82rem;
- color: var(--text-dim);
- max-width: 320px;
-}
-
-/* ── Drag & Drop Photo Upload ───────────────────── */
-.upload-dropzone {
- border: 2px dashed rgba(255, 255, 255, 0.15);
- border-radius: var(--radius-md);
- padding: 36px 20px;
- text-align: center;
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 8px;
- cursor: pointer;
- background: var(--bg-deep);
- transition: all 0.2s ease;
-}
-
-.upload-dropzone:hover,
-.upload-dropzone.dragover {
- border-color: var(--accent);
- background: rgba(16, 185, 129, 0.04);
-}
-
-.upload-icon {
- font-size: 2.4rem;
- color: var(--accent);
-}
-
-.upload-text {
- font-size: 0.92rem;
- color: var(--text);
-}
-
-.upload-link {
- color: var(--accent);
- text-decoration: underline;
- cursor: pointer;
-}
-
-.upload-hint {
- font-size: 0.75rem;
- color: var(--text-muted);
-}
-
-/* ── Presets & Quick Test ───────────────────────── */
-.presets-intro {
- font-size: 0.84rem;
- color: var(--text-dim);
- margin-bottom: 12px;
-}
-
-.preset-buttons {
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 8px;
- margin-bottom: 16px;
-}
-
-@media (max-width: 500px) {
- .preset-buttons {
- grid-template-columns: 1fr;
- }
-}
-
-.preset-chip {
- background: var(--bg-card2);
- border: 1px solid var(--border-subtle);
- border-radius: var(--radius-sm);
- color: var(--text);
- font-family: inherit;
- font-size: 0.82rem;
- font-weight: 600;
- padding: 10px 12px;
- text-align: left;
- cursor: pointer;
- transition: all 0.2s ease;
-}
-
-.preset-chip:hover {
- border-color: var(--accent);
- background: var(--bg-card-hover);
-}
-
-.preset-chip.active {
- border-color: var(--accent);
- background: rgba(16, 185, 129, 0.12);
- color: var(--accent-light);
-}
-
-.custom-fen-row {
- display: flex;
- gap: 8px;
-}
-
-.custom-fen-input {
- flex: 1;
- background: var(--bg-deep);
- border: 1px solid var(--border-subtle);
- border-radius: var(--radius-sm);
- color: var(--text);
- font-family: 'Space Mono', monospace;
- font-size: 0.8rem;
- padding: 10px 12px;
- outline: none;
- transition: border-color 0.2s;
-}
-
-.custom-fen-input:focus {
- border-color: var(--accent);
-}
-
-/* ── Board preview card ─────────────────────────── */
-.board-wrapper {
- border-radius: var(--radius-md);
- overflow: hidden;
- background: #000;
- border: 1px solid var(--border-subtle);
-}
-
-.board-wrapper img {
- width: 100%;
- display: block;
-}
-
-.conf-badge {
- font-size: 0.75rem;
- background: var(--bg-card2);
- border: 1px solid rgba(16, 185, 129, 0.3);
- border-radius: 999px;
- padding: 3px 10px;
- color: var(--accent-light);
- font-family: 'Space Mono', monospace;
- font-weight: 700;
-}
-
-/* ── Config card ────────────────────────────────── */
-.control-group {
- margin-bottom: 20px;
-}
-
-.ctrl-label {
- display: flex;
- align-items: center;
- justify-content: space-between;
- font-size: 0.84rem;
- font-weight: 600;
- color: var(--text-dim);
- margin-bottom: 8px;
-}
-
-.elo-hint {
- font-family: 'Space Mono', monospace;
- font-size: 0.82rem;
- color: var(--accent2);
- font-weight: 700;
-}
-
-/* Toggle buttons */
-.toggle-group {
- display: flex;
- gap: 8px;
-}
-
-.toggle-btn {
- flex: 1;
- background: var(--bg-card2);
- border: 1.5px solid var(--border-subtle);
- border-radius: var(--radius-md);
- color: var(--text-dim);
- font-family: inherit;
- font-size: 0.88rem;
- font-weight: 600;
- padding: 10px 8px;
- cursor: pointer;
- transition: all 0.15s ease;
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 8px;
-}
-
-.toggle-btn:hover {
- border-color: rgba(255, 255, 255, 0.2);
- color: var(--text);
-}
-
-.toggle-btn.active {
- background: var(--accent);
- border-color: var(--accent);
- color: #062b1a;
- font-weight: 700;
- box-shadow: 0 2px 12px var(--accent-glow);
-}
-
-.piece-icon {
- font-size: 1.2rem;
-}
-
-/* Depth slider */
-.depth-row {
- display: flex;
- align-items: center;
- gap: 14px;
-}
-
-input[type="range"] {
- flex: 1;
- -webkit-appearance: none;
- appearance: none;
- height: 6px;
- border-radius: 3px;
- background: var(--bg-card2);
- outline: none;
-}
-
-input[type="range"]::-webkit-slider-thumb {
- -webkit-appearance: none;
- appearance: none;
- width: 20px;
- height: 20px;
- border-radius: 50%;
- background: var(--accent);
- cursor: pointer;
- box-shadow: 0 0 10px var(--accent-glow);
- transition: transform 0.1s;
-}
-
-input[type="range"]::-webkit-slider-thumb:hover {
- transform: scale(1.15);
-}
-
-.depth-val {
- font-family: 'Space Mono', monospace;
- font-size: 1.2rem;
- font-weight: 700;
- color: var(--accent2);
- min-width: 28px;
- text-align: right;
-}
-
-.elo-note {
- font-size: 0.72rem;
- color: var(--text-muted);
- margin-top: 6px;
-}
-
-/* Action Buttons */
-.btn-row {
- display: flex;
- gap: 10px;
- margin-top: 8px;
-}
-
-.btn {
- font-family: inherit;
- font-size: 0.92rem;
- font-weight: 700;
- padding: 12px 18px;
- border-radius: var(--radius-md);
- border: none;
- cursor: pointer;
- transition: all 0.15s ease;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- gap: 6px;
-}
-
-.btn-start {
- flex: 1.4;
- background: var(--accent);
- color: #062b1a;
- box-shadow: 0 4px 14px var(--accent-glow);
-}
-
-.btn-start:hover:not(:disabled) {
- background: var(--accent-light);
- transform: translateY(-1px);
-}
-
-.btn-stop {
- flex: 1;
- background: var(--bg-card2);
- color: var(--danger);
- border: 1.5px solid var(--danger);
-}
-
-.btn-stop:hover:not(:disabled) {
- background: var(--danger);
- color: #fff;
-}
-
-.btn-secondary {
- background: var(--bg-card2);
- color: var(--text);
- border: 1px solid var(--border-subtle);
- font-size: 0.85rem;
-}
-
-.btn-secondary:hover {
- background: var(--bg-card-hover);
- border-color: rgba(255, 255, 255, 0.2);
-}
-
-.btn:disabled {
- opacity: 0.35;
- cursor: not-allowed;
- transform: none !important;
-}
-
-/* ── Move Output Card ───────────────────────────── */
-.move-card {
- position: relative;
- overflow: hidden;
-}
-
-.engine-badge {
- font-family: 'Space Mono', monospace;
- font-size: 0.7rem;
- font-weight: 700;
- color: var(--text-dim);
- background: var(--bg-card2);
- padding: 3px 10px;
- border-radius: 999px;
- border: 1px solid var(--border-subtle);
-}
-
-.move-display {
- background: linear-gradient(145deg, var(--bg-card2), var(--bg-deep));
- border-radius: var(--radius-md);
- padding: 24px 20px;
- min-height: 128px;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-bottom: 14px;
- border: 1.5px solid rgba(255, 255, 255, 0.06);
- position: relative;
-}
-
-.move-waiting {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 10px;
- color: var(--text-dim);
- font-size: 0.9rem;
- text-align: center;
-}
-
-.wait-icon {
- font-size: 2rem;
- animation: pulse 1.5s infinite alternate;
-}
-
-.move-result {
- text-align: center;
- width: 100%;
-}
-
-.move-header {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 12px;
- margin-bottom: 8px;
-}
-
-.move-san {
- font-family: 'Space Mono', monospace;
- font-size: 1.7rem;
- color: var(--accent);
- font-weight: 700;
- letter-spacing: 0.05em;
- text-shadow: 0 0 16px var(--accent-glow);
-}
-
-.move-uci-badge {
- font-family: 'Space Mono', monospace;
- font-size: 0.85rem;
- font-weight: 700;
- color: var(--accent2);
- background: var(--bg-deep);
- padding: 4px 10px;
- border-radius: 999px;
- border: 1px solid var(--border-subtle);
-}
-
-.move-text {
- font-size: 1.35rem;
- font-weight: 700;
- color: var(--text);
- line-height: 1.3;
- letter-spacing: -0.01em;
-}
-
-/* Recent Suggestions Trail */
-.recent-moves-container {
- margin-bottom: 14px;
- display: flex;
- align-items: center;
- gap: 10px;
-}
-
-.recent-label {
- font-size: 0.74rem;
- font-weight: 700;
- text-transform: uppercase;
- color: var(--text-muted);
-}
-
-.recent-pills {
- display: flex;
- gap: 6px;
- flex-wrap: wrap;
-}
-
-.recent-chip {
- font-family: 'Space Mono', monospace;
- font-size: 0.78rem;
- background: var(--bg-card2);
- border: 1px solid var(--border-subtle);
- border-radius: 999px;
- padding: 2px 10px;
- color: var(--text-dim);
-}
-
-/* Status Bar */
-.status-bar {
- background: var(--bg-card2);
- border-radius: var(--radius-sm);
- padding: 10px 14px;
- font-size: 0.82rem;
- color: var(--text-dim);
- min-height: 40px;
- display: flex;
- align-items: center;
- gap: 8px;
- border: 1px solid var(--border-subtle);
-}
-
-.status-indicator-dot {
- width: 7px;
- height: 7px;
- border-radius: 50%;
- background: var(--text-muted);
- flex-shrink: 0;
-}
-
+*, *::before, *::after { box-sizing: border-box; }
+:root { color-scheme: light; --bg: #f4f5f0; --paper: #fff; --ink: #1e302c; --muted: #68756e; --line: #e3e8e0; --green: #245b49; --green-hover: #194634; --mint: #e7f0df; --lime: #d9efb4; --danger: #ab3e36; --radius: 20px; accent-color: var(--green); }
+html { scroll-behavior: smooth; }
+body { margin: 0; background: var(--bg); color: var(--ink); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; font-size: 14px; line-height: 1.5; min-width: 280px; -webkit-font-smoothing: antialiased; }
+button, input, select, textarea { font: inherit; }
+button, a, input, select, textarea { -webkit-tap-highlight-color: transparent; }
+button { cursor: pointer; }
+button:disabled { opacity: .4; cursor: not-allowed; }
+a { color: inherit; }
+h1, h2, h3, p { margin: 0; }
+button, a { touch-action: manipulation; }
+:focus-visible { outline: 3px solid #8abd67; outline-offset: 4px; }
+[hidden] { display: none !important; }
+.visually-hidden { position: absolute !important; width: 1px !important; height: 1px !important; padding: 0 !important; margin: -1px !important; overflow: hidden !important; clip: rect(0,0,0,0) !important; clip-path: inset(50%) !important; white-space: nowrap !important; border: 0 !important; }
+.icon-library { position: absolute; width: 0; height: 0; overflow: hidden; }
+.icon { width: 20px; height: 20px; flex: 0 0 20px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
+.header { border-bottom: 1px solid var(--line); }
+.header-inner, .main, .footer { max-width: 1160px; margin: 0 auto; }
+.header-inner { min-height: 88px; padding: 18px 32px; display: flex; align-items: center; justify-content: space-between; gap: 12px; }
+.brand { display: flex; align-items: center; gap: 10px; text-decoration: none; font-size: 22px; font-weight: 750; letter-spacing: -.8px; line-height: 1.15; }
+.brand-mark { width: 42px; height: 42px; border-radius: 13px; background: var(--green); color: #edf4e9; display: grid; place-items: center; }
+.brand-mark .icon { width: 28px; height: 28px; }
+.brand-light { font-weight: 400; }
+.brand small { display: block; margin-top: 6px; font-size: 8px; font-weight: 650; letter-spacing: 1.9px; color: var(--muted); }
+.status-pill { border: 1px solid var(--line); border-radius: 30px; min-height: 36px; background: #fff9; color: var(--muted); display: inline-flex; align-items: center; gap: 7px; padding: 8px 13px; font-size: 11px; font-weight: 650; white-space: nowrap; }
+.status-dot, .status-indicator-dot { width: 6px; height: 6px; flex: 0 0 6px; border-radius: 50%; background: #8c9b93; }
+.status-pill.online { color: var(--green); background: #e9f0e5; border-color: #dce7d6; }
+.status-pill.online .status-dot { background: #478751; }
+.status-pill.offline { color: var(--danger); }
+.status-pill.offline .status-dot { background: var(--danger); }
+.status-pill.connecting .status-dot { background: #b1903c; }
+.main { padding: 34px 32px 36px; }
+.page-intro { display: flex; align-items: flex-end; justify-content: space-between; gap: 20px; margin-bottom: 30px; }
+.eyebrow { color: var(--muted); font-size: 9px; letter-spacing: 2px; font-weight: 650; margin-bottom: 11px; }
+h1 { font-size: clamp(27px, 3.5vw, 39px); font-weight: 700; line-height: 1.15; letter-spacing: -1.6px; }
+h1 span { color: #789166; font-weight: 400; }
+.intro-description { color: var(--muted); font-size: 12px; line-height: 1.7; padding-bottom: 2px; }
+.workspace { display: grid; grid-template-columns: minmax(0, 1.38fr) minmax(0, 1fr); align-items: start; gap: 24px; }
+.camera-panel, .card { background: var(--paper); border: 1px solid var(--line); border-radius: var(--radius); }
+.camera-panel { padding: 20px; min-width: 0; }
+.panel-heading, .card-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
+.panel-heading { margin-bottom: 16px; }
+h2 { font-size: 13px; font-weight: 650; display: flex; align-items: center; gap: 8px; letter-spacing: -.15px; }
+h2 .icon { width: 17px; height: 17px; flex-basis: 17px; color: #7b8a80; }
+.frame-ratio { color: #97a095; font-size: 8px; font-weight: 600; letter-spacing: 1.3px; }
+.camera-frame { position: relative; width: 100%; aspect-ratio: 1 / 1; overflow: hidden; border-radius: 13px; background: #182521; isolation: isolate; }
+#cameraFeed, #photoPreview { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; display: block; }
+#moveOverlay { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 2; pointer-events: none; overflow: visible; }
+.frame-move-label { position: absolute; bottom: 14px; left: 50%; transform: translateX(-50%); max-width: calc(100% - 28px); padding: 8px 14px; border: 1px solid #d9efb440; border-radius: 9px; background: #163326ed; color: #e6f6cf; font-size: 14px; font-weight: 650; text-align: center; z-index: 4; pointer-events: none; }
+.camera-frame.is-locking, .camera-frame.calibrating { cursor: crosshair; touch-action: none; }
+.camera-overlay { position: absolute; inset: 0; z-index: 3; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 28px 24px; color: #e4e9df; text-align: center; background: radial-gradient(ellipse at 50% 40%, #2b3c30 0%, #192620 60%, #15211c 100%); pointer-events: none; }
+.camera-overlay.hidden { display: none; }
+.empty-board { width: 117px; height: 117px; position: relative; margin-bottom: 26px; background: conic-gradient(#4e6040 25%, #3d4b36 0 50%, #4e6040 0 75%, #3d4b36 0) 50% 50% / 29.25px 29.25px; border-radius: 2px; box-shadow: 0 14px 24px #07120d30; }
+.empty-knight { position: absolute; left: 32px; top: 25px; width: 57px; height: 66px; color: #bdce9f; fill: #3d4b36; stroke: currentColor; stroke-width: 1.1; stroke-linecap: round; stroke-linejoin: round; }
+.view-corner { position: absolute; width: 18px; height: 18px; border-color: #b1ce90; border-style: solid; opacity: .65; }
+.view-corner.tl { top: -10px; left: -10px; border-width: 2px 0 0 2px; border-radius: 5px 0 0 0; }
+.view-corner.tr { top: -10px; right: -10px; border-width: 2px 2px 0 0; border-radius: 0 5px 0 0; }
+.view-corner.bl { bottom: -10px; left: -10px; border-width: 0 0 2px 2px; border-radius: 0 0 0 5px; }
+.view-corner.br { bottom: -10px; right: -10px; border-width: 0 2px 2px 0; border-radius: 0 0 5px 0; }
+.camera-overlay h3 { font-size: 20px; font-weight: 550; letter-spacing: -.4px; margin-bottom: 8px; }
+.camera-overlay p { font-size: 12px; color: #a3b1a0; line-height: 1.7; }
+.camera-empty-note { margin-top: 23px; font-size: 7px; letter-spacing: 1.2px; color: #83937c; }
+.frame-hud { position: absolute; inset: 13px 13px auto; display: flex; align-items: center; gap: 8px; z-index: 4; pointer-events: none; }
+.frame-tag { display: inline-flex; align-items: center; gap: 6px; min-height: 26px; background: #0d191acc; color: #dbe6dd; border: 1px solid #ffffff12; border-radius: 6px; padding: 5px 8px; font-size: 9px; font-weight: 600; line-height: 1.3; backdrop-filter: blur(8px); }
+.hud-dot { width: 5px; height: 5px; border-radius: 50%; background: #819388; }
+.frame-tag.locked { color: var(--lime); }
+.live-indicator { margin-left: auto; font-size: 8px; letter-spacing: 1px; }
+.live-indicator .hud-dot { background: #b9d795; }
+.confidence { margin-left: auto; font-variant-numeric: tabular-nums; }
+.live-indicator:not([hidden]) + .confidence { margin-left: 0; }
+.camera-actions { display: flex; gap: 9px; margin-top: 16px; }
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 46px; border-radius: 10px; padding: 11px 16px; border: 1px solid transparent; font-size: 12px; font-weight: 650; line-height: 1.3; transition: background .15s, border-color .15s; }
+.btn .icon { width: 17px; height: 17px; flex-basis: 17px; }
+.btn-primary { background: var(--green); color: #fff; }
+.btn-primary:hover:not(:disabled) { background: var(--green-hover); }
+.btn-secondary, .btn-icon { background: #f5f7f2; color: var(--ink); border-color: var(--line); }
+.btn-secondary:hover:not(:disabled), .btn-icon:hover:not(:disabled) { background: #eaf0e4; }
+.camera-actions .btn-primary { flex: 1; }
+.camera-actions .btn-secondary { min-width: 88px; }
+.btn-icon { width: 46px; padding: 10px; flex: 0 0 46px; }
+.camera-secondary-actions { display: flex; justify-content: center; gap: 28px; margin: 10px 0 8px; }
+.text-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; border: 0; background: transparent; color: var(--muted); font-size: 11px; font-weight: 550; padding: 9px 0; min-height: 36px; border-radius: 4px; text-decoration: none; }
+.text-btn .icon { width: 14px; height: 14px; flex-basis: 14px; }
+.text-btn:hover:not(:disabled) { color: var(--green); }
+.board-tools { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding-top: 10px; border-top: 1px solid var(--line); color: var(--muted); font-size: 10px; }
+.board-tools > div { display: flex; gap: 16px; }
+.board-tools .text-btn { font-size: 10px; }
+.camera-tip { margin-top: 6px; color: #8b968d; font-size: 10px; line-height: 1.6; }
+.coach-panel { display: flex; flex-direction: column; gap: 18px; min-width: 0; }
+.card { padding: 22px; }
+.move-card { background: #f0f5e9; border-color: #e1e9d6; }
+.move-card h2 .icon { color: #688052; }
+.engine-badge { background: #fff9; color: #728267; border: 1px solid #e3e9d8; border-radius: 20px; font-size: 8px; padding: 3px 8px; white-space: nowrap; }
+.move-display { min-height: 178px; display: flex; align-items: center; padding: 24px 0 20px; }
+.move-waiting { width: 100%; }
+.waiting-arrow { display: grid; place-items: center; width: 34px; height: 34px; border-radius: 10px; background: #e2ebd6; color: #759455; margin-bottom: 15px; }
+.waiting-arrow .icon { width: 19px; height: 19px; }
+.move-waiting h3 { font-size: 21px; letter-spacing: -.5px; font-weight: 600; margin-bottom: 8px; }
+.move-waiting p { color: #7a8871; font-size: 12px; max-width: 270px; line-height: 1.65; }
+.move-result { width: 100%; }
+.move-overline { font-size: 8px; letter-spacing: 1.3px; color: #748464; font-weight: 650; margin-bottom: 8px; }
+.move-text { font-size: 30px; line-height: 1.17; font-weight: 650; letter-spacing: -1px; overflow-wrap: anywhere; }
+.move-notation { display: flex; align-items: center; gap: 10px; margin-top: 14px; }
+.move-san { background: #dfeace; border: 1px solid #d5e2c2; padding: 4px 11px; border-radius: 6px; font-weight: 700; font-size: 13px; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }
+.move-uci { color: #77836d; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; }
+.move-caption { color: #7a8871; font-size: 10px; margin-top: 12px; }
+.status-bar { display: flex; align-items: flex-start; gap: 7px; border-top: 1px solid #dfe7d6; padding-top: 13px; color: #798671; font-size: 10px; line-height: 1.6; }
+.status-indicator-dot { margin-top: 5px; width: 5px; height: 5px; flex-basis: 5px; background: #8d9d7d; }
+.status-bar.ok { color: var(--green); }
+.status-bar.ok .status-indicator-dot { background: #629744; }
+.status-bar.error { color: var(--danger); }
.status-bar.error .status-indicator-dot { background: var(--danger); }
-.status-bar.error { color: var(--danger); border-color: rgba(239, 68, 68, 0.3); }
-
-.status-bar.ok .status-indicator-dot { background: var(--accent); }
-.status-bar.ok { color: var(--accent-light); border-color: rgba(16, 185, 129, 0.3); }
-
-/* ── Mode info card ─────────────────────────────── */
-.info-card {
- padding: 14px 18px;
-}
-
-.mode-info {
- display: flex;
- align-items: flex-start;
- gap: 14px;
- font-size: 0.84rem;
-}
-
-.mode-icon {
- font-size: 1.6rem;
- flex-shrink: 0;
-}
-
-.mode-info strong {
- display: block;
- margin-bottom: 2px;
- color: var(--text);
- font-size: 0.92rem;
-}
-
-.mode-info p {
- color: var(--text-dim);
- line-height: 1.45;
-}
-
-/* ── Modal Dialog ───────────────────────────────── */
-.modal-dialog {
- border: 1px solid var(--border-subtle);
- border-radius: var(--radius-lg);
- background: var(--bg-card);
- color: var(--text);
- padding: 0;
- max-width: 480px;
- width: 90%;
- margin: auto;
- box-shadow: 0 10px 40px rgba(0, 0, 0, 0.7);
-}
-
-.modal-dialog::backdrop {
- background: rgba(0, 0, 0, 0.75);
- backdrop-filter: blur(4px);
-}
-
-.modal-content {
- padding: 24px;
- display: flex;
- flex-direction: column;
- gap: 14px;
-}
-
-.modal-title {
- font-size: 1.15rem;
- font-weight: 700;
-}
-
-.modal-desc {
- font-size: 0.85rem;
- color: var(--text-dim);
-}
-
-.modal-input {
- background: var(--bg-deep);
- border: 1px solid var(--border-subtle);
- border-radius: var(--radius-sm);
- color: var(--text);
- font-family: 'Space Mono', monospace;
- font-size: 0.85rem;
- padding: 12px;
- width: 100%;
- outline: none;
-}
-
-.modal-input:focus {
- border-color: var(--accent);
-}
-
-.modal-status {
- font-size: 0.8rem;
- font-family: 'Space Mono', monospace;
- color: var(--text-dim);
- padding: 6px 0;
-}
-
-.modal-actions {
- display: flex;
- justify-content: flex-end;
- gap: 10px;
- margin-top: 8px;
-}
-
-/* ── Footer ─────────────────────────────────────── */
-.footer {
- font-size: 0.78rem;
- color: var(--text-muted);
- padding: 20px;
- border-top: 1px solid var(--border-subtle);
- margin-top: auto;
-}
-
-.footer-inner {
- max-width: 1140px;
- margin: 0 auto;
- display: flex;
- align-items: center;
- justify-content: space-between;
- flex-wrap: wrap;
- gap: 12px;
-}
-
-.footer-links {
- display: flex;
- align-items: center;
- gap: 8px;
-}
-
-.footer-link-btn,
-.footer-link {
- background: none;
- border: none;
- color: var(--text-dim);
- font-size: inherit;
- font-family: inherit;
- cursor: pointer;
- text-decoration: underline;
- transition: color 0.15s;
-}
-
-.footer-link-btn:hover,
-.footer-link:hover {
- color: var(--accent);
-}
-
-/* ── Animations ─────────────────────────────────── */
-@keyframes pulse {
- 0% { opacity: 1; }
- 100% { opacity: 0.4; }
-}
-
-@keyframes slideIn {
- from {
- opacity: 0;
- transform: translateY(10px) scale(0.98);
- }
- to {
- opacity: 1;
- transform: translateY(0) scale(1);
- }
-}
-
-.move-anim {
- animation: slideIn 0.35s cubic-bezier(0.16, 1, 0.3, 1);
-}
-
-@media (prefers-reduced-motion: reduce) {
- .move-anim,
- .live-indicator,
- .wait-icon {
- animation: none;
- }
+.recent-moves { padding-bottom: 12px; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 9px; color: #7b886f; }
+#recentPills { display: flex; flex-wrap: wrap; gap: 4px; }
+.recent-chip { border: 1px solid #dce5d0; border-radius: 4px; padding: 2px 6px; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 9px; }
+.settings-card .card-heading { margin-bottom: 22px; }
+.section-number { color: #b1bbad; font-size: 10px; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }
+.control-group { margin-bottom: 20px; }
+.ctrl-label { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 11px; font-weight: 550; color: #768272; margin-bottom: 9px; }
+.toggle-group { display: flex; gap: 8px; }
+.toggle-btn { display: flex; align-items: center; justify-content: center; gap: 8px; min-height: 42px; flex: 1; border: 1px solid var(--line); border-radius: 8px; background: #fff; color: #7b8579; font-size: 12px; font-weight: 600; }
+.toggle-btn.active { border-color: #a9ba9c; background: #f1f5eb; color: var(--green); }
+.piece-dot { width: 11px; height: 11px; border-radius: 50%; }
+.piece-dot.white { border: 1px solid #a3afa0; background: #fff; box-shadow: inset 0 -2px 0 #e7ebe3; }
+.piece-dot.black { background: #334338; border: 1px solid #334338; }
+.field-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 22px; color: #768272; font-size: 11px; }
+select { max-width: 58%; min-height: 36px; border: 1px solid var(--line); border-radius: 7px; background: #f8f9f5; color: var(--ink); padding: 7px 24px 7px 9px; font-size: 11px; }
+.strength-control { margin-bottom: 19px; }
+.depth-value { color: var(--green); font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; font-weight: 700; }
+.depth-unit { color: #a1ada0; font-size: 10px; font-weight: 400; }
+input[type="range"] { width: 100%; height: 26px; margin: 0; background: transparent; cursor: pointer; }
+.range-labels { display: flex; justify-content: space-between; font-size: 9px; color: #9ba594; margin-top: 2px; }
+.advanced-settings { border-top: 1px solid var(--line); }
+.advanced-settings summary { display: flex; align-items: center; justify-content: space-between; cursor: pointer; min-height: 44px; margin-bottom: -8px; padding-top: 6px; font-size: 10px; font-weight: 600; color: #819078; list-style: none; }
+.advanced-settings summary::-webkit-details-marker { display: none; }
+.advanced-settings summary .icon { width: 16px; height: 16px; flex-basis: 16px; transition: transform .15s; }
+.advanced-settings[open] summary .icon { transform: rotate(180deg); }
+.advanced-content { padding-top: 20px; }
+.field-help { font-size: 10px; line-height: 1.7; color: #929d8b; }
+.fen-field .field-help { margin-bottom: 8px; }
+textarea, .modal-input { display: block; width: 100%; border: 1px solid var(--line); border-radius: 8px; color: var(--ink); background: #f8f9f5; padding: 10px; font-size: 11px; }
+textarea { resize: vertical; min-height: 74px; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; line-height: 1.7; margin-bottom: 7px; }
+textarea::placeholder, .modal-input::placeholder { color: #a3ad9b; }
+.setup-actions { display: flex; gap: 7px; margin-top: 12px; }
+.setup-actions .btn { flex: 1; }
+.btn-small { min-height: 39px; padding: 9px 10px; font-size: 10px; border-radius: 8px; }
+.reset-btn { margin-top: 8px; font-size: 10px; }
+.how-it-works { display: flex; gap: 12px; padding: 2px 10px; }
+.how-icon { width: 33px; height: 33px; flex: 0 0 33px; border: 1px solid #e0e6d9; background: #eef2e8; border-radius: 10px; display: grid; place-items: center; color: #879676; margin-top: 2px; }
+.how-icon .icon { width: 17px; height: 17px; }
+.how-it-works h3 { color: #7a8970; font-size: 11px; font-weight: 600; margin-bottom: 5px; }
+.how-it-works p { color: #a0a998; font-size: 10px; line-height: 1.7; max-width: 285px; }
+.footer { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 16px 32px 25px; color: #9ba693; font-size: 10px; }
+.footer > div { display: flex; align-items: center; gap: 20px; }
+.footer .text-btn, .footer a { color: #89977e; font-size: 10px; text-decoration: none; }
+.footer a:hover { color: var(--green); }
+.modal-dialog { border: 1px solid var(--line); border-radius: var(--radius); padding: 0; width: min(460px, calc(100% - 32px)); margin: auto; color: var(--ink); background: var(--paper); box-shadow: 0 30px 100px #18302440; }
+.modal-dialog::backdrop { background: #14231b80; backdrop-filter: blur(4px); }
+.modal-content { padding: 24px; }
+.modal-content .card-heading { margin-bottom: 12px; }
+.modal-content .card-heading .btn-icon { min-height: 32px; width: 32px; flex-basis: 32px; padding: 0; font-size: 23px; font-weight: 400; }
+.modal-content > .field-help { margin-bottom: 18px; }
+.modal-input { min-height: 44px; }
+.modal-status { min-height: 30px; padding-top: 10px; font-size: 11px; color: var(--muted); }
+.modal-actions { display: flex; flex-wrap: wrap; gap: 7px; margin-top: 12px; }
+.modal-actions .btn-primary { margin-left: auto; }
+@media (max-width: 800px) {
+ .header-inner { min-height: 72px; padding: 15px 20px; }
+ .brand { font-size: 20px; }
+ .brand-mark { width: 37px; height: 37px; border-radius: 11px; }
+ .brand small { font-size: 7px; letter-spacing: 1.5px; }
+ .main { padding: 26px 20px 18px; max-width: 600px; }
+ .page-intro { margin-bottom: 23px; }
+ .intro-description { display: none; }
+ .eyebrow { font-size: 8px; letter-spacing: 1.6px; margin-bottom: 9px; }
+ h1 { font-size: 30px; letter-spacing: -1.1px; }
+ .workspace { grid-template-columns: minmax(0, 1fr); gap: 16px; }
+ .camera-panel { padding: 16px; }
+ .panel-heading { margin-bottom: 13px; }
+ .coach-panel { gap: 16px; }
+ .card { padding: 20px; }
+ .move-display { min-height: 145px; padding-top: 21px; }
+ .move-waiting { display: grid; grid-template-columns: 37px minmax(0, 1fr); align-items: center; column-gap: 13px; }
+ .waiting-arrow { grid-row: span 2; margin-bottom: 0; }
+ .move-waiting h3 { font-size: 19px; margin-bottom: 5px; }
+ .move-waiting p { font-size: 11px; max-width: none; }
+ .settings-card .card-heading { margin-bottom: 18px; }
+ .how-it-works { padding: 4px 8px; }
+ .how-it-works p { max-width: none; }
+ .footer { max-width: 600px; padding: 17px 20px 25px; font-size: 9px; }
+ .footer > div { gap: 14px; }
+ .footer .text-btn, .footer a { font-size: 9px; }
+}
+@media (max-width: 400px) {
+ .header-inner { padding-left: 16px; padding-right: 16px; }
+ .main { padding-left: 12px; padding-right: 12px; }
+ .status-pill { font-size: 10px; padding: 7px 10px; gap: 6px; }
+ h1 { font-size: 27px; }
+ .camera-panel { padding: 13px; border-radius: 16px; }
+ .camera-overlay { padding: 22px 16px; }
+ .empty-board { width: 88px; height: 88px; background-size: 22px 22px; margin-bottom: 24px; }
+ .empty-knight { left: 23px; top: 17px; width: 44px; height: 52px; }
+ .camera-overlay h3 { font-size: 18px; }
+ .camera-overlay p { font-size: 11px; }
+ .camera-empty-note { font-size: 6px; margin-top: 18px; letter-spacing: .7px; }
+ .camera-actions { gap: 7px; margin-top: 13px; }
+ .camera-actions .btn { font-size: 11px; padding-left: 12px; padding-right: 12px; }
+ .camera-actions .btn-secondary { min-width: 74px; }
+ .board-tools > div { gap: 12px; }
+ .card { padding: 18px; border-radius: 16px; }
+ .move-text { font-size: 28px; }
+ .footer { padding-left: 16px; padding-right: 16px; flex-wrap: wrap; gap: 0; }
+}
+@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } *, *::before, *::after { animation: none !important; transition: none !important; } }
+
+/* Supporting copy and controls remain readable at phone viewing distance. */
+.ctrl-label, .field-row, .field-help, .camera-tip, .status-bar, .move-caption, .move-uci, .text-btn, .how-it-works p { font-size: 12px; color: #5f6e62; }
+.move-waiting p { color: #5f7056; }
+.how-it-works h3, .advanced-settings summary { color: #506749; font-size: 12px; }
+.camera-overlay p { color: #bbc8b5; }
+.camera-empty-note { color: #abbc9d; font-size: 9px; }
+.frame-hud { flex-wrap: wrap; }
+.frame-tag { font-size: 10px; }
+.toggle-btn, .btn-small { min-height: 44px; font-size: 12px; }
+.text-btn { min-height: 44px; }
+@media (max-width: 800px) {
+ select, textarea, .modal-input { font-size: 16px; min-height: 44px; }
+ select { max-width: 65%; padding-right: 18px; font-size: 13px; }
+ .status-pill { min-height: 44px; }
+ .main { padding-bottom: max(18px, env(safe-area-inset-bottom)); }
+ .board-tools .text-btn { font-size: 11px; }
}
diff --git a/frontend/tests/app.browser.js b/frontend/tests/app.browser.js
new file mode 100644
index 0000000..1497997
--- /dev/null
+++ b/frontend/tests/app.browser.js
@@ -0,0 +1,244 @@
+import test, { before, after } from "node:test";
+import assert from "node:assert/strict";
+import { chromium } from "playwright";
+import { createServer } from "node:http";
+import { readFile, mkdir } from "node:fs/promises";
+import { existsSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import path from "node:path";
+
+const root = fileURLToPath(new URL("../", import.meta.url));
+const repo = path.dirname(root);
+const startFen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
+const corners = [[.1, .15], [.85, .2], [.9, .9], [.08, .87]];
+const advice = { status: "ok", fen: startFen, turn: "w", move_uci: "d2d4", move_san: "d4", move_human: "Pawn to d4",
+ confidence: .95, board_corners: corners, board_detected: true, board_locked: true, pieces_detected: true,
+ orientation: "w", engine: "stockfish" };
+let browser, server, origin;
+before(async () => {
+ server = createServer(async (req, res) => {
+ try {
+ if (req.url === "/health") { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify({ status: "ok", engine: "stockfish" })); return; }
+ const file = req.url === "/" ? "index.html" : req.url.split("?")[0].slice(1);
+ if (!/^(index\.html|style\.css|app\.js|overlay\.js)$/.test(file)) { res.writeHead(404); res.end(); return; }
+ res.setHeader("Content-Type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "text/html");
+ res.end(await readFile(path.join(root, file)));
+ } catch { res.writeHead(500); res.end(); }
+ });
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+ origin = `http://127.0.0.1:${server.address().port}`;
+ const chrome = process.env.CHROME_PATH || (process.platform === "win32" ? "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" : undefined);
+ browser = await chromium.launch({ ...(chrome && existsSync(chrome) ? { executablePath: chrome } : {}), headless: true });
+});
+after(async () => { await browser?.close(); await new Promise(resolve => server?.close(resolve)); });
+
+async function newPage(viewport = { width: 390, height: 844 }) {
+ const page = await browser.newPage({ viewport });
+ const errors = [];
+ page.on("pageerror", err => errors.push(err.message));
+ page.errors = errors;
+ return page;
+}
+async function respond(route, data = advice) { await route.fulfill({ json: data }); }
+async function photo(page) {
+ const b64 = await page.evaluate(() => {
+ const canvas = document.createElement("canvas"); canvas.width = 800; canvas.height = 450;
+ const ctx = canvas.getContext("2d"); ctx.fillStyle = "#e2edde"; ctx.fillRect(0, 0, 800, 450);
+ return canvas.toDataURL("image/png").split(",")[1];
+ });
+ await page.locator("#fileInput").setInputFiles({ name: "board.png", mimeType: "image/png", buffer: Buffer.from(b64, "base64") });
+}
+async function fakeCamera(page, delay = 0) {
+ await page.addInitScript(({ delay }) => {
+ navigator.mediaDevices.getUserMedia = async () => {
+ await new Promise(resolve => setTimeout(resolve, delay));
+ const canvas = document.createElement("canvas"); canvas.width = 640; canvas.height = 480;
+ const ctx = canvas.getContext("2d"); ctx.fillStyle = "#cbdac8"; ctx.fillRect(0, 0, 640, 480);
+ const stream = canvas.captureStream(5);
+ window.fakeStream = stream;
+ const draw = setInterval(() => ctx.fillRect(0, 0, 640, 480), 200);
+ stream.getTracks()[0].addEventListener("ended", () => clearInterval(draw));
+ return stream;
+ };
+ }, { delay });
+}
+
+test("mobile and desktop layouts have one square frame, no overflow, and usable connection dialog", async () => {
+ for (const viewport of [{ width: 360, height: 800 }, { width: 390, height: 844 }, { width: 768, height: 1024 }, { width: 1440, height: 1000 }]) {
+ const page = await newPage(viewport);
+ await page.goto(origin);
+ await page.getByText("Engine online", { exact: true }).waitFor();
+ const box = await page.locator("#cameraFrame").boundingBox();
+ assert.ok(Math.abs(box.width - box.height) < 1);
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
+ assert.equal(await page.locator("#boardCard").count(), 0);
+ await page.locator("#engineStatus").click();
+ assert.equal(await page.locator("#apiModal").isVisible(), true);
+ await page.locator("#btnCloseApi").click();
+ assert.deepEqual(page.errors, []);
+ await mkdir(path.join(repo, ".tmp", "screens"), { recursive: true });
+ await page.screenshot({ path: path.join(repo, ".tmp", "screens", `ui-${viewport.width}.png`), fullPage: true });
+ await page.close();
+ }
+});
+
+test("photo overlay uses the camera frame and cached suggestions remain visible", async () => {
+ const page = await newPage(); let requests = 0;
+ await page.route("**/api/analyze", route => respond(route, { ...advice, status: ++requests === 1 ? "ok" : "no_change" }));
+ await page.goto(origin); await photo(page);
+ await page.locator("#moveResult").waitFor();
+ assert.equal(await page.locator("#moveText").textContent(), "Pawn to d4");
+ assert.equal(await page.locator("#moveOverlay").getAttribute("aria-label"), "Suggested move from d2 to d4");
+ assert.equal(await page.locator("#frameMoveLabel").isVisible(), true);
+ const frame = await page.locator("#cameraFrame").boundingBox(), overlay = await page.locator("#moveOverlay").boundingBox();
+ assert.deepEqual(overlay, frame);
+ await page.locator("#depthSlider").evaluate(el => { el.value = "11"; el.dispatchEvent(new Event("input")); el.dispatchEvent(new Event("change")); });
+ await page.getByText(/Position unchanged/).waitFor();
+ assert.equal(await page.locator("#moveOverlay line").count(), 2);
+ assert.deepEqual(page.errors, []); await page.close();
+});
+
+test("camera polls every settled frame, clears opponent arrow, and resumes suggestions", async () => {
+ const page = await newPage(); await fakeCamera(page); let requests = 0, active = 0, maxActive = 0;
+ await page.route("**/api/analyze", async route => {
+ active++; maxActive = Math.max(maxActive, active); requests++;
+ assert.equal(route.request().postDataJSON().orientation, "auto");
+ await new Promise(resolve => setTimeout(resolve, 150));
+ const data = requests === 1 ? advice : requests === 2 ? { ...advice, status: "no_change" } : requests === 3 ?
+ { ...advice, status: "opponent_turn", move_uci: null, turn: "b" } : { ...advice, move_uci: "g1f3", move_san: "Nf3", move_human: "Knight to f3" };
+ await respond(route, data); active--;
+ });
+ await page.goto(origin); await page.locator("#btnStart").click();
+ await page.locator("#moveResult").waitFor();
+ await page.getByText(/Position unchanged/).waitFor();
+ await page.locator("#waitText").filter({ hasText: "Opponent’s turn" }).waitFor();
+ assert.equal(await page.locator("#moveOverlay line").count(), 0);
+ await page.locator("#moveText").filter({ hasText: "Knight to f3" }).waitFor();
+ assert.ok(requests >= 4); assert.equal(maxActive, 1);
+ await page.locator("#btnStop").click();
+ assert.equal(await page.locator("#moveOverlay line").count(), 0);
+ assert.deepEqual(page.errors, []); await page.close();
+});
+
+test("a stopped camera cannot display an in-flight result or reopen after delayed permission", async () => {
+ const page = await newPage(); await fakeCamera(page); let started;
+ const requestStarted = new Promise(resolve => { started = resolve; });
+ await page.route("**/api/analyze", async route => {
+ started(); await new Promise(resolve => setTimeout(resolve, 1000));
+ try { await respond(route); } catch { /* Request was canceled by stop. */ }
+ });
+ await page.goto(origin); await page.locator("#btnStart").click(); await requestStarted;
+ await page.locator("#btnStop").click();
+ await page.waitForTimeout(1200);
+ assert.equal(await page.locator("#moveResult").isVisible(), false);
+ assert.equal(await page.locator("#moveOverlay line").count(), 0);
+ await page.close();
+ const delayed = await newPage(); await fakeCamera(delayed, 500);
+ await delayed.goto(origin); await delayed.locator("#btnStart").click(); await delayed.locator("#btnStop").click();
+ await delayed.waitForTimeout(700);
+ assert.equal(await delayed.locator("#cameraFeed").isVisible(), false);
+ assert.equal(await delayed.evaluate(() => fakeStream.getTracks()[0].readyState), "ended");
+ assert.deepEqual(delayed.errors, []); await delayed.close();
+});
+
+test("unclear position removes stale arrows while retaining the detected board lock", async () => {
+ const page = await newPage(); let requests = 0;
+ await page.route("**/api/analyze", route => respond(route, ++requests === 1 ? advice :
+ { ...advice, status: "position_uncertain", fen: null, move_uci: null, message: "Remove your hand." }));
+ await page.goto(origin); await photo(page); await page.locator("#moveResult").waitFor();
+ await page.locator("#depthSlider").evaluate(el => { el.value = "12"; el.dispatchEvent(new Event("input")); el.dispatchEvent(new Event("change")); });
+ await page.getByText("Remove your hand.", { exact: true }).waitFor();
+ assert.equal(await page.locator("#moveOverlay line").count(), 0);
+ assert.equal(await page.locator("#moveOverlay polygon").count(), 1);
+ assert.equal(await page.locator("#moveResult").isVisible(), false);
+ assert.deepEqual(page.errors, []); await page.close();
+});
+
+test("auto black orientation rotates the arrow and an empty board is never locked", async () => {
+ const page = await newPage(); let requests = 0;
+ await page.route("**/api/analyze", route => respond(route, ++requests === 1 ?
+ { ...advice, board_corners: [[0, 0], [1, 0], [1, 1], [0, 1]], orientation: "b" } :
+ { ...advice, status: "setup_required", fen: null, move_uci: null, pieces_detected: false, board_locked: false }));
+ await page.goto(origin); await photo(page); await page.locator("#moveResult").waitFor();
+ const line = page.locator("#moveOverlay line").last();
+ assert.equal(Number(await line.getAttribute("x1")), 562.5);
+ assert.equal(Number(await line.getAttribute("y1")), 187.5);
+ await page.locator("#depthSlider").evaluate(el => { el.value = "12"; el.dispatchEvent(new Event("input")); el.dispatchEvent(new Event("change")); });
+ await page.locator("#waitText").filter({ hasText: "Put the pieces" }).waitFor();
+ assert.equal(await page.locator("#moveOverlay polygon").count(), 0);
+ assert.equal(await page.locator("#frameMoveLabel").isVisible(), false);
+ assert.deepEqual(page.errors, []); await page.close();
+});
+
+test("denied camera permission leaves controls usable and explains photo fallback", async () => {
+ const page = await newPage();
+ await page.addInitScript(() => {
+ navigator.mediaDevices.getUserMedia = async () => { throw new DOMException("Permission denied", "NotAllowedError"); };
+ });
+ await page.goto(origin); await page.locator("#btnStart").click();
+ await page.locator("#statusMsg").filter({ hasText: "Camera access was denied" }).waitFor();
+ assert.equal(await page.locator("#btnStart").isEnabled(), true);
+ assert.equal(await page.locator("#btnStop").isEnabled(), false);
+ assert.equal(await page.locator("#btnUploadPhoto").isEnabled(), true);
+ assert.deepEqual(page.errors, []); await page.close();
+});
+
+test("settings during camera permission do not strand Start and stale denial cannot cancel a photo", async () => {
+ const page = await newPage(); await fakeCamera(page, 500);
+ await page.route("**/api/analyze", route => respond(route));
+ await page.goto(origin); await page.locator("#btnStart").click();
+ await page.locator('#colorToggle button[data-val="b"]').click();
+ await page.locator("#cameraFeed").waitFor(); await page.locator("#moveResult").waitFor();
+ assert.equal(await page.locator("#btnStop").isEnabled(), true);
+ await page.locator("#btnStop").click();
+ assert.equal(await page.locator("#btnStart").isEnabled(), true);
+ await page.close();
+ const denied = await newPage();
+ await denied.addInitScript(() => {
+ navigator.mediaDevices.getUserMedia = async () => {
+ await new Promise(resolve => setTimeout(resolve, 600));
+ throw new DOMException("Permission denied", "NotAllowedError");
+ };
+ });
+ await denied.route("**/api/analyze", route => respond(route));
+ await denied.goto(origin); await denied.locator("#btnStart").click(); await photo(denied);
+ await denied.locator("#moveResult").waitFor(); await denied.waitForTimeout(800);
+ assert.equal(await denied.locator("#moveResult").isVisible(), true);
+ assert.equal(await denied.locator("#photoPreview").isVisible(), true);
+ assert.equal(await denied.locator("#moveText").textContent(), "Pawn to d4");
+ assert.deepEqual(denied.errors, []); await denied.close();
+});
+
+test("Try demo switches an active scan and static suggestions survive tab visibility changes", async () => {
+ const page = await newPage(); await fakeCamera(page); let started;
+ const requestStarted = new Promise(resolve => { started = resolve; });
+ await page.route("**/api/analyze", async route => { started(); await new Promise(resolve => setTimeout(resolve, 700)); try { await respond(route); } catch {} });
+ await page.route("**/api/analyze-fen", route => respond(route, { ...advice, board_corners: undefined }));
+ await page.goto(origin); await page.locator("#btnStart").click(); await requestStarted;
+ await page.locator("#btnDemo").click(); await page.locator("#moveResult").waitFor();
+ assert.equal(await page.locator("#cameraFeed").isVisible(), false);
+ assert.equal(await page.locator("#photoPreview").isVisible(), true);
+ await page.evaluate(() => {
+ Object.defineProperty(document, "hidden", { configurable: true, get: () => true });
+ document.dispatchEvent(new Event("visibilitychange"));
+ Object.defineProperty(document, "hidden", { configurable: true, get: () => false });
+ document.dispatchEvent(new Event("visibilitychange"));
+ });
+ assert.equal(await page.locator("#moveResult").isVisible(), true);
+ assert.equal(await page.locator("#moveOverlay line").count(), 2);
+ assert.deepEqual(page.errors, []); await page.close();
+});
+
+test("live backend photo reads return an overlay and a legal next move", { skip: !process.env.CHESS_API_URL }, async () => {
+ const page = await newPage();
+ await page.goto(process.env.CHESS_API_URL);
+ await page.locator("#fileInput").setInputFiles(path.join(repo, ".tmp", "camera-start.png"));
+ await page.locator("#moveResult").waitFor();
+ assert.equal(await page.locator("#boardStatus").textContent(), "Board locked");
+ assert.equal(await page.locator("#moveOverlay line").count(), 2);
+ assert.match(await page.locator("#moveUci").textContent(), /^[a-h][1-8] → [a-h][1-8]$/);
+ await page.screenshot({ path: path.join(repo, ".tmp", "screens", "live-overlay-mobile.png"), fullPage: true });
+ await page.locator("#btnDemo").click(); await page.locator("#moveResult").waitFor();
+ assert.equal(await page.locator("#moveOverlay line").count(), 2);
+ assert.deepEqual(page.errors, []); await page.close();
+});
diff --git a/frontend/tests/overlay.test.js b/frontend/tests/overlay.test.js
new file mode 100644
index 0000000..cd5e4e5
--- /dev/null
+++ b/frontend/tests/overlay.test.js
@@ -0,0 +1,43 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { fitInside, projectPoint, moveGeometry, validCorners, resolveApiBase } from "../overlay.js";
+
+test("landscape and portrait camera fit matches the square capture letterbox", () => {
+ assert.deepEqual(fitInside(1920, 1080), { x: 0, y: 218.75, width: 1000, height: 562.5 });
+ assert.deepEqual(fitInside(1080, 1920), { x: 218.75, y: 0, width: 562.5, height: 1000 });
+});
+
+test("perspective projection maps all four actual board corners exactly", () => {
+ const corners = [[.12, .18], [.84, .25], [.97, .9], [.05, .95]];
+ [[0, 0], [1, 0], [1, 1], [0, 1]].forEach(([x, y], i) => {
+ const p = projectPoint(corners, x, y);
+ assert.ok(Math.abs(p[0] - corners[i][0]) < 1e-10);
+ assert.ok(Math.abs(p[1] - corners[i][1]) < 1e-10);
+ });
+});
+
+test("e2 to e4 points to the correct squares for either board orientation", () => {
+ const corners = [[0, 0], [1, 0], [1, 1], [0, 1]];
+ assert.deepEqual(moveGeometry("e2e4", corners).from, [.5625, .8125]);
+ assert.deepEqual(moveGeometry("e2e4", corners).to, [.5625, .5625]);
+ assert.deepEqual(moveGeometry("e2e4", corners, "b").from, [.4375, .1875]);
+ assert.deepEqual(moveGeometry("e2e4", corners, "b").to, [.4375, .4375]);
+ assert.deepEqual(moveGeometry("e7e8q", corners).to, [.5625, .0625]);
+ assert.equal(moveGeometry("bad", corners), null);
+});
+
+test("crossed, out-of-frame and degenerate manual locks are rejected", () => {
+ assert.equal(validCorners([[.1, .1], [.9, .1], [.9, .9], [.1, .9]]), true);
+ assert.equal(validCorners([[0, 0], [1, 1], [1, 0], [0, 1]]), false);
+ assert.equal(validCorners([[0, 0], [1, 0], [1, 0], [0, 0]]), false);
+ assert.equal(validCorners([[0, 0], [2, 0], [1, 1], [0, 1]]), false);
+});
+
+test("Railway and local apps use their own API; Pages and overrides resolve safely", () => {
+ const fallback = "https://backend.up.railway.app";
+ assert.equal(resolveApiBase({ origin: "https://preview.up.railway.app", fallback }), "https://preview.up.railway.app");
+ assert.equal(resolveApiBase({ origin: "http://127.0.0.1:8080", fallback }), "http://127.0.0.1:8080");
+ assert.equal(resolveApiBase({ origin: "https://chess.pages.dev", fallback }), fallback);
+ assert.equal(resolveApiBase({ origin: "https://chess.pages.dev", search: "?api=https://other.example/", fallback }), "https://other.example");
+ assert.throws(() => resolveApiBase({ origin: "https://chess.pages.dev", stored: "javascript:bad", fallback }));
+});
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..e5d1da3
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,42 @@
+{
+ "name": "chess-vision-coach",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "chess-vision-coach",
+ "devDependencies": {
+ "playwright": "^1.57.0"
+ }
+ },
+ "node_modules/playwright": {
+ "version": "1.65.1",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz",
+ "integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.65.1"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.65.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz",
+ "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..b365e1f
--- /dev/null
+++ b/package.json
@@ -0,0 +1,12 @@
+{
+ "name": "chess-vision-coach",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "test": "node --test frontend/tests/*.test.js",
+ "test:browser": "node --test frontend/tests/*.browser.js"
+ },
+ "devDependencies": {
+ "playwright": "^1.57.0"
+ }
+}
From 671f9c3a656489eeb4f1bacaa9b5feaa295bcc8d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=F0=9D=97=94=F0=9D=98=86=F0=9D=98=82=F0=9D=98=80?=
=?UTF-8?q?=F0=9D=97=B5=20=F0=9D=97=9E?= <100coldice@gmail.com>
Date: Tue, 24 Nov 2026 20:53:40 +0530
Subject: [PATCH 4/4] chore: unify deployment assets and add camera regression
CI
---
.dockerignore | 11 +
.github/workflows/checks.yml | 51 ++
.gitignore | 6 +
README.md | 87 +-
backend/DEPLOY.md | 80 +-
backend/Dockerfile | 6 +-
backend/frontend/_headers | 14 -
backend/frontend/app.js | 519 ------------
backend/frontend/index.html | 247 ------
backend/frontend/style.css | 957 ----------------------
backend/requirements-dev.txt | 3 +
backend/tests/generate_camera_fixtures.py | 19 +
docs/API.md | 221 +++--
docs/PERFORMANCE.md | 92 +--
docs/README.md | 269 ++----
15 files changed, 384 insertions(+), 2198 deletions(-)
create mode 100644 .dockerignore
create mode 100644 .github/workflows/checks.yml
delete mode 100644 backend/frontend/_headers
delete mode 100644 backend/frontend/app.js
delete mode 100644 backend/frontend/index.html
delete mode 100644 backend/frontend/style.css
create mode 100644 backend/requirements-dev.txt
create mode 100644 backend/tests/generate_camera_fixtures.py
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..8bcf8ca
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,11 @@
+.git
+.venv
+.tmp
+.pytest_cache
+.wrangler
+node_modules
+test-results
+**/__pycache__
+**/*.pyc
+.env
+.env.*
diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml
new file mode 100644
index 0000000..a4ed76a
--- /dev/null
+++ b/.github/workflows/checks.yml
@@ -0,0 +1,51 @@
+name: Camera coach checks
+on:
+ pull_request:
+ push:
+ branches: [main]
+permissions:
+ contents: read
+jobs:
+ regression:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ cache: pip
+ cache-dependency-path: backend/requirements.txt
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '24'
+ cache: npm
+ - name: Install dependencies
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y stockfish
+ python -m pip install -r backend/requirements.txt pytest httpx
+ npm ci --ignore-scripts
+ npx playwright install --with-deps chromium
+ - name: Backend and overlay regressions
+ run: |
+ python -m pytest backend/tests -q -p no:cacheprovider
+ npm test
+ - name: Mobile browser and live backend regressions
+ env:
+ CHESS_API_URL: http://127.0.0.1:8080
+ STOCKFISH_PATH: /usr/games/stockfish
+ run: |
+ python backend/tests/generate_camera_fixtures.py
+ python -m uvicorn main:app --app-dir backend --host 127.0.0.1 --port 8080 > /tmp/chess-api.log 2>&1 &
+ for attempt in $(seq 1 30); do
+ if curl --fail --silent http://127.0.0.1:8080/health; then break; fi
+ sleep 1
+ done
+ npm run test:browser
+ - uses: actions/upload-artifact@v4
+ if: always()
+ with:
+ name: camera-ui-screenshots
+ path: .tmp/screens
+ if-no-files-found: ignore
diff --git a/.gitignore b/.gitignore
index 8e7eafa..7c50ded 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,3 +25,9 @@ models/*.weights
# Node (if using Wrangler CLI)
node_modules/
+
+# Local verification and deployment artifacts
+.tmp/
+.pytest_cache/
+.wrangler/
+test-results/
diff --git a/README.md b/README.md
index 796260f..f665467 100644
--- a/README.md
+++ b/README.md
@@ -1,57 +1,66 @@
# Chess Vision Coach
-
+A phone-friendly chess camera coach with a move arrow directly over your board and a plain-language suggestion such as **Pawn to d4**.
-
- Point your phone camera at a chess board. Get your next move. No bullshit.
-
+The camera, uploaded photo, detected board boundary, and move arrow share one square view. Start the camera, keep the whole board visible, and the app detects and locks the board automatically. It follows the position as you and your opponent move, and shows advice when it is your turn.
-## 🌟 Overview
+## Board recognition
-Chess Vision Coach is a lightweight, blazing-fast web application that helps you analyze over-the-board chess positions in real-time. Simply point your smartphone camera at a physical chess board, and the app will instantly suggest the best move using the powerful Stockfish engine.
+This version uses OpenCV to find a verified checkerboard and measure piece color and occupancy. It does **not** contain a trained model for identifying arbitrary physical piece types.
-## ✨ Features
+- Begin with the pieces in their standard starting positions for automatic calibration.
+- To join a game already in progress, enter its exact FEN once under **Position & preferences**, choose the side to move, and select **Use for camera**. The supplied piece identities are then retained through legal move tracking.
+- Keep the board in view between moves. The tracker can match an unchanged position, one legal move, or two consecutive legal moves. Unclear frames and ambiguous promotions request a clear frame or position confirmation instead of inventing pieces.
-- **Zero-weight Board Detection:** Utilizes OpenCV for fast, accurate board detection without the need for heavy GPU models. Perfect for overhead phone cameras.
-- **Persistent Engine:** Stockfish is started once on boot and kept alive for all requests, ensuring zero restart overhead between moves.
-- **Smart FEN Caching:** The engine is only called when the board position actually changes, saving resources and battery life.
-- **Multiple Play Modes:** Choose between "Win Mode" for the strongest possible moves, or "Loss Mode" for more human-like, believable inaccuracies.
-- **Adjustable Strength:** Easily change the engine depth to match your desired Elo rating (approx. 800 to 2600+).
+Board orientation and your playing color are separate settings. Orientation is detected automatically; you can also select **White at bottom** or **Black at bottom** regardless of which color you play.
-## 🚀 Quick Deploy
+## Run locally
-Get your own instance running in under a minute!
+Use Python 3.11+ and install Stockfish for full engine strength. The app also provides a bounded Python fallback when the Stockfish binary is unavailable.
-```bash
-# 1. Deploy the Backend to Railway
-cd backend && railway up
+From the repository root:
-# 2. Deploy the Frontend to Cloudflare Pages
-# - Edit API_BASE in frontend/app.js to point to your Railway URL
-# - Push to GitHub and connect in Cloudflare Pages dashboard
+```powershell
+python -m venv .venv
+& .venv\Scripts\python.exe -m pip install -r backend/requirements.txt
+& .venv\Scripts\python.exe -m uvicorn main:app --app-dir backend --host 127.0.0.1 --port 8080
```
-## 🏗️ Architecture & Design
+Open `http://127.0.0.1:8080`. FastAPI serves the frontend and API together; no frontend build is required. Phone camera access needs HTTPS when accessing a server on another device.
-- **Frontend:** Pure HTML/CSS/Vanilla JS for minimal footprint. Hosted on **Cloudflare Pages** for global Edge CDN delivery and custom `Permissions-Policy` headers (crucial for camera access).
-- **Backend:** **FastAPI** providing a robust, async API. Deployed on **Railway** for easy containerized hosting.
-- **Vision:** **OpenCV** was chosen over YOLOv8 for its zero-megabyte model size and ultra-fast inference on standard CPUs, making it ideal for the Railway free tier.
-- **Chess Engine:** **Stockfish** integrated via a persistent, thread-safe service wrapper that auto-recovers from any edge-case crashes.
+If Stockfish is outside the standard system paths, set `STOCKFISH_PATH` to its executable path before starting the server.
-## 📚 Documentation
+## Deploy to Railway
-For more detailed information, check out our comprehensive docs:
+Deploy **the repository root**, which contains the Dockerfile that packages both `backend/` and `frontend/`:
-- [Full Documentation](docs/README.md)
-- [API Reference](docs/API.md)
-- [Performance Notes](docs/PERFORMANCE.md)
+```powershell
+railway login
+railway link
+railway up --service backend
+```
+
+Open the service's HTTPS domain. The Railway-hosted frontend uses that deployment's own API by default. The Docker image installs Stockfish; Railway supplies `PORT`.
+
+For a separate static frontend, publish `frontend/` and use **Connection settings** or a `?api=https://your-backend.up.railway.app` URL to select its backend.
+
+## Tests
+
+From the repository root:
+
+```powershell
+& .venv\Scripts\python.exe -m pip install -r backend/requirements-dev.txt
+& .venv\Scripts\python.exe -m pytest backend/tests -q -p no:cacheprovider
+npm ci
+npm test
+npm run test:browser
+```
+
+The browser suite starts its own test server and uses installed Chrome on Windows. On Linux, install its browser with `npx playwright install --with-deps chromium`. To include real backend integration, generate synthetic camera fixtures with `python backend/tests/generate_camera_fixtures.py`, start the local backend, and set `CHESS_API_URL=http://127.0.0.1:8080` before running the browser suite. CI runs all three suites and saves mobile/desktop screenshots.
+
+## Documentation
----
-
- Built with ❤️ for chess enthusiasts everywhere.
-
+- [Setup and camera workflow](docs/README.md)
+- [API reference](docs/API.md)
+- [Performance and operating limits](docs/PERFORMANCE.md)
+- [Railway deployment](backend/DEPLOY.md)
diff --git a/backend/DEPLOY.md b/backend/DEPLOY.md
index 998dbd1..65facda 100644
--- a/backend/DEPLOY.md
+++ b/backend/DEPLOY.md
@@ -1,57 +1,61 @@
-# Railway Deploy — Chess Vision Coach Backend
+# Railway deployment
-## THIS IS THE FOLDER YOU DEPLOY TO RAILWAY
-Do not deploy the whole repo root. Deploy only this `railway-deploy/` folder.
+## Deploy the repository root
----
+Use the root `Dockerfile` and root `railway.json`. The root image copies both `backend/` and `frontend/`, installs Stockfish, and runs FastAPI. The service serves the web UI at `/`, API routes at `/api/`, and health at `/health`.
-## Method 1: Railway CLI (recommended — 2 commands)
+Deploying only `backend/` does not package the current root frontend. The recommended deployment is the whole repository from its root directory.
-```bash
-# 1. Install Railway CLI if you haven't
-npm install -g @railway/cli
+## Existing project with Railway CLI
-# 2. Login
-railway login
-
-# 3. Navigate INTO this folder
-cd railway-deploy
+From the repository root:
-# 4. Link to your existing Railway project
+```powershell
+railway login
railway link
-# → select your project: chess-machine-production
-
-# 5. Deploy
-railway up
+railway status
+railway up --service backend
```
-Railway will detect the Dockerfile automatically and build it.
+Use your actual service name if it differs from `backend`. The CLI can also select an environment with `--environment production`. A detached deployment returns before it is healthy; verify deployment status and `/health` afterward.
----
+## GitHub deployment
-## Method 2: GitHub (auto-deploy on push)
+Connect the Railway service to the repository and its intended release branch. Leave the service root directory at the repository root so the root Dockerfile packages the UI and API together. The root Railway configuration defines `/health` as the deployment health check.
-1. Create a new GitHub repo (e.g. `chess-backend`)
-2. Copy ONLY the contents of this `railway-deploy/` folder into it (not the folder itself)
-3. Push to GitHub
-4. In Railway dashboard → your service → Settings → Source → connect that GitHub repo
-5. Railway will auto-deploy on every push
+The Docker image installs Stockfish and sets its executable path. Railway injects `PORT`; do not hard-code a different port in the service configuration.
----
+## Configuration
-## Environment variables (already set in Dockerfile — nothing extra needed)
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `STOCKFISH_PATH` | `/usr/games/stockfish` in the Docker image | Stockfish executable. |
+| `PORT` | Supplied by Railway; local Docker fallback `8080` | HTTP listening port. |
+| `MIN_INTERVAL_SEC` | `0.5` | Minimum interval between analysis requests for one session. |
-| Variable | Value | Set by |
-|---|---|---|
-| `STOCKFISH_PATH` | `/usr/games/stockfish` | Dockerfile ENV |
-| `PORT` | auto-assigned | Railway injects at runtime |
+Camera sessions are stored in backend memory. A restart requires starting or calibrating tracking again. For multiple replicas, add session affinity or shared state before relying on continuous position tracking across replicas.
----
+## Verify the service
-## Verify it's working
+Open `https://YOUR-SERVICE.up.railway.app/health`. A ready Stockfish deployment returns:
-After deploy, visit:
-```
-https://YOUR-APP.up.railway.app/health
+```json
+{
+ "status": "ok",
+ "engine": "stockfish",
+ "detector": "opencv",
+ "recognition": "legal-occupancy-tracking",
+ "requires_setup_for_unknown_positions": true,
+ "camera_overlay": true
+}
```
-Should return: `{"status":"ok","engine":"stockfish","detector":"opencv"}`
+
+`engine: "python-chess-fallback"` means the service is available with the weaker fallback engine. Check deployment logs and `STOCKFISH_PATH` if Stockfish is expected. A readiness failure returns HTTP 503.
+
+Then open the HTTPS root URL and use **Try a demo** to verify an engine result and an arrow in the square frame. On a phone, start the camera with a normal starting setup, verify board lock and a suggestion, then move a piece and verify the turn changes. Joining a midgame position requires its exact FEN once; this detector does not independently identify arbitrary piece types.
+
+## Separate frontend hosting
+
+The current frontend has no build step. A static host can publish the `frontend/` directory. Use the UI's **Connection settings** or a `?api=https://YOUR-SERVICE.up.railway.app` URL to select the backend. The Railway-hosted frontend selects its own origin automatically.
+
+Serve phone camera access over HTTPS. The `frontend/_headers` file supplies headers for hosts that support that convention; browser camera permission still comes from the user.
diff --git a/backend/Dockerfile b/backend/Dockerfile
index 24cf7a1..952aa62 100644
--- a/backend/Dockerfile
+++ b/backend/Dockerfile
@@ -7,8 +7,10 @@ RUN apt-get update && \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
-COPY requirements.txt .
+COPY backend/requirements.txt ./requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
-COPY . .
+COPY backend/ ./backend/
+COPY frontend/ ./frontend/
ENV STOCKFISH_PATH=/usr/games/stockfish
+WORKDIR /app/backend
CMD ["sh", "-c", "uvicorn main:app --host 0.0.0.0 --port ${PORT:-8080}"]
diff --git a/backend/frontend/_headers b/backend/frontend/_headers
deleted file mode 100644
index 0594127..0000000
--- a/backend/frontend/_headers
+++ /dev/null
@@ -1,14 +0,0 @@
-# Cloudflare Pages — HTTP headers
-
-/*
- X-Frame-Options: DENY
- X-Content-Type-Options: nosniff
- Referrer-Policy: strict-origin-when-cross-origin
- Permissions-Policy: camera=*
-
-# Cache static assets
-/style.css
- Cache-Control: public, max-age=86400
-
-/app.js
- Cache-Control: public, max-age=86400
diff --git a/backend/frontend/app.js b/backend/frontend/app.js
deleted file mode 100644
index 4133470..0000000
--- a/backend/frontend/app.js
+++ /dev/null
@@ -1,519 +0,0 @@
-/**
- * Chess Vision Coach — Frontend Application v2.0
- */
-
-const DEFAULT_API_BASE = "https://backend-production-e51676e6.up.railway.app";
-const urlParams = new URLSearchParams(window.location.search);
-let API_BASE = urlParams.get("api") || localStorage.getItem("chess_api_base") || DEFAULT_API_BASE;
-
-const POLL_INTERVAL = 2500;
-const MAX_CAPTURE_SIZE = 480;
-const JPEG_QUALITY = 0.82;
-const SESSION_ID = "session_" + Math.random().toString(36).slice(2, 9);
-
-const DEPTH_ELO = {
- 4: 800, 5: 1000, 6: 1200, 7: 1400, 8: 1600, 9: 1750,
- 10: 1900, 11: 2000, 12: 2100, 13: 2200, 14: 2300, 15: 2400, 16: 2600
-};
-
-let isRunning = false;
-let pollTimer = null;
-let lastFrameHash = null;
-let playerColor = "w";
-let playMode = "win";
-let depth = 10;
-let currentInputTab = "camera";
-const recentMoves = [];
-
-const $ = id => document.getElementById(id);
-
-// UI Elements
-const cameraFeed = $("cameraFeed");
-const captureCanvas = $("captureCanvas");
-const cameraOverlay = $("cameraOverlay");
-const liveIndicator = $("liveIndicator");
-const engineStatus = $("engineStatus");
-const engineBadge = $("engineBadge");
-const btnStart = $("btnStart");
-const btnStop = $("btnStop");
-const depthSlider = $("depthSlider");
-const depthVal = $("depthVal");
-const eloHint = $("eloHint");
-
-const moveWaiting = $("moveWaiting");
-const moveResult = $("moveResult");
-const moveText = $("moveText");
-const moveSan = $("moveSan");
-const moveUci = $("moveUci");
-const waitText = $("waitText");
-const statusMsg = $("statusMsg");
-const statusBar = $("statusBar");
-const boardCard = $("boardCard");
-const boardImg = $("boardImg");
-const confBadge = $("confBadge");
-const modeInfo = $("modeInfo");
-const recentContainer = $("recentContainer");
-const recentPills = $("recentPills");
-
-// Mode Tabs & Containers
-const cameraContainer = $("cameraContainer");
-const uploadContainer = $("uploadContainer");
-const presetsContainer = $("presetsContainer");
-const dropZone = $("dropZone");
-const fileInput = $("fileInput");
-const customFenInput = $("customFenInput");
-const btnAnalyzeFen = $("btnAnalyzeFen");
-
-// Modal Elements
-const apiModal = $("apiModal");
-const apiUrlInput = $("apiUrlInput");
-const modalPingStatus = $("modalPingStatus");
-const btnTestPing = $("btnTestPing");
-const btnResetApiDefault = $("btnResetApiDefault");
-const btnSaveApi = $("btnSaveApi");
-const btnConfigApi = $("btnConfigApi");
-
-window.addEventListener("DOMContentLoaded", () => {
- initTabs();
- initToggleGroup("colorToggle", val => { playerColor = val; });
- initToggleGroup("modeToggle", val => { playMode = val; updateModeInfo(); });
- initPresets();
- initUpload();
- initModal();
-
- depthSlider.addEventListener("input", onDepthChange);
- btnStart.addEventListener("click", startAnalysis);
- btnStop.addEventListener("click", stopAnalysis);
- btnAnalyzeFen.addEventListener("click", () => analyzeDirectFen(customFenInput.value.trim()));
-
- checkBackendHealth();
- updateModeInfo();
-});
-
-// ── Tab Navigation ────────────────────────────────────────────────────────
-function initTabs() {
- document.querySelectorAll(".tab-btn").forEach(btn => {
- btn.addEventListener("click", () => {
- document.querySelectorAll(".tab-btn").forEach(b => {
- b.classList.remove("active");
- b.setAttribute("aria-selected", "false");
- });
- btn.classList.add("active");
- btn.setAttribute("aria-selected", "true");
-
- currentInputTab = btn.dataset.tab;
- cameraContainer.style.display = currentInputTab === "camera" ? "block" : "none";
- uploadContainer.style.display = currentInputTab === "upload" ? "block" : "none";
- presetsContainer.style.display = currentInputTab === "presets" ? "block" : "none";
-
- if (currentInputTab !== "camera" && isRunning) {
- stopAnalysis();
- }
- });
- });
-}
-
-// ── Quick Test Presets ────────────────────────────────────────────────────
-function initPresets() {
- document.querySelectorAll(".preset-chip").forEach(chip => {
- chip.addEventListener("click", () => {
- document.querySelectorAll(".preset-chip").forEach(c => c.classList.remove("active"));
- chip.classList.add("active");
- const fen = chip.dataset.fen;
- const col = chip.dataset.color || "w";
- customFenInput.value = fen;
-
- // Update color toggle
- const colorBtn = document.querySelector(`#colorToggle button[data-val="${col}"]`);
- if (colorBtn) colorBtn.click();
-
- analyzeDirectFen(fen);
- });
- });
-}
-
-// ── File Upload & Drag/Drop ───────────────────────────────────────────────
-function initUpload() {
- fileInput.addEventListener("change", e => {
- const file = e.target.files[0];
- if (file) handleImageFile(file);
- });
-
- dropZone.addEventListener("dragover", e => {
- e.preventDefault();
- dropZone.classList.add("dragover");
- });
-
- dropZone.addEventListener("dragleave", () => {
- dropZone.classList.remove("dragover");
- });
-
- dropZone.addEventListener("drop", e => {
- e.preventDefault();
- dropZone.classList.remove("dragover");
- const file = e.dataTransfer.files[0];
- if (file && file.type.startsWith("image/")) {
- handleImageFile(file);
- }
- });
-}
-
-function handleImageFile(file) {
- const reader = new FileReader();
- reader.onload = e => {
- const dataUrl = e.target.result;
- const b64 = dataUrl.split(",")[1];
- analyzeBase64Image(b64);
- };
- reader.readAsDataURL(file);
-}
-
-// ── Toggle Groups ─────────────────────────────────────────────────────────
-function initToggleGroup(groupId, onChange) {
- const group = $(groupId);
- group.querySelectorAll(".toggle-btn").forEach(btn => {
- btn.addEventListener("click", () => {
- group.querySelectorAll(".toggle-btn").forEach(b => {
- b.classList.remove("active");
- b.setAttribute("aria-pressed", "false");
- });
- btn.classList.add("active");
- btn.setAttribute("aria-pressed", "true");
- onChange(btn.dataset.val);
- });
- });
-}
-
-function onDepthChange() {
- depth = parseInt(depthSlider.value);
- depthVal.textContent = depth;
- eloHint.textContent = `≈ ${DEPTH_ELO[depth] ?? "?"} Elo*`;
-}
-
-// ── Camera Capture & Analysis ─────────────────────────────────────────────
-async function startAnalysis() {
- if (isRunning) return;
-
- try {
- const stream = await navigator.mediaDevices.getUserMedia({
- video: { facingMode: "environment", width: { ideal: 1280 }, height: { ideal: 720 } }
- });
- cameraFeed.srcObject = stream;
- await cameraFeed.play();
- cameraOverlay.classList.add("hidden");
- liveIndicator.style.display = "inline-block";
- } catch (err) {
- setStatus(`Camera access error: ${err.message}`, "error");
- return;
- }
-
- try {
- await fetch(`${API_BASE}/api/reset-session?session_id=${SESSION_ID}`, { method: "POST" });
- } catch (_) { }
-
- isRunning = true;
- lastFrameHash = null;
- btnStart.disabled = true;
- btnStop.disabled = false;
- setStatus("Camera live. Analyzing overhead board…", "");
- showWaiting("Scanning camera frame for chess pieces…");
-
- pollTimer = setInterval(captureAndAnalyze, POLL_INTERVAL);
- captureAndAnalyze();
-}
-
-function stopAnalysis() {
- if (!isRunning) return;
- isRunning = false;
- clearInterval(pollTimer);
- pollTimer = null;
-
- const stream = cameraFeed.srcObject;
- if (stream) stream.getTracks().forEach(t => t.stop());
- cameraFeed.srcObject = null;
- cameraOverlay.classList.remove("hidden");
- liveIndicator.style.display = "none";
-
- btnStart.disabled = false;
- btnStop.disabled = true;
- setStatus("Analysis stopped.", "");
-}
-
-async function captureAndAnalyze() {
- if (!isRunning) return;
- const vw = cameraFeed.videoWidth;
- const vh = cameraFeed.videoHeight;
- if (!vw || !vh) return;
-
- const scale = Math.min(MAX_CAPTURE_SIZE / vw, MAX_CAPTURE_SIZE / vh, 1);
- const cw = Math.round(vw * scale);
- const ch = Math.round(vh * scale);
-
- captureCanvas.width = cw;
- captureCanvas.height = ch;
- const ctx = captureCanvas.getContext("2d");
- ctx.drawImage(cameraFeed, 0, 0, cw, ch);
-
- const imageB64Full = captureCanvas.toDataURL("image/jpeg", JPEG_QUALITY);
- const imageB64 = imageB64Full.split(",")[1];
-
- const frameHash = await quickHash(imageB64.slice(0, 2000));
- if (frameHash === lastFrameHash) return;
- lastFrameHash = frameHash;
-
- await analyzeBase64Image(imageB64);
-}
-
-// ── API Invocation ────────────────────────────────────────────────────────
-async function analyzeBase64Image(imageB64) {
- try {
- const t0 = performance.now();
- const res = await fetch(`${API_BASE}/api/analyze`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- image_b64: imageB64,
- player_color: playerColor,
- depth: depth,
- mode: playMode,
- session_id: SESSION_ID,
- }),
- });
-
- const elapsed = Math.round(performance.now() - t0);
-
- if (!res.ok) {
- setStatus(`Server error ${res.status}`, "error");
- return;
- }
-
- const data = await res.json();
- handleResponse(data, elapsed);
-
- } catch (err) {
- setStatus(`Network error: ${err.message}`, "error");
- }
-}
-
-async function analyzeDirectFen(fen) {
- if (!fen) return;
- showWaiting("Evaluating position with Stockfish…");
- try {
- const t0 = performance.now();
- const res = await fetch(`${API_BASE}/api/analyze-fen`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- fen: fen,
- player_color: playerColor,
- depth: depth,
- mode: playMode,
- }),
- });
-
- const elapsed = Math.round(performance.now() - t0);
-
- if (!res.ok) {
- const errData = await res.json().catch(() => ({}));
- setStatus(`Error: ${errData.message || res.statusText}`, "error");
- return;
- }
-
- const data = await res.json();
- handleResponse(data, elapsed);
-
- } catch (err) {
- setStatus(`Network error: ${err.message}`, "error");
- }
-}
-
-// ── Response Handler ──────────────────────────────────────────────────────
-function handleResponse(data, elapsedMs) {
- switch (data.status) {
-
- case "ok":
- showMove(data.move_human, data.move_san, data.move_uci);
- const confStr = data.confidence < 1.0 ? ` | Conf: ${pct(data.confidence)}` : "";
- setStatus(`Optimal move computed (${elapsedMs}ms)${confStr} • ≈${data.approx_elo} Elo`, "ok");
- if (data.board_image_b64) {
- updateBoard(data.board_image_b64, data.confidence);
- }
- addRecentMove(data.move_san || data.move_uci);
- break;
-
- case "no_change":
- setStatus("Board unchanged — waiting for opponent's move…", "");
- break;
-
- case "opponent_turn":
- setStatus("Opponent's turn detected. Waiting for their move…", "");
- break;
-
- case "detection_error":
- setStatus(`⚠ ${data.message}`, "error");
- showWaiting("Board not fully visible. Reposition camera overhead.");
- break;
-
- case "engine_error":
- setStatus("⚙ Engine restarting… retrying automatically.", "");
- break;
-
- case "rate_limited":
- setStatus("Slowing down analysis pace…", "");
- break;
-
- case "game_over":
- setStatus("Checkmate, stalemate, or game over.", "ok");
- showWaiting("Game over — no legal moves remaining.");
- break;
-
- default:
- setStatus(data.message ?? "Unknown response.", "");
- }
-}
-
-function showMove(humanText, san, uci) {
- moveWaiting.style.display = "none";
- moveResult.style.display = "block";
- moveText.textContent = humanText ?? "—";
- moveSan.textContent = san ?? uci ?? "";
- moveUci.textContent = uci ? `${uci.slice(0, 2)} → ${uci.slice(2, 4)}` : "";
-
- moveResult.classList.remove("move-anim");
- void moveResult.offsetWidth;
- moveResult.classList.add("move-anim");
-}
-
-function showWaiting(msg) {
- moveWaiting.style.display = "flex";
- moveResult.style.display = "none";
- if (msg) waitText.textContent = msg;
-}
-
-function setStatus(msg, type = "") {
- statusMsg.textContent = msg;
- statusBar.className = "status-bar" + (type ? ` ${type}` : "");
-}
-
-function updateBoard(b64, confidence) {
- if (!b64) return;
- boardCard.style.display = "block";
- boardImg.src = `data:image/png;base64,${b64}`;
- confBadge.textContent = pct(confidence);
-}
-
-function addRecentMove(san) {
- if (!san) return;
- if (!recentMoves.includes(san)) {
- recentMoves.unshift(san);
- if (recentMoves.length > 5) recentMoves.pop();
-
- recentContainer.style.display = "flex";
- recentPills.innerHTML = recentMoves.map(m => `
${m} `).join("");
- }
-}
-
-function pct(val) {
- return val != null ? `${Math.round(val * 100)}%` : "—";
-}
-
-function updateModeInfo() {
- const modes = {
- win: {
- icon: "🏆",
- title: "Win Mode",
- desc: "Calculates sharp, decisive, high-accuracy moves tailored to win quickly.",
- },
- loss: {
- icon: "🎭",
- title: "Loss Mode",
- desc: "Provides believable, human-like inaccuracies without obvious tactical blunders.",
- },
- };
- const m = modes[playMode] || modes.win;
- modeInfo.innerHTML = `
-
${m.icon}
-
-
${m.title}
-
${m.desc}
-
`;
-}
-
-// ── Health Check & Engine Status ──────────────────────────────────────────
-async function checkBackendHealth() {
- setEngineStatus("connecting", "Connecting…");
- try {
- const t0 = performance.now();
- const res = await fetch(`${API_BASE}/health`, { signal: AbortSignal.timeout(5000) });
- const latency = Math.round(performance.now() - t0);
- if (res.ok) {
- const data = await res.json().catch(() => ({}));
- const engineName = data.engine === "stockfish" ? "Stockfish 16" : "Python Engine";
- setEngineStatus("online", `Online (${latency}ms)`);
- if (engineBadge) engineBadge.textContent = engineName;
- } else {
- setEngineStatus("offline", `Server Error (${res.status})`);
- }
- } catch {
- setEngineStatus("offline", "Backend Offline");
- }
-}
-
-function setEngineStatus(cls, label) {
- engineStatus.className = `status-pill ${cls}`;
- engineStatus.querySelector(".status-label").textContent = label;
- engineStatus.title = `API: ${API_BASE} (Click to configure)`;
-}
-
-// ── API Configuration Modal ───────────────────────────────────────────────
-function initModal() {
- engineStatus.addEventListener("click", openApiModal);
- if (btnConfigApi) btnConfigApi.addEventListener("click", openApiModal);
-
- btnTestPing.addEventListener("click", async () => {
- const targetUrl = apiUrlInput.value.trim().replace(/\/+$/, "");
- modalPingStatus.textContent = "Testing connection…";
- try {
- const t0 = performance.now();
- const res = await fetch(`${targetUrl}/health`, { signal: AbortSignal.timeout(5000) });
- const ms = Math.round(performance.now() - t0);
- if (res.ok) {
- modalPingStatus.textContent = `✓ Connected! Response in ${ms}ms`;
- modalPingStatus.style.color = "var(--accent)";
- } else {
- modalPingStatus.textContent = `✗ HTTP Error ${res.status}`;
- modalPingStatus.style.color = "var(--danger)";
- }
- } catch (e) {
- modalPingStatus.textContent = `✗ Unreachable: ${e.message}`;
- modalPingStatus.style.color = "var(--danger)";
- }
- });
-
- btnResetApiDefault.addEventListener("click", () => {
- apiUrlInput.value = DEFAULT_API_BASE;
- });
-
- btnSaveApi.addEventListener("click", () => {
- const val = apiUrlInput.value.trim().replace(/\/+$/, "");
- if (val) {
- API_BASE = val;
- localStorage.setItem("chess_api_base", API_BASE);
- apiModal.close();
- checkBackendHealth();
- }
- });
-}
-
-function openApiModal() {
- apiUrlInput.value = API_BASE;
- modalPingStatus.textContent = "Click 'Test Connection' to verify server reachability.";
- modalPingStatus.style.color = "var(--text-dim)";
- apiModal.showModal();
-}
-
-async function quickHash(str) {
- if (!crypto?.subtle) return str.slice(0, 64);
- const buf = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(str));
- return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, "0")).join("");
-}
diff --git a/backend/frontend/index.html b/backend/frontend/index.html
deleted file mode 100644
index 7466703..0000000
--- a/backend/frontend/index.html
+++ /dev/null
@@ -1,247 +0,0 @@
-
-
-
-
-
-
-
-
Chess Vision Coach • AI Move Suggester
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 📷 Live Camera
-
-
- 📁 Upload Photo
-
-
- ⚡ Quick Test
-
-
-
-
-
-
-
- Camera Feed
- ● LIVE
-
-
-
-
-
- 📷
- Point camera overhead at your physical board
- Click "Start Analysis" below or switch to "Quick Test" to try without camera
-
-
-
-
-
-
-
Upload Board Snapshot
-
-
- 📤
- Drag & drop a chessboard photo here, or browse files
- PNG, JPEG, WebP up to 10MB
-
-
-
-
-
-
Test Positions & FEN Input
-
Instantly test move suggestions without needing a camera:
-
- Starting Position
- Italian Game Fork
- Scholar's Mate Threat
- Endgame Knight
-
-
-
- Analyze FEN
-
-
-
-
-
-
- Detected Board & Move Arrow
- –
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Player Setup
-
-
-
-
I'm playing as
-
-
- ♔ White
-
-
- ♚ Black
-
-
-
-
-
-
-
Engine Strategy
-
-
- 🏆 Win Mode
-
-
- 🎭 Loss Mode
-
-
-
-
-
-
-
- Calculation Depth
- ≈ 1900 Elo*
-
-
-
- 10
-
-
* Approximate Elo estimate for practical human play
-
-
-
-
- ▶ Start Analysis
- ■ Stop
-
-
-
-
-
-
- Recommended Move
- Stockfish 16
-
-
-
-
-
- ⏳
- Ready. Press "Start Analysis" or choose a Quick Test position.
-
-
-
-
-
-
-
-
-
-
- Ready for moves.
-
-
-
-
-
-
-
🏆
-
-
Win Mode
-
Calculates sharp, decisive, high-accuracy moves tailored to win quickly.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Backend API Settings
-
Configure the Railway or local FastAPI backend server URL:
-
-
Testing connection…
-
- Test Connection
- Reset Default
- Save & Close
-
-
-
-
-
-
-
diff --git a/backend/frontend/style.css b/backend/frontend/style.css
deleted file mode 100644
index 9603e67..0000000
--- a/backend/frontend/style.css
+++ /dev/null
@@ -1,957 +0,0 @@
-/* ═══════════════════════════════════════════════════════════
- Chess Vision Coach — Stylesheet v2.0
- Modern Dark Theme with Cyber-Emerald & Amber Accents
- ═══════════════════════════════════════════════════════════ */
-
-*, *::before, *::after {
- box-sizing: border-box;
- margin: 0;
- padding: 0;
-}
-
-:root {
- color-scheme: light dark;
- --bg-deep: #090b0e;
- --bg-card: #12161f;
- --bg-card2: #1a202c;
- --bg-card-hover: #222938;
- --border-subtle: rgba(255, 255, 255, 0.08);
- --border-focus: rgba(16, 185, 129, 0.5);
-
- --accent: #10b981;
- --accent-light: #34d399;
- --accent-glow: rgba(16, 185, 129, 0.25);
-
- --accent2: #f59e0b;
- --accent2-glow: rgba(245, 158, 11, 0.2);
-
- --primary: #6366f1;
- --danger: #ef4444;
- --text: #f9fafb;
- --text-dim: #9ca3af;
- --text-muted: #6b7280;
-
- --radius-lg: 14px;
- --radius-md: 10px;
- --radius-sm: 6px;
- --gap: 16px;
-
- accent-color: var(--accent);
- scrollbar-color: var(--bg-card2) transparent;
-}
-
-html {
- font-size: 16px;
- scroll-behavior: smooth;
-}
-
-body {
- font-family: 'Space Grotesk', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
- background: var(--bg-deep);
- background-image:
- radial-gradient(circle at 15% 15%, rgba(16, 185, 129, 0.05) 0%, transparent 40%),
- radial-gradient(circle at 85% 85%, rgba(99, 102, 241, 0.04) 0%, transparent 40%);
- background-attachment: fixed;
- color: var(--text);
- min-height: 100dvh;
- display: flex;
- flex-direction: column;
- line-height: 1.5;
-}
-
-/* ── Accessibility ───────────────────────────────── */
-.visually-hidden {
- position: absolute !important;
- clip-path: inset(50%) !important;
- overflow: hidden !important;
- width: 1px !important;
- height: 1px !important;
- margin: -1px !important;
- padding: 0 !important;
- border: 0 !important;
- white-space: nowrap !important;
-}
-
-:focus-visible {
- outline: 2px solid var(--accent);
- outline-offset: 2px;
-}
-
-/* ── Header ─────────────────────────────────────── */
-.header {
- background: rgba(18, 22, 31, 0.85);
- backdrop-filter: blur(12px);
- -webkit-backdrop-filter: blur(12px);
- border-bottom: 1px solid var(--border-subtle);
- padding: 0 24px;
- height: 64px;
- position: sticky;
- top: 0;
- z-index: 100;
-}
-
-.header-inner {
- max-width: 1140px;
- margin: 0 auto;
- height: 100%;
- display: flex;
- align-items: center;
- justify-content: space-between;
-}
-
-.logo {
- display: flex;
- align-items: center;
- gap: 12px;
-}
-
-.logo-icon {
- font-size: 1.8rem;
- line-height: 1;
- filter: drop-shadow(0 0 8px var(--accent-glow));
-}
-
-.logo-titles {
- display: flex;
- flex-direction: column;
-}
-
-.logo-text {
- font-weight: 700;
- font-size: 1.15rem;
- letter-spacing: -0.02em;
- color: var(--text);
-}
-
-.logo-badge {
- font-size: 0.68rem;
- font-weight: 600;
- text-transform: uppercase;
- letter-spacing: 0.08em;
- color: var(--accent);
-}
-
-/* Status Pill */
-.status-pill {
- display: flex;
- align-items: center;
- gap: 8px;
- background: var(--bg-card2);
- border: 1px solid var(--border-subtle);
- border-radius: 999px;
- padding: 6px 16px;
- font-size: 0.82rem;
- font-family: inherit;
- color: var(--text-dim);
- cursor: pointer;
- transition: all 0.2s ease;
-}
-
-.status-pill:hover {
- border-color: var(--accent);
- background: var(--bg-card-hover);
-}
-
-.status-dot {
- width: 9px;
- height: 9px;
- border-radius: 50%;
- background: #6b7280;
- transition: all 0.3s ease;
-}
-
-.status-pill.online .status-dot {
- background: var(--accent);
- box-shadow: 0 0 10px var(--accent);
-}
-.status-pill.online .status-label {
- color: var(--accent-light);
- font-weight: 600;
-}
-
-.status-pill.offline .status-dot {
- background: var(--danger);
- box-shadow: 0 0 8px rgba(239, 68, 68, 0.4);
-}
-.status-pill.offline .status-label {
- color: var(--danger);
-}
-
-.status-pill.connecting .status-dot {
- background: var(--accent2);
- animation: pulse 1s infinite alternate;
-}
-
-/* ── Main Layout ────────────────────────────────── */
-.main {
- flex: 1;
- max-width: 1140px;
- width: 100%;
- margin: 0 auto;
- padding: var(--gap);
- display: grid;
- grid-template-columns: 1.05fr 0.95fr;
- gap: var(--gap);
- align-items: start;
-}
-
-@media (max-width: 820px) {
- .main {
- grid-template-columns: 1fr;
- padding: 12px;
- }
-}
-
-.col {
- display: flex;
- flex-direction: column;
- gap: var(--gap);
-}
-
-/* ── Universal Cards ────────────────────────────── */
-.card {
- background: var(--bg-card);
- border: 1px solid var(--border-subtle);
- border-radius: var(--radius-lg);
- padding: 20px;
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
- transition: border-color 0.2s ease;
-}
-
-.card:hover {
- border-color: rgba(255, 255, 255, 0.12);
-}
-
-.card-label {
- font-size: 0.74rem;
- font-weight: 700;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--text-dim);
- margin-bottom: 14px;
- display: flex;
- align-items: center;
- justify-content: space-between;
-}
-
-/* ── Input Mode Tabs ────────────────────────────── */
-.mode-tabs-card {
- padding: 8px;
-}
-
-.tab-group {
- display: flex;
- gap: 6px;
- background: var(--bg-deep);
- padding: 4px;
- border-radius: var(--radius-md);
-}
-
-.tab-btn {
- flex: 1;
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 6px;
- background: transparent;
- border: none;
- border-radius: var(--radius-sm);
- color: var(--text-dim);
- font-family: inherit;
- font-size: 0.85rem;
- font-weight: 600;
- padding: 10px 8px;
- cursor: pointer;
- transition: all 0.2s ease;
-}
-
-.tab-btn:hover {
- color: var(--text);
- background: rgba(255, 255, 255, 0.04);
-}
-
-.tab-btn.active {
- background: var(--bg-card2);
- color: var(--accent);
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
-}
-
-/* ── Camera Card ────────────────────────────────── */
-.camera-wrapper {
- position: relative;
- background: #000;
- border-radius: var(--radius-md);
- overflow: hidden;
- aspect-ratio: 4 / 3;
- box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.8);
-}
-
-#cameraFeed {
- width: 100%;
- height: 100%;
- object-fit: cover;
- display: block;
-}
-
-.live-indicator {
- font-size: 0.68rem;
- font-weight: 700;
- color: #ef4444;
- letter-spacing: 0.05em;
- animation: pulse 1s infinite alternate;
-}
-
-.camera-overlay {
- position: absolute;
- inset: 0;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- text-align: center;
- padding: 24px;
- background: rgba(10, 14, 20, 0.88);
- color: var(--text);
- transition: opacity 0.3s;
-}
-
-.camera-overlay.hidden {
- opacity: 0;
- pointer-events: none;
-}
-
-.overlay-icon {
- font-size: 2.8rem;
- margin-bottom: 8px;
- color: var(--accent);
-}
-
-.overlay-title {
- font-size: 1rem;
- font-weight: 600;
- margin-bottom: 4px;
-}
-
-.overlay-sub {
- font-size: 0.82rem;
- color: var(--text-dim);
- max-width: 320px;
-}
-
-/* ── Drag & Drop Photo Upload ───────────────────── */
-.upload-dropzone {
- border: 2px dashed rgba(255, 255, 255, 0.15);
- border-radius: var(--radius-md);
- padding: 36px 20px;
- text-align: center;
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 8px;
- cursor: pointer;
- background: var(--bg-deep);
- transition: all 0.2s ease;
-}
-
-.upload-dropzone:hover,
-.upload-dropzone.dragover {
- border-color: var(--accent);
- background: rgba(16, 185, 129, 0.04);
-}
-
-.upload-icon {
- font-size: 2.4rem;
- color: var(--accent);
-}
-
-.upload-text {
- font-size: 0.92rem;
- color: var(--text);
-}
-
-.upload-link {
- color: var(--accent);
- text-decoration: underline;
- cursor: pointer;
-}
-
-.upload-hint {
- font-size: 0.75rem;
- color: var(--text-muted);
-}
-
-/* ── Presets & Quick Test ───────────────────────── */
-.presets-intro {
- font-size: 0.84rem;
- color: var(--text-dim);
- margin-bottom: 12px;
-}
-
-.preset-buttons {
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 8px;
- margin-bottom: 16px;
-}
-
-@media (max-width: 500px) {
- .preset-buttons {
- grid-template-columns: 1fr;
- }
-}
-
-.preset-chip {
- background: var(--bg-card2);
- border: 1px solid var(--border-subtle);
- border-radius: var(--radius-sm);
- color: var(--text);
- font-family: inherit;
- font-size: 0.82rem;
- font-weight: 600;
- padding: 10px 12px;
- text-align: left;
- cursor: pointer;
- transition: all 0.2s ease;
-}
-
-.preset-chip:hover {
- border-color: var(--accent);
- background: var(--bg-card-hover);
-}
-
-.preset-chip.active {
- border-color: var(--accent);
- background: rgba(16, 185, 129, 0.12);
- color: var(--accent-light);
-}
-
-.custom-fen-row {
- display: flex;
- gap: 8px;
-}
-
-.custom-fen-input {
- flex: 1;
- background: var(--bg-deep);
- border: 1px solid var(--border-subtle);
- border-radius: var(--radius-sm);
- color: var(--text);
- font-family: 'Space Mono', monospace;
- font-size: 0.8rem;
- padding: 10px 12px;
- outline: none;
- transition: border-color 0.2s;
-}
-
-.custom-fen-input:focus {
- border-color: var(--accent);
-}
-
-/* ── Board preview card ─────────────────────────── */
-.board-wrapper {
- border-radius: var(--radius-md);
- overflow: hidden;
- background: #000;
- border: 1px solid var(--border-subtle);
-}
-
-.board-wrapper img {
- width: 100%;
- display: block;
-}
-
-.conf-badge {
- font-size: 0.75rem;
- background: var(--bg-card2);
- border: 1px solid rgba(16, 185, 129, 0.3);
- border-radius: 999px;
- padding: 3px 10px;
- color: var(--accent-light);
- font-family: 'Space Mono', monospace;
- font-weight: 700;
-}
-
-/* ── Config card ────────────────────────────────── */
-.control-group {
- margin-bottom: 20px;
-}
-
-.ctrl-label {
- display: flex;
- align-items: center;
- justify-content: space-between;
- font-size: 0.84rem;
- font-weight: 600;
- color: var(--text-dim);
- margin-bottom: 8px;
-}
-
-.elo-hint {
- font-family: 'Space Mono', monospace;
- font-size: 0.82rem;
- color: var(--accent2);
- font-weight: 700;
-}
-
-/* Toggle buttons */
-.toggle-group {
- display: flex;
- gap: 8px;
-}
-
-.toggle-btn {
- flex: 1;
- background: var(--bg-card2);
- border: 1.5px solid var(--border-subtle);
- border-radius: var(--radius-md);
- color: var(--text-dim);
- font-family: inherit;
- font-size: 0.88rem;
- font-weight: 600;
- padding: 10px 8px;
- cursor: pointer;
- transition: all 0.15s ease;
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 8px;
-}
-
-.toggle-btn:hover {
- border-color: rgba(255, 255, 255, 0.2);
- color: var(--text);
-}
-
-.toggle-btn.active {
- background: var(--accent);
- border-color: var(--accent);
- color: #062b1a;
- font-weight: 700;
- box-shadow: 0 2px 12px var(--accent-glow);
-}
-
-.piece-icon {
- font-size: 1.2rem;
-}
-
-/* Depth slider */
-.depth-row {
- display: flex;
- align-items: center;
- gap: 14px;
-}
-
-input[type="range"] {
- flex: 1;
- -webkit-appearance: none;
- appearance: none;
- height: 6px;
- border-radius: 3px;
- background: var(--bg-card2);
- outline: none;
-}
-
-input[type="range"]::-webkit-slider-thumb {
- -webkit-appearance: none;
- appearance: none;
- width: 20px;
- height: 20px;
- border-radius: 50%;
- background: var(--accent);
- cursor: pointer;
- box-shadow: 0 0 10px var(--accent-glow);
- transition: transform 0.1s;
-}
-
-input[type="range"]::-webkit-slider-thumb:hover {
- transform: scale(1.15);
-}
-
-.depth-val {
- font-family: 'Space Mono', monospace;
- font-size: 1.2rem;
- font-weight: 700;
- color: var(--accent2);
- min-width: 28px;
- text-align: right;
-}
-
-.elo-note {
- font-size: 0.72rem;
- color: var(--text-muted);
- margin-top: 6px;
-}
-
-/* Action Buttons */
-.btn-row {
- display: flex;
- gap: 10px;
- margin-top: 8px;
-}
-
-.btn {
- font-family: inherit;
- font-size: 0.92rem;
- font-weight: 700;
- padding: 12px 18px;
- border-radius: var(--radius-md);
- border: none;
- cursor: pointer;
- transition: all 0.15s ease;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- gap: 6px;
-}
-
-.btn-start {
- flex: 1.4;
- background: var(--accent);
- color: #062b1a;
- box-shadow: 0 4px 14px var(--accent-glow);
-}
-
-.btn-start:hover:not(:disabled) {
- background: var(--accent-light);
- transform: translateY(-1px);
-}
-
-.btn-stop {
- flex: 1;
- background: var(--bg-card2);
- color: var(--danger);
- border: 1.5px solid var(--danger);
-}
-
-.btn-stop:hover:not(:disabled) {
- background: var(--danger);
- color: #fff;
-}
-
-.btn-secondary {
- background: var(--bg-card2);
- color: var(--text);
- border: 1px solid var(--border-subtle);
- font-size: 0.85rem;
-}
-
-.btn-secondary:hover {
- background: var(--bg-card-hover);
- border-color: rgba(255, 255, 255, 0.2);
-}
-
-.btn:disabled {
- opacity: 0.35;
- cursor: not-allowed;
- transform: none !important;
-}
-
-/* ── Move Output Card ───────────────────────────── */
-.move-card {
- position: relative;
- overflow: hidden;
-}
-
-.engine-badge {
- font-family: 'Space Mono', monospace;
- font-size: 0.7rem;
- font-weight: 700;
- color: var(--text-dim);
- background: var(--bg-card2);
- padding: 3px 10px;
- border-radius: 999px;
- border: 1px solid var(--border-subtle);
-}
-
-.move-display {
- background: linear-gradient(145deg, var(--bg-card2), var(--bg-deep));
- border-radius: var(--radius-md);
- padding: 24px 20px;
- min-height: 128px;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-bottom: 14px;
- border: 1.5px solid rgba(255, 255, 255, 0.06);
- position: relative;
-}
-
-.move-waiting {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 10px;
- color: var(--text-dim);
- font-size: 0.9rem;
- text-align: center;
-}
-
-.wait-icon {
- font-size: 2rem;
- animation: pulse 1.5s infinite alternate;
-}
-
-.move-result {
- text-align: center;
- width: 100%;
-}
-
-.move-header {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 12px;
- margin-bottom: 8px;
-}
-
-.move-san {
- font-family: 'Space Mono', monospace;
- font-size: 1.7rem;
- color: var(--accent);
- font-weight: 700;
- letter-spacing: 0.05em;
- text-shadow: 0 0 16px var(--accent-glow);
-}
-
-.move-uci-badge {
- font-family: 'Space Mono', monospace;
- font-size: 0.85rem;
- font-weight: 700;
- color: var(--accent2);
- background: var(--bg-deep);
- padding: 4px 10px;
- border-radius: 999px;
- border: 1px solid var(--border-subtle);
-}
-
-.move-text {
- font-size: 1.35rem;
- font-weight: 700;
- color: var(--text);
- line-height: 1.3;
- letter-spacing: -0.01em;
-}
-
-/* Recent Suggestions Trail */
-.recent-moves-container {
- margin-bottom: 14px;
- display: flex;
- align-items: center;
- gap: 10px;
-}
-
-.recent-label {
- font-size: 0.74rem;
- font-weight: 700;
- text-transform: uppercase;
- color: var(--text-muted);
-}
-
-.recent-pills {
- display: flex;
- gap: 6px;
- flex-wrap: wrap;
-}
-
-.recent-chip {
- font-family: 'Space Mono', monospace;
- font-size: 0.78rem;
- background: var(--bg-card2);
- border: 1px solid var(--border-subtle);
- border-radius: 999px;
- padding: 2px 10px;
- color: var(--text-dim);
-}
-
-/* Status Bar */
-.status-bar {
- background: var(--bg-card2);
- border-radius: var(--radius-sm);
- padding: 10px 14px;
- font-size: 0.82rem;
- color: var(--text-dim);
- min-height: 40px;
- display: flex;
- align-items: center;
- gap: 8px;
- border: 1px solid var(--border-subtle);
-}
-
-.status-indicator-dot {
- width: 7px;
- height: 7px;
- border-radius: 50%;
- background: var(--text-muted);
- flex-shrink: 0;
-}
-
-.status-bar.error .status-indicator-dot { background: var(--danger); }
-.status-bar.error { color: var(--danger); border-color: rgba(239, 68, 68, 0.3); }
-
-.status-bar.ok .status-indicator-dot { background: var(--accent); }
-.status-bar.ok { color: var(--accent-light); border-color: rgba(16, 185, 129, 0.3); }
-
-/* ── Mode info card ─────────────────────────────── */
-.info-card {
- padding: 14px 18px;
-}
-
-.mode-info {
- display: flex;
- align-items: flex-start;
- gap: 14px;
- font-size: 0.84rem;
-}
-
-.mode-icon {
- font-size: 1.6rem;
- flex-shrink: 0;
-}
-
-.mode-info strong {
- display: block;
- margin-bottom: 2px;
- color: var(--text);
- font-size: 0.92rem;
-}
-
-.mode-info p {
- color: var(--text-dim);
- line-height: 1.45;
-}
-
-/* ── Modal Dialog ───────────────────────────────── */
-.modal-dialog {
- border: 1px solid var(--border-subtle);
- border-radius: var(--radius-lg);
- background: var(--bg-card);
- color: var(--text);
- padding: 0;
- max-width: 480px;
- width: 90%;
- margin: auto;
- box-shadow: 0 10px 40px rgba(0, 0, 0, 0.7);
-}
-
-.modal-dialog::backdrop {
- background: rgba(0, 0, 0, 0.75);
- backdrop-filter: blur(4px);
-}
-
-.modal-content {
- padding: 24px;
- display: flex;
- flex-direction: column;
- gap: 14px;
-}
-
-.modal-title {
- font-size: 1.15rem;
- font-weight: 700;
-}
-
-.modal-desc {
- font-size: 0.85rem;
- color: var(--text-dim);
-}
-
-.modal-input {
- background: var(--bg-deep);
- border: 1px solid var(--border-subtle);
- border-radius: var(--radius-sm);
- color: var(--text);
- font-family: 'Space Mono', monospace;
- font-size: 0.85rem;
- padding: 12px;
- width: 100%;
- outline: none;
-}
-
-.modal-input:focus {
- border-color: var(--accent);
-}
-
-.modal-status {
- font-size: 0.8rem;
- font-family: 'Space Mono', monospace;
- color: var(--text-dim);
- padding: 6px 0;
-}
-
-.modal-actions {
- display: flex;
- justify-content: flex-end;
- gap: 10px;
- margin-top: 8px;
-}
-
-/* ── Footer ─────────────────────────────────────── */
-.footer {
- font-size: 0.78rem;
- color: var(--text-muted);
- padding: 20px;
- border-top: 1px solid var(--border-subtle);
- margin-top: auto;
-}
-
-.footer-inner {
- max-width: 1140px;
- margin: 0 auto;
- display: flex;
- align-items: center;
- justify-content: space-between;
- flex-wrap: wrap;
- gap: 12px;
-}
-
-.footer-links {
- display: flex;
- align-items: center;
- gap: 8px;
-}
-
-.footer-link-btn,
-.footer-link {
- background: none;
- border: none;
- color: var(--text-dim);
- font-size: inherit;
- font-family: inherit;
- cursor: pointer;
- text-decoration: underline;
- transition: color 0.15s;
-}
-
-.footer-link-btn:hover,
-.footer-link:hover {
- color: var(--accent);
-}
-
-/* ── Animations ─────────────────────────────────── */
-@keyframes pulse {
- 0% { opacity: 1; }
- 100% { opacity: 0.4; }
-}
-
-@keyframes slideIn {
- from {
- opacity: 0;
- transform: translateY(10px) scale(0.98);
- }
- to {
- opacity: 1;
- transform: translateY(0) scale(1);
- }
-}
-
-.move-anim {
- animation: slideIn 0.35s cubic-bezier(0.16, 1, 0.3, 1);
-}
-
-@media (prefers-reduced-motion: reduce) {
- .move-anim,
- .live-indicator,
- .wait-icon {
- animation: none;
- }
-}
diff --git a/backend/requirements-dev.txt b/backend/requirements-dev.txt
new file mode 100644
index 0000000..5ae2984
--- /dev/null
+++ b/backend/requirements-dev.txt
@@ -0,0 +1,3 @@
+-r requirements.txt
+pytest>=8,<10
+httpx>=0.27,<0.29
diff --git a/backend/tests/generate_camera_fixtures.py b/backend/tests/generate_camera_fixtures.py
new file mode 100644
index 0000000..e9fe24a
--- /dev/null
+++ b/backend/tests/generate_camera_fixtures.py
@@ -0,0 +1,19 @@
+"""Generate reproducible synthetic camera fixtures for browser integration QA."""
+from pathlib import Path
+import sys
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import chess
+import cv2
+from test_board_detector import board_image
+
+
+if __name__ == "__main__":
+ output = Path(__file__).resolve().parents[2] / ".tmp"
+ output.mkdir(exist_ok=True)
+ board = chess.Board()
+ for name, move in [("camera-start.png", None), ("camera-e4.png", "e2e4")]:
+ if move:
+ board.push_uci(move)
+ assert cv2.imwrite(str(output / name), board_image(board)), "Could not write camera fixture"
+ print("Generated synthetic camera fixtures in .tmp")
diff --git a/docs/API.md b/docs/API.md
index a3cca0f..5fe8a55 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -1,155 +1,152 @@
-# API Documentation — Chess Vision Coach
+# API reference
-Base URL: `https://your-app.up.railway.app`
+The API is served by FastAPI at the same origin as the Railway-hosted frontend. Interactive documentation is available at `/docs`.
----
+## `GET /health`
-## Endpoints
+Returns HTTP 200 when the engine service and detector are ready, or HTTP 503 while they are not ready.
-### `GET /health`
-
-Health check. Returns 200 if the backend is running.
-
-**Response:**
```json
-{ "status": "ok", "engine": "stockfish", "detector": "opencv" }
+{
+ "status": "ok",
+ "engine": "stockfish",
+ "detector": "opencv",
+ "recognition": "legal-occupancy-tracking",
+ "requires_setup_for_unknown_positions": true,
+ "camera_overlay": true
+}
```
----
+`engine` is `python-chess-fallback` when Stockfish is unavailable. A ready fallback service does not imply Stockfish strength.
-### `GET /api/depth-info`
+## `POST /api/analyze`
-Returns the depth → approximate Elo mapping used by the frontend dropdown.
+Analyzes a camera frame or an authoritative FEN within a tracking session.
-**Response:**
```json
{
- "depths": [
- { "depth": 4, "approx_elo": 800 },
- { "depth": 5, "approx_elo": 1000 },
- { "depth": 6, "approx_elo": 1200 },
- { "depth": 7, "approx_elo": 1400 },
- { "depth": 8, "approx_elo": 1600 },
- { "depth": 9, "approx_elo": 1750 },
- { "depth": 10, "approx_elo": 1900 },
- { "depth": 11, "approx_elo": 2000 },
- { "depth": 12, "approx_elo": 2100 },
- { "depth": 13, "approx_elo": 2200 },
- { "depth": 14, "approx_elo": 2300 },
- { "depth": 15, "approx_elo": 2400 },
- { "depth": 16, "approx_elo": 2600 }
- ],
- "note": "Elo values are approximate estimates, not official ratings."
+ "image_b64": "
",
+ "player_color": "w",
+ "orientation": "w",
+ "depth": 10,
+ "mode": "win",
+ "session_id": ""
}
```
----
+| Field | Default | Meaning |
+| --- | --- | --- |
+| `image_b64` | `null` | Encoded image; a base64 data URL is also accepted. Decoded image limit: 6 MB. |
+| `fen` | `null` | Direct position input. When present, it takes precedence over the image. |
+| `setup_fen` | `null` | Exact position used to calibrate an image once. Later frames omit it and use the session's trusted position. |
+| `player_color` | `"w"` | The color receiving advice: `w` or `b`. |
+| `orientation` | `"auto"` | Color at the bottom of the captured board: `w`, `b`, or `auto`. Automatic inference is most useful at the standard opening setup. |
+| `side_to_move` | `null` | Optional `w` or `b` override when calibrating `setup_fen`; it does not rewrite an ordinary trusted FEN. |
+| `board_corners` | `null` | Four normalized `[x, y]` points in image order: top-left, top-right, bottom-right, bottom-left. |
+| `depth` | `10` | Integer from 4 through 16. Engine search also has a time budget. |
+| `mode` | `"win"` | `win` for stronger advice; `loss` for deliberately weaker choices. |
+| `session_id` | `"default"` | Unique identifier, 1–128 characters. Use a separate identifier for each camera session. |
-### `POST /api/analyze`
+Supply `image_b64` or `fen`. FEN strings have a maximum length of 128 characters and must describe a legal chess position. Piece types in a supplied FEN are authoritative: the detector can verify their colors and occupied squares, but cannot independently verify arbitrary physical piece identities.
-Main analysis endpoint.
+For a standard new game, the detector uses the standard piece arrangement when the observed starting occupancy matches. For an unknown midgame image, it returns `setup_required`; it does not invent a position. Subsequent frames match an unchanged position, one legal move, or two consecutive legal moves from the session's trusted position.
+
+### Move response
-**Request body (JSON):**
```json
{
- "image_b64": "string (base64 JPEG/PNG — no data URL prefix)",
- "player_color": "w | b",
- "depth": 10,
- "mode": "win | loss",
- "session_id": "string (unique per browser session)"
+ "status": "ok",
+ "fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
+ "turn": "w",
+ "move_uci": "e2e4",
+ "move_san": "e4",
+ "move_human": "Pawn to e4",
+ "confidence": 0.9,
+ "engine": "stockfish",
+ "approx_elo": 1900,
+ "board_image_b64": null,
+ "board_detected": true,
+ "board_locked": true,
+ "board_corners": [[0.1, 0.1], [0.9, 0.1], [0.9, 0.9], [0.1, 0.9]],
+ "orientation": "w",
+ "requires_setup": false,
+ "piece_count": 32,
+ "pieces_detected": true,
+ "overlay": {
+ "from_square": "e2",
+ "to_square": "e4",
+ "piece": "pawn",
+ "promotion": null,
+ "orientation": "w",
+ "from": [0.55, 0.75],
+ "to": [0.55, 0.55],
+ "from_polygon": [[0.5, 0.7], [0.6, 0.7], [0.6, 0.8], [0.5, 0.8]],
+ "to_polygon": [[0.5, 0.5], [0.6, 0.5], [0.6, 0.6], [0.5, 0.6]]
+ }
}
```
-**Response statuses and their meanings:**
+The move above illustrates the response format; the engine can select another legal opening move. `fen` describes the position **before** the suggested move. `turn` comes from that position rather than the player's selected color.
-#### `ok` — Move found
-```json
-{
- "status": "ok",
- "fen": "rnbqkbnr/.../8 w KQkq - 0 1",
- "turn": "w",
- "move_uci": "e2e4",
- "move_san": "e4",
- "move_human": "Move Pawn to e4",
- "confidence": 0.87,
- "approx_elo": 1900,
- "board_image_b64": ""
-}
-```
+All geometry uses the uploaded image coordinate system, normalized to `[0, 1]`. The frontend captures its complete camera image inside a square with letterboxing, and draws the returned geometry over that same square. `from` and `to` are projected square centers; the polygons are the projected square boundaries. When there is no image geometry, `overlay` can contain the square names without coordinate fields.
-Field notes:
-- `confidence` — 0.0 to 1.0. Board detection quality. Values below 0.45 are rejected server-side.
-- `approx_elo` — Approximate strength of the suggestion. Matches `depth-info` values.
-- `board_image_b64` — 480×480 PNG of the warped/detected board with a green arrow showing the recommended move. Can be null.
+`board_image_b64` remains `null` for compatibility; the client renders the overlay directly. `confidence` describes detector measurements, not a calibrated probability of piece-type recognition. `approx_elo` is a legacy rough estimate, not a measured rating, and is `null` for the Python fallback.
-#### `no_change` — Board hasn't moved
-```json
-{
- "status": "no_change",
- "message": "Board unchanged. Waiting for opponent's move.",
- "fen": "...",
- "confidence": 0.91
-}
-```
-Frontend should display a waiting message and not call Stockfish.
+### Response statuses
-#### `opponent_turn` — Board changed but it's not your move
-```json
-{
- "status": "opponent_turn",
- "message": "Opponent's turn detected. Waiting...",
- "fen": "...",
- "confidence": 0.88
-}
-```
+| Status | Meaning and client behavior |
+| --- | --- |
+| `ok` | Legal move found. Display its text and overlay. |
+| `no_change` | Cached advice for the unchanged chess state and analysis settings. The full move remains in the response. Keep displaying it and use the current frame's geometry. |
+| `opponent_turn` | Trusted position is the opponent's turn. Clear the move arrow and keep scanning. |
+| `setup_required` | Board geometry exists, but piece identities need calibration. Offer standard starting setup or an exact FEN. |
+| `position_uncertain` | No unique legal tracked position matches the frame. Clear the arrow and request a steady, unobstructed board or position confirmation. |
+| `detection_error` | No reliable board or readable image was found. Clear the arrow and keep scanning. |
+| `invalid_fen` | Illegal or malformed supplied position. Correct its pieces, side to move, and state fields. HTTP 400. |
+| `rate_limited` | Requests are too close together. HTTP 429; observe `Retry-After` and the `retry_after` JSON field. |
+| `game_over` | Checkmate, stalemate, or another automatic game-ending condition. No move is returned. |
+| `engine_error` | Analysis failed. HTTP 503; retry the same position. Failed results do not poison the move cache. |
-#### `detection_error` — Board could not be reliably detected
-```json
-{
- "status": "detection_error",
- "message": "Board not detected. Please ensure the full board is visible and well-lit.",
- "confidence": 0.22
-}
-```
-Frontend should show the message and request the user reposition the camera.
+Detected geometry can be returned even when the position needs setup. `board_locked` requires both a detected board and detected pieces. An empty checkerboard does not produce a move.
-#### `rate_limited` — Too many requests per session
-```json
-{
- "status": "rate_limited",
- "message": "Analysing too fast. Slow down."
-}
-```
-HTTP 429. Frontend should back off.
+The cache includes piece placement, turn, castling rights, en passant state, the halfmove clock, player color, depth, and mode. Changing those settings triggers fresh advice. Camera tracking advances only from a validated position, and the engine result is checked against its legal moves.
+
+## `POST /api/analyze-fen`
+
+Evaluates a legal FEN directly without camera detection or a tracking session:
-#### `game_over` — No legal moves in position
```json
{
- "status": "game_over",
- "message": "Game over or no legal moves."
+ "fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
+ "depth": 10,
+ "mode": "win"
}
```
----
-
-### `POST /api/reset-session`
+The endpoint returns `ok`, `game_over`, `invalid_fen`, or `engine_error` and the corresponding move fields. It uses the side to move from the FEN. Optional `player_color` is accepted for compatibility and does not change that side. Confidence is `1.0` for supplied-position input; it is not a camera recognition score.
-Clears the FEN cache and rate-limit timer for a session.
-Call this when the user presses "Start Analysis".
+## `POST /api/reset-session?session_id=...`
-**Query param:** `session_id` (string)
+Clears the trusted position, cached result, and request timer for one session:
-**Response:**
```json
-{ "status": "reset", "session_id": "abc123" }
+{"status": "reset", "session_id": "camera-session"}
```
----
+The frontend can also begin a new game by creating a new session identifier. Sessions are kept in process memory, expire after 30 minutes of inactivity, and are lost when the backend restarts.
+
+## `GET /api/depth-info`
+
+Returns the legacy `depths` list with entries containing `depth` and `approx_elo`, plus a note that the estimates are not official ratings. The frontend presents depth as Quick, Balanced, or Deeper rather than promising an Elo rating.
+
+## HTTP errors
-## Error codes
+| Code | Meaning |
+| --- | --- |
+| 400 | Missing input, invalid base64, or illegal FEN. |
+| 413 | Decoded image exceeds 6 MB. |
+| 422 | Request field validation failed, such as invalid color, depth, or corner coordinates. |
+| 429 | Per-session request interval reached. |
+| 503 | Engine unavailable or all tracking-session slots busy. |
-| HTTP Code | Meaning |
-|---|---|
-| 400 | Invalid base64 image data |
-| 429 | Rate limited (min 1s between requests per session) |
-| 500 | Stockfish engine error |
+Read `message` for structured status errors or `detail` for FastAPI input errors. Do not reuse a stale arrow after an uncertain position or failed analysis.
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md
index d6b6bc9..af008fc 100644
--- a/docs/PERFORMANCE.md
+++ b/docs/PERFORMANCE.md
@@ -1,82 +1,58 @@
-# Performance Optimization Notes
+# Performance and operating limits
-## Image Pipeline
+The application favors prompt, bounded analysis and reliable state transitions. These notes describe implementation choices, not measured guarantees for a particular phone, network, board, or Railway plan.
-### Resolution choice: 480×480
-- Phone camera native: ~1920×1080 (≈4MB JPEG raw)
-- After resize to 480×480: ≈30-70KB JPEG at quality 0.82
-- Bandwidth savings: ~97% reduction
-- Board detection accuracy: No meaningful loss at 480px — chess squares are 60px each, plenty for colour classification.
+## Camera and network
-### JPEG quality 0.82
-- Quality 0.90+ → no accuracy gain, +40% file size
-- Quality 0.70 → noticeable artifacts in square boundaries, reduces detection accuracy
-- 0.82 is the sweet spot for phone camera over 4G
+The frontend captures a 720-by-720 JPEG at quality `0.9`. The complete native camera frame is scaled to fit and letterboxed, so a landscape or portrait source keeps all visible board corners. The square view and captured image use the same alignment.
----
+Camera scans are scheduled after the preceding request completes, with a 1.25-second interval. This prevents overlapping requests from building a backlog. Requests time out after 15 seconds, and a generation check discards responses from an old camera, photo, or settings state.
-## Stockfish
+The previous partial-image hash shortcut has been removed. Hashing a JPEG prefix can miss changed squares; every scheduled frame now reaches detection. An unchanged validated position still avoids an engine search through the server's result cache.
-### Persistent process
-- Without persistence: each request spawns a new process = 200-400ms overhead + CPU spike
-- With persistence: process kept alive, reused = 0ms spawn overhead
-- Lock used: `threading.Lock` guards concurrent access (FastAPI uses thread pool for sync code)
+Scanning pauses when the tab is hidden. Camera tracks are stopped when the user stops the camera or leaves the page. Payload size and elapsed time depend on image content and network conditions; there is no fixed bandwidth-per-move guarantee.
-### Hash/RAM settings (Railway free tier safe)
-- `Hash: 64MB` — transposition table. 256MB would be faster but risks OOM on Railway Starter ($5/mo).
-- `Threads: 2` — Railway Starter has 2 vCPUs. Setting higher has no benefit.
+## Vision
----
+The detector limits incoming images to a maximum dimension of 960 pixels and warps a verified board to 480-by-480 for square measurements. It checks an 8-by-8 alternating pattern before accepting a candidate rectangle and uses adaptive foreground/color measurements for occupancy.
-## Board Detection
+This pipeline has no learned piece-type model. Its valid operating path is:
-### Duplicate frame skip
-- SHA-1 hash of the first 2KB of the base64 image
-- If hash matches last frame, skip the entire detection + Stockfish pipeline
-- Eliminates ~80% of redundant work during static positions
+1. Calibrate the standard starting arrangement or an exact supplied FEN.
+2. Measure occupied squares and piece colors in the next frame.
+3. Match an unchanged position, one legal move, or two consecutive legal moves.
+4. Keep the position uncommitted when no unique match exists.
-### FEN cache
-- Full FEN comparison (board part only, ignoring clocks)
-- Prevents Stockfish calls when the board hasn't changed between frames
+Clear overhead views and visible square backgrounds work best. Glare, shadows, similar piece and board colors, hands over squares, partial boards, and missed move sequences can prevent a unique result. Different promotions can have the same occupancy and require explicit position confirmation.
----
+Automatic starting calibration assumes that a matching starting occupancy contains the normal starting piece arrangement. Same-color piece types cannot be distinguished from occupancy alone.
-## Network (4G India)
+## Chess engine
-- Poll interval: 2500ms — fast enough to catch moves, slow enough not to waste data
-- Per-frame upload: ~40-60KB JPEG
-- Per-frame download: ~25KB (JSON with base64 board image)
-- Total per move: ~100KB — negligible on 4G
+Stockfish is kept in a persistent UCI process with one thread and a 32 MB hash table. A lock serializes commands to that process, while FastAPI runs detector and engine work in a thread pool so health and unrelated API requests can proceed.
----
+Stockfish search uses both the selected depth and a 350 ms search budget. Weaker mode can perform an additional short candidate analysis. Process startup, UCI communication, detection, queueing, and network time are additional overhead; the search budget is not a whole-request latency guarantee.
-## Railway resource usage (estimated)
+When Stockfish cannot run, the Python evaluator performs a shallower search with a 300 ms target budget and returns legal advice. Responses label this fallback and omit an Elo estimate. Its recommendations should not be treated as Stockfish strength.
-| Resource | Idle | During analysis |
-|---|---|---|
-| CPU | ~1% | ~15-25% |
-| RAM | ~80MB | ~120MB |
-| Network | 0 | ~100KB/move |
+## Sessions and caching
-Fits comfortably in Railway Starter plan ($5/mo).
+The server caches successful advice using the chess state that affects legal moves: piece placement, side to move, castling rights, and en passant state, together with player color, depth, and mode. An unchanged position returns the complete cached suggestion and recalculated geometry for the current frame.
----
+Failed engine calls do not store a successful-result cache entry. The validated camera position remains available so the next frame can retry it. Invalid or unclear detections cannot overwrite the trusted position.
-## Future optimizations
+Each session serializes its requests. Session state is in memory, with up to 512 sessions and a 30-minute inactivity expiry. A backend restart clears it. Multiple server processes or replicas do not share that state; keep a camera session on one backend instance unless shared storage is added.
-1. **WebSocket instead of HTTP polling**
- - Eliminates HTTP handshake overhead (~20ms saved per frame)
- - Use if latency becomes noticeable in fast bullet games
+The default minimum request interval is 0.5 seconds per session and can be changed with `MIN_INTERVAL_SEC`. The frontend's normal scan interval already exceeds this default.
-2. **YOLOv8 piece detection**
- - Would improve piece-type classification (currently all pieces shown as pawns in FEN)
- - Add `ultralytics` to requirements, download `yolov8n-chess.pt` (~6MB)
- - Trade-off: +100ms inference on CPU, +200MB RAM
+## Validation
-3. **Frontend PWA**
- - Add `manifest.json` and service worker for home screen install on Android
- - Enables offline caching of static assets
+Run the detector, engine, and API regressions together:
-4. **Rate limit tuning**
- - Current: 1s minimum between requests per session
- - Reduce to 0.5s for faster capture during fast games
+```powershell
+& .venv\Scripts\python.exe -m pytest backend/tests -q -p no:cacheprovider
+npm test
+npm run test:browser
+```
+
+Camera geometry tests and synthetic-board regressions verify expected transformations and state changes. They do not establish recognition accuracy across arbitrary physical chess sets. Evaluate real phone-camera captures from the intended board and lighting before making accuracy or latency claims.
diff --git a/docs/README.md b/docs/README.md
index bf0bc14..744a50e 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -1,238 +1,83 @@
-# Chess Vision Coach
+# Setup and camera workflow
-A lightweight web-based chess move suggester powered by Stockfish + OpenCV.
-Point your phone camera at the board — get your next move instantly.
+## How the app works
----
+The frontend captures the complete camera image into a square canvas with letterboxing rather than cropping away board corners. The backend detects the board quadrilateral, verifies its alternating 8-by-8 pattern, and measures piece color and occupied squares. The returned corners and move coordinates are normalized to that same captured image.
-## Architecture Decisions
+The frontend uses a perspective transform to draw the move arrow over the live camera or uploaded photo. It does not open a separate board-overlay window.
-### Why Cloudflare Pages (not GitHub Pages)?
+Piece identity comes from a known position: either the normal opening setup or an exact FEN supplied by the user. Legal move matching then preserves kings, queens, other piece types, side to move, castling rights, and en passant information. The detector never repairs an unreadable image by adding kings, changing pieces to queens, or deleting attacking pieces.
-| Feature | GitHub Pages | Cloudflare Pages |
-|---|---|---|
-| HTTPS | ✓ | ✓ |
-| Camera API (requires HTTPS) | ✓ | ✓ |
-| Edge CDN | Basic | Global PoPs (faster in India) |
-| Custom headers (Permissions-Policy) | ✗ | ✓ (via `_headers`) |
-| Deploy from CLI | Extra setup | `wrangler pages deploy` |
+## Start a new game
-**Chosen: Cloudflare Pages** — custom headers let us set `Permissions-Policy: camera=*`
-explicitly, which avoids camera permission issues on some Android browsers.
-GitHub Pages works too if you prefer it (just push frontend/ to gh-pages branch).
+1. Arrange the pieces in their normal starting positions.
+2. Select your playing color and the color at the bottom of the camera view.
+3. Select **Start camera** and allow camera access in the browser.
+4. Keep all 64 squares visible, preferably from overhead with even light.
+5. Once the board is locked, follow the arrow and the move written below the camera view.
----
+After you move, the app watches for your opponent's reply. An unchanged board retains the current suggestion; a detected opponent turn clears it. Keep hands clear while a new position is being read.
-### Why OpenCV (not YOLOv8)?
+## Analyze an existing game
-| | OpenCV | YOLOv8 |
-|---|---|---|
-| Model size | 0 MB | ~50-200 MB |
-| Inference time | ~20-40ms | ~100-200ms (CPU) |
-| GPU required | No | No (but much slower) |
-| Accuracy (overhead angle, stable board) | Good | Excellent |
-| Railway RAM usage | Low | High |
+Open **Position & preferences**, enter the exact current FEN, choose the side to move, and select **Use for camera** while the camera or photo is visible. The backend checks that the observed piece colors and occupancy match that setup before starting tracking. Piece types cannot be verified from color and occupancy alone, so the FEN must describe the real board accurately.
-**Chosen: OpenCV** for this use-case (stable overhead phone camera, standard board).
-YOLOv8 would be the right choice if: boards are partially visible, taken at odd angles,
-or pieces are exotic 3D sets. The hybrid approach (OpenCV for board detection, YOLO
-for piece classification) would be the ideal future upgrade.
+**Analyze FEN** evaluates a position directly and displays an example board in the same square frame. **Try a demo** provides a starting-position example without camera access.
----
+The vision pipeline does not independently identify arbitrary midgame pieces. It needs calibration when joining a game midway, after more than two moves are missed, or when several legal positions have identical observed occupancy, such as different promotion choices.
-## Project Structure
+## Board alignment
-```
-chess-vision-coach/
-├── frontend/
-│ ├── index.html # Single-page UI
-│ ├── style.css # Dark theme, Space Grotesk font
-│ ├── app.js # Camera capture, API calls, UI logic
-│ └── _headers # Cloudflare Pages HTTP headers
-│
-├── backend/
-│ ├── main.py # FastAPI app, lifespan startup
-│ ├── Procfile # Railway process definition
-│ ├── nixpacks.toml # Installs stockfish binary on Railway
-│ ├── requirements.txt
-│ ├── routers/
-│ │ └── analysis.py # POST /api/analyze, GET /api/depth-info
-│ └── services/
-│ ├── stockfish_service.py # Persistent Stockfish wrapper
-│ └── board_detector.py # OpenCV board + piece detection
-│
-├── docs/
-│ ├── README.md # ← you are here
-│ ├── API.md # Full API reference
-│ └── PERFORMANCE.md # Optimization notes
-│
-└── models/ # Empty — reserved for future YOLO weights
-```
-
----
+Automatic alignment verifies the board pattern instead of treating any rectangle as a chessboard. When automatic alignment is difficult, select **Set corners** and tap the board's top-left, top-right, bottom-right, then bottom-left corner. Crossed or degenerate corners are rejected. **Unlock** clears the calibration and scans again.
-## Local Setup
+Orientation describes the camera view, independently of whose turn it is or which color you play. Turning the camera to the opposite side requires changing the orientation and recalibrating. A partial board, glare, low contrast, or a hand over pieces can cause the app to withhold a suggestion until a readable frame returns.
-### Prerequisites
+## Local development
-- Python 3.11+
-- Stockfish installed locally
- - **Ubuntu/Debian:** `sudo apt install stockfish`
- - **macOS:** `brew install stockfish`
- - **Windows:** Download from https://stockfishchess.org/download/
+From the repository root on Windows:
-### Backend
-
-```bash
-cd backend
+```powershell
python -m venv .venv
-source .venv/bin/activate # Windows: .venv\Scripts\activate
-pip install -r requirements.txt
-
-# If Stockfish is not at /usr/games/stockfish, set the path:
-export STOCKFISH_PATH=/path/to/stockfish
-
-uvicorn main:app --reload --port 8000
+& .venv\Scripts\python.exe -m pip install -r backend/requirements.txt
+& .venv\Scripts\python.exe -m uvicorn main:app --app-dir backend --reload --host 127.0.0.1 --port 8080
```
-API will be available at: http://localhost:8000
-Docs at: http://localhost:8000/docs
-
-### Frontend
-
-```bash
-# No build step needed — pure HTML/CSS/JS
-
-# Option 1: Python simple server
-cd frontend
-python -m http.server 5500
-
-# Option 2: VS Code Live Server extension
-
-# Option 3: npx serve
-npx serve frontend/
-```
-
-**Important:** Edit `frontend/app.js` line 12:
-```js
-const API_BASE = "http://localhost:8000"; // for local dev
+On macOS or Linux, use `.venv/bin/python` in place of `.venv\Scripts\python.exe`. Open `http://127.0.0.1:8080` for the app and `/docs` for interactive API documentation.
+
+Install Stockfish through your system package manager or [the official download page](https://stockfishchess.org/download/). Set `STOCKFISH_PATH` if the executable is not discoverable. Health and move responses distinguish Stockfish from the weaker Python fallback.
+
+The frontend is plain HTML, CSS, and JavaScript modules. No frontend compilation is needed. Serve it through FastAPI to use the local API automatically. If a separate frontend server runs on another port, use its URL with `?api=http://127.0.0.1:8080` or select the API in **Connection settings**.
+
+## Project layout
+
+```text
+frontend/
+ index.html Mobile-first camera UI
+ style.css Responsive styles
+ app.js Camera, requests, tracking UI, and overlay rendering
+ overlay.js Perspective and square-coordinate helpers
+ tests/ Frontend regression tests
+ _headers Headers for separate static hosting
+backend/
+ main.py FastAPI startup, health, and static frontend serving
+ routers/analysis.py
+ services/board_detector.py
+ services/stockfish_service.py
+ tests/
+ requirements.txt
+Dockerfile Root deployment: backend and frontend together
+railway.json Railway build and health-check configuration
```
----
-
-## Railway Deployment (Backend)
-
-1. **Create Railway project**
- ```
- railway login
- railway new chess-vision-coach
- ```
-
-2. **Link backend folder**
- ```
- cd backend
- railway link
- ```
-
-3. **Set environment variables** (in Railway dashboard or CLI)
- ```
- STOCKFISH_PATH=/run/current-system/sw/bin/stockfish
- PORT=8000
- ```
- > `nixpacks.toml` automatically installs stockfish via Nix packages.
- > After first deploy, check the exact binary path in Railway logs and update STOCKFISH_PATH if needed.
-
-4. **Deploy**
- ```
- railway up
- ```
-
-5. **Get your Railway URL**
- Railway will assign: `https://your-app-name.up.railway.app`
+## Deployment and checks
-6. **Update frontend** — edit `frontend/app.js`:
- ```js
- const API_BASE = "https://your-app-name.up.railway.app";
- ```
+See [Railway deployment](../backend/DEPLOY.md) for the recommended single-service deployment. A separate static host can publish `frontend/` with no build command and select the Railway API through connection settings.
----
-
-## Cloudflare Pages Deployment (Frontend)
-
-1. **Install Wrangler**
- ```
- npm install -g wrangler
- wrangler login
- ```
-
-2. **Deploy**
- ```
- cd frontend
- wrangler pages deploy . --project-name chess-vision-coach
- ```
-
-3. Your app is live at: `https://chess-vision-coach.pages.dev`
-
-**Alternative — GitHub auto-deploy:**
-1. Push repo to GitHub.
-2. Go to Cloudflare Pages → Create Project → Connect to Git.
-3. Set build output directory: `frontend/`
-4. Leave build command empty.
-
----
-
-## Environment Variables
-
-| Variable | Default | Description |
-|---|---|---|
-| `STOCKFISH_PATH` | `/usr/games/stockfish` | Absolute path to the Stockfish binary |
-| `PORT` | `8000` | HTTP port (Railway sets this automatically) |
-
----
-
-## API Reference
-
-See `docs/API.md` for full details.
-
-### Quick reference
-
-**POST `/api/analyze`**
-```json
-{
- "image_b64": "",
- "player_color": "w",
- "depth": 10,
- "mode": "win",
- "session_id": "abc123"
-}
-```
-
-**Response (success):**
-```json
-{
- "status": "ok",
- "fen": "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1",
- "turn": "w",
- "move_uci": "e2e4",
- "move_san": "e4",
- "move_human": "Move Pawn to e4",
- "confidence": 0.87,
- "approx_elo": 1900,
- "board_image_b64": ""
-}
+```powershell
+& .venv\Scripts\python.exe -m pytest backend/tests -q -p no:cacheprovider
+npm install
+npm test
+npm run test:browser
```
-**Other statuses:** `no_change` · `opponent_turn` · `detection_error` · `rate_limited` · `game_over`
-
----
-
-## Performance Notes
-
-See `docs/PERFORMANCE.md` for full details.
-
-- **Frame capture:** 480×480 px JPEG at quality 0.82 ≈ 30-60 KB per upload.
-- **Poll interval:** 2500ms (one frame every 2.5 seconds) is plenty for over-the-board play.
-- **Duplicate frame skip:** SHA-1 hash of first 2KB avoids sending identical frames.
-- **Persistent Stockfish:** Engine started once at boot; each request reuses the same process.
-- **FEN cache:** Board changes detected before calling Stockfish — zero engine calls for unchanged positions.
-- **OpenCV no-model:** No model weights to load; board detection is instant CPU math.
+See [API reference](API.md) for request and response details and [performance notes](PERFORMANCE.md) for timing and tracking limits.