Files
station-master/test/server/session.test.ts
T
Jesse 2fbfe11977 v0.5.3 — a table you size yourself, and games an administrator can see and end
Both halves came out of playing the StartOS build. The wrapper's health
check and admin actions consume this; they land separately.

The host picks the table size (2-4) when creating a game, and the seats
array is built at that length once. Before, it GREW as people joined, so
the four rows on screen were partly fiction — a 2-player game just started
with a 2-long array, while a host who dropped a bot into a later chair
padded it with a null and silently disabled Start behind a one-line note.
A gap can no longer be written down rather than merely being refused.

That also avoided a trap. Compacting seats at Lobby.Start — the obvious
way to support a "closed" chair — would have shifted the player index that
every PlayerSession stamps at join time and that /api/stream and
/api/intent both route by, handing a player somebody else's railroad with
no error anywhere.

And it fixed a live balance bug: minCombinedRevenue is derived from the
player count, but the config was fixed at CREATE while the count wasn't
known until START, so the lobby guessed 4. Every 2-player game ran against
a floor of 60 instead of 30 — and missing the floor means everyone loses,
so a 2-player competitive game was set up to fail for a UI artifact rather
than a rule.

/api/health gained games:{active,lobby}, read from a new cheap summary()
on GameSession rather than exportSave(), which would copy every intent of
every game to answer a question about none of them. Three admin routes are
new behind an ADMIN_SECRET env var in an x-admin-secret header: GET
/api/games, GET /api/games/<id>/save, DELETE /api/games/<id>. Until now a
started game could not be ended by anyone — no route, no player action, no
resignation — so an abandoned game stayed active in the index and was
faithfully resumed on every boot, forever.

Three deliberate choices there: the admin secret is NOT the join secret,
which every player holds and which would therefore let anyone at the table
destroy anyone else's game; unset means the routes 404 exactly as any
unknown path does, with or without a header, so a server never given an
administrator doesn't advertise that it has one; and a delete returns the
deleted game's save, since the intents are the game (D5) — nothing is
destroyed without being handed to whoever destroyed it.

SavedGame gained an optional lastMoveAt (falling back to createdAt) so
"has this stalled?" survives a restart. Kept out of history for the same
reason the turn timings are: a replay must reproduce a game from decisions
alone, and wall-clock is not a decision.

index.ts logs "Resuming N saved games..." before the loop rather than one
line per game after it. Measured a full 4-player game at 100ms to replay,
and only unfinished games are replayed, so listening before loading would
have bought nothing for the cost of a "still loading" state everywhere.

Verified: 667 tests pass (662 + 5), and the new session tests were checked
against two mutations (lastMoveAt never advancing; resume dropping it) to
confirm they fail without the code. Live against a running server: health
counts tracking through the lobby->game transition, admin auth rejecting a
missing and a wrong secret, list/export/delete, the deleted game's files
and index entry actually gone from disk, a second delete 404ing, the admin
routes invisible when ADMIN_SECRET is unset, and a 3-player table refusing
a 4th player and a size of 5 refused at the door.

Also carries the TODO items raised on 2026-08-21: the lobby offering no
game parameters (the floor bug within it now fixed, the form still
missing), and the four optionalRules — of which only reducedVisibility and
emergencyToolbox are read by anything, while sisterTrains and
employeeRotation are declared, defaulted, and consulted nowhere.
2026-08-21 14:53:53 -04:00

303 lines
15 KiB
TypeScript

