feat(hint): unify the vs_ai idle hint online + offline (server-enforced, monotonic)
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 15s
CI / ui (pull_request) Successful in 1m28s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m43s

Online vs_ai hints were broken: #207 made the vs_ai hint button always-enabled and
wallet-free (assuming all vs_ai = the offline idle-gate), but the backend still served
online vs_ai from the allowance/wallet, so over-clicking hit ErrNoHintsLeft -> a generic
error toast. Now online vs_ai uses the SAME idle-gate model as offline.

Backend: Hint() for a vs_ai game skips the allowance/wallet and increments no hints_used
(owner: vs_ai counts toward no hint statistic), and is idle-gated from the SERVER clock --
it returns ErrHintLocked (code hint_locked) until the robot's last move + 30 min, else
serves the top move. GameState/StateView expose hint_unlock_left_seconds (server-computed
seconds remaining; 0 for a human game / first move / not-your-turn). Pure helper
hintUnlockLeftSeconds unit-tested.

Wire: StateView gains hint_unlock_left_seconds (FlatBuffers, additive); pkg/wire + gateway
transcode carry it (round-trip test).

Client: the gate counts down from a MONOTONIC clock (performance.now()) anchored to the
source's seconds-left when it lands (on load from the view; to the full window when the
robot moves), so a client clock change cannot skew it and a relaunch re-reads a fresh
value. The vs_ai hint button (online + offline) shows the lock + toast; doHint handles the
hint_locked backstop by re-syncing. Replaces #207's absolute hintUnlockAtMs on the
wire/model/delta (the offline record keeps the absolute for persistence; the view exposes
seconds-left).

