v0.5.0 — multiplayer Phases 2 and 3: a server that runs a game and survives being restarted
Phases 0-1 shipped in v0.4.0 (seat/identity split, per-player turn state, the Session boundary). This lands Phase 2 (server core, one game, no lobby) and Phase 3 (persistence and resumption) per docs/architecture/multiplayer.md §12. Phases 4-6 (lobby/reconnection, the 22 opponent-directed cards, StartOS packaging) are still ahead. Phase 2: src/server/session.ts hosts a game in pure logic (no sockets) on top of game.ts's existing Game/submit/currentActor/actionMenu; it verifies seat === currentActor(game) itself before calling submit, since submit() trusts its caller and a server can't. src/server/http.ts and index.ts add POST /api/game, GET /api/stream (SSE, per-seat), POST /api/intent, and static serving of dist/. src/sim/frame-delta.ts is a purpose-built per-seat board delta for one live push at a time. Found and fixed along the way: actionMenu(game, seat) only used seat for the hand field, so a server computing every connected seat's Menu would have handed the acting player's legal moves to a waiting seat. Verified with a live end-to-end smoke test (2-player game, two SSE streams, a rejected intent from the wrong seat, an idempotent resend) plus test/server/session.test.ts and test/redaction.test.ts. Not verified: an actual browser (none available in this environment). Phase 3: src/server/persistence.ts writes game.json and turn-timings.json, atomic-rewrite-then- rename. game.ts gained fromMultiplayerSave, fixing a narration-attribution bug found while testing it (fromSave's replay loop drops the actor argument, invisible in solitaire, unreadable the moment there's more than one seat — fromSave itself still has this gap, deliberately untouched). Verified live: server killed and restarted mid-game, both seats reconnected exactly where they left off. Two rules bugs found while building this: the New Train phase never implemented its car-placement round (every car of every train was placed by the Superintendent alone, in every mode, all along — now reads the round position off tray.consist.length); and victory conditions are now one shared, configurable GameConfig set across solitaire/competitive/coop instead of a fixed length lookup and a dead firstToTarget condition. Also folds in the three fixes already released on the patch line as v0.4.9b/c/d: a switching train's crew badge failing to draw once it left the Office square, an unload that always took the westmost car regardless of which was picked, and a legal decision that could render with zero buttons. docs/testing/0.5.0-test-plan.md and three reported-bug save files (docs/station-master-seed*.json) included for reproducibility. tools/jitsi-harness/ deliberately left untracked — unrelated side-project work, not part of this release. 635 tests, 0 failures.
This commit is contained in:
+83
-9
@@ -18,8 +18,9 @@
|
||||
import type { Intent } from '../engine/intents.ts';
|
||||
import type { Frame } from '../sim/view.ts';
|
||||
import type { PlayerIndex } from '../engine/state.ts';
|
||||
import type { HouseRuleOverrides } from '../engine/content.ts';
|
||||
import type { Game, Menu, Save } from './game.ts';
|
||||
import { applyDelta } from '../sim/frame-delta.ts';
|
||||
import type { FrameDelta } from '../sim/frame-delta.ts';
|
||||
import type { Game, Menu, NewGameOptions, Save } from './game.ts';
|
||||
import {
|
||||
actionMenu,
|
||||
configWith,
|
||||
@@ -115,14 +116,14 @@ export type LocalSession = Session & {
|
||||
* `Game` is mutated in place by `submit`, so the wrapper keeps a mutable reference rather than
|
||||
* copying — `undo` and `restore` replace the whole game, which is why `game` is a getter.
|
||||
*
|
||||
* It takes `rules` rather than a whole `GameConfig` because DEALING is the only thing on the far
|
||||
* side of this that the page is allowed to decide. A config carries the mode, the victory condition
|
||||
* and the optional rules — table settings a lobby owns — and handing main.ts a `GameConfig` to build
|
||||
* meant importing the engine's own defaults into the page, which is the boundary `session.test.ts`
|
||||
* guards. The seed and the house rules are the two things a player picks when they press New game.
|
||||
* It takes `NewGameOptions` rather than a whole `GameConfig` because DEALING is the only thing on the
|
||||
* far side of this that the page is allowed to decide. A config carries the mode and the optional
|
||||
* rules — table settings a lobby owns — and handing main.ts a `GameConfig` to build meant importing
|
||||
* the engine's own defaults into the page, which is the boundary `session.test.ts` guards. The seed,
|
||||
* the house rules and the victory-condition dials are what a player picks when they press New game.
|
||||
*/
|
||||
export function createLocalSession(seed: number, rules?: HouseRuleOverrides): LocalSession {
|
||||
let game: Game = rules ? newGame(seed, configWith(rules)) : newGame(seed);
|
||||
export function createLocalSession(seed: number, options?: NewGameOptions): LocalSession {
|
||||
let game: Game = options ? newGame(seed, configWith(options)) : newGame(seed);
|
||||
const listeners = new Set<() => void>();
|
||||
const changed = (): void => {
|
||||
for (const fn of [...listeners]) fn();
|
||||
@@ -187,3 +188,76 @@ export function createLocalSession(seed: number, rules?: HouseRuleOverrides): Lo
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The push envelope `src/server/session.ts` sends over SSE — mirrored here rather than imported,
|
||||
* so this file never depends on anything under `src/server/` even at the type level. */
|
||||
type Push = { frame: FrameDelta; menu: Menu | null; lines: { text: string; tone: string }[] };
|
||||
|
||||
/**
|
||||
* A session backed by a server (Phase 2). Holds no authoritative state — no deck order, no other
|
||||
* seat's hand — only the last `Frame`/`Menu` a push actually told it. `capabilities` are all `false`:
|
||||
* undo would have to un-see what other players already saw, a local save is meaningless when the
|
||||
* server is the store, and dealing a new game is the lobby's job (Phase 4).
|
||||
*
|
||||
* Construction is synchronous (the `Session` interface has no async surface), but the first real
|
||||
* `Frame` only exists once the SSE connection's first push arrives — `main.ts` accounts for this by
|
||||
* not rendering until `subscribe`'s callback fires at least once for a session whose `capabilities`
|
||||
* are all `false` (a `LocalSession` always has data the instant it is constructed; this does not).
|
||||
*/
|
||||
export function createRemoteSession(seat: PlayerIndex, secret: string): Session {
|
||||
let frame: Frame | null = null;
|
||||
let menu: Menu | null = null;
|
||||
let lines: { text: string; tone: string }[] = [];
|
||||
let nextSeq = 1;
|
||||
const listeners = new Set<() => void>();
|
||||
const changed = (): void => {
|
||||
for (const fn of [...listeners]) fn();
|
||||
};
|
||||
|
||||
const qs = `seat=${seat}&secret=${encodeURIComponent(secret)}`;
|
||||
const source = new EventSource(`/api/stream?${qs}`);
|
||||
source.onmessage = (ev: MessageEvent<string>) => {
|
||||
const push = JSON.parse(ev.data) as Push;
|
||||
frame = applyDelta(frame, push.frame);
|
||||
menu = push.menu;
|
||||
lines = [...lines, ...push.lines];
|
||||
changed();
|
||||
};
|
||||
|
||||
const need = (): Frame => {
|
||||
if (frame === null) throw new Error('RemoteSession.view() called before the first Frame arrived');
|
||||
return frame;
|
||||
};
|
||||
|
||||
return {
|
||||
view: need,
|
||||
menu: () => menu ?? { options: [], direct: [], placeable: [], hand: [], makeUp: null },
|
||||
seat: () => seat,
|
||||
actor: () => need().actor,
|
||||
overHandLimit: () => need().overHandLimit,
|
||||
handPlayable: () => (menu?.hand ?? []).map((h) => h.playNow !== null),
|
||||
async submit(intent: Intent): Promise<boolean> {
|
||||
const seq = nextSeq++;
|
||||
const res = await fetch(`/api/intent?${qs}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ seq, intent }),
|
||||
});
|
||||
const result = (await res.json()) as { ok: boolean; code?: string };
|
||||
// The visible update arrives via the SSE push (broadcast to every seat, including this one),
|
||||
// not from this response — this only reports whether the rules accepted it.
|
||||
return result.ok;
|
||||
},
|
||||
subscribe(fn: () => void) {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
},
|
||||
capabilities: { undo: false, saveLocal: false, newGame: false },
|
||||
|
||||
lines: () => lines,
|
||||
takeCues: () => [],
|
||||
takeScheduled: () => null,
|
||||
takeAnnouncement: () => null,
|
||||
justDrawn: () => null,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user