Fix influence sources and optimistic Undo; surface Great Architect

This commit is contained in:
coyotte508 2026-10-11 22:39:13 +02:00
commit dd23158535
15 changed files with 480 additions and 89 deletions

View file

@ -172,7 +172,7 @@ impl City {
#[must_use]
pub fn influenced(&self) -> bool {
self.uninfluenced_buildings() as usize != self.pieces.amount()
self.uninfluenced_buildings() as usize != self.pieces.buildings(None).len()
}
}

View file

@ -52,8 +52,9 @@ fn separation_of_power() -> AdvanceBuilder {
.add_transient_event_listener(
|event| &mut event.on_influence_culture_attempt,
2,
|r, city, _, _| {
|r, city, _, p| {
if let Ok(info) = r
&& info.is_defender(p.index)
&& matches!(city.mood_state, MoodState::Happy)
{
info.set_no_boost();

View file

@ -646,23 +646,28 @@ fn affordable_start_position(
let player = game.player(player_index);
let available = &player.resources;
let mut tokens = available.culture_tokens;
let mut action_cost = ResourcePile::empty();
if add_action_cost {
// either none (action cost and boost cost) or both can use Colosseum
action_cost = action_type.payment_options(game, player_index).default;
let c = action_cost.culture_tokens;
if c > 0 {
tokens -= c;
}
}
if player.wonders_owned.contains(Wonder::Colosseum) {
tokens += available.mood_tokens;
let m = action_cost.mood_tokens;
if m > 0 {
tokens -= m;
}
}
let arena = player.wonders_owned.contains(Wonder::Colosseum);
let tokens = u16::from(available.culture_tokens)
+ if arena {
u16::from(available.mood_tokens)
} else {
0
};
// Include interchangeable mood before reserving the action fee.
let action_cost = if add_action_cost {
action_type.payment_options(game, player_index).default
} else {
ResourcePile::empty()
};
let fee = u16::from(action_cost.culture_tokens)
+ if arena {
u16::from(action_cost.mood_tokens)
} else {
0
};
let tokens = tokens
.checked_sub(fee)
.ok_or("Cannot afford influence action")?;
let start = influence_start_positions(game, player);
start
@ -673,14 +678,14 @@ fn affordable_start_position(
.distance(target_city.position)
.saturating_sub(size as u32) as u8;
if min_cost > tokens {
if u16::from(min_cost) > tokens {
// avoid unnecessary calculations
return None;
}
let distance = influence_distance(game, position, target_city.position);
let boost_cost = distance.saturating_sub(size as u8);
if boost_cost > tokens {
if u16::from(boost_cost) > tokens {
return None;
}
Some((position, boost_cost))

View file

@ -829,3 +829,100 @@ fn steel_weapons_explains_missing_and_declined_payments() {
assert!(!log.contains("steel weapons added"));
}
}
#[test]
fn separation_of_power_only_protects_its_owners_happy_cities() {
use server::cache::Cache;
use server::cultural_influence::influence_culture_boost_cost;
use server::game::GameContext;
use server::game_data::GameData;
for owner in [0, 1] {
for happy in [false, true] {
let mut data = serde_json::to_value(load_culture().cloned_data()).unwrap();
data["players"][owner]["advances"]
.as_array_mut()
.unwrap()
.push(serde_json::json!("SeparationOfPower"));
data["players"][0]["cities"][2]["mood_state"] =
serde_json::json!(if happy { "Happy" } else { "Neutral" });
let data: GameData = serde_json::from_value(data).unwrap();
let cache = Cache::new(&data.options);
let game = Game::from_data(data, cache, GameContext::Play);
let result = influence_culture_boost_cost(
&game,
1,
&SelectedStructure::new(Position::from_offset("C2"), Structure::Building(Temple)),
&PlayingActionType::InfluenceCultureAttempt,
true,
false,
0,
);
assert_eq!(
result.is_err(),
owner == 0 && happy,
"owner={owner}, happy={happy}"
);
}
}
}
#[test]
fn proselytism_counts_settlers_in_a_wonder_city() {
use server::cache::Cache;
use server::cultural_influence::influence_culture_boost_cost_from;
use server::game::GameContext;
use server::game_data::GameData;
let mut data = serde_json::to_value(load_culture().cloned_data()).unwrap();
data["players"][1]["civilization"] = serde_json::json!("India");
data["players"][1]["advances"]
.as_array_mut()
.unwrap()
.push(serde_json::json!("StateReligion"));
let source = data["players"][1]["cities"][0]["position"]
.as_str()
.unwrap()
.to_owned();
data["players"][1]["cities"][0]["city_pieces"]["wonders"] =
serde_json::json!(["GreatMausoleum"]);
data["players"][1]["units"] = serde_json::json!([
{"id":100,"position":source,"unit_type":"Settler"},
{"id":101,"position":source,"unit_type":"Settler"}
]);
let data: GameData = serde_json::from_value(data).unwrap();
let cache = Cache::new(&data.options);
let mut game = Game::from_data(data, cache, GameContext::Play);
let source = Position::from_offset(&source);
assert!(!game.players[1].get_city(source).influenced());
let result = influence_culture_boost_cost_from(
&game,
1,
&SelectedStructure::new(Position::from_offset("C2"), Structure::Building(Temple)),
&PlayingActionType::InfluenceCultureAttempt,
true,
false,
0,
Some(source),
)
.unwrap();
assert!(result.range_boost_cost.default.is_empty());
game.players[1].get_city_mut(source).pieces.academy = Some(0);
assert!(
game.players[1].get_city(source).influenced(),
"An actual foreign building still blocks the source"
);
}
#[test]
fn arts_can_reserve_its_fee_from_great_arena_mood() {
use server::cultural_influence::influence_culture_boost_cost;
let mut game = execute_action(load_culture(), advance_action(Advance::Arts, ResourcePile::ideas(2)), 1);
game.players[1].wonders_owned.insert(Wonder::Colosseum);
game.players[1].resources = ResourcePile::mood_tokens(7);
let kind = PlayingActionType::Special(SpecialAction::Modifier(
PlayingActionModifier::ArtsInfluenceCultureAttempt,
));
let target = SelectedStructure::new(Position::from_offset("C2"), Structure::Building(Temple));
assert!(influence_culture_boost_cost(&game, 1, &target, &kind, true, false, 0).is_ok());
game.players[1].resources = ResourcePile::empty();
assert!(influence_culture_boost_cost(&game, 1, &target, &kind, true, false, 0).is_err());
}

View file

@ -180,3 +180,10 @@ Trade Routes reward amounts now swap directly between engine-approved combinatio
# Viewer 0.1.65 / engine unchanged (0.4.61)
Prediction and server-acknowledgement fingerprints now canonicalize nested object fields, preserving array order and all visible values. Rust map serialization order could previously make equivalent states compare unequal, intermittently forcing deterministic actions such as Theaters to wait for the backend. Regression coverage checks semantic differences and completing Theaters before either server acknowledgement. The browser smoke test can also accept a local pre-Theaters state via THEATERS_STATE; no live game moves are submitted.
# Viewer 0.1.66 / engine 0.4.62
Wonders shows a Great Architect suggestion when the player holds that card, explaining its culture discount and advance waiver while retaining Engineering. Its button uses the engine-provided card action and remains disabled with the normal reason when unavailable. Undo's retained-action comparison also uses canonical object ordering, so equivalent host serialization cannot discard a valid prior snapshot. Undo also handles historic turns with no action array, which previously threw and forced a server wait. Browser coverage exercises undoing Theaters without a server acknowledgement, and confirms Advance skips its already-quoted culture payment and opens research.
Separation of Power protects only its owner as defender. Wonders no longer make a city count as foreign-influenced, restoring those cities as cultural influence sources, including India’s Proselytism range from settlers. Influence reserves the Arts fee after including interchangeable mood from Great Arena, avoiding unsigned underflow when culture is empty.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.65",
"version": "0.1.66",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.65",
"version": "0.1.66",
"dependencies": {
"@boardgamers/protocol": "0.9.0",
"lucide-svelte": "^0.577.0",

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.65",
"version": "0.1.66",
"private": true,
"type": "module",
"scripts": {

View file

@ -0,0 +1,83 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { chromium } from 'playwright';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const npcs = JSON.parse(await engine.init(2, [], {}, 'abilities-ui', {})).players.slice(2);
async function fixture(name) {
const game = JSON.parse(
await readFile(new URL(`../../server/tests/test_games/${name}.json`, import.meta.url), 'utf8'),
);
for (const npc of npcs)
if (!game.players.some((p) => p.civilization === npc.civilization))
game.players.push({ ...npc, id: game.players.length });
return game;
}
const browser = await chromium.launch({
headless: true,
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
try {
for (const [width, height] of [
[1400, 900],
[390, 740],
]) {
for (const kind of ['architect', 'advance']) {
const state = await fixture(
kind === 'architect' ? 'incidents/great_persons/great_architect' : 'action_cards/spy',
);
const seat = 0;
state.players[0].action_cards = [kind === 'architect' ? 155 : 1];
const page = await browser.newPage({ viewport: { width, height } }),
errors = [];
page.on('pageerror', (e) => errors.push(e.message));
await page.route('**/*', async (route) => {
const path = new URL(route.request().url()).pathname;
if (path === '/')
return route.fulfill({
contentType: 'text/html',
body: '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><div id="app"></div><script src="/viewer.js"></script>',
});
if (!['/viewer.js', '/server_bg.wasm'].includes(path)) return route.abort();
return route.fulfill({
contentType: path.endsWith('.wasm') ? 'application/wasm' : 'text/javascript',
body: await readFile(new URL('../dist' + path, import.meta.url)),
});
});
await page.goto('http://clash.test');
await page.evaluate(
({ state, seat }) => {
window.host = clash3d.launch('#app');
window.sent = [];
host.on('move', (a) => sent.push(a));
host.emit('player', { index: seat });
host.emit('theme', { dark: true });
host.emit('preferences', { sound: false });
host.emit('state', state);
},
{ state: engine.stripSecret(JSON.stringify(state), seat), seat },
);
if (kind === 'architect') {
await page.getByRole('button', { name: /^Wonders:/ }).click();
await page.getByRole('button', { name: 'Use Great Architect', exact: true }).waitFor();
await page.screenshot({ path: `/tmp/clash-architect-${width}.png` });
await page.getByRole('button', { name: 'Use Great Architect', exact: true }).click();
await page.getByRole('heading', { name: 'Build Wonder', exact: true }).waitFor();
} else {
await page.getByRole('button', { name: /^Action cards:/ }).click();
await page.getByRole('button', { name: 'Play Advance', exact: true }).click();
await page.screenshot({ path: `/tmp/clash-advance-${width}.png` });
await page.getByText('Choose a highlighted advance.', { exact: true }).waitFor({state: 'attached'});
assert.equal(await page.getByText('Pay for action', { exact: true }).count(), 0);
await page.screenshot({ path: `/tmp/clash-advance-${width}.png` });
}
assert.equal(await page.evaluate(() => sent.length), 1);
assert.deepEqual(errors, []);
console.log({ width, kind, serverAcknowledgements: 0 });
await page.close();
}
}
console.log('Card desktop/mobile smoke passed');
} finally {
await browser.close();
}

View file

@ -18,35 +18,75 @@ const browser = await chromium.launch({
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
try {
for (const [width,height] of [[1400,900],[390,740]]) {
const state=process.env.THEATERS_STATE ? JSON.parse(await readFile(process.env.THEATERS_STATE,'utf8')) : await fixture('advances/sanitation_and_draft');
const seat=process.env.THEATERS_STATE ? 1 : 0;
if(!process.env.THEATERS_STATE) {state.players[0].advances.push('Arts','Theaters');state.players[0].resources.mood_tokens=2;state.players[0].resources.culture_tokens=2;}
const page=await browser.newPage({viewport:{width,height}}),errors=[];
page.on('pageerror',e=>errors.push(e.message));
await page.route('**/*',async route=>{
const path=new URL(route.request().url()).pathname;
if(path==='/') return route.fulfill({contentType:'text/html',body:'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><div id="app"></div><script src="/viewer.js"></script>'});
if(!['/viewer.js','/server_bg.wasm'].includes(path)) return route.abort();
return route.fulfill({contentType:path.endsWith('.wasm')?'application/wasm':'text/javascript',body:await readFile(new URL('../dist'+path,import.meta.url))});
});
await page.goto('http://clash.test');
await page.evaluate(({state,seat})=>{window.host=clash3d.launch('#app');window.sent=[];host.on('move',a=>sent.push(a));host.emit('player',{index:seat});host.emit('theme',{dark:true});host.emit('preferences',{sound:false});host.emit('state',state)},{state:engine.stripSecret(JSON.stringify(state),seat),seat});
await page.getByRole('button',{name:'Abilities and cultural influence',exact:true}).click();
const start=performance.now();
await page.getByRole('button',{name:/Use Theaters/}).click();
const pay=page.getByRole('button',{name:/^Pay 1 Mood/i});
await pay.waitFor();
assert.equal(await pay.isEnabled(),true);
const elapsed=performance.now()-start;
assert.equal(await page.evaluate(()=>sent.length),1);
await page.screenshot({path:`/tmp/clash-theaters-${width}.png`});
await pay.click();
await page.waitForFunction(()=>!document.querySelector('.decision-panel'));
assert.equal(await page.evaluate(()=>sent.length),1,'Conversion is queued and shown without a backend response');
assert.deepEqual(errors,[]);
console.log({width,choiceReadyMs:Math.round(elapsed),serverAcknowledgements:0});
await page.close();
}
console.log('Theaters desktop/mobile smoke passed');
} finally {await browser.close();}
for (const [width, height] of [
[1400, 900],
[390, 740],
]) {
const state = process.env.THEATERS_STATE
? JSON.parse(await readFile(process.env.THEATERS_STATE, 'utf8'))
: await fixture('advances/sanitation_and_draft');
const seat = process.env.THEATERS_STATE ? 1 : 0;
if (!process.env.THEATERS_STATE) {
state.players[0].advances.push('Arts', 'Theaters');
state.players[0].resources.mood_tokens = 2;
state.players[0].resources.culture_tokens = 2;
}
const page = await browser.newPage({ viewport: { width, height } }),
errors = [];
page.on('pageerror', (e) => errors.push(e.message));
await page.route('**/*', async (route) => {
const path = new URL(route.request().url()).pathname;
if (path === '/')
return route.fulfill({
contentType: 'text/html',
body: '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><div id="app"></div><script src="/viewer.js"></script>',
});
if (!['/viewer.js', '/server_bg.wasm'].includes(path)) return route.abort();
return route.fulfill({
contentType: path.endsWith('.wasm') ? 'application/wasm' : 'text/javascript',
body: await readFile(new URL('../dist' + path, import.meta.url)),
});
});
await page.goto('http://clash.test');
await page.evaluate(
({ state, seat }) => {
window.host = clash3d.launch('#app');
window.sent = [];
host.on('move', (a) => sent.push(a));
host.emit('player', { index: seat });
host.emit('theme', { dark: true });
host.emit('preferences', { sound: false });
host.emit('state', state);
},
{ state: engine.stripSecret(JSON.stringify(state), seat), seat },
);
await page.getByRole('button', { name: 'Abilities and cultural influence', exact: true }).click();
const start = performance.now();
await page.getByRole('button', { name: /Use Theaters/ }).click();
const pay = page.getByRole('button', { name: /^Pay 1 Mood/i });
await pay.waitFor();
assert.equal(await pay.isEnabled(), true);
const elapsed = performance.now() - start;
assert.equal(await page.evaluate(() => sent.length), 1);
await page.screenshot({ path: `/tmp/clash-theaters-${width}.png` });
await pay.click();
await page.waitForFunction(() => !document.querySelector('.decision-panel'));
assert.equal(
await page.evaluate(() => sent.length),
1,
'Conversion is queued and shown without a backend response',
);
await page.getByRole('button', { name: 'Undo last action', exact: true }).click();
await page.screenshot({ path: `/tmp/clash-undo-${width}.png` });
await pay.waitFor();
assert.equal(await pay.isEnabled(), true, 'Undo restores the choice before the backend responds');
assert.equal(await page.evaluate(() => sent.length), 1);
assert.deepEqual(errors, []);
console.log({ width, choiceReadyMs: Math.round(elapsed), serverAcknowledgements: 0 });
await page.close();
}
console.log('Theaters desktop/mobile smoke passed');
} finally {
await browser.close();
}

View file

@ -2,9 +2,12 @@
import { printedCardName } from './card-names';
import { X, Landmark, Hammer, BookOpen, Layers } from 'lucide-svelte';
import WonderCard from './WonderCard.svelte';
import ResourceText from './ResourceText.svelte';
import { actionReason } from './model';
import type { Controller } from './controller';
let { controller }: { controller: Controller } = $props();
const session = $derived(controller.session);
const architect = $derived($session.view?.actionCards?.find((card) => card.id === 155));
let tab = $state<'hand' | 'reference'>('hand');
const close = () => controller.patch({ wondersOpen: false });
function show(node: HTMLDialogElement) {
@ -49,6 +52,26 @@
Private hand · {$session.view?.wonderCards.length ?? 0}
{$session.view?.wonderCards.length === 1 ? 'card' : 'cards'}
</p>
{#if architect}
<article class="play-card architect-suggestion">
<header class="play-card-header">
<h3>{printedCardName(architect.name)}</h3>
<button
class="primary card-play-button"
disabled={!architect.action || $session.pending || !!$session.playback}
title={architect.reason ?? 'Choose a wonder to build with Great Architect'}
onclick={() => architect?.action && controller.submit(architect.action, architect.cost)}
><Hammer size={16} />Use Great Architect</button
>
</header>
<p>
<ResourceText
text="Save 3 culture tokens and ignore the wonder’s required advance. You still need Engineering."
/>
</p>
{#if actionReason(architect.reason)}<small>{actionReason(architect.reason)}</small>{/if}
</article>
{/if}
{#each $session.view?.wonderCards ?? [] as card (card.id)}
<div class="wonder-hand-entry">
<WonderCard {card} />

View file

@ -810,6 +810,34 @@ test('Free Economy pays the displayed fee once, with no second click or duplicat
}
});
test('Advance pays the quoted culture and opens research without a payment click', async () => {
const app = paymentController(),
c = app.controller;
const game = JSON.parse(fixture('action_cards/spy'));
game.players[0].action_cards = [1];
let state = JSON.stringify(game);
try {
c.setPlayer(0);
await c.load(engine.stripSecret(state, 0));
const card = app.session().view!.actionCards!.find((card) => card.id === 1)!;
c.submit(card.action!, card.cost);
assert.equal(app.session().view!.decision!.advanceSelection, true);
assert.equal(app.session().pending, false);
assert.equal(app.sent.length, 1);
state = engine.tryMove(state, app.sent[0], 0);
await c.load(engine.stripSecret(state, 0));
assert.equal(app.sent.length, 2);
assert.deepEqual(JSON.parse(app.sent[1]), { Response: { Payment: [{ culture_tokens: 1 }] } });
assert.equal(app.session().view!.decision!.advanceSelection, true);
state = engine.tryMove(state, app.sent[1], 0);
await c.load(engine.stripSecret(state, 0));
assert.equal(app.sent.length, 2);
assert.equal(app.session().view!.decision!.advanceSelection, true);
} finally {
app.close();
}
});
test('only an accepted matching quote continues payment, and a send failure restores the controls', async () => {
for (const mode of ['unquoted', 'changed', 'reconnect', 'rejected']) {
const app = paymentController(),
@ -2517,7 +2545,8 @@ test('exploration previews four tiles before a second destination click submits'
});
test('trade-route toggle is read-only and exclusive with other map guides', async () => {
const app = paymentController(), c = app.controller;
const app = paymentController(),
c = app.controller;
try {
c.setPlayer(0);
await c.load(engine.stripSecret(fixture('advances/trade_routes'), 0));
@ -2534,5 +2563,7 @@ test('trade-route toggle is read-only and exclusive with other map guides', asyn
c.showTradeRoutes(false);
assert.equal(app.session().game, game);
assert.deepEqual(app.sent, []);
} finally { app.close(); }
} finally {
app.close();
}
});

View file

@ -414,7 +414,8 @@ test('the last end-of-age free advance waits when it draws hidden cards', () =>
test('a fresh game exposes a stable public history ID and predicts its first action and Undo', async () => {
const raw = await engine.init(2, [], { civilization: 'Random' }, 'first-action-prediction', {});
const seat = engine.currentPlayer(raw);
const publicRaw = strip(raw, seat), initial = JSON.parse(publicRaw);
const publicRaw = strip(raw, seat),
initial = JSON.parse(publicRaw);
assert.ok(initial.board_history.id);
assert.deepEqual(initial.board_history.frames, []);
assert.ok(!initial.seed);
@ -422,9 +423,11 @@ test('a fresh game exposes a stable public history ID and predicts its first act
try {
app.controller.setPlayer(seat);
await app.controller.load(publicRaw);
const city = app.session().view!.cities.find(c => !c.reason && c.choices.length)!;
const city = app.session().view!.cities.find((c) => !c.reason && c.choices.length)!;
const choice = city.choices[0];
const preview = JSON.parse(engine.webCollectPreview(publicRaw, seat, city.position, JSON.stringify([{...choice, times: 1}])));
const preview = JSON.parse(
engine.webCollectPreview(publicRaw, seat, city.position, JSON.stringify([{ ...choice, times: 1 }])),
);
app.controller.submit(preview.action);
assert.equal(app.session().pending, false);
const after = move(raw, preview.action, seat);
@ -436,26 +439,37 @@ test('a fresh game exposes a stable public history ID and predicts its first act
const shown = app.session();
await app.controller.load(strip(move(after, 'Undo', seat), seat));
assert.equal(app.session(), shown);
} finally { app.close(); }
} finally {
app.close();
}
});
test('normal actions use prediction by default across construction, recruitment, happiness, research and abilities', async () => {
const g = JSON.parse(await engine.init(2, [], { civilization: 'Random' }, 'all-action-prediction', {}));
const seat = engine.currentPlayer(JSON.stringify(g)), p = g.players[seat];
const seat = engine.currentPlayer(JSON.stringify(g)),
p = g.players[seat];
p.civilization = 'Rome';
p.resources = { food: 7, wood: 7, ore: 7, ideas: 7, gold: 7, mood_tokens: 7, culture_tokens: 7 };
p.advances = ['Farming', 'Mining', 'Tactics', 'Myths', 'Fishing', 'Bartering', 'Storage', 'Taxes'];
p.incident_tokens = 3;
p.cities[0].mood_state = 'Neutral';
const empty = g.map.tiles.find(([pos, terrain]: string[]) => ['Fertile', 'Forest', 'Mountain'].includes(terrain) && !g.players.some((q: any) => (q.cities ?? []).some((c: any) => c.position === pos)));
const empty = g.map.tiles.find(
([pos, terrain]: string[]) =>
['Fertile', 'Forest', 'Mountain'].includes(terrain) &&
!g.players.some((q: any) => (q.cities ?? []).some((c: any) => c.position === pos)),
);
p.cities.push({ position: empty[0], mood_state: 'Happy' });
const raw = JSON.stringify(g), filtered = strip(raw, seat);
const raw = JSON.stringify(g),
filtered = strip(raw, seat);
const view = JSON.parse(engine.webView(filtered, seat));
const city = view.cityActions[0];
const query = (q: unknown) => JSON.parse(engine.webQuery(filtered, seat, JSON.stringify(q)));
const actions: [string, unknown][] = [
['construction', city.buildings.find((b: any) => b.name === 'Fortress').choices[0].action],
['recruitment', query({ kind: 'recruit', city: city.position, units: { infantry: 1 }, replaced: [] }).action],
[
'recruitment',
query({ kind: 'recruit', city: city.position, units: { infantry: 1 }, replaced: [] }).action,
],
['happiness', city.happiness[0].action],
['research', view.advances.find((a: any) => a.id === 'Irrigation' || a.name === 'Irrigation').action],
['ability', view.specialActions.find((a: any) => a.name === 'Taxes').action],
@ -471,8 +485,11 @@ test('normal actions use prediction by default across construction, recruitment,
test('round three End turn predicts until it actually reaches objective completion', () => {
const g = JSON.parse(fixture('advances/collect_free_economy', ore));
g.round = 3; g.current_player_index = 0; g.starting_player_index = 0;
const raw = JSON.stringify(g), end = { Playing: 'EndTurn' };
g.round = 3;
g.current_player_index = 0;
g.starting_player_index = 0;
const raw = JSON.stringify(g),
end = { Playing: 'EndTurn' };
const prediction = predictMove(engine, strip(raw), end, 0);
assert.ok('raw' in prediction);
const next = move(raw, end);
@ -485,30 +502,47 @@ test('rolls and hidden draws wait even when sampled visible outcomes could coinc
for (const change of [{ rng: '2' }, { dice_roll_log: [1] }, { action_cards_left: [2] }]) {
let executions = 0;
const simulation = {
tryMove: () => { executions++; return JSON.stringify({ ...before, ...change }); },
tryMove: () => {
executions++;
return JSON.stringify({ ...before, ...change });
},
stripSecret: () => JSON.stringify(before),
};
assert.deepEqual(predictMove(simulation, JSON.stringify(before), { Playing: 'EndTurn' }, 0), { reason: 'hidden' });
assert.deepEqual(predictMove(simulation, JSON.stringify(before), { Playing: 'EndTurn' }, 0), {
reason: 'hidden',
});
assert.equal(executions, 1);
}
});
test('Spy waits before looking at a masked hand without trapping the local engine', () => {
const game = JSON.parse(readFileSync(new URL('../../server/tests/test_games/action_cards/spy.json', import.meta.url), 'utf8'));
for (const npc of npcs) if (!game.players.some((p: any) => p.civilization === npc.civilization)) game.players.push({ ...npc, id: game.players.length });
const game = JSON.parse(
readFileSync(new URL('../../server/tests/test_games/action_cards/spy.json', import.meta.url), 'utf8'),
);
for (const npc of npcs)
if (!game.players.some((p: any) => p.civilization === npc.civilization))
game.players.push({ ...npc, id: game.players.length });
const raw = JSON.stringify(game);
const card = JSON.parse(engine.webView(strip(raw), 0)).actionCards.find((c: any) => c.id === 7);
const payment = move(raw, card.action);
assert.deepEqual(predictMove(engine, strip(payment), { Response: { Payment: [{ culture_tokens: 1 }] } }, 0), { reason: 'unsupported' });
assert.deepEqual(
predictMove(engine, strip(payment), { Response: { Payment: [{ culture_tokens: 1 }] } }, 0),
{ reason: 'unsupported' },
);
// The reveal boundary must not disable prediction for subsequent ordinary actions.
const next = fixture('advances/collect_free_economy', ore);
assert.ok('raw' in predictMove(engine, strip(next), ore, 0));
});
test('prediction fingerprints ignore nested map field order but preserve values and array order', () => {
const a = { players: [{ id: 0, resources: { food: 2, gold: 1 }, event_info: { first: 'a', second: 'b' } }], events: [{ details: { target: 'A1', amount: 1 } }] };
const b = { events: [{ details: { amount: 1, target: 'A1' } }], players: [{ event_info: { second: 'b', first: 'a' }, resources: { gold: 1, food: 2 }, id: 0 }] };
const a = {
players: [{ id: 0, resources: { food: 2, gold: 1 }, event_info: { first: 'a', second: 'b' } }],
events: [{ details: { target: 'A1', amount: 1 } }],
};
const b = {
events: [{ details: { amount: 1, target: 'A1' } }],
players: [{ event_info: { second: 'b', first: 'a' }, resources: { gold: 1, food: 2 }, id: 0 }],
};
assert.equal(fingerprint(JSON.stringify(a)), fingerprint(JSON.stringify(b)));
b.players[0].resources.food = 3;
assert.notEqual(fingerprint(JSON.stringify(a)), fingerprint(JSON.stringify(b)));
@ -522,16 +556,21 @@ test('Theaters opens its direction choice and completes locally before any serve
g.players[0].resources.culture_tokens = 2;
// Multiple nested map entries exercise hash-map iteration in engine serialization.
g.players[0].event_info = { first: 'a', second: 'b', third: 'c' };
const raw = JSON.stringify(g), app = harness();
const raw = JSON.stringify(g),
app = harness();
try {
app.controller.setPlayer(0);
await app.controller.load(strip(raw));
const theater = app.session().view!.specialActions!.find(a => a.name === 'Theaters')!;
const theater = app.session().view!.specialActions!.find((a) => a.name === 'Theaters')!;
app.controller.submit(theater.action);
assert.equal(app.sent.length, 1);
assert.equal(app.session().pending, false);
assert.equal(app.session().view!.decision?.name, 'Theaters');
const response = app.controller.query<{action: any}>({kind: 'decision', values: [], payments: [{mood_tokens: 1}]}).action;
const response = app.controller.query<{ action: any }>({
kind: 'decision',
values: [],
payments: [{ mood_tokens: 1 }],
}).action;
app.controller.submit(response);
assert.equal(app.sent.length, 1, 'Second move is queued without waiting to update the UI');
assert.equal(app.session().pending, false);
@ -542,5 +581,20 @@ test('Theaters opens its direction choice and completes locally before any serve
await app.controller.load(strip(move(first, response)));
assert.equal(app.session().pending, false);
assert.equal(app.session().game!.players[0].resources!.culture_tokens, 3);
} finally { app.close(); }
} finally {
app.close();
}
});
test('Undo counts empty historic turns as zero actions', () => {
const previous = { log_index: 1, log: [{ rounds: [{ turns: [{}, { actions: [{ action: 'a' }] }] }] }] };
const current = structuredClone(previous);
current.log_index = 2;
current.log[0].rounds[0].turns[1].actions!.push({ action: 'b' });
const board_history = { id: 'empty-turn', frames: [{ cursor: 0 }, { cursor: 1 }, { cursor: 2 }] };
const undone = JSON.parse(
predictUndo(JSON.stringify(previous), JSON.stringify({ ...current, board_history }))!,
);
assert.equal(undone.log_index, 1);
assert.deepEqual(undone.board_history.frames, [{ cursor: 0 }, { cursor: 1 }]);
});

View file

@ -28,13 +28,15 @@ export function fingerprint(raw: string): string {
delete game.rng;
delete game.seed;
delete game.messages;
// Rust maps can serialize in different insertion orders between executions.
// Canonicalize every object, including nested player/event data; array order
// still matters for actions, choices and history.
return JSON.stringify(game, (_key, value) =>
value && typeof value === 'object' && !Array.isArray(value)
? Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1)))
: value,
return canonicalJson(game);
}
/** Stable map serialization; sequence order remains significant. */
export function canonicalJson(value: unknown): string {
return JSON.stringify(value, (_key, item) =>
item && typeof item === 'object' && !Array.isArray(item)
? Object.fromEntries(Object.entries(item).sort(([a], [b]) => (a < b ? -1 : 1)))
: item,
);
}
@ -165,7 +167,10 @@ function logLength(game: Json) {
const turns = (game.log ?? []).flatMap((age: Json) => age.rounds.flatMap((round: Json) => round.turns));
return turns.reduce(
(sum: number, turn: Json, i: number) =>
sum + (i + 1 === turns.length ? Math.min(game.log_index, turn.actions.length) : turn.actions.length),
sum +
(i + 1 === turns.length
? Math.min(game.log_index, turn.actions?.length ?? 0)
: (turn.actions?.length ?? 0)),
0,
);
}

View file

@ -0,0 +1,44 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { UndoPreview } from './undo-preview.ts';
import type { Game, View } from './types.ts';
test('Undo keeps earlier snapshots when host action object fields are reordered', () => {
const cache = new UndoPreview();
const before = {
board_history: { id: 'undo-order', frames: [] },
current_player_index: 0,
age: 1,
round: 1,
log_index: 1,
log: [
{
age: 1,
rounds: [
{
round: 1,
turns: [
{
turn_type: { Player: 0 },
actions: [
{ action: { Playing: { Custom: { action: 'Theaters', payment: { food: 1, gold: 2 } } } } },
],
},
],
},
],
},
],
} as unknown as Game;
const view = { canUndo: true } as View;
cache.remember('earlier snapshot', before, view, 0);
const after = structuredClone(before);
after.log_index = 2;
const actions = after.log![0].rounds[0].turns[0].actions!;
actions[0].action = { Playing: { Custom: { payment: { gold: 2, food: 1 }, action: 'Theaters' } } };
actions.push({ action: { Response: { ResourceReward: { gold: 1 } } } });
cache.remember('later snapshot', after, view, 0);
assert.equal(cache.previous(after, view), 'earlier snapshot');
actions[0].action = { Playing: { Custom: { action: 'Sports' } } };
assert.equal(cache.previous(after, view), undefined, 'A genuinely different branch cannot reuse Undo');
});

View file

@ -1,4 +1,5 @@
import type { Game, View } from './types.ts';
import { canonicalJson } from './prediction.ts';
interface Snapshot {
game: Game;
@ -7,7 +8,7 @@ interface Snapshot {
const turn = (game: Game) => game.log?.at(-1)?.rounds.at(-1)?.turns.at(-1);
const prefix = (game: Game, count: number) =>
JSON.stringify((turn(game)?.actions ?? []).slice(0, count).map((entry) => entry.action));
canonicalJson((turn(game)?.actions ?? []).slice(0, count).map((entry) => entry.action));
/** Only retain states shown for this seat, never simulate hidden undo patches. */
export class UndoPreview {