Docs FUNCTIONAL(+_ru)/ARCHITECTURE updated. Verified: go build/vet + game/server/transcode
tests (+ new hintUnlockLeftSeconds); ui check 0 / unit 490 / e2e 198 (one pre-existing
webkit offline flake) / app entry 114.2/115.
This commit is contained in:
Ilia Denisov
2026-07-07 00:42:43 +02:00
parent ee7ff06403
commit 7fc1301b31
22 changed files with 254 additions and 127 deletions
+36 -13
View File
@@ -23,7 +23,7 @@
import { centre, premiumGrid } from '../lib/premiums';
import { variantNameKey, usesStarBlank, BLANK_STAR } from '../lib/variants';
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 { insideVK, vkAndroidWebView, vkCopyText, vkDownloadFile, vkPlatform, vkShowImages } from '../lib/vk';
import { getCachedGame, setCachedGame, setCachedDraft, type CachedGame } from '../lib/gamecache';
@@ -168,19 +168,30 @@
// hint was spent in another game (see lib/hints).
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
// unlocks only after the player has been stuck ~30 min on a turn). The unlock is a persisted
// wall-clock instant carried on the game view (`hintUnlockAtMs`, stamped by the source off the
// robot's reply and kept fresh by the move delta), so the wait survives leaving and reopening the
// app. It is sanitised on read (source + lib/hints cap it at now + the window) so a device clock
// set BACK cannot freeze the gate; a clock set forward just opens the hint early, harmless for a
// solo game. `now` ticks so the 🔒 lifts live at the mark. 0 = open (the human's first move).
let now = $state(Date.now());
const hintUnlockAt = $derived(view?.game.vsAi ? (view.hintUnlockAtMs ?? 0) : 0);
const hintRemaining = $derived(hintGateRemainingMs(hintUnlockAt, now));
// unlocks only after the player has been stuck ~30 min on a turn). The source (the SERVER clock
// online, the device clock offline) tells us the SECONDS LEFT (view.hintUnlockLeftSeconds); we
// anchor a MONOTONIC countdown (performance.now()) to it, so a client clock change cannot skew it.
// A fresh value arrives on load (armHintGate below); when the robot moves the wait is the full
// window. `monoNow` ticks so the 🔒 lifts live at the mark.
let hintGateStart = $state<number | null>(null); // performance.now() at the last anchor; null = open
let gateLeftMs = $state(0);
let monoNow = $state(performance.now());
const hintRemaining = $derived(hintGateRemainingMs(hintGateStart, gateLeftMs, monoNow));
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(() => {
if (!view?.game.vsAi) return;
const iv = setInterval(() => (now = Date.now()), 10_000);
const iv = setInterval(() => (monoNow = performance.now()), 10_000);
return () => clearInterval(iv);
});
// RACK_SIZE mirrors the engine's rules.RackSize (7 for every current variant). The exchange
@@ -225,6 +236,8 @@
source.draftGet(id).catch(() => ''),
]);
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);
// Seed the unread flag from the authoritative state (the live stream only raises it).
seedChatUnread(id, st.game.unreadChat, st.game.unreadMessages);
@@ -345,7 +358,11 @@
// While composing, reload so a draft overlapping the new move is reconciled; otherwise apply
// the move as a delta with no fetch.
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) {
// 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).
@@ -873,7 +890,7 @@
// 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.
if (view?.game.vsAi) {
const remaining = hintGateRemainingMs(hintUnlockAt, Date.now());
const remaining = hintGateRemainingMs(hintGateStart, gateLeftMs, performance.now());
if (remaining > 0) {
showToast(t('game.hintLockedIn', { n: hintLockMinutes(remaining) }), 'info');
return;
@@ -915,6 +932,12 @@
// The backend does not spend a hint when there is no move.
if (e instanceof GatewayError && e.code === 'no_hint_available') {
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 {
handleError(e);
}
+12 -2
View File
@@ -74,8 +74,13 @@ walletBalance():number {
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) {
builder.startObject(7);
builder.startObject(8);
}
static addGame(builder:flatbuffers.Builder, gameOffset:flatbuffers.Offset) {
@@ -130,12 +135,16 @@ static addWalletBalance(builder:flatbuffers.Builder, walletBalance:number) {
builder.addFieldInt32(6, walletBalance, 0);
}
static addHintUnlockLeftSeconds(builder:flatbuffers.Builder, hintUnlockLeftSeconds:number) {
builder.addFieldInt32(7, hintUnlockLeftSeconds, 0);
}
static endStateView(builder:flatbuffers.Builder):flatbuffers.Offset {
const offset = builder.endObject();
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.addGame(builder, gameOffset);
StateView.addSeat(builder, seat);
@@ -144,6 +153,7 @@ static createStateView(builder:flatbuffers.Builder, gameOffset:flatbuffers.Offse
StateView.addHintsRemaining(builder, hintsRemaining);
StateView.addAlphabet(builder, alphabetOffset);
StateView.addWalletBalance(builder, walletBalance);
StateView.addHintUnlockLeftSeconds(builder, hintUnlockLeftSeconds);
return StateView.endStateView(builder);
}
}
+1
View File
@@ -461,6 +461,7 @@ function decodeStateViewTable(v: fb.StateView): StateView {
bagLen: v.bagLen(),
hintsRemaining: v.hintsRemaining(),
walletBalance: v.walletBalance(),
hintUnlockLeftSeconds: v.hintUnlockLeftSeconds(),
};
}
+2 -10
View File
@@ -11,9 +11,6 @@ export interface MoveDelta {
move?: MoveRecord;
game?: GameView;
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
// 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 };
const view: StateView = {
...cached.view,
game: d.game,
bagLen: d.bagLen,
hintUnlockAtMs: d.hintUnlockAtMs ?? cached.view.hintUnlockAtMs,
};
const view: StateView = { ...cached.view, game: d.game, bagLen: d.bagLen };
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 {
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 === '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)', () => {
it('is 0 when the gate is open — no unlock time (the human first move, or a non-gated game)', () => {
expect(hintGateRemainingMs(undefined, 5000, 1000)).toBe(0);
expect(hintGateRemainingMs(0, 5000, 1000)).toBe(0);
describe('hintGateRemainingMs (the vs_ai idle-hint gate, monotonic)', () => {
it('is 0 when the gate is open — a null anchor (the human first move, or a non-gated game)', () => {
expect(hintGateRemainingMs(null, 60_000, 5000)).toBe(0);
});
it('is 0 once the unlock instant has passed (the gate is open)', () => {
expect(hintGateRemainingMs(1000, 1000, 1000)).toBe(0);
expect(hintGateRemainingMs(1000, 1500, 1000)).toBe(0);
it('is the window remaining minus the monotonic time elapsed since the anchor', () => {
// anchored at mono 1000 with 60s left; 20s of monotonic time later -> 40s left.
expect(hintGateRemainingMs(1000, 60_000, 1000 + 20_000)).toBe(40_000);
});
it('is the wall-clock time remaining while still gated', () => {
expect(hintGateRemainingMs(1000, 400, 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);
it('is 0 once the elapsed monotonic time reaches (or passes) the window', () => {
expect(hintGateRemainingMs(1000, 60_000, 1000 + 60_000)).toBe(0);
expect(hintGateRemainingMs(1000, 60_000, 1000 + 90_000)).toBe(0);
});
});
+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
* once it is available. hintUnlockAtMs is the wall-clock instant the hint opens (the robot's last
* move plus the idle window), persisted so the wait survives leaving and reopening the app; 0 or
* undefined means the gate is open (the human's first move, or a non-gated game).
*
* 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.
* once it is available. It counts down from a MONOTONIC clock (performance.now()), so a client clock
* change cannot skew it: gateStartMono is performance.now() captured when the source's "seconds left"
* 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 gate is open (the human's first move, or a non-gated game). The duration comes from the source
* (the SERVER clock online, the device clock offline) and is re-fetched on every load, so the wait
* both persists across a relaunch and stays immune to a live clock change.
*/
export function hintGateRemainingMs(
hintUnlockAtMs: number | undefined,
nowMs: number,
gateMs: number = HINT_GATE_MS,
): number {
if (!hintUnlockAtMs) return 0;
return Math.min(gateMs, Math.max(0, hintUnlockAtMs - nowMs));
export function hintGateRemainingMs(gateStartMono: number | null, gateLeftMs: number, monoNow: number): number {
if (gateStartMono === null) return 0;
return Math.max(0, gateLeftMs - (monoNow - gateStartMono));
}
/** 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 {
const set = this.listeners.get(entry.record.id);
if (!set) return;
const hintUnlockAtMs = this.hintUnlock(entry);
for (const m of moves) {
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);
}
if (entry.game.isOver) {
@@ -342,11 +341,14 @@ export class LocalSource implements GameLoopSource {
// --- 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;
// The vs_ai idle-hint seconds left, from the stored unlock instant (device wall clock, persisted
// for the offline record) minus now — capped at the window so a device clock set back cannot push
// it far ahead and freeze the gate, ceiled to whole seconds and floored at 0. The client anchors a
// monotonic countdown to this; 0 while open (a human-first opening, no robot move yet).
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 {
@@ -359,7 +361,7 @@ export class LocalSource implements GameLoopSource {
bagLen: entry.game.bagLength,
hintsRemaining: 1,
walletBalance: 0,
hintUnlockAtMs: this.hintUnlock(entry),
hintUnlockLeftSeconds: this.hintUnlockLeft(entry),
};
}
+6 -5
View File
@@ -82,10 +82,11 @@ export interface StateView {
bagLen: number;
hintsRemaining: 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;
/** For a vs_ai game, the seconds until the idle hint unlocks (computed by the source: the SERVER
* clock online, the device clock offline) — 0/undefined while open (the human's first move, or a
* non-vs_ai game). The client anchors a MONOTONIC countdown (performance.now()) to it on receipt,
* so a client clock change cannot skew it; a relaunch re-fetches a fresh value. See lib/hints. */
hintUnlockLeftSeconds?: number;
}
export interface MoveResult {
@@ -425,7 +426,7 @@ export interface GameList {
*/
export type PushEvent =
| { 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: 'chat_message'; message: ChatMessage }
| { kind: 'nudge'; gameId: string; fromUserId: string; senderName: string }