feat(hint): persist the vs_ai idle-hint wait (wall-clock + read sanitiser)
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Has been skipped
CI / integration (pull_request) Has been skipped
CI / ui (pull_request) Successful in 1m28s
CI / conformance (pull_request) Successful in 11s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m44s
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Has been skipped
CI / integration (pull_request) Has been skipped
CI / ui (pull_request) Successful in 1m28s
CI / conformance (pull_request) Successful in 11s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m44s
Per the owner's call, the idle-hint gate now PERSISTS across leaving and reopening the app, instead of the session-scoped monotonic clock: the unlock is a wall-clock instant (hintUnlockAtMs) stamped from the robot's reply, stored on the local record, carried on the game view + the opponent_moved move delta, and read through a sanitiser that caps it at now + the window. So: - the wait survives a relaunch (a stuck turn is not forgotten); - a device clock set BACK cannot freeze the gate (the cap bounds the remaining to the window and self-heals on the next read); - a clock set FORWARD just opens the hint early -- accepted as harmless for a solo game. - lib/hints.ts hintGateRemainingMs now takes the unlock instant + clamps to the window. - localgame: re-add hintUnlockAtMs to the record/meta; stamp it off the robot's reply; sanitise on read (a shared hintUnlock helper feeds stateView + the opponent_moved event). - gamedelta + PushEvent: the move delta carries hintUnlockAtMs so the view stays fresh. - Game.svelte: hintUnlockAt derives from the view; the tick + lock + toast unchanged. - offline.spec.ts: also assert the lock survives a reload (the wait persisted). - Docs FUNCTIONAL(+_ru)/ARCHITECTURE updated (persist + sanitiser, not monotonic-resets).
This commit is contained in:
@@ -1253,10 +1253,12 @@ device-local games** (reconstructed by replaying the IndexedDB move journal) and
|
|||||||
creates one through the in-browser engine — the same game screen then drives it, the robot replying
|
creates one through the in-browser engine — the same game screen then drives it, the robot replying
|
||||||
locally; online-only affordances (the Stats tab, the friend/random options in New Game) are disabled
|
locally; online-only affordances (the Stats tab, the friend/random options in New Game) are disabled
|
||||||
or hidden. A local `vs_ai` hint is unlimited and wallet-free but idle-gated (unlocked ~30 min into a
|
or hidden. A local `vs_ai` hint is unlimited and wallet-free but idle-gated (unlocked ~30 min into a
|
||||||
stuck turn); the gate is enforced **client-side against a monotonic clock** (`performance.now()`,
|
stuck turn). The gate is a **persisted wall-clock unlock instant** (`hintUnlockAtMs` on the record +
|
||||||
`lib/hints`), never a wall-clock timestamp — a device clock the player controls must not be able to
|
the game view, stamped from the robot's reply, carried on the move delta), so the wait survives a
|
||||||
open or freeze it, so the wait is session-scoped (a reload restarts it). An online `vs_ai` game will
|
relaunch — but it is **sanitised on read** (capped at `now + window`, `lib/hints` + `source.ts`) so a
|
||||||
gate the same way but from the server's clock (a follow-up). To have data ready before the switch, the **Profile advertises the current dictionary
|
device clock the player sets **back** cannot push the unlock away and freeze the gate; a clock set
|
||||||
|
**forward** merely opens the hint early, harmless for a solo game. An online `vs_ai` game will gate the
|
||||||
|
same way but from the server's clock (a follow-up). To have data ready before the switch, the **Profile advertises the current dictionary
|
||||||
version per variant** (`dict_versions`,
|
version per variant** (`dict_versions`,
|
||||||
filled from the registry on the existing cold-start profile request — no extra round-trip), and an
|
filled from the registry on the existing cold-start profile request — no extra round-trip), and an
|
||||||
eligible installed PWA (standalone web + confirmed email) **background-preloads** those dictionaries
|
eligible installed PWA (standalone web + confirmed email) **background-preloads** those dictionaries
|
||||||
|
|||||||
+5
-3
@@ -220,9 +220,11 @@ personal hint wallet once the per-game allowance is spent. Against the robot
|
|||||||
anti-frustration aid: one unlocks only after the player has been **stuck ~30 minutes
|
anti-frustration aid: one unlocks only after the player has been **stuck ~30 minutes
|
||||||
on a turn** (timed from the robot's last move; the very first move, before the robot
|
on a turn** (timed from the robot's last move; the very first move, before the robot
|
||||||
has played, is exempt). While gated the hint button carries a small **🔒 lock** and a
|
has played, is exempt). While gated the hint button carries a small **🔒 lock** and a
|
||||||
tap shows how long remains; the lock lifts live at the mark. The wait uses a steady
|
tap shows how long remains; the lock lifts live at the mark. The wait **persists across
|
||||||
in-app timer, not the device clock — changing the clock cannot open or freeze it
|
leaving and reopening the app**, so a stuck turn is not forgotten. It stays robust to a
|
||||||
(though a reload restarts the wait). The game ends when the
|
device clock change: the remaining is capped at the window, so a clock set back cannot
|
||||||
|
freeze it, and a clock set forward merely opens the hint early — harmless in a solo game.
|
||||||
|
The game ends when the
|
||||||
bag empties and a player clears their rack, after 6 consecutive scoreless turns,
|
bag empties and a player clears their rack, after 6 consecutive scoreless turns,
|
||||||
by resignation, or by the per-game move timeout (5 minutes to 24 hours, default
|
by resignation, or by the per-game move timeout (5 minutes to 24 hours, default
|
||||||
24 hours): a missed turn auto-resigns, except while the player is inside their
|
24 hours): a missed turn auto-resigns, except while the player is inside their
|
||||||
|
|||||||
@@ -227,9 +227,10 @@ e-mail) либо ввод фразы. Активные игры форфейтя
|
|||||||
анти-фрустрация: подсказка открывается, только когда игрок **застрял на ходу ~30 минут**
|
анти-фрустрация: подсказка открывается, только когда игрок **застрял на ходу ~30 минут**
|
||||||
(отсчёт от последнего хода робота; самый первый ход, до хода робота, исключён). Пока гейт
|
(отсчёт от последнего хода робота; самый первый ход, до хода робота, исключён). Пока гейт
|
||||||
закрыт, кнопка подсказки несёт маленький **🔒 замок**, а тап показывает, сколько осталось;
|
закрыт, кнопка подсказки несёт маленький **🔒 замок**, а тап показывает, сколько осталось;
|
||||||
замок снимается вживую в нужный момент. Отсчёт идёт по ровному внутриигровому таймеру, а не
|
замок снимается вживую в нужный момент. Отсчёт **переживает выход и повторный вход в
|
||||||
по системным часам — их перевод не откроет и не заморозит гейт (но перезагрузка отсчёт
|
приложение**, так что застрявший ход не забывается. И он устойчив к переводу часов: остаток
|
||||||
начинает заново). Партия
|
ограничен окном, поэтому перевод назад не заморозит гейт, а перевод вперёд просто откроет
|
||||||
|
подсказку раньше — безвредно в соло-игре. Партия
|
||||||
завершается, когда мешок пуст и игрок выложил стойку, после 6 подряд бесплодных
|
завершается, когда мешок пуст и игрок выложил стойку, после 6 подряд бесплодных
|
||||||
ходов, по сдаче, либо по таймауту хода (от 5 минут до 24 часов, дефолт 24 часа):
|
ходов, по сдаче, либо по таймауту хода (от 5 минут до 24 часов, дефолт 24 часа):
|
||||||
пропущенный ход означает авто-сдачу, кроме как когда игрок внутри своего
|
пропущенный ход означает авто-сдачу, кроме как когда игрок внутри своего
|
||||||
|
|||||||
@@ -86,5 +86,8 @@ test.describe('offline mode', () => {
|
|||||||
await page.reload();
|
await page.reload();
|
||||||
await expect(page.locator('[data-cell]').first()).toBeVisible();
|
await expect(page.locator('[data-cell]').first()).toBeVisible();
|
||||||
await expect(page.locator('[data-cell].filled')).toHaveCount(filled);
|
await expect(page.locator('[data-cell].filled')).toHaveCount(filled);
|
||||||
|
// The idle-hint gate is persisted (a wall-clock unlock time), so the 🔒 survives the reload —
|
||||||
|
// the wait was not reset by relaunching.
|
||||||
|
await expect(page.locator('.lock')).toBeVisible();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+13
-30
@@ -168,35 +168,19 @@
|
|||||||
// hint was spent in another game (see lib/hints).
|
// hint was spent in another game (see lib/hints).
|
||||||
const hintCount = $derived(hintsLeft(view, app.profile?.hintBalance ?? 0));
|
const hintCount = $derived(hintsLeft(view, app.profile?.hintBalance ?? 0));
|
||||||
// A vs_ai game's hint is unlimited and wallet-free, but idle-gated (an anti-frustration aid: it
|
// A vs_ai game's hint is unlimited and wallet-free, but idle-gated (an anti-frustration aid: it
|
||||||
// unlocks only after the player has been stuck ~30 min on a turn). The wait is measured with a
|
// unlocks only after the player has been stuck ~30 min on a turn). The unlock is a persisted
|
||||||
// MONOTONIC clock (performance.now()), never a wall-clock timestamp — a device clock change (by the
|
// wall-clock instant carried on the game view (`hintUnlockAtMs`, stamped by the source off the
|
||||||
// player or an auto-sync) must not open or freeze the gate. hintGateStart is that clock when the
|
// robot's reply and kept fresh by the move delta), so the wait survives leaving and reopening the
|
||||||
// current turn's wait began (null = open: the human's first move, or the robot's turn); monoNow
|
// app. It is sanitised on read (source + lib/hints cap it at now + the window) so a device clock
|
||||||
// ticks so the 🔒 lifts live at the mark. A reload restarts the wait — the monotonic clock is
|
// set BACK cannot freeze the gate; a clock set forward just opens the hint early, harmless for a
|
||||||
// session-scoped, and there is no tamper-proof way to carry idle time across a relaunch.
|
// solo game. `now` ticks so the 🔒 lifts live at the mark. 0 = open (the human's first move).
|
||||||
let hintGateStart = $state<number | null>(null);
|
let now = $state(Date.now());
|
||||||
let hintArmedFor = -1; // the moveCount the current wait was armed for (plain: not a reactive dep)
|
const hintUnlockAt = $derived(view?.game.vsAi ? (view.hintUnlockAtMs ?? 0) : 0);
|
||||||
let monoNow = $state(performance.now());
|
const hintRemaining = $derived(hintGateRemainingMs(hintUnlockAt, now));
|
||||||
const hintRemaining = $derived(view?.game.vsAi ? hintGateRemainingMs(hintGateStart, monoNow) : 0);
|
|
||||||
const hintGated = $derived(hintRemaining > 0);
|
const hintGated = $derived(hintRemaining > 0);
|
||||||
// Arm the wait when it becomes the human's turn after the robot has moved; a human-first opening
|
|
||||||
// (no move yet, moveCount 0) is open at once. Re-arms only when the turn actually changes.
|
|
||||||
$effect(() => {
|
|
||||||
const mc = view?.game.moveCount ?? 0;
|
|
||||||
if (!view?.game.vsAi || !isMyTurn) {
|
|
||||||
hintGateStart = null;
|
|
||||||
hintArmedFor = -1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (hintArmedFor !== mc) {
|
|
||||||
hintArmedFor = mc;
|
|
||||||
hintGateStart = mc === 0 ? null : performance.now();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
// Tick the monotonic clock while a vs_ai game is open, so the gate re-evaluates and unlocks live.
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (!view?.game.vsAi) return;
|
if (!view?.game.vsAi) return;
|
||||||
const iv = setInterval(() => (monoNow = performance.now()), 10_000);
|
const iv = setInterval(() => (now = Date.now()), 10_000);
|
||||||
return () => clearInterval(iv);
|
return () => clearInterval(iv);
|
||||||
});
|
});
|
||||||
// RACK_SIZE mirrors the engine's rules.RackSize (7 for every current variant). The exchange
|
// RACK_SIZE mirrors the engine's rules.RackSize (7 for every current variant). The exchange
|
||||||
@@ -361,7 +345,7 @@
|
|||||||
// While composing, reload so a draft overlapping the new move is reconciled; otherwise apply
|
// While composing, reload so a draft overlapping the new move is reconciled; otherwise apply
|
||||||
// the move as a delta with no fetch.
|
// the move as a delta with no fetch.
|
||||||
if (placement.pending.length > 0) void load();
|
if (placement.pending.length > 0) void load();
|
||||||
else applyDelta(applyMoveDelta(cacheSnapshot(), { move: e.move, game: e.game, bagLen: e.bagLen }));
|
else applyDelta(applyMoveDelta(cacheSnapshot(), { move: e.move, game: e.game, bagLen: e.bagLen, hintUnlockAtMs: e.hintUnlockAtMs }));
|
||||||
} else if (e.kind === 'your_turn' && e.gameId === id) {
|
} else if (e.kind === 'your_turn' && e.gameId === id) {
|
||||||
// The opponent_moved delta carries the new state; your_turn only confirms the turn. Refetch
|
// The opponent_moved delta carries the new state; your_turn only confirms the turn. Refetch
|
||||||
// only if we missed the move (our cached count trails the event's).
|
// only if we missed the move (our cached count trails the event's).
|
||||||
@@ -887,10 +871,9 @@
|
|||||||
}
|
}
|
||||||
async function doHint() {
|
async function doHint() {
|
||||||
// vs_ai: the idle gate replaces the wallet. While it is still closed, a tap only explains when the
|
// vs_ai: the idle gate replaces the wallet. While it is still closed, a tap only explains when the
|
||||||
// hint unlocks (no wallet is ever spent) — matching the 🔒 badge. Measured fresh off the monotonic
|
// hint unlocks (no wallet is ever spent) — matching the 🔒 badge. Measured fresh at tap time.
|
||||||
// clock at tap time.
|
|
||||||
if (view?.game.vsAi) {
|
if (view?.game.vsAi) {
|
||||||
const remaining = hintGateRemainingMs(hintGateStart, performance.now());
|
const remaining = hintGateRemainingMs(hintUnlockAt, Date.now());
|
||||||
if (remaining > 0) {
|
if (remaining > 0) {
|
||||||
showToast(t('game.hintLockedIn', { n: hintLockMinutes(remaining) }), 'info');
|
showToast(t('game.hintLockedIn', { n: hintLockMinutes(remaining) }), 'info');
|
||||||
return;
|
return;
|
||||||
|
|||||||
+10
-2
@@ -11,6 +11,9 @@ export interface MoveDelta {
|
|||||||
move?: MoveRecord;
|
move?: MoveRecord;
|
||||||
game?: GameView;
|
game?: GameView;
|
||||||
bagLen: number;
|
bagLen: number;
|
||||||
|
/** For a vs_ai game, the refreshed idle-hint unlock instant (the robot's reply re-arms the gate),
|
||||||
|
* so the cached view stays current without a refetch; absent leaves the prior value. */
|
||||||
|
hintUnlockAtMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -50,7 +53,12 @@ export function applyMoveDelta(cached: CachedGame | undefined, d: MoveDelta): De
|
|||||||
if (next > have + 1) return { refetch: true }; // a gap — an intermediate move was missed
|
if (next > have + 1) return { refetch: true }; // a gap — an intermediate move was missed
|
||||||
// The actor's own move changed their rack (a draw), which opponent_moved does not carry.
|
// The actor's own move changed their rack (a draw), which opponent_moved does not carry.
|
||||||
if (d.move.player === cached.view.seat) return { refetch: true };
|
if (d.move.player === cached.view.seat) return { refetch: true };
|
||||||
const view: StateView = { ...cached.view, game: d.game, bagLen: d.bagLen };
|
const view: StateView = {
|
||||||
|
...cached.view,
|
||||||
|
game: d.game,
|
||||||
|
bagLen: d.bagLen,
|
||||||
|
hintUnlockAtMs: d.hintUnlockAtMs ?? cached.view.hintUnlockAtMs,
|
||||||
|
};
|
||||||
return { cache: { view, moves: [...cached.moves, d.move] }, refetch: false };
|
return { cache: { view, moves: [...cached.moves, d.move] }, refetch: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,7 +87,7 @@ export function applyGameOver(cached: CachedGame | undefined, game: GameView | u
|
|||||||
*/
|
*/
|
||||||
export function advanceCached(cached: CachedGame | undefined, e: PushEvent): CachedGame | undefined {
|
export function advanceCached(cached: CachedGame | undefined, e: PushEvent): CachedGame | undefined {
|
||||||
if (e.kind === 'opponent_moved') {
|
if (e.kind === 'opponent_moved') {
|
||||||
return applyMoveDelta(cached, { move: e.move, game: e.game, bagLen: e.bagLen }).cache;
|
return applyMoveDelta(cached, { move: e.move, game: e.game, bagLen: e.bagLen, hintUnlockAtMs: e.hintUnlockAtMs }).cache;
|
||||||
}
|
}
|
||||||
if (e.kind === 'game_over') return applyGameOver(cached, e.game).cache;
|
if (e.kind === 'game_over') return applyGameOver(cached, e.game).cache;
|
||||||
if (e.kind === 'opponent_joined' && e.state) return applyOpponentJoined(cached, e.state);
|
if (e.kind === 'opponent_joined' && e.state) return applyOpponentJoined(cached, e.state);
|
||||||
|
|||||||
@@ -31,19 +31,25 @@ describe('hintsLeft', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('hintGateRemainingMs (the vs_ai idle-hint gate, monotonic)', () => {
|
describe('hintGateRemainingMs (the vs_ai idle-hint gate)', () => {
|
||||||
it('is 0 when the gate is open — a null start (the human first move, or a non-gated game)', () => {
|
it('is 0 when the gate is open — no unlock time (the human first move, or a non-gated game)', () => {
|
||||||
expect(hintGateRemainingMs(null, 5000, 1000)).toBe(0);
|
expect(hintGateRemainingMs(undefined, 5000, 1000)).toBe(0);
|
||||||
|
expect(hintGateRemainingMs(0, 5000, 1000)).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('is 0 once the idle window has fully elapsed', () => {
|
it('is 0 once the unlock instant has passed (the gate is open)', () => {
|
||||||
expect(hintGateRemainingMs(0, 1000, 1000)).toBe(0);
|
expect(hintGateRemainingMs(1000, 1000, 1000)).toBe(0);
|
||||||
expect(hintGateRemainingMs(0, 1500, 1000)).toBe(0);
|
expect(hintGateRemainingMs(1000, 1500, 1000)).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('counts down the monotonic time remaining while still gated (only the delta matters)', () => {
|
it('is the wall-clock time remaining while still gated', () => {
|
||||||
expect(hintGateRemainingMs(0, 400, 1000)).toBe(600);
|
expect(hintGateRemainingMs(1000, 400, 1000)).toBe(600);
|
||||||
expect(hintGateRemainingMs(1000, 1400, 1000)).toBe(600);
|
});
|
||||||
|
|
||||||
|
it('clamps to the window, so a clock set back cannot freeze the gate above the window', () => {
|
||||||
|
// now shoved far into the past (device clock moved back): the raw remaining would exceed the
|
||||||
|
// window, but the cap keeps it at the window so the wait stays bounded and self-heals.
|
||||||
|
expect(hintGateRemainingMs(1000, -100_000, 1000)).toBe(1000);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+13
-9
@@ -30,19 +30,23 @@ export const HINT_GATE_MS = 30 * 60 * 1000;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* hintGateRemainingMs returns how long (in milliseconds) until a vs_ai game's idle hint unlocks — 0
|
* hintGateRemainingMs returns how long (in milliseconds) until a vs_ai game's idle hint unlocks — 0
|
||||||
* once it is available. It is measured from a MONOTONIC clock (performance.now()), never a wall-clock
|
* once it is available. hintUnlockAtMs is the wall-clock instant the hint opens (the robot's last
|
||||||
* timestamp, so a device clock change — by the user or an auto-sync — can neither open nor freeze the
|
* move plus the idle window), persisted so the wait survives leaving and reopening the app; 0 or
|
||||||
* gate. gateStartMono is the performance.now() captured when the current turn's wait began; null
|
* undefined means the gate is open (the human's first move, or a non-gated game).
|
||||||
* means the gate is open (the human's first move, or not a gated game). The vs_ai hint is unlimited
|
*
|
||||||
* and wallet-free; this idle gate is an anti-frustration aid that unlocks only after a stuck turn.
|
* The result is CLAMPED to the window. A wall-clock timestamp is the only way to carry idle time
|
||||||
|
* across an app relaunch, but a device clock the player changes (or an auto-sync) could push the
|
||||||
|
* unlock far into the future and freeze the gate; capping the remaining at the window means the wait
|
||||||
|
* is never longer than intended and self-heals (the caller re-reads a sanitised value on load). A
|
||||||
|
* clock moved forward simply opens the hint early — harmless for this solo anti-frustration aid.
|
||||||
*/
|
*/
|
||||||
export function hintGateRemainingMs(
|
export function hintGateRemainingMs(
|
||||||
gateStartMono: number | null,
|
hintUnlockAtMs: number | undefined,
|
||||||
monoNow: number,
|
nowMs: number,
|
||||||
gateMs: number = HINT_GATE_MS,
|
gateMs: number = HINT_GATE_MS,
|
||||||
): number {
|
): number {
|
||||||
if (gateStartMono === null) return 0;
|
if (!hintUnlockAtMs) return 0;
|
||||||
return Math.max(0, gateMs - (monoNow - gateStartMono));
|
return Math.min(gateMs, Math.max(0, hintUnlockAtMs - nowMs));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** hintLockMinutes rounds a remaining-milliseconds gap up to whole minutes for the "available in N
|
/** hintLockMinutes rounds a remaining-milliseconds gap up to whole minutes for the "available in N
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ function makeGame(seed: bigint): LocalGame {
|
|||||||
return new LocalGame({ variant: 'scrabble_en', version: 'sample', seed, players: 2, dawg, multipleWords: true });
|
return new LocalGame({ variant: 'scrabble_en', version: 'sample', seed, players: 2, dawg, multipleWords: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
const meta = { id: 'g1', seats, createdAtUnix: 1, updatedAtUnix: 2 };
|
const meta = { id: 'g1', seats, createdAtUnix: 1, updatedAtUnix: 2, hintUnlockAtMs: 0 };
|
||||||
|
|
||||||
describe('local game serialize + replay', () => {
|
describe('local game serialize + replay', () => {
|
||||||
it('reconstructs a mid-game position by replay', () => {
|
it('reconstructs a mid-game position by replay', () => {
|
||||||
|
|||||||
@@ -38,6 +38,11 @@ export interface LocalGameRecord {
|
|||||||
status: 'active' | 'finished';
|
status: 'active' | 'finished';
|
||||||
createdAtUnix: number;
|
createdAtUnix: number;
|
||||||
updatedAtUnix: number;
|
updatedAtUnix: number;
|
||||||
|
/** Wall-clock ms at which the vs_ai idle hint unlocks (the robot's last move + the window), or 0
|
||||||
|
* while open (no robot move yet). Persisted so the wait survives leaving and reopening the app;
|
||||||
|
* read through a sanitiser (cap at now + window) so a device clock set back cannot freeze it —
|
||||||
|
* see lib/hints. */
|
||||||
|
hintUnlockAtMs: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The record fields the caller owns (the engine supplies the rest). */
|
/** The record fields the caller owns (the engine supplies the rest). */
|
||||||
@@ -46,6 +51,7 @@ export interface RecordMeta {
|
|||||||
seats: Seat[];
|
seats: Seat[];
|
||||||
createdAtUnix: number;
|
createdAtUnix: number;
|
||||||
updatedAtUnix: number;
|
updatedAtUnix: number;
|
||||||
|
hintUnlockAtMs: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -67,6 +73,7 @@ export function serializeGame(game: LocalGame, meta: RecordMeta): LocalGameRecor
|
|||||||
status: game.isOver ? 'finished' : 'active',
|
status: game.isOver ? 'finished' : 'active',
|
||||||
createdAtUnix: meta.createdAtUnix,
|
createdAtUnix: meta.createdAtUnix,
|
||||||
updatedAtUnix: meta.updatedAtUnix,
|
updatedAtUnix: meta.updatedAtUnix,
|
||||||
|
hintUnlockAtMs: meta.hintUnlockAtMs,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { serializeGame, replayGame, type LocalGameRecord, type Seat as LocalSeat
|
|||||||
import { getLocalGame, saveLocalGame, listLocalGames, deleteLocalGame } from './store';
|
import { getLocalGame, saveLocalGame, listLocalGames, deleteLocalGame } from './store';
|
||||||
import { RULESETS } from './ruleset';
|
import { RULESETS } from './ruleset';
|
||||||
import { getDawg } from '../dict';
|
import { getDawg } from '../dict';
|
||||||
|
import { HINT_GATE_MS } from '../hints';
|
||||||
import { LOCAL_ID_PREFIX, isLocalGameId } from './id';
|
import { LOCAL_ID_PREFIX, isLocalGameId } from './id';
|
||||||
import { decide } from '../robot/strategy';
|
import { decide } from '../robot/strategy';
|
||||||
import { GatewayError, type PlacedTile } from '../client';
|
import { GatewayError, type PlacedTile } from '../client';
|
||||||
@@ -120,6 +121,7 @@ export class LocalSource implements GameLoopSource {
|
|||||||
seats: opts.seats.map((s) => ({ kind: s.kind, name: s.name, accountId: s.accountId })),
|
seats: opts.seats.map((s) => ({ kind: s.kind, name: s.name, accountId: s.accountId })),
|
||||||
createdAtUnix: now,
|
createdAtUnix: now,
|
||||||
updatedAtUnix: now,
|
updatedAtUnix: now,
|
||||||
|
hintUnlockAtMs: 0, // no robot move yet: a human-first opening's hint is open at once
|
||||||
});
|
});
|
||||||
const entry: Live = { game, record };
|
const entry: Live = { game, record };
|
||||||
this.live.set(opts.id, entry);
|
this.live.set(opts.id, entry);
|
||||||
@@ -277,15 +279,20 @@ export class LocalSource implements GameLoopSource {
|
|||||||
else if (dec.kind === 'exchange' && g.bagLength >= RULESETS[entry.record.variant].rackSize) out.push(g.exchange(dec.exchange));
|
else if (dec.kind === 'exchange' && g.bagLength >= RULESETS[entry.record.variant].rackSize) out.push(g.exchange(dec.exchange));
|
||||||
else out.push(g.pass());
|
else out.push(g.pass());
|
||||||
}
|
}
|
||||||
|
// Arm the idle hint gate from the robot's reply: a wall-clock unlock time, persisted so the wait
|
||||||
|
// survives a relaunch. Read back through a sanitiser (lib/hints / stateView) so a clock set back
|
||||||
|
// cannot freeze it.
|
||||||
|
if (out.length > 0) entry.record.hintUnlockAtMs = Date.now() + HINT_GATE_MS;
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
private emitRobot(entry: Live, moves: LocalMove[]): void {
|
private emitRobot(entry: Live, moves: LocalMove[]): void {
|
||||||
const set = this.listeners.get(entry.record.id);
|
const set = this.listeners.get(entry.record.id);
|
||||||
if (!set) return;
|
if (!set) return;
|
||||||
|
const hintUnlockAtMs = this.hintUnlock(entry);
|
||||||
for (const m of moves) {
|
for (const m of moves) {
|
||||||
const game = this.gameView(entry);
|
const game = this.gameView(entry);
|
||||||
const ev: PushEvent = { kind: 'opponent_moved', gameId: entry.record.id, move: this.moveRecord(entry.record.variant, m), game, bagLen: entry.game.bagLength };
|
const ev: PushEvent = { kind: 'opponent_moved', gameId: entry.record.id, move: this.moveRecord(entry.record.variant, m), game, bagLen: entry.game.bagLength, hintUnlockAtMs };
|
||||||
for (const cb of set) cb(ev);
|
for (const cb of set) cb(ev);
|
||||||
}
|
}
|
||||||
if (entry.game.isOver) {
|
if (entry.game.isOver) {
|
||||||
@@ -301,6 +308,7 @@ export class LocalSource implements GameLoopSource {
|
|||||||
seats: entry.record.seats,
|
seats: entry.record.seats,
|
||||||
createdAtUnix: entry.record.createdAtUnix,
|
createdAtUnix: entry.record.createdAtUnix,
|
||||||
updatedAtUnix: nowUnix(),
|
updatedAtUnix: nowUnix(),
|
||||||
|
hintUnlockAtMs: entry.record.hintUnlockAtMs,
|
||||||
});
|
});
|
||||||
await saveLocalGame(entry.record);
|
await saveLocalGame(entry.record);
|
||||||
}
|
}
|
||||||
@@ -333,10 +341,25 @@ export class LocalSource implements GameLoopSource {
|
|||||||
|
|
||||||
// --- shape builders --------------------------------------------------------
|
// --- shape builders --------------------------------------------------------
|
||||||
|
|
||||||
|
// The vs_ai idle-hint unlock instant, sanitised on read: capped at now + the window so a device
|
||||||
|
// clock set back cannot push it far ahead and freeze the gate (the client counts down from here).
|
||||||
|
// 0 while open (a human-first opening, no robot move yet).
|
||||||
|
private hintUnlock(entry: Live): number {
|
||||||
|
return entry.record.hintUnlockAtMs ? Math.min(entry.record.hintUnlockAtMs, Date.now() + HINT_GATE_MS) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
private stateView(entry: Live): StateView {
|
private stateView(entry: Live): StateView {
|
||||||
const seat = this.humanSeat(entry);
|
const seat = this.humanSeat(entry);
|
||||||
const rack = entry.game.handOf(seat).map((t) => indexToLetter(entry.record.variant, t));
|
const rack = entry.game.handOf(seat).map((t) => indexToLetter(entry.record.variant, t));
|
||||||
return { game: this.gameView(entry), seat, rack, bagLen: entry.game.bagLength, hintsRemaining: 1, walletBalance: 0 };
|
return {
|
||||||
|
game: this.gameView(entry),
|
||||||
|
seat,
|
||||||
|
rack,
|
||||||
|
bagLen: entry.game.bagLength,
|
||||||
|
hintsRemaining: 1,
|
||||||
|
walletBalance: 0,
|
||||||
|
hintUnlockAtMs: this.hintUnlock(entry),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private gameView(entry: Live): GameView {
|
private gameView(entry: Live): GameView {
|
||||||
|
|||||||
+5
-1
@@ -82,6 +82,10 @@ export interface StateView {
|
|||||||
bagLen: number;
|
bagLen: number;
|
||||||
hintsRemaining: number;
|
hintsRemaining: number;
|
||||||
walletBalance: number;
|
walletBalance: number;
|
||||||
|
/** For a vs_ai game, the wall-clock ms at which the idle hint unlocks — persisted so the wait
|
||||||
|
* survives a relaunch, and sanitised on read so a device clock set back cannot freeze it — or
|
||||||
|
* 0/undefined while open (the human's first move, or a non-vs_ai game). See lib/hints. */
|
||||||
|
hintUnlockAtMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MoveResult {
|
export interface MoveResult {
|
||||||
@@ -421,7 +425,7 @@ export interface GameList {
|
|||||||
*/
|
*/
|
||||||
export type PushEvent =
|
export type PushEvent =
|
||||||
| { kind: 'your_turn'; gameId: string; deadlineUnix: number; opponentName: string; moveCount: number }
|
| { kind: 'your_turn'; gameId: string; deadlineUnix: number; opponentName: string; moveCount: number }
|
||||||
| { kind: 'opponent_moved'; gameId: string; move?: MoveRecord; game?: GameView; bagLen: number }
|
| { kind: 'opponent_moved'; gameId: string; move?: MoveRecord; game?: GameView; bagLen: number; hintUnlockAtMs?: number }
|
||||||
| { kind: 'game_over'; gameId: string; result: string; scoreLine: string; game?: GameView }
|
| { kind: 'game_over'; gameId: string; result: string; scoreLine: string; game?: GameView }
|
||||||
| { kind: 'chat_message'; message: ChatMessage }
|
| { kind: 'chat_message'; message: ChatMessage }
|
||||||
| { kind: 'nudge'; gameId: string; fromUserId: string; senderName: string }
|
| { kind: 'nudge'; gameId: string; fromUserId: string; senderName: string }
|
||||||
|
|||||||
Reference in New Issue
Block a user