Serve lightweight live logs and remove unused viewer undo checks
This commit is contained in:
parent
8bc8910c24
commit
0f65697aa6
10 changed files with 231 additions and 93 deletions
|
|
@ -68,7 +68,7 @@ Enable “Show everyone’s VP” at game creation to reveal accumulated VP toke
|
||||||
|
|
||||||
## Replay, journal and platform compatibility
|
## Replay, journal and platform compatibility
|
||||||
|
|
||||||
The journal retains the latest 200 events. Older score contributions are accumulated by player and source, so the score breakdown remains accurate. The accepted move history remains complete for every replay boundary and analysis branch; unlike the journal, its storage grows with the number of moves. Undo restores its previous branch instead of appending undo events; regression tests repeatedly undo and replay the same action to check that abandoned branches do not accumulate. Log slices reuse the current position and short-lived role checkpoints rather than repeatedly replaying the entire game; raw checkpoints are never saved or sent to viewers. Replay frames are private to the requesting seat, and postgame analysis disables forced-move automation so each branch can be explored explicitly. Analysis is unavailable during live games to protect hidden objectives and future draws.
|
The journal retains the latest 200 events. Older score contributions are accumulated by player and source, so the score breakdown remains accurate. The accepted move history remains complete for every replay boundary and analysis branch; unlike the journal, its storage grows with the number of moves. Undo restores its previous branch instead of appending undo events; regression tests repeatedly undo and replay the same action to check that abandoned branches do not accumulate. BGS live log slices return lightweight indexed notifications without replaying or cloning game state; the viewer refreshes the authoritative seat-filtered state. Explicit bounded history requests reconstruct replay frames. Historical frames skip edit-eligibility checks, and viewer states no longer calculate generic undo availability. Live play exposes only eligible choice edits; local snapshot and host undo APIs remain separate. Replay frames are private to the requesting seat, and postgame analysis disables forced-move automation so each branch can be explored explicitly. Analysis is unavailable during live games to protect hidden objectives and future draws.
|
||||||
|
|
||||||
Chat opens from the button next to the journal. On a host/SDK exposing `openChat` and advertising `platformChat`, it opens the native BGS chat. Protocol 0.9 hosts retain the functional SDK chat dialog. Native chat requires the corresponding platform PR and a protocol package upgrade; no unsupported messages are sent to older hosts.
|
Chat opens from the button next to the journal. On a host/SDK exposing `openChat` and advertising `platformChat`, it opens the native BGS chat. Protocol 0.9 hosts retain the functional SDK chat dialog. Native chat requires the corresponding platform PR and a protocol package upgrade; no unsupported messages are sent to older hosts.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,31 @@ import * as game from "../engine/index.js";
|
||||||
import en from "../viewer/locales/en.json" with { type: "json" };
|
import en from "../viewer/locales/en.json" with { type: "json" };
|
||||||
import { RELEASE } from "../release-config.js";
|
import { RELEASE } from "../release-config.js";
|
||||||
|
|
||||||
|
// An omitted end is a live notification, not a historical seek. Keep one
|
||||||
|
// lightweight entry per requested index for platform log consumers (index zero
|
||||||
|
// is the initial position), without exposing raw moves/private choices. The
|
||||||
|
// viewer fetches authoritative seat-filtered state on receipt; never replay here.
|
||||||
|
export function logSlice(s, { player, start = 0, end } = {}, _context) {
|
||||||
|
if (end !== undefined) return game.logSlice(s, { player, start, end });
|
||||||
|
if (!Number.isSafeInteger(start) || start < 0)
|
||||||
|
throw Object.assign(new Error("Invalid replay range"), {
|
||||||
|
name: "InvalidMoveError",
|
||||||
|
});
|
||||||
|
const log = [];
|
||||||
|
for (let index = start; index < game.logLength(s); index++)
|
||||||
|
log.push({ index, simple: index === 0 ? "Game started" : `Move ${index}` });
|
||||||
|
return { log, frames: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The platform's default analysisView omits end. Analysis history navigation
|
||||||
|
// needs frames, unlike live notifications, so explicitly request full history.
|
||||||
|
export function analysisView(s, { player } = {}, _context) {
|
||||||
|
return {
|
||||||
|
state: game.stripSecret(s, player),
|
||||||
|
log: game.logSlice(s, { player, start: 0, end: game.logLength(s) - 1 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const solo = (s) => s.options.hostedSolo === true;
|
const solo = (s) => s.options.hostedSolo === true;
|
||||||
function checkSeat(s, p) {
|
function checkSeat(s, p) {
|
||||||
if (solo(s) && p !== 0)
|
if (solo(s) && p !== 0)
|
||||||
|
|
|
||||||
|
|
@ -1411,7 +1411,7 @@ function placementUndoState(s, p) {
|
||||||
return null;
|
return null;
|
||||||
return candidate;
|
return candidate;
|
||||||
}
|
}
|
||||||
function productionEditState(s, p, checkpoint) {
|
function productionEditState(s, p) {
|
||||||
if (s.tutorial || s.finished || s.puertoma || s.tasks[0]?.kind !== "produce")
|
if (s.tutorial || s.finished || s.puertoma || s.tasks[0]?.kind !== "produce")
|
||||||
return null;
|
return null;
|
||||||
const index = s.history.findLastIndex((h) => h.p === p);
|
const index = s.history.findLastIndex((h) => h.p === p);
|
||||||
|
|
@ -1425,7 +1425,7 @@ function productionEditState(s, p, checkpoint) {
|
||||||
.some((h) => !["produce", "produceBonus", "pass"].includes(h.move.type))
|
.some((h) => !["produce", "produceBonus", "pass"].includes(h.move.type))
|
||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
const before = replayFromCheckpoint(s, index + 1, checkpoint);
|
const before = replay(s, index + 1);
|
||||||
const task = playerTask(before, p);
|
const task = playerTask(before, p);
|
||||||
if (
|
if (
|
||||||
!["produce", "produceBonus"].includes(task?.kind) ||
|
!["produce", "produceBonus"].includes(task?.kind) ||
|
||||||
|
|
@ -1441,10 +1441,9 @@ function productionEditState(s, p, checkpoint) {
|
||||||
return null;
|
return null;
|
||||||
let candidate;
|
let candidate;
|
||||||
try {
|
try {
|
||||||
candidate = replayFromCheckpoint(
|
candidate = replay(
|
||||||
{ ...s, history: s.history.filter((_, i) => i !== index) },
|
{ ...s, history: s.history.filter((_, i) => i !== index) },
|
||||||
s.history.length,
|
s.history.length,
|
||||||
checkpoint,
|
|
||||||
);
|
);
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
|
|
@ -1468,23 +1467,17 @@ function productionEditState(s, p, checkpoint) {
|
||||||
return reveals(candidate) === reveals(s) ? candidate : null;
|
return reveals(candidate) === reveals(s) ? candidate : null;
|
||||||
}
|
}
|
||||||
export function canEditProduction(s, p) {
|
export function canEditProduction(s, p) {
|
||||||
return canEditProductionFromCheckpoint(s, p);
|
return !!productionEditState(s, p);
|
||||||
}
|
|
||||||
function canEditProductionFromCheckpoint(s, p, checkpoint) {
|
|
||||||
return !!productionEditState(s, p, checkpoint);
|
|
||||||
}
|
}
|
||||||
export function canEditPlacement(s, p) {
|
export function canEditPlacement(s, p) {
|
||||||
return !!placementUndoState(s, p);
|
return !!placementUndoState(s, p);
|
||||||
}
|
}
|
||||||
export function canUndo(s, p) {
|
export function canUndo(s, p) {
|
||||||
return canUndoFromPrevious(s, p);
|
|
||||||
}
|
|
||||||
function canUndoFromPrevious(s, p, previous) {
|
|
||||||
if (s.tutorial) return false;
|
if (s.tutorial) return false;
|
||||||
const last = s.history.at(-1);
|
const last = s.history.at(-1);
|
||||||
if (!last || last.p !== p || s.finished || !currentPlayers(s).includes(p))
|
if (!last || last.p !== p || s.finished || !currentPlayers(s).includes(p))
|
||||||
return false;
|
return false;
|
||||||
const before = previous ?? replay(s, logLength(s) - 1);
|
const before = replay(s, logLength(s) - 1);
|
||||||
return (
|
return (
|
||||||
JSON.stringify(currentPlayers(before).slice().sort()) ===
|
JSON.stringify(currentPlayers(before).slice().sort()) ===
|
||||||
JSON.stringify(currentPlayers(s).slice().sort()) &&
|
JSON.stringify(currentPlayers(s).slice().sort()) &&
|
||||||
|
|
@ -1614,7 +1607,7 @@ function applyMove(state, m, p, historical = false) {
|
||||||
// Historical transitions only receive private states constructed by replay
|
// Historical transitions only receive private states constructed by replay
|
||||||
// (or this logSlice call). Entries are append-only and each incoming move is
|
// (or this logSlice call). Entries are append-only and each incoming move is
|
||||||
// cloned below. Copy the array, not its entire growing prefix: no public
|
// cloned below. Copy the array, not its entire growing prefix: no public
|
||||||
// input history is shared, and predecessor/checkpoint arrays remain stable.
|
// input history is shared, and earlier replay arrays remain stable.
|
||||||
const s = historical ? cloneReplayPosition(state) : clone(state),
|
const s = historical ? cloneReplayPosition(state) : clone(state),
|
||||||
t = playerTask(s, p),
|
t = playerTask(s, p),
|
||||||
a = s.players[p],
|
a = s.players[p],
|
||||||
|
|
@ -2203,9 +2196,9 @@ export function rankings(s) {
|
||||||
// BGS supplies an engine context as the third argument. Never interpret that
|
// BGS supplies an engine context as the third argument. Never interpret that
|
||||||
// public protocol argument as a replay state or checkpoint.
|
// public protocol argument as a replay state or checkpoint.
|
||||||
export function stripSecret(state, p, _context) {
|
export function stripSecret(state, p, _context) {
|
||||||
return stripSecretForLog(state, p);
|
return stripSecretForViewer(state, p, true);
|
||||||
}
|
}
|
||||||
function stripSecretForLog(state, p, previous, checkpoint) {
|
function stripSecretForViewer(state, p, editable = false) {
|
||||||
// The authoritative move history is needed for replay, but never belongs in a
|
// The authoritative move history is needed for replay, but never belongs in a
|
||||||
// viewer frame. Exclude it before cloning every frame of a long log slice.
|
// viewer frame. Exclude it before cloning every frame of a long log slice.
|
||||||
const { history: _history, ...visible } = state;
|
const { history: _history, ...visible } = state;
|
||||||
|
|
@ -2244,11 +2237,11 @@ function stripSecretForLog(state, p, previous, checkpoint) {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// Logs contain only public moves; historical earned points are public even though totals are concealed.
|
// Logs contain only public moves; historical earned points are public even though totals are concealed.
|
||||||
s.canUndo = Number.isInteger(p) && canUndoFromPrevious(state, p, previous);
|
// Historical frames are display-only: eligibility can replay old choices.
|
||||||
s.canEditPlacement = Number.isInteger(p) && canEditPlacement(state, p);
|
s.canEditPlacement =
|
||||||
|
editable && Number.isInteger(p) && canEditPlacement(state, p);
|
||||||
s.canEditProduction =
|
s.canEditProduction =
|
||||||
Number.isInteger(p) &&
|
editable && Number.isInteger(p) && canEditProduction(state, p);
|
||||||
canEditProductionFromCheckpoint(state, p, checkpoint);
|
|
||||||
s.currentPlayers = currentPlayers(state);
|
s.currentPlayers = currentPlayers(state);
|
||||||
const ownTask = Number.isInteger(p) ? playerTask(state, p) : null;
|
const ownTask = Number.isInteger(p) ? playerTask(state, p) : null;
|
||||||
if (ownTask && ownTask.p === p && ownTask !== state.tasks[0]) {
|
if (ownTask && ownTask.p === p && ownTask !== state.tasks[0]) {
|
||||||
|
|
@ -2283,21 +2276,6 @@ export function replay(s, options = {}) {
|
||||||
});
|
});
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
// Only the current logSlice call supplies a checkpoint from its own prefix.
|
|
||||||
// No cached raw state is stored in game data or exposed to the viewer.
|
|
||||||
function replayFromCheckpoint(s, to, checkpoint) {
|
|
||||||
if (!checkpoint || checkpoint.history.length > to - 1) return replay(s, to);
|
|
||||||
let r = checkpoint;
|
|
||||||
for (let i = checkpoint.history.length; i < to - 1; i++)
|
|
||||||
r = applyMove(r, s.history[i].move, s.history[i].p, true);
|
|
||||||
if (r === checkpoint) r = clone(r);
|
|
||||||
r.players.forEach((p, i) => {
|
|
||||||
p.name = s.players[i].name;
|
|
||||||
p.bot = s.players[i].bot;
|
|
||||||
if (s.players[i].settings) p.settings = clone(s.players[i].settings);
|
|
||||||
});
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
export function logSlice(
|
export function logSlice(
|
||||||
s,
|
s,
|
||||||
{ player, start = 0, end = logLength(s) - 1 } = {},
|
{ player, start = 0, end = logLength(s) - 1 } = {},
|
||||||
|
|
@ -2305,36 +2283,16 @@ export function logSlice(
|
||||||
assert(integer(start) && integer(end), "Invalid replay range");
|
assert(integer(start) && integer(end), "Invalid replay range");
|
||||||
const frames = [];
|
const frames = [];
|
||||||
if (start > Math.min(end, logLength(s) - 1)) return { frames };
|
if (start > Math.min(end, logLength(s) - 1)) return { frames };
|
||||||
// The common move response and last-position seek need no reconstruction.
|
// Latest-position seeks can use authoritative state without reconstruction.
|
||||||
if (start === logLength(s) - 1) {
|
if (start === logLength(s) - 1) {
|
||||||
frames.push(stripSecret(s, player));
|
frames.push(stripSecret(s, player));
|
||||||
return { frames };
|
return { frames };
|
||||||
}
|
}
|
||||||
// Reconstruct the predecessor as part of the same prefix pass. Otherwise
|
let position = replay(s, start + 1);
|
||||||
// the first frame's canUndo check replays that entire prefix a second time.
|
for (let i = start; i <= Math.min(end, logLength(s) - 1); i++) {
|
||||||
let previous = start > 0 ? replay(s, start) : undefined;
|
frames.push(stripSecretForViewer(position, player, i === logLength(s) - 1));
|
||||||
let position = previous
|
|
||||||
? applyMove(
|
|
||||||
previous,
|
|
||||||
s.history[start - 1].move,
|
|
||||||
s.history[start - 1].p,
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
: replay(s, 1);
|
|
||||||
let checkpoint;
|
|
||||||
for (let i = Math.max(0, start); i <= Math.min(end, logLength(s) - 1); i++) {
|
|
||||||
// Keep just the start of this role to accelerate production-edit checks.
|
|
||||||
// The checkpoint stays inside this call; branches use the ordinary replay.
|
|
||||||
if (position.history.length === position.roleHistoryStart + 1)
|
|
||||||
checkpoint = position;
|
|
||||||
// A preceding frame is already available after the first step. Reuse it
|
|
||||||
// when computing undo availability rather than replaying from move zero.
|
|
||||||
frames.push(stripSecretForLog(position, player, previous, checkpoint));
|
|
||||||
const h = s.history[i];
|
const h = s.history[i];
|
||||||
if (h && i < end) {
|
if (h && i < end) position = applyMove(position, h.move, h.p, true);
|
||||||
previous = position;
|
|
||||||
position = applyMove(position, h.move, h.p, true);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return { frames };
|
return { frames };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@boardgamers/puerto-rico",
|
"name": "@boardgamers/puerto-rico",
|
||||||
"version": "0.3.17",
|
"version": "0.3.18",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "Puerto Rico 1897 Special Edition for Boardgamers Space",
|
"description": "Puerto Rico 1897 Special Edition for Boardgamers Space",
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,17 @@
|
||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import * as E from "../engine/index.js";
|
import * as E from "../engine/index.js";
|
||||||
|
|
||||||
|
// Only the current frame carries edit affordances; older views are read-only.
|
||||||
|
function historicalView(state, player, current = false) {
|
||||||
|
const view = E.stripSecret(state, player);
|
||||||
|
if (!current) {
|
||||||
|
view.canEditPlacement = false;
|
||||||
|
view.canEditProduction = false;
|
||||||
|
}
|
||||||
|
return view;
|
||||||
|
}
|
||||||
|
|
||||||
import * as host from "../bgs/engine.js";
|
import * as host from "../bgs/engine.js";
|
||||||
function fixture() {
|
function fixture() {
|
||||||
let s = E.init(3, [], {}, "production-edit");
|
let s = E.init(3, [], {}, "production-edit");
|
||||||
|
|
@ -27,10 +38,14 @@ test("early production can be edited without retracting another producer's choic
|
||||||
s = produce(s, 0);
|
s = produce(s, 0);
|
||||||
assert.equal(E.canUndo(s, 1), false);
|
assert.equal(E.canUndo(s, 1), false);
|
||||||
assert.equal(E.canEditProduction(s, 1), true);
|
assert.equal(E.canEditProduction(s, 1), true);
|
||||||
|
assert.equal(E.stripSecret(s, 1).canEditProduction, true);
|
||||||
const frames = E.logSlice(s, { player: 1 }).frames;
|
const frames = E.logSlice(s, { player: 1 }).frames;
|
||||||
assert.equal(frames.at(-1).canEditProduction, true);
|
assert.equal(frames.at(-1).canEditProduction, true);
|
||||||
for (let i = 0; i < frames.length; i++)
|
for (let i = 0; i < frames.length; i++)
|
||||||
assert.deepEqual(frames[i], E.stripSecret(E.replay(s, { to: i + 1 }), 1));
|
assert.deepEqual(
|
||||||
|
frames[i],
|
||||||
|
historicalView(E.replay(s, { to: i + 1 }), 1, i === frames.length - 1),
|
||||||
|
);
|
||||||
const edited = E.move(s, { type: "editProduction" }, 1);
|
const edited = E.move(s, { type: "editProduction" }, 1);
|
||||||
assert.deepEqual(edited.players[0], s.players[0]);
|
assert.deepEqual(edited.players[0], s.players[0]);
|
||||||
assert.deepEqual(edited.players[1], start.players[1]);
|
assert.deepEqual(edited.players[1], start.players[1]);
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,17 @@ import test from "node:test";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { inspectEngine } from "@boardgamers/protocol/engine";
|
import { inspectEngine } from "@boardgamers/protocol/engine";
|
||||||
import * as E from "../engine/index.js";
|
import * as E from "../engine/index.js";
|
||||||
|
|
||||||
|
// Only the current frame carries edit affordances; older views are read-only.
|
||||||
|
function historicalView(state, player, current = false) {
|
||||||
|
const view = E.stripSecret(state, player);
|
||||||
|
if (!current) {
|
||||||
|
view.canEditPlacement = false;
|
||||||
|
view.canEditProduction = false;
|
||||||
|
}
|
||||||
|
return view;
|
||||||
|
}
|
||||||
|
|
||||||
import * as host from "../bgs/engine.js";
|
import * as host from "../bgs/engine.js";
|
||||||
import { tokenSources } from "../viewer/score.js";
|
import { tokenSources } from "../viewer/score.js";
|
||||||
|
|
||||||
|
|
@ -33,7 +44,7 @@ test("BGS required engine methods and history boundaries conform to the protocol
|
||||||
for (let i = 0; i < frames.length; i++)
|
for (let i = 0; i < frames.length; i++)
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
frames[i],
|
frames[i],
|
||||||
host.stripSecret(host.replay(s, { to: count - 2 + i }), 0),
|
historicalView(host.replay(s, { to: count - 2 + i }), 0, i === 2),
|
||||||
);
|
);
|
||||||
assert.deepEqual(host.replay(s), s);
|
assert.deepEqual(host.replay(s), s);
|
||||||
assert.deepEqual(host.logSlice(s, { start: count, end: count }).frames, []);
|
assert.deepEqual(host.logSlice(s, { start: count, end: count }).frames, []);
|
||||||
|
|
@ -49,14 +60,22 @@ test("BGS context passed to stripSecret does not become a replay checkpoint", ()
|
||||||
assert.equal(host.canUndo(s, 0), true);
|
assert.equal(host.canUndo(s, 0), true);
|
||||||
const context = { now: Date.now(), gameId: "protocol-check" };
|
const context = { now: Date.now(), gameId: "protocol-check" };
|
||||||
assert.deepEqual(host.stripSecret(s, 0, context), host.stripSecret(s, 0));
|
assert.deepEqual(host.stripSecret(s, 0, context), host.stripSecret(s, 0));
|
||||||
assert.equal(host.stripSecret(s, 0, context).canUndo, true);
|
assert.equal("canUndo" in host.stripSecret(s, 0, context), false);
|
||||||
|
// This role would previously replay its predecessor for canUndo. Stripping
|
||||||
|
// the view must work even when reconstruction is deliberately unavailable.
|
||||||
|
assert.doesNotThrow(() =>
|
||||||
|
host.stripSecret({ ...s, config: null }, 0, context),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("historical views keep private state out of player and spectator payloads", () => {
|
test("historical views keep private state out of player and spectator payloads", () => {
|
||||||
const s = host.init(3, [], {}, "protocol-privacy");
|
const s = host.init(3, [], {}, "protocol-privacy");
|
||||||
for (const player of [undefined, 0, 1]) {
|
for (const player of [undefined, 0, 1]) {
|
||||||
const view = host.logSlice(s, { player, start: host.logLength(s) - 1 })
|
const view = host.logSlice(s, {
|
||||||
.frames[0];
|
player,
|
||||||
|
start: host.logLength(s) - 1,
|
||||||
|
end: host.logLength(s) - 1,
|
||||||
|
}).frames[0];
|
||||||
for (const field of ["history", "config", "random", "bag", "discard"])
|
for (const field of ["history", "config", "random", "bag", "discard"])
|
||||||
assert.equal(view[field], undefined);
|
assert.equal(view[field], undefined);
|
||||||
view.players.forEach((p, seat) => {
|
view.players.forEach((p, seat) => {
|
||||||
|
|
@ -128,28 +147,32 @@ test("long pass sequences keep the journal bounded without losing deterministic
|
||||||
assert.deepEqual(E.replay(s, { to: 1 }), initial);
|
assert.deepEqual(E.replay(s, { to: 1 }), initial);
|
||||||
const before = structuredClone(s);
|
const before = structuredClone(s);
|
||||||
// Long BGS log requests must retain all historical frames even though the
|
// Long BGS log requests must retain all historical frames even though the
|
||||||
// visible journal is capped. Compare the reused predecessor against replay.
|
// visible journal is capped. Compare each display frame against replay.
|
||||||
const frames = E.logSlice(s, { player: 0 }).frames;
|
const frames = E.logSlice(s, { player: 0 }).frames;
|
||||||
assert.equal(frames.length, 451);
|
assert.equal(frames.length, 451);
|
||||||
for (const i of [0, 1, 50, 199, 200, 300, 400, 449, 450])
|
for (const i of [0, 1, 50, 199, 200, 300, 400, 449, 450])
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
frames[i],
|
frames[i],
|
||||||
E.stripSecret(E.replay(s, { to: i + 1 }), 0),
|
historicalView(E.replay(s, { to: i + 1 }), 0, i === 450),
|
||||||
`frame ${i}`,
|
`frame ${i}`,
|
||||||
);
|
);
|
||||||
assert.deepEqual(E.logSlice(s, { player: 0, start: 450, end: 450 }).frames, [
|
assert.deepEqual(E.logSlice(s, { player: 0, start: 450, end: 450 }).frames, [
|
||||||
frames[450],
|
frames[450],
|
||||||
]);
|
]);
|
||||||
assert.deepEqual(E.logSlice(s, { start: 450 }).frames, [E.stripSecret(s)]);
|
assert.deepEqual(E.logSlice(s, { start: 450 }).frames, [E.stripSecret(s)]);
|
||||||
// A late slice must include an exact first frame (including undo), not just
|
// A late slice must include an exact first frame (including privacy), not just
|
||||||
// exact later frames. Seat 2 exercises the first-frame predecessor path.
|
// exact later frames. Include every player and spectators.
|
||||||
for (const player of [undefined, 0, 1, 2]) {
|
for (const player of [undefined, 0, 1, 2]) {
|
||||||
for (const start of [448, 449]) {
|
for (const start of [448, 449]) {
|
||||||
const late = E.logSlice(s, { player, start, end: 450 }).frames;
|
const late = E.logSlice(s, { player, start, end: 450 }).frames;
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
late,
|
late,
|
||||||
Array.from({ length: 451 - start }, (_, offset) =>
|
Array.from({ length: 451 - start }, (_, offset) =>
|
||||||
E.stripSecret(E.replay(s, { to: start + offset + 1 }), player),
|
historicalView(
|
||||||
|
E.replay(s, { to: start + offset + 1 }),
|
||||||
|
player,
|
||||||
|
start + offset === 450,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -201,3 +224,86 @@ test("host settings changes never resolve virtual opponents or advance a replay
|
||||||
assert.deepEqual(next, expected);
|
assert.deepEqual(next, expected);
|
||||||
assert.deepEqual(s, before);
|
assert.deepEqual(s, before);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("BGS live slices preserve indices without replay, cloning, or private payloads", () => {
|
||||||
|
// Access traps prove that even full live history does not inspect positions
|
||||||
|
// or raw moves. Private choices must never enter the notification payload.
|
||||||
|
const s = { history: new Array(4) };
|
||||||
|
for (const key of ["config", "players", "random", "bag", "tasks"])
|
||||||
|
Object.defineProperty(s, key, {
|
||||||
|
get() {
|
||||||
|
throw Error(`read ${key}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
for (let i = 0; i < 4; i++)
|
||||||
|
Object.defineProperty(s.history, i, {
|
||||||
|
get() {
|
||||||
|
throw Error("read private move");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const originalClone = globalThis.structuredClone;
|
||||||
|
globalThis.structuredClone = () => {
|
||||||
|
throw Error("cloned live state");
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const expected = Array.from({ length: 5 }, (_, index) => ({
|
||||||
|
index,
|
||||||
|
simple: index ? `Move ${index}` : "Game started",
|
||||||
|
}));
|
||||||
|
assert.deepEqual(host.logSlice(s), { log: expected, frames: [] });
|
||||||
|
for (const start of [0, 1, 3, 4, 5, 10])
|
||||||
|
assert.deepEqual(host.logSlice(s, { start, player: 0 }, { now: 1 }), {
|
||||||
|
log: expected.slice(start),
|
||||||
|
frames: [],
|
||||||
|
});
|
||||||
|
for (const start of [-1, 0.5, NaN, Infinity, "0", null, 2 ** 53])
|
||||||
|
assert.throws(() => host.logSlice(s, { start }), {
|
||||||
|
name: "InvalidMoveError",
|
||||||
|
message: "Invalid replay range",
|
||||||
|
});
|
||||||
|
for (const end of [-1, 0.5, NaN, Infinity, "0", null, 2 ** 53])
|
||||||
|
assert.throws(() => host.logSlice(s, { end }), {
|
||||||
|
name: "InvalidMoveError",
|
||||||
|
});
|
||||||
|
assert.deepEqual(host.logSlice(s, { start: 5, end: 4 }), { frames: [] });
|
||||||
|
assert.throws(() => host.logSlice(s, { start: 0, end: 0 }), /read config/);
|
||||||
|
} finally {
|
||||||
|
globalThis.structuredClone = originalClone;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("BGS analysis supplies explicit historical frames rather than live notifications", () => {
|
||||||
|
let s = host.init(3, [], {}, "analysis-view-log");
|
||||||
|
for (let i = 0; i < 8; i++) s = host.moveAI(s);
|
||||||
|
const before = structuredClone(s);
|
||||||
|
for (const player of [undefined, 0, 1]) {
|
||||||
|
const view = host.analysisView(s, { player }, { now: 1 });
|
||||||
|
assert.deepEqual(view.state, host.stripSecret(s, player));
|
||||||
|
assert.equal(view.log.frames.length, host.logLength(s));
|
||||||
|
assert.deepEqual(
|
||||||
|
view.log,
|
||||||
|
host.logSlice(s, { player, start: 0, end: host.logLength(s) - 1 }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert.deepEqual(s, before);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("current placement views retain edit eligibility while older frames are read-only", () => {
|
||||||
|
let s = E.init(3, [], {}, "placement-view-edit");
|
||||||
|
s = E.move(s, { type: "role", id: "recruiter" }, 0);
|
||||||
|
s = E.move(s, { type: "recruitBonus" }, 0);
|
||||||
|
s = E.move(s, { type: "assign", ...E.autoAssignment(s, 1) }, 1);
|
||||||
|
assert.equal(E.stripSecret(s, 1).canEditPlacement, true);
|
||||||
|
const index = E.logLength(s) - 1;
|
||||||
|
s = E.move(s, { type: "assign", ...E.autoAssignment(s, 2) }, 2);
|
||||||
|
assert.equal(E.stripSecret(s, 1).canEditPlacement, true);
|
||||||
|
const old = host.logSlice(s, { player: 1, start: index, end: index })
|
||||||
|
.frames[0];
|
||||||
|
assert.equal(old.canEditPlacement, false);
|
||||||
|
assert.equal(old.canEditProduction, false);
|
||||||
|
assert.equal("canUndo" in old, false);
|
||||||
|
assert.deepEqual(
|
||||||
|
host.logSlice(s, { player: 1, start: index + 1, end: index + 1 }).frames[0],
|
||||||
|
E.stripSecret(s, 1),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,16 @@ import test from "node:test";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import * as E from "../engine/index.js";
|
import * as E from "../engine/index.js";
|
||||||
|
|
||||||
|
// Only the current frame carries edit affordances; older views are read-only.
|
||||||
|
function historicalView(state, player, current = false) {
|
||||||
|
const view = E.stripSecret(state, player);
|
||||||
|
if (!current) {
|
||||||
|
view.canEditPlacement = false;
|
||||||
|
view.canEditProduction = false;
|
||||||
|
}
|
||||||
|
return view;
|
||||||
|
}
|
||||||
|
|
||||||
function freeze(value) {
|
function freeze(value) {
|
||||||
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
||||||
Object.values(value).forEach(freeze);
|
Object.values(value).forEach(freeze);
|
||||||
|
|
@ -23,7 +33,10 @@ test("replay and log frames own their data and preserve live metadata at every b
|
||||||
assert.deepEqual(replayed, s);
|
assert.deepEqual(replayed, s);
|
||||||
const frames = E.logSlice(s, { player: 0, start: n - 3, end: n + 5 }).frames;
|
const frames = E.logSlice(s, { player: 0, start: n - 3, end: n + 5 }).frames;
|
||||||
for (let i = 0; i < 3; i++) {
|
for (let i = 0; i < 3; i++) {
|
||||||
assert.deepEqual(frames[i], E.stripSecret(E.replay(s, n - 2 + i), 0));
|
assert.deepEqual(
|
||||||
|
frames[i],
|
||||||
|
historicalView(E.replay(s, n - 2 + i), 0, i === 2),
|
||||||
|
);
|
||||||
assert.equal(frames[i].players[0].name, "Renamed");
|
assert.equal(frames[i].players[0].name, "Renamed");
|
||||||
assert.equal(frames[i].players[1].bot, true);
|
assert.equal(frames[i].players[1].bot, true);
|
||||||
assert.deepEqual(frames[i].players[2].settings, s.players[2].settings);
|
assert.deepEqual(frames[i].players[2].settings, s.players[2].settings);
|
||||||
|
|
|
||||||
|
|
@ -165,3 +165,37 @@ test("duplicate recruitment snapshots cannot release a pending move", async () =
|
||||||
await next;
|
await next;
|
||||||
viewer.destroy();
|
viewer.destroy();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("analysis full-history responses render the requested frame, not frame zero", () => {
|
||||||
|
const { viewer, calls } = fixture();
|
||||||
|
viewer.onState({ historyLength: 5 });
|
||||||
|
viewer.onReplayStart();
|
||||||
|
viewer.onReplayTo(4);
|
||||||
|
const frames = Array.from({ length: 5 }, (_, i) => ({
|
||||||
|
historyLength: i + 1,
|
||||||
|
}));
|
||||||
|
viewer.onLog({ start: 0, data: { frames } });
|
||||||
|
assert.deepEqual(calls.at(-1), ["render", frames[3]]);
|
||||||
|
viewer.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("lightweight live notifications fetch state without settling pending submissions", async () => {
|
||||||
|
const { viewer, calls } = fixture();
|
||||||
|
viewer.onPlayer({ index: 0 });
|
||||||
|
viewer.onState({ historyLength: 2, tasks: [{ kind: "role", p: 0 }] });
|
||||||
|
let done = false;
|
||||||
|
const request = viewer.move({ type: "role", id: "builder" }).then(() => {
|
||||||
|
done = true;
|
||||||
|
});
|
||||||
|
viewer.onLog({
|
||||||
|
start: 2,
|
||||||
|
data: { log: [{ index: 2, simple: "Move 2" }], frames: [] },
|
||||||
|
});
|
||||||
|
assert.deepEqual(calls.at(-1), ["fetchState", undefined]);
|
||||||
|
await Promise.resolve();
|
||||||
|
assert.equal(done, false);
|
||||||
|
viewer.onState({ historyLength: 3, tasks: [{ kind: "build", p: 0 }] });
|
||||||
|
await request;
|
||||||
|
assert.equal(done, true);
|
||||||
|
viewer.destroy();
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -115,9 +115,11 @@ export function viewerLifecycle(ctx, ui, chat) {
|
||||||
if (live) ui.render(live);
|
if (live) ui.render(live);
|
||||||
},
|
},
|
||||||
onLog(log) {
|
onLog(log) {
|
||||||
// Late responses for a previous seek must not replace the current frame.
|
// Analysis returns full history from zero, while live replay requests
|
||||||
if (replaying && log.start === position - 1 && log.data?.frames?.[0])
|
// return a slice. Only render a response containing the requested index;
|
||||||
ui.render(log.data.frames[0]);
|
// late responses for a different seek must not replace the current frame.
|
||||||
|
const frame = log.data?.frames?.[position - 1 - log.start];
|
||||||
|
if (replaying && frame) ui.render(frame);
|
||||||
else if (!replaying) ctx.fetchState();
|
else if (!replaying) ctx.fetchState();
|
||||||
},
|
},
|
||||||
destroy() {
|
destroy() {
|
||||||
|
|
|
||||||
21
viewer/ui.js
21
viewer/ui.js
|
|
@ -254,7 +254,7 @@ export function mountGame(
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(" · ");
|
.join(" · ");
|
||||||
const bonus = rewardPreview(m);
|
const bonus = rewardPreview(m);
|
||||||
return `<button type="button" class="move ${classes}" data-move="${encode(m)}" ${hint ? `title="${esc(hint)}" ${description ? `aria-label="${esc(hint)}"` : ""}` : ""} ${allowed() || (enabled && !pending && (m.type === "bohio" || (m.type === "undo" && state.canUndo) || (m.type === "editPlacement" && state.canEditPlacement) || (m.type === "editProduction" && state.canEditProduction))) ? "" : "disabled"}>${pictogram ? icon(pictogram, 26) : ""}<span>${label}${bonus}</span></button>`;
|
return `<button type="button" class="move ${classes}" data-move="${encode(m)}" ${hint ? `title="${esc(hint)}" ${description ? `aria-label="${esc(hint)}"` : ""}` : ""} ${allowed() || (enabled && !pending && (m.type === "bohio" || (m.type === "editPlacement" && state.canEditPlacement) || (m.type === "editProduction" && state.canEditProduction))) ? "" : "disabled"}>${pictogram ? icon(pictogram, 26) : ""}<span>${label}${bonus}</span></button>`;
|
||||||
};
|
};
|
||||||
function rewardPreview(move) {
|
function rewardPreview(move) {
|
||||||
const festival = festivalRewards(state, seat, move);
|
const festival = festivalRewards(state, seat, move);
|
||||||
|
|
@ -988,12 +988,6 @@ export function mountGame(
|
||||||
"quiet dock-order",
|
"quiet dock-order",
|
||||||
)
|
)
|
||||||
: "";
|
: "";
|
||||||
// Live hosted games only reopen eligible independent choices. Keep the
|
|
||||||
// legacy undo affordance for local play and analysis, not live role rewind.
|
|
||||||
const undo =
|
|
||||||
(localControls || preferences.analysis) && state.canUndo && enabled
|
|
||||||
? moveButton({ type: "undo" }, t("undo"), "undo", "quiet dock-undo")
|
|
||||||
: "";
|
|
||||||
const edit =
|
const edit =
|
||||||
enabled && state.canEditPlacement
|
enabled && state.canEditPlacement
|
||||||
? moveButton(
|
? moveButton(
|
||||||
|
|
@ -1013,14 +1007,7 @@ export function mountGame(
|
||||||
)
|
)
|
||||||
: "";
|
: "";
|
||||||
const controls =
|
const controls =
|
||||||
special +
|
special + edit + editProduction + choices + confirm + passControl + order;
|
||||||
undo +
|
|
||||||
edit +
|
|
||||||
editProduction +
|
|
||||||
choices +
|
|
||||||
confirm +
|
|
||||||
passControl +
|
|
||||||
order;
|
|
||||||
const compact = (controls.match(/<button\b/g)?.length ?? 0) <= 1;
|
const compact = (controls.match(/<button\b/g)?.length ?? 0) <= 1;
|
||||||
return `<div class="action-dock${compact ? " action-dock-compact" : ""}"><div class="dock-prompt" aria-live="polite">${icon(task?.kind === "role" ? "governor" : (state.role ?? "building"), 26)}<strong>${title()}</strong></div><div class="dock-controls">${controls}</div></div>`;
|
return `<div class="action-dock${compact ? " action-dock-compact" : ""}"><div class="dock-prompt" aria-live="polite">${icon(task?.kind === "role" ? "governor" : (state.role ?? "building"), 26)}<strong>${title()}</strong></div><div class="dock-controls">${controls}</div></div>`;
|
||||||
}
|
}
|
||||||
|
|
@ -1388,8 +1375,7 @@ export function mountGame(
|
||||||
!(
|
!(
|
||||||
enabled &&
|
enabled &&
|
||||||
!pending &&
|
!pending &&
|
||||||
((m.type === "undo" && state.canUndo) ||
|
((m.type === "editPlacement" && state.canEditPlacement) ||
|
||||||
(m.type === "editPlacement" && state.canEditPlacement) ||
|
|
||||||
(m.type === "editProduction" && state.canEditProduction) ||
|
(m.type === "editProduction" && state.canEditProduction) ||
|
||||||
(m.type === "bohio" &&
|
(m.type === "bohio" &&
|
||||||
state.legal.some((x) => JSON.stringify(x) === JSON.stringify(m))))
|
state.legal.some((x) => JSON.stringify(x) === JSON.stringify(m))))
|
||||||
|
|
@ -1537,7 +1523,6 @@ export function mountGame(
|
||||||
el.dataset.move &&
|
el.dataset.move &&
|
||||||
[
|
[
|
||||||
"bohio",
|
"bohio",
|
||||||
...(state.canUndo ? ["undo"] : []),
|
|
||||||
...(state.canEditPlacement ? ["editPlacement"] : []),
|
...(state.canEditPlacement ? ["editPlacement"] : []),
|
||||||
...(state.canEditProduction ? ["editProduction"] : []),
|
...(state.canEditProduction ? ["editProduction"] : []),
|
||||||
].includes(JSON.parse(decodeURIComponent(el.dataset.move)).type)
|
].includes(JSON.parse(decodeURIComponent(el.dataset.move)).type)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue