Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions client/src/adapter/engine-worker-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,10 @@ export class EngineWorkerClient {
return this.request<string>({ type: "exportState" });
}

async exportPersistedState(): Promise<string> {
return this.request<string>({ type: "exportPersistedState" });
}

async restoreState(stateJson: string): Promise<void> {
await this.request<null>({ type: "restoreState", stateJson });
}
Expand Down
8 changes: 8 additions & 0 deletions client/src/adapter/engine-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import init, {
apply_seat_mutation,
project_seat_view,
export_game_state_json,
export_persisted_game_state_json,
clear_game_state,
set_multiplayer_mode,
resolve_all,
Expand Down Expand Up @@ -73,6 +74,7 @@ type EngineRequest =
| { type: "restoreState"; id: number; stateJson: string }
| { type: "resumeMultiplayerHostState"; id: number; stateJson: string }
| { type: "exportState"; id: number }
| { type: "exportPersistedState"; id: number }
| { type: "loadCardDbFromUrl"; id: number }
| { type: "buildAiCardSubset"; id: number }
| { type: "evaluateDeckCompatibility"; id: number; request: unknown }
Expand Down Expand Up @@ -339,6 +341,12 @@ self.onmessage = async (e: MessageEvent<EngineRequest>) => {
break;
}

case "exportPersistedState": {
const json = export_persisted_game_state_json();
result(msg.id, json);
break;
}

case "resetGame": {
clear_game_state();
result(msg.id, null);
Expand Down
16 changes: 8 additions & 8 deletions client/src/adapter/p2p-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,13 +300,13 @@ export class P2PHostAdapter implements EngineAdapter {
/** True when the adapter was constructed from a persisted session (resume flow). */
private readonly isResume: boolean;
/**
* Pending GameState snapshot to hand to `wasm.resumeMultiplayerHostState`
* during `initialize()`. Set in the constructor from `resumeData.state`;
* Pending persisted snapshot to hand to `wasm.resumeMultiplayerHostState`
* during `initialize()`. Set in the constructor from `resumeData.persistedJson`;
* nulled after the WASM call consumes it. Held on the adapter rather
* than threaded through `initialize()` so the EngineAdapter interface
* stays uniform across fresh/resume flows.
*/
private resumeGameState: GameState | null = null;
private resumeGameStateJson: string | null = null;

constructor(
private readonly hostDeckData: unknown,
Expand Down Expand Up @@ -354,7 +354,7 @@ export class P2PHostAdapter implements EngineAdapter {
gameId: string;
roomCode: string;
hostDisplayName?: string;
resumeData?: { state: GameState; session: PersistedP2PHostSession };
resumeData?: { persistedJson: string; session: PersistedP2PHostSession };
},
) {
if (playerCount < 2 || playerCount > 6) {
Expand All @@ -379,7 +379,7 @@ export class P2PHostAdapter implements EngineAdapter {
this.isResume = persistence?.resumeData !== undefined;

if (persistence?.resumeData) {
this.resumeGameState = persistence.resumeData.state;
this.resumeGameStateJson = persistence.resumeData.persistedJson;
this.rehydrateFromPersistedSession(persistence.resumeData.session);
this.pregameSeatView = seatStateToView(this.pregameSeatState);
}
Expand Down Expand Up @@ -776,9 +776,9 @@ export class P2PHostAdapter implements EngineAdapter {
// mirrors server-core's `from_persisted` pattern. Fresh-host path:
// just flip the flag; engine state is populated by the guests
// joining + `initializeGame`.
if (this.isResume && this.resumeGameState) {
await this.wasm.resumeMultiplayerHostState(this.resumeGameState);
this.resumeGameState = null;
if (this.isResume && this.resumeGameStateJson) {
await this.wasm.resumeMultiplayerHostState(this.resumeGameStateJson);
this.resumeGameStateJson = null;
traceAdapter("Host", "initialize-resume", {
tokens: this.playerTokens.size,
gameStarted: this.gameStarted,
Expand Down
4 changes: 3 additions & 1 deletion client/src/adapter/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2639,7 +2639,9 @@ export interface EngineAdapter {
aiSeats: { playerId: number; difficulty: string }[],
maxResolutions?: number,
): Promise<BatchResolveResult>;
restoreState(state: GameState): void | Promise<void>;
restoreState(state: GameState, persistedJson?: string): void | Promise<void>;
/** Authoritative persisted envelope for browser/P2P resume (rollback sidecar). */
exportPersistedState?(): Promise<string>;
dispose(): void;

/**
Expand Down
21 changes: 15 additions & 6 deletions client/src/adapter/wasm-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,14 +429,20 @@ export class WasmAdapter implements EngineAdapter {
throw new Error("resolveAll requires worker-based engine");
}

async restoreState(state: GameState): Promise<void> {
async restoreState(state: GameState, persistedJson?: string): Promise<void> {
this.assertInitialized();
await this.ensureCardDb();
const json = JSON.stringify(state);
const json = persistedJson ?? JSON.stringify(state);
if (this.engine) await this.engine.restoreState(json);
else await this.fallback!.restoreState(json);
}

async exportPersistedState(): Promise<string> {
this.assertInitialized();
if (this.engine) return this.engine.exportPersistedState();
return this.fallback!.exportPersistedState();
}

/**
* Toggle the engine's multiplayer enforcement flag. When enabled, the
* Rust side refuses `restore_game_state` with a descriptive error —
Expand Down Expand Up @@ -479,9 +485,8 @@ export class WasmAdapter implements EngineAdapter {
* Distinct from `restoreState` (undo semantics, deterministic re-seed).
* Mirrors `server-core::GameSession::from_persisted`.
*/
async resumeMultiplayerHostState(state: GameState): Promise<void> {
async resumeMultiplayerHostState(persistedJson: string): Promise<void> {
this.assertInitialized();
const json = JSON.stringify(state);
if (this.engine) {
// Ensure the card database is loaded before the engine rehydrates
// ability definitions on restore. Same sequential-queue guarantee
Expand All @@ -492,9 +497,9 @@ export class WasmAdapter implements EngineAdapter {
() => { /* card DB is best-effort */ },
);
}
await this.engine.resumeMultiplayerHostState(json);
await this.engine.resumeMultiplayerHostState(persistedJson);
} else {
this.fallback!.resumeMultiplayerHostState(json);
this.fallback!.resumeMultiplayerHostState(persistedJson);
}
}

Expand Down Expand Up @@ -641,6 +646,7 @@ interface MainThreadFallback {
getViewerSnapshot(viewerId: number): Promise<ViewerSnapshot>;
getAiAction(difficulty: string, playerId: number, waitingForType?: WaitingFor["type"]): Promise<GameAction | null>;
restoreState(stateJson: string): Promise<void>;
exportPersistedState(): Promise<string>;
resumeMultiplayerHostState(stateJson: string): void;
setMultiplayerMode(enabled: boolean): void;
applySeatMutation(stateJson: string, mutationJson: string): Promise<unknown>;
Expand Down Expand Up @@ -733,6 +739,9 @@ async function createMainThreadFallback(): Promise<MainThreadFallback> {
restoreState: (stateJson: string) =>
enqueue(() => wasm.restore_game_state(stateJson)),

exportPersistedState: () =>
enqueue(() => wasm.export_persisted_game_state_json()),

resumeMultiplayerHostState: (stateJson: string) => {
enqueue(() => wasm.resume_multiplayer_host_state(stateJson));
},
Expand Down
8 changes: 4 additions & 4 deletions client/src/game/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { flashInGameRolls } from "./diceContest";
import i18n from "../i18n";
import { useAnimationStore } from "../stores/animationStore";
import { useAppNotificationStore } from "../stores/appToastStore";
import { isMultiplayerMode, useGameStore, legalResultState, saveGame, saveCheckpoints } from "../stores/gameStore";
import { isMultiplayerMode, useGameStore, legalResultState, saveGameWithAdapter, saveCheckpoints } from "../stores/gameStore";
import { getOpponentDisplayName } from "../stores/multiplayerStore";
import { usePreferencesStore } from "../stores/preferencesStore";
import { useUiStore } from "../stores/uiStore";
Expand Down Expand Up @@ -313,7 +313,7 @@ async function processAction(action: GameAction, actor: number): Promise<void> {
}
}
const { gameId } = useGameStore.getState();
if (gameId) saveGame(gameId, newState);
if (gameId) await saveGameWithAdapter(gameId, newState, adapter);

// 3c. Feed the throughput tracker: count stack entries that left the stack
// this action (resolved, countered, or otherwise removed), id-diffed so a
Expand Down Expand Up @@ -749,7 +749,7 @@ export async function restoreGameState(
turnCheckpoints: preservedCheckpoints,
});
if (gameId) {
await saveGame(gameId, restoredState);
await saveGameWithAdapter(gameId, restoredState, adapter);
await saveCheckpoints(gameId, preservedCheckpoints);
}

Expand Down Expand Up @@ -872,7 +872,7 @@ export async function dispatchResolveAll(

const { gameId } = useGameStore.getState();
const newState = useGameStore.getState().gameState;
if (gameId && newState) saveGame(gameId, newState);
if (gameId && newState) await saveGameWithAdapter(gameId, newState, adapter);
} finally {
batchResolveInProgress = false;
setIsResolvingAll(false);
Expand Down
20 changes: 12 additions & 8 deletions client/src/providers/GameProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
clearP2PHostSession,
loadActiveGame,
loadGame,
loadPersistedGameJson,
loadP2PHostSession,
saveActiveGame,
useGameStore,
Expand Down Expand Up @@ -711,15 +712,15 @@ export function GameProvider({
// keyed on `phase-<roomCode>`) still match. Partial state
// (only one record present) is treated as inconsistent:
// clear both and fall through to a fresh game.
const [savedState, savedSession] = await Promise.all([
loadGame(gameId),
const [savedPersistedJson, savedSession] = await Promise.all([
loadPersistedGameJson(gameId),
loadP2PHostSession(gameId),
]);
signal.throwIfAborted();

const isResume =
savedState !== null && savedSession !== null && savedSession.gameStarted;
if ((savedState !== null) !== (savedSession !== null)) {
savedPersistedJson !== null && savedSession !== null && savedSession.gameStarted;
if ((savedPersistedJson !== null) !== (savedSession !== null)) {
// Inconsistent: one record present, the other missing.
// Drop both so the menu's Resume button doesn't re-offer.
await clearGame(gameId);
Expand Down Expand Up @@ -800,8 +801,8 @@ export function GameProvider({
gameId,
roomCode: host.roomCode,
hostDisplayName: useMultiplayerStore.getState().displayName || undefined,
resumeData: isResume && savedState && savedSession
? { state: savedState, session: savedSession }
resumeData: isResume && savedPersistedJson && savedSession
? { persistedJson: savedPersistedJson, session: savedSession }
: undefined,
},
);
Expand Down Expand Up @@ -1142,7 +1143,10 @@ export function GameProvider({
const setupLocal = async () => {
if (cancelled) return;

const savedState = await loadGame(gameId);
const [savedState, persistedJson] = await Promise.all([
loadGame(gameId),
loadPersistedGameJson(gameId),
]);
const adapter = getSharedAdapter();

if (savedState) {
Expand All @@ -1151,7 +1155,7 @@ export function GameProvider({
// and handle token creation / effects after resume.
await ensureCardDatabase().catch(() => {/* card DB is best-effort */});
if (cancelled) return;
await resumeGame(gameId, adapter, savedState);
await resumeGame(gameId, adapter, savedState, persistedJson);
if (cancelled) return;
// Derive player count from the restored state — the URL param may be
// absent on resume (e.g. navigating directly to a saved game URL).
Expand Down
65 changes: 61 additions & 4 deletions client/src/services/gamePersistence.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createStore, del, get, set } from "idb-keyval";

import type { FormatConfig, GameState, MatchConfig } from "../adapter/types";
import type { EngineAdapter } from "../adapter/types";
import type { SeatState } from "../multiplayer/seatTypes";
import { ACTIVE_GAME_KEY, GAME_CHECKPOINTS_PREFIX, GAME_KEY_PREFIX } from "../constants/storage";

Expand Down Expand Up @@ -98,7 +99,31 @@ function getGameStore(): ReturnType<typeof createStore> {

// ── Game State (IndexedDB) ──────────────────────────────────────────────

export async function saveGame(gameId: string, state: GameState): Promise<void> {
/** Wire envelope for authoritative browser/P2P persistence. */
export interface PersistedGameStateWire {
state: GameState;
pending_cast_sacrifice_rollbacks?: Record<string, unknown>;
}

function isPersistedGameStateWire(value: unknown): value is PersistedGameStateWire {
return (
typeof value === "object"
&& value !== null
&& "state" in value
&& typeof (value as PersistedGameStateWire).state === "object"
);
}

/**
* Persist authoritative engine state. When `persistedJson` is provided it is
* written verbatim (includes sacrifice rollback sidecar); otherwise the bare
* `GameState` is stored for legacy/manual-import paths.
*/
export async function saveGame(
gameId: string,
state: GameState,
persistedJson?: string,
): Promise<void> {
if (
state.match_phase === "Completed"
|| (!state.match_phase && state.waiting_for.type === "GameOver")
Expand All @@ -107,21 +132,53 @@ export async function saveGame(gameId: string, state: GameState): Promise<void>
return;
}
try {
await set(GAME_KEY_PREFIX + gameId, state, getGameStore());
const toStore = persistedJson ? JSON.parse(persistedJson) : state;
await set(GAME_KEY_PREFIX + gameId, toStore, getGameStore());
} catch (err) {
console.warn("[saveGame] IndexedDB write failed:", err);
}
}

export async function loadGame(gameId: string): Promise<GameState | null> {
try {
const state = await get<GameState>(GAME_KEY_PREFIX + gameId, getGameStore());
return state ?? null;
const raw = await get<unknown>(GAME_KEY_PREFIX + gameId, getGameStore());
if (!raw) return null;
if (isPersistedGameStateWire(raw)) return raw.state;
return raw as GameState;
} catch {
return null;
}
}

/** Load the raw persisted envelope for engine resume (includes rollback sidecar). */
export async function loadPersistedGameJson(gameId: string): Promise<string | null> {
try {
const raw = await get<unknown>(GAME_KEY_PREFIX + gameId, getGameStore());
if (!raw) return null;
return JSON.stringify(raw);
} catch {
return null;
}
}

/** Persist authoritative engine state when the adapter can export rollbacks. */
export async function saveGameWithAdapter(
gameId: string,
state: GameState,
adapter: EngineAdapter,
): Promise<void> {
if (adapter.exportPersistedState) {
try {
const persistedJson = await adapter.exportPersistedState();
await saveGame(gameId, state, persistedJson);
return;
} catch (err) {
console.warn("[saveGameWithAdapter] exportPersistedState failed:", err);
}
}
await saveGame(gameId, state);
}

export async function clearGame(gameId: string): Promise<void> {
try {
await del(GAME_KEY_PREFIX + gameId, getGameStore());
Expand Down
Loading
Loading