Make Calendar previews cancellable and add research reminders

Release viewer 0.1.193 and engine 0.4.128 with bounded live Calendar previews, explicit research alternatives, matching regression coverage and localized costs.
This commit is contained in:
coyotte508 2026-11-02 20:32:52 +00:00
commit 5bccb8f811
46 changed files with 1402 additions and 39 deletions

View file

@ -76,7 +76,12 @@ pub fn try_execute_action(
player_index: usize,
) -> Result<Game, String> {
game.early_choice_update = false;
if let Action::QueueMoves { key, actions, waiting } = &action {
if let Action::QueueMoves {
key,
actions,
waiting,
} = &action
{
crate::action_queue::save(&mut game, player_index, key, actions.clone(), *waiting)?;
return Ok(game);
}
@ -84,6 +89,13 @@ pub fn try_execute_action(
crate::early_choices::save(&mut game, player_index, key, response.clone())?;
return Ok(game);
}
// A persisted transient prompt has no action/cursor to undo or deck to
// mutate yet. Even lower-level callers must resolve it at the live boundary.
// Recorded/replayed Calendar actions never carry this marker. Independent
// private queue updates above must remain available to the other seats.
if game.uncommitted_calendar {
return crate::board_history::execute(game, action, player_index);
}
if game.civilization_draft.is_some() {
crate::game_setup::execute_draft_choice(&mut game, player_index, &action)?;
return Ok(game);
@ -92,6 +104,16 @@ pub fn try_execute_action(
return Err(format!("Player {player_index} is not the active player"));
}
if let Action::Response(response) = &action
&& crate::content::civilizations::maya::is_calendar_event(&game)
{
crate::content::civilizations::maya::validate_calendar_response(
&game,
response,
player_index,
)?;
}
if game.context == GameContext::AI {
return execute_without_undo(&mut game, action, player_index).map(|()| game);
}

View file

@ -157,13 +157,85 @@ fn title(action: &Action) -> String {
.to_owned()
}
pub fn execute(game: Game, action: Action, player: usize) -> Result<Game, String> {
pub fn execute(mut game: Game, action: Action, player: usize) -> Result<Game, String> {
if matches!(
action,
Action::QueueChoice { .. } | Action::QueueMoves { .. }
) {
return try_execute_action(game, action, player);
}
// Look-only Calendar is a bounded live update, not an atomic logged action.
// Keep this ahead of snapshots, clock credits, automatic choices and plans.
if game.uncommitted_calendar {
if player != game.active_player() {
return Err(format!("Player {player} is not the active player"));
}
if game.events.len() != 1 || !crate::content::civilizations::maya::is_calendar_event(&game)
{
return Err("Invalid Calendar preview".into());
}
let keep = match &action {
Action::Undo => true,
Action::Response(response) => {
crate::content::civilizations::maya::validate_calendar_response(
&game, response, player,
)?;
matches!(response, crate::content::persistent_events::EventResponse::Payment(p)
if p[0].is_empty())
}
_ => return Err("Calendar is waiting for a response".into()),
};
let event = game.events.pop().expect("Calendar event");
game.uncommitted_calendar = false;
if keep {
game.early_choice_update = true;
return Ok(game);
}
// Commit the original start and the paid response as TWO ordinary
// actions. A composite undo patch would rewind two states but one cursor.
let crate::content::persistent_events::PersistentEventType::CustomAction(start) =
event.event_type
else {
unreachable!("validated Calendar event")
};
game = execute_one(
game,
Action::Playing(PlayingAction::Custom(start.action)),
player,
)?;
} else if matches!(&action, Action::Playing(PlayingAction::Custom(custom))
if custom.action == crate::content::custom_actions::CustomActionType::Calendar)
&& game.events.is_empty()
{
if player != game.active_player() {
return Err(format!("Player {player} is not the active player"));
}
// Special action cost lookup assumes the ability exists. Reject an
// unavailable Calendar before entering that lower-level executor.
if !game.player(player).special_actions.contains_key(
&crate::content::custom_actions::SpecialAction::Custom(
crate::content::custom_actions::CustomActionType::Calendar,
),
) {
return Err("Custom action not available".into());
}
let prepared = try_execute_action(game.clone(), action, player)?;
if prepared.events.len() != 1
|| !crate::content::civilizations::maya::is_calendar_event(&prepared)
|| prepared.current_event_handler().is_none()
{
return Err("Invalid Calendar preview".into());
}
// The clone alone may replenish/shuffle an empty deck. Only the private
// request comes back; cancel never changes authoritative RNG or decks.
game.events = prepared.events;
game.uncommitted_calendar = true;
// Knowledge cannot be undone, including Astronomy purchased beforehand.
// This is deliberately NOT information_revealed(): no clock credit.
game.lock_undo();
game.early_choice_update = true;
return Ok(game);
}
let history_navigation = matches!(action, Action::Undo | Action::Redo);
let mut game = execute_one(game, action, player)?;
crate::early_choices::prune_objectives(&mut game);

View file

@ -102,6 +102,43 @@ fn calendar() -> SpecialAdvanceInfo {
} else { p.log(game, "Kept the next event on top of the deck"); }
}), |_, _| true).build()
}
/// Validate before the listener (which assumes a well-formed payment) runs.
/// This also covers recorded Calendar prompts restored by Undo or older saves.
pub(crate) fn validate_calendar_response(
game: &Game,
response: &EventResponse,
player: usize,
) -> Result<(), String> {
let (EventResponse::Payment(payments), Some(handler)) =
(response, game.current_event_handler())
else {
return Err("Invalid Calendar payment".into());
};
let PersistentEventRequest::Payment(requests) = &handler.request else {
return Err("Invalid Calendar payment".into());
};
let ([payment], [request]) = (payments.as_slice(), requests.as_slice()) else {
return Err("Invalid Calendar payment".into());
};
if request.optional && payment.is_empty() {
return Ok(());
}
if !request.cost.is_valid_payment(payment)
|| !game.player(player).resources.has_at_least(payment)
{
return Err("Invalid Calendar payment".into());
}
Ok(())
}
pub(crate) fn is_calendar_event(game: &Game) -> bool {
game.events.last().is_some_and(|event| {
matches!(&event.event_type,
crate::content::persistent_events::PersistentEventType::CustomAction(a)
if a.action.action == CustomActionType::Calendar)
})
}
fn art_cost(c: &mut CostInfo, p: &EventPlayer) {
let resources = base_resources();
let mut pairs = vec![];

View file

@ -136,6 +136,8 @@ pub struct Game {
pub events: Vec<PersistentEventState>,
pub early_choices: Vec<crate::early_choices::SavedChoice>,
pub early_choice_update: bool,
/// A private Calendar prompt, not yet part of the committed action history.
pub uncommitted_calendar: bool,
pub action_plan: Option<crate::action_queue::Plan>,
// in turn order starting from starting_player_index and wrapping around
pub players: Vec<Player>,
@ -339,12 +341,15 @@ impl Game {
#[must_use]
pub fn can_undo(&self) -> bool {
self.context != GameContext::AI && self.undo_limit < self.log_index
self.context != GameContext::AI
&& (self.uncommitted_calendar || self.undo_limit < self.log_index)
}
#[must_use]
pub fn can_redo(&self) -> bool {
self.context != GameContext::AI && self.log_index < current_turn_log(self).actions.len()
self.context != GameContext::AI
&& !self.uncommitted_calendar
&& self.log_index < current_turn_log(self).actions.len()
}
pub(crate) fn is_pirate_zone(&self, position: Position) -> bool {

View file

@ -48,6 +48,8 @@ pub struct GameData {
early_choices: Vec<crate::early_choices::SavedChoice>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
early_choice_update: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
uncommitted_calendar: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
action_plan: Option<crate::action_queue::Plan>,
players: Vec<PlayerData>,
@ -128,6 +130,7 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
action_plan: data.action_plan,
early_choices: data.early_choices,
early_choice_update: data.early_choice_update,
uncommitted_calendar: data.uncommitted_calendar,
context,
cache,
options: data.options,
@ -193,6 +196,7 @@ pub fn data(game: Game) -> GameData {
action_plan: game.action_plan,
early_choices: game.early_choices,
early_choice_update: game.early_choice_update,
uncommitted_calendar: game.uncommitted_calendar,
players: game.players.into_iter().map(player_data).collect(),
map: game.map.data(),
civilization_draft: game.civilization_draft,
@ -234,6 +238,7 @@ pub fn cloned_data(game: &Game) -> GameData {
action_plan: game.action_plan.clone(),
early_choices: game.early_choices.clone(),
early_choice_update: game.early_choice_update,
uncommitted_calendar: game.uncommitted_calendar,
players: game.players.iter().map(cloned_player_data).collect(),
map: game.map.cloned_data(),
civilization_draft: game.civilization_draft.clone(),

View file

@ -189,6 +189,7 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game {
action_plan: None,
early_choices: vec![],
early_choice_update: false,
uncommitted_calendar: false,
seed: setup.seed.clone(),
context: GameContext::Play,
version: JSON_SCHEMA_VERSION,

View file

@ -14,6 +14,9 @@ pub struct ReplayGameData {
seed: String,
log: Vec<ActionLogAge>,
log_index: usize,
// Look-only information boundaries are intentionally absent from the log.
#[serde(default)]
undo_limit: Option<usize>,
players: Vec<ReplayPlayerData>,
#[serde(default)]
dropped_players: Vec<usize>,
@ -152,6 +155,19 @@ pub fn replay(data: ReplayGameData, to: Option<usize>) -> Result<Game, String> {
// Reconstructing any cursor must neither earn nor revoke existing credits.
game.time_increments = data.time_increments;
if full_replay {
// Reconstructing a playable current save must not reopen actions sealed
// by an unrecorded Calendar look. Historical cursors keep their own limits.
if let Some(limit) = data.undo_limit {
game.undo_limit = game.undo_limit.max(limit.min(game.log_index));
let limit = game.undo_limit;
for action in crate::log::current_turn_log_mut(&mut game)
.actions
.iter_mut()
.take(limit)
{
action.undo.clear();
}
}
game.finish_after_drop();
}
Ok(game)

View file

@ -28,6 +28,7 @@ mod collection_potential;
mod decisions;
mod effects;
mod journal;
mod research;
mod turn;
mod waiting;
pub use actions::recruit_preview;

View file

@ -379,7 +379,8 @@ pub fn cards(game: &Game, seat: usize, can_play: bool) -> Vec<Value> {
let reason = action_reason(game,seat,can_play,PlayingActionType::ActionCard(*id));
json!({"id":id,"name":c.civil_card.name,"description":c.civil_card.description,"free":PlayingActionType::ActionCard(*id).cost(game,seat).free,
"cost":PlayingActionType::ActionCard(*id).payment_options(game,seat).default,
"researchAdvances":if reason.is_none() {crate::content::action_cards::research_choices(game, game.player(seat), &c.civil_card.name)} else {vec![]},
"researchAdvances":if reason.is_none() {super::research::card_choices(game, seat, *id)} else {vec![]},
"freeResearch":super::research::card_is_free_research(*id),
"tactics":c.tactics_card.as_ref().map(|t|json!({"name":t.name,"description":t.description})),
"reason":reason,"action":reason.is_none().then(||Action::Playing(PlayingAction::ActionCard(*id)))})
}).collect()
@ -412,6 +413,8 @@ pub fn special(game: &Game, seat: usize, can_play: bool) -> Vec<Value> {
cities.into_iter().map(|city|json!({"name":info.event_origin.name(game),"description":execution.ability.description,"position":city,"reason":reason,
"cost":info.cost.cost.payment_options(game.player(seat),info.event_origin.clone()).default_payment(),
"free":info.cost.cost.free,
"researchAdvances":if reason.is_none() {super::research::ability_choices(game, seat, info.custom_action_type())} else {vec![]},
"freeResearch":super::research::ability_is_free_research(info.custom_action_type()),
"activatesCity":(info.custom_action_type() == crate::content::custom_actions::CustomActionType::GoldenAge)
.then(|| crate::leader::leader_position(game.player(seat))),
"action":Action::Playing(PlayingAction::Custom(CustomAction::new(info.custom_action_type(),city)))})).collect::<Vec<_>>()

View file

@ -0,0 +1,103 @@
//! Read-only research-source metadata. The caller must first check the source
//! action's actual availability (turn, hand/leader ownership, costs and limits).
//! Keep target mappings in engine identifiers, never translated descriptions.
use crate::advance::Advance;
use crate::content::advances::AdvanceGroup;
use crate::content::custom_actions::CustomActionType;
use crate::game::Game;
use crate::player::{CostTrigger, Player};
fn in_groups(game: &Game, player: &Player, groups: &[AdvanceGroup]) -> Vec<Advance> {
groups
.iter()
.flat_map(|group| &game.cache.get_advance_group(*group).advances)
.filter(|a| player.can_advance_free(a.advance, game))
.map(|a| a.advance)
.collect()
}
pub(super) fn card_choices(game: &Game, seat: usize, id: u8) -> Vec<Advance> {
use AdvanceGroup::{
Autocracy, Construction, Culture, Democracy, Economy, Education, Science, Seafaring,
Spirituality, Theocracy, Warfare,
};
// The same groups used by incidents::great_persons::great_person_card.
// Playability alone is insufficient: a Great Person's secondary effect may
// remain playable after all its advances have already been researched.
let groups: &[AdvanceGroup] = match id {
118 => &[Seafaring],
119 | 156 => &[Culture],
120 => &[Spirituality],
121 => &[Education],
122 => &[Science],
123 => &[Democracy, Autocracy, Theocracy],
124 => &[Warfare],
125 => &[Economy],
126 => &[Construction],
_ => {
return crate::content::action_cards::research_choices(
game,
game.player(seat),
&game.cache.get_action_card(id).civil_card.name,
);
}
};
in_groups(game, game.player(seat), groups)
}
pub(super) fn card_is_free_research(id: u8) -> bool {
matches!(id, 1..=4 | 39 | 40 | 118..=126 | 156)
}
pub(super) fn ability_choices(game: &Game, seat: usize, action: CustomActionType) -> Vec<Advance> {
use AdvanceGroup::{Agriculture, Construction, Education, Warfare};
use CustomActionType::{
AgricultureEconomist, Aqueduct, ArtOfWar, Constructor, GoldenAge, Master,
};
let player = game.player(seat);
match action {
// Same targets as leader_ability::advance_gain_custom_action. The
// action availability check already verifies the happy leader city.
ArtOfWar => in_groups(game, player, &[Warfare]),
AgricultureEconomist => in_groups(game, player, &[Agriculture]),
Master => in_groups(game, player, &[Education]),
Constructor => in_groups(game, player, &[Construction]),
Aqueduct => vec![Advance::Sanitation],
GoldenAge => {
// Match india::golden_age_advances before its upfront payment:
// reserve the culture token, then test actual research payments.
let mut available = player.resources.clone();
if available.culture_tokens == 0 {
return vec![];
}
available.culture_tokens -= 1;
game.cache
.get_advance_groups()
.iter()
.filter(|group| !group.advances.iter().any(|a| player.has_advance(a.advance)))
.flat_map(|group| &group.advances)
.filter(|a| {
player.can_advance_free(a.advance, game)
&& player
.advance_cost(a.advance, game, CostTrigger::NoModifiers)
.cost
.first_valid_payment(&available)
.is_some()
})
.map(|a| a.advance)
.collect()
}
// Triggered rewards and borrowed abilities are not research actions.
_ => vec![],
}
}
pub(super) fn ability_is_free_research(action: CustomActionType) -> bool {
matches!(
action,
CustomActionType::ArtOfWar
| CustomActionType::AgricultureEconomist
| CustomActionType::Master
| CustomActionType::Constructor
)
}

View file

@ -0,0 +1,393 @@
//! Calendar's live boundary must not record look-only interactions.
use serde_json::{Value, json};
use server::{
action::{Action, try_execute_action},
advance::{Advance, AdvanceAction},
board_history,
cache::Cache,
collect::{Collect, PositionCollection},
content::{
custom_actions::{CustomAction, CustomActionType},
persistent_events::{EventResponse, PersistentEventRequest},
},
game::{Game, GameContext},
game_api::{log_length, strip_secret},
game_data::GameData,
game_setup::{GameSetupBuilder, setup_game},
playing_actions::{PlayingAction, PlayingActionType},
resource_pile::ResourcePile,
timing::time_increments,
};
fn saved(game: &Game) -> Value {
serde_json::to_value(game.cloned_data()).unwrap()
}
fn reload(value: Value) -> Game {
let data: GameData = serde_json::from_value(value).unwrap();
let cache = Cache::new(&data.options);
Game::from_data(data, cache, GameContext::Play)
}
fn play(game: Game, action: Action) -> Game {
board_history::execute(game, action, 0).unwrap()
}
fn calendar() -> Action {
Action::Playing(PlayingAction::Custom(CustomAction::new(
CustomActionType::Calendar,
None,
)))
}
fn payment(pile: ResourcePile) -> Action {
Action::Response(EventResponse::Payment(vec![pile]))
}
fn keep() -> Action {
payment(ResourcePile::empty())
}
fn bury() -> Action {
payment(ResourcePile::culture_tokens(1))
}
fn research(advance: Advance) -> Action {
Action::Playing(PlayingAction::Advance(AdvanceAction::new(
advance,
ResourcePile::food(2),
)))
}
// All setup changes are legal recorded actions, so the resulting save replays.
fn before_astronomy() -> Game {
let mut game = setup_game(
&GameSetupBuilder::new(2)
.seed("calendar-preview-regression".into())
.assigned_civilizations(vec!["Maya".into(), "Rome".into()])
.build(),
);
if game.active_player() != 0 {
game = board_history::execute(game, Action::Playing(PlayingAction::EndTurn), 1).unwrap();
}
game = play(game, research(Advance::Math));
let home = game.player(0).cities[0].position;
for _ in 0..2 {
game = play(
game,
Action::Playing(PlayingAction::Collect(Collect::new(
home,
vec![PositionCollection::new(home, ResourcePile::food(1))],
PlayingActionType::Collect,
))),
);
}
game = play(game, Action::Playing(PlayingAction::EndTurn));
game = board_history::execute(game, Action::Playing(PlayingAction::EndTurn), 1).unwrap();
game
}
fn ready() -> Game {
play(before_astronomy(), research(Advance::Astronomy))
}
fn prompt(game: &Game) -> String {
let PersistentEventRequest::Payment(requests) = &game.current_event_handler().unwrap().request
else {
panic!("Calendar payment request");
};
requests[0].name.clone()
}
fn current_turn_log(game: &Game) -> &server::log::ActionLogTurn {
game.log
.last()
.unwrap()
.rounds
.last()
.unwrap()
.turns
.last()
.unwrap()
}
fn history_shape(game: &Game) -> (usize, usize, Value) {
(
log_length(game),
current_turn_log(game).actions.len(),
saved(game)["board_history"].clone(),
)
}
#[test]
fn hundreds_of_keep_and_cancel_cycles_are_bounded_live_updates_without_clock_credits() {
let original = ready();
let shape = history_shape(&original);
let resources = original.player(0).resources.clone();
let counters = time_increments(&original);
let deck = original.incidents_left.clone();
let rng = original.rng.seed;
let mut game = play(play(original, calendar()), Action::Undo);
let sealed = saved(&game);
for i in 0..200 {
game = play(game, calendar());
assert!(game.uncommitted_calendar && game.early_choice_update);
assert!(game.can_undo());
assert!(!game.can_redo());
assert_eq!(history_shape(&game), shape);
assert_eq!(game.player(0).resources, resources);
assert_eq!(game.incidents_left, deck);
assert_eq!(game.rng.seed, rng);
assert_eq!(time_increments(&game), counters);
assert!(saved(&game).to_string().len() < sealed.to_string().len() + 4000);
game = play(game, if i % 2 == 0 { keep() } else { Action::Undo });
assert!(!game.uncommitted_calendar && game.early_choice_update);
assert_eq!(saved(&game), sealed);
}
}
#[test]
fn looking_seals_astronomy_but_cancels_only_the_uncommitted_prompt() {
let before = before_astronomy();
let game = play(before.clone(), research(Advance::Astronomy));
assert!(game.can_undo());
let undone = play(game.clone(), Action::Undo);
assert!(!undone.player(0).advances.contains(Advance::Astronomy));
assert_eq!(undone.player(0).resources, before.player(0).resources);
for close in [Action::Undo, keep()] {
let peek = play(game.clone(), calendar());
assert_eq!(peek.undo_limit, peek.log_index);
assert!(
current_turn_log(&peek)
.actions
.iter()
.all(|a| a.undo.is_empty())
);
let closed = play(peek, close);
assert!(closed.player(0).advances.contains(Advance::Astronomy));
assert!(!closed.can_undo());
assert_eq!(history_shape(&closed), history_shape(&game));
assert!(board_history::execute(closed, Action::Undo, 0).is_err());
}
}
#[test]
fn paid_burial_has_two_actions_and_one_step_undo_redo_until_the_next_look() {
let start = ready();
let count = log_length(&start);
let deck = start.incidents_left.clone();
let culture = start.player(0).resources.culture_tokens;
let open = play(start.clone(), calendar());
let paid = play(open, bury());
assert!(!paid.uncommitted_calendar && !paid.early_choice_update);
assert!(paid.events.is_empty());
assert_eq!(log_length(&paid), count + 2);
assert_eq!(paid.incidents_left.last(), deck.first());
assert_eq!(paid.player(0).resources.culture_tokens, culture - 1);
assert!(paid.can_undo());
let mut undone = play(reload(saved(&paid)), Action::Undo);
assert_eq!(log_length(&undone), count + 1);
assert_eq!(undone.incidents_left, deck);
assert_eq!(undone.player(0).resources.culture_tokens, culture);
assert!(!undone.uncommitted_calendar);
assert!(
!undone.can_undo(),
"recorded look is an information boundary"
);
assert!(undone.can_redo());
assert!(prompt(&undone).starts_with(&undone.cache.get_incident(deck[0]).name));
// Legacy/undo-restored prompts keep the ordinary one-response history flow.
let kept = play(undone.clone(), keep());
assert_eq!(log_length(&kept), count + 2);
assert!(kept.events.is_empty());
for _ in 0..3 {
undone = play(play(undone, Action::Redo), Action::Undo);
assert_eq!(log_length(&undone), count + 1);
assert_eq!(undone.incidents_left, deck);
}
let redone = play(undone, Action::Redo);
assert_eq!(redone.incidents_left, paid.incidents_left);
assert_eq!(redone.player(0).resources, paid.player(0).resources);
assert_eq!(time_increments(&redone), time_increments(&paid));
let next = play(redone, calendar());
let closed = play(next, Action::Undo);
assert_eq!(log_length(&closed), count + 2);
assert_eq!(closed.player(0).resources.culture_tokens, culture - 1);
assert!(!closed.can_undo());
assert_eq!(closed.incidents_left, paid.incidents_left);
}
#[test]
fn empty_deck_peek_is_speculative_and_paid_commit_reproduces_it() {
let mut start = ready();
start.incidents_left.clear();
let rng = start.rng.seed;
// The lower executor is the recorded/replay representation, with no live hook.
let recorded = try_execute_action(start.clone(), calendar(), 0).unwrap();
assert!(!recorded.uncommitted_calendar);
assert!(!recorded.incidents_left.is_empty());
assert_ne!(recorded.rng.seed, rng);
let expected_top = recorded.incidents_left[0];
let mut game = start.clone();
for close in [keep(), Action::Undo, keep()] {
let open = play(game, calendar());
assert_eq!(prompt(&open), prompt(&recorded));
assert!(open.incidents_left.is_empty());
assert_eq!(open.rng.seed, rng);
game = play(reload(saved(&open)), close);
assert!(game.incidents_left.is_empty());
assert_eq!(game.rng.seed, rng);
}
let paid = play(play(game, calendar()), bury());
let expected = try_execute_action(recorded, bury(), 0).unwrap();
assert_eq!(paid.incidents_left, expected.incidents_left);
assert_eq!(paid.rng.seed, expected.rng.seed);
assert_eq!(paid.incidents_left.last(), Some(&expected_top));
let undone = play(paid, Action::Undo);
assert_eq!(undone.incidents_left[0], expected_top);
assert!(!undone.uncommitted_calendar);
assert_eq!(undone.player(0).resources, start.player(0).resources);
}
#[test]
fn reload_privacy_and_rejections_do_not_expose_or_resolve_a_preview() {
let start = ready();
assert!(board_history::execute(start.clone(), calendar(), 1).is_err());
assert!(board_history::execute(before_astronomy(), calendar(), 0).is_err());
let open = play(start, calendar());
let request = prompt(&open);
let raw = saved(&open);
assert_eq!(raw["uncommitted_calendar"], json!(true));
let owner = strip_secret(open.clone(), Some(0));
assert!(owner.uncommitted_calendar);
assert_eq!(prompt(&owner), request);
for seat in [Some(1), None] {
let public = strip_secret(open.clone(), seat);
assert!(public.uncommitted_calendar);
assert_eq!(prompt(&public), "Calendar · Inspecting the next event");
assert!(!saved(&public)["events"].to_string().contains(&request));
}
let open = reload(raw.clone());
assert!(open.uncommitted_calendar && open.can_undo());
for action in [
Action::Response(EventResponse::Payment(vec![])),
Action::Response(EventResponse::Payment(vec![ResourcePile::empty(); 2])),
Action::Response(EventResponse::Bool(false)),
payment(ResourcePile::food(1)),
payment(ResourcePile::culture_tokens(2)),
payment(ResourcePile::culture_tokens(1) + ResourcePile::food(1)),
calendar(),
Action::Playing(PlayingAction::EndTurn),
Action::Redo,
] {
assert!(board_history::execute(open.clone(), action, 0).is_err());
assert_eq!(saved(&open), raw);
}
for action in [keep(), bury(), Action::Undo] {
for seat in [1, usize::MAX] {
assert!(board_history::execute(open.clone(), action.clone(), seat).is_err());
}
}
let mut broke = open.clone();
broke.player_mut(0).resources.culture_tokens = 0;
assert!(board_history::execute(broke.clone(), bury(), 0).is_err());
assert!(play(broke, keep()).events.is_empty());
// Lower callers must not try to apply a nonexistent cursor patch.
let closed = try_execute_action(open, Action::Undo, 0).unwrap();
assert!(!closed.uncommitted_calendar);
assert!(closed.early_choice_update);
assert!(saved(&closed).get("uncommitted_calendar").is_none());
}
#[test]
fn independent_private_queue_updates_remain_available_during_a_preview() {
let mut game = ready();
// Seat 1 has finished its final turn and can preselect a status advance.
game.round = 3;
game.starting_player_index = 1;
let offer = server::early_choices::offers(&game, 1)
.into_iter()
.find(|offer| offer.title == "Free Advance")
.unwrap();
let queue = |response| Action::QueueChoice {
key: offer.key.clone(),
response,
};
game = board_history::execute(game, queue(Some(offer.options[0].response.clone())), 1).unwrap();
game.action_plan = Some(server::action_queue::Plan {
player: 1,
key: "failed-plan".into(),
actions: vec![],
waiting: false,
error: Some("The earlier choice has changed; review your plan".into()),
});
let open = play(game, calendar());
let original = saved(&open);
for execute in [board_history::execute, try_execute_action] {
let revised = execute(
open.clone(),
queue(Some(offer.options[1].response.clone())),
1,
)
.unwrap();
assert!(revised.uncommitted_calendar && revised.early_choice_update);
assert_eq!(revised.early_choices[0].response, offer.options[1].response);
let cleared = execute(
revised,
Action::QueueMoves {
key: "failed-plan".into(),
actions: vec![],
waiting: false,
},
1,
)
.unwrap();
assert!(cleared.action_plan.is_none());
assert!(cleared.uncommitted_calendar && cleared.early_choice_update);
assert_eq!(saved(&cleared)["events"], original["events"]);
assert_eq!(history_shape(&cleared), history_shape(&open));
assert_eq!(time_increments(&cleared), time_increments(&open));
for close in [keep(), Action::Undo] {
let closed = play(cleared.clone(), close);
assert!(closed.events.is_empty());
assert!(!closed.uncommitted_calendar && closed.early_choice_update);
assert_eq!(closed.early_choices, cleared.early_choices);
assert_eq!(history_shape(&closed), history_shape(&open));
}
}
}
#[test]
fn full_replay_omits_transient_prompts_preserves_the_seal_and_reproduces_paid_actions() {
let game = ready();
for state in [
play(game.clone(), calendar()),
play(play(game.clone(), calendar()), keep()),
] {
let replayed =
server::replay::replay(serde_json::from_value(saved(&state)).unwrap(), None).unwrap();
assert_eq!(log_length(&replayed), log_length(&state));
assert_eq!(replayed.incidents_left, state.incidents_left);
assert_eq!(replayed.rng.seed, state.rng.seed);
assert_eq!(replayed.player(0).resources, state.player(0).resources);
assert!(!replayed.uncommitted_calendar);
assert!(replayed.events.is_empty());
assert!(
!replayed.can_undo(),
"current reconstruction must preserve the look's seal"
);
}
let paid = play(play(game, calendar()), bury());
let replayed =
server::replay::replay(serde_json::from_value(saved(&paid)).unwrap(), None).unwrap();
assert_eq!(log_length(&replayed), log_length(&paid));
assert_eq!(replayed.incidents_left, paid.incidents_left);
assert_eq!(replayed.rng.seed, paid.rng.seed);
assert_eq!(replayed.player(0).resources, paid.player(0).resources);
assert_eq!(time_increments(&replayed), time_increments(&paid));
assert!(replayed.can_undo());
let undone = play(replayed, Action::Undo);
assert!(!undone.uncommitted_calendar);
assert!(undone.can_redo());
assert_eq!(log_length(&undone), log_length(&paid) - 1);
}

View file

@ -776,3 +776,32 @@ no game rules or deployed engine update is required. Regression coverage include
private previews, free/paid keep-bury responses, zero-culture cases, public/free
Great Persons, and desktop/mobile browser checks in English and French. Retain
French objective/retry and Chinese locale-switching browser regressions too.
## Viewer 0.1.193 / engine 0.4.128
Calendar look-only previews are bounded live updates. Opening, keeping the top
card, or cancelling with Undo adds no committed actions, journal entries, board
frames or clock credits. Preview requests remain owner-only, and speculative
empty-deck shuffles leave the authoritative deck and RNG unchanged. Looking seals
prior committed undo history; cancelling only closes the preview. A paid burial
commits the existing start/payment action pair, preserving payment Undo/Redo
until another reveal. Saved previews, legacy recorded prompts, private queues
and current-state replay retain their respective history and privacy boundaries.
Research now advertises legal card and leader alternatives for each advance,
including Great Scientist, Merchant and Warlord, the other direct research Great
Persons, research action cards, and applicable leader abilities. Explicit source
buttons use the existing card/ability flow and show action/token costs separately
from research resource costs. Ordinary research stays a separate deliberate
purchase; selecting an advance never automatically spends a source. Availability,
prerequisites, ownership, Shogunate limits and private hands are respected, and
existing free-advance decisions do not show redundant alternatives. Aqueduct and
Synergies retain their dedicated explanations.
Publish the matching engine and viewer together. All 17 catalogs include the
new wording. Regression checks cover repeated look/cancel cycles, payment
Undo/Redo, replay and privacy, prediction safety, empty-log state refreshes,
research-source eligibility and explicit purchases, plus English/French desktop
and mobile browser flows. Existing Great Person localization, Synergies/Aqueduct,
French objective/retry and Chinese locale-switching browser checks are retained.
No live game moves or historical game-state repairs are part of this release.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.192",
"version": "0.1.193",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.192",
"version": "0.1.193",
"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.192",
"version": "0.1.193",
"private": true,
"type": "module",
"scripts": {

View file

@ -114,6 +114,20 @@ try {
const result = JSON.parse(move(merchant, response));
assert.equal(result.players[seat].resources.culture_tokens, width === 1400 ? 1 : 2);
assert.equal(result.events?.length ?? 0, 0);
await emit(JSON.stringify(result));
await preview.waitFor({ state: 'detached' });
await emit(merchant);
await preview.waitFor();
const cancel = page.locator('.decision-heading').getByRole('button', { name: t('Cancel ability'), exact: true });
await cancel.click();
await page.waitForFunction(() => sent.length === 1);
assert.equal(JSON.parse(await page.evaluate(() => sent[0])), 'Undo');
const closed = move(merchant, 'Undo');
assert.equal(engine.isLiveUpdate(closed), true);
assert.equal(engine.logLength(closed), engine.logLength(merchant));
assert.deepEqual(engine.timeIncrements(closed), engine.timeIncrements(merchant));
await emit(closed);
await preview.waitFor({ state: 'detached' });
await emit(fixture('Great Merchant', 0));
await preview.waitFor();
assert.equal(await actions.getByRole('button').count(), 1);
@ -124,6 +138,7 @@ try {
await emit(fixture('Famine'));
await page.locator('.decision-panel .payment-choices').waitFor();
assert.equal(await preview.count(), 0, 'ordinary event UI remains unchanged');
assert.ok(await cancel.isEnabled(), 'ordinary Calendar previews can also be cancelled');
await emit(merchant, 1 - seat);
await preview.waitFor({ state: 'detached' });
assert.equal(await page.locator('.decision-panel').count(), 0, 'opponent cannot see or act on this preview');

View file

@ -58,7 +58,7 @@ function rust(directory) {
// Ignore test modules and diagnostics: these are not player-facing rules.
if (/#\[cfg\(test\)\]/.test(content.slice(0, start))) continue;
const context = content.slice(Math.max(0, start - 120), start);
if (/(?:panic!|assert(?:_eq|_ne)?!|debug_assert(?:_eq|_ne)?!|expect)\s*\([^;]*$/.test(context)) continue;
if (/(?:panic!|unreachable!|assert(?:_eq|_ne)?!|debug_assert(?:_eq|_ne)?!|expect)\s*\([^;]*$/.test(context)) continue;
add(rustTemplate(value), path.relative(root, file));
}
}

View file

@ -71,7 +71,7 @@ test('extracts current continued engine rules and omits test/technical noise', (
'A: When drawing a wonder: Take {p0} from anywhere in the game',
]) assert.ok(Object.keys(inventory).some((key) => key.startsWith(prefix)), prefix);
for (const key of ['Build {p0} at {p1}', 'Free with {p0} · once per turn', 'city size {p0}, Fortress', 'Recruit {p0} units & action card']) assert.ok(inventory[key], key);
for (const key of ['action-panel floating-panel early-choices', 'current={p0}, available={p1}, conversions={p2}, exact={p3}, skip={p4}', 'crate::timing::deserialize_counters', 'button[data-panel-close]', 'Build {p0}{p1}']) assert.equal(inventory[key], undefined, key);
for (const key of ['action-panel floating-panel early-choices', 'current={p0}, available={p1}, conversions={p2}, exact={p3}, skip={p4}', 'crate::timing::deserialize_counters', 'button[data-panel-close]', 'Build {p0}{p1}', 'validated Calendar event']) assert.equal(inventory[key], undefined, key);
assert.ok(Object.values(inventory).flat().every((file) => !/\.test\.ts|_tests\.rs/.test(file)));
// Check mode must not write even if output flags are accidentally supplied.
const before = fs.readFileSync(output, 'utf8');

View file

@ -0,0 +1,144 @@
// Offline built-viewer regression: npm run build && node scripts/research-reminders-smoke.mjs
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, [], {}, 'research-reminders-browser', {})).players.slice(2);
async function fixture(name = 'action_cards/synergies') {
const g = JSON.parse(await readFile(new URL(`../../server/tests/test_games/${name}.json`, import.meta.url), 'utf8'));
for (const npc of npcs) if (!g.players.some((p) => p.civilization === npc.civilization)) g.players.push({ ...npc, id: g.players.length });
g.players[0].advances = ['Farming', 'Mining', 'Math', 'Tactics', 'Bartering'];
g.players[0].action_cards = [122];
g.players[0].incident_tokens = 3;
g.players[1].action_cards = [];
return g;
}
const v = (g) => JSON.parse(engine.webView(engine.stripSecret(JSON.stringify(g), 0), 0));
const browser = await chromium.launch({ headless: true, args: ['--use-gl=angle', '--use-angle=swiftshader'] });
try {
for (const locale of ['en', 'fr']) {
const translations = locale === 'en' ? {} : JSON.parse(await readFile(new URL('../dist/fr.json', import.meta.url), 'utf8'));
const t = (text) => translations[text] ?? text;
for (const [width, height] of [[1400, 900], [390, 740]]) {
const page = await browser.newPage({ viewport: { width, height } });
page.setDefaultTimeout(30000);
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.route('**/*', async (route) => {
const url = new URL(route.request().url());
if (url.hostname === 'fonts.googleapis.com') return route.fulfill({ contentType: 'text/css', body: '' });
if (url.hostname !== 'clash.test') return route.abort();
if (url.pathname === '/') 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>' });
const path = decodeURIComponent(url.pathname.slice(1));
assert(!path.includes('..'));
const types = { js: 'text/javascript', json: 'application/json', wasm: 'application/wasm', woff2: 'font/woff2', svg: 'image/svg+xml' };
try { return route.fulfill({ contentType: types[path.split('.').at(-1)] ?? 'application/octet-stream', body: await readFile(new URL('../dist/' + path, import.meta.url)) }); }
catch { return route.abort(); }
});
async function mount(game, seat = 0) {
await page.goto('http://clash.test/');
await page.evaluate(({ state, seat, locale }) => {
window.host = clash3d.launch('#app'); window.sent = [];
host.on('move', (action) => sent.push(action));
host.emit('player', seat === null ? {} : { index: seat });
host.emit('theme', { dark: true });
host.emit('preferences', { sound: false, locale });
host.emit('state', state);
}, { state: engine.stripSecret(JSON.stringify(game), seat ?? undefined), seat, locale });
await page.waitForSelector(`[data-clash-locale="${locale}"]`);
}
const open = async (id) => {
await page.getByRole('button', { name: t('Research tree'), exact: true }).click();
await page.locator(`#research-${id} .research-pick`).click();
};
const sent = () => page.evaluate(() => window.sent.map((a) => JSON.parse(a)));
const detail = page.locator('.research-detail');
const alternatives = detail.locator('.research-alternatives');
const primary = detail.locator('.research-payment > .primary');
// Merely opening/selecting an advance never spends either resources or a card.
let game = await fixture();
await mount(game); await open('Medicine');
const provinceLink = page.locator('.research-civilization-link').filter({ hasText: t('Provinces') }).first();
assert.equal(await provinceLink.getByText(t('Unlocks'), { exact: true }).count(), 1);
await alternatives.getByText(t('Alternative research available'), { exact: true }).waitFor();
assert((await alternatives.innerText()).includes(t('No research resource cost')));
assert.deepEqual(await sent(), []);
assert(await primary.isEnabled(), 'normal paid research remains an explicit separate option');
await primary.scrollIntoViewIfNeeded();
await page.screenshot({ path: `/tmp/clash-research-reminder-${locale}-${width}-paid-choice.png` });
await primary.click();
await page.waitForFunction(() => sent.length === 1);
assert.deepEqual((await sent())[0], v(game).advances.find((a) => a.id === 'Medicine').action);
const paid = JSON.parse(engine.tryMove(JSON.stringify(game), JSON.stringify((await sent())[0]), 0));
assert(paid.players[0].action_cards.includes(122), 'paid research does not silently consume Scientist');
for (const [id, name, target] of [[122, 'Great Scientist', 'Medicine'], [125, 'Great Merchant', 'TradeRoutes'], [124, 'Great Warlord', 'SteelWeapons']]) {
game = await fixture(); game.players[0].action_cards = [id];
await mount(game); await open(target);
assert.deepEqual(await sent(), []);
const use = alternatives.locator('.research-source');
assert.equal(await use.count(), 1);
assert((await use.innerText()).includes(t(name)));
assert((await page.locator(`#research-${target} .research-card-hint`).innerText()).includes(t(name)));
await use.scrollIntoViewIfNeeded();
assert(await use.isVisible());
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
await page.screenshot({ path: `/tmp/clash-research-reminder-${locale}-${width}-${id}.png` });
await use.click();
await page.waitForFunction(() => sent.length === 1);
assert.deepEqual((await sent())[0], { Playing: { ActionCard: id } });
const requested = engine.tryMove(JSON.stringify(game), JSON.stringify((await sent())[0]), 0);
await page.evaluate((state) => { window.sent = []; host.emit('state', state); }, engine.stripSecret(requested, 0));
await page.locator('.research-dialog').waitFor();
assert.equal(await page.locator('.research-alternatives').count(), 0, 'no redundant reminders inside an existing free-advance choice');
assert.equal(await page.locator('.research-card-hint').count(), 0);
await page.locator(`#research-${target} .research-pick`).click();
assert.deepEqual(await sent(), []);
await primary.click();
await page.waitForFunction(() => sent.length === 1);
assert.deepEqual((await sent())[0], { Response: { SelectAdvance: target } });
}
// Leader alternatives use the real custom action rather than paid Advance.
game = await fixture('civilizations/greece/master');
game.players[0].action_cards = [];
game.players[0].advances.push('Writing');
await mount(game); await open('Philosophy');
assert((await alternatives.innerText()).includes(t('Master')));
assert.deepEqual(await sent(), []);
await alternatives.locator('.research-source').click();
await page.waitForFunction(() => sent.length === 1);
assert.deepEqual((await sent())[0], { Playing: { Custom: { action: 'Master' } } });
// Keep Synergies' specific two-advance benefit alongside the new reminders.
game = await fixture(); game.players[0].action_cards = [33];
await mount(game); await open('Medicine');
assert((await alternatives.innerText()).includes(t('· 2 advances in this category')), await alternatives.innerText());
assert((await alternatives.innerText()).includes(t('Pay research cost next')));
const groupHint = page.locator('.research-branch > .research-card-hint').first();
assert((await groupHint.innerText()).includes(t('· 2 advances · normal resource costs')), await groupHint.innerText());
assert.deepEqual(await sent(), []);
await alternatives.locator('.research-source').click();
await page.waitForFunction(() => sent.length === 1);
assert.deepEqual((await sent())[0], { Playing: { ActionCard: 33 } });
// A private opponent's hand and an exhausted action allowance never make reminders.
game = await fixture();
game.players[0].action_cards = [];
game.players[1].action_cards = [122, 125, 124];
await mount(game); await open('Medicine');
assert.equal(await page.locator('.research-alternatives, .research-card-hint').count(), 0);
game.players[0].action_cards = [122]; game.actions_left = 0;
await mount(game);
await page.getByRole('button', { name: t('Research tree'), exact: true }).click();
assert.equal(await page.locator('.research-card-hint').count(), 0);
assert.deepEqual(errors, []);
await page.close();
console.log(`${locale} ${width}: deliberate paid research, Scientist/Merchant/Warlord and leader shortcuts, free-choice suppression, privacy and action limits passed.`);
}
}
} finally { await browser.close(); }

View file

@ -42,7 +42,7 @@
type View,
} from './types';
import { buildingInfo } from './city';
import { manGodAbility, researchOwners, researchFreeHints, aqueductResearch, researchCardHints, type ResearchReference } from './research-links';
import { manGodAbility, researchOwners, researchFreeHints, aqueductResearch, researchCardHints, researchAbilityHints, type ResearchReference } from './research-links';
import { actionReason, pileText } from './model';
import { groupIcons, researchPresentation } from './research';
import { researchDecision } from './decision-controls';
@ -122,12 +122,17 @@
function cardHints(advance: AdvanceView) {
return !reference && !choice && !$session.playback ? researchCardHints(view, advance) : [];
}
function abilityHints(advance: AdvanceView) {
// Aqueduct already has its own two-option payment explanation below.
return !reference && !choice && !$session.playback
? researchAbilityHints(view, advance).filter((offer) => offer !== aqueduct(advance)) : [];
}
function aqueduct(advance: AdvanceView | undefined) {
return !reference && !choice ? aqueductResearch(view, advance) : undefined;
}
function researchAvailable(advance: AdvanceView) {
const alternative = aqueduct(advance);
return !!advance.action || !!(alternative && !alternative.reason) || cardHints(advance).length > 0;
return !!advance.action || !!(alternative && !alternative.reason) || cardHints(advance).length > 0 || abilityHints(advance).length > 0;
}
function unavailableReason(advance: AdvanceView) {
if (researchAvailable(advance)) return "";
@ -338,7 +343,7 @@
<div class="research-card-hint">
<button class="research-advance-link" disabled={$session.pending}
onclick={() => controller.playContextualCard(card.id, 'research')}>
<Layers size={13} />Use {printedCardName(card.name)} · 2 advances · normal resource costs
<Layers size={13} /><span>Use {printedCardName(card.name)} <span>· 2 advances · normal resource costs</span></span>
</button>
<button class="icon-button" aria-label={`Details of ${printedCardName(card.name)}`} onclick={() => cardReference = card}><Info size={15} /></button>
</div>
@ -480,12 +485,21 @@
<button class="research-advance-link" disabled={$session.pending}
title={card.description}
onclick={() => controller.playContextualCard(card.id, 'research')}>
<Layers size={13} />Use {printedCardName(card.name)}{card.name === 'Synergies' ? ' · 2 advances in this category' : ''}
<Layers size={13} /><span>Use {printedCardName(card.name)}{#if card.name === 'Synergies'}<small>· 2 advances in this category</small>{/if}{#if card.freeResearch}<small>No research resource cost</small>{/if}</span>
</button>
<button class="icon-button" aria-label={`Details of ${printedCardName(card.name)}`}
onclick={() => (cardReference = card)}><Info size={14} /></button>
</div>
{/each}
{#each abilityHints(advance) as ability}
<div class="research-card-hint">
<button class="research-advance-link" disabled={$session.pending}
title={ability.description}
onclick={() => controller.submit(ability.action, ability.cost)}>
<Lightbulb size={13} /><span>Use {ability.name}{#if ability.freeResearch}<small>No research resource cost</small>{/if}</span>
</button>
</div>
{/each}
{#each advances.filter((a) => a.required === advance.id && a.group !== advance.group) as unlocked}
{@const UnlockIcon = researchPresentation(unlocked).icon}
<button
@ -493,7 +507,7 @@
onclick={() => showAdvance(unlocked.id)}
title={`${unlocked.group} · ${unlocked.name}`}
>
<UnlockIcon size={14} />Unlocks {unlocked.name}<ArrowRight size={12} />
<UnlockIcon size={14} /><span>Unlocks</span><span>{unlocked.name}</span><ArrowRight size={12} />
</button>
{/each}
{#each civilizationAdvances.filter( (a) => a.prerequisites.some((p) => p.id === advance.id) ) as special}
@ -503,8 +517,8 @@
title={`${special.active ? 'Unlocked' : 'Unlocks automatically'}: ${special.name}`}
>
<CivilizationEmblem civilization={player!.civilization} size={14} />
{special.active ? 'Unlocked' : 'Unlocks'}
{special.name}<ArrowRight size={12} />
<span>{special.active ? 'Unlocked' : 'Unlocks'}</span>
<span>{special.name}</span><ArrowRight size={12} />
</button>
{/each}
</article>
@ -549,6 +563,38 @@
{buildingInfo[selected.unlocks].effect}
</p>{/if}
{#if unavailableReason(selected) && !selected.owned}<small>{unavailableReason(selected)}</small>{/if}
{#if cardHints(selected).length || abilityHints(selected).length}
<section class="research-alternatives" aria-label="Alternative research available">
<strong>Alternative research available</strong>
<p>Use a card or ability below instead of normal research. Its own costs and effects still apply.</p>
{#each cardHints(selected) as card}
<div class="research-source-row">
<button class="secondary research-source" disabled={$session.pending}
title={card.description} onclick={() => controller.playContextualCard(card.id, 'research')}>
<span><Layers size={15} />Use {printedCardName(card.name)}{#if card.name === 'Synergies'}<span>· 2 advances in this category</span>{/if}</span>
<span class="research-source-cost">
{card.freeResearch ? 'No research resource cost' : 'Pay research cost next'}
{#if Object.values(card.cost).some(Boolean)}<ResourceAmount pile={card.cost} compact />{/if}
· {card.free ? 'Free action' : '1 action'}
</span>
</button>
<button class="icon-button" aria-label={`Details of ${printedCardName(card.name)}`}
onclick={() => cardReference = card}><Info size={16} /></button>
</div>
{/each}
{#each abilityHints(selected) as ability}
<button class="secondary research-source" disabled={$session.pending}
title={ability.description} onclick={() => controller.submit(ability.action, ability.cost)}>
<span><Lightbulb size={15} />Use {ability.name}</span>
<span class="research-source-cost">
{ability.freeResearch ? 'No research resource cost' : 'Pay research cost next'}
{#if ability.cost && Object.values(ability.cost).some(Boolean)}<ResourceAmount pile={ability.cost} compact />{/if}
· {ability.free ? 'Free action' : '1 action'}
</span>
</button>
{/each}
</section>
{/if}
{#if $session.error && !reference}<p class="inline-error" role="alert">{$session.error}</p>{/if}
</div>
{#if !reference && !$session.playback}<div class="research-payment" class:early-payment={!!early}>
@ -647,4 +693,13 @@
.research-card-hint { display: flex; align-items: center; gap: .4rem; padding: .35rem .6rem; border-top: 1px solid var(--border); }
.research-card-hint .research-advance-link { display: flex; align-items: center; gap: .35rem; text-align: left; font-size: .8rem; }
.research-card-hint .icon-button { flex-shrink: 0; }
.research-card-hint small { display: block; color: var(--muted); font-size: .7rem; }
.research-alternatives { margin-top: .7rem; padding: .65rem; border: 1px solid var(--line); border-left: 3px solid var(--accent); border-radius: 5px; background: var(--paper); }
.research-alternatives > strong { font-size: .85rem; }
.research-alternatives > p { margin: .25rem 0 .5rem; }
.research-source-row { display: flex; align-items: center; gap: .35rem; }
.research-source-row .icon-button { flex-shrink: 0; }
.research-source { display: flex; flex: 1; flex-direction: column; align-items: flex-start; gap: .3rem; margin-top: .3rem; min-width: 0; width: 100%; text-align: left; white-space: normal; }
.research-source > span { display: flex; align-items: center; flex-wrap: wrap; gap: .3rem; }
.research-source .research-source-cost { font-size: .72rem; font-weight: normal; }
</style>

View file

@ -2,6 +2,8 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { handCardDescription } from './card-text.ts';
import { canCancelAbility } from './decision-controls.ts';
import { journal } from './model.ts';
import type { View } from './types.ts';
const engine = createRequire(import.meta.url)('../.engine/server.js');
@ -23,7 +25,7 @@ async function calendar(event = 'Great Merchant', culture = 2) {
game.incidents_left = [eventId, ...game.incidents_left.filter((id: number) => id !== eventId)];
state = JSON.stringify(game);
const action = view(state, seat).specialActions!.find((action) => action.name === 'Calendar')!.action;
return { state: move(state, action), seat, eventId, actionsLeft: game.actions_left };
return { state: move(state, action), before: state, action, seat, eventId, actionsLeft: game.actions_left };
}
function choose(state: string, seat: number, payment: object) {
@ -33,6 +35,79 @@ function choose(state: string, seat: number, payment: object) {
return move(state, action, seat);
}
test('Calendar look-only previews can be cancelled or kept without growing logs, board history or clocks', async () => {
const { before, action, seat } = await calendar();
const original = JSON.parse(before);
const length = engine.logLength(before);
const clock = engine.timeIncrements(before);
const entries = journal(original);
let state = before;
for (let i = 0; i < 50; i++) {
state = move(state, action, seat);
assert.equal(engine.isLiveUpdate(state), true);
assert.equal(engine.logLength(state), length);
assert.equal(view(state, seat).canUndo, true);
assert.equal(canCancelAbility(JSON.parse(engine.stripSecret(state, seat)), view(state, seat)), true);
assert.equal(canCancelAbility(JSON.parse(engine.stripSecret(state, 1 - seat)), view(state, 1 - seat)), false);
assert.deepEqual(engine.logSlice(state, { start: length, player: seat }), []);
assert.deepEqual(journal(JSON.parse(state)), entries, 'unvalidated Calendar does not appear in the journal');
// Both the existing keep button and the generic Cancel/Undo close the preview.
state = i % 2 ? move(state, 'Undo', seat) : choose(state, seat, {});
const closed = JSON.parse(state);
assert.equal(engine.isLiveUpdate(state), true);
assert.equal(engine.logLength(state), length);
assert.ok(!view(state, seat).decision);
assert.deepEqual(closed.log, original.log, 'raw saved actions do not grow either');
assert.deepEqual(closed.board_history, original.board_history);
assert.deepEqual(closed.incidents_left, original.incidents_left);
assert.equal(closed.rng, original.rng);
assert.equal(closed.actions_left, original.actions_left);
assert.deepEqual(closed.players[seat].resources, original.players[seat].resources);
assert.deepEqual(engine.timeIncrements(state), clock);
assert.deepEqual(engine.logSlice(state, { start: length, player: seat }), []);
}
});
test('Calendar cancellation works for ordinary events and with no culture, while invalid responses cannot close it', async () => {
for (const event of ['Great Scientist', 'Famine']) {
const { state, seat, before } = await calendar(event, 0);
const game = JSON.parse(engine.stripSecret(state, seat));
assert.equal(canCancelAbility(game, view(state, seat)), true);
assert.throws(() => move(state, 'Undo', 1 - seat));
for (const payments of [[], [{ culture_tokens: 1 }], [{ food: 1 }], [{}, {}]]) {
assert.throws(() => move(state, { Response: { Payment: payments } }, seat));
}
const closed = move(state, 'Undo', seat);
assert.equal(engine.logLength(closed), engine.logLength(before));
assert.ok(!view(closed, seat).decision);
assert.deepEqual(engine.timeIncrements(closed), engine.timeIncrements(before));
}
});
test('Calendar paid burial is recorded, undoable, and sealed by a subsequent preview', async () => {
const { before, state, action, seat } = await calendar();
const original = JSON.parse(before);
const buried = choose(state, seat, { culture_tokens: 1 });
assert.equal(engine.isLiveUpdate(buried), false);
assert.equal(engine.logLength(buried), engine.logLength(before) + 2);
assert.equal(engine.logSlice(buried, { start: engine.logLength(before), player: seat }).length, 2);
assert.equal(view(buried, seat).canUndo, true);
const restored = move(buried, 'Undo', seat);
assert.deepEqual(JSON.parse(restored).incidents_left, original.incidents_left);
assert.deepEqual(JSON.parse(restored).players[seat].resources, original.players[seat].resources);
assert.equal(view(restored, seat).canRedo, true);
const redone = move(restored, 'Redo', seat);
assert.deepEqual(JSON.parse(redone).incidents_left, JSON.parse(buried).incidents_left);
assert.deepEqual(engine.timeIncrements(redone), engine.timeIncrements(buried));
const peekedAgain = move(buried, action, seat);
const closed = move(peekedAgain, 'Undo', seat);
assert.equal(engine.logLength(closed), engine.logLength(buried));
assert.deepEqual(JSON.parse(closed).incidents_left, JSON.parse(buried).incidents_left);
assert.deepEqual(JSON.parse(closed).players[seat].resources, JSON.parse(buried).players[seat].resources);
assert.equal(view(closed, seat).canUndo, false, 'learning the new top cannot refund the previous burial');
assert.throws(() => move(closed, 'Undo', seat));
});
test('Calendar structures Great Merchant event, acquisition and civil effect without triggering the event', async () => {
const { state, seat } = await calendar();
const decision = view(state, seat).decision!;

View file

@ -20,11 +20,18 @@ const suggestions: Record<string, { context: CardContext; benefit: string }> = {
export function contextualCards(view: View | null, context: CardContext) {
if (!view?.canPlay) return [];
return (view.actionCards ?? []).flatMap((card: ActionCard) => {
const suggestion = suggestions[card.name];
// Engine-declared targets cover Great Persons without guessing from rules
// text. Empty targets must not advertise a card whose secondary effect is
// playable but whose research is not.
const suggestion = suggestions[card.name] ??
(card.researchAdvances?.length ? {
context: 'research' as const,
benefit: card.freeResearch ? 'No research resource cost' : 'Gain an advance',
} : undefined);
const matches =
suggestion?.context === context ||
(context === 'after-battle' && (card.name === 'Great Ideas' || card.name === 'Hero General'));
return card.action && suggestion && matches ? [{ card, benefit: suggestion.benefit }] : [];
return card.action && !card.reason && suggestion && matches ? [{ card, benefit: suggestion.benefit }] : [];
});
}

View file

@ -27,6 +27,7 @@ import { happinessTargets } from './happiness';
import { UndoPreview } from './undo-preview';
import { fingerprint, isTrap, predictMove, predictUndo } from './prediction';
import {
calendarDecision,
researchDecision,
mapDecisionOptions,
mapDecisionIndex,
@ -1953,6 +1954,9 @@ export class Controller {
return null;
try {
if (move === 'Undo') {
// Closing Calendar does not rewind the committed log. An older local
// snapshot could otherwise incorrectly undo the action before the peek.
if (calendarDecision(s.game)) return null;
// Undo patches are stripped from the browser's state: restore the
// position this seat was shown one step earlier on the same branch.
const previous = this.undoPreview.previous(s.game, s.view);

View file

@ -72,9 +72,18 @@ export function toggleDecisionSelection(decision: Decision, selected: number[],
return selected.length < decision.max ? [...selected, index] : selected;
}
/** Calendar may have an uncommitted prompt without an action-log entry. */
export function calendarDecision(game: Game | null): boolean {
const type = game?.events?.at(-1)?.event_type;
if (!type || typeof type !== 'object') return false;
const custom = type.CustomAction;
return !!custom && typeof custom === 'object' && 'action' in custom && custom.action === 'Calendar';
}
/** Cancel an initial ability prompt or refund a pending government-change payment. */
export function canCancelAbility(game: Game | null, view: View | null): boolean {
if (!game || !view?.decision || !view.canUndo) return false;
if (calendarDecision(game)) return true;
const governmentChoice = view.decision.options.some((option) =>
option.value && typeof option.value === 'object' && 'new_government' in option.value);
if (governmentChoice) return true; // Undo refunds the optional government-change payment.

View file

@ -354,6 +354,19 @@ test('research graph has valid prerequisites and setup summaries retain historic
);
});
test('empty live log deltas and update notifications fetch authoritative state for Calendar previews', () => {
// The real viewer supplies onState, not custom onLog/onUpdate handlers.
const client = createViewer<string, string>({ onState() {} });
let refreshes = 0;
client.emitter.on('fetchState', () => { refreshes++; });
try {
client.emitter.emit('gamelog', { start: 4, data: [] });
assert.equal(refreshes, 1, 'an unchanged log still refreshes the private prompt');
client.emitter.emit('state:updated');
assert.equal(refreshes, 2, 'same-player live updates also refresh on websocket notification');
} finally { client.destroy(); }
});
test('BGS lifecycle, chat acknowledgements, journal, and cleanup', async () => {
const chat = new ChatController({ readDelayMs: 0 });
let renders = 0;

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Civil effekt",
"Keep on top": "Behold øverst i bunken",
"Put at the bottom": "Læg nederst i bunken",
"Preview only. This event has not been triggered.": "Kun en forhåndsvisning. Denne begivenhed er endnu ikke udløst."
"Preview only. This event has not been triggered.": "Kun en forhåndsvisning. Denne begivenhed er endnu ikke udløst.",
"Invalid Calendar preview": "Ugyldig forhåndsvisning for Kalender",
"Invalid Calendar payment": "Ugyldig betaling for Kalender",
"Calendar is waiting for a response": "Kalender afventer et svar",
"Alternative research available": "En anden forskningsmulighed er tilgængelig",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Brug et kort eller en evne nedenfor i stedet for normal forskning. Dets egne omkostninger og effekter gælder stadig.",
"No research resource cost": "Ingen ressourceomkostning for forskning"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Ziviler Effekt",
"Keep on top": "Oben auf dem Stapel lassen",
"Put at the bottom": "Unter den Stapel legen",
"Preview only. This event has not been triggered.": "Nur eine Vorschau. Dieses Ereignis wurde noch nicht ausgelöst."
"Preview only. This event has not been triggered.": "Nur eine Vorschau. Dieses Ereignis wurde noch nicht ausgelöst.",
"Invalid Calendar preview": "Ungültige Kalendervorschau",
"Invalid Calendar payment": "Ungültige Zahlung für Kalender",
"Calendar is waiting for a response": "Kalender wartet auf eine Antwort",
"Alternative research available": "Andere Forschungsmöglichkeit verfügbar",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Nutze eine der folgenden Karten oder Fähigkeiten statt der normalen Forschung. Ihre eigenen Kosten und Effekte gelten weiterhin.",
"No research resource cost": "Keine Ressourcenkosten für die Forschung"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Πολιτική επίδραση",
"Keep on top": "Διατήρηση στην κορυφή",
"Put at the bottom": "Τοποθέτηση στο κάτω μέρος",
"Preview only. This event has not been triggered.": "Μόνο προεπισκόπηση. Αυτό το γεγονός δεν έχει ακόμη ενεργοποιηθεί."
"Preview only. This event has not been triggered.": "Μόνο προεπισκόπηση. Αυτό το γεγονός δεν έχει ακόμη ενεργοποιηθεί.",
"Invalid Calendar preview": "Μη έγκυρη προεπισκόπηση Ημερολογίου",
"Invalid Calendar payment": "Μη έγκυρη πληρωμή για το Ημερολόγιο",
"Calendar is waiting for a response": "Το Ημερολόγιο περιμένει απάντηση",
"Alternative research available": "Διαθέσιμος εναλλακτικός τρόπος έρευνας",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Χρησιμοποιήστε μία από τις παρακάτω κάρτες ή ικανότητες αντί για κανονική έρευνα. Το κόστος και οι επιδράσεις της εξακολουθούν να ισχύουν.",
"No research resource cost": "Έρευνα χωρίς κόστος πόρων"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Civil effect",
"Keep on top": "Keep on top",
"Put at the bottom": "Put at the bottom",
"Preview only. This event has not been triggered.": "Preview only. This event has not been triggered."
"Preview only. This event has not been triggered.": "Preview only. This event has not been triggered.",
"Invalid Calendar preview": "Invalid Calendar preview",
"Invalid Calendar payment": "Invalid Calendar payment",
"Calendar is waiting for a response": "Calendar is waiting for a response",
"Alternative research available": "Alternative research available",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Use a card or ability below instead of normal research. Its own costs and effects still apply.",
"No research resource cost": "No research resource cost"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "اثر غیرنظامی",
"Keep on top": "بالای دسته نگه دار",
"Put at the bottom": "زیر دسته قرار بده",
"Preview only. This event has not been triggered.": "فقط پیش‌نمایش است. این رویداد هنوز فعال نشده است."
"Preview only. This event has not been triggered.": "فقط پیش‌نمایش است. این رویداد هنوز فعال نشده است.",
"Invalid Calendar preview": "پیش‌نمایش تقویم نامعتبر است",
"Invalid Calendar payment": "پرداخت تقویم نامعتبر است",
"Calendar is waiting for a response": "تقویم منتظر پاسخ است",
"Alternative research available": "روش دیگری برای پژوهش در دسترس است",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "به‌جای پژوهش معمول، از یکی از کارت‌ها یا توانایی‌های زیر استفاده کنید. هزینه‌ها و اثرهای خود آن همچنان اعمال می‌شوند.",
"No research resource cost": "پژوهش بدون هزینهٔ منابع"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Effet civil",
"Keep on top": "Garder au-dessus du paquet",
"Put at the bottom": "Placer sous le paquet",
"Preview only. This event has not been triggered.": "Aperçu uniquement : cet événement n'est pas encore déclenché."
"Preview only. This event has not been triggered.": "Aperçu uniquement : cet événement n'est pas encore déclenché.",
"Invalid Calendar preview": "Aperçu de Calendrier invalide",
"Invalid Calendar payment": "Paiement de Calendrier invalide",
"Calendar is waiting for a response": "Calendrier attend une réponse",
"Alternative research available": "Autre moyen d'obtenir ce progrès",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Vous pouvez utiliser une carte ou une capacité ci-dessous au lieu de la recherche normale. Ses coûts et ses effets s'appliquent.",
"No research resource cost": "Recherche sans coût en ressources"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "नागरिक प्रभाव",
"Keep on top": "ऊपर रखें",
"Put at the bottom": "सबसे नीचे रखें",
"Preview only. This event has not been triggered.": "यह केवल पूर्वावलोकन है। यह घटना अभी शुरू नहीं हुई है।"
"Preview only. This event has not been triggered.": "यह केवल पूर्वावलोकन है। यह घटना अभी शुरू नहीं हुई है।",
"Invalid Calendar preview": "कैलेंडर का अमान्य पूर्वावलोकन",
"Invalid Calendar payment": "कैलेंडर का अमान्य भुगतान",
"Calendar is waiting for a response": "कैलेंडर उत्तर की प्रतीक्षा कर रहा है",
"Alternative research available": "शोध का वैकल्पिक तरीका उपलब्ध है",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "सामान्य शोध के बजाय नीचे दिया गया कार्ड या क्षमता इस्तेमाल करें। उसके अपने खर्च और प्रभाव फिर भी लागू होंगे।",
"No research resource cost": "शोध के लिए संसाधन खर्च नहीं"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Effetto civile",
"Keep on top": "Lascia in cima al mazzo",
"Put at the bottom": "Metti in fondo al mazzo",
"Preview only. This event has not been triggered.": "Solo un'anteprima. Questo evento non è ancora stato attivato."
"Preview only. This event has not been triggered.": "Solo un'anteprima. Questo evento non è ancora stato attivato.",
"Invalid Calendar preview": "Anteprima del Calendario non valida",
"Invalid Calendar payment": "Pagamento del Calendario non valido",
"Calendar is waiting for a response": "Il Calendario attende una risposta",
"Alternative research available": "È disponibile un altro modo di ricercare",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Usa una carta o un'abilità qui sotto invece della ricerca normale. I suoi costi ed effetti si applicano comunque.",
"No research resource cost": "Ricerca senza costo in risorse"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "민간 효과",
"Keep on top": "덱 맨 위에 유지",
"Put at the bottom": "덱 맨 아래로 보내기",
"Preview only. This event has not been triggered.": "미리보기입니다. 이 이벤트는 아직 발생하지 않았습니다."
"Preview only. This event has not been triggered.": "미리보기입니다. 이 이벤트는 아직 발생하지 않았습니다.",
"Invalid Calendar preview": "잘못된 달력 미리보기",
"Invalid Calendar payment": "잘못된 달력 비용 지불",
"Calendar is waiting for a response": "달력이 응답을 기다리고 있습니다",
"Alternative research available": "다른 연구 방법 사용 가능",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "일반 연구 대신 아래 카드나 능력을 사용하세요. 해당 카드나 능력의 비용과 효과는 그대로 적용됩니다.",
"No research resource cost": "연구 자원 비용 없음"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Civiel effect",
"Keep on top": "Boven op de stapel laten",
"Put at the bottom": "Onder op de stapel leggen",
"Preview only. This event has not been triggered.": "Alleen een voorbeeld. Deze gebeurtenis is nog niet geactiveerd."
"Preview only. This event has not been triggered.": "Alleen een voorbeeld. Deze gebeurtenis is nog niet geactiveerd.",
"Invalid Calendar preview": "Ongeldig Kalendervoorbeeld",
"Invalid Calendar payment": "Ongeldige betaling voor Kalender",
"Calendar is waiting for a response": "Kalender wacht op een antwoord",
"Alternative research available": "Andere onderzoeksmogelijkheid beschikbaar",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Gebruik een kaart of vaardigheid hieronder in plaats van normaal onderzoek. De eigen kosten en effecten blijven gelden.",
"No research resource cost": "Geen grondstofkosten voor onderzoek"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Efekt cywilny",
"Keep on top": "Zostaw na wierzchu",
"Put at the bottom": "Przełóż na spód",
"Preview only. This event has not been triggered.": "To tylko podgląd. Wydarzenie nie zostało jeszcze wywołane."
"Preview only. This event has not been triggered.": "To tylko podgląd. Wydarzenie nie zostało jeszcze wywołane.",
"Invalid Calendar preview": "Nieprawidłowy podgląd Kalendarza",
"Invalid Calendar payment": "Nieprawidłowa opłata za Kalendarz",
"Calendar is waiting for a response": "Kalendarz czeka na odpowiedź",
"Alternative research available": "Dostępny inny sposób badań",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Użyj poniższej karty lub zdolności zamiast zwykłych badań. Jej własne koszty i efekty nadal obowiązują.",
"No research resource cost": "Badania bez kosztu w zasobach"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Efeito civil",
"Keep on top": "Manter no topo",
"Put at the bottom": "Colocar no fundo",
"Preview only. This event has not been triggered.": "Apenas uma prévia. Este evento ainda não foi desencadeado."
"Preview only. This event has not been triggered.": "Apenas uma prévia. Este evento ainda não foi desencadeado.",
"Invalid Calendar preview": "Prévia inválida do Calendário",
"Invalid Calendar payment": "Pagamento inválido do Calendário",
"Calendar is waiting for a response": "O Calendário está aguardando uma resposta",
"Alternative research available": "Alternativa de pesquisa disponível",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Use uma carta ou habilidade abaixo em vez da pesquisa normal. Seus próprios custos e efeitos continuam se aplicando.",
"No research resource cost": "Pesquisa sem custo em recursos"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Efect civil",
"Keep on top": "Păstrează deasupra teancului",
"Put at the bottom": "Pune sub teanc",
"Preview only. This event has not been triggered.": "Doar previzualizare. Acest eveniment nu a fost încă declanșat."
"Preview only. This event has not been triggered.": "Doar previzualizare. Acest eveniment nu a fost încă declanșat.",
"Invalid Calendar preview": "Previzualizare nevalidă pentru Calendar",
"Invalid Calendar payment": "Plată nevalidă pentru Calendar",
"Calendar is waiting for a response": "Calendar așteaptă un răspuns",
"Alternative research available": "Alternativă de cercetare disponibilă",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Folosește o carte sau o abilitate de mai jos în locul cercetării normale. Costurile și efectele proprii se aplică în continuare.",
"No research resource cost": "Cercetare fără cost în resurse"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Мирный эффект",
"Keep on top": "Оставить сверху колоды",
"Put at the bottom": "Положить под колоду",
"Preview only. This event has not been triggered.": "Только предварительный просмотр. Это событие ещё не произошло."
"Preview only. This event has not been triggered.": "Только предварительный просмотр. Это событие ещё не произошло.",
"Invalid Calendar preview": "Недопустимый просмотр Календаря",
"Invalid Calendar payment": "Недопустимая оплата Календаря",
"Calendar is waiting for a response": "Календарь ожидает ответа",
"Alternative research available": "Доступен другой способ исследования",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Используйте указанную ниже карту или способность вместо обычного исследования. Её собственные затраты и эффекты по-прежнему применяются.",
"No research resource cost": "Исследование без затрат ресурсов"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "Hiệu ứng dân sự",
"Keep on top": "Giữ trên cùng chồng bài",
"Put at the bottom": "Đặt xuống dưới cùng chồng bài",
"Preview only. This event has not been triggered.": "Chỉ là xem trước. Sự kiện này chưa được kích hoạt."
"Preview only. This event has not been triggered.": "Chỉ là xem trước. Sự kiện này chưa được kích hoạt.",
"Invalid Calendar preview": "Xem trước Lịch không hợp lệ",
"Invalid Calendar payment": "Thanh toán cho Lịch không hợp lệ",
"Calendar is waiting for a response": "Lịch đang chờ phản hồi",
"Alternative research available": "Có cách nghiên cứu khác",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "Dùng một lá bài hoặc khả năng bên dưới thay cho nghiên cứu thông thường. Chi phí và hiệu ứng riêng của nó vẫn áp dụng.",
"No research resource cost": "Nghiên cứu không tốn tài nguyên"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "内政效果",
"Keep on top": "保留在牌堆顶",
"Put at the bottom": "放到牌堆底",
"Preview only. This event has not been triggered.": "仅供预览。此事件尚未触发。"
"Preview only. This event has not been triggered.": "仅供预览。此事件尚未触发。",
"Invalid Calendar preview": "无效的历法预览",
"Invalid Calendar payment": "无效的历法支付",
"Calendar is waiting for a response": "历法正在等待回应",
"Alternative research available": "有其他研究方式可用",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "可以使用下方的卡牌或能力代替普通研究。该卡牌或能力自身的费用与效果仍然适用。",
"No research resource cost": "研究无需支付资源"
}

View file

@ -5238,5 +5238,11 @@
"Civil effect": "內政效果",
"Keep on top": "保留在牌堆頂",
"Put at the bottom": "放到牌堆底",
"Preview only. This event has not been triggered.": "僅供預覽。此事件尚未觸發。"
"Preview only. This event has not been triggered.": "僅供預覽。此事件尚未觸發。",
"Invalid Calendar preview": "無效的曆法預覽",
"Invalid Calendar payment": "無效的曆法支付",
"Calendar is waiting for a response": "曆法正在等待回應",
"Alternative research available": "有其他研究方式可用",
"Use a card or ability below instead of normal research. Its own costs and effects still apply.": "可以使用下方的卡牌或能力代替一般研究。該卡牌或能力本身的費用與效果仍然適用。",
"No research resource cost": "研究無需支付資源"
}

View file

@ -516,6 +516,54 @@ test('rolls and hidden draws wait even when sampled visible outcomes could coinc
}
});
test('Calendar never predicts a private top-card preview even if sampled cards could coincide', () => {
let executions = 0;
const raw = JSON.stringify({ board_history: { id: 'calendar', frames: [] } });
const simulation = { tryMove: () => { executions++; return raw; }, stripSecret: () => raw };
assert.deepEqual(predictMove(simulation, raw, { Playing: { Custom: { action: 'Calendar' } } }, 0),
{ reason: 'unsupported' });
assert.equal(executions, 0, 'do not inspect a shuffled local deck at all');
});
test('Calendar Cancel never optimistically undoes the committed move before the preview', async () => {
let raw = await engine.init(2, [], { civilization: 'ChooseCivilization' }, 'calendar-prediction', {});
for (const civilization of ['Maya', 'Rome']) {
raw = move(raw, { ChooseCivilization: civilization }, engine.currentPlayer(raw));
}
const seat = engine.currentPlayer(raw);
const initial = JSON.parse(raw);
initial.players[seat].advances.push('Fishing', 'Navigation', 'Cartography', 'Astronomy');
initial.players[seat].resources.food = 0;
raw = JSON.stringify(initial);
const city = initial.players[seat].cities[0].position;
const collection = { Playing: { Collect: { city_position: city,
collections: [{ position: city, pile: { food: 1 }, times: 1 }], action_type: 'Collect' } } };
const app = harness();
try {
app.controller.setPlayer(seat);
await app.controller.load(strip(raw, seat));
raw = move(raw, collection, seat);
await app.controller.load(strip(raw, seat));
const collected = structuredClone(app.session().game!);
const calendar = app.session().view!.specialActions!.find(a => a.name === 'Calendar')!.action;
const pending = move(raw, calendar, seat);
assert.equal(engine.logLength(pending), engine.logLength(raw));
await app.controller.load(strip(pending, seat));
assert.equal(app.session().view!.canUndo, true);
app.controller.submit('Undo');
assert.deepEqual(app.sent.map(action => JSON.parse(action)), ['Undo']);
assert.equal(app.session().game!.actions_left, collected.actions_left);
assert.deepEqual(app.session().game!.players[seat].resources, collected.players[seat].resources);
assert.equal(app.session().game!.log_index, collected.log_index);
const closed = move(pending, 'Undo', seat);
await app.controller.load(strip(closed, seat));
assert.equal(app.session().pending, false);
assert.ok(!app.session().view!.decision);
assert.equal(app.session().view!.canUndo, false);
assert.deepEqual(app.session().game!.players[seat].resources, collected.players[seat].resources);
} finally { app.close(); }
});
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'),

View file

@ -96,6 +96,10 @@ function excluded(raw: string, move: unknown, seat: number) {
if (next === game.starting_player_index) return true;
}
if ('ChooseCivilization' in move) return true;
// Calendar's tentative look does not change the authoritative RNG or pile.
// Two samples can coincidentally reveal the same card, so always wait for the
// owner-only server prompt rather than previewing the shuffled browser deck.
if ((move as Json).Playing?.Custom?.action === 'Calendar') return true;
const destination = (move as Json).Movement?.Move?.destination;
if (!destination) return false;
// Capturing undefended settlers or cities is deterministic and stays eligible.

View file

@ -94,6 +94,12 @@ export function aqueductResearch(view: View | null | undefined, advance: Advance
}
export function researchCardHints(view: View | null | undefined, advance: AdvanceView) {
if (advance.owned) return [];
return (view?.actionCards ?? []).filter((card) => card.action && card.researchAdvances?.includes(advance.id));
if (!view?.canPlay || advance.owned) return [];
return (view.actionCards ?? []).filter((card) => !card.reason && card.action && card.researchAdvances?.includes(advance.id));
}
/** These offers belong only to the viewing seat, never to public opponent leaders. */
export function researchAbilityHints(view: View | null | undefined, advance: AdvanceView) {
if (!view?.canPlay || advance.owned) return [];
return (view.specialActions ?? []).filter((offer) => !offer.reason && offer.action && offer.researchAdvances?.includes(advance.id));
}

View file

@ -0,0 +1,189 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import { researchAbilityHints, researchCardHints } from './research-links.ts';
import { contextualCards } from './contextual-cards.ts';
import type { AdvanceView, View } from './types.ts';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const npcs = JSON.parse(await engine.init(2, [], {}, 'research-sources', {})).players.slice(2);
function fixture(name = 'action_cards/synergies') {
const g = JSON.parse(readFileSync(new URL(`../../server/tests/test_games/${name}.json`, import.meta.url), 'utf8'));
for (const npc of npcs) if (!g.players.some((p: any) => p.civilization === npc.civilization)) g.players.push({ ...npc, id: g.players.length });
g.players[0].incident_tokens = 3;
g.players[0].action_cards = [];
return g;
}
const view = (g: any, seat: number | null = 0): View => JSON.parse(engine.webView(engine.stripSecret(JSON.stringify(g), seat), seat));
const move = (g: any, action: any) => JSON.parse(engine.tryMove(JSON.stringify(g), JSON.stringify(action), 0));
const advance = (v: View, id: string) => v.advances.find((a) => a.id === id)!;
const card = (v: View, id: number) => v.actionCards!.find((c) => c.id === id)!;
const targets = (v: View) => v.decision!.options.map((o) => o.value as string).sort();
const roots = ['Farming', 'Mining', 'Fishing', 'Arts', 'Myths', 'Writing', 'Math', 'Tactics', 'Bartering', 'Voting'];
test('research helpers use only usable own-seat metadata, never names or public opponent hands', () => {
const a = { id: 'Medicine', owned: false } as AdvanceView;
const source = { id: 122, name: 'localized name', action: { Playing: { ActionCard: 122 } }, cost: {}, freeResearch: true, researchAdvances: ['Medicine'] };
const v = { canPlay: true, actionCards: [source], specialActions: [{ ...source, id: undefined }] } as unknown as View;
assert.equal(researchCardHints(v, a).length, 1);
assert.equal(researchAbilityHints(v, a).length, 1);
assert.equal(contextualCards(v, 'research')[0].card.id, 122);
assert.equal(contextualCards(v, 'build').length, 0);
for (const change of [{ canPlay: false }, { actionCards: [], specialActions: [] }]) {
assert.deepEqual(researchCardHints({ ...v, ...change }, a), []);
assert.deepEqual(researchAbilityHints({ ...v, ...change }, a), []);
}
for (const change of [{ action: null }, { reason: 'Already used' }, { researchAdvances: [] }]) {
assert.deepEqual(researchCardHints({ ...v, actionCards: [{ ...source, ...change }] } as unknown as View, a), []);
assert.deepEqual(researchAbilityHints({ ...v, specialActions: [{ ...source, ...change }] } as unknown as View, a), []);
}
assert.deepEqual(researchCardHints(v, { ...a, owned: true }), []);
assert.deepEqual(researchAbilityHints(v, { ...a, owned: true }), []);
assert.deepEqual(researchCardHints(v, { ...a, id: 'Metallurgy' }), []);
});
test('all ten research Great Persons expose exactly their actual free-advance choices', () => {
for (const id of [118, 119, 120, 121, 122, 123, 124, 125, 126, 156]) {
const g = fixture();
g.players[0].advances = roots;
g.players[0].action_cards = [id];
const v = view(g), c = card(v, id);
assert(c.action, `${id} should be playable`);
assert(c.freeResearch);
assert(c.researchAdvances!.length > 1, `${id} should offer a choice`);
assert.deepEqual([...c.researchAdvances!].sort(), targets(view(move(g, c.action))), `${id} exact choices`);
for (const id of c.researchAdvances!) assert(researchCardHints(v, advance(v, id)).includes(c));
}
});
test('Scientist respects prerequisites, ownership, actions, pending decisions, and depleted groups', () => {
const g = fixture();
g.players[0].action_cards = [122];
assert.deepEqual(card(view(g), 122).researchAdvances, ['Math']);
g.players[0].advances.push('Math');
let v = view(g);
assert(researchCardHints(v, advance(v, 'Medicine')).length);
g.players[0].resources = {};
v = view(g);
assert.equal(advance(v, 'Medicine').action, null);
assert(researchCardHints(v, advance(v, 'Medicine')).length, 'free source remains useful without normal resources');
g.actions_left = 0;
assert.deepEqual(card(view(g), 122).researchAdvances, []);
g.actions_left = 3;
const pending = move(g, card(view(g), 122).action);
assert.equal(view(pending).canPlay, false);
assert.deepEqual(researchCardHints(view(pending), advance(view(pending), 'Medicine')), []);
g.players[0].advances.push('Medicine', 'Astronomy');
assert.deepEqual(card(view(g), 122).researchAdvances, ['Metallurgy'], 'singleton still advertised');
g.players[0].advances.push('Metallurgy');
const exhausted = card(view(g), 122);
assert(exhausted.action, 'secondary effect is still playable');
assert.deepEqual(exhausted.researchAdvances, []);
assert.deepEqual(contextualCards(view(g), 'research'), []);
});
test('paid research and an explicitly chosen Scientist remain separate actions', () => {
const g = fixture();
g.players[0].advances.push('Math');
g.players[0].action_cards = [122];
const v = view(g), medicine = advance(v, 'Medicine');
const paid = move(g, medicine.action);
assert(paid.players[0].advances.includes('Medicine'));
assert(paid.players[0].action_cards.includes(122));
assert.equal(paid.actions_left, g.actions_left - 1);
const requested = move(g, card(v, 122).action), decision = view(requested).decision!;
assert.equal(decision.advanceMode, 'free');
const selected = move(requested, advance(view(requested), 'Medicine').action);
assert(selected.players[0].advances.includes('Medicine'));
assert(!selected.players[0].action_cards.includes(122));
assert.equal(selected.players[0].resources.food, g.players[0].resources.food);
assert.equal(selected.players[0].resources.gold, g.players[0].resources.gold);
assert.equal(selected.players[0].resources.ideas, g.players[0].resources.ideas + 1);
assert.equal(selected.actions_left, g.actions_left - 1);
});
test('opponent and spectator views do not expose private research cards', () => {
const g = fixture();
g.players[0].action_cards = [122, 125, 124];
g.players[1].action_cards = [];
for (const seat of [1, null]) {
const v = view(g, seat);
assert.deepEqual(v.actionCards ?? [], []);
assert.deepEqual(contextualCards(v, 'research'), []);
for (const a of v.advances) assert.deepEqual(researchCardHints(v, a), []);
}
g.current_player_index = 1;
const ownWaiting = view(g);
assert(ownWaiting.actionCards!.every((c) => c.action === null && !c.researchAdvances?.length));
});
test('Shogunate free card allowance is respected and unavailable after once-per-turn use', () => {
const g = fixture();
g.players[0].civilization = 'Japan';
g.players[0].advances = [...roots];
g.players[0].action_cards = [122];
g.actions_left = 0;
const usable = card(view(g), 122);
assert(usable.action);
assert(usable.researchAdvances!.includes('Medicine'));
g.players[0].event_info = { 'Shogunate card': 'used' };
const used = card(view(g), 122);
assert.equal(used.action, null);
assert.deepEqual(used.researchAdvances, []);
});
const leaders = [
['Greece', 'Pericles', 'Master', 'Writing'],
['China', 'SunTzu', 'ArtOfWar', 'Tactics'],
['China', 'Wu', 'AgricultureEconomist', 'Farming'],
['Phoenicia', 'Hiram', 'Constructor', 'Mining'],
];
function leaderFixture(civilization: string, leader: string) {
const g = fixture('civilizations/greece/master');
g.players[0].civilization = civilization;
g.players[0].units[0].unit_type = { Leader: leader };
g.players[0].resources = { food: 6, mood_tokens: 3, culture_tokens: 3 };
return g;
}
const ability = (v: View, kind: string) => v.specialActions?.find((a) => (a.action as any).Playing?.Custom?.action === kind);
test('four research leaders expose exact choices only with a happy leader city, token, and action', () => {
for (const [civilization, leader, kind, root] of leaders) {
const g = leaderFixture(civilization, leader);
g.players[0].advances = [...new Set([...g.players[0].advances, root])];
const v = view(g), offer = ability(v, kind)!;
assert(offer, `${kind} available`);
assert(offer.freeResearch);
let requested = move(g, offer.action);
// Resolve the ability's token payment, not a research resource payment.
if (view(requested).decision?.fields.length) requested = move(requested, { Response: { Payment: [{ mood_tokens: 1 }] } });
assert.deepEqual([...offer.researchAdvances!].sort(), targets(view(requested)), kind);
assert(researchAbilityHints(v, advance(v, offer.researchAdvances![0])).includes(offer));
g.players[0].cities[0].mood_state = 'Neutral';
assert.equal(ability(view(g), kind), undefined, `${kind} needs happy city`);
g.players[0].cities[0].mood_state = 'Happy';
g.players[0].resources = {};
assert.equal(ability(view(g), kind), undefined, `${kind} needs token`);
g.players[0].resources = { mood_tokens: 3 };
g.actions_left = 0;
assert.equal(ability(view(g), kind), undefined, `${kind} needs action`);
}
});
test('Golden Age reserves its culture fee and advertises only affordable unstarted groups', () => {
const g = leaderFixture('India', 'SriGupta');
g.actions_left = 0;
const v = view(g), offer = ability(v, 'GoldenAge')!;
assert(offer && offer.free && !offer.freeResearch);
assert(offer.researchAdvances!.includes('Math'));
assert(!offer.researchAdvances!.includes('Storage'));
let requested = move(g, offer.action);
if (view(requested).decision?.fields.length) requested = move(requested, { Response: { Payment: [{ culture_tokens: 1 }] } });
assert.deepEqual([...offer.researchAdvances!].sort(), targets(view(requested)));
g.players[0].resources = { culture_tokens: 1 };
assert.equal(ability(view(g), 'GoldenAge'), undefined);
g.players[0].resources = { culture_tokens: 3, food: 6 };
g.players[0].cities[0].angry_activation = true;
assert.equal(ability(view(g), 'GoldenAge'), undefined);
});

View file

@ -302,6 +302,9 @@ export interface View {
actionCards?: ActionCard[];
unavailableSpecialActions?: View['specialActions'];
specialActions?: {
/** Legal permanent research targets for this source, supplied by the engine. */
researchAdvances?: string[];
freeResearch?: boolean;
reason?: string | null;
name: string;
description: string;
@ -688,6 +691,8 @@ export interface MoveDestination {
}
export interface ActionCard {
researchAdvances?: string[];
/** No research resource cost; the card's own action/token cost still applies. */
freeResearch?: boolean;
id: number;
name: string;
description: string;