diff --git a/README.md b/README.md index 0b982f9..40adece 100644 --- a/README.md +++ b/README.md @@ -15,13 +15,13 @@ npm run dev Open . Start with **Flight school / École de vol**: seven untimed exercises use the real engine, with editable programs and a teammate already maintaining the computer. The examples cover firing, energy, malfunctions, battlebots/interceptors, double actions, phasing and specializations. -For a full mission, expand **Local session / Session locale**. Select 1–5 humans, the crew, mission, threat pools and optional modules. In solo, you control four androids and have access to the full action deck. In multiplayer testing, open another tab with `?seat=1`, etc. Confirm presence within two minutes; the shared mission starts three seconds after everyone is ready. Select a card half, then a turn. Advance individual phases to lock previous turns, or let the shared clock do so. After programming, the captain can resolve one step at a time or finish the mission; everyone can inspect the replay and log. +For a full mission, expand **Local session / Session locale**. Select 1–5 humans, the crew, mission, threat pools and optional modules. In solo, you control four androids and have access to the full action deck. In multiplayer testing, open another tab with `?seat=1`, etc. Readiness lasts two minutes; everyone must be ready together. The local mission starts after a three-second countdown. If someone misses the window, the crew keeps waiting. Select a card half, then a turn. Advance individual phases to lock previous turns, or let the shared clock do so. After programming, the captain can resolve one step at a time or finish the mission; everyone can inspect the replay and log. The local seat selector, “Ready all” and “Next announcement” buttons are development tools. This host has **no authentication** and deliberately listens only on `127.0.0.1`. It is not an online multiplayer deployment. Use external voice for cooperation; browser speech synthesis is optional and communications-blackout silence relies on the players. ## Implemented -- Trusted host clock, autonomous deadlines, presence cancellation, reconnection, atomic game commands and idempotent command sequences. +- Trusted host clock, autonomous deadlines, expiring readiness, reconnection, atomic game commands and idempotent command sequences. - 34 imported fixed mission schedules, including 18 double-action missions. The randomized mission generator has not been ported. - Private hands and permitted card backs; phase packets, incoming data, transfers, android donations, solo programming and shared-slot conflict checks. - Exact 90-card base and 90-card double-action decks, 6 heroic cards and all 10 specializations at levels 1–3. diff --git a/bgs/engine.js b/bgs/engine.js index 162dfc1..cfb3010 100644 --- a/bgs/engine.js +++ b/bgs/engine.js @@ -1,6 +1,7 @@ import { createHash } from "node:crypto"; import { createSession, + keepPresent, advanceClock, nextWakeup as wakeup, submit, @@ -35,9 +36,19 @@ function settle(state) { runId = g.campaign?.id ?? g.seed; for (const [seat, id] of (state.bgs?.playerIds ?? []).entries()) { const e = state.bgs.explorers?.[id]; - if (!e?.activeRun) continue; + if ( + e && + !e.activeRun && + !e.runs.some((run) => run.id === runId) && + ["programming", "resolution"].includes(state.stage) && + state.bgs.settings.careers + ) { + state.bgs.explorers[id] = startExplorer(e, runId); + } + const current = state.bgs.explorers?.[id]; + if (!current?.activeRun) continue; if (state.stage === "cancelled") { - state.bgs.explorers[id] = cancelExplorer(e, runId); + state.bgs.explorers[id] = cancelExplorer(current, runId); continue; } const outcome = result(state); @@ -54,7 +65,7 @@ function settle(state) { .filter((e) => e.type === "threat") .reduce((n, e) => n + (e.severity === "serious" ? 2 : 1), 0), }; - state.bgs.explorers[id] = settleExplorer(e, { + state.bgs.explorers[id] = settleExplorer(current, { id: runId, ...outcome, count: g.campaign?.missions.length ?? 1, @@ -124,6 +135,7 @@ export function init(players, expansions, options, seed, creator, context) { const state = createSession( { players, + connectionChecks: true, crewSize, mission, gameOptions: { @@ -161,6 +173,11 @@ 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"); @@ -196,6 +213,7 @@ export function move(input, command, seat, context) { const next = createSession( { players: state.players.length, + connectionChecks: true, crewSize: state.crewSize, mission, gameOptions: { @@ -285,19 +303,6 @@ export function move(input, command, seat, context) { } else reject("Unknown career action"); state.revision++; } else { - if ( - command.type === "ready" && - state.bgs.settings.careers && - state.bgs.explorers[state.bgs.playerIds[seat]] - ) { - const id = state.bgs.playerIds[seat], - e = state.bgs.explorers[id]; - if (!e.activeRun) - state.bgs.explorers[id] = startExplorer( - e, - state.game.campaign?.id ?? state.game.seed, - ); - } const response = submit(state, seat, command, now); if (!response.accepted) reject(response.error); return settle(response.state); diff --git a/bgs/gameinfo.json b/bgs/gameinfo.json index 93fd985..c167442 100644 --- a/bgs/gameinfo.json +++ b/bgs/gameinfo.json @@ -6,12 +6,13 @@ }, "public": false, "timeControl": "engine", + "tableMode": "live", "rating": "none", "meta": {}, "engine": { "package": { "name": "@boardgamers/space-alert", - "version": "0.1.1" + "version": "0.1.2" }, "entryPoint": "bgs/engine.js" }, diff --git a/bgs/viewer.js b/bgs/viewer.js index f88809b..54685f9 100644 --- a/bgs/viewer.js +++ b/bgs/viewer.js @@ -45,6 +45,16 @@ 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. @@ -92,6 +102,7 @@ registerViewer("SpaceAlert", (context) => { if (el) el.textContent = String(error); }, destroy() { + clearInterval(presence); ui.destroy(); if (pending) { clearTimeout(pending.timer); diff --git a/docs/design.md b/docs/design.md index 3b3e9ab..4661d0d 100644 --- a/docs/design.md +++ b/docs/design.md @@ -27,7 +27,7 @@ All four layers are implemented, with both a standalone local host and an authen | Androids | Multiplayer android actions use donated cards face up and are irreversible once placed. Heroic cards belong to their assigned crew member. Solo has distinct rules: four androids, a shared available deck and revisable programs until the global deadlines. | | Resolution | Follow the Mission Steps Board: appearances, ordered crew actions, damage calculations, threat movement and X/Y/Z effects, computer checks, and end-of-mission handling. Rebuild from the initial ship and committed programs; a visual planning marker is not actual ship state. | | Ship | Six stations, gravolifts, reactor/shield capacities, laser and pulse weapons, rockets, interceptors, battlebots, malfunctions and damage tiles. Delays shift the remaining program and can discard actions; they are not simply skipped turns. | -| Outcome | Shared survival and score. Cancellation for missing presence is neither a defeat nor a competitive tie. BGS needs explicit cooperative/no-rating treatment. | +| Outcome | Shared survival and score. Expired readiness keeps the crew waiting; it does not end a game. BGS needs explicit cooperative/no-rating treatment. | | Campaign | Up to three linked base-game missions, repairs and carried damage. Keep an in-game campaign in engine state; do not confuse it with persistent New Frontier character careers. | Sources: [base rules](https://filemanager.czechgames.com/storage/files/space-alert/rules/space-alert-rules-en.pdf), especially §§2–3 and §§5–6, and the [teaching handbook](https://filemanager.czechgames.com/storage/files/space-alert/other-downloads/handbook/space-alert-handbook-en.pdf). diff --git a/docs/realtime-host.md b/docs/realtime-host.md index 51e7c19..e0b2d9b 100644 --- a/docs/realtime-host.md +++ b/docs/realtime-host.md @@ -6,7 +6,7 @@ The adapter is in `bgs/engine.js`; the hosted viewer is `bgs/viewer.js`. It uses 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. -There is a fixed two-minute presence check after the host starts the game. Each human presses **I’m ready**; launch is shared, three seconds after the final confirmation. Missing readiness cancels without an inactivity or Elo penalty. Reconnecting does not restart or pause the flight. +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. 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. @@ -14,7 +14,7 @@ After programming, resolution has no deadline. Campaign repairs and the decision ## Same table, new game -BGS **Play again** creates a new game record with fresh randomness, the same reserved seats and optional setup changes. Other players confirm their seats; the host starts when they are ready. 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. +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. @@ -28,4 +28,4 @@ Use external voice for cooperation. Speech synthesis is optional; no official re ## Verification -`npm test` covers trusted timestamps, deadline catch-up without clients, readiness cancellation, duplicate commands, late rejections, spectator secrecy, reordered-seat career inheritance, cancellation, and the underlying game rules. BGS tests cover durable wakeups, terminal notifications, atomic table creation, concurrent continuations, access checks and seat confirmation. The hosted viewer has also been exercised with two authenticated browser sessions, including a mobile viewport. +`npm test` covers trusted timestamps, deadline catch-up without clients, readiness expiry, withdrawal and disconnect recovery, duplicate commands, late rejections, spectator secrecy, reordered-seat career inheritance, cancellation, and the underlying game rules. BGS tests cover durable wakeups, terminal notifications, atomic table creation, concurrent continuations, access checks and seat confirmation. The hosted viewer has also been exercised with two authenticated browser sessions, including a mobile viewport. diff --git a/package.json b/package.json index a590c71..38f4c6b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@boardgamers/space-alert", - "version": "0.1.1", + "version": "0.1.2", "private": true, "type": "module", "description": "Space Alert and The New Frontier: deterministic game engine and local playtest", diff --git a/preview/app.js b/preview/app.js index 047c04f..b4dcbd1 100644 --- a/preview/app.js +++ b/preview/app.js @@ -222,7 +222,7 @@ export function mountConsole(root, host = null) { function render(next, force = false) { view = next; received = performance.now(); - const newKey = `${view.presenceDeadline}/${view.revision}/${seat}/${locale}`; + const newKey = `${view.revision}/${seat}/${locale}`; renderCareers(next); if (!force && key === newKey) return; key = newKey; @@ -431,8 +431,8 @@ export function mountConsole(root, host = null) { ) : view.stage === "presence" ? t( - "Deux minutes pour confirmer ; le départ est commun.", - "Two minutes to confirm; launch is shared.", + "Prêt pendant deux minutes. Nous attendons que tout le monde soit prêt.", + "Ready lasts two minutes. We wait until everyone is ready together.", ) : view.stage === "resolution" ? t( @@ -440,25 +440,34 @@ export function mountConsole(root, host = null) { "Programs are locked. Advance resolution or review its steps.", ) : ""; - $("#controls").innerHTML = - view.stage === "presence" - ? button( - "ready", - own.ready - ? t("Présence confirmée", "Presence confirmed") - : t("Je suis prêt", "I’m ready"), - own.ready, - 'class="primary"', - ) - : planning - ? `${g?.solo ? "" : button("advance-phase", t("Phase suivante →", "Next phase →"), own.finishedPlanning || own.planningPhase >= view.mission.phaseEndsMs.length)}${button("finish-planning", t("Verrouiller mon programme", "Lock my program"), own.finishedPlanning || view.phase < view.mission.phaseEndsMs.length)}${g.dataCredits ? button("draw", `${t("Piocher", "Draw")} +${g.dataCredits}`) : ""}${g.androidDataCredits ? button("draw-android", t("Carte androïde", "Android card") + ` +${g.androidDataCredits}`, !g.canDrawAndroid) : ""}` - : view.stage === "resolution" - ? `${button("resolve", t("Étape suivante →", "Next step →"), seat !== 0 || !!resolution?.outcome, 'class="primary"')}${button("resolve-all", t("Résoudre la mission", "Resolve mission"), seat !== 0 || !!resolution?.outcome)}` - : view.stage === "cancelled" - ? '" - : ""; + $("#controls").innerHTML = ["presence", "countdown"].includes(view.stage) + ? button( + 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], + 'class="primary"', + ) + : planning + ? `${g?.solo ? "" : button("advance-phase", t("Phase suivante →", "Next phase →"), own.finishedPlanning || own.planningPhase >= view.mission.phaseEndsMs.length)}${button("finish-planning", t("Verrouiller mon programme", "Lock my program"), own.finishedPlanning || view.phase < view.mission.phaseEndsMs.length)}${g.dataCredits ? button("draw", `${t("Piocher", "Draw")} +${g.dataCredits}`) : ""}${g.androidDataCredits ? button("draw-android", t("Carte androïde", "Android card") + ` +${g.androidDataCredits}`, !g.canDrawAndroid) : ""}` + : view.stage === "resolution" + ? `${button("resolve", t("Étape suivante →", "Next step →"), seat !== 0 || !!resolution?.outcome, 'class="primary"')}${button("resolve-all", t("Résoudre la mission", "Resolve mission"), seat !== 0 || !!resolution?.outcome)}` + : view.stage === "cancelled" + ? '" + : ""; + const preparing = ["presence", "countdown"].includes(view.stage); + root.classList.toggle("preparing", preparing); + $("#preparation").hidden = !preparing; + $("#ready-help").textContent = preparing + ? $("#player-help").textContent + : ""; + $("#ready-controls").replaceChildren( + ...(preparing ? [...$("#controls").childNodes] : []), + ); + if (preparing && host) $("#notice").textContent = view.mission.title; const hand = [ ...(g?.hand ?? []), ...(g?.androidCards ?? []).filter((c) => c.owner === crew), @@ -1166,7 +1175,7 @@ export function mountConsole(root, host = null) { const now = view.serverNow + performance.now() - received; const end = view.stage === "presence" - ? view.presenceDeadline + ? view.players[seat]?.readyUntil : view.stage === "countdown" ? view.missionStartAt : view.stage === "programming" @@ -1174,13 +1183,17 @@ export function mountConsole(root, host = null) { : now; $("#clock").textContent = view.tutorial ? t("Libre", "Untimed") - : duration(end - now); + : view.stage === "presence" && !view.players[seat]?.ready + ? t("En attente", "Waiting") + : duration((end ?? now) - now); $("#clock-caption").textContent = view.tutorial ? "" : view.stage === "programming" ? t("avant le saut", "until jump") : view.stage === "presence" - ? t("pour confirmer", "to confirm") + ? view.players[seat]?.ready + ? t("prêt encore", "ready for") + : "" : ""; }, 100), ); diff --git a/preview/index.html b/preview/index.html index fa14478..9d42e97 100644 --- a/preview/index.html +++ b/preview/index.html @@ -38,6 +38,10 @@
+
diff --git a/preview/style.css b/preview/style.css index f6d2627..3d7047e 100644 --- a/preview/style.css +++ b/preview/style.css @@ -695,3 +695,15 @@ input:not([type="checkbox"]):not([type="range"]) { #lesson-list button { margin: 0.3rem 0.1rem; } + +.preparing .flight-layout, +.preparing #journal { + display: none; +} +#preparation { + margin: 24px 0; +} +#ready-help { + margin-bottom: 12px; + color: var(--muted); +} diff --git a/src/session.js b/src/session.js index 30e353a..173d0d1 100644 --- a/src/session.js +++ b/src/session.js @@ -10,6 +10,7 @@ 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) @@ -20,7 +21,13 @@ function append(state, at, type, details = {}) { state.revision++; } export function createSession( - { players, crewSize = Math.max(4, players), mission, gameOptions }, + { + players, + crewSize = Math.max(4, players), + mission, + gameOptions, + connectionChecks = false, + }, now, ) { timestamp(now); @@ -35,7 +42,7 @@ export function createSession( revision: 0, observedAt: now, createdAt: now, - presenceDeadline: now + PRESENCE_WINDOW_MS, + connectionChecks, missionStartAt: null, mission: { id: mission.id, @@ -47,6 +54,8 @@ export function createSession( players: Array.from({ length: players }, (_, seat) => ({ seat, ready: false, + readyUntil: null, + connectedUntil: null, planningPhase: 0, finishedPlanning: false, lastSequence: 0, @@ -78,13 +87,22 @@ export function advanceClock(input, now) { const state = structuredClone(input); state.observedAt = Math.max(now, state.observedAt); now = state.observedAt; - if (state.stage === "presence" && now >= state.presenceDeadline) { - state.stage = "cancelled"; - state.cancellation = { - reason: "presence-timeout", - missingSeats: state.players.filter((p) => !p.ready).map((p) => p.seat), - }; - append(state, state.presenceDeadline, "cancelled", state.cancellation); + if (["presence", "countdown"].includes(state.stage)) { + // A delayed wakeup must settle readiness at launch time, not after the flight. + const at = + state.stage === "countdown" ? Math.min(now, state.missionStartAt) : now; + for (const player of state.players) { + if (player.ready && readinessDeadline(state, player) <= at) { + player.ready = false; + player.readyUntil = player.connectedUntil = null; + append(state, at, "ready-expired", { seat: player.seat }); + } + } + if (state.stage === "countdown" && !state.players.every((p) => p.ready)) { + state.stage = "presence"; + state.missionStartAt = null; + append(state, at, "launch-postponed"); + } } if (state.stage === "countdown" && now >= state.missionStartAt) { state.stage = "programming"; @@ -117,9 +135,32 @@ 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; + } + return state; +} + export function nextWakeup(state) { - if (state.stage === "presence") return state.presenceDeadline; - if (state.stage === "countdown") return state.missionStartAt; + if (["presence", "countdown"].includes(state.stage)) { + const deadlines = state.players + .filter((p) => p.ready) + .map((p) => readinessDeadline(state, p)); + if (state.stage === "countdown") deadlines.push(state.missionStartAt); + return deadlines.length ? Math.min(...deadlines) : null; + } if (state.stage === "programming") return state.missionStartAt + state.timeline[state.cursor].atMs; return null; @@ -141,6 +182,7 @@ export function submit(input, seat, command, receivedAt) { if ( ![ "ready", + "unready", "advance-phase", "finish-planning", ...Object.keys(GAME_COMMAND_FIELDS), @@ -173,15 +215,26 @@ export function submit(input, seat, command, receivedAt) { draft.revision++; return { state: draft, accepted: true, duplicate: false }; } - if (command.type === "ready") { + if (command.type === "unready") { + if (!["presence", "countdown"].includes(state.stage)) + return reject("The mission has started"); + player.ready = false; + player.readyUntil = player.connectedUntil = 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 (!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)) { state.stage = "countdown"; - state.missionStartAt = now + LAUNCH_COUNTDOWN_MS; + state.missionStartAt = + now + (state.connectionChecks ? 10_000 : LAUNCH_COUNTDOWN_MS); append(state, now, "launch-scheduled", { startsAt: state.missionStartAt, }); diff --git a/src/view.js b/src/view.js index 8697f24..e2f3ec3 100644 --- a/src/view.js +++ b/src/view.js @@ -8,7 +8,7 @@ export function snapshot(state, seat) { revision: state.revision, stage: state.stage, serverNow: state.observedAt, - presenceDeadline: state.presenceDeadline, + missionStartAt: state.missionStartAt, mission: state.mission, crewSize: state.crewSize, diff --git a/test/bgs.test.js b/test/bgs.test.js index f7ee0be..3fc3c15 100644 --- a/test/bgs.test.js +++ b/test/bgs.test.js @@ -10,13 +10,14 @@ const ctx = (now, extra = {}) => ({ }); const initial = (options = {}) => e.init(2, [], options, "private-seed", 0, ctx(1000)); -const launch = (s = initial()) => - e.move( - e.move(s, { type: "ready", sequence: 1 }, 0, ctx(1001)), - { type: "ready", sequence: 1 }, - 1, - ctx(1002), - ); +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", () => { assert.throws(() => e.init(2, [], {}, "seed", 0), /server clock/); assert.throws( @@ -60,18 +61,18 @@ test("catches up while disconnected, leaves resolution untimed, and repeats safe assert.equal(e.ended(resolved), true); assert.equal(e.scores(resolved)[0], e.scores(resolved)[1]); }); -test("missing readiness cancels without inventing player timeouts", () => { +test("missing readiness keeps the table waiting without player timeouts", () => { const s = e.advanceTime(initial(), ctx(121000)); - assert.equal(e.ended(s), true); - assert.equal(e.cancelled(s), true); + assert.equal(e.ended(s), false); + assert.equal(e.cancelled(s), false); assert.equal(e.nextWakeup(s), null); - assert.deepEqual(e.currentPlayer(s), []); + assert.deepEqual(e.currentPlayer(s), [0, 1]); }); test("snapshots hide deck, future announcements and other hands from players and spectators", () => { - const s = e.advanceTime(launch(), ctx(4010)); + const s = e.advanceTime(launch(), ctx(12000)); for (const seat of [undefined, 0, 1]) { - const view = e.stripSecret(s, seat, ctx(4100)); - assert.equal(view.serverNow, 4100); + const view = e.stripSecret(s, seat, ctx(12100)); + assert.equal(view.serverNow, 12100); assert.equal(view.timeline, undefined); assert.equal(view.bgs.playerIds, undefined); assert.equal(view.game.seed, undefined); @@ -134,3 +135,34 @@ test("a dropped player ends the cooperative session and unlocks explorer records Object.values(cancelled.bgs.explorers).every((p) => p.activeRun === null), ); }); + +test("disconnect during launch returns to waiting; heartbeat 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)); + assert.equal(s.stage, "presence"); + assert.equal(e.ended(s), false); + assert.equal(s.missionStartAt, null); + 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); +}); +test("expired readiness leaves careers editable and does not start a run", () => { + let s = e.move( + initial({ careers: true }), + { type: "ready", sequence: 1 }, + 0, + ctx(1001), + ); + assert.equal(s.bgs.explorers.alice.activeRun, null); + s = e.advanceTime(s, ctx(100000)); + assert.equal( + e.stripSecret(s, 0, ctx(100000)).explorers.find((x) => x.id === "alice") + .editable, + true, + ); +}); diff --git a/test/preview.test.js b/test/preview.test.js index b2bd2f1..be5c457 100644 --- a/test/preview.test.js +++ b/test/preview.test.js @@ -45,12 +45,13 @@ test("local host shares state across seats and commits deadline changes on rejec type: "ready", sequence: 1, }); - assert.equal(late.status, 409); + assert.equal(late.status, 200); const stored = await fetch(base + "/api/state?seat=0").then((r) => r.json(), ); - assert.equal(stored.stage, "cancelled"); - assert.deepEqual(stored.cancellation.missingSeats, [1, 2, 3]); + assert.equal(stored.stage, "presence"); + assert.equal(stored.players[0].ready, false); + assert.equal(stored.players[1].ready, true); } finally { server.close(); await once(server, "close"); diff --git a/test/session.test.js b/test/session.test.js index 436a49e..db5b42b 100644 --- a/test/session.test.js +++ b/test/session.test.js @@ -76,39 +76,52 @@ test("all 34 imported timelines compile, including the 18 double-action missions } }); -test("presence expires autonomously; the engine records cancellation, not a defeat", () => { - const state = create(); - assert.equal(nextWakeup(state), epoch + 120_000); - const result = advanceClock(state, epoch + 120_000); - assert.equal(result.stage, "cancelled"); - assert.deepEqual(result.cancellation, { - reason: "presence-timeout", - missingSeats: [0, 1, 2, 3], - }); - assert.equal(nextWakeup(result), null); - assert.equal(result.log.length, 1); - assert.equal(state.log.length, 0, "Input state is not mutated"); - assert.equal(advanceClock(result, epoch + 900_000).log.length, 1); +test("waiting has no deadline; readiness expires individually without cancelling", () => { + let state = create(); + assert.equal(nextWakeup(state), null); + state = advanceClock(state, epoch + 86400000); + assert.equal(state.stage, "presence"); + state = submit( + state, + 0, + { type: "ready", sequence: 1 }, + epoch + 86400000, + ).state; + assert.equal(nextWakeup(state), epoch + 86520000); + const later = advanceClock(state, epoch + 86520000); + assert.equal(later.stage, "presence"); + assert.equal(later.players[0].ready, false); + assert.equal(nextWakeup(later), null); + assert.equal(state.players[0].ready, true); }); -test("the last ready request at the exact deadline is too late", () => { - let state = create(); - for (const seat of [0, 1, 2]) - state = submit( - state, - seat, - { type: "ready", sequence: 1 }, - epoch + 119_999, - ).state; - const result = submit( +test("readiness must overlap, and withdrawing during countdown postpones launch", () => { + let state = create(2); + state = submit(state, 0, { type: "ready", sequence: 1 }, epoch).state; + state = submit( state, - 3, + 1, { type: "ready", sequence: 1 }, - epoch + 120_000, - ); - assert.equal(result.accepted, false); - assert.equal(result.state.stage, "cancelled"); - assert.deepEqual(result.state.cancellation.missingSeats, [3]); + epoch + 120000, + ).state; + assert.equal(state.stage, "presence"); + assert.equal(state.players[0].ready, false); + state = submit( + state, + 0, + { type: "ready", sequence: 2 }, + epoch + 120001, + ).state; + assert.equal(state.stage, "countdown"); + state = submit( + state, + 1, + { type: "unready", sequence: 2 }, + epoch + 120002, + ).state; + assert.equal(state.stage, "presence"); + assert.equal(state.missionStartAt, null); + assert.equal(state.players[0].ready, true); }); test("the shared countdown starts once, after the last player is ready", () => {