/**
* The game session host (`src/server/session.ts`) — pure logic, no sockets, exercised directly.
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import type { GameConfig, PlayerIndex } from '../../src/engine/state.ts';
import type { Push } from '../../src/server/session.ts';
import { createSession, resumeSession } from '../../src/server/session.ts';
const config: GameConfig = {
mode: 'competitive',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
employeeRotation: false,
emergencyToolbox: false,
},
};
describe('the game session host', () => {
it('gives a fresh connect a full Frame — nothing nulled', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const push = session.connect(0 as PlayerIndex);
assert.notEqual(push.frame!.cells, null, 'a first connect nulled the board');
assert.notEqual(push.frame!.division, null, 'a first connect nulled the division');
});
it('only the current actor gets a real Menu; every other seat gets null', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const a = session.connect(0 as PlayerIndex);
const b = session.connect(1 as PlayerIndex);
const actorPushes = [a, b].filter((p) => p.menu !== null);
assert.equal(actorPushes.length, 1, 'more than one seat (or zero) was given a real Menu');
});
it('rejects an intent from a seat that is not the current actor, with NOT_YOUR_TURN', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
// Whichever seat is NOT the current actor should be refused, regardless of the intent's content.
const bPush = session.connect(1 as PlayerIndex);
const notActor = (bPush.menu === null ? 1 : 0) as PlayerIndex;
const result = session.intent(notActor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(result.accepted, false);
if (!result.accepted) assert.equal(result.code, 'NOT_YOUR_TURN');
});
it('accepts a legal intent from the current actor and pushes every seat', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const aPush = session.connect(0 as PlayerIndex);
const actor = (aPush.menu !== null ? 0 : 1) as PlayerIndex;
const result = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(result.accepted, true);
if (result.accepted) assert.equal(result.pushes.size, 2, 'not every connected seat was pushed to');
});
it('rejects an illegal intent with its real RejectionCode, and does not remember the seq', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const aPush = session.connect(0 as PlayerIndex);
const actor = (aPush.menu !== null ? 0 : 1) as PlayerIndex;
// Discarding before ever drawing is illegal on an opening hand at the limit — a safe "this is
// definitely rejected" fixture that does not depend on exactly which cards were dealt.
const bad = session.intent(actor, 1, { type: 'card.discard', cardId: 'not-a-real-card', toSlot: 0 });
assert.equal(bad.accepted, false);
if (!bad.accepted) assert.ok(bad.code.length > 0, 'a rejection carried no code at all');
// The same seq, now with a legal intent, must still go through — a rejection is not "applied".
const retry = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(retry.accepted, true, 'a seq burned by an earlier rejection could not be reused');
});
it('treats a repeated seq as an already-applied no-op, not a second application', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const aPush = session.connect(0 as PlayerIndex);
const actor = (aPush.menu !== null ? 0 : 1) as PlayerIndex;
const first = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(first.accepted, true);
const second = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(second.accepted, true, 'a resend of an already-applied seq was rejected instead of ignored');
if (second.accepted) assert.equal(second.pushes.size, 0, 'a resend produced pushes as if newly applied');
});
it('deltas the board on a second push when it has not changed since the first', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const aPush = session.connect(0 as PlayerIndex);
session.connect(1 as PlayerIndex); // both seats need a baseline Frame before a delta means anything
const actor = (aPush.menu !== null ? 0 : 1) as PlayerIndex;
const result = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(result.accepted, true);
if (!result.accepted) return;
// Choosing "draw" doesn't move a single card on the board — the division/cells should be nulled
// on this push for a seat that already had them from `connect`.
const push = result.pushes.get(actor)!;
assert.equal(push.frame!.division, null, 'the board was resent even though nothing on it changed');
});
it('only sends narration NEW since the last push to that specific seat', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const aPush = session.connect(0 as PlayerIndex);
const actor = (aPush.menu !== null ? 0 : 1) as PlayerIndex;
// A first connect is this seat's first contact, so it gets everything narrated so far (the
// "Game Begins" intro and whatever `drain()` said entering the first Stage) — not an empty log.
assert.ok(aPush.lines.length > 0, 'a first connect got no narration at all, not even the game-begins intro');
const first = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(first.accepted, true);
if (!first.accepted) return;
const firstLines = first.pushes.get(actor)!.lines;
assert.ok(firstLines.length > 0, 'the acting seat got no narration for its own action');
const second = session.intent(actor, 2, { type: 'draw.end' });
assert.equal(second.accepted, true);
if (!second.accepted) return;
const secondLines = second.pushes.get(actor)!.lines;
assert.ok(secondLines.length > 0, 'a second real action produced no narration at all');
for (const line of firstLines) {
assert.ok(!secondLines.includes(line), 'the second push repeated narration already sent in the first');
}
});
});
describe('turn timings (lobby-and-sessions.md §5)', () => {
it('records a wall-clock span once the acting player, phase, Day or Stage changes', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
let pushes = new Map<PlayerIndex, Push>([
[0 as PlayerIndex, session.connect(0 as PlayerIndex)],
[1 as PlayerIndex, session.connect(1 as PlayerIndex)],
]);
const seq = new Map<PlayerIndex, number>([[0 as PlayerIndex, 1], [1 as PlayerIndex, 1]]);
const timings = [];
for (let step = 0; step < 60 && timings.length === 0; step++) {
const acting = [0, 1].find((seat) => pushes.get(seat as PlayerIndex)!.menu !== null) as PlayerIndex | undefined;
const menu = acting === undefined ? null : pushes.get(acting)!.menu;
if (acting === undefined || !menu || menu.options.length === 0) break;
const n = seq.get(acting)!;
seq.set(acting, n + 1);
const result = session.intent(acting, n, menu.options[0]!);
assert.equal(result.accepted, true, `step ${step}: ${JSON.stringify(menu.options[0])} rejected`);
if (!result.accepted) break;
if (result.timing) timings.push(result.timing);
pushes = result.pushes;
}
assert.ok(timings.length > 0, 'no turn timing ever closed across 60 real steps of actual play');
const [timing] = timings;
assert.ok(timing!.endedAt >= timing!.startedAt, 'a span ended before it started');
assert.ok([0, 1].includes(timing!.player), 'a timing named a player outside the table');
});
});
describe('bot seats (Phase 4 — D8, lobby-and-sessions.md §2)', () => {
it('a bot never becomes the observable current actor — it plays before anyone can see it waiting', () => {
// Seat 0 acts first (the opening Superintendent), so marking it a bot exercises `driveBots()`
// at CONSTRUCTION time — before any external `intent()` has run at all.
const session = createSession(11, config, ['Bot', 'Alice'], [0 as PlayerIndex]);
assert.equal(session.isBot(0 as PlayerIndex), true);
assert.equal(session.isBot(1 as PlayerIndex), false);
const botPush = session.connect(0 as PlayerIndex);
const humanPush = session.connect(1 as PlayerIndex);
assert.equal(botPush.menu, null, 'the bot seat was handed a real decision to make');
assert.notEqual(humanPush.menu, null, 'nobody was left with a turn to take — the bot never played');
});
it('botSeats round-trips through exportSave/resumeSession', () => {
const session = createSession(11, config, ['Bot', 'Alice'], [0 as PlayerIndex]);
const resumed = resumeSession(session.exportSave());
assert.equal(resumed.isBot(0 as PlayerIndex), true);
assert.equal(resumed.connect(0 as PlayerIndex).menu, null, 'a resumed bot seat still never gets a real decision');
});
it('a bot seat is driven forward after a human intent too, not only at construction', () => {
// Two bots and one human: whichever of the two non-human seats comes up next after the human's
// own move must be played automatically, with no external `intent()` for either of them.
const session = createSession(11, config, ['Alice', 'Bot', 'Bot'], [1 as PlayerIndex, 2 as PlayerIndex]);
const before = session.exportSave().history.length;
const applied = session.intent(0 as PlayerIndex, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(applied.accepted, true);
assert.equal(session.connect(1 as PlayerIndex).menu, null, 'bot seat 1 was left with a real decision');
assert.equal(session.connect(2 as PlayerIndex).menu, null, 'bot seat 2 was left with a real decision');
// Not a strict proof either bot actually moved (the human's own turn may not have ended yet),
// but the history can only ever have grown, never shrunk, and never rejected mid-drive.
assert.ok(session.exportSave().history.length >= before + 1);
});
});
describe('persistence hooks — exportSave / resumeSession (Phase 3)', () => {
it('exportSave carries enough to reconstruct the exact same game', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const push = session.connect(0 as PlayerIndex);
const actor = (push.menu !== null ? 0 : 1) as PlayerIndex;
const applied = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(applied.accepted, true);
const saved = session.exportSave();
assert.equal(saved.seed, 42);
assert.deepEqual(saved.playerNames, ['Alice', 'Bob']);
assert.equal(saved.history.length, 1);
assert.equal(saved.status, 'active');
assert.ok(saved.createdAt > 0, 'createdAt was not set');
const resumed = resumeSession(saved);
const before = session.connect(actor);
const after = resumed.connect(actor);
assert.deepEqual(after.frame, before.frame, 'resumeSession did not reconstruct the same board/state');
});
it('a resumed session keeps enforcing whose turn it is', () => {
const session = createSession(7, config, ['Alice', 'Bob']);
const push = session.connect(0 as PlayerIndex);
const actor = (push.menu !== null ? 0 : 1) as PlayerIndex;
session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
const resumed = resumeSession(session.exportSave());
const notActor = (actor === 0 ? 1 : 0) as PlayerIndex;
const rejected = resumed.intent(notActor, 1, { type: 'draw.end' });
assert.equal(rejected.accepted, false);
if (!rejected.accepted) assert.equal(rejected.code, 'NOT_YOUR_TURN');
});
it('marks status finished only once the game actually is', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
assert.equal(session.exportSave().status, 'active');
});
});
describe('summary() — what an administrator sees without replaying the game', () => {
it('describes a fresh game: who is at the table, where it has got to, and who it waits on', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const s = session.summary();
assert.equal(s.playerCount, 2);
assert.deepEqual(s.playerNames, ['Alice', 'Bob']);
assert.equal(s.status, 'active');
assert.equal(s.day, 1);
assert.equal(s.stage, 1);
assert.equal(typeof s.phase, 'string');
assert.ok(s.waitingOn, 'a game in play must be waiting on somebody');
assert.equal(s.waitingOn!.name, s.playerNames[s.waitingOn!.seat]);
});
it('does not hand back a copy of the history the way exportSave must', () => {
// The health check polls this on a timer, so it answering with every intent of every game
// would make a question about none of them cost a copy of all of them.
const session = createSession(42, config, ['Alice', 'Bob']);
assert.equal('history' in session.summary(), false);
});
it('moves lastMoveAt when a move is accepted, and leaves it alone when one is refused', async () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const created = session.summary();
assert.equal(created.lastMoveAt, created.createdAt, 'an untouched game has not moved since it began');
const actor = (session.connect(0 as PlayerIndex).menu !== null ? 0 : 1) as PlayerIndex;
const idle = (1 - actor) as PlayerIndex;
// A rejection is not a move — a player poking at a game they cannot act in must not make it
// look alive to whoever is deciding whether it has stalled.
session.intent(idle, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(session.summary().lastMoveAt, created.lastMoveAt, 'a refused intent moved the clock');
await new Promise((r) => setTimeout(r, 2));
const accepted = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(accepted.accepted, true);
assert.ok(session.summary().lastMoveAt > created.lastMoveAt, 'an accepted intent did not move the clock');
});
it('carries lastMoveAt across a restart, and falls back to createdAt for a save without one', async () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const actor = (session.connect(0 as PlayerIndex).menu !== null ? 0 : 1) as PlayerIndex;
await new Promise((r) => setTimeout(r, 2));
session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
const saved = session.exportSave();
assert.equal(resumeSession(saved).summary().lastMoveAt, saved.lastMoveAt);
// A game written before the field existed still has to load, and reads as untouched since it
// began rather than as having just moved.
const { lastMoveAt: _dropped, ...older } = saved;
const revived = resumeSession(older).summary();
assert.equal(revived.lastMoveAt, saved.createdAt);
});
it('reports a finished game as waiting on nobody', () => {
// Every seat a bot, so the game plays itself to a finish inside the constructor.
const session = createSession(4242, config, ['A', 'B'], [0 as PlayerIndex, 1 as PlayerIndex]);
const s = session.summary();
assert.equal(s.status, 'finished');
assert.equal(s.waitingOn, null, 'a finished game must not name somebody to wait for');
});
});