v0.5.1 — multiplayer Phase 4: lobby, sessions, reconnection

A real server existed since v0.5.0 but nobody could reach it without a hand-built ?seat=&secret=
URL. This is what makes it a game you can actually create or join.

The server now hosts more than one game: src/server/lobby.ts (new) is pure logic — creating,
joining, bot seats, host transfer, starting — same split session.ts already draws for a running
game. persistence.ts gained one directory per gameId plus a top-level index so index.ts resumes
every saved game on boot. /api/stream and /api/intent now authenticate by session token instead of
?seat=&secret= — the token alone proves identity (lobby-and-sessions.md §1), so the join secret's
job ends at the lobby door.

Bots fill empty seats at Lobby.Start only, never take over a disconnected human (D8): session.ts
gained driveBots(), playing developerBot forward through consecutive bot seats after every accepted
intent. Disconnect keeps the seat and says so — Push gained an optional presence field, built
entirely by http.ts and never routed through the engine, since a disconnect is transport news, not
a GameEvent. Host rights pass to the earliest-joined remaining player if the host drops before
start.

Client: src/web/lobby.ts adds create/join forms and a live seating screen; localStorage replaces
?seat= for reconnecting straight back into a game already joined. A Multiplayer button sits beside
New game; the New Game dialog itself is untouched.

Found only by the live smoke test, not by typechecking: /api/intent read its token from the JSON
body while the client sends it in the query string (matching /api/stream) — every intent failed
"no such game" until caught by curl-level verification.

Doc fix: multiplayer.md's D18 said the player cap was 6; lobby-and-sessions.md §2 says 2-4 with the
reasoning and the test coverage to back it. The two had drifted apart. D18 now reads 2-4.

Not verified: an actual browser walking through the lobby screens — none available in this
environment, same limitation Phase 2's RemoteSession shipped under. 656 tests, 0 failures.

