premoves (server-side, survive closed tab), provider outages pause games instead of aborting, turn watchdog, lock race fix, overthinking experiment harness
This commit is contained in:
@@ -24,5 +24,6 @@ export const api = {
|
||||
get: <T>(p: string) => req<T>('GET', p),
|
||||
post: <T>(p: string, b?: unknown) => req<T>('POST', p, b ?? {}),
|
||||
patch: <T>(p: string, b?: unknown) => req<T>('PATCH', p, b ?? {}),
|
||||
put: <T>(p: string, b?: unknown) => req<T>('PUT', p, b ?? {}),
|
||||
del: <T>(p: string) => req<T>('DELETE', p)
|
||||
};
|
||||
|
||||
@@ -11,7 +11,10 @@
|
||||
orientation = 'white',
|
||||
arrow = null,
|
||||
movable = null,
|
||||
onmove
|
||||
onmove,
|
||||
premove = null,
|
||||
onpremove,
|
||||
onpremoveunset
|
||||
}: {
|
||||
fen: string;
|
||||
lastMove?: [string, string];
|
||||
@@ -21,10 +24,18 @@
|
||||
/** when set, the given color may move: dests = legal destinations per square */
|
||||
movable?: { color: 'white' | 'black'; dests: Map<string, string[]> } | null;
|
||||
onmove?: (from: string, to: string) => void;
|
||||
/** queued premove to display (owned by the page; null = none) */
|
||||
premove?: [string, string] | null;
|
||||
/** user dragged a piece while it was the opponent's turn (requires movable.color = my side) */
|
||||
onpremove?: (from: string, to: string) => void;
|
||||
onpremoveunset?: () => void;
|
||||
} = $props();
|
||||
|
||||
let el: HTMLDivElement;
|
||||
let api: Api | undefined;
|
||||
let lastFen = '';
|
||||
// chessground fires premove callbacks async (setTimeout) \u2014 count our own cancels to swallow them
|
||||
let silentUnsets = 0;
|
||||
|
||||
onMount(() => {
|
||||
api = Chessground(el, {
|
||||
@@ -35,7 +46,18 @@
|
||||
animation: { enabled: true, duration: 220 },
|
||||
highlight: { lastMove: true, check: true },
|
||||
movable: { free: false, color: undefined, showDests: true, events: { after: (o, d) => onmove?.(o, d) } },
|
||||
premovable: { enabled: false },
|
||||
premovable: {
|
||||
enabled: true,
|
||||
showDests: true,
|
||||
castle: true,
|
||||
events: {
|
||||
set: (o, d) => onpremove?.(o, d),
|
||||
unset: () => {
|
||||
if (silentUnsets > 0) silentUnsets--;
|
||||
else onpremoveunset?.();
|
||||
}
|
||||
}
|
||||
},
|
||||
draggable: { enabled: true, showGhost: true },
|
||||
drawable: {
|
||||
enabled: true,
|
||||
@@ -65,6 +87,18 @@
|
||||
: { color: undefined, dests: new Map() },
|
||||
drawable: { autoShapes: arrow ? [{ orig: arrow[0] as Key, dest: arrow[1] as Key, brush: 'best' }] : [] }
|
||||
});
|
||||
const fenChanged = fen !== lastFen;
|
||||
lastFen = fen;
|
||||
const cur = api.state.premovable.current;
|
||||
if (premove) {
|
||||
if (!cur || cur[0] !== premove[0] || cur[1] !== premove[1]) {
|
||||
api.state.premovable.current = premove as Key[] as [Key, Key];
|
||||
api.state.dom.redraw();
|
||||
}
|
||||
} else if (cur && fenChanged) {
|
||||
silentUnsets++;
|
||||
api.cancelPremove();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
{#if m}
|
||||
<div class="cell" class:cur={current === m.ply} class:open={expanded === m.ply}>
|
||||
<button class="mv" onclick={() => onselect(m.ply)} title={m.classification ? CLS_LABEL[m.classification] : ''}>
|
||||
<span class="san" class:illegal={m.illegal}>{m.san ?? m.uci}</span>{#if m.classification && NAG[m.classification]}<span class="nag {m.classification}">{NAG[m.classification]}</span>{/if}
|
||||
<span class="san" class:illegal={m.illegal}>{m.san ?? m.uci}</span>{#if m.premoved}<span class="pm" title="Сыграно премувом — сразу после хода соперника">⚡</span>{/if}{#if m.classification && NAG[m.classification]}<span class="nag {m.classification}">{NAG[m.classification]}</span>{/if}
|
||||
{#if m.offeredDraw}<span class="draw" title="Предложил ничью">½?</span>{/if}
|
||||
</button>
|
||||
<span class="ev mono">{evalLabel(m.eval)}</span>
|
||||
@@ -148,6 +148,10 @@
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
.pm {
|
||||
font-size: 0.8em;
|
||||
margin-left: 2px;
|
||||
}
|
||||
.san.illegal {
|
||||
text-decoration: line-through wavy var(--danger);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ export class GameView {
|
||||
turn = $state<LiveTurn | null>(null);
|
||||
predictions = $state<GameResponse['predictions']>({ counts: {}, mine: null });
|
||||
error = $state<string | null>(null);
|
||||
/** server dropped my premove (illegal after the opponent's reply) */
|
||||
stall = $state<GameResponse['stall']>(null);
|
||||
premoveDropped = $state<{ side: Side; uci: string; reason: string; at: number } | null>(null);
|
||||
private offs: (() => void)[] = [];
|
||||
|
||||
constructor(id: string) {
|
||||
@@ -31,6 +34,7 @@ export class GameView {
|
||||
this.moves = r.moves;
|
||||
this.turn = r.live ? { ...r.live, tools: [...r.live.tools] } : null;
|
||||
this.predictions = r.predictions;
|
||||
this.stall = r.stall ?? null;
|
||||
this.error = null;
|
||||
} catch (e) {
|
||||
this.error = (e as Error).message;
|
||||
@@ -51,6 +55,7 @@ export class GameView {
|
||||
const t = this.turn;
|
||||
switch (ev.type) {
|
||||
case 'turn_start':
|
||||
this.stall = null;
|
||||
this.turn = { ply: ev.ply, side: ev.side, startedAt: ev.at, thinking: '', text: '', tools: [] };
|
||||
break;
|
||||
case 'thinking_delta':
|
||||
@@ -68,6 +73,7 @@ export class GameView {
|
||||
break;
|
||||
}
|
||||
case 'move':
|
||||
this.stall = null;
|
||||
if (!this.moves.some((m) => m.ply === ev.move.ply)) this.moves.push(ev.move);
|
||||
if (this.game) {
|
||||
this.game.ply = ev.move.ply;
|
||||
@@ -87,6 +93,9 @@ export class GameView {
|
||||
}
|
||||
case 'turn_end':
|
||||
break;
|
||||
case 'premove_dropped':
|
||||
this.premoveDropped = { side: ev.side, uci: ev.uci, reason: ev.reason, at: Date.now() };
|
||||
break;
|
||||
case 'interview':
|
||||
if (this.game) this.game.interviews = { ...this.game.interviews, [ev.side]: ev.text };
|
||||
break;
|
||||
|
||||
@@ -60,6 +60,8 @@ export interface GameDetail extends GameSummary {
|
||||
interviews: { white?: string | null; black?: string | null };
|
||||
lastWords: { white?: string | null; black?: string | null };
|
||||
pendingDrawBy: Side | null;
|
||||
/** my own queued premove (only sent to the human who set it) */
|
||||
premove?: { uci: string; phrase: string | null } | null;
|
||||
createdBy: string | null;
|
||||
error: string | null;
|
||||
}
|
||||
@@ -77,6 +79,8 @@ export interface GameResponse {
|
||||
game: GameDetail;
|
||||
moves: MoveDTO[];
|
||||
live: LiveTurn | null;
|
||||
/** last attempt failed (provider outage) — game paused, retried automatically */
|
||||
stall?: { note: string; at: string; attempts: number } | null;
|
||||
predictions: { counts: Partial<Record<'white' | 'draw' | 'black', number>>; mine: 'white' | 'draw' | 'black' | null };
|
||||
}
|
||||
|
||||
|
||||
@@ -74,13 +74,72 @@
|
||||
|
||||
// ---- human move input
|
||||
const myTurn = $derived(!!mySide && g?.status === 'running' && view.sideToMove === mySide && atLive);
|
||||
// premoves: allowed while the AI opponent thinks (the server plays them the instant it replies)
|
||||
const canPremove = $derived(!!mySide && g?.status === 'running' && atLive && !myTurn && view.player(otherSide(mySide)).kind === 'ai');
|
||||
const dests = $derived.by(() => {
|
||||
if (canPremove) return { color: mySide!, dests: new Map<string, string[]>() };
|
||||
if (!myTurn) return null;
|
||||
const c = new Chess(g!.fen);
|
||||
const m = new Map<string, string[]>();
|
||||
for (const mv of c.moves({ verbose: true })) m.set(mv.from, [...(m.get(mv.from) ?? []), mv.to]);
|
||||
return { color: mySide!, dests: m };
|
||||
});
|
||||
/** my queued premove, pinned to the position (move count) it was made in */
|
||||
let pm = $state<{ at: number; from: string; to: string; phrase: string | null } | null>(null);
|
||||
$effect(() => {
|
||||
// adopt a premove the server still holds (after a reload) — once per REST snapshot
|
||||
const sp = g?.premove;
|
||||
if (!g || !sp) return;
|
||||
pm = { at: g.ply, from: sp.uci.slice(0, 2), to: sp.uci.slice(2, 4), phrase: sp.phrase };
|
||||
g.premove = null;
|
||||
});
|
||||
const premoveShown = $derived<[string, string] | null>(pm && pm.at === view.moves.length && canPremove ? [pm.from, pm.to] : null);
|
||||
async function setPremove(from: string, to: string) {
|
||||
moveErr = null;
|
||||
const piece = new Chess(g!.fen).get(from as any);
|
||||
const promo = piece?.type === 'p' && (to[1] === '8' || to[1] === '1') ? 'q' : '';
|
||||
const at = view.moves.length;
|
||||
const ph = phrase.trim() || null;
|
||||
pm = { at, from, to, phrase: ph };
|
||||
try {
|
||||
const r = await api.put<{ played: boolean }>(`/api/games/${view.id}/premove`, { move: from + to + promo, phrase: ph ?? undefined });
|
||||
if (ph) phrase = '';
|
||||
if (r.played) pm = null;
|
||||
} catch (e) {
|
||||
pm = null;
|
||||
moveErr = (e as Error).message;
|
||||
}
|
||||
}
|
||||
async function unsetPremove() {
|
||||
if (!pm) return;
|
||||
pm = null;
|
||||
await api.del(`/api/games/${view.id}/premove`).catch(() => {});
|
||||
}
|
||||
// ping when the AI finally replies (title + a short beep) — the opponent may think for minutes
|
||||
let wasMyTurn: boolean | null = null;
|
||||
$effect(() => {
|
||||
const now = myTurn;
|
||||
if (wasMyTurn === false && now) beep();
|
||||
wasMyTurn = now;
|
||||
});
|
||||
function beep() {
|
||||
try {
|
||||
const ctx = new AudioContext();
|
||||
const o = ctx.createOscillator();
|
||||
const gn = ctx.createGain();
|
||||
o.frequency.value = 660;
|
||||
gn.gain.setValueAtTime(0.0001, ctx.currentTime);
|
||||
gn.gain.exponentialRampToValueAtTime(0.15, ctx.currentTime + 0.02);
|
||||
gn.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.35);
|
||||
o.connect(gn).connect(ctx.destination);
|
||||
o.start();
|
||||
o.stop(ctx.currentTime + 0.4);
|
||||
o.onended = () => ctx.close();
|
||||
} catch {
|
||||
/* autoplay policy — ignore */
|
||||
}
|
||||
}
|
||||
const dropped = $derived(view.premoveDropped && view.premoveDropped.side === mySide ? view.premoveDropped : null);
|
||||
let phrase = $state('');
|
||||
let offerDraw = $state(false);
|
||||
let moveErr = $state<string | null>(null);
|
||||
@@ -134,7 +193,7 @@
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={key} />
|
||||
<svelte:head><title>{g ? `${g.status === 'running' ? 'LIVE · ' : ''}${playerTitle(g.white)} — ${playerTitle(g.black)} · AI·CHESS` : 'AI·CHESS'}</title></svelte:head>
|
||||
<svelte:head><title>{g ? `${myTurn ? '● Твой ход · ' : g.status === 'running' ? 'LIVE · ' : ''}${playerTitle(g.white)} — ${playerTitle(g.black)} · AI·CHESS` : 'AI·CHESS'}</title></svelte:head>
|
||||
|
||||
{#if view.error}
|
||||
<div class="error-box">{view.error}</div>
|
||||
@@ -199,6 +258,9 @@
|
||||
|
||||
<!-- ───── center ───── -->
|
||||
<section class="col-board">
|
||||
{#if g.status === 'running' && view.stall}
|
||||
<div class="notes mono hot stall">⏸ {view.stall.note} <span class="muted">· попыток: {view.stall.attempts}</span></div>
|
||||
{/if}
|
||||
{#if g.status === 'running' && atLive}
|
||||
<div class="notes mono" class:hot={repetitionHot}><span class="label">агент видит:</span> {ruleNotes.join(' · ')}</div>
|
||||
{:else if !atLive}
|
||||
@@ -215,7 +277,7 @@
|
||||
|
||||
<div class="board-row">
|
||||
<EvalBar ev={shownEval} {orientation} />
|
||||
<Board fen={pos.fen} lastMove={pos.lastMove} check={pos.check} {orientation} {arrow} movable={dests} onmove={humanMove} />
|
||||
<Board fen={pos.fen} lastMove={pos.lastMove} check={pos.check} {orientation} {arrow} movable={dests} onmove={humanMove} premove={premoveShown} onpremove={setPremove} onpremoveunset={unsetPremove} />
|
||||
</div>
|
||||
|
||||
<div class="controls">
|
||||
@@ -236,6 +298,15 @@
|
||||
<div class="panel play">
|
||||
<div class="panel-head">{myTurn ? 'Твой ход' : 'Ход соперника'} <span class="spacer"></span><small>ты играешь {mySide === 'white' ? 'белыми' : 'чёрными'}</small></div>
|
||||
<div class="panel-body stack">
|
||||
{#if premoveShown}
|
||||
<div class="premove mono">
|
||||
⚡ премув <b>{premoveShown[0]}–{premoveShown[1]}</b>{#if pm?.phrase} · с репликой{/if} — сыграется сразу после хода соперника, даже если закроешь вкладку
|
||||
<button class="btn sm" onclick={() => unsetPremove()}>отменить</button>
|
||||
</div>
|
||||
{:else if canPremove}
|
||||
<div class="hint muted">Пока соперник думает, можно сделать <b>премув</b>: перетащи фигуру — ход сыграется мгновенно после его ответа (если будет легален).</div>
|
||||
{/if}
|
||||
{#if dropped && myTurn}<div class="hint warn-text">Премув {dropped.uci.slice(0, 2)}–{dropped.uci.slice(2, 4)} не сработал: стал нелегальным после ответа соперника.</div>{/if}
|
||||
<input class="input" placeholder="Реплика сопернику (уйдёт вместе со следующим ходом)" maxlength="400" bind:value={phrase} />
|
||||
<div class="row wrap-row">
|
||||
<label class="row"><input type="checkbox" bind:checked={offerDraw} /> предложить ничью с ходом</label>
|
||||
@@ -458,6 +529,26 @@
|
||||
.nav button:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
.premove {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
font-size: 12px;
|
||||
padding: 8px 10px;
|
||||
border: 1px dashed var(--accent);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
.premove .btn {
|
||||
margin-left: auto;
|
||||
}
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.warn-text {
|
||||
color: var(--accent-text, var(--accent));
|
||||
}
|
||||
.wrap-row {
|
||||
flex-wrap: wrap;
|
||||
font-size: 13px;
|
||||
|
||||
Reference in New Issue
Block a user