Support saved analyses and translated chat

This commit is contained in:
coyotte508 2026-09-21 20:32:49 +02:00
commit f89f7fb206
10 changed files with 230 additions and 11 deletions

View file

@ -999,3 +999,17 @@ export function moveAI(data, player) {
}
return state;
}
export function replay(data, { to = data.history.length } = {}) {
requireThat(
Number.isInteger(to) && to >= 0 && to <= data.history.length,
"Invalid history position.",
);
let state = init(data.players.length, [], {}, data._seed);
state.players.forEach((player, seat) => {
player.name = data.players[seat].name;
});
for (const entry of data.history.slice(0, to))
state = applyMove(state, entry.move, entry.player);
return state;
}

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/primordial-soup",
"version": "0.1.1",
"version": "0.1.2",
"private": true,
"type": "module",
"main": "dist/engine.js",
@ -10,14 +10,16 @@
"scripts": {
"build": "node scripts/build.mjs",
"test": "node --test test/*.test.js",
"dev": "node scripts/dev.mjs"
"dev": "node scripts/dev.mjs",
"test:browser": "pnpm build && node test/analysis-chat-browser.mjs"
},
"dependencies": {
"@boardgamers/protocol": "0.3.3",
"@boardgamers/protocol": "0.4.0",
"@noble/hashes": "2.0.1"
},
"devDependencies": {
"esbuild": "0.25.12",
"playwright": "1.62.1",
"prettier": "3.6.2"
},
"repository": {

39
pnpm-lock.yaml generated
View file

@ -9,8 +9,8 @@ importers:
.:
dependencies:
'@boardgamers/protocol':
specifier: 0.3.3
version: 0.3.3
specifier: 0.4.0
version: 0.4.0
'@noble/hashes':
specifier: 2.0.1
version: 2.0.1
@ -18,14 +18,17 @@ importers:
esbuild:
specifier: 0.25.12
version: 0.25.12
playwright:
specifier: 1.62.1
version: 1.62.1
prettier:
specifier: 3.6.2
version: 3.6.2
packages:
'@boardgamers/protocol@0.3.3':
resolution: {integrity: sha512-AS+x84WHXRudW6xt/s/5I3xYmNTQFbZEBp3V+41w0I2RirSr2fWjYnYf0p11nwTbZ6G5upivKz/sjYLtk8HOYA==}
'@boardgamers/protocol@0.4.0':
resolution: {integrity: sha512-dqrU94QGPZAh7vWhHmu2AHY6bFo7NbNVytb3dyUidou8R6P0FfT3xm0qLR8LbrE4EHEYmm99LajdfTfKmgwEzQ==}
'@esbuild/aix-ppc64@0.25.12':
resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==}
@ -192,6 +195,21 @@ packages:
engines: {node: '>=18'}
hasBin: true
fsevents@2.3.2:
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
playwright-core@1.62.1:
resolution: {integrity: sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==}
engines: {node: '>=20'}
hasBin: true
playwright@1.62.1:
resolution: {integrity: sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==}
engines: {node: '>=20'}
hasBin: true
prettier@3.6.2:
resolution: {integrity: sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==}
engines: {node: '>=14'}
@ -202,7 +220,7 @@ packages:
snapshots:
'@boardgamers/protocol@0.3.3':
'@boardgamers/protocol@0.4.0':
dependencies:
zod: 4.6.5
@ -315,6 +333,17 @@ snapshots:
'@esbuild/win32-ia32': 0.25.12
'@esbuild/win32-x64': 0.25.12
fsevents@2.3.2:
optional: true
playwright-core@1.62.1: {}
playwright@1.62.1:
dependencies:
playwright-core: 1.62.1
optionalDependencies:
fsevents: 2.3.2
prettier@3.6.2: {}
zod@4.6.5: {}

View file

@ -1,2 +1,5 @@
allowBuilds:
esbuild: true
minimumReleaseAgeExclude:
- "@boardgamers/protocol@0.4.0"

View file

@ -0,0 +1,115 @@
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { fileURLToPath } from "node:url";
const browser = await chromium.launch({
executablePath: process.env.CHROMIUM_EXECUTABLE,
});
const root = fileURLToPath(new URL("../", import.meta.url));
try {
for (const game of ["soup"]) {
const engine = await import(
game === "fuji"
? root + "/packages/engine/dist/wrapper.js"
: root + "/engine/index.js"
);
const state = engine.stripSecret(
await engine.init(3, [], {}, "analysis-chat-browser"),
0,
);
for (const width of [390, 1400]) {
const page = await browser.newPage({ viewport: { width, height: 950 } });
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.setContent(
'<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"></head><body><div id="app"></div></body></html>',
);
const prefix =
game === "fuji"
? root + "/packages/viewer/dist/fuji-viewer"
: root + "/dist/viewer";
await page.addStyleTag({ path: prefix + ".css" });
await page.addScriptTag({
path: prefix + (game === "fuji" ? ".iife.js" : ".js"),
});
await page.evaluate(
({ state, game }) => {
window.e = (game === "fuji" ? fuji : primordialSoup).launch("#app");
window.requests = [];
e.on("chat:translate", (request) => {
requests.push(request);
e.emit("chat:translation", {
...request,
ok: true,
text: "Bonjour <img src=x>",
language: "en",
});
});
e.emit("preferences", { sound: false });
e.emit("player", { index: 0 });
e.emit("state", state);
e.emit("chat:state", { canSend: true, translationTarget: "fr" });
e.emit("chat:messages", [
{
_id: "000000000000000000000070",
type: "text",
text: "Hello",
language: "en",
author: "Ada",
playerIndex: 1,
},
]);
},
{ state, game },
);
await page.locator(".chat-translate").click();
await page
.getByRole("button", {
name: "Translated · Show original",
exact: true,
})
.waitFor();
assert.equal(
await page
.locator('[data-message-id="000000000000000000000070"] img')
.count(),
0,
);
assert.match(
await page
.locator('[data-message-id="000000000000000000000070"]')
.textContent(),
/Bonjour <img src=x>/,
);
await page.locator(".chat-translate").click();
assert.match(
await page
.locator('[data-message-id="000000000000000000000070"]')
.textContent(),
/Hello/,
);
assert.equal(await page.evaluate(() => requests.length), 1);
await page.evaluate(() =>
e.emit("preferences", { sound: false, analysis: true }),
);
await page.waitForFunction(
() =>
!document.querySelector(".chat-translate")?.getBoundingClientRect()
.height,
);
assert.equal(
await page.getByRole("button", { name: /^Chat/ }).count(),
0,
);
assert.equal(await page.getByRole("tab", { name: /^Chat/ }).count(), 0);
await page.screenshot({
path: `/tmp/${game}-analysis-${width}.png`,
fullPage: true,
});
assert.deepEqual(errors, []);
console.log(`${game} ${width}: translation/original/analysis passed`);
await page.close();
}
}
} finally {
await browser.close();
}

