Files
galaxy-game/ui/frontend/tests/game-state.test.ts
T
Ilia Denisov ce7a66b3e6 ui/phase-11: map wired to live game state
Replaces the Phase 10 map stub with live planet rendering driven by
`user.games.report`, and wires the header turn counter to the same
data. Phase 11's frontend sits on a per-game `GameStateStore` that
lives in `lib/game-state.svelte.ts`: the in-game shell layout
instantiates one per game, exposes it through Svelte context, and
disposes it on remount. The store discovers the game's current turn
through `lobby.my.games.list`, fetches the matching report, and
exposes a TS-friendly snapshot to the header turn counter, the map
view, and the inspector / order / calculator tabs that later phases
will plug onto the same instance.

The pipeline forced one cross-stage decision: the user surface needs
the current turn number to know which report to fetch, but
`GameSummary` did not expose it. Phase 11 extends the lobby
catalogue (FB schema, transcoder, Go model, backend
gameSummaryWire, gateway decoders, openapi, TS bindings,
api/lobby.ts) with `current_turn:int32`. The data was already
tracked in backend's `RuntimeSnapshot.CurrentTurn`; surfacing it is
a wire change only. Two alternatives were rejected: a brand-new
`user.games.state` message (full wire-flow for one field) and
hard-coding `turn=0` (works for the dev sandbox, which never
advances past zero, but renders the initial state for any real
game). The change crosses Phase 8's already-shipped catalogue per
the project's "decisions baked back into the live plan" rule —
existing tests and fixtures are updated in the same patch.

The state binding lives in `map/state-binding.ts::reportToWorld`:
one Point primitive per planet across all four kinds (local /
other / uninhabited / unidentified) with distinct fill colours,
fill alphas, and point radii so the user can tell them apart at a
glance. The planet engine number is reused as the primitive id so
a hit-test result resolves directly to a planet without an extra
lookup table. Zero-planet reports yield a well-formed empty world;
malformed dimensions fall back to 1×1 so a bad report cannot crash
the renderer.

The map view's mount effect creates the renderer once and skips
re-mount on no-op refreshes (same turn, same wrap mode); a turn
change or wrap-mode flip disposes and recreates it. The renderer's
external API does not yet expose `setWorld`; Phase 24 / 34 will
extract it once high-frequency updates land. The store installs a
`visibilitychange` listener that calls `refresh()` when the tab
regains focus.

Wrap-mode preference uses `Cache` namespace `game-prefs`, key
`<gameId>/wrap-mode`, default `torus`. Phase 11 reads through
`store.wrapMode`; Phase 29 wires the toggle UI on top of
`setWrapMode`.

Tests: Vitest unit coverage for `reportToWorld` (every kind,
ids, styling, empty / zero-dimension edges, priority order) and
for the store lifecycle (init success, missing-membership error,
forbidden-result error, `setTurn`, wrap-mode persistence across
instances, `failBootstrap`). Playwright e2e mocks the gateway for
`lobby.my.games.list` and `user.games.report` and asserts the
live data path: turn counter shows the reported turn,
`active-view-map` flips to `data-status="ready"`, and
`data-planet-count` matches the fixture count. The zero-planet
regression and the missing-membership error path are covered.

Phase 11 status stays `pending` in `ui/PLAN.md` until the local-ci
run lands green; flipping to `done` follows in the next commit per
the per-stage CI gate in `CLAUDE.md`.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 21:17:17 +02:00

265 lines
7.5 KiB
TypeScript

