Use native BGS presence and versioned career checkpoints

This commit is contained in:
coyotte508 2026-09-30 10:13:20 +02:00
commit d7630cacb1
9 changed files with 161 additions and 63 deletions

View file

@ -48,7 +48,7 @@ No publisher artwork, scanned cards, rulebook files or official voice recordings
## Build for BGS
The viewer requires `@boardgamers/protocol` **0.7.0**, whose npm publication is separate from this repository. After it is published:
The BGS integration requires `@boardgamers/protocol` **0.8.0**, whose npm publication is separate from this repository. After it is published:
```sh
npm install

View file

@ -1,7 +1,7 @@
import { createHash } from "node:crypto";
import {
createSession,
keepPresent,
setPresence,
advanceClock,
nextWakeup as wakeup,
submit,
@ -18,6 +18,7 @@ import {
consentToCloning,
claimAchievement,
eligibleAchievements,
compactExplorer,
} from "../src/game/career.js";
const reject = (message) => {
@ -33,7 +34,7 @@ const result = (state) =>
(!state.game?.campaign ? state.game?.resolution?.outcome : null);
function settle(state) {
const g = state.game,
runId = g.campaign?.id ?? g.seed;
runId = `${state.bgs.gameId}:${g.campaign ? "campaign" : state.bgs.missionNumber}`;
for (const [seat, id] of (state.bgs?.playerIds ?? []).entries()) {
const e = state.bgs.explorers?.[id];
if (
@ -113,7 +114,10 @@ export function init(players, expansions, options, seed, creator, context) {
: Math.max(4, players);
const playerIds =
context.playerIds ?? Array.from({ length: players }, (_, i) => String(i));
const previous = context.previous?.state?.bgs?.explorers ?? {};
const progress = context.table?.progress;
if (progress && progress.version !== 1)
throw Error("Unsupported Space Alert career version");
const previous = progress?.data?.explorers ?? {};
const explorers = Object.fromEntries(
playerIds
.filter((id) => options.careers || previous[id])
@ -160,7 +164,39 @@ export function init(players, expansions, options, seed, creator, context) {
missionNumber: 1,
settings: options,
};
return state;
return setPresence(state, context.present ?? []);
}
export function presenceChanged(state, present) {
return setPresence(state, present);
}
export function phase(state) {
const waiting = ["presence", "countdown"].includes(state.stage);
const between =
state.stage === "resolution" &&
!!state.game.resolution?.outcome &&
!ended(state);
return {
name: waiting ? "waiting" : between ? "between-rounds" : "playing",
canLeave: waiting || between,
};
}
export function tableProgress(state) {
return {
version: 1,
data: {
explorers: Object.fromEntries(
Object.entries(state.bgs.explorers).map(([id, explorer]) => [
id,
compactExplorer({ ...explorer, activeRun: null }),
]),
),
},
};
}
export function migrateTableProgress(progress) {
if (progress.version !== 1)
throw Error("Unsupported Space Alert career version");
return structuredClone(progress);
}
export function advanceTime(state, context) {
return settle(advanceClock(state, trusted(context)));
@ -173,11 +209,6 @@ export function move(input, command, seat, context) {
if (!Number.isInteger(seat) || !input.players[seat]) reject("Unknown player");
if (!command || typeof command !== "object" || Array.isArray(command))
reject("Invalid command");
if (command.type === "presence") {
if (Object.keys(command).some((key) => key !== "type"))
reject("Unsupported presence field");
return settle(keepPresent(input, seat, now));
}
let state = advanceTime(input, context);
if (!Number.isSafeInteger(command.sequence) || command.sequence < 1)
reject("Invalid sequence");
@ -237,7 +268,7 @@ export function move(input, command, seat, context) {
p.name = state.players[i].name;
});
next.revision = state.revision + 1;
state = next;
state = setPresence(next, context.present ?? []);
} else if (command.type === "career") {
if (
Object.keys(command).some(

View file

@ -45,16 +45,6 @@ registerViewer("SpaceAlert", (context) => {
},
});
ui.setPlayer(undefined);
const presence = setInterval(() => {
if (
document.visibilityState !== "visible" ||
pending ||
!lastState?.players[seat]?.ready
)
return;
if (["presence", "countdown"].includes(lastState.stage))
context.move({ type: "presence" });
}, 2000);
function render(state) {
lastState = state;
// Finished games can be opened without reinstalling an archived engine.
@ -102,7 +92,6 @@ registerViewer("SpaceAlert", (context) => {
if (el) el.textContent = String(error);
},
destroy() {
clearInterval(presence);
ui.destroy();
if (pending) {
clearTimeout(pending.timer);

View file

@ -1,22 +1,24 @@
# BGS integration
The adapter is in `bgs/engine.js`; the hosted viewer is `bgs/viewer.js`. It uses BGS protocol 0.7 and the platform's durable engine wakeups. The standalone development server remains useful for rule tests, but is not the online host.
The adapter is in `bgs/engine.js`; the hosted viewer is `bgs/viewer.js`. It uses BGS protocol 0.8 and the platform's durable engine wakeups. The standalone development server remains useful for rule tests, but is not the online host.
## Clock and commands
BGS supplies a trusted `context.now` after acquiring the game lock. The adapter never trusts browser timestamps. It exposes `advanceTime` and `nextWakeup`; BGS saves each semantic deadline and wakes the game even when everyone closes their browser. It also commits due events before accepting a player move. Late moves return HTTP 422.
The crew can wait indefinitely. **I’m ready** lasts two minutes; everyone must be ready at once. BGS launches after a ten-second countdown, with connection checks while ready. Expiry, withdrawal or a disconnect returns to waiting without cancelling the game. Once the flight starts, reconnecting never restarts or pauses it.
The crew can wait indefinitely. **I’m ready** lasts two minutes; everyone must be ready at once. BGS launches after a ten-second countdown, with native BGS presence checks. The platform tracks loaded, visible tabs; the viewer sends no heartbeat moves. Expiry, withdrawal or a disconnect returns to waiting without cancelling the game. Once the flight starts, reconnecting never restarts or pauses it.
Commands carry a sequence number per seat. Repeated committed commands are harmless; gaps and stale edits are rejected. The viewer receives `move:result` acknowledgements and refreshes after rejection. Snapshots omit seeds, future announcements, decks and other players' hands. Server time accompanies snapshots so the browser can animate the countdown between updates.
The adapter reports waiting, playing and between-mission phases. While waiting or between campaign missions, **Leave table** ends the attempt without a quit penalty. Once play begins, that shortcut is unavailable.
After programming, resolution has no deadline. Campaign repairs and the decision to launch the next mission are untimed too. Only the next presence check and flight restart the clock. Campaigns contain three or five missions within one BGS game; their repairs and shared results stay in that game state.
## Same table, new game
BGS **Play again** creates a new game record with fresh randomness, the same reserved seats and optional setup changes. The crew stays seated at the same table URL, with one shared chat. The next Space Alert mission opens its preparation screen immediately; everyone uses **I’m ready** there. Async games such as Fuji ask for one new confirmation per play. Reservations send no invitation emails. Old games remain available through the table's paginated history. This generic flow also works for asynchronous games such as Fuji.
At initialization, BGS supplies the previous completed game state only when it belongs to the same table, game and engine version. The adapter copies explorer careers by account ID, independently of seat order. Completed runs award experience once; cancellation releases the active run without awarding progress. Turning careers off preserves the records for later games at this table.
BGS carries only the versioned `tableProgress` checkpoint into the next game's `init`; full game states are never copied. The adapter keeps career totals, achievements and the latest mission summary, keyed by account ID. Older summaries stay with their original replays. `migrateTableProgress` rejects unknown schemas. Cancellation clears an unfinished run without awarding experience; disabling careers preserves earned progress.
Careers are **table-local**, not account-wide profiles. Moving to another table starts a separate career. There is no global campaign directory or cross-table character synchronization. The game version is retained between games; retired versions ask players to create a new table.

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/space-alert",
"version": "0.1.2",
"version": "0.1.3",
"private": true,
"type": "module",
"description": "Space Alert and The New Frontier: deterministic game engine and local playtest",
@ -19,7 +19,7 @@
"url": "git+https://github.com/boardgamers/space-alert.git"
},
"devDependencies": {
"@boardgamers/protocol": "^0.7.0",
"@boardgamers/protocol": "^0.8.0",
"esbuild": "^0.28.2"
},
"exports": {

View file

@ -445,8 +445,10 @@ export function mountConsole(root, host = null) {
own.ready ? "unready" : "ready",
own.ready
? t("Pas encore prêt", "Not ready yet")
: t("Je suis prêt", "I’m ready"),
!view.players[seat],
: !own.present
? t("Connexion…", "Connecting…")
: t("Je suis prêt", "I’m ready"),
!view.players[seat] || !own.present,
'class="primary"',
)
: planning

View file

@ -34,6 +34,25 @@ export function createExplorer(id, name, cloning = true) {
activeRun: null,
};
}
export function compactExplorer(input) {
const e = structuredClone(input);
check(!e.activeRun, "Finish the expedition before saving career progress");
const archive = e.archive ?? {
completed: 0,
campaigns: 0,
firstCompletedAt: null,
};
for (const r of e.runs.slice(0, -1)) {
if (!r.survived || r.training) continue;
archive.completed++;
if (r.count >= 3 && r.count === r.limit) archive.campaigns++;
archive.firstCompletedAt ??= r.at;
}
e.archive = archive;
e.runs = e.runs.slice(-1);
return e;
}
export function experienceFor(score, count = 1, limit = 3) {
check(
Number.isFinite(score) &&
@ -446,17 +465,24 @@ export function eligibleAchievements(explorer, runId) {
if (a.category !== "addiction") return true;
const completed = explorer.runs.filter((x) => x.survived && !x.training),
earned = ACHIEVEMENTS.filter((x) => explorer.achievements.includes(x.id));
if (a.runs && completed.length < a.runs) return false;
if (
a.runs &&
completed.length + (explorer.archive?.completed ?? 0) < a.runs
)
return false;
if (
a.campaigns &&
completed.filter((x) => x.count >= 3 && x.count === x.limit).length <
completed.filter((x) => x.count >= 3 && x.count === x.limit).length +
(explorer.archive?.campaigns ?? 0) <
a.campaigns
)
return false;
if (a.clones && explorer.clones < a.clones) return false;
if (
a.days &&
(!completed.length || r.at - completed[0].at < a.days * 86400000)
((explorer.archive?.firstCompletedAt ?? completed[0]?.at) == null ||
r.at - (explorer.archive?.firstCompletedAt ?? completed[0].at) <
a.days * 86400000)
)
return false;
for (const tier of ["basic", "advanced"])

View file

@ -10,7 +10,6 @@ import { compileTimeline } from "./missions.js";
export const PRESENCE_WINDOW_MS = 120_000;
export const LAUNCH_COUNTDOWN_MS = 3_000;
export const CONNECTION_GRACE_MS = 8_000;
const active = new Set(["presence", "countdown", "programming"]);
function timestamp(now) {
if (!Number.isSafeInteger(now) || now < 0)
@ -55,7 +54,7 @@ export function createSession(
seat,
ready: false,
readyUntil: null,
connectedUntil: null,
present: !connectionChecks,
planningPhase: 0,
finishedPlanning: false,
lastSequence: 0,
@ -92,9 +91,12 @@ export function advanceClock(input, now) {
const at =
state.stage === "countdown" ? Math.min(now, state.missionStartAt) : now;
for (const player of state.players) {
if (player.ready && readinessDeadline(state, player) <= at) {
if (
player.ready &&
(player.readyUntil <= at || (state.connectionChecks && !player.present))
) {
player.ready = false;
player.readyUntil = player.connectedUntil = null;
player.readyUntil = null;
append(state, at, "ready-expired", { seat: player.seat });
}
}
@ -135,21 +137,10 @@ export function advanceClock(input, now) {
return state;
}
function readinessDeadline(state, player) {
return Math.min(
player.readyUntil ?? 0,
state.connectionChecks ? (player.connectedUntil ?? 0) : Infinity,
);
}
export function keepPresent(input, seat, now) {
const state = advanceClock(input, now);
if (
["presence", "countdown"].includes(state.stage) &&
state.players[seat]?.ready
) {
state.players[seat].connectedUntil = state.observedAt + CONNECTION_GRACE_MS;
}
export function setPresence(input, seats) {
const state = structuredClone(input);
for (const player of state.players)
player.present = seats.includes(player.seat);
return state;
}
@ -157,7 +148,7 @@ export function nextWakeup(state) {
if (["presence", "countdown"].includes(state.stage)) {
const deadlines = state.players
.filter((p) => p.ready)
.map((p) => readinessDeadline(state, p));
.map((p) => p.readyUntil);
if (state.stage === "countdown") deadlines.push(state.missionStartAt);
return deadlines.length ? Math.min(...deadlines) : null;
}
@ -219,16 +210,17 @@ export function submit(input, seat, command, receivedAt) {
if (!["presence", "countdown"].includes(state.stage))
return reject("The mission has started");
player.ready = false;
player.readyUntil = player.connectedUntil = null;
player.readyUntil = null;
state.stage = "presence";
state.missionStartAt = null;
append(state, now, "unready", { seat });
} else if (command.type === "ready") {
if (state.stage !== "presence") return reject("Presence check is closed");
if (state.connectionChecks && !player.present)
return reject("Reconnect to the table before getting ready");
if (!player.ready) {
player.ready = true;
player.readyUntil = now + PRESENCE_WINDOW_MS;
player.connectedUntil = now + CONNECTION_GRACE_MS;
append(state, now, "ready", { seat });
}
if (state.players.every((p) => p.ready)) {

View file

@ -6,6 +6,7 @@ const ctx = (now, extra = {}) => ({
now,
gameId: "bgs-test",
playerIds: ["alice", "bob"],
present: [0, 1],
...extra,
});
const initial = (options = {}) =>
@ -14,8 +15,6 @@ const launch = (s = initial()) => {
s = e.move(s, { type: "ready", sequence: 1 }, 0, ctx(1001));
s = e.move(s, { type: "ready", sequence: 1 }, 1, ctx(1002));
const start = s.missionStartAt;
for (const seat of [0, 1])
s = e.move(s, { type: "presence" }, seat, ctx(start - 5000));
return e.advanceTime(s, ctx(start));
};
test("requires a trusted server timestamp and ignores client clock claims", () => {
@ -92,7 +91,11 @@ test("careers carry by account across reordered seats, and only their owner can
1,
ctx(2000, {
playerIds: ["bob", "alice"],
previous: { state: old, gameId: "old", playerIds: ["alice", "bob"] },
table: {
id: "table",
round: 2,
progress: e.tableProgress(e.dropPlayer(old)),
},
}),
);
const teammateReady = e.move(
@ -136,17 +139,17 @@ test("a dropped player ends the cooperative session and unlocks explorer records
);
});
test("disconnect during launch returns to waiting; heartbeat never renews consent", () => {
test("disconnect during launch returns to waiting; platform presence never renews consent", () => {
let s = e.move(initial(), { type: "ready", sequence: 1 }, 0, ctx(1001));
s = e.move(s, { type: "ready", sequence: 1 }, 1, ctx(1002));
assert.equal(s.stage, "countdown");
s = e.advanceTime(s, ctx(12000));
s = e.presenceChanged(s, [], ctx(9000));
s = e.advanceTime(s, ctx(9000));
assert.equal(s.stage, "presence");
assert.equal(e.ended(s), false);
assert.equal(s.missionStartAt, null);
s = e.presenceChanged(s, [0], ctx(13000));
s = e.move(s, { type: "ready", sequence: 2 }, 0, ctx(13000));
for (let at = 15000; at < 133000; at += 2000)
s = e.move(s, { type: "presence" }, 0, ctx(at));
s = e.advanceTime(s, ctx(133000));
assert.equal(s.players[0].ready, false);
assert.equal(e.nextWakeup(s), null);
@ -159,10 +162,63 @@ test("expired readiness leaves careers editable and does not start a run", () =>
ctx(1001),
);
assert.equal(s.bgs.explorers.alice.activeRun, null);
s = e.advanceTime(s, ctx(100000));
s = e.advanceTime(s, ctx(121002));
assert.equal(
e.stripSecret(s, 0, ctx(100000)).explorers.find((x) => x.id === "alice")
e.stripSecret(s, 0, ctx(121002)).explorers.find((x) => x.id === "alice")
.editable,
true,
);
});
test("platform presence gates readiness; user moves cannot spoof it", () => {
const absent = e.init(2, [], {}, "seed", 0, ctx(1000, { present: [] }));
assert.throws(
() => e.move(absent, { type: "ready", sequence: 1 }, 0, ctx(1001)),
/Reconnect/,
);
assert.throws(
() => e.move(absent, { type: "presence", sequence: 1 }, 0, ctx(1001)),
/Unsupported/,
);
const present = e.presenceChanged(absent, [0], ctx(1002));
assert.equal(
e.move(present, { type: "ready", sequence: 1 }, 0, ctx(1003)).players[0]
.ready,
true,
);
assert.deepEqual(e.phase(present), { name: "waiting", canLeave: true });
assert.deepEqual(e.phase(launch()), { name: "playing", canLeave: false });
});
test("career progress is bounded, contains no mission secrets, and rejects unknown schemas", () => {
const s = e.dropPlayer(initial({ careers: true }));
s.bgs.explorers.alice.runs = Array.from({ length: 1000 }, (_, i) => ({
id: `old-${i}`,
survived: true,
at: i,
count: 3,
limit: 3,
training: false,
}));
const progress = e.tableProgress(s);
assert.equal(progress.data.explorers.alice.runs.length, 1);
assert.equal(progress.data.explorers.alice.archive.completed, 999);
assert.equal(progress.data.explorers.alice.archive.campaigns, 999);
assert.ok(JSON.stringify(progress).length < 4000);
assert.ok(!JSON.stringify(progress).includes("private-seed"));
assert.deepEqual(e.migrateTableProgress(progress), progress);
assert.throws(
() => e.migrateTableProgress({ version: 2, data: {} }),
/Unsupported/,
);
const next = e.init(
2,
[],
{ careers: true },
"different-seed",
0,
ctx(2000, { table: { id: "table", round: 2, progress } }),
);
assert.equal(next.bgs.explorers.alice.archive.completed, 999);
assert.equal(next.players[0].ready, false);
assert.equal(next.players[0].lastSequence, 0);
});