Merge pull request 'feat(hint): unify the vs_ai idle hint online + offline (server-enforced, monotonic)' (#209) from feature/online-vsai-hint into development
CI / changes (push) Successful in 1s
CI / unit (push) Successful in 10s
CI / integration (push) Successful in 16s
CI / ui (push) Successful in 1m12s
CI / conformance (push) Successful in 10s
CI / gate (push) Successful in 0s
CI / deploy (push) Successful in 1m40s

This commit was merged in pull request #209.
This commit is contained in:
2026-07-06 23:04:38 +00:00
22 changed files with 257 additions and 127 deletions
+23
View File
@@ -69,6 +69,29 @@ func TestHintsRemaining(t *testing.T) {
} }
} }
func TestHintUnlockLeftSeconds(t *testing.T) {
now := time.Now()
// A gated vs_ai game on the caller's turn, the robot having moved 10 min ago (turn started then).
gated := Game{VsAI: true, ToMove: 0, MoveCount: 2, TurnStartedAt: now.Add(-10 * time.Minute)}
cases := []struct {
name string
g Game
seat int
want int
}{
{"non-vs_ai is open", Game{VsAI: false, ToMove: 0, MoveCount: 2, TurnStartedAt: now.Add(-10 * time.Minute)}, 0, 0},
{"not the caller's turn is open", gated, 1, 0},
{"human first move (no robot move) is open", Game{VsAI: true, ToMove: 0, MoveCount: 0, TurnStartedAt: now}, 0, 0},
{"robot moved 10 min ago leaves 20 min", gated, 0, 20 * 60},
{"robot moved past the window is open", Game{VsAI: true, ToMove: 0, MoveCount: 2, TurnStartedAt: now.Add(-40 * time.Minute)}, 0, 0},
}
for _, c := range cases {
if got := hintUnlockLeftSeconds(c.g, c.seat, now); got != c.want {
t.Errorf("%s: hintUnlockLeftSeconds = %d, want %d", c.name, got, c.want)
}
}
}
func TestAllowedTimeout(t *testing.T) { func TestAllowedTimeout(t *testing.T) {
if !allowedTimeout(24 * time.Hour) { if !allowedTimeout(24 * time.Hour) {
t.Error("24h must be allowed") t.Error("24h must be allowed")
+47 -4
View File
@@ -1058,10 +1058,31 @@ func (svc *Service) MarkChangesApplied(ctx context.Context, variant engine.Varia
return svc.store.MarkChangesApplied(ctx, variant.String(), version) return svc.store.MarkChangesApplied(ctx, variant.String(), version)
} }
// Hint reveals the top-scoring legal play for the requesting player on their // hintIdleWindow is how long a vs_ai player must be stuck on a turn (since the robot's last move)
// turn, spending one hint from their per-game allowance and then their profile // before the idle hint unlocks. Mirrors the offline client (lib/hints HINT_GATE_MS = 30 min).
// wallet. It returns ErrHintsDisabled, ErrNoHintsLeft or ErrNoHintAvailable as const hintIdleWindow = 30 * time.Minute
// appropriate.
// hintUnlockLeftSeconds is the seconds until g's vs_ai idle hint unlocks for seat, measured from now:
// the robot's last move (the current turn's start, on the human's turn) plus the window, floored at
// 0 and ceiled to whole seconds. It is 0 for a non-vs_ai game, when it is not seat's turn, or on the
// human's first move (MoveCount 0, no robot move yet) — the gate is an anti-frustration aid, not a
// first-move tax. The client anchors a monotonic countdown to it, so a client clock cannot skew it.
func hintUnlockLeftSeconds(g Game, seat int, now time.Time) int {
if !g.VsAI || g.ToMove != seat || g.MoveCount < 1 {
return 0
}
left := g.TurnStartedAt.Add(hintIdleWindow).Sub(now)
if left <= 0 {
return 0
}
return int((left + time.Second - 1) / time.Second) // ceil to whole seconds (no math import)
}
// Hint reveals the top-scoring legal play for the requesting player on their turn. For a human game
// it spends one hint from the per-game allowance then the profile wallet (ErrHintsDisabled /
// ErrNoHintsLeft / ErrNoHintAvailable). For a vs_ai game the hint is unlimited and wallet-free but
// idle-gated from the server clock (ErrHintLocked until the window elapses) and counts toward no
// hint statistic.
func (svc *Service) Hint(ctx context.Context, gameID, accountID uuid.UUID) (HintResult, error) { func (svc *Service) Hint(ctx context.Context, gameID, accountID uuid.UUID) (HintResult, error) {
pre, err := svc.store.GetGame(ctx, gameID) pre, err := svc.store.GetGame(ctx, gameID)
if err != nil { if err != nil {
@@ -1080,6 +1101,26 @@ func (svc *Service) Hint(ctx context.Context, gameID, accountID uuid.UUID) (Hint
if !pre.HintsAllowed { if !pre.HintsAllowed {
return HintResult{}, ErrHintsDisabled return HintResult{}, ErrHintsDisabled
} }
if pre.VsAI {
// vs_ai: unlimited and wallet-free, but idle-gated from the server clock — and counted toward
// no hint statistic. Enforce the gate (the client normally pre-gates from the view's
// HintUnlockLeftSeconds; this is the authoritative backstop), then serve the top move without
// touching the allowance, the wallet or hints_used.
if hintUnlockLeftSeconds(pre, seat, svc.clock()) > 0 {
return HintResult{}, ErrHintLocked
}
unlock := svc.locks.lock(gameID)
defer unlock()
g, err := svc.liveGame(ctx, pre)
if err != nil {
return HintResult{}, err
}
move, ok := g.HintView()
if !ok {
return HintResult{}, ErrNoHintAvailable
}
return HintResult{Move: move}, nil
}
acc, err := svc.accounts.GetByID(ctx, accountID) acc, err := svc.accounts.GetByID(ctx, accountID)
if err != nil { if err != nil {
return HintResult{}, err return HintResult{}, err
@@ -1208,6 +1249,8 @@ func (svc *Service) GameState(ctx context.Context, gameID, accountID uuid.UUID)
BagLen: g.BagLen(), BagLen: g.BagLen(),
HintsRemaining: hintsRemaining(pre.HintsPerPlayer, pre.Seats[seat].HintsUsed, acc.HintBalance), HintsRemaining: hintsRemaining(pre.HintsPerPlayer, pre.Seats[seat].HintsUsed, acc.HintBalance),
WalletBalance: acc.HintBalance, WalletBalance: acc.HintBalance,
// vs_ai idle-hint gate (seconds left; 0 for a human game / first move / not your turn).
HintUnlockLeftSeconds: hintUnlockLeftSeconds(pre, seat, svc.clock()),
}, nil }, nil
} }
+9
View File
@@ -65,6 +65,10 @@ var (
ErrNoHintsLeft = errors.New("game: no hints remaining") ErrNoHintsLeft = errors.New("game: no hints remaining")
// ErrNoHintAvailable is returned when the player has no legal play to reveal. // ErrNoHintAvailable is returned when the player has no legal play to reveal.
ErrNoHintAvailable = errors.New("game: no legal move to suggest") ErrNoHintAvailable = errors.New("game: no legal move to suggest")
// ErrHintLocked is returned when a vs_ai game's idle hint is still gated (the player has not yet
// been stuck the idle window since the robot's last move). The client normally pre-gates from
// StateView.HintUnlockLeftSeconds, so this is the authoritative server-clock backstop.
ErrHintLocked = errors.New("game: hint is not available yet")
// ErrGameLimitReached is returned when an account already holds MaxActiveQuickGames // ErrGameLimitReached is returned when an account already holds MaxActiveQuickGames
// simultaneous quick games and tries to create another game (quick or by invitation). // simultaneous quick games and tries to create another game (quick or by invitation).
ErrGameLimitReached = errors.New("game: simultaneous game limit reached") ErrGameLimitReached = errors.New("game: simultaneous game limit reached")
@@ -240,6 +244,11 @@ type StateView struct {
// WalletBalance is the player's global hint-wallet balance alone (HintsRemaining folds // WalletBalance is the player's global hint-wallet balance alone (HintsRemaining folds
// it in with the per-game allowance), so the client keeps the wallet live across games. // it in with the per-game allowance), so the client keeps the wallet live across games.
WalletBalance int WalletBalance int
// HintUnlockLeftSeconds is, for a vs_ai game on the requesting player's turn, the seconds left
// until the idle hint unlocks (the robot's last move plus the idle window, from the server clock);
// 0 for the human's first move, when it is not their turn, or a non-vs_ai game. The vs_ai hint is
// unlimited and wallet-free; this idle gate replaces the allowance/wallet for it.
HintUnlockLeftSeconds int
} }
// HistoryMove is one decoded journal row, independent of any dictionary. // HistoryMove is one decoded journal row, independent of any dictionary.
+17 -13
View File
@@ -163,13 +163,16 @@ type alphabetEntryDTO struct {
// stateDTO is a player's view of a game. Rack carries wire alphabet indices (a // stateDTO is a player's view of a game. Rack carries wire alphabet indices (a
// blank is engine.BlankIndex). Alphabet is present only when the request asked for it. // blank is engine.BlankIndex). Alphabet is present only when the request asked for it.
type stateDTO struct { type stateDTO struct {
Game gameDTO `json:"game"` Game gameDTO `json:"game"`
Seat int `json:"seat"` Seat int `json:"seat"`
Rack []int `json:"rack"` Rack []int `json:"rack"`
BagLen int `json:"bag_len"` BagLen int `json:"bag_len"`
HintsRemaining int `json:"hints_remaining"` HintsRemaining int `json:"hints_remaining"`
WalletBalance int `json:"wallet_balance"` WalletBalance int `json:"wallet_balance"`
Alphabet []alphabetEntryDTO `json:"alphabet,omitempty"` // HintUnlockLeftSeconds is the vs_ai idle-hint gate: seconds until the hint unlocks (0 for a human
// game / first move / not your turn). The client anchors a monotonic countdown to it.
HintUnlockLeftSeconds int `json:"hint_unlock_left_seconds"`
Alphabet []alphabetEntryDTO `json:"alphabet,omitempty"`
} }
// matchDTO reports whether the caller has been paired into a game. // matchDTO reports whether the caller has been paired into a game.
@@ -315,12 +318,13 @@ func stateDTOFrom(v game.StateView, includeAlphabet bool) (stateDTO, error) {
return stateDTO{}, err return stateDTO{}, err
} }
dto := stateDTO{ dto := stateDTO{
Game: gameDTOFromGame(v.Game), Game: gameDTOFromGame(v.Game),
Seat: v.Seat, Seat: v.Seat,
Rack: rack, Rack: rack,
BagLen: v.BagLen, BagLen: v.BagLen,
HintsRemaining: v.HintsRemaining, HintsRemaining: v.HintsRemaining,
WalletBalance: v.WalletBalance, WalletBalance: v.WalletBalance,
HintUnlockLeftSeconds: v.HintUnlockLeftSeconds,
} }
if includeAlphabet { if includeAlphabet {
tab, err := engine.AlphabetTable(v.Game.Variant) tab, err := engine.AlphabetTable(v.Game.Variant)
+3
View File
@@ -239,6 +239,9 @@ func statusForError(err error) (int, string) {
return http.StatusConflict, "no_hint_available" return http.StatusConflict, "no_hint_available"
case errors.Is(err, game.ErrHintsDisabled), errors.Is(err, game.ErrNoHintsLeft): case errors.Is(err, game.ErrHintsDisabled), errors.Is(err, game.ErrNoHintsLeft):
return http.StatusConflict, "hint_unavailable" return http.StatusConflict, "hint_unavailable"
case errors.Is(err, game.ErrHintLocked):
// A vs_ai idle hint is still gated (the server-clock backstop); the client shows the lock.
return http.StatusConflict, "hint_locked"
case errors.Is(err, engine.ErrIllegalPlay), errors.Is(err, engine.ErrTilesNotOnRack), errors.Is(err, engine.ErrGameOver): case errors.Is(err, engine.ErrIllegalPlay), errors.Is(err, engine.ErrTilesNotOnRack), errors.Is(err, engine.ErrGameOver):
return http.StatusUnprocessableEntity, "illegal_play" return http.StatusUnprocessableEntity, "illegal_play"
case errors.Is(err, account.ErrEmailTaken), errors.Is(err, account.ErrIdentityTaken): case errors.Is(err, account.ErrEmailTaken), errors.Is(err, account.ErrIdentityTaken):
+8 -7
View File
@@ -1252,13 +1252,14 @@ an *Offline* chip and confines play to on-device `vs_ai` games. The **offline lo
device-local games** (reconstructed by replaying the IndexedDB move journal) and its New-vs-AI entry device-local games** (reconstructed by replaying the IndexedDB move journal) and its New-vs-AI entry
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 `vs_ai` hint (online and offline alike) is unlimited and wallet-free but idle-gated
stuck turn). The gate is a **persisted wall-clock unlock instant** (`hintUnlockAtMs` on the record + (unlocked ~30 min into a stuck turn), and counts toward no hint statistic. The **source** reports the
the game view, stamped from the robot's reply, carried on the move delta), so the wait survives a **seconds left** (`hint_unlock_left_seconds` on the game view) — computed by the **backend from the
relaunch — but it is **sanitised on read** (capped at `now + window`, `lib/hints` + `source.ts`) so a server clock** online (which also enforces the gate, returning `hint_locked` for an early request),
device clock the player sets **back** cannot push the unlock away and freeze the gate; a clock set and by the offline source from the device clock (persisted, capped at the window). The **client
**forward** merely opens the hint early, harmless for a solo game. An online `vs_ai` game will gate the anchors a MONOTONIC countdown** (`performance.now()`, `lib/hints`) to that seconds-left when it lands
same way but from the server's clock (a follow-up). To have data ready before the switch, the **Profile advertises the current dictionary (on load, and to the full window when the robot moves), so a client clock change cannot skew it, and
a relaunch re-reads a fresh value so the wait is not forgotten. 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 -5
View File
@@ -220,11 +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 **persists across tap shows how long remains; the lock lifts live at the mark. The same gate applies **online and
leaving and reopening the app**, so a stuck turn is not forgotten. It stays robust to a offline**: the countdown runs on a **steady in-app timer**, not the device clock, so changing the
device clock change: the remaining is capped at the window, so a clock set back cannot clock cannot skew it, and a relaunch re-reads the remaining time so a stuck turn is not forgotten.
freeze it, and a clock set forward merely opens the hint early — harmless in a solo game. Online the **server enforces** it from its own clock (which the player cannot touch); a vs_ai hint
The game ends when the counts toward no hint statistic. 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
+5 -4
View File
@@ -227,10 +227,11 @@ e-mail) либо ввод фразы. Активные игры форфейтя
анти-фрустрация: подсказка открывается, только когда игрок **застрял на ходу ~30 минут** анти-фрустрация: подсказка открывается, только когда игрок **застрял на ходу ~30 минут**
(отсчёт от последнего хода робота; самый первый ход, до хода робота, исключён). Пока гейт (отсчёт от последнего хода робота; самый первый ход, до хода робота, исключён). Пока гейт
закрыт, кнопка подсказки несёт маленький **🔒 замок**, а тап показывает, сколько осталось; закрыт, кнопка подсказки несёт маленький **🔒 замок**, а тап показывает, сколько осталось;
замок снимается вживую в нужный момент. Отсчёт **переживает выход и повторный вход в замок снимается вживую в нужный момент. Один и тот же гейт работает **онлайн и офлайн**: отсчёт
приложение**, так что застрявший ход не забывается. И он устойчив к переводу часов: остаток идёт по **ровному внутриигровому таймеру**, а не по системным часам, поэтому их перевод его не
ограничен окном, поэтому перевод назад не заморозит гейт, а перевод вперёд просто откроет собьёт, а повторный вход перечитывает остаток — застрявший ход не забывается. Онлайн гейт
подсказку раньше — безвредно в соло-игре. Партия **принуждает сервер** по своим часам (их игрок не тронет); vs_ai-подсказка не учитывается ни в
одной статистике подсказок. Партия
завершается, когда мешок пуст и игрок выложил стойку, после 6 подряд бесплодных завершается, когда мешок пуст и игрок выложил стойку, после 6 подряд бесплодных
ходов, по сдаче, либо по таймауту хода (от 5 минут до 24 часов, дефолт 24 часа): ходов, по сдаче, либо по таймауту хода (от 5 минут до 24 часов, дефолт 24 часа):
пропущенный ход означает авто-сдачу, кроме как когда игрок внутри своего пропущенный ход означает авто-сдачу, кроме как когда игрок внутри своего
+8 -7
View File
@@ -181,13 +181,14 @@ type AlphabetEntryJSON struct {
// StateResp is a player's view of a game. Rack carries wire alphabet indices; // StateResp is a player's view of a game. Rack carries wire alphabet indices;
// Alphabet is present only when the request asked for it. // Alphabet is present only when the request asked for it.
type StateResp struct { type StateResp struct {
Game GameResp `json:"game"` Game GameResp `json:"game"`
Seat int `json:"seat"` Seat int `json:"seat"`
Rack []int `json:"rack"` Rack []int `json:"rack"`
BagLen int `json:"bag_len"` BagLen int `json:"bag_len"`
HintsRemaining int `json:"hints_remaining"` HintsRemaining int `json:"hints_remaining"`
WalletBalance int `json:"wallet_balance"` WalletBalance int `json:"wallet_balance"`
Alphabet []AlphabetEntryJSON `json:"alphabet,omitempty"` HintUnlockLeftSeconds int `json:"hint_unlock_left_seconds"`
Alphabet []AlphabetEntryJSON `json:"alphabet,omitempty"`
} }
// MatchResp reports an auto-match outcome. // MatchResp reports an auto-match outcome.
+8 -7
View File
@@ -299,13 +299,14 @@ func toWireState(s backendclient.StateResp) wire.StateView {
alphabet[i] = wire.AlphabetEntry{Index: e.Index, Letter: e.Letter, Value: e.Value} alphabet[i] = wire.AlphabetEntry{Index: e.Index, Letter: e.Letter, Value: e.Value}
} }
return wire.StateView{ return wire.StateView{
Game: toWireGame(s.Game), Game: toWireGame(s.Game),
Seat: s.Seat, Seat: s.Seat,
Rack: s.Rack, Rack: s.Rack,
BagLen: s.BagLen, BagLen: s.BagLen,
HintsRemaining: s.HintsRemaining, HintsRemaining: s.HintsRemaining,
WalletBalance: s.WalletBalance, WalletBalance: s.WalletBalance,
Alphabet: alphabet, HintUnlockLeftSeconds: s.HintUnlockLeftSeconds,
Alphabet: alphabet,
} }
} }
+3 -3
View File
@@ -59,7 +59,7 @@ func TestGameStateRoundTripForwardsUserID(t *testing.T) {
if r.URL.Path != "/api/v1/user/games/g-1/state" { if r.URL.Path != "/api/v1/user/games/g-1/state" {
t.Errorf("unexpected path %q", r.URL.Path) t.Errorf("unexpected path %q", r.URL.Path)
} }
_, _ = w.Write([]byte(`{"game":{"id":"g-1","variant":"scrabble_en","status":"active","players":2,"to_move":1,"seats":[{"seat":0,"account_id":"u-7","score":5}]},"seat":0,"rack":[0,1],"bag_len":80,"hints_remaining":4,"wallet_balance":3}`)) _, _ = w.Write([]byte(`{"game":{"id":"g-1","variant":"scrabble_en","status":"active","players":2,"to_move":1,"seats":[{"seat":0,"account_id":"u-7","score":5}]},"seat":0,"rack":[0,1],"bag_len":80,"hints_remaining":4,"wallet_balance":3,"hint_unlock_left_seconds":1200}`))
}) })
defer cleanup() defer cleanup()
@@ -77,8 +77,8 @@ func TestGameStateRoundTripForwardsUserID(t *testing.T) {
t.Fatalf("handler: %v", err) t.Fatalf("handler: %v", err)
} }
st := fb.GetRootAsStateView(payload, 0) st := fb.GetRootAsStateView(payload, 0)
if st.BagLen() != 80 || st.RackLength() != 2 || st.HintsRemaining() != 4 || st.WalletBalance() != 3 { if st.BagLen() != 80 || st.RackLength() != 2 || st.HintsRemaining() != 4 || st.WalletBalance() != 3 || st.HintUnlockLeftSeconds() != 1200 {
t.Fatalf("state decoded wrong: bag=%d rack=%d hints=%d wallet=%d", st.BagLen(), st.RackLength(), st.HintsRemaining(), st.WalletBalance()) t.Fatalf("state decoded wrong: bag=%d rack=%d hints=%d wallet=%d unlockLeft=%d", st.BagLen(), st.RackLength(), st.HintsRemaining(), st.WalletBalance(), st.HintUnlockLeftSeconds())
} }
game := st.Game(nil) game := st.Game(nil)
if game == nil || string(game.Id()) != "g-1" || string(game.Variant()) != "scrabble_en" || game.ToMove() != 1 { if game == nil || string(game.Id()) != "g-1" || string(game.Variant()) != "scrabble_en" || game.ToMove() != 1 {
+7
View File
@@ -316,6 +316,13 @@ table StateView {
// the wallet is a single global figure the client keeps live across games (added trailing — // the wallet is a single global figure the client keeps live across games (added trailing —
// backward-compatible). // backward-compatible).
wallet_balance:int; wallet_balance:int;
// hint_unlock_left_seconds is, for a vs_ai game, how many seconds until the idle hint unlocks
// (the robot's last move plus the idle window, computed from the SERVER clock online / the device
// clock offline, capped at the window and floored at 0); 0 for a human's first move (no robot move
// yet) or a non-vs_ai game. The client anchors a MONOTONIC countdown (performance.now()) to it, so a
// client clock change cannot skew it — see lib/hints. Seconds granularity is enough; sent trailing
// (additive, backward-compatible).
hint_unlock_left_seconds:int;
} }
// GameActionRequest carries just a game id (pass / resign / hint / history). // GameActionRequest carries just a game id (pass / resign / hint / history).
+16 -1
View File
@@ -156,8 +156,20 @@ func (rcv *StateView) MutateWalletBalance(n int32) bool {
return rcv._tab.MutateInt32Slot(16, n) return rcv._tab.MutateInt32Slot(16, n)
} }
func (rcv *StateView) HintUnlockLeftSeconds() int32 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(18))
if o != 0 {
return rcv._tab.GetInt32(o + rcv._tab.Pos)
}
return 0
}
func (rcv *StateView) MutateHintUnlockLeftSeconds(n int32) bool {
return rcv._tab.MutateInt32Slot(18, n)
}
func StateViewStart(builder *flatbuffers.Builder) { func StateViewStart(builder *flatbuffers.Builder) {
builder.StartObject(7) builder.StartObject(8)
} }
func StateViewAddGame(builder *flatbuffers.Builder, game flatbuffers.UOffsetT) { func StateViewAddGame(builder *flatbuffers.Builder, game flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(game), 0) builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(game), 0)
@@ -186,6 +198,9 @@ func StateViewStartAlphabetVector(builder *flatbuffers.Builder, numElems int) fl
func StateViewAddWalletBalance(builder *flatbuffers.Builder, walletBalance int32) { func StateViewAddWalletBalance(builder *flatbuffers.Builder, walletBalance int32) {
builder.PrependInt32Slot(6, walletBalance, 0) builder.PrependInt32Slot(6, walletBalance, 0)
} }
func StateViewAddHintUnlockLeftSeconds(builder *flatbuffers.Builder, hintUnlockLeftSeconds int32) {
builder.PrependInt32Slot(7, hintUnlockLeftSeconds, 0)
}
func StateViewEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { func StateViewEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject() return builder.EndObject()
} }
+9 -7
View File
@@ -87,13 +87,14 @@ type AlphabetEntry struct {
// (wire alphabet indices), bag size and hint budget. Alphabet is set only when the // (wire alphabet indices), bag size and hint budget. Alphabet is set only when the
// recipient may not have cached the variant's display table yet. // recipient may not have cached the variant's display table yet.
type StateView struct { type StateView struct {
Game GameView Game GameView
Seat int Seat int
Rack []int Rack []int
BagLen int BagLen int
HintsRemaining int HintsRemaining int
WalletBalance int WalletBalance int
Alphabet []AlphabetEntry HintUnlockLeftSeconds int
Alphabet []AlphabetEntry
} }
// AccountRef is a referenced account with its display name resolved. // AccountRef is a referenced account with its display name resolved.
@@ -256,6 +257,7 @@ func BuildStateView(b *flatbuffers.Builder, s StateView) flatbuffers.UOffsetT {
fb.StateViewAddBagLen(b, int32(s.BagLen)) fb.StateViewAddBagLen(b, int32(s.BagLen))
fb.StateViewAddHintsRemaining(b, int32(s.HintsRemaining)) fb.StateViewAddHintsRemaining(b, int32(s.HintsRemaining))
fb.StateViewAddWalletBalance(b, int32(s.WalletBalance)) fb.StateViewAddWalletBalance(b, int32(s.WalletBalance))
fb.StateViewAddHintUnlockLeftSeconds(b, int32(s.HintUnlockLeftSeconds))
if hasAlphabet { if hasAlphabet {
fb.StateViewAddAlphabet(b, alphabet) fb.StateViewAddAlphabet(b, alphabet)
} }
+39 -13
View File
@@ -23,7 +23,7 @@
import { centre, premiumGrid } from '../lib/premiums'; import { centre, premiumGrid } from '../lib/premiums';
import { variantNameKey, usesStarBlank, BLANK_STAR } from '../lib/variants'; import { variantNameKey, usesStarBlank, BLANK_STAR } from '../lib/variants';
import { alphabetLetters, hasAlphabet } from '../lib/alphabet'; import { alphabetLetters, hasAlphabet } from '../lib/alphabet';
import { hintsLeft, hintGateRemainingMs, hintLockMinutes } from '../lib/hints'; import { hintsLeft, hintGateRemainingMs, hintLockMinutes, HINT_GATE_MS } from '../lib/hints';
import { downloadUrl, shareOrDownloadGcg, shareUrlAsFile } from '../lib/share'; import { downloadUrl, shareOrDownloadGcg, shareUrlAsFile } from '../lib/share';
import { insideVK, vkAndroidWebView, vkCopyText, vkDownloadFile, vkPlatform, vkShowImages } from '../lib/vk'; import { insideVK, vkAndroidWebView, vkCopyText, vkDownloadFile, vkPlatform, vkShowImages } from '../lib/vk';
import { getCachedGame, setCachedGame, setCachedDraft, type CachedGame } from '../lib/gamecache'; import { getCachedGame, setCachedGame, setCachedDraft, type CachedGame } from '../lib/gamecache';
@@ -168,19 +168,30 @@
// 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 unlock is a persisted // unlocks only after the player has been stuck ~30 min on a turn). The source (the SERVER clock
// wall-clock instant carried on the game view (`hintUnlockAtMs`, stamped by the source off the // online, the device clock offline) tells us the SECONDS LEFT (view.hintUnlockLeftSeconds); we
// robot's reply and kept fresh by the move delta), so the wait survives leaving and reopening the // anchor a MONOTONIC countdown (performance.now()) to it, so a client clock change cannot skew it.
// app. It is sanitised on read (source + lib/hints cap it at now + the window) so a device clock // A fresh value arrives on load (armHintGate below); when the robot moves the wait is the full
// set BACK cannot freeze the gate; a clock set forward just opens the hint early, harmless for a // window. `monoNow` ticks so the 🔒 lifts live at the mark.
// solo game. `now` ticks so the 🔒 lifts live at the mark. 0 = open (the human's first move). let hintGateStart = $state<number | null>(null); // performance.now() at the last anchor; null = open
let now = $state(Date.now()); let gateLeftMs = $state(0);
const hintUnlockAt = $derived(view?.game.vsAi ? (view.hintUnlockAtMs ?? 0) : 0); let monoNow = $state(performance.now());
const hintRemaining = $derived(hintGateRemainingMs(hintUnlockAt, now)); const hintRemaining = $derived(hintGateRemainingMs(hintGateStart, gateLeftMs, monoNow));
const hintGated = $derived(hintRemaining > 0); const hintGated = $derived(hintRemaining > 0);
// Anchor the countdown to a freshly received seconds-left (or open the gate). Called on every state
// load from the view, and on the robot's move to the full window (the robot just moved).
function armHintGate(leftSeconds: number): void {
if (leftSeconds > 0) {
hintGateStart = performance.now();
gateLeftMs = leftSeconds * 1000;
} else {
hintGateStart = null;
gateLeftMs = 0;
}
}
$effect(() => { $effect(() => {
if (!view?.game.vsAi) return; if (!view?.game.vsAi) return;
const iv = setInterval(() => (now = Date.now()), 10_000); const iv = setInterval(() => (monoNow = performance.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
@@ -225,6 +236,8 @@
source.draftGet(id).catch(() => ''), source.draftGet(id).catch(() => ''),
]); ]);
view = st; view = st;
// Anchor the vs_ai idle-hint countdown to the freshly fetched seconds-left (0 = open / non-vs_ai).
armHintGate(st.game.vsAi ? (st.hintUnlockLeftSeconds ?? 0) : 0);
syncWallet(st.walletBalance); syncWallet(st.walletBalance);
// Seed the unread flag from the authoritative state (the live stream only raises it). // Seed the unread flag from the authoritative state (the live stream only raises it).
seedChatUnread(id, st.game.unreadChat, st.game.unreadMessages); seedChatUnread(id, st.game.unreadChat, st.game.unreadMessages);
@@ -277,6 +290,9 @@
if (cached) { if (cached) {
view = cached.view; view = cached.view;
moves = cached.moves; moves = cached.moves;
// Arm the vs_ai idle-hint countdown from the cached seconds-left so the 🔒 shows at once on a
// warm open (no wait for load()); the cached value is a snapshot, refreshed by load() below.
armHintGate(cached.view.game.vsAi ? (cached.view.hintUnlockLeftSeconds ?? 0) : 0);
// Apply the cached draft synchronously so a warm/preloaded open paints the pending tiles // Apply the cached draft synchronously so a warm/preloaded open paints the pending tiles
// already on the board (no full-rack-then-jump). load() then refreshes in the background. // already on the board (no full-rack-then-jump). load() then refreshes in the background.
applyDraft(cached.view, cached.draft ?? ''); applyDraft(cached.view, cached.draft ?? '');
@@ -345,7 +361,11 @@
// 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, hintUnlockAtMs: e.hintUnlockAtMs })); else {
applyDelta(applyMoveDelta(cacheSnapshot(), { move: e.move, game: e.game, bagLen: e.bagLen }));
// The robot just moved (vs_ai) → the human's turn begins with the full idle window.
if (view?.game.vsAi) armHintGate(HINT_GATE_MS / 1000);
}
} 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).
@@ -873,7 +893,7 @@
// 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 at tap time. // hint unlocks (no wallet is ever spent) — matching the 🔒 badge. Measured fresh at tap time.
if (view?.game.vsAi) { if (view?.game.vsAi) {
const remaining = hintGateRemainingMs(hintUnlockAt, Date.now()); const remaining = hintGateRemainingMs(hintGateStart, gateLeftMs, performance.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;
@@ -915,6 +935,12 @@
// The backend does not spend a hint when there is no move. // The backend does not spend a hint when there is no move.
if (e instanceof GatewayError && e.code === 'no_hint_available') { if (e instanceof GatewayError && e.code === 'no_hint_available') {
showToast(t('game.noHintOptions'), 'info'); showToast(t('game.noHintOptions'), 'info');
} else if (e instanceof GatewayError && e.code === 'hint_locked') {
// The server-clock backstop refused a vs_ai hint the client thought was open (a rare client
// clock desync): re-sync the countdown from a fresh fetch and explain the gate.
await load();
const left = hintGateRemainingMs(hintGateStart, gateLeftMs, performance.now());
showToast(t('game.hintLockedIn', { n: hintLockMinutes(left || 60_000) }), 'info');
} else { } else {
handleError(e); handleError(e);
} }
+12 -2
View File
@@ -74,8 +74,13 @@ walletBalance():number {
return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
} }
hintUnlockLeftSeconds():number {
const offset = this.bb!.__offset(this.bb_pos, 18);
return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
}
static startStateView(builder:flatbuffers.Builder) { static startStateView(builder:flatbuffers.Builder) {
builder.startObject(7); builder.startObject(8);
} }
static addGame(builder:flatbuffers.Builder, gameOffset:flatbuffers.Offset) { static addGame(builder:flatbuffers.Builder, gameOffset:flatbuffers.Offset) {
@@ -130,12 +135,16 @@ static addWalletBalance(builder:flatbuffers.Builder, walletBalance:number) {
builder.addFieldInt32(6, walletBalance, 0); builder.addFieldInt32(6, walletBalance, 0);
} }
static addHintUnlockLeftSeconds(builder:flatbuffers.Builder, hintUnlockLeftSeconds:number) {
builder.addFieldInt32(7, hintUnlockLeftSeconds, 0);
}
static endStateView(builder:flatbuffers.Builder):flatbuffers.Offset { static endStateView(builder:flatbuffers.Builder):flatbuffers.Offset {
const offset = builder.endObject(); const offset = builder.endObject();
return offset; return offset;
} }
static createStateView(builder:flatbuffers.Builder, gameOffset:flatbuffers.Offset, seat:number, rackOffset:flatbuffers.Offset, bagLen:number, hintsRemaining:number, alphabetOffset:flatbuffers.Offset, walletBalance:number):flatbuffers.Offset { static createStateView(builder:flatbuffers.Builder, gameOffset:flatbuffers.Offset, seat:number, rackOffset:flatbuffers.Offset, bagLen:number, hintsRemaining:number, alphabetOffset:flatbuffers.Offset, walletBalance:number, hintUnlockLeftSeconds:number):flatbuffers.Offset {
StateView.startStateView(builder); StateView.startStateView(builder);
StateView.addGame(builder, gameOffset); StateView.addGame(builder, gameOffset);
StateView.addSeat(builder, seat); StateView.addSeat(builder, seat);
@@ -144,6 +153,7 @@ static createStateView(builder:flatbuffers.Builder, gameOffset:flatbuffers.Offse
StateView.addHintsRemaining(builder, hintsRemaining); StateView.addHintsRemaining(builder, hintsRemaining);
StateView.addAlphabet(builder, alphabetOffset); StateView.addAlphabet(builder, alphabetOffset);
StateView.addWalletBalance(builder, walletBalance); StateView.addWalletBalance(builder, walletBalance);
StateView.addHintUnlockLeftSeconds(builder, hintUnlockLeftSeconds);
return StateView.endStateView(builder); return StateView.endStateView(builder);
} }
} }
+1
View File
@@ -461,6 +461,7 @@ function decodeStateViewTable(v: fb.StateView): StateView {
bagLen: v.bagLen(), bagLen: v.bagLen(),
hintsRemaining: v.hintsRemaining(), hintsRemaining: v.hintsRemaining(),
walletBalance: v.walletBalance(), walletBalance: v.walletBalance(),
hintUnlockLeftSeconds: v.hintUnlockLeftSeconds(),
}; };
} }
+2 -10
View File
@@ -11,9 +11,6 @@ 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;
} }
/** /**
@@ -53,12 +50,7 @@ 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 = { const view: StateView = { ...cached.view, game: d.game, bagLen: d.bagLen };
...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 };
} }
@@ -87,7 +79,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, hintUnlockAtMs: e.hintUnlockAtMs }).cache; return applyMoveDelta(cached, { move: e.move, game: e.game, bagLen: e.bagLen }).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);
+9 -15
View File
@@ -31,25 +31,19 @@ describe('hintsLeft', () => {
}); });
}); });
describe('hintGateRemainingMs (the vs_ai idle-hint gate)', () => { describe('hintGateRemainingMs (the vs_ai idle-hint gate, monotonic)', () => {
it('is 0 when the gate is open — no unlock time (the human first move, or a non-gated game)', () => { it('is 0 when the gate is open — a null anchor (the human first move, or a non-gated game)', () => {
expect(hintGateRemainingMs(undefined, 5000, 1000)).toBe(0); expect(hintGateRemainingMs(null, 60_000, 5000)).toBe(0);
expect(hintGateRemainingMs(0, 5000, 1000)).toBe(0);
}); });
it('is 0 once the unlock instant has passed (the gate is open)', () => { it('is the window remaining minus the monotonic time elapsed since the anchor', () => {
expect(hintGateRemainingMs(1000, 1000, 1000)).toBe(0); // anchored at mono 1000 with 60s left; 20s of monotonic time later -> 40s left.
expect(hintGateRemainingMs(1000, 1500, 1000)).toBe(0); expect(hintGateRemainingMs(1000, 60_000, 1000 + 20_000)).toBe(40_000);
}); });
it('is the wall-clock time remaining while still gated', () => { it('is 0 once the elapsed monotonic time reaches (or passes) the window', () => {
expect(hintGateRemainingMs(1000, 400, 1000)).toBe(600); expect(hintGateRemainingMs(1000, 60_000, 1000 + 60_000)).toBe(0);
}); expect(hintGateRemainingMs(1000, 60_000, 1000 + 90_000)).toBe(0);
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);
}); });
}); });
+10 -16
View File
@@ -30,23 +30,17 @@ 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. hintUnlockAtMs is the wall-clock instant the hint opens (the robot's last * once it is available. It counts down from a MONOTONIC clock (performance.now()), so a client clock
* move plus the idle window), persisted so the wait survives leaving and reopening the app; 0 or * change cannot skew it: gateStartMono is performance.now() captured when the source's "seconds left"
* undefined means the gate is open (the human's first move, or a non-gated game). * was received, gateLeftMs is that seconds-left in ms, and monoNow is performance.now() now; the
* * remaining is gateLeftMs minus the monotonic time elapsed since the anchor. gateStartMono null means
* The result is CLAMPED to the window. A wall-clock timestamp is the only way to carry idle time * the gate is open (the human's first move, or a non-gated game). The duration comes from the source
* across an app relaunch, but a device clock the player changes (or an auto-sync) could push the * (the SERVER clock online, the device clock offline) and is re-fetched on every load, so the wait
* unlock far into the future and freeze the gate; capping the remaining at the window means the wait * both persists across a relaunch and stays immune to a live clock change.
* 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, gateLeftMs: number, monoNow: number): number {
hintUnlockAtMs: number | undefined, if (gateStartMono === null) return 0;
nowMs: number, return Math.max(0, gateLeftMs - (monoNow - gateStartMono));
gateMs: number = HINT_GATE_MS,
): number {
if (!hintUnlockAtMs) return 0;
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
+10 -8
View File
@@ -290,10 +290,9 @@ export class LocalSource implements GameLoopSource {
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, hintUnlockAtMs }; const ev: PushEvent = { kind: 'opponent_moved', gameId: entry.record.id, move: this.moveRecord(entry.record.variant, m), game, bagLen: entry.game.bagLength };
for (const cb of set) cb(ev); for (const cb of set) cb(ev);
} }
if (entry.game.isOver) { if (entry.game.isOver) {
@@ -342,11 +341,14 @@ 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 // The vs_ai idle-hint seconds left, from the stored unlock instant (device wall clock, persisted
// clock set back cannot push it far ahead and freeze the gate (the client counts down from here). // for the offline record) minus now — capped at the window so a device clock set back cannot push
// 0 while open (a human-first opening, no robot move yet). // it far ahead and freeze the gate, ceiled to whole seconds and floored at 0. The client anchors a
private hintUnlock(entry: Live): number { // monotonic countdown to this; 0 while open (a human-first opening, no robot move yet).
return entry.record.hintUnlockAtMs ? Math.min(entry.record.hintUnlockAtMs, Date.now() + HINT_GATE_MS) : 0; private hintUnlockLeft(entry: Live): number {
if (!entry.record.hintUnlockAtMs) return 0;
const leftMs = Math.min(HINT_GATE_MS, entry.record.hintUnlockAtMs - Date.now());
return leftMs > 0 ? Math.ceil(leftMs / 1000) : 0;
} }
private stateView(entry: Live): StateView { private stateView(entry: Live): StateView {
@@ -359,7 +361,7 @@ export class LocalSource implements GameLoopSource {
bagLen: entry.game.bagLength, bagLen: entry.game.bagLength,
hintsRemaining: 1, hintsRemaining: 1,
walletBalance: 0, walletBalance: 0,
hintUnlockAtMs: this.hintUnlock(entry), hintUnlockLeftSeconds: this.hintUnlockLeft(entry),
}; };
} }
+6 -5
View File
@@ -82,10 +82,11 @@ 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 /** For a vs_ai game, the seconds until the idle hint unlocks (computed by the source: the SERVER
* survives a relaunch, and sanitised on read so a device clock set back cannot freeze it — or * clock online, the device clock offline) — 0/undefined while open (the human's first move, or a
* 0/undefined while open (the human's first move, or a non-vs_ai game). See lib/hints. */ * non-vs_ai game). The client anchors a MONOTONIC countdown (performance.now()) to it on receipt,
hintUnlockAtMs?: number; * so a client clock change cannot skew it; a relaunch re-fetches a fresh value. See lib/hints. */
hintUnlockLeftSeconds?: number;
} }
export interface MoveResult { export interface MoveResult {
@@ -425,7 +426,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; hintUnlockAtMs?: number } | { kind: 'opponent_moved'; gameId: string; move?: MoveRecord; game?: GameView; bagLen: 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 }