From ba43a8bdb20f4c50299c3e352b494d3773412636 Mon Sep 17 00:00:00 2001 From: Ashton Anderson Date: Wed, 2 Dec 2026 20:03:11 -0500 Subject: [PATCH] Every game against Maia is held by the server: the browser-run path is removed The server has held every player's games since the share reached 100%, but the site still fell back to running a game in the browser (start_game, get_move, submit_move) when the account request hadn't answered within four seconds, or when a browser had opted out in localStorage. About 30 play games a day still went that way, from some 20 accounts. Now a play page always creates its game on the server (the request gets the guest cookie by itself if it is missing), and the code that ran a game in the browser is gone: - useServerGames, the build and per-browser switches, and `serverGames` on the account - start_game (also the setup dialog's early request) and submit_move calls, and the retry wrapper for Maia's move in a game - in the play controllers: asking for Maia's moves, the local clock flag, rules and resignation endings, local takebacks and extra time, the game log - unlimited and practice games kept in localStorage to be continued (the server keeps every unfinished game), and the question before starting a game from a link (the server's game-in-progress question covers it) get_move stays: the opening drills use it. Co-Authored-By: Claude Fable 5.2 --- src/api/auth.test.ts | 13 +- src/api/auth.ts | 2 - src/api/play.test.ts | 104 ------ src/api/play.ts | 158 +-------- src/components/Common/PlaySetupModal.tsx | 82 +---- .../Play/StartGameConfirmModal.test.tsx | 41 --- src/components/Play/StartGameConfirmModal.tsx | 57 ---- src/components/Play/index.ts | 1 - src/contexts/PlayControllerContext.ts | 2 - src/hooks/useGameInProgressQuestion.ts | 2 +- .../usePlayController/useGameLog.test.ts | 128 ------- src/hooks/usePlayController/useGameLog.ts | 88 ----- .../useHandBrainController.ts | 273 ++------------- .../usePlayController.test.ts | 74 ++--- .../usePlayController/usePlayController.ts | 176 +--------- src/hooks/usePlayController/useServerTurns.ts | 5 +- .../useVsMaiaController.server.test.ts | 2 +- .../usePlayController/useVsMaiaController.ts | 314 ++---------------- src/hooks/useServerGames.ts | 22 -- src/hooks/useStartConfirmation.test.ts | 31 -- src/hooks/useStartConfirmation.ts | 26 -- src/lib/serverGames.test.ts | 22 -- src/lib/serverGames.ts | 49 +-- src/lib/unfinishedGame.test.ts | 68 ---- src/lib/unfinishedGame.ts | 78 +---- src/pages/play/hb.tsx | 111 +------ src/pages/play/maia.tsx | 158 ++------- src/types/auth.ts | 3 - 28 files changed, 167 insertions(+), 1923 deletions(-) delete mode 100644 src/components/Play/StartGameConfirmModal.test.tsx delete mode 100644 src/components/Play/StartGameConfirmModal.tsx delete mode 100644 src/hooks/usePlayController/useGameLog.test.ts delete mode 100644 src/hooks/usePlayController/useGameLog.ts delete mode 100644 src/hooks/useServerGames.ts delete mode 100644 src/hooks/useStartConfirmation.test.ts delete mode 100644 src/hooks/useStartConfirmation.ts delete mode 100644 src/lib/unfinishedGame.test.ts diff --git a/src/api/auth.test.ts b/src/api/auth.test.ts index 075ae34b..381389f4 100644 --- a/src/api/auth.test.ts +++ b/src/api/auth.test.ts @@ -7,21 +7,18 @@ jest.mock('./guest', () => ({ const { requestAccount } = jest.requireMock('./guest') describe('the account request', () => { - it("says whether the player's games are held by the server", async () => { + it("gives the account's ids and name", async () => { requestAccount.mockResolvedValue({ client_id: 'c1', display_name: 'Guest', lichess_id: null, + // Still sent by the backend; no longer read. server_games: true, }) - expect(await fetchAccount()).toMatchObject({ + expect(await fetchAccount()).toEqual({ clientId: 'c1', - serverGames: true, + displayName: 'Guest', + lichessId: null, }) }) - - it('takes an older answer, without the field, as no', async () => { - requestAccount.mockResolvedValue({ client_id: 'c1', display_name: 'Guest' }) - expect((await fetchAccount()).serverGames).toBe(false) - }) }) diff --git a/src/api/auth.ts b/src/api/auth.ts index e531d52c..de458254 100644 --- a/src/api/auth.ts +++ b/src/api/auth.ts @@ -11,8 +11,6 @@ const parseAccountInfo = (data: { [x: string]: string }) => { clientId: clientId, displayName: displayName, lichessId: lichessId, - // A boolean in the answer, whatever the type above says. - serverGames: (data['server_games'] as unknown) === true, } } diff --git a/src/api/play.test.ts b/src/api/play.test.ts index ccc9e647..4868800b 100644 --- a/src/api/play.test.ts +++ b/src/api/play.test.ts @@ -3,8 +3,6 @@ import { fetchPlayPlayerStats, MoveRequestError, retryUnlessRejected, - startGame, - startGameWithRetry, } from './play' const respond = (status: number, body: unknown) => { @@ -65,105 +63,3 @@ describe('fetchGameMove', () => { expect(retryUnlessRejected(new TypeError('Failed to fetch'))).toBe(true) }) }) - -const reply = (status: number, body: unknown) => - Promise.resolve({ - ok: status >= 200 && status < 300, - status, - json: () => Promise.resolve(body), - }) - -describe('startGame', () => { - const start = (retried = false) => - (retried ? startGameWithRetry : startGame)( - 'white', - 'maia_kdd_600', - 'play', - true, - 'unlimited', - ) - - it("returns the new game's id", async () => { - respond(200, { game_id: 'abc', opponent_elo: 1500 }) - await expect(start()).resolves.toEqual({ - gameId: 'abc', - opponentElo: 1500, - }) - }) - - it('throws, with the status, when the server fails', async () => { - respond(502, null) - const error = await start().catch((e) => e) - expect(error).toBeInstanceOf(MoveRequestError) - expect(error.status).toBe(502) - }) - - it('retries a dropped connection until the game starts', async () => { - const fetchMock = jest - .fn() - .mockRejectedValueOnce(new TypeError('Load failed')) - .mockReturnValueOnce(reply(503, null)) - .mockReturnValueOnce(reply(200, { game_id: 'abc', opponent_elo: 1500 })) - global.fetch = fetchMock as unknown as typeof fetch - - await expect(start(true)).resolves.toMatchObject({ gameId: 'abc' }) - expect(fetchMock).toHaveBeenCalledTimes(3) - }) - - it('does not retry a request the server rejected', async () => { - // 401 twice: fetchAsGuest's retry after the account request, which - // answers 401 too (its body is not read). - const fetchMock = jest.fn().mockImplementation(() => reply(401, {})) - global.fetch = fetchMock as unknown as typeof fetch - - const error = await start(true).catch((e) => e) - expect(error).toBeInstanceOf(MoveRequestError) - expect(error.status).toBe(401) - // start_game, the account request, start_game again: once only. - expect(fetchMock).toHaveBeenCalledTimes(3) - }) -}) - -describe('fetchPlayPlayerStats', () => { - // play/get_player_stats (CSSLab/maia-platform-backend#293). - const STATS = { - play_games_played: 3, - hand_games_played: 40, - brain_games_played: 0, - play_won: 1, - play_drawn: 0, - hand_won: 22, - hand_drawn: 3, - brain_won: 0, - brain_drawn: 0, - play_elo: 1540, - hand_elo: 1610, - brain_elo: 1500, - } - - it('reads whether each rating is provisional', async () => { - respond(200, { - ...STATS, - play_provisional: true, - hand_provisional: false, - brain_provisional: true, - }) - expect(await fetchPlayPlayerStats()).toMatchObject({ - playElo: 1540, - playProvisional: true, - handElo: 1610, - handProvisional: false, - brainElo: 1500, - brainProvisional: true, - }) - }) - - it('takes a rating as settled when the backend does not say', async () => { - respond(200, STATS) - expect(await fetchPlayPlayerStats()).toMatchObject({ - playProvisional: false, - handProvisional: false, - brainProvisional: false, - }) - }) -}) diff --git a/src/api/play.ts b/src/api/play.ts index eed7f6eb..d2334700 100644 --- a/src/api/play.ts +++ b/src/api/play.ts @@ -1,7 +1,6 @@ import { backOff } from 'exponential-backoff' import { buildUrl } from './utils' import { fetchAsGuest } from './guest' -import { Color, TimeControl } from 'src/types' const normalizeOpeningBookFen = (fen: string) => { const parts = fen.trim().split(/\s+/) @@ -11,111 +10,6 @@ const normalizeOpeningBookFen = (fen: string) => { return fen.trim() } -export const startGame = async ( - playerColor: Color, - maiaVersion: string, - gameType: 'play' | 'hand' | 'brain', - sampleMoves: boolean, - timeControl: TimeControl, - maiaPartnerVersion: string | undefined = undefined, -) => { - const params: Record = maiaPartnerVersion - ? { - maia_name: maiaVersion, - maia_friendly_name: maiaPartnerVersion, - player_color: playerColor, - game_type: gameType, - sample_moves: sampleMoves.toString(), - time_control: timeControl, - } - : { - maia_name: maiaVersion, - player_color: playerColor, - game_type: gameType, - sample_moves: sampleMoves.toString(), - time_control: timeControl, - } - - const res = await fetchAsGuest( - buildUrl('play/start_game?' + new URLSearchParams(params)), - { - method: 'GET', - headers: { - Accept: 'application/json', - }, - }, - ) - - const data = await res.json().catch(() => null) - if (!res.ok || typeof data?.game_id !== 'string') { - // A 401 here: the guest cookie couldn't be set (see fetchAsGuest). - throw new MoveRequestError(res.status, `start_game: HTTP ${res.status}`) - } - - return { - gameId: data['game_id'] as string, - opponentElo: data['opponent_elo'] as number, - } -} - -/** - * startGame, retried a few times (a second or two in all) unless the server - * rejected the request: most failed starts fail at once, on phones, which is - * what a dropped connection looks like. Throws if it still fails. - */ -export const startGameWithRetry = (...args: Parameters) => - backOff(() => startGame(...args), { - jitter: 'full', - numOfAttempts: 4, - retry: retryUnlessRejected, - }) - -// A game against Maia started by the setup dialog as the visitor chose a -// side, so that start_game runs while /play/maia loads and renders rather -// than after. /play/maia takes it if its settings match, or starts its own. -let earlyStart: { - key: string - response: ReturnType -} | null = null - -export const startGameEarly = ( - playerColor: Color, - maiaVersion: string, - sampleMoves: boolean, - timeControl: TimeControl, -) => { - const response = startGame( - playerColor, - maiaVersion, - 'play', - sampleMoves, - timeControl, - ) - response.catch(() => undefined) - earlyStart = { - key: JSON.stringify([playerColor, maiaVersion, sampleMoves, timeControl]), - response, - } -} - -export const takeEarlyGame = ( - playerColor: Color, - maiaVersion: string, - sampleMoves: boolean, - timeControl: TimeControl, -) => { - const key = JSON.stringify([ - playerColor, - maiaVersion, - sampleMoves, - timeControl, - ]) - if (!earlyStart || earlyStart.key !== key) return null - const { response } = earlyStart - earlyStart = null - return response -} - export const fetchGameMove = async ( moves: string[], maiaVersion = 'maia_kdd_1900', @@ -161,7 +55,7 @@ export const fetchGameMove = async ( return body } -/** The server answered, but not with a move (or a new game). */ +/** The server answered, but not with what was asked for (a move, a game). */ export class MoveRequestError extends Error { constructor( readonly status: number, @@ -218,41 +112,6 @@ export const fetchOpeningBookMoves = async (fen: string) => { return res.json() } -export const logGameMove = async ( - gameId: string, - moves: string[], - moveTimes: number[], - gameOverState: 'not_over' | 'rules' | 'resign' | 'time', - gameType: 'play' | 'hand' | 'brain', - fen: string | undefined = undefined, - winner: string | undefined = undefined, - brainMoves: string[] = [], - // For a page being hidden or left: the request outlives the page. - { keepalive = false }: { keepalive?: boolean } = {}, -) => { - const res = await fetch(buildUrl('play/submit_move'), { - method: 'POST', - keepalive, - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - game_id: gameId, - moves: moves, - game_over_state: gameOverState, - game_type: gameType, - move_times: moveTimes, - fen: fen, - brain_moves: brainMoves, - - ...(winner && winner !== 'none' ? { winner: winner } : {}), - }), - }) - - return res.json() -} - export const fetchPlayPlayerStats = async () => { const res = await fetch(buildUrl('play/get_player_stats')) const data = await res.json() @@ -275,17 +134,6 @@ export const fetchPlayPlayerStats = async () => { } } -/** - * fetchGameMove, retried a few times (a few seconds in all) unless the server - * rejected the request. Throws if it still fails. - */ -export const fetchMaiaMove = (...args: Parameters) => - backOff(() => fetchGameMove(...args), { - jitter: 'full', - numOfAttempts: 6, - retry: retryUnlessRejected, - }) - /** How strong Maia felt for its rating. */ export type FeedbackStrength = 'too_weak' | 'about_right' | 'too_strong' @@ -302,8 +150,8 @@ export interface GameFeedback { /** * Sends the player's feedback on a game (play/game_feedback). Each call sets * what it sends and the server keeps the rest, so a rating is sent as soon as - * it is picked. Retried a little: the end of a game the browser runs may not - * have reached the server yet (a 409). + * it is picked. Retried a little, and again if the server says the game + * isn't over yet (a 409). */ export const sendGameFeedback = (gameId: string, feedback: GameFeedback) => backOff( diff --git a/src/components/Common/PlaySetupModal.tsx b/src/components/Common/PlaySetupModal.tsx index 9b92db1b..72b24c39 100644 --- a/src/components/Common/PlaySetupModal.tsx +++ b/src/components/Common/PlaySetupModal.tsx @@ -19,14 +19,12 @@ import { TimeControlOptions, } from 'src/types' import { ModalContext } from 'src/contexts/ModalContext' -import { startGameEarly } from 'src/api/play' import { fetchCurrentServerGame, resignServerGame } from 'src/api/serverGames' import { ServerGame, describeServerGame, serverGamePage, } from 'src/lib/serverGames' -import { useServerGames } from 'src/hooks/useServerGames' import { trackPlaySetupLeft } from 'src/lib/analytics' import { whenPageCloses } from 'src/lib/posthogClient' import { checkStartPosition } from 'src/lib/startPosition' @@ -35,11 +33,6 @@ import { TIME_MINUTES_STEPS, nearestStepIndex, } from 'src/lib/timeControl' -import { - UnfinishedGame, - clearUnfinishedGame, - loadUnfinishedGame, -} from 'src/lib/unfinishedGame' import { MAIA_VERSIONS as maiaOptions, PlaySetupInitialState, @@ -236,44 +229,11 @@ export const PlaySetupModal: React.FC = ( ) const [practice, setPractice] = useState(initial.practice) - // An unlimited or practice game vs Maia left unfinished in this browser, - // offered to continue (read after the first render: the dialog is in /play's - // server HTML). - const [unfinishedGame, setUnfinishedGame] = useState( - null, - ) - // Shown for Hand & Brain too: starting any game resigns it. - useEffect(() => { - setUnfinishedGame(loadUnfinishedGame()) - }, []) - - const continueUnfinishedGame = useCallback(() => { - if (!unfinishedGame) return - const { config } = unfinishedGame - outcome.current = 'game' - setPlaySetupModalProps(undefined) - onClose?.() - push({ - pathname: '/play/maia', - query: { - player: config.player, - maiaVersion: config.maiaVersion, - timeControl: config.timeControl, - sampleMoves: config.sampleMoves, - simulateMaiaTime: config.simulateMaiaTime ?? true, - startFen: config.startFen, - practice: !!config.practice, - }, - }) - }, [unfinishedGame, setPlaySetupModalProps, onClose, push]) - // The player's game in progress on the server (src/lib/serverGames.ts): it // has to be resumed or resigned before another game is started. const [openServerGame, setOpenServerGame] = useState(null) const [resigningOpenGame, setResigningOpenGame] = useState(false) - const serverGames = useServerGames() useEffect(() => { - if (!serverGames) return let canceled = false fetchCurrentServerGame() .then((game) => { @@ -283,7 +243,7 @@ export const PlaySetupModal: React.FC = ( return () => { canceled = true } - }, [serverGames]) + }, []) const resumeOpenServerGame = useCallback(() => { if (!openServerGame) return @@ -388,7 +348,7 @@ export const PlaySetupModal: React.FC = ( choice.current = { maiaVersion, timeControl, - hadGame: !!unfinishedGame || !!openServerGame, + hadGame: !!openServerGame, } const start = useCallback( @@ -410,7 +370,7 @@ export const PlaySetupModal: React.FC = ( } // The server holds one game per player at a time. - if (serverGames && openServerGame) { + if (openServerGame) { toast.error('Resume or resign your game in progress first') return } @@ -418,8 +378,6 @@ export const PlaySetupModal: React.FC = ( outcome.current = 'game' setPlaySetupModalProps(undefined) onClose?.() - // A new game resigns any unfinished one (on the backend, as it starts). - clearUnfinishedGame() // Next time the dialog starts from these choices. Not a challenge's: // those settings were set for the visitor, not chosen by them. @@ -440,16 +398,7 @@ export const PlaySetupModal: React.FC = ( } if (props.playType == 'againstMaia') { - // A game the server holds is created by /play/maia itself (as is - // any game while it isn't known yet who runs this player's). - if (serverGames === false) { - startGameEarly( - resolvedPlayer as Color, - maiaVersion, - sampleMoves, - timeControl, - ) - } + // The game is created by /play/maia itself. push({ pathname: '/play/maia', query: { @@ -486,7 +435,6 @@ export const PlaySetupModal: React.FC = ( }, [ openServerGame, - serverGames, setPlaySetupModalProps, props.playType, push, @@ -584,28 +532,6 @@ export const PlaySetupModal: React.FC = ( )} - {unfinishedGame && ( -
-
-

- Unfinished game vs{' '} - {unfinishedGame.config.maiaVersion.replace( - 'maia_kdd_', - 'Maia-3 ', - )} -

-

- Starting a new game resigns the unfinished game -

-
- -
- )} {props.playType == 'handAndBrain' ? ( <>
diff --git a/src/components/Play/StartGameConfirmModal.test.tsx b/src/components/Play/StartGameConfirmModal.test.tsx deleted file mode 100644 index ce33bc5b..00000000 --- a/src/components/Play/StartGameConfirmModal.test.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { fireEvent, render, screen } from '@testing-library/react' -import { StartGameConfirmModal } from './StartGameConfirmModal' - -describe('StartGameConfirmModal', () => { - it('shows nothing while closed', () => { - const { container } = render( - , - ) - expect(container).toBeEmptyDOMElement() - }) - - it('starts the game, or leaves without starting one', () => { - const onStart = jest.fn() - const onCancel = jest.fn() - render( - , - ) - - expect( - screen.getByRole('dialog', { name: 'Start a new game?' }), - ).toBeInTheDocument() - expect( - screen.getByText( - 'If you have a game in progress, starting this one resigns it.', - ), - ).toBeInTheDocument() - const start = screen.getByRole('button', { name: 'Start game' }) - expect(start).toHaveFocus() - - fireEvent.click(start) - expect(onStart).toHaveBeenCalledTimes(1) - expect(onCancel).not.toHaveBeenCalled() - - fireEvent.click(screen.getByRole('button', { name: 'Not now' })) - expect(onCancel).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/components/Play/StartGameConfirmModal.tsx b/src/components/Play/StartGameConfirmModal.tsx deleted file mode 100644 index ee99dd91..00000000 --- a/src/components/Play/StartGameConfirmModal.tsx +++ /dev/null @@ -1,57 +0,0 @@ -interface StartGameConfirmModalProps { - isOpen: boolean - onStart: () => void - onCancel: () => void -} - -/** - * Asks before a play page opened by a link starts a game, which ends the - * player's game in progress (src/hooks/useStartConfirmation). - */ -export const StartGameConfirmModal: React.FC = ({ - isOpen, - onStart, - onCancel, -}) => { - if (!isOpen) return null - - return ( -
-
-

- Start a new game? -

- -

- If you have a game in progress, starting this one resigns it. -

- -
- - -
-
-
- ) -} diff --git a/src/components/Play/index.ts b/src/components/Play/index.ts index 01404ab6..6ad4dd09 100644 --- a/src/components/Play/index.ts +++ b/src/components/Play/index.ts @@ -1,6 +1,5 @@ export * from './PlayControls' export * from './HandBrainPlayControls' -export * from './StartGameConfirmModal' export * from './GameInProgressModal' export * from './ResignOfferModal' export * from './GameFeedback' diff --git a/src/contexts/PlayControllerContext.ts b/src/contexts/PlayControllerContext.ts index 40f721c9..fecffb41 100644 --- a/src/contexts/PlayControllerContext.ts +++ b/src/contexts/PlayControllerContext.ts @@ -19,7 +19,6 @@ export interface IPlayControllerContext extends BaseTreeControllerContext { blackClock: ReturnType['blackClock'] lastMoveTime: ReturnType['lastMoveTime'] stats: ReturnType['stats'] - setResigned: ReturnType['setResigned'] reset: ReturnType['reset'] makePlayerMove: ReturnType['makePlayerMove'] updateClock: ReturnType['updateClock'] @@ -66,7 +65,6 @@ export const PlayControllerContext = lastRating: undefined, rating: 0, }, - setResigned: fn, reset: fn, makePlayerMove: fn, updateClock: fn, diff --git a/src/hooks/useGameInProgressQuestion.ts b/src/hooks/useGameInProgressQuestion.ts index 37174b6d..bf3b6ceb 100644 --- a/src/hooks/useGameInProgressQuestion.ts +++ b/src/hooks/useGameInProgressQuestion.ts @@ -49,7 +49,7 @@ export interface GameInProgressQuestion { * game with the same settings again. */ export const useGameInProgressQuestion = () => { - // Decided on the page's first render, as in useStartConfirmation. + // Decided on the page's first render. const [followedLink] = useState(openedByFollowingLink) const [question, setQuestion] = useState() const [resigning, setResigning] = useState(false) diff --git a/src/hooks/usePlayController/useGameLog.test.ts b/src/hooks/usePlayController/useGameLog.test.ts deleted file mode 100644 index d9e85835..00000000 --- a/src/hooks/usePlayController/useGameLog.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { act, renderHook } from '@testing-library/react' -import { - GameOverState, - LOG_EVERY_PLIES, - hasUnsentMoves, - shouldLogGame, - useGameLog, -} from './useGameLog' - -describe('shouldLogGame', () => { - it('sends every LOG_EVERY_PLIES half-moves, not each one', () => { - const sent = [] - for (let plies = 1; plies <= LOG_EVERY_PLIES * 3; plies++) { - if (shouldLogGame(plies, 'not_over', null)) sent.push(plies) - } - expect(sent).toEqual([ - LOG_EVERY_PLIES, - LOG_EVERY_PLIES * 2, - LOG_EVERY_PLIES * 3, - ]) - }) - - it('sends a game that has ended, at any length', () => { - expect(shouldLogGame(7, 'resign', null)).toBe(true) - expect(shouldLogGame(0, 'time', null)).toBe(true) - }) - - it('does not send the same thing twice', () => { - expect( - shouldLogGame(LOG_EVERY_PLIES, 'not_over', `${LOG_EVERY_PLIES}/not_over`), - ).toBe(false) - expect(shouldLogGame(31, 'rules', '31/rules')).toBe(false) - }) - - it('has moves to send when the page goes until they are sent', () => { - expect(hasUnsentMoves(3, 'not_over', null)).toBe(true) - expect(hasUnsentMoves(3, 'not_over', '3/not_over')).toBe(false) - expect(hasUnsentMoves(0, 'not_over', null)).toBe(false) - expect(hasUnsentMoves(9, 'resign', null)).toBe(false) - }) -}) - -describe('useGameLog', () => { - let visibility: DocumentVisibilityState = 'visible' - - beforeEach(() => { - visibility = 'visible' - Object.defineProperty(document, 'visibilityState', { - configurable: true, - get: () => visibility, - }) - }) - - const setup = (gameId = 'g1') => { - const calls: [string, number, GameOverState, boolean][] = [] - const props = { gameId, plies: 0, state: 'not_over' as GameOverState } - const hook = renderHook( - (p: typeof props) => - useGameLog({ - ...p, - send: (leaving) => calls.push([p.gameId, p.plies, p.state, leaving]), - }), - { initialProps: props }, - ) - const play = (next: Partial) => { - Object.assign(props, next) - hook.rerender({ ...props }) - } - return { calls, play, hook } - } - - it('sends a 45-half-move game three times instead of 45', () => { - const { calls, play } = setup() - for (let plies = 1; plies <= 45; plies++) play({ plies }) - play({ state: 'resign' }) - expect(calls).toEqual([ - ['g1', 20, 'not_over', false], - ['g1', 40, 'not_over', false], - ['g1', 45, 'resign', false], - ]) - }) - - it('sends the moves not yet sent when the page is hidden', () => { - const { calls, play } = setup() - for (let plies = 1; plies <= 7; plies++) play({ plies }) - act(() => { - visibility = 'hidden' - document.dispatchEvent(new Event('visibilitychange')) - }) - // Hidden again with nothing new: nothing more. - act(() => { - document.dispatchEvent(new Event('visibilitychange')) - }) - expect(calls).toEqual([['g1', 7, 'not_over', true]]) - }) - - it('sends the moves not yet sent when the page is left', () => { - const { calls, play } = setup() - play({ plies: 3 }) - act(() => { - window.dispatchEvent(new Event('pagehide')) - }) - expect(calls).toEqual([['g1', 3, 'not_over', true]]) - }) - - it('sends the game being left for another one', () => { - const { calls, play } = setup() - play({ plies: 5 }) - play({ gameId: 'g2', plies: 0 }) - play({ plies: 1 }) - expect(calls).toEqual([['g1', 5, 'not_over', true]]) - }) - - it('sends the game when its page closes', () => { - const { calls, play, hook } = setup() - play({ plies: 4 }) - hook.unmount() - expect(calls).toEqual([['g1', 4, 'not_over', true]]) - }) - - it('waits for the game to have an id', () => { - const { calls, play } = setup('') - play({ state: 'resign' }) - expect(calls).toEqual([]) - play({ gameId: 'g1' }) - expect(calls).toEqual([['g1', 0, 'resign', false]]) - }) -}) diff --git a/src/hooks/usePlayController/useGameLog.ts b/src/hooks/usePlayController/useGameLog.ts deleted file mode 100644 index 73d78ba1..00000000 --- a/src/hooks/usePlayController/useGameLog.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { useEffect, useRef } from 'react' - -/** - * When a game against Maia is sent to the backend (play/submit_move). - * - * It was sent after every half-move, Maia's included: about 330,000 requests - * a day, a third of everything the site's host (Vercel) counts and bills. Each - * request carries every move so far, so sending fewer of them loses nothing - * but the moves since the last one, and those are sent when the page is hidden - * or left. A game is now sent every LOG_EVERY_PLIES half-moves, when it ends, - * and when the page is hidden, left or moves on to another game. - */ -export const LOG_EVERY_PLIES = 20 - -export type GameOverState = 'not_over' | 'rules' | 'resign' | 'time' - -const keyOf = (plies: number, state: GameOverState) => `${plies}/${state}` - -/** Whether the game should be sent now, given what was last sent. */ -export const shouldLogGame = ( - plies: number, - state: GameOverState, - lastSent: string | null, -) => { - if (keyOf(plies, state) === lastSent) return false - if (state !== 'not_over') return true - return plies > 0 && plies % LOG_EVERY_PLIES === 0 -} - -/** Whether moves are waiting to be sent when the page goes away. */ -export const hasUnsentMoves = ( - plies: number, - state: GameOverState, - lastSent: string | null, -) => state === 'not_over' && plies > 0 && keyOf(plies, state) !== lastSent - -/** - * Calls `send` as above. `send(true)` is for a page being hidden or left: it - * should send with fetch's keepalive and not wait for an answer. - */ -export const useGameLog = ({ - gameId, - plies, - state, - send, -}: { - gameId: string - plies: number - state: GameOverState - send: (leaving: boolean) => void -}) => { - const lastSent = useRef(null) - const latest = useRef({ gameId, plies, state, send }) - - // Updated in an effect, not while rendering, so that when the game changes - // the cleanup below still sees the game that is being left. - useEffect(() => { - latest.current = { gameId, plies, state, send } - }) - - useEffect(() => { - if (!gameId) return - if (!shouldLogGame(plies, state, lastSent.current)) return - lastSent.current = keyOf(plies, state) - latest.current.send(false) - }, [gameId, plies, state]) - - useEffect(() => { - const flush = () => { - const { gameId, plies, state, send } = latest.current - if (!gameId || !hasUnsentMoves(plies, state, lastSent.current)) return - lastSent.current = keyOf(plies, state) - send(true) - } - const onVisibilityChange = () => { - if (document.visibilityState === 'hidden') flush() - } - document.addEventListener('visibilitychange', onVisibilityChange) - window.addEventListener('pagehide', flush) - return () => { - document.removeEventListener('visibilitychange', onVisibilityChange) - window.removeEventListener('pagehide', flush) - // Leaving the game, for another game or another page. - flush() - lastSent.current = null - } - }, [gameId]) -} diff --git a/src/hooks/usePlayController/useHandBrainController.ts b/src/hooks/usePlayController/useHandBrainController.ts index 9d73f9de..67927507 100644 --- a/src/hooks/usePlayController/useHandBrainController.ts +++ b/src/hooks/usePlayController/useHandBrainController.ts @@ -1,21 +1,14 @@ import { PieceSymbol, Chess } from 'chess.ts' import type { Key } from 'chessground/types' -import { backOff } from 'exponential-backoff' import type { DrawShape } from 'chessground/draw' -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useMemo, useState } from 'react' import { PlayGameConfig } from 'src/types' import { useStats } from 'src/hooks/useStats' import { usePlayController } from './usePlayController' -import { fetchMaiaMove, logGameMove, fetchPlayPlayerStats } from 'src/api' -import { - dismissMaiaMoveFailedToast, - reportMaiaMoveFailed, -} from 'src/components/Common/maiaMoveFailedToast' +import { fetchPlayPlayerStats } from 'src/api' import { useSound } from 'src/hooks/useSound' import { safeUpdateRating } from 'src/lib/ratingUtils' -import { maiaMoveClocks } from 'src/lib/timeControl' -import { useGameLog } from './useGameLog' import { useServerTurns } from './useServerTurns' import { ServerGame } from 'src/lib/serverGames' import { UnfinishedGame } from 'src/lib/unfinishedGame' @@ -44,27 +37,22 @@ export const useHandBrainController = ( id: string, playGameConfig: PlayGameConfig, simulateMaiaTime: boolean, - // A game the server holds (src/lib/serverGames.ts): `resume` has the moves - // to show at once, `serverGame` its state. The server then names the + // The game as the server holds it (src/lib/serverGames.ts): `resume` has + // the moves to show at once, `serverGame` its state. The server names the // brain's piece (hand games) or makes the hand's move (brain games). resume?: UnfinishedGame, serverGame?: ServerGame, onServerResync?: (game: ServerGame) => void, ) => { const isBrain = playGameConfig.isBrain - const serverHeld = !!serverGame - const controller = usePlayController(id, playGameConfig, resume, serverHeld) + const hasGame = !!serverGame + const controller = usePlayController(id, playGameConfig, resume) const { playMoveSound } = useSound() const [selectedPiece, setSelectedPiece] = useState( undefined, ) - const [brainMoves, setBrainMoves] = useState([]) - // Asks Maia again (for a piece, or a move) after a request that failed. - const [maiaAttempt, setMaiaAttempt] = useState(0) - const retryMaia = useCallback(() => setMaiaAttempt((n) => n + 1), []) - const [stats, incrementStats, updateRating] = useStats( isBrain ? brainStatsLoader : handStatsLoader, ) @@ -90,7 +78,6 @@ export const useHandBrainController = ( // Hand: the brain's piece for the next move comes with each answer. // Brain: the piece the player named has been played. onShown: (game) => { - setBrainMoves(game.brain_moves ?? []) setSelectedPiece( !isBrain && game.state === 'not_over' && game.partner_piece ? (game.partner_piece as PieceSymbol) @@ -117,78 +104,18 @@ export const useHandBrainController = ( } }, [isBrain, selectedPiece, controller.availableMoves]) - useEffect(() => { - if ( - !serverHeld && - controller.game.id && - !isBrain && - !selectedPiece && - controller.playerActive - ) { - // Maia is brain - let canceled = false - - const maiaChoosePiece = async () => { - let maiaMoves - try { - maiaMoves = await fetchMaiaMove( - controller.moveList, - playGameConfig.maiaPartnerVersion, - playGameConfig.startFen, - ) - } catch (error) { - if (!canceled) reportMaiaMoveFailed(error, retryMaia) - return - } - dismissMaiaMoveFailedToast() - const nextMove: string = maiaMoves['top_move'] - - const pieceType = controller.pieces[nextMove.substring(0, 2)]?.type - if (!pieceType) return - - if (!canceled) { - setSelectedPiece(pieceType) - setBrainMoves([...brainMoves, pieceType]) - } - } - - maiaChoosePiece() - return () => { - canceled = true - } - } - }, [ - brainMoves, - controller.game.id, - controller.moveList, - controller.pieces, - controller.playerActive, - isBrain, - playGameConfig.maiaPartnerVersion, - playGameConfig.startFen, - selectedPiece, - maiaAttempt, - retryMaia, - serverHeld, - ]) - const makePlayerMove = useCallback( async (moveUci: string) => { // Not a move in the game (made on an earlier position): ignored. - if (serverHeld && !server.canPlay(moveUci)) return + if (!hasGame || !server.canPlay(moveUci)) return const chess = new Chess(controller.currentNode.fen) const destinationSquare = moveUci.slice(2, 4) const isCapture = !!chess.get(destinationSquare) - if (serverHeld) { - const thinkMs = server.thinkMs() - controller.updateClock() - server.sendMove(moveUci, thinkMs) - } else { - const moveTime = controller.updateClock() - controller.addMoveWithTime(moveUci, moveTime) - } + const thinkMs = server.thinkMs() + controller.updateClock() + server.sendMove(moveUci, thinkMs) setSelectedPiece(undefined) playMoveSound(isCapture) @@ -196,141 +123,24 @@ export const useHandBrainController = ( [ controller, playMoveSound, - serverHeld, + hasGame, server.thinkMs, server.sendMove, server.canPlay, ], ) - useEffect(() => { - let canceled = false - let moveTimeout: ReturnType | undefined - - const makeMaiaMove = async () => { - const maiaClock = - (controller.player == 'white' - ? controller.blackClock - : controller.whiteClock) / 1000 - const clocks = maiaMoveClocks(controller.timeControl, maiaClock) - - let maiaMoves - try { - maiaMoves = await fetchMaiaMove( - controller.moveList, - playGameConfig.maiaVersion, - playGameConfig.startFen, - null, - clocks.initialClock, - clocks.currentClock, - clocks.increment, - ) - } catch (error) { - if (!canceled) reportMaiaMoveFailed(error, retryMaia) - return - } - const nextMove: string = maiaMoves['top_move'] - const moveDelay = maiaMoves['move_delay'] - - if (canceled) { - return - } - dismissMaiaMoveFailedToast() - - moveTimeout = setTimeout( - () => { - if (canceled) { - return - } - - const moveTime = controller.updateClock() - - const chess = new Chess(controller.currentNode.fen) - const destinationSquare = nextMove.slice(2, 4) - const isCapture = !!chess.get(destinationSquare) - - controller.addMoveWithTime(nextMove, moveTime) - playMoveSound(isCapture) - }, - simulateMaiaTime ? moveDelay * 1000 : 0, - ) - } - - if ( - !serverHeld && - controller.game.id && - !controller.playerActive && - !controller.game.termination - ) { - makeMaiaMove() - return () => { - canceled = true - - if (moveTimeout) { - clearTimeout(moveTimeout) - } - } - } - }, [ - controller.playerActive, - controller.moveList, - controller, - playGameConfig.maiaVersion, - playGameConfig.startFen, - simulateMaiaTime, - maiaAttempt, - retryMaia, - serverHeld, - ]) - const selectPiece = useCallback( async (piece: PieceSymbol) => { - if (movablePieceTypes.has(piece)) { - setSelectedPiece(piece) - - if (serverHeld) { - // The server has the partner Maia make the move with this piece, - // and answers with it and the opponent's reply. - server.sendPiece(piece, server.thinkMs()) - return - } - - let maiaMoves - try { - maiaMoves = await fetchMaiaMove( - controller.moveList, - playGameConfig.maiaPartnerVersion, - playGameConfig.startFen, - piece, - ) - } catch (error) { - // The piece can be chosen again, or Try again asks for this one. - setSelectedPiece(undefined) - reportMaiaMoveFailed(error, () => selectPieceRef.current?.(piece)) - return - } - dismissMaiaMoveFailedToast() - setBrainMoves([...brainMoves, piece]) - makePlayerMove(maiaMoves['top_move']) - } + if (!hasGame || !movablePieceTypes.has(piece)) return + setSelectedPiece(piece) + // The server has the partner Maia make the move with this piece, and + // answers with it and the opponent's reply. + server.sendPiece(piece, server.thinkMs()) }, - [ - controller.moveList, - makePlayerMove, - movablePieceTypes, - playGameConfig.maiaPartnerVersion, - playGameConfig.startFen, - brainMoves, - serverHeld, - server.sendPiece, - server.thinkMs, - ], + [movablePieceTypes, hasGame, server.sendPiece, server.thinkMs], ) - // Try again calls the latest selectPiece, with the latest position. - const selectPieceRef = useRef(selectPiece) - selectPieceRef.current = selectPiece - const boardShapes: DrawShape[] = useMemo(() => { if (!isBrain && selectedPiece) { return Object.entries(controller.pieces) @@ -349,57 +159,12 @@ export const useHandBrainController = ( const reset = () => { setSelectedPiece(undefined) - setBrainMoves([]) controller.reset() } - const gameOverState = controller.game.termination?.type || 'not_over' const resign = useCallback(() => { - if (serverHeld) { - server.resign() - return - } - controller.setResigned(true) - }, [serverHeld, server.resign, controller.setResigned]) - - useGameLog({ - // Never sent for a game the server holds: it has every move already. - gameId: serverHeld ? '' : controller.game.id, - plies: controller.moveList.length, - state: gameOverState, - send: (leaving) => { - const winner = controller.game.termination?.winner - const log = (keepalive: boolean) => - logGameMove( - controller.game.id, - controller.moveList, - controller.moveTimes, - gameOverState, - playGameConfig.isBrain ? 'brain' : 'hand', - playGameConfig.startFen || undefined, - winner, - brainMoves, - { keepalive }, - ) - - if (leaving) { - log(true).catch(() => undefined) - return - } - - const submitFn = async () => { - const response = await backOff(() => log(false), { jitter: 'full' }) - if (controller.game.termination) { - // Safely update rating - only if the response contains a valid rating - safeUpdateRating(response.player_elo, (rating) => - updateRating(rating, response.player_provisional), - ) - incrementStats(1, winner == playGameConfig.player ? 1 : 0) - } - } - submitFn() - }, - }) + if (hasGame) server.resign() + }, [hasGame, server.resign]) return { ...controller, diff --git a/src/hooks/usePlayController/usePlayController.test.ts b/src/hooks/usePlayController/usePlayController.test.ts index c078bc86..f149e167 100644 --- a/src/hooks/usePlayController/usePlayController.test.ts +++ b/src/hooks/usePlayController/usePlayController.test.ts @@ -27,32 +27,16 @@ const play = ( } } -describe('usePlayController takebacks (practice games)', () => { - it('takes back the player move and Maia reply, back to the player', () => { - const { result } = renderHook(() => - usePlayController('game', config({ practice: true })), - ) - play(result, ['e2e4', 'e7e5', 'g1f3', 'b8c6']) - expect(result.current.playerActive).toBe(true) - expect(result.current.canTakeBack).toBe(true) - - act(() => result.current.takeBack()) - - expect(result.current.moveList).toEqual(['e2e4', 'e7e5']) - expect(result.current.playerActive).toBe(true) - }) - - it("takes back just the player's move while Maia is to move", () => { +// Takebacks and extra time are asked of the server (useVsMaiaController); +// this controller says whether each can be asked for. +describe('usePlayController practice games', () => { + it('offers a takeback once the player has moved', () => { const { result } = renderHook(() => usePlayController('game', config({ practice: true })), ) + expect(result.current.canTakeBack).toBe(false) play(result, ['e2e4', 'e7e5', 'g1f3']) - expect(result.current.playerActive).toBe(false) - - act(() => result.current.takeBack()) - - expect(result.current.moveList).toEqual(['e2e4', 'e7e5']) - expect(result.current.playerActive).toBe(true) + expect(result.current.canTakeBack).toBe(true) }) it('has nothing to take back before the player has moved', () => { @@ -68,30 +52,38 @@ describe('usePlayController takebacks (practice games)', () => { play(result, ['e2e4', 'e7e5']) expect(result.current.canTakeBack).toBe(false) expect(result.current.canAddTime).toBe(false) - - act(() => result.current.takeBack()) - expect(result.current.moveList).toEqual(['e2e4', 'e7e5']) }) -}) -describe('usePlayController extra time (practice games)', () => { - it("adds to the player's clock only", () => { - const { result } = renderHook(() => + it('offers extra time in a game with a clock, not in unlimited games', () => { + const timed = renderHook(() => usePlayController('game', config({ practice: true })), ) - act(() => result.current.addTime(15_000)) - expect(result.current.whiteClock).toBe(5 * 60_000 + 15_000) - expect(result.current.blackClock).toBe(5 * 60_000) - }) - - it('is not offered in unlimited games', () => { - const { result } = renderHook(() => + expect(timed.result.current.canAddTime).toBe(true) + const unlimited = renderHook(() => usePlayController( 'game', config({ practice: true, timeControl: 'unlimited' }), ), ) - expect(result.current.canAddTime).toBe(false) + expect(unlimited.result.current.canAddTime).toBe(false) + }) +}) + +describe('usePlayController endings', () => { + it('ends the game only when the server says so, checkmate included', () => { + const { result } = renderHook(() => usePlayController('game', config())) + play(result, ['f2f3', 'e7e5', 'g2g4', 'd8h4']) + expect(result.current.game.termination).toBeUndefined() + + act(() => + result.current.setServerTermination({ + result: '0-1', + winner: 'black', + type: 'rules', + }), + ) + expect(result.current.game.termination?.winner).toBe('black') + expect(result.current.toPlay).toBeNull() }) }) @@ -139,7 +131,13 @@ describe('usePlayController clock state', () => { activeColor: 'white', }) - act(() => result.current.setResigned(true)) + act(() => + result.current.setServerTermination({ + result: '0-1', + winner: 'black', + type: 'resign', + }), + ) expect(window.__MaiaClockState).toMatchObject({ lifecycle: 'finished', result: 'black_wins', diff --git a/src/hooks/usePlayController/usePlayController.ts b/src/hooks/usePlayController/usePlayController.ts index 1e221426..3aabfa93 100644 --- a/src/hooks/usePlayController/usePlayController.ts +++ b/src/hooks/usePlayController/usePlayController.ts @@ -8,65 +8,19 @@ import { useMemo, useState, useCallback, useEffect } from 'react' import { initialClockSeconds } from 'src/lib/timeControl' import { buildClockState, publishClockState } from 'src/lib/clockState' import { UnfinishedGame } from 'src/lib/unfinishedGame' -import { resignTermination } from 'src/lib/resignation' const nullFen = new Chess().fen() -const computeTermination = (chess: Chess): Termination | undefined => { - if (!chess.gameOver()) { - return undefined - } - - if (chess.inDraw() || chess.inStalemate() || chess.inThreefoldRepetition()) { - return { - result: '1/2-1/2', - winner: 'none', - type: 'rules', - } - } - - const turn = chess.turn() == 'w' ? 'white' : 'black' - - if (chess.inCheckmate()) { - return { - result: turn == 'white' ? '0-1' : '1-0', - winner: turn == 'white' ? 'black' : 'white', - type: 'rules', - } - } -} - -const computeTimeTermination = ( - chess: Chess, - playerWhoRanOutOfTime: Color, -): Termination => { - // If there's insufficient material on the board, it's a draw - if (chess.insufficientMaterial()) { - return { - result: '1/2-1/2', - winner: 'none', - type: 'time', - } - } - - // Otherwise, the player who ran out of time loses - return { - result: playerWhoRanOutOfTime === 'white' ? '0-1' : '1-0', - winner: playerWhoRanOutOfTime === 'white' ? 'black' : 'white', - type: 'time', - } -} - export const usePlayController = ( id: string, config: PlayGameConfig, - // A game continued from where it was left (src/lib/unfinishedGame.ts). + // The moves and clocks the game starts from: the server's game as it was + // when the page got it (serverGameStart in src/lib/serverGames.ts). resume?: UnfinishedGame, +) => { // The server holds the game (src/lib/serverGames.ts): it says how the game // ends (setServerTermination) and what the clocks read (syncClocks), and is // asked when a clock runs out here (clockExpired). - serverHeld = false, -) => { const [gameTree, setGameTree] = useState(() => { const tree = new GameTree(config.startFen || nullFen) if (resume) tree.addMovesToMainLine(resume.moves, resume.moveTimes) @@ -82,13 +36,11 @@ export const usePlayController = ( }, []) const [treeVersion, setTreeVersion] = useState(0) - const [resigned, setResigned] = useState(false) - const [timeExpired, setTimeExpired] = useState(null) const [serverTermination, setServerTermination] = useState< Termination | undefined >(undefined) - // The side whose clock reached zero on this screen, in a game the server - // holds: the server's clock decides whether it really has. + // The side whose clock reached zero on this screen: the server's clock + // decides whether it really has. const [clockExpired, setClockExpired] = useState<{ color: Color at: number @@ -128,19 +80,7 @@ export const usePlayController = ( const lastNode = mainLine[mainLine.length - 1] const turn = lastNode.turn - const chess = gameTree.toChess() - - // A mating move that was registered stands even if the clock ran out - // at the same moment, so checkmate takes precedence over the flag. - const termination = serverHeld - ? serverTermination - : chess.inCheckmate() - ? computeTermination(chess) - : timeExpired - ? computeTimeTermination(chess, timeExpired) - : resigned - ? resignTermination(config.player, 'player') - : computeTermination(chess) + const termination = serverTermination const moves = [] const rootNode = gameTree.getRoot() @@ -177,12 +117,9 @@ export const usePlayController = ( }, [ gameTree, treeVersion, - resigned, - timeExpired, whiteClock, blackClock, id, - serverHeld, serverTermination, config.player, ]) @@ -198,8 +135,8 @@ export const usePlayController = ( const chess = new Chess(controller.currentNode.fen) const verboseMoves = chess.moves({ verbose: true }) - // No moves until the game has its id (/play/maia shows the game while - // start_game answers): a move needs it to be logged. + // No moves until the game has its id (/play/maia shows the board while + // the server creates the game). const cantMove = !playerActive || game.termination || !id const availableMoves = cantMove @@ -265,19 +202,6 @@ export const usePlayController = ( [toPlay, updateClockForColor], ) - const expireOnTime = useCallback((color: Color) => { - const now = Date.now() - - if (color == 'white') { - setWhiteClock(0) - } else { - setBlackClock(0) - } - - setLastMoveTime(now) - setTimeExpired(color) - }, []) - useEffect(() => { if ( !game.termination && @@ -290,28 +214,23 @@ export const usePlayController = ( // A clock set by the server started at lastMoveTime, which can be // before this ran. const timeRemaining = - serverHeld && lastMoveTime > 0 + lastMoveTime > 0 ? Math.max(0, clockNow - (Date.now() - lastMoveTime)) : clockNow - const timeout = setTimeout(() => { - if (serverHeld) { - setClockExpired({ color: activeColor, at: Date.now() }) - } else { - expireOnTime(activeColor) - } - }, timeRemaining) + const timeout = setTimeout( + () => setClockExpired({ color: activeColor, at: Date.now() }), + timeRemaining, + ) return () => clearTimeout(timeout) } }, [ - expireOnTime, game.termination, blackClock, moveList.length, config.timeControl, toPlay, whiteClock, - serverHeld, lastMoveTime, ]) @@ -382,10 +301,9 @@ export const usePlayController = ( [gameTree, controller.setCurrentNode], ) - // The player's last move, and Maia's reply to it if there is one, so - // that it is the player's turn again (practice games). The clocks keep - // their times: the side whose clock was running is charged up to now, and - // the player's clock runs from here. + // A practice game's takeback (the player's last move, and Maia's reply to + // it if there is one) and extra time are asked of the server by the page's + // controller; here, whether each can be asked for. const playerMovesPlayed = useMemo(() => { const mainLine = gameTree.getMainLine() const playerTurn = config.player === 'white' ? 'w' : 'b' @@ -395,68 +313,12 @@ export const usePlayController = ( const canTakeBack = !!config.practice && !game.termination && playerMovesPlayed > 0 - // Charges the running clock (the side to move's) with the time since the - // last move, without increment, and restarts the count from now, so a - // clock change mid-move keeps the running time. - const chargeRunningClock = useCallback(() => { - if (moveList.length < 2 || lastMoveTime <= 0 || !toPlay) return - const elapsed = Date.now() - lastMoveTime - if (toPlay === 'white') { - setWhiteClock((clock) => Math.max(clock - elapsed, 0)) - } else { - setBlackClock((clock) => Math.max(clock - elapsed, 0)) - } - setLastMoveTime(Date.now()) - }, [moveList.length, lastMoveTime, toPlay]) - - const takeBack = useCallback(() => { - if (!canTakeBack) return - - const tip = gameTree.getLastMainlineNode() - const plies = playerActive ? 2 : 1 - let target = tip - for (let i = 0; i < plies && target.parent; i++) { - target = target.parent - } - - chargeRunningClock() - // Clocks only run from the second move on: back before it, they wait - // to start again. - if (moveList.length - plies < 2) setLastMoveTime(0) - - target.removeAllChildren() - setTreeVersion((prev) => prev + 1) - controller.setCurrentNode(target) - }, [ - canTakeBack, - gameTree, - playerActive, - moveList.length, - chargeRunningClock, - controller.setCurrentNode, - ]) - - // Extra time on the player's clock, on request (practice games). const canAddTime = !!config.practice && !game.termination && config.timeControl != 'unlimited' - const addTime = useCallback( - (ms: number) => { - if (!canAddTime) return - chargeRunningClock() - if (config.player === 'white') { - setWhiteClock((clock) => clock + ms) - } else { - setBlackClock((clock) => clock + ms) - } - }, - [canAddTime, config.player, chargeRunningClock], - ) - const reset = () => { const newTree = new GameTree(config.startFen || nullFen) setGameTree(newTree) - setResigned(false) - setTimeExpired(null) + setServerTermination(undefined) setLastMoveTime(0) setWhiteClock(initialClockValue) setBlackClock(initialClockValue) @@ -517,17 +379,13 @@ export const usePlayController = ( setOrientation: controller.setOrientation, addMoveWithTime, - setResigned, - serverHeld, setServerTermination, syncClocks, clockExpired, reset, practice: !!config.practice, canTakeBack, - takeBack, canAddTime, - addTime, makePlayerMove, updateClock, updateClockForColor, diff --git a/src/hooks/usePlayController/useServerTurns.ts b/src/hooks/usePlayController/useServerTurns.ts index 2ca605c5..d7e6774c 100644 --- a/src/hooks/usePlayController/useServerTurns.ts +++ b/src/hooks/usePlayController/useServerTurns.ts @@ -119,9 +119,8 @@ export const useServerTurns = (options: Options) => { /** * Shows the player's move at once and sends it. A move that can't be - * played where the game stands is ignored, as it is in a game the browser - * runs: sent, the server refused it (400) and every move after it was a - * ply out until the game was redrawn. + * played where the game stands is ignored: sent, the server refused it + * (400) and every move after it was a ply out until the game was redrawn. */ const sendMove = useCallback( (moveUci: string, think: number) => { diff --git a/src/hooks/usePlayController/useVsMaiaController.server.test.ts b/src/hooks/usePlayController/useVsMaiaController.server.test.ts index 9fd79a2b..03aafa3c 100644 --- a/src/hooks/usePlayController/useVsMaiaController.server.test.ts +++ b/src/hooks/usePlayController/useVsMaiaController.server.test.ts @@ -561,7 +561,7 @@ describe('playing a game the server holds', () => { ...practice, clock: { ...practice.clock!, white_ms: 315000 }, }) - act(() => result.current.addTime(15000)) + act(() => result.current.addTime()) await settle() expect(addTimeServerGame).toHaveBeenCalledWith('g1') expect(result.current.whiteClock).toBe(315000) diff --git a/src/hooks/usePlayController/useVsMaiaController.ts b/src/hooks/usePlayController/useVsMaiaController.ts index 01ffc593..99a48105 100644 --- a/src/hooks/usePlayController/useVsMaiaController.ts +++ b/src/hooks/usePlayController/useVsMaiaController.ts @@ -1,10 +1,9 @@ -import { useCallback, useEffect, useRef, useState } from 'react' +import { useCallback, useRef, useState } from 'react' import { Chess } from 'chess.ts' import { PlayGameConfig, QueuedPremove } from 'src/types' -import { backOff } from 'exponential-backoff' import { useStats } from 'src/hooks/useStats' import { usePlayController } from 'src/hooks/usePlayController' -import { fetchMaiaMove, logGameMove, fetchPlayPlayerStats } from 'src/api' +import { fetchPlayPlayerStats } from 'src/api' import { ServerGameConflict, addTimeServerGame, @@ -12,20 +11,10 @@ import { } from 'src/api/serverGames' import { ServerGame } from 'src/lib/serverGames' import { useServerTurns } from './useServerTurns' -import { - dismissMaiaMoveFailedToast, - reportMaiaMoveFailed, -} from 'src/components/Common/maiaMoveFailedToast' +import { reportMaiaMoveFailed } from 'src/components/Common/maiaMoveFailedToast' import { useSound } from 'src/hooks/useSound' import { safeUpdateRating } from 'src/lib/ratingUtils' -import { maiaMoveClocks } from 'src/lib/timeControl' -import { useGameLog } from './useGameLog' -import { - UnfinishedGame, - canResume, - clearUnfinishedGame, - saveUnfinishedGame, -} from 'src/lib/unfinishedGame' +import { UnfinishedGame } from 'src/lib/unfinishedGame' const playStatsLoader = async () => { const stats = await fetchPlayPlayerStats() @@ -39,33 +28,28 @@ const playStatsLoader = async () => { const PREMOVE_SOUND_DELAY_MS = 120 -// The backend updates ratings only for games sent without a starting -// position, so a practice game from the usual start sends it explicitly to -// stay unrated. (Its win, draw or loss still counts in the player's stats.) -const STANDARD_START_FEN = new Chess().fen() - export const useVsMaiaPlayController = ( id: string, playGameConfig: PlayGameConfig, simulateMaiaTime: boolean, + // The game's moves and clocks as the page got them, to show at once. resume?: UnfinishedGame, - // The game as the server holds it, when it does (src/lib/serverGames.ts): - // each of the player's moves is sent to it and answered with Maia's reply, - // the clocks and the result. `resume` then holds the moves to show at once. + // The game as the server holds it (src/lib/serverGames.ts): each of the + // player's moves is sent to it and answered with Maia's reply, the clocks + // and the result. Not there yet while the server creates the game: the + // board is shown, and nothing can be played or asked for. serverGame?: ServerGame, // The server says the game isn't where this page thought: start again from // its state. onServerResync?: (game: ServerGame) => void, ) => { - const serverHeld = !!serverGame - const controller = usePlayController(id, playGameConfig, resume, serverHeld) + const hasGame = !!serverGame + const controller = usePlayController(id, playGameConfig, resume) const [stats, incrementStats, updateRating] = useStats(playStatsLoader) const { playMoveSound } = useSound() const [queuedPremove, setQueuedPremove] = useState(null) const queuedPremoveRef = useRef(null) const [premoveResetKey, setPremoveResetKey] = useState(0) - // Asks for Maia's move again after a request that failed. - const [maiaMoveAttempt, setMaiaMoveAttempt] = useState(0) const clearPremove = useCallback(() => { if (!queuedPremoveRef.current) { @@ -106,8 +90,6 @@ export const useVsMaiaPlayController = ( [], ) - // --- A game the server holds (useServerTurns) -------------------------- - const server = useServerTurns({ controller, id, @@ -148,253 +130,22 @@ export const useVsMaiaPlayController = ( }) const resign = useCallback(() => { - if (!serverHeld) { - controller.updateClock() - controller.setResigned(true) - return - } - server.resign() - }, [ - serverHeld, - server.resign, - controller.updateClock, - controller.setResigned, - ]) + if (hasGame) server.resign() + }, [hasGame, server.resign]) const makePlayerMove = async (moveUci: string, moveTimeOverride?: number) => { - if (serverHeld) { - // Not a move in the game (made on an earlier position): ignored. - if (!server.canPlay(moveUci)) return - const thinkMs = moveTimeOverride ?? server.thinkMs() - // Charged here too, so that Maia's clock is the one running while its - // reply is on the way; the server's answer sets both clocks right. - controller.updateClock() - clearPremove() - server.sendMove(moveUci, thinkMs) - return - } - const moveTime = moveTimeOverride ?? controller.updateClock() + // Not a move in the game (made on an earlier position): ignored. + if (!hasGame || !server.canPlay(moveUci)) return + const thinkMs = moveTimeOverride ?? server.thinkMs() + // Charged here too, so that Maia's clock is the one running while its + // reply is on the way; the server's answer sets both clocks right. + controller.updateClock() clearPremove() - controller.addMoveWithTime(moveUci, moveTime) + server.sendMove(moveUci, thinkMs) } - useEffect(() => { - // The server makes Maia's moves in a game it holds (above). - if (serverHeld) return - - let canceled = false - let moveTimeout: ReturnType | undefined - - const makeMaiaMove = async () => { - if ( - controller.game.id && - !controller.playerActive && - !controller.game.termination - ) { - const maiaClock = - (controller.player == 'white' - ? controller.blackClock - : controller.whiteClock) / 1000 - const clocks = maiaMoveClocks(controller.timeControl, maiaClock) - - let maiaMoves - try { - maiaMoves = await fetchMaiaMove( - controller.moveList, - playGameConfig.maiaVersion, - playGameConfig.startFen, - null, - clocks.initialClock, - clocks.currentClock, - clocks.increment, - ) - } catch (error) { - if (canceled) return - reportMaiaMoveFailed(error, () => setMaiaMoveAttempt((n) => n + 1)) - return - } - dismissMaiaMoveFailedToast() - const nextMove: string = maiaMoves['top_move'] - const moveDelay = maiaMoves['move_delay'] - - if (canceled) { - return - } - - if (simulateMaiaTime) { - const minimumDelayMs = 200 + Math.random() * 100 - const delayMs = Math.max(moveDelay * 1000, minimumDelayMs) - - moveTimeout = setTimeout(() => { - if (canceled) { - return - } - - const chess = new Chess(controller.currentNode.fen) - const moveTime = controller.updateClock() - const destinationSquare = nextMove.slice(2, 4) - const isCapture = !!chess.get(destinationSquare) - const moveResult = chess.move(nextMove, { sloppy: true }) - - controller.addMoveWithTime(nextMove, moveTime) - playMoveSound(isCapture) - - const legalPremoveUci = - moveResult && queuedPremoveRef.current - ? getLegalPremoveUci(chess.fen(), queuedPremoveRef.current) - : null - - if (queuedPremoveRef.current) { - clearPremove() - } - - if (legalPremoveUci) { - const premoveDestination = legalPremoveUci.slice(2, 4) - const isPremoveCapture = !!chess.get(premoveDestination) - - controller.updateClockForColor(controller.player, 0, true) - controller.addMoveWithTime(legalPremoveUci, 0) - setTimeout( - () => playMoveSound(isPremoveCapture), - PREMOVE_SOUND_DELAY_MS, - ) - } - }, delayMs) - } else { - const chess = new Chess(controller.currentNode.fen) - const moveTime = controller.updateClock() - const destinationSquare = nextMove.slice(2, 4) - const isCapture = !!chess.get(destinationSquare) - const moveResult = chess.move(nextMove, { sloppy: true }) - - controller.addMoveWithTime(nextMove, moveTime) - playMoveSound(isCapture) - - const legalPremoveUci = - moveResult && queuedPremoveRef.current - ? getLegalPremoveUci(chess.fen(), queuedPremoveRef.current) - : null - - if (queuedPremoveRef.current) { - clearPremove() - } - - if (legalPremoveUci) { - const premoveDestination = legalPremoveUci.slice(2, 4) - const isPremoveCapture = !!chess.get(premoveDestination) - - controller.updateClockForColor(controller.player, 0, true) - controller.addMoveWithTime(legalPremoveUci, 0) - setTimeout( - () => playMoveSound(isPremoveCapture), - PREMOVE_SOUND_DELAY_MS, - ) - } - } - } - } - - makeMaiaMove() - - return () => { - canceled = true - - if (moveTimeout) { - clearTimeout(moveTimeout) - } - } - }, [ - controller.game.id, - controller.playerActive, - controller.game.termination, - controller.moveList.length, - playGameConfig.maiaVersion, - playGameConfig.startFen, - simulateMaiaTime, - clearPremove, - getLegalPremoveUci, - maiaMoveAttempt, - serverHeld, - ]) - - const gameOverState = controller.game.termination?.type || 'not_over' - useGameLog({ - // Until start_game has answered (a resignation in that moment), nothing - // is sent; it is once the game has its id. Never, for a game the server - // holds: it has every move already. - gameId: serverHeld ? '' : controller.game.id, - plies: controller.moveList.length, - state: gameOverState, - send: (leaving) => { - const winner = controller.game.termination?.winner - const log = (keepalive: boolean) => - logGameMove( - controller.game.id, - controller.moveList, - controller.moveTimes, - gameOverState, - 'play', - playGameConfig.startFen || - (playGameConfig.practice ? STANDARD_START_FEN : undefined), - winner, - [], - { keepalive }, - ) - - if (leaving) { - log(true).catch(() => undefined) - return - } - - const submitFn = async () => { - const response = await backOff(() => log(false), { jitter: 'full' }) - - if (controller.game.termination) { - if (!playGameConfig.practice) { - safeUpdateRating(response.player_elo, (rating) => - updateRating(rating, response.player_provisional), - ) - } - incrementStats(1, winner == playGameConfig.player ? 1 : 0) - } - } - submitFn() - }, - }) - - // Unlimited and practice games are kept in this browser after each move, - // so they can be continued if the tab is closed; forgotten once over. - useEffect(() => { - // A game the server holds is continued from the server, not from here. - if (serverHeld) return - if (!controller.game.id || !canResume(playGameConfig)) return - if (controller.game.termination) { - clearUnfinishedGame(controller.game.id) - return - } - if (controller.moveList.length === 0) return - saveUnfinishedGame({ - id: controller.game.id, - config: playGameConfig, - moves: controller.moveList, - moveTimes: controller.moveTimes, - whiteClock: controller.whiteClock, - blackClock: controller.blackClock, - savedAt: Date.now(), - }) - }, [ - controller.game.id, - controller.game.termination, - controller.moveList, - controller.moveTimes, - controller.whiteClock, - controller.blackClock, - playGameConfig, - serverHeld, - ]) - - // In a game the server holds, a takeback and extra time (practice games) - // are asked of the server; the board is then drawn again from its state. + // A takeback and extra time (practice games) are asked of the server; the + // board is then drawn again from its state. const practiceRequest = useCallback( (request: (gameId: string) => Promise, redraw: boolean) => { request(id) @@ -412,23 +163,12 @@ export const useVsMaiaPlayController = ( const takeBack = useCallback(() => { clearPremove() - if (serverHeld) { - practiceRequest(takeBackServerGame, true) - return - } - controller.takeBack() - }, [clearPremove, controller.takeBack, serverHeld, practiceRequest]) + if (hasGame) practiceRequest(takeBackServerGame, true) + }, [clearPremove, hasGame, practiceRequest]) - const addTime = useCallback( - (ms: number) => { - if (serverHeld) { - practiceRequest(addTimeServerGame, false) - return - } - controller.addTime(ms) - }, - [controller.addTime, serverHeld, practiceRequest], - ) + const addTime = useCallback(() => { + if (hasGame) practiceRequest(addTimeServerGame, false) + }, [hasGame, practiceRequest]) return { ...controller, diff --git a/src/hooks/useServerGames.ts b/src/hooks/useServerGames.ts deleted file mode 100644 index 254e18f3..00000000 --- a/src/hooks/useServerGames.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { useContext, useEffect, useState } from 'react' -import { AuthContext } from 'src/contexts/AuthContext' -import { serverGamesFor } from 'src/lib/serverGames' - -// How long a page waits for the account request before playing the old way, -// which doesn't need it. -const ACCOUNT_WAIT_MS = 4000 - -/** - * Whether this player's games are held by the server (serverGamesFor): - * undefined while that isn't known yet, and false if the account request - * hasn't answered in time. - */ -export const useServerGames = (): boolean | undefined => { - const { user } = useContext(AuthContext) - const [gaveUp, setGaveUp] = useState(false) - useEffect(() => { - const timeout = setTimeout(() => setGaveUp(true), ACCOUNT_WAIT_MS) - return () => clearTimeout(timeout) - }, []) - return serverGamesFor(user) ?? (gaveUp ? false : undefined) -} diff --git a/src/hooks/useStartConfirmation.test.ts b/src/hooks/useStartConfirmation.test.ts deleted file mode 100644 index 7015d1e2..00000000 --- a/src/hooks/useStartConfirmation.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { act, renderHook } from '@testing-library/react' -import { markAppHydrated } from 'src/components/Common/PageShell' -import { useStartConfirmation } from './useStartConfirmation' - -// In order: until _app marks the app hydrated, a page is one opened by loading -// it; after that, any page is one reached by a click in the site. -describe('useStartConfirmation', () => { - it('asks on a page opened by a link, a bookmark or a refresh, until the visitor confirms', () => { - const { result, rerender } = renderHook(() => useStartConfirmation()) - expect(result.current.mustConfirm).toBe(true) - - act(() => result.current.confirm()) - expect(result.current.mustConfirm).toBe(false) - - // The page's later games start without asking again. - rerender() - expect(result.current.mustConfirm).toBe(false) - }) - - it('keeps asking on that page after the app has hydrated, until confirmed', () => { - const { result } = renderHook(() => useStartConfirmation()) - markAppHydrated() - expect(result.current.mustConfirm).toBe(true) - }) - - it("doesn't ask on a page reached by a click in the site", () => { - markAppHydrated() - const { result } = renderHook(() => useStartConfirmation()) - expect(result.current.mustConfirm).toBe(false) - }) -}) diff --git a/src/hooks/useStartConfirmation.ts b/src/hooks/useStartConfirmation.ts deleted file mode 100644 index 69ef0e78..00000000 --- a/src/hooks/useStartConfirmation.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { useCallback, useState } from 'react' -import { isAppHydrated } from 'src/components/Common/PageShell' - -/** - * Whether a play page has to ask before it starts a game with start_game, - * which resigns the player's game in progress (and rates the loss). - * - * A page opened by loading it (a link, from another site too, a bookmark or a - * refresh) asks: any site can link to /play/maia or /play/hb, and starting at - * once let it make a visitor resign. A page reached by a click in the site - * starts at once, since the visitor has just chosen to play. Once the visitor - * has confirmed, the page's later games start without asking. - * - * Games the server holds (/play/games) don't need this: starting one answers - * with the game in progress instead of resigning it. - */ -export const useStartConfirmation = () => { - // Decided on the page's first render, which for a page opened by loading - // it happens while the app hydrates (src/components/Common/PageShell). - const [openedByPageLoad] = useState( - () => typeof window !== 'undefined' && !isAppHydrated(), - ) - const [confirmed, setConfirmed] = useState(false) - const confirm = useCallback(() => setConfirmed(true), []) - return { mustConfirm: openedByPageLoad && !confirmed, confirm } -} diff --git a/src/lib/serverGames.test.ts b/src/lib/serverGames.test.ts index 05faaaeb..7b05b439 100644 --- a/src/lib/serverGames.test.ts +++ b/src/lib/serverGames.test.ts @@ -9,7 +9,6 @@ import { serverGameConfig, serverGamePage, serverGameStart, - serverGamesFor, serverTermination, } from './serverGames' @@ -188,27 +187,6 @@ describe('a game the server holds', () => { ) }) - it("is the server's decision for each player, once the account request has answered", () => { - expect(serverGamesFor(null)).toBeUndefined() - const guest = { clientId: 'c1', displayName: 'Guest' } - expect(serverGamesFor(guest)).toBe(false) - expect(serverGamesFor({ ...guest, serverGames: false })).toBe(false) - expect(serverGamesFor({ ...guest, serverGames: true })).toBe(true) - }) - - it('can be switched on or off for one browser, whatever the server says', () => { - const guest = { clientId: 'c1', displayName: 'Guest', serverGames: false } - window.localStorage.setItem('maia.serverGames', '1') - expect(serverGamesFor(guest)).toBe(true) - // Known at once: no need to wait for the account request. - expect(serverGamesFor(null)).toBe(true) - window.localStorage.setItem('maia.serverGames', '0') - expect(serverGamesFor({ ...guest, serverGames: true })).toBe(false) - window.localStorage.removeItem('maia.serverGames') - expect(serverGamesFor({ ...guest, serverGames: true })).toBe(true) - expect(serverGamesFor(null)).toBeUndefined() - }) - it('is the game an address asks for when its settings are the same', () => { const asked: PlayGameConfig = { ...config, diff --git a/src/lib/serverGames.ts b/src/lib/serverGames.ts index 3e2b73f1..0079d345 100644 --- a/src/lib/serverGames.ts +++ b/src/lib/serverGames.ts @@ -1,53 +1,12 @@ -import { - Color, - PlayGameConfig, - Termination, - TimeControl, - User, -} from 'src/types' +import { Color, PlayGameConfig, Termination, TimeControl } from 'src/types' import { UnfinishedGame } from 'src/lib/unfinishedGame' import { resignTermination } from 'src/lib/resignation' /** - * Games the server holds (the backend's /play/games): the browser sends each - * of the player's moves and is sent Maia's reply, the clocks and the result. - * Otherwise games are run by the browser and reported to the server, as - * before. - * - * Which it is for a player is the server's decision (a share of players that - * can be changed without a deploy), told in the account request as - * `server_games`. NEXT_PUBLIC_SERVER_GAMES overrides it for a build: '1' is - * everyone, '0' nobody. One browser can override it for itself (see - * browserSetting below). + * Games against Maia are held by the server (the backend's /play/games): the + * browser sends each of the player's moves and is sent Maia's reply, the + * clocks and the result. */ -const BUILD_SETTING = process.env.NEXT_PUBLIC_SERVER_GAMES - -/** - * Whether this player's games are held by the server; undefined until the - * account request has answered (`user` is null until then). - */ -export const serverGamesFor = (user: User | null): boolean | undefined => { - if (BUILD_SETTING === '1') return true - if (BUILD_SETTING === '0') return false - const here = browserSetting() - if (here !== undefined) return here - return user ? !!user.serverGames : undefined -} - -// A browser can be put in or out whatever the server's share says, to try -// the server's games on the live site before the share reaches it (or to -// step out): in the console, localStorage.setItem('maia.serverGames', '1') -// (or '0'; removeItem to follow the server again). -const BROWSER_SETTING_KEY = 'maia.serverGames' -const browserSetting = (): boolean | undefined => { - try { - const value = window.localStorage.getItem(BROWSER_SETTING_KEY) - return value === '1' ? true : value === '0' ? false : undefined - } catch { - // No storage (private mode, or not in a browser): follow the server. - return undefined - } -} export interface ServerClock { white_ms: number diff --git a/src/lib/unfinishedGame.test.ts b/src/lib/unfinishedGame.test.ts deleted file mode 100644 index 29936eae..00000000 --- a/src/lib/unfinishedGame.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { PlayGameConfig } from 'src/types' -import { - UnfinishedGame, - canResume, - clearUnfinishedGame, - loadUnfinishedGame, - sameGameSettings, - saveUnfinishedGame, -} from './unfinishedGame' - -const config = (overrides: Partial = {}): PlayGameConfig => ({ - player: 'white', - timeControl: 'unlimited', - maiaVersion: 'maia_kdd_1500', - playType: 'againstMaia', - isBrain: false, - sampleMoves: true, - ...overrides, -}) - -const game = (overrides: Partial = {}): UnfinishedGame => ({ - id: 'abc', - config: config(), - moves: ['e2e4', 'e7e5'], - moveTimes: [0, 0], - whiteClock: 0, - blackClock: 0, - savedAt: Date.now(), - ...overrides, -}) - -describe('unfinished games', () => { - beforeEach(() => window.localStorage.clear()) - - it('keeps unlimited and practice games only', () => { - expect(canResume(config())).toBe(true) - expect(canResume(config({ timeControl: '5+0', practice: true }))).toBe(true) - expect(canResume(config({ timeControl: '5+0' }))).toBe(false) - expect(canResume(config({ playType: 'handAndBrain' }))).toBe(false) - }) - - it('saves, loads and clears a game', () => { - saveUnfinishedGame(game()) - expect(loadUnfinishedGame()?.id).toBe('abc') - - clearUnfinishedGame('other') - expect(loadUnfinishedGame()?.id).toBe('abc') - - clearUnfinishedGame('abc') - expect(loadUnfinishedGame()).toBeNull() - }) - - it('forgets games that are too old or have no moves', () => { - saveUnfinishedGame(game({ savedAt: Date.now() - 15 * 24 * 3600 * 1000 })) - expect(loadUnfinishedGame()).toBeNull() - - saveUnfinishedGame(game({ moves: [] })) - expect(loadUnfinishedGame()).toBeNull() - }) - - it('matches games by the settings in the address', () => { - expect(sameGameSettings(config(), config({ sampleMoves: false }))).toBe( - true, - ) - expect(sameGameSettings(config(), config({ player: 'black' }))).toBe(false) - expect(sameGameSettings(config(), config({ practice: true }))).toBe(false) - }) -}) diff --git a/src/lib/unfinishedGame.ts b/src/lib/unfinishedGame.ts index 0308daff..26179884 100644 --- a/src/lib/unfinishedGame.ts +++ b/src/lib/unfinishedGame.ts @@ -1,87 +1,17 @@ import { PlayGameConfig } from 'src/types' /** - * The visitor's unfinished game against Maia, kept in this browser so that it - * can be continued after the tab was closed or refreshed. Only unlimited and - * practice games are kept: a rated game with clocks has to be played in one - * sitting (paused clocks would let a player stop to look things up). - * - * The backend still has the game as unfinished (each move is sent to it), so - * a continued game goes on with the same id. Starting another game resigns - * it there, so this is cleared then too. + * A game's moves and clocks as a play page starts from them: the server's + * game as it was when the page got it (serverGameStart in + * src/lib/serverGames.ts), so that the board shows it from its first render. */ export interface UnfinishedGame { id: string config: PlayGameConfig moves: string[] moveTimes: number[] - // Each clock's time left (ms) at the last move; they're paused while away. + // Each clock's time left (ms) at the last move. whiteClock: number blackClock: number savedAt: number } - -const UNFINISHED_GAME_KEY = 'maia-unfinished-game' - -// Older games aren't offered: the backend may well have ended them since -// (any game started elsewhere, on another device, resigns them). -const MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000 - -export const canResume = (config: PlayGameConfig) => - config.playType === 'againstMaia' && - (config.timeControl === 'unlimited' || !!config.practice) - -/** The settings that identify a game in /play/maia's address. */ -const configKey = (config: PlayGameConfig) => - JSON.stringify([ - config.player, - config.maiaVersion, - config.timeControl, - config.startFen || '', - !!config.practice, - ]) - -export const sameGameSettings = (a: PlayGameConfig, b: PlayGameConfig) => - configKey(a) === configKey(b) - -export const loadUnfinishedGame = (): UnfinishedGame | null => { - try { - const stored = window.localStorage.getItem(UNFINISHED_GAME_KEY) - if (!stored) return null - const game = JSON.parse(stored) as UnfinishedGame - const valid = - typeof game?.id === 'string' && - Array.isArray(game.moves) && - game.moves.length > 0 && - Date.now() - game.savedAt < MAX_AGE_MS && - canResume(game.config) - if (!valid) { - window.localStorage.removeItem(UNFINISHED_GAME_KEY) - return null - } - return game - } catch { - return null - } -} - -export const saveUnfinishedGame = (game: UnfinishedGame) => { - try { - window.localStorage.setItem(UNFINISHED_GAME_KEY, JSON.stringify(game)) - } catch { - // Storage can be unavailable (private mode, blocked site data). - } -} - -/** Forgets the kept game (`id`: only if it's that one). */ -export const clearUnfinishedGame = (id?: string) => { - try { - if (id !== undefined) { - const stored = window.localStorage.getItem(UNFINISHED_GAME_KEY) - if (!stored || (JSON.parse(stored) as UnfinishedGame).id !== id) return - } - window.localStorage.removeItem(UNFINISHED_GAME_KEY) - } catch { - // As above. - } -} diff --git a/src/pages/play/hb.tsx b/src/pages/play/hb.tsx index 8f17765a..a7808120 100644 --- a/src/pages/play/hb.tsx +++ b/src/pages/play/hb.tsx @@ -10,7 +10,7 @@ import { useState, } from 'react' -import { MoveRequestError, startGameWithRetry } from 'src/api/play' +import { MoveRequestError } from 'src/api/play' import { trackGameStartFailed } from 'src/lib/analytics' // From 'src/components' itself, not its folders: GameplayInterface takes the // components it renders from there, and in development that file must start @@ -22,7 +22,6 @@ import { GameInProgressModal, GameplayInterface, HandBrainPlayControls, - StartGameConfirmModal, } from 'src/components' import { ModalContext, useTour } from 'src/contexts' import { Color, PlayGameConfig, TimeControl } from 'src/types' @@ -40,8 +39,6 @@ import { serverGamePage, serverGameStart, } from 'src/lib/serverGames' -import { useServerGames } from 'src/hooks/useServerGames' -import { useStartConfirmation } from 'src/hooks/useStartConfirmation' import { useGameInProgressQuestion } from 'src/hooks/useGameInProgressQuestion' import { useQueryBoolean } from 'src/hooks/useQueryBoolean' import { UnfinishedGame } from 'src/lib/unfinishedGame' @@ -174,20 +171,15 @@ const PlayHandBrainPage: NextPage = () => { setPlaySetupModalProps({ ...playGameConfig }) }, [setPlaySetupModalProps, playGameConfig]) - // The game as the server holds it, when it does: started here, or the - // player's game in progress, picked up again. Each new state from the - // server redraws the board from it. - // undefined until the account request has said (see useServerGames). - const serverHeld = useServerGames() - // Opened by a link, a bookmark or a refresh: start_game resigns the game in - // progress, so the visitor is asked before a new game is started. - const { mustConfirm, confirm } = useStartConfirmation() - const [askingToStart, setAskingToStart] = useState(false) + // The game as the server holds it (src/lib/serverGames.ts): started here, + // or the player's game in progress, picked up again. Each new state from + // the server redraws the board from it; `resumeGame` is its moves and + // clocks, to show at once. const [serverGame, setServerGame] = useState() const [resumeGame, setResumeGame] = useState() const [serverGameVersion, setServerGameVersion] = useState(0) - // A game the server holds: opened for a game while another is in progress, - // the visitor is asked which to play. + // Opened for a game while another is in progress, the visitor is asked + // which to play. const inProgressQuestion = useGameInProgressQuestion() const hadGame = useRef(false) @@ -206,8 +198,6 @@ const PlayHandBrainPage: NextPage = () => { return } - // No game is started until it is known who runs this player's games. - if (serverHeld === undefined) return if (id) hadGame.current = true let canceled = false @@ -219,9 +209,9 @@ const PlayHandBrainPage: NextPage = () => { return config } - // The address has a game the server holds but this page doesn't have its - // state (back or forward in the browser): ask for it. - if (serverHeld && typeof id === 'string' && serverGame?.game_id !== id) { + // The address has a game but this page doesn't have its state (back or + // forward in the browser): ask the server for it. + if (typeof id === 'string' && serverGame?.game_id !== id) { fetchServerGame(id) .then((game) => { if (!canceled) takeServerGame(game) @@ -232,7 +222,7 @@ const PlayHandBrainPage: NextPage = () => { } } - // A game the server holds is created there. If the player already has a + // The game is created on the server. If the player already has a // game in progress the server answers with that one, which is picked up // where it was (on the play page, if it is a game against Maia alone): // at once when the page was opened to come back to it, and otherwise if @@ -301,7 +291,7 @@ const PlayHandBrainPage: NextPage = () => { ) } - if (!id && serverHeld) { + if (!id) { setServerGame(undefined) setResumeGame(undefined) startServerGame() @@ -310,80 +300,21 @@ const PlayHandBrainPage: NextPage = () => { inProgressQuestion.close() } } - - async function fetchGameId() { - let response - try { - response = await startGameWithRetry( - playGameConfig.player, - playGameConfig.maiaVersion, - playGameConfig.isBrain ? 'brain' : 'hand', - playGameConfig.sampleMoves, - playGameConfig.timeControl, - playGameConfig.maiaPartnerVersion, - ) - } catch (e) { - console.error(e) - trackGameStartFailed( - playGameConfig.isBrain ? 'brain' : 'hand', - e, - e instanceof MoveRequestError ? e.status : undefined, - ) - router.push('/401') - return - } - const newGameId = response.gameId - - if (!canceled) { - router.replace( - { - pathname: '/play/hb', - query: { - id: newGameId, - ...playGameConfig, - }, - }, - { - pathname: '/play/hb', - query: { - // We don't show the game ID in the address bar - // so that if the page is manually refreshed - // the old game ID is not persisted - ...playGameConfig, - }, - }, - ) - } - } - - if (!id) { - if (mustConfirm) { - setAskingToStart(true) - return - } - fetchGameId() - - return () => { - canceled = true - } - } }, [ id, - mustConfirm, playGameConfig, router, setPlaySetupModalProps, startFen, startFenCheck, - serverHeld, ]) - // A game the server holds is shown once its state is here. + // The game is shown once its state is here. const ready = router.isReady && !!id && - (serverHeld === false || - (serverGame !== undefined && serverGame.game_id === id)) + serverGame !== undefined && + serverGame.game_id === id return ( <> @@ -403,8 +334,8 @@ const PlayHandBrainPage: NextPage = () => { playAgain={playAgain} simulateMaiaTime={simulateMaiaTime} setSimulateMaiaTime={setSimulateMaiaTime} - resume={serverHeld ? resumeGame : undefined} - serverGame={serverHeld ? serverGame : undefined} + resume={resumeGame} + serverGame={serverGame} onServerResync={(game) => { const config = serverGameConfig(game, playGameConfig) setResumeGame(serverGameStart(game, config)) @@ -414,14 +345,6 @@ const PlayHandBrainPage: NextPage = () => { /> )} - { - setAskingToStart(false) - confirm() - }} - onCancel={() => router.push('/play')} - /> = ({ setSimulateMaiaTime={setSimulateMaiaTime} practice={controller.practice} takeBack={controller.canTakeBack ? controller.takeBack : undefined} - addTime={ - controller.canAddTime - ? () => controller.addTime(PRACTICE_EXTRA_TIME_MS) - : undefined - } + addTime={controller.canAddTime ? controller.addTime : undefined} />
{sharing && challengeRound ? ( @@ -404,36 +387,25 @@ const PlayMaiaPage: NextPage = () => { }, [initialTourCheck, startTour]) // The game is shown from the moment it is asked for, its board at the - // starting position, and takes moves once start_game has answered with its - // id. A new game (Play again) starts with a new PlayMaia. + // starting position, and takes moves once the server has answered with the + // game. A new game (Play again) starts with a new PlayMaia. const [gameKey, setGameKey] = useState(0) const hadGame = useRef(false) - // A game with these settings left unfinished in this browser (closed tab, - // refresh, or Continue in the setup dialog) is continued rather than a new - // one started, which would resign it. Decided each time a game is needed; - // the board is drawn again with its moves (PlayMaia's key). + // The game as the server holds it (src/lib/serverGames.ts): started here, + // or the player's game in progress, picked up again (a refresh, another + // device). Each new state from the server redraws the board from it + // (PlayMaia's key); `resumeGame` is its moves and clocks, to show at once. const [resumeGame, setResumeGame] = useState() - // The game as the server holds it, in a game it holds: started here, or - // the player's game in progress, picked up again (a refresh, another - // device). Each new state from the server redraws the board from it. const [serverGame, setServerGame] = useState() const [serverGameVersion, setServerGameVersion] = useState(0) - // undefined until the account request has said (see useServerGames). A - // World Championship challenge is always the server's: soup D plays it - // there, whoever the player. - const serverShare = useServerGames() + // A World Championship challenge: soup D plays it, whoever the player. const wchChallengeId = typeof challengeId === 'string' && challengeFor(challengeId) ? challengeId : undefined - const serverHeld = wchChallengeId ? true : serverShare - // Opened by a link, a bookmark or a refresh: start_game resigns the game in - // progress, so the visitor is asked before a new game is started. - const { mustConfirm, confirm } = useStartConfirmation() - const [askingToStart, setAskingToStart] = useState(false) - // A game the server holds: opened for a game while another is in progress, - // the visitor is asked which to play. + // Opened for a game while another is in progress, the visitor is asked + // which to play. const inProgressQuestion = useGameInProgressQuestion() useEffect(() => { @@ -459,13 +431,11 @@ const PlayMaiaPage: NextPage = () => { router.replace({ pathname: '/play', query }) return } - // No game is started until it is known who runs this player's games. - if (serverHeld === undefined) return if (id) { hadGame.current = true - // The address has a game the server holds but this page doesn't have - // its state (back or forward in the browser): ask for it. - if (serverHeld && typeof id === 'string' && serverGame?.game_id !== id) { + // The address has a game but this page doesn't have its state (back or + // forward in the browser): ask the server for it. + if (typeof id === 'string' && serverGame?.game_id !== id) { let stale = false fetchServerGame(id) .then((game) => { @@ -518,44 +488,8 @@ const PlayMaiaPage: NextPage = () => { }, ) - async function fetchGameId() { - let response - try { - const start = () => - startGameWithRetry( - playGameConfig.player, - playGameConfig.maiaVersion, - 'play', - playGameConfig.sampleMoves, - playGameConfig.timeControl, - undefined, - ) - // The game the setup dialog started as the visitor chose, if it was - // this one (src/api/play.ts); if that failed, one more try here. - const early = takeEarlyGame( - playGameConfig.player, - playGameConfig.maiaVersion, - playGameConfig.sampleMoves, - playGameConfig.timeControl, - ) - response = await (early ? early.catch(start) : start()) - } catch (e) { - console.error(e) - trackGameStartFailed( - 'play', - e, - e instanceof MoveRequestError ? e.status : undefined, - ) - router.push('/401') - return - } - const newGameId = response.gameId - - if (!canceled) showGame(newGameId) - } - - // A game the server holds: it is created there, with Maia's first move - // if Maia moves first. If the player already has a game in progress the + // The game is created on the server, with Maia's first move if Maia + // moves first. If the player already has a game in progress the // server answers with that one, which is picked up where it was: at // once when the page was opened to come back to it, and otherwise if // the visitor says so, rather than resign it for the game asked for @@ -623,40 +557,18 @@ const PlayMaiaPage: NextPage = () => { showGame(game.game_id, config) } - if (!id && serverHeld) { - setServerGame(undefined) - setResumeGame(undefined) - startServerGame() - - return () => { - canceled = true - inProgressQuestion.close() - } - } + setServerGame(undefined) + setResumeGame(undefined) + startServerGame() - if (!id) { - const unfinished = loadUnfinishedGame() - if (unfinished && sameGameSettings(unfinished.config, playGameConfig)) { - setResumeGame(unfinished) - showGame(unfinished.id) - return - } - setResumeGame(undefined) - if (mustConfirm) { - setAskingToStart(true) - return - } - fetchGameId() - - return () => { - canceled = true - } + return () => { + canceled = true + inProgressQuestion.close() } }, [ challengeId, forcedColor, id, - mustConfirm, modalSubtitle, modalTitle, playGameConfig, @@ -664,7 +576,6 @@ const PlayMaiaPage: NextPage = () => { router, startFen, startFenCheck, - serverHeld, ]) return ( @@ -684,20 +595,13 @@ const PlayMaiaPage: NextPage = () => { // must have the game from its first render, to play Maia's first // move when Maia moves first. key={`${gameKey}-${resumeGame?.id ?? ''}-${serverGameVersion}-${ - serverHeld && serverGame?.game_id === id ? 'held' : '' + serverGame?.game_id === id ? 'held' : '' }`} - // A game the server holds takes no moves until its state is here. - id={ - typeof id === 'string' && - (serverHeld === false || serverGame?.game_id === id) - ? id - : '' - } + // The game takes no moves until its state is here. + id={typeof id === 'string' && serverGame?.game_id === id ? id : ''} playGameConfig={playGameConfig} resume={resumeGame} - serverGame={ - serverHeld && serverGame?.game_id === id ? serverGame : undefined - } + serverGame={serverGame?.game_id === id ? serverGame : undefined} onServerResync={(game) => { const config = serverGameConfig(game, playGameConfig) setResumeGame(serverGameStart(game, config)) @@ -731,14 +635,6 @@ const PlayMaiaPage: NextPage = () => { ) : ( )} - { - setAskingToStart(false) - confirm() - }} - onCancel={() => router.push('/play')} - />