tools/jitsi-harness/ deliberately left untracked — unrelated side-project work, not part of this
release.
This commit is contained in:
Jesse
2026-08-21 05:25:47 -04:00
parent c3c5cbfeec
commit e76bd77099
17 changed files with 1420 additions and 125 deletions
+278 -64
View File
@@ -1,14 +1,20 @@
/**
* The HTTP/SSE wiring — Phase 2 of `docs/architecture/multiplayer.md` (§8-9, §12 steps 8 and 12).
* The HTTP/SSE wiring — Phase 2 of `docs/architecture/multiplayer.md` (§8-9, §12 steps 8 and 12),
* extended for Phase 4 (§12 steps 17-20) to a lobby and more than one game.
*
* Plain `node:http`, no framework: the project has zero runtime dependencies
* (`package.json`), and `scripts/build-web.ts` already shells out to `tsc` directly rather than
* reaching for a bundler — this matches that everywhere-else choice rather than introducing the
* first framework dependency for one route table.
*
* All the game logic lives in `session.ts`; this file is deliberately thin — routing, the join-secret
* gate, SSE mechanics, and static file serving for the built client (`dist/`, D16: the server serves
* the client, which is what makes same-origin work with no CORS).
* All the game logic lives in `session.ts` and `lobby.ts`; this file is deliberately thin — routing,
* the join-secret gate on the DOOR (create/join), token resolution once a player is through it, SSE
* mechanics, and static file serving for the built client (`dist/`, D16: the server serves the
* client, which is what makes same-origin work with no CORS).
*
* TOKENS REPLACE `?seat=&secret=` ON THE RUNNING-GAME ROUTES. `lobby-and-sessions.md` §1: the token
* already proves "I am the player who was in this game," which is the only identity claim `/api/stream`
* and `/api/intent` need — the join secret's job ends at the lobby door.
*/
import { createServer } from 'node:http';
@@ -19,23 +25,43 @@ import { extname, join, normalize } from 'node:path';
import type { Intent } from '../engine/intents.ts';
import type { GameConfig, PlayerIndex } from '../engine/state.ts';
import { appendTiming, writeGame } from './persistence.ts';
import {
appendTiming,
deleteLobby,
gameDir,
upsertIndexEntry,
writeGame,
writeLobby,
writeSessions,
} from './persistence.ts';
import { createSession } from './session.ts';
import type { GameSession, Push } from './session.ts';
import {
createLobby,
freshGameCode,
joinLobby,
reassignHost,
setBotSeat,
startLobby,
} from './lobby.ts';
import type { Lobby, PlayerSession } from './lobby.ts';
export type ServerOptions = {
port: number;
bindAddress: string;
/** D14 — a server-wide secret, passed out of band. Gates every `/api/*` route. */
/** D14 — a server-wide secret, passed out of band. Gates lobby creation and joining — the door;
* once a player is through it and holds a token, the token alone authenticates them. */
joinSecret: string;
/** The built client (`npm run build:web`'s `dist/`), served at `/` (D16). */
distDir: string;
/** Where `game.json`/`turn-timings.json` live (Phase 3). */
/** Where every game's files live, one subdirectory per `gameId` (`persistence.ts`'s `gameDir`). */
dataDir: string;
/** `package.json`'s version — stamped onto every write, checked on every load (§12 step 15). */
engineVersion: string;
/** Already reconstructed by `index.ts`'s load-on-start, or `null` for a fresh server. */
initialSession: GameSession | null;
/** Reconstructed by `index.ts`'s load-on-start. Empty maps for a fresh server. */
initialGames: Map<string, GameSession>;
initialLobbies: Map<string, Lobby>;
initialSessions: Map<string, PlayerSession>;
};
const MIME: Record<string, string> = {
@@ -82,92 +108,272 @@ async function serveStatic(distDir: string, urlPath: string, res: ServerResponse
}
}
/**
* What a lobby SSE push carries — the whole `Lobby`, since the seat list is small and a delta
* mechanism buys nothing at this size (`session.ts`'s `Push` deltas the BOARD, which is not this).
*
* `started` rides on the FINAL push of a lobby's life, sent the instant before the connection is
* closed at `Lobby.Start` — without it, the client's only signal that the game began is the stream
* simply ending, indistinguishable from a network hiccup that `EventSource` would otherwise retry.
*/
type LobbyPush = { lobby: Lobby; you: PlayerIndex; started: boolean };
export function startServer(opts: ServerOptions): void {
let session: GameSession | null = opts.initialSession;
// One open SSE response per seat — a second connection from the same seat replaces the first
// rather than fanning out to both (Phase 2 has no concept of "the same seat from two tabs").
const connections = new Map<PlayerIndex, ServerResponse>();
const eventIds = new Map<PlayerIndex, number>();
const games = opts.initialGames;
const lobbies = opts.initialLobbies;
const sessions = opts.initialSessions;
const gameCodes = new Map<string, string>(); // gameCode -> gameId, for /api/lobby/join
for (const [gameId, lobby] of lobbies) gameCodes.set(lobby.gameCode, gameId);
function checkSecret(url: URL, res: ServerResponse): boolean {
if (url.searchParams.get('secret') === opts.joinSecret) return true;
sendJson(res, 403, { error: 'bad or missing secret' });
return false;
// One open SSE response per (gameId, seat) for a running game, and per (gameId, token) for a
// lobby still being seated — a second connection from the same seat/token replaces the first
// rather than fanning out to both (no concept yet of "the same seat from two tabs").
const gameConnections = new Map<string, Map<PlayerIndex, ServerResponse>>();
const gameEventIds = new Map<string, Map<PlayerIndex, number>>();
const lobbyConnections = new Map<string, Map<string, ServerResponse>>();
function writeSse(res: ServerResponse, id: number, data: unknown): void {
res.write(`id: ${id}\ndata: ${JSON.stringify(data)}\n\n`);
}
function writeSse(seat: PlayerIndex, push: Push): void {
const res = connections.get(seat);
if (!res) return; // that seat is not currently connected — Phase 4's reconnect story, not this one
const id = (eventIds.get(seat) ?? 0) + 1;
eventIds.set(seat, id);
res.write(`id: ${id}\ndata: ${JSON.stringify(push)}\n\n`);
function nextEventId(gameId: string, seat: PlayerIndex): number {
const ids = gameEventIds.get(gameId) ?? new Map<PlayerIndex, number>();
const id = (ids.get(seat) ?? 0) + 1;
ids.set(seat, id);
gameEventIds.set(gameId, ids);
return id;
}
function broadcast(pushes: Map<PlayerIndex, Push>): void {
for (const [seat, push] of pushes) writeSse(seat, push);
function broadcastGame(gameId: string, pushes: Map<PlayerIndex, Push>): void {
const conns = gameConnections.get(gameId);
if (!conns) return;
for (const [seat, push] of pushes) {
const res = conns.get(seat);
if (res) writeSse(res, nextEventId(gameId, seat), push);
}
}
/**
* Presence is transport-layer news about a CONNECTION, never a `GameEvent` — it does not go
* through `session.ts` at all (`lobby-and-sessions.md` §5). Sent to every OTHER currently
* connected seat of the same game as a presence-only push (an empty board delta, no menu, no new
* lines) rather than inventing a second SSE event type — one message shape for the client to parse.
*/
function broadcastPresence(gameId: string, seat: PlayerIndex, connected: boolean): void {
const conns = gameConnections.get(gameId);
if (!conns) return;
for (const [other, res] of conns) {
if (other === seat) continue;
const push: Push = { menu: null, lines: [], presence: { seat, connected } };
writeSse(res, nextEventId(gameId, other), push);
}
}
function broadcastLobby(gameId: string): void {
const lobby = lobbies.get(gameId);
const conns = lobbyConnections.get(gameId);
if (!lobby || !conns) return;
for (const [token, res] of conns) {
const ps = sessions.get(token);
if (!ps) continue;
writeSse(res, 0, { lobby, you: ps.player, started: false } satisfies LobbyPush);
}
}
async function persistLobby(lobby: Lobby): Promise<void> {
lobbies.set(lobby.gameId, lobby);
gameCodes.set(lobby.gameCode, lobby.gameId);
await writeLobby(opts.dataDir, lobby);
await upsertIndexEntry(opts.dataDir, { gameId: lobby.gameId, gameCode: lobby.gameCode, status: 'lobby' });
}
async function persistSession(ps: PlayerSession): Promise<void> {
sessions.set(ps.token, ps);
const all = [...sessions.values()].filter((s) => s.gameId === ps.gameId);
await writeSessions(opts.dataDir, ps.gameId, all);
}
const server = createServer((req, res) => {
void (async () => {
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
if (url.pathname === '/api/game' && req.method === 'POST') {
if (!checkSecret(url, res)) return;
if (session) {
sendJson(res, 409, { error: 'a game already exists on this server' });
// -- Lobby: creating and joining (the door — join-secret gated) --------------------------
if (url.pathname === '/api/lobby/create' && req.method === 'POST') {
const body = (await readJson(req)) as { secret?: string; config?: GameConfig; displayName?: string };
if (body.secret !== opts.joinSecret) {
sendJson(res, 403, { error: 'bad or missing secret' });
return;
}
const body = (await readJson(req)) as { config?: GameConfig; playerNames?: string[]; seed?: number };
if (!body.config || !Array.isArray(body.playerNames) || body.playerNames.length < 1) {
sendJson(res, 400, { error: 'expected { config, playerNames }' });
if (!body.config || typeof body.displayName !== 'string' || body.displayName.trim() === '') {
sendJson(res, 400, { error: 'expected { secret, config, displayName }' });
return;
}
session = createSession(body.seed ?? Math.floor(Math.random() * 1e9), body.config, body.playerNames);
// Persisted immediately, empty history and all — a crash one second after creation should
// still resume as "the game exists, day 1, nobody has moved" rather than vanish entirely.
await writeGame(opts.dataDir, session.exportSave(), opts.engineVersion);
sendJson(res, 200, { ok: true, playerCount: session.playerCount });
const gameCode = freshGameCode((code) => gameCodes.has(code));
const { lobby, session } = createLobby(body.config, body.displayName.trim(), gameCode);
await persistLobby(lobby);
await persistSession(session);
sendJson(res, 200, { gameId: lobby.gameId, gameCode: lobby.gameCode, token: session.token, player: session.player });
return;
}
if (url.pathname === '/api/stream' && req.method === 'GET') {
if (!checkSecret(url, res)) return;
if (!session) {
sendJson(res, 404, { error: 'no game yet' });
if (url.pathname === '/api/lobby/join' && req.method === 'POST') {
const body = (await readJson(req)) as { secret?: string; gameCode?: string; displayName?: string };
if (body.secret !== opts.joinSecret) {
sendJson(res, 403, { error: 'bad or missing secret' });
return;
}
const seat = Number(url.searchParams.get('seat')) as PlayerIndex;
if (!Number.isInteger(seat) || seat < 0 || seat >= session.playerCount) {
sendJson(res, 400, { error: 'bad or missing ?seat=' });
if (typeof body.gameCode !== 'string' || typeof body.displayName !== 'string' || body.displayName.trim() === '') {
sendJson(res, 400, { error: 'expected { secret, gameCode, displayName }' });
return;
}
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
const gameId = gameCodes.get(body.gameCode.trim().toUpperCase());
const lobby = gameId ? lobbies.get(gameId) : undefined;
if (!lobby) {
// A game code that already started is no longer in `lobbies` at all — same NOT_FOUND a
// typo gets, which tells a latecomer "that game is gone" without leaking which case it was.
sendJson(res, 404, { error: 'no open lobby with that code' });
return;
}
const result = joinLobby(lobby, body.displayName.trim());
if (!result.ok) {
sendJson(res, 409, { error: result.code });
return;
}
await persistLobby(result.lobby);
await persistSession(result.session);
broadcastLobby(lobby.gameId);
sendJson(res, 200, { gameId: lobby.gameId, token: result.session.token, player: result.session.player });
return;
}
// -- Lobby: seating, once inside (token-authenticated) ------------------------------------
if (url.pathname === '/api/lobby/bot' && req.method === 'POST') {
const body = (await readJson(req)) as { token?: string; seat?: number; filled?: boolean };
const ps = typeof body.token === 'string' ? sessions.get(body.token) : undefined;
const lobby = ps ? lobbies.get(ps.gameId) : undefined;
if (!ps || !lobby) {
sendJson(res, 404, { error: 'no such lobby' });
return;
}
if (lobby.hostToken !== ps.token) {
sendJson(res, 403, { error: 'NOT_HOST' });
return;
}
if (typeof body.seat !== 'number' || typeof body.filled !== 'boolean') {
sendJson(res, 400, { error: 'expected { token, seat, filled }' });
return;
}
const updated = setBotSeat(lobby, body.seat as PlayerIndex, body.filled);
await persistLobby(updated);
broadcastLobby(lobby.gameId);
sendJson(res, 200, { ok: true });
return;
}
if (url.pathname === '/api/lobby/start' && req.method === 'POST') {
const body = (await readJson(req)) as { token?: string };
const ps = typeof body.token === 'string' ? sessions.get(body.token) : undefined;
const lobby = ps ? lobbies.get(ps.gameId) : undefined;
if (!ps || !lobby) {
sendJson(res, 404, { error: 'no such lobby' });
return;
}
const result = startLobby(lobby, ps.token);
if (!result.ok) {
sendJson(res, 409, { error: result.code });
return;
}
const session = createSession(Math.floor(Math.random() * 1e9), lobby.config, result.playerNames, result.botSeats);
games.set(lobby.gameId, session);
lobbies.delete(lobby.gameId);
// Every SSE watcher on the LOBBY stream is done — the game stream is what carries the game
// forward from here. `started: true` on one last message, THEN close, is what lets a
// still-open lobby tab tell "the game began" apart from a network hiccup `EventSource`
// would otherwise silently retry through.
for (const [watcherToken, watcherRes] of lobbyConnections.get(lobby.gameId) ?? []) {
const watcherPs = sessions.get(watcherToken);
if (watcherPs) writeSse(watcherRes, 0, { lobby, you: watcherPs.player, started: true } satisfies LobbyPush);
watcherRes.end();
}
lobbyConnections.delete(lobby.gameId);
await writeGame(gameDir(opts.dataDir, lobby.gameId), session.exportSave(), opts.engineVersion);
await upsertIndexEntry(opts.dataDir, { gameId: lobby.gameId, gameCode: lobby.gameCode, status: 'active' });
await deleteLobby(opts.dataDir, lobby.gameId);
sendJson(res, 200, { ok: true });
return;
}
if (url.pathname === '/api/lobby/stream' && req.method === 'GET') {
const token = url.searchParams.get('token') ?? '';
const ps = sessions.get(token);
const lobby = ps ? lobbies.get(ps.gameId) : undefined;
if (!ps || !lobby) {
sendJson(res, 404, { error: 'no such lobby' });
return;
}
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
const conns = lobbyConnections.get(lobby.gameId) ?? new Map<string, ServerResponse>();
conns.set(token, res);
lobbyConnections.set(lobby.gameId, conns);
writeSse(res, 0, { lobby, you: ps.player, started: false } satisfies LobbyPush);
const heartbeat = setInterval(() => res.write(': ping\n\n'), HEARTBEAT_MS);
req.on('close', () => {
clearInterval(heartbeat);
const live = lobbyConnections.get(lobby.gameId);
if (live?.get(token) === res) live.delete(token);
// `lobby-and-sessions.md` §2 — host rights pass to the earliest-joined remaining player
// if the host's connection closes before start. `lobbies.get` again, not the captured
// `lobby`, because it may have changed (another join, another bot toggle) since connect.
const current = lobbies.get(lobby.gameId);
if (current && current.hostToken === token) {
void persistLobby(reassignHost(current, token)).then(() => broadcastLobby(lobby.gameId));
}
});
connections.set(seat, res);
writeSse(seat, session.connect(seat));
return;
}
// -- The running game (token-authenticated) ------------------------------------------------
if (url.pathname === '/api/stream' && req.method === 'GET') {
const token = url.searchParams.get('token') ?? '';
const ps = sessions.get(token);
const session = ps ? games.get(ps.gameId) : undefined;
if (!ps || !session) {
sendJson(res, 404, { error: 'no such game' });
return;
}
const { gameId, player: seat } = ps;
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
const conns = gameConnections.get(gameId) ?? new Map<PlayerIndex, ServerResponse>();
conns.set(seat, res);
gameConnections.set(gameId, conns);
writeSse(res, nextEventId(gameId, seat), session.connect(seat));
broadcastPresence(gameId, seat, true);
// Idle for minutes at a time is the expected shape of this game (multiplayer.md §9) — a
// silent SSE connection is exactly what a proxy in the path may reap. A comment line is not a
// real event (EventSource ignores lines starting with `:`), so it costs the client nothing.
const heartbeat = setInterval(() => res.write(': ping\n\n'), HEARTBEAT_MS);
req.on('close', () => {
clearInterval(heartbeat);
if (connections.get(seat) === res) connections.delete(seat);
const live = gameConnections.get(gameId);
if (live?.get(seat) === res) live.delete(seat);
broadcastPresence(gameId, seat, false);
});
return;
}
if (url.pathname === '/api/intent' && req.method === 'POST') {
if (!checkSecret(url, res)) return;
if (!session) {
sendJson(res, 404, { error: 'no game yet' });
return;
}
const seat = Number(url.searchParams.get('seat')) as PlayerIndex;
if (!Number.isInteger(seat) || seat < 0 || seat >= session.playerCount) {
sendJson(res, 400, { error: 'bad or missing ?seat=' });
// Token comes from the QUERY STRING, matching `/api/stream` and matching what
// `web/session.ts`'s `RemoteSession.submit` actually sends (`fetch('/api/intent?token=…')`)
// — the body carries only what changes per call, `{ seq, intent }`.
const token = url.searchParams.get('token') ?? '';
const ps = sessions.get(token);
const session = ps ? games.get(ps.gameId) : undefined;
if (!ps || !session) {
sendJson(res, 404, { error: 'no such game' });
return;
}
const body = (await readJson(req)) as { seq?: number; intent?: Intent };
@@ -175,15 +381,23 @@ export function startServer(opts: ServerOptions): void {
sendJson(res, 400, { error: 'expected { seq, intent }' });
return;
}
const result = session.intent(seat, body.seq, body.intent);
const result = session.intent(ps.player, body.seq, body.intent);
if (result.accepted) {
// Persisted BEFORE the response goes out — "accepted" should mean "durably on disk" at
// this scale, not just "applied in memory" (§12 step 14).
await writeGame(opts.dataDir, session.exportSave(), opts.engineVersion);
if (result.timing) await appendTiming(opts.dataDir, result.timing);
const dir = gameDir(opts.dataDir, ps.gameId);
await writeGame(dir, session.exportSave(), opts.engineVersion);
if (result.timing) await appendTiming(dir, result.timing);
if (session.exportSave().status === 'finished') {
// `upsertIndexEntry` replaces the WHOLE row for this `gameId`, so the code has to be
// carried forward here rather than left blank — `gameCodes` is the only place still
// holding it once a lobby's own record is gone.
const gameCode = [...gameCodes.entries()].find(([, id]) => id === ps.gameId)?.[0] ?? '';
await upsertIndexEntry(opts.dataDir, { gameId: ps.gameId, gameCode, status: 'finished' });
}
}
sendJson(res, 200, result.accepted ? { ok: true } : { ok: false, code: result.code });
if (result.accepted) broadcast(result.pushes);
if (result.accepted) broadcastGame(ps.gameId, result.pushes);
return;
}