// Vitest coverage for the per-game runes store
// (`lib/game-state.svelte.ts`). The test stubs `lobby.my.games.list`
// and `user.games.report` at module level and drives the store
// through its lifecycle: init → ready → error → setTurn → wrap-mode
// persistence.
import "@testing-library/jest-dom/vitest";
import "fake-indexeddb/auto";
import {
afterEach,
beforeEach,
describe,
expect,
test,
vi,
} from "vitest";
import { Builder } from "flatbuffers";
import { GameStateStore } from "../src/lib/game-state.svelte";
import type { GalaxyClient } from "../src/api/galaxy-client";
import type { Cache } from "../src/platform/store/index";
import { IDBCache } from "../src/platform/store/idb-cache";
import { openGalaxyDB, type GalaxyDB } from "../src/platform/store/idb";
import type { IDBPDatabase } from "idb";
import { UUID } from "../src/proto/galaxy/fbs/common";
import {
LocalPlanet,
Report,
} from "../src/proto/galaxy/fbs/report";
const listMyGamesSpy = vi.fn();
vi.mock("../src/api/lobby", async () => {
const actual = await vi.importActual<typeof import("../src/api/lobby")>(
"../src/api/lobby",
);
return {
...actual,
listMyGames: (...args: unknown[]) => listMyGamesSpy(...args),
};
});
let db: IDBPDatabase<GalaxyDB>;
let dbName: string;
let cache: Cache;
beforeEach(async () => {
dbName = `galaxy-game-state-test-${crypto.randomUUID()}`;
db = await openGalaxyDB(dbName);
cache = new IDBCache(db);
listMyGamesSpy.mockReset();
});
afterEach(async () => {
db.close();
await new Promise<void>((resolve) => {
const req = indexedDB.deleteDatabase(dbName);
req.onsuccess = () => resolve();
req.onerror = () => resolve();
req.onblocked = () => resolve();
});
});
const GAME_ID = "11111111-2222-3333-4444-555555555555";
function makeGameSummary(currentTurn: number): {
gameId: string;
gameName: string;
gameType: string;
status: string;
ownerUserId: string;
minPlayers: number;
maxPlayers: number;
enrollmentEndsAt: Date;
createdAt: Date;
updatedAt: Date;
currentTurn: number;
} {
return {
gameId: GAME_ID,
gameName: "Test Game",
gameType: "private",
status: "running",
ownerUserId: "owner-1",
minPlayers: 2,
maxPlayers: 8,
enrollmentEndsAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
currentTurn,
};
}
interface PlanetFixture {
number: number;
name: string;
x: number;
y: number;
}
function buildReportPayload(opts: {
turn: number;
width?: number;
height?: number;
planets?: PlanetFixture[];
}): Uint8Array {
const builder = new Builder(256);
const planetOffsets = (opts.planets ?? []).map((planet) => {
const name = builder.createString(planet.name);
LocalPlanet.startLocalPlanet(builder);
LocalPlanet.addNumber(builder, BigInt(planet.number));
LocalPlanet.addX(builder, planet.x);
LocalPlanet.addY(builder, planet.y);
LocalPlanet.addName(builder, name);
LocalPlanet.addSize(builder, 10);
LocalPlanet.addResources(builder, 0.5);
return LocalPlanet.endLocalPlanet(builder);
});
const localPlanetVec =
planetOffsets.length === 0
? null
: Report.createLocalPlanetVector(builder, planetOffsets);
Report.startReport(builder);
Report.addTurn(builder, BigInt(opts.turn));
Report.addWidth(builder, opts.width ?? 4000);
Report.addHeight(builder, opts.height ?? 4000);
Report.addPlanetCount(builder, planetOffsets.length);
if (localPlanetVec !== null) {
Report.addLocalPlanet(builder, localPlanetVec);
}
const reportOff = Report.endReport(builder);
builder.finish(reportOff);
return builder.asUint8Array();
}
function makeFakeClient(
executeCommand: (
messageType: string,
payload: Uint8Array,
) => Promise<{ resultCode: string; payloadBytes: Uint8Array }>,
): GalaxyClient {
return { executeCommand } as unknown as GalaxyClient;
}
describe("GameStateStore", () => {
test("init transitions through loading and ready when both calls succeed", async () => {
listMyGamesSpy.mockResolvedValue([makeGameSummary(7)]);
const calls: Array<{ messageType: string; payload: Uint8Array }> = [];
const client = makeFakeClient(async (messageType, payload) => {
calls.push({ messageType, payload });
return {
resultCode: "ok",
payloadBytes: buildReportPayload({
turn: 7,
planets: [{ number: 1, name: "Home", x: 100, y: 100 }],
}),
};
});
const store = new GameStateStore();
expect(store.status).toBe("idle");
await store.init({ client, cache, gameId: GAME_ID });
expect(listMyGamesSpy).toHaveBeenCalledTimes(1);
expect(calls.length).toBe(1);
expect(calls[0]?.messageType).toBe("user.games.report");
expect(store.status).toBe("ready");
expect(store.report).not.toBeNull();
expect(store.report?.turn).toBe(7);
expect(store.report?.planets.length).toBe(1);
expect(store.report?.planets[0]?.kind).toBe("local");
store.dispose();
});
test("init surfaces an error when the game is missing from lobby", async () => {
listMyGamesSpy.mockResolvedValue([makeGameSummary(0).gameId === "other" ? null : makeGameSummary(0)].filter(Boolean));
// Replace the helper above's awkward filter with an explicit
// mismatched id so the lookup miss is unambiguous.
listMyGamesSpy.mockResolvedValue([
{ ...makeGameSummary(2), gameId: "different-game-id" },
]);
const client = makeFakeClient(async () => ({
resultCode: "ok",
payloadBytes: buildReportPayload({ turn: 0 }),
}));
const store = new GameStateStore();
await store.init({ client, cache, gameId: GAME_ID });
expect(store.status).toBe("error");
expect(store.error).toMatch(/not in your list/);
expect(store.report).toBeNull();
store.dispose();
});
test("init surfaces error when user.games.report returns a non-ok result", async () => {
listMyGamesSpy.mockResolvedValue([makeGameSummary(0)]);
const client = makeFakeClient(async () => ({
resultCode: "forbidden",
payloadBytes: new TextEncoder().encode(
JSON.stringify({ code: "forbidden", message: "no membership" }),
),
}));
const store = new GameStateStore();
await store.init({ client, cache, gameId: GAME_ID });
expect(store.status).toBe("error");
expect(store.error).toMatch(/no membership/);
store.dispose();
});
test("setTurn loads a different turn snapshot", async () => {
listMyGamesSpy.mockResolvedValue([makeGameSummary(3)]);
const turns: number[] = [];
const client = makeFakeClient(async () => {
const turn = turns.length === 0 ? 3 : 1;
turns.push(turn);
return {
resultCode: "ok",
payloadBytes: buildReportPayload({ turn }),
};
});
const store = new GameStateStore();
await store.init({ client, cache, gameId: GAME_ID });
expect(store.report?.turn).toBe(3);
await store.setTurn(1);
expect(store.status).toBe("ready");
expect(store.report?.turn).toBe(1);
store.dispose();
});
test("setWrapMode persists across instances through Cache", async () => {
listMyGamesSpy.mockResolvedValue([makeGameSummary(0)]);
const client = makeFakeClient(async () => ({
resultCode: "ok",
payloadBytes: buildReportPayload({ turn: 0 }),
}));
const a = new GameStateStore();
await a.init({ client, cache, gameId: GAME_ID });
expect(a.wrapMode).toBe("torus");
await a.setWrapMode("no-wrap");
expect(a.wrapMode).toBe("no-wrap");
a.dispose();
const b = new GameStateStore();
await b.init({ client, cache, gameId: GAME_ID });
expect(b.wrapMode).toBe("no-wrap");
b.dispose();
});
test("failBootstrap moves the store into the error state with the given message", () => {
const store = new GameStateStore();
store.failBootstrap("device session missing");
expect(store.status).toBe("error");
expect(store.error).toBe("device session missing");
});
});