View file

@ -384,3 +384,25 @@ test("a bot completes its colony turn but yields to an opponent's Holding decisi
assert.equal(s.tasks[0].kind, "follow");
assert.equal(s.history.length, 1);
});
test("replay restores a playable analysis boundary without running dropped-player bots", () => {
let state = E.init(3, [], {}, "analysis-replay");
state.players[0].name = "Alice";
const snapshots = [structuredClone(state)];
for (let i = 0; i < 80 && !state.finished; i++) {
state = E.move(state, E.legalMoves(state)[0], E.currentPlayer(state));
snapshots.push(structuredClone(state));
}
const original = structuredClone(state);
for (const to of [0, 5, 20, state.history.length]) {
const copy = E.replay(state, { to });
assert.deepEqual(copy, snapshots[to]);
assert.equal(E.logLength(copy), to);
if (!copy.finished)
assert.ok(
E.move(copy, E.legalMoves(copy)[0], E.currentPlayer(copy)).history
.length > to,
);
}
assert.deepEqual(state, original);
});

View file

@ -26,6 +26,7 @@ export function mountActivity(target, { chat, openPlayer, backToBoard } = {}) {
const journal = journalPanel.querySelector("ol");
const count = section.querySelector(".chat-count");
let active = chat ? "chat" : "journal";
let analysis = false;
let players = [];
let identity = "";
let journalKey;
@ -81,7 +82,7 @@ export function mountActivity(target, { chat, openPlayer, backToBoard } = {}) {
});
}
function select(kind) {
active = kind === "chat" && chat ? "chat" : "journal";
active = kind === "chat" && chat && !analysis ? "chat" : "journal";
for (const tab of tabs) {
tab.setAttribute("aria-selected", String(tab.dataset.tab === active));
tab.tabIndex = tab.dataset.tab === active ? 0 : -1;
@ -137,7 +138,7 @@ export function mountActivity(target, { chat, openPlayer, backToBoard } = {}) {
count.hidden = !unread;
count.textContent = unread;
count.setAttribute("aria-label", `${unread} unread messages`);
shortcut.hidden = !unread;
shortcut.hidden = analysis || !unread;
shortcut.innerHTML = `${icon("chat")} Chat <span>${unread}</span>`;
shortcut.setAttribute(
"aria-label",
@ -147,6 +148,12 @@ export function mountActivity(target, { chat, openPlayer, backToBoard } = {}) {
select(active);
return {
open,
setAnalysisMode(value) {
analysis = value;
tabs.find((tab) => tab.dataset.tab === "chat").hidden = analysis || !chat;
select(analysis ? "journal" : active);
shortcut.hidden = analysis || !chat?.unread;
},
update(state) {
players = state.players;
const nextIdentity = JSON.stringify(

View file

@ -74,6 +74,9 @@ registerViewer(
});
return {
chat,
onPreferences(preferences) {
ui.setAnalysisMode(preferences.analysis === true);
},
onPlayer(player) {
ui.setPlayer(player.index);
},

View file

@ -977,3 +977,18 @@
.action.primary .resource-amount {
color: inherit;
}
.soup-activity .chat-translate {
min-height: 24px;
padding: 2px 4px;
margin-left: 6px;
border: 0;
background: transparent;
color: inherit;
font-size: 0.8em;
text-decoration: underline;
}
.pond-tools [hidden] {
display: none;
}

View file

@ -183,7 +183,11 @@ export function mountGame(
openPlayer: onOpenPlayer,
backToBoard() {
$(".play-area").scrollIntoView({ block: "start" });
$(chat ? '[data-ui="chat"]' : '[data-ui="journal"]').focus({
$(
chat && !$('[data-ui="chat"]').hidden
? '[data-ui="chat"]'
: '[data-ui="journal"]',
).focus({
preventScroll: true,
});
},
@ -442,6 +446,11 @@ export function mountGame(
state = viewerState(s);
render();
},
setAnalysisMode(analysis) {
const button = $('[data-ui="chat"]');
if (button) button.hidden = analysis;
activity.setAnalysisMode(analysis);
},
setPlayer(p) {
seat = p;
viewPlayer = p;