Support current battle choice promises and persistent notices
Verify and publish checkpoint container / container (push) Successful in 11m42s

This commit is contained in:
Quintine committed 2026-11-16 21:49:48 +11:00
1 parent 77d02b3231
commit bd8377d87b
16 files changed
+684 -32

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { Children, isValidElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { ActionableNotice } from '../components/actionable-notice';
import { Button } from '../components/ui/button';
import { initialActionableNotices, updateActionableNotices } from '../lib/actionable-notices';
void test('distinct actionable messages stay queued until each Continue, while exact retries coalesce', () => {
let queue = initialActionableNotices;
const enqueue = (text: string) => { queue = updateActionableNotices(queue, {type:'enqueue',text}); };
const dismiss = (id: number) => { queue = updateActionableNotices(queue, {type:'dismiss',id}); };
enqueue('Your action may have completed. Check the refreshed table.');
const first = queue.items[0];
enqueue('Your action may have completed. Check the refreshed table.');
enqueue('Second faction added. Switch factions to make each ready.');
assert.deepEqual(queue.items.map(item => item.text), [
'Your action may have completed. Check the refreshed table.',
'Second faction added. Switch factions to make each ready.',
]);
const firstView = ActionableNotice({notice:first,onDismiss:dismiss}); assert.ok(firstView);
const html = renderToStaticMarkup(firstView);
assert.match(html, /Your action may have completed/);
assert.match(html, /Continue/);
assert.doesNotMatch(html, /Second faction added/);
const button = Children.toArray(firstView.props.children).filter(isValidElement).find(child => child.type === Button);
assert.ok(button);
(button.props as {onClick: () => void}).onClick();
assert.equal(queue.items[0].text, 'Second faction added. Switch factions to make each ready.');
(button.props as {onClick: () => void}).onClick();
assert.equal(queue.items.length, 1, 'A stale prior Continue cannot dismiss the next notice');
dismiss(queue.items[0].id);
assert.deepEqual(queue.items, []);
assert.equal(ActionableNotice({notice:null,onDismiss:dismiss}), null);
});
void test('retrying after explicit acknowledgement creates an independent notice identity', () => {
let queue = updateActionableNotices(initialActionableNotices, {type:'enqueue',text:'Reconnect required.'});
const old = queue.items[0];
queue = updateActionableNotices(queue, {type:'dismiss',id:old.id});
queue = updateActionableNotices(queue, {type:'enqueue',text:'Reconnect required.'});
assert.notEqual(queue.items[0].id, old.id);
queue = updateActionableNotices(queue, {type:'dismiss',id:old.id});
assert.equal(queue.items.length, 1);
queue = updateActionableNotices(queue, {type:'dismiss',id:queue.items[0].id});
const next = updateActionableNotices(queue, {type:'enqueue',text:'Another seat.'});
assert.ok(next.items[0].id > old.id);
assert.deepEqual(initialActionableNotices.items, [], 'The shared initial state was not mutated');
});
@@ -0,0 +1,193 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { applyAction, viewGame, type Action, type Game } from '../game/engine';
import { botActions } from '../game/bots';
import { DIFFICULTIES } from '../game/bot-profiles';
import type { TruthQuestion } from '../game/truthtrance';
import { createBattleTerritoryExplosionFixture } from './fixture-battle-territory-explosion';
const act = (game: Game, actor: string, action: Action) => applyAction(game, actor, action);
function player(game: Game, id: string) {
const seat = game.players.find(candidate => candidate.id === id); assert.ok(seat); return seat;
}
function inventory(game: Game) {
return [...game.deck, ...game.discard, ...game.players.flatMap(seat => seat.hand),
...(game.auction?.cards.slice(game.auction.index + Number(game.currentAuctionSale?.origin === 'normal')) ?? [])]
.map(card => card.id).sort();
}
function reject(game: Game, actor: string, action: Action) {
const before = structuredClone(game);
assert.throws(() => act(game, actor, action));
assert.deepEqual(game, before, 'A forbidden action must not alter its input');
}
/** A genuine public Basic three-faction setup and native movement yields a
* three-army fight in Imperial Basin. Only the existing physical Truthtrance
* and one already-held card are exchanged between their real zones after that
* native prefix; the closed original auctions and both physical card counts
* remain unchanged. No battle, force, wallet or order state is assigned. */
function source() {
const game = structuredClone(createBattleTerritoryExplosionFixture({advanced:false}).beforeFirst);
assert.equal(game.phase, 6); assert.ok(!game.battle && game.active);
const chooser = game.active, choices = viewGame(game, chooser).battleChoices.filter(choice => choice.chooser === chooser);
assert.ok(choices.length >= 2, 'The actual current chooser has multiple real battles');
const [chosen, alternate] = choices;
const target = (choice: typeof chosen) => choice.attacker === chooser ? choice.defender : choice.attacker;
const asker = game.players.find(seat => seat.id !== chooser)!.id;
const initial = inventory(game), hand = player(game, asker).hand;
let truth = hand.find(card => card.effect === 'truthtrance');
if (!truth) {
const replacement = hand[0]; assert.ok(replacement, 'The original dealt card supplies the conserved exchange');
const owner = game.players.find(seat => seat.id !== asker && seat.hand.some(card => card.effect === 'truthtrance'));
if (owner) {
const index = owner.hand.findIndex(card => card.effect === 'truthtrance');
truth = owner.hand[index]; owner.hand[index] = replacement;
} else {
const zone = [game.deck,game.discard].find(cards => cards.some(card => card.effect === 'truthtrance'));
assert.ok(zone, 'The original Truthtrance must be in an actual hand, deck or discard');
const index = zone.findIndex(card => card.effect === 'truthtrance');
truth = zone[index]; zone[index] = replacement;
}
hand[0] = truth;
}
assert.deepEqual(inventory(game), initial);
const event = viewGame(game, chooser).battleOrder?.event; assert.ok(event);
const desired: Action = {type:'chooseBattle',territory:chosen.territory,target:target(chosen)};
const other: Action = {type:'chooseBattle',territory:alternate.territory,target:target(alternate)};
assert.notDeepEqual(desired, other);
const question: TruthQuestion = {kind:'turnActions',target:chooser,turn:game.turn,mixed:{kind:'action',
action:{kind:'battleChoice',source:event,territory:chosen.territory,target:target(chosen)}}};
return {game,chooser,asker,truth:truth.id,event,desired,other,question,initial};
}
function ask(f: ReturnType<typeof source>, question: TruthQuestion = f.question,
input: Game = f.game, asker = f.asker, truth = f.truth): Game {
let game = act(input, asker, {type:'card',card:truth});
for (let count = 0; count < 8 && game.truthtrance?.stage === 'priority'; count++) {
const seat = game.players.find(candidate => !game.truthtrance!.passed.includes(candidate.id)); assert.ok(seat);
game = act(game, seat.id, {type:'truthPass'});
}
assert.equal(game.truthtrance?.stage, 'ask');
game = act(game, asker, {type:'truthAsk',question});
return game;
}
function choiceQuestion(f: ReturnType<typeof source>, kind: 'and' | 'or'): TruthQuestion {
const term = (action: Action) => ({kind:'action' as const, action:{kind:'battleChoice' as const,
source:f.event,territory:action.territory as string,target:action.target as string}});
return {kind:'turnActions',target:f.chooser,turn:f.game.turn,
mixed:{kind,terms:[term(f.desired),term(f.other)]}};
}
void test('a real Basic chooser Yes rejects another battle and follows its exact private guide', () => {
const f = source(), asked = ask(f);
const game = act(asked, f.chooser, {type:'truthAnswer',answer:'yes'});
reject(game, f.chooser, f.other);
const guide = viewGame(game, f.chooser).turnActionGuide; assert.ok(guide);
assert.equal(guide.action.type, 'chooseBattle');
assert.equal(guide.action.territory, f.desired.territory);
assert.equal(guide.action.target, f.desired.target);
assert.equal(guide.action.turnActionPromiseEvent, guide.event);
const chosen = act(game, f.chooser, guide.action);
assert.equal(chosen.battle?.territory, f.desired.territory);
assert.ok([chosen.battle?.attacker, chosen.battle?.defender].includes(f.desired.target as string));
assert.equal(chosen.turnActionPromises?.[0].fulfilled, true);
assert.deepEqual(inventory(chosen), f.initial);
});
void test('a real Basic chooser No forbids the named battle while preserving the other native choice', () => {
const f = source(), game = act(ask(f), f.chooser, {type:'truthAnswer',answer:'no'});
reject(game, f.chooser, f.desired);
const chosen = act(game, f.chooser, f.other);
assert.equal(chosen.battle?.territory, f.other.territory);
assert.ok([chosen.battle?.attacker, chosen.battle?.defender].includes(f.other.target as string));
assert.equal(chosen.turnActionPromises?.[0].fulfilled, true);
assert.deepEqual(inventory(chosen), f.initial);
});
void test('all four minimal bots answer and execute the real promised battle choice', () => {
const f = source(), asked = ask(f);
for (const difficulty of DIFFICULTIES) {
const answering = viewGame(asked, f.chooser);
answering.players.find(seat => seat.id === f.chooser)!.bot = difficulty;
const answer = botActions(answering).find(action => action.type === 'truthAnswer');
assert.ok(answer, difficulty);
const game = act(asked, f.chooser, answer);
const view = viewGame(game, f.chooser);
view.players.find(seat => seat.id === f.chooser)!.bot = difficulty;
const options = botActions(view);
assert.ok(options.length, difficulty);
const legal = options.find(action => {
try { act(game, f.chooser, action); return true; } catch { return false; }
});
assert.ok(legal, `${difficulty} must offer at least one legal continuation`);
const chosen = act(game, f.chooser, legal);
assert.ok(chosen.battle, `${difficulty} must choose an actual battle`);
assert.equal(chosen.turnActionPromises?.[0].fulfilled, true);
assert.deepEqual(inventory(chosen), f.initial);
}
});
void test('two different current battle choices cannot both be chosen in one native opportunity', () => {
const f = source(), asked = ask(f,choiceQuestion(f,'and'));
const answers = viewGame(asked, f.chooser).truthTurnActionAnswers; assert.ok(answers);
assert.ok(answers.includes('no')); assert.ok(!answers.includes('yes'));
reject(asked, f.chooser, {type:'truthAnswer',answer:'yes'});
const bound = act(asked, f.chooser, {type:'truthAnswer',answer:'no'});
for (const choice of [f.desired,f.other]) {
const chosen = act(bound, f.chooser, choice);
assert.ok(chosen.battle);
assert.equal(chosen.turnActionPromises?.[0].fulfilled, true);
assert.deepEqual(inventory(chosen), f.initial);
}
});
void test('either real battle fulfills an OR of the two current choices', () => {
const f = source(), asked = ask(f,choiceQuestion(f,'or'));
const answers = viewGame(asked, f.chooser).truthTurnActionAnswers; assert.ok(answers?.includes('yes'));
const bound = act(asked, f.chooser, {type:'truthAnswer',answer:'yes'});
const guide = viewGame(bound, f.chooser).turnActionGuide; assert.ok(guide);
assert.equal(guide.action.type, 'chooseBattle');
assert.ok([f.desired,f.other].some(choice => choice.territory === guide.action.territory &&
choice.target === guide.action.target), 'The private guide must use one real qualifying choice');
for (const choice of [f.desired,f.other]) {
const chosen = act(bound, f.chooser, choice);
assert.ok(chosen.battle);
assert.equal(chosen.turnActionPromises?.[0].fulfilled, true);
assert.deepEqual(inventory(chosen), f.initial);
}
});
void test('an earlier accepted Yes excludes a later conflicting Yes while preserving the original choice', () => {
const f = source(), secondAsker = f.game.players.find(seat => seat.id !== f.chooser && seat.id !== f.asker)!;
const targetHand = secondAsker.hand;
let second = targetHand.find(card => card.effect === 'truthtrance' && card.id !== f.truth);
if (!second) {
const replacement = targetHand[0]; assert.ok(replacement);
const owner = f.game.players.find(seat => seat.id !== secondAsker.id &&
seat.hand.some(card => card.effect === 'truthtrance' && card.id !== f.truth));
if (owner) {
const index = owner.hand.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth);
second = owner.hand[index]; owner.hand[index] = replacement;
} else {
const zone = [f.game.deck,f.game.discard].find(cards =>
cards.some(card => card.effect === 'truthtrance' && card.id !== f.truth));
assert.ok(zone);
const index = zone.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth);
second = zone[index]; zone[index] = replacement;
}
targetHand[0] = second;
}
assert.deepEqual(inventory(f.game), f.initial, 'Both actual Truth cards are staged by conserved swaps');
let game = act(ask(f), f.chooser, {type:'truthAnswer',answer:'yes'});
const otherQuestion: TruthQuestion = {kind:'turnActions',target:f.chooser,turn:game.turn,mixed:{kind:'action',
action:{kind:'battleChoice',source:f.event,territory:f.other.territory as string,target:f.other.target as string}}};
game = ask(f,otherQuestion,game,secondAsker.id,second.id);
const answers = viewGame(game,f.chooser).truthTurnActionAnswers; assert.ok(answers);
assert.ok(answers.includes('no')); assert.ok(!answers.includes('yes'));
reject(game,f.chooser,{type:'truthAnswer',answer:'yes'});
game = act(game,f.chooser,{type:'truthAnswer',answer:'no'});
reject(game,f.chooser,f.other);
const chosen = act(game,f.chooser,f.desired);
assert.ok(chosen.battle);
assert.equal(chosen.turnActionPromises?.length, 2);
assert.ok(chosen.turnActionPromises?.every(promise => promise.fulfilled));
assert.deepEqual(inventory(chosen),f.initial);
});
@@ -0,0 +1,75 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { TurnActionFields, turnActionInputError } from '../components/turn-action-fields';
import { TurnActionGuideButton } from '../components/turn-action-promises';
import { createGame, joinGame, newPlayer, viewGame, type Action, type GameView } from '../game/engine';
import type { MixedActionExpression } from '../game/mixed-action-question';
import type { TurnActionLeaf } from '../game/turn-action-promises';
import { battleChooserEvent } from '../game/battle-chooser-order';
type Expression = MixedActionExpression<TurnActionLeaf>;
type Element = ReactElement<{ children?: ReactNode; [key: string]: unknown }>;
const source = battleChooserEvent(1,null,0);
function elements(node: ReactNode): Element[] {
if (Array.isArray(node)) return node.flatMap(elements);
if (!isValidElement<{ children?: ReactNode; [key: string]: unknown }>(node)) return [];
return [node, ...elements(node.props.children)];
}
/** Controlled public projection: tests the editor and guide, not game setup. */
function projection(viewer = 'p'): GameView {
const game = createGame('BATTLECHOICECONTROL', newPlayer('p', 'Atreides', 'atreides'));
joinGame(game, newPlayer('a', 'Emperor', 'emperor'));
joinGame(game, newPlayer('g', 'Guild', 'guild'));
const view = viewGame(game, viewer);
view.status = 'playing'; view.turn = 1; view.phase = 6; view.active = 'p'; view.battle = null;
view.battleOrder = {event:source, phaseEvent:'battleOrder:1', remaining:['p','a','g'], current:'p', uses:[]};
view.battleChoices = [
{chooser:'p', attacker:'p', defender:'a', territory:'arrakeen'},
{chooser:'p', attacker:'g', defender:'p', territory:'carthag'},
];
return view;
}
const choice = (territory: string, target: string, event = source): Expression =>
({kind:'action', action:{kind:'battleChoice',source:event,territory,target}});
void test('editor selects only the current chooser’s actual public battle pairs', () => {
const game = projection('a');
// A Truthtrance question itself temporarily suppresses the projected current
// order indicator, but does not change the authoritative active chooser.
game.battleOrder!.current = null;
let value: Expression = {kind:'action',action:{kind:'ship',territory:'carthag',minimum:1}};
const tree = () => TurnActionFields({game, value, target:'p', disabled:false, onChange(next) {value = next;}});
const action = elements(tree()).find(element => element.props.id === 'truth-turn-action-1-action'); assert.ok(action);
(action.props.onChange as (event: {currentTarget:{value:string}}) => void)({currentTarget:{value:'battleChoice'}});
assert.deepEqual(value, choice('arrakeen','a'));
assert.equal(turnActionInputError(value,game,'p'),null);
const html = renderToStaticMarkup(createElement(TurnActionFields,{game,value,target:'p',disabled:false,onChange() {}}));
assert.match(html,/Current unresolved battle/); assert.match(html,/Arrakeen/); assert.match(html,/Emperor/);
const select = elements(tree()).find(element => element.props.id === 'truth-turn-action-1-battle-choice'); assert.ok(select);
(select.props.onChange as (event: {currentTarget:{value:string}}) => void)({currentTarget:{value:JSON.stringify(['carthag','g'])}});
assert.deepEqual(value,choice('carthag','g')); assert.equal(turnActionInputError(value,game,'p'),null);
assert.notEqual(turnActionInputError(choice('arrakeen','g'),game,'p'),null);
assert.notEqual(turnActionInputError(choice('arrakeen','a','stale'),game,'p'),null);
assert.notEqual(turnActionInputError(choice('arrakeen','a'),game,'g'),null);
game.active = 'g'; assert.notEqual(turnActionInputError(value,game,'p'),null);
});
void test('guided native battle choice rejects changed event, chooser or candidate', () => {
for (const mutate of [
(view:GameView) => {view.battleOrder!.event = 'later-source';},
(view:GameView) => {view.active = 'g';},
(view:GameView) => {view.battleChoices = view.battleChoices.filter(row => row.territory !== 'arrakeen');},
]) {
const game = projection(), event = 'battle-choice-promise', mixed = choice('arrakeen','a');
game.turnActionPromises = [{event,player:'p',asker:'a',turn:1,mixed,answer:true,fulfilled:false,released:false}];
const action: Action = {type:'chooseBattle',territory:'arrakeen',target:'a',turnActionPromiseEvent:event,turnActionPromisePhase:6};
game.turnActionGuide = {event,action};
const sent: Action[] = [], props = {game,busy:false,act:(next:Action) => sent.push(next)};
const button = TurnActionGuideButton(props); assert.ok(button); assert.equal(button.props.disabled,false);
assert.match(renderToStaticMarkup(createElement(TurnActionGuideButton,props)),/Choose the battle against Emperor in Arrakeen/);
button.props.onClick(); assert.deepEqual(sent,[action]);
mutate(game); button.props.onClick(); assert.deepEqual(sent,[action]);
}
});
@@ -0,0 +1,74 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { compileMixedActionExpression, type MixedActionExpression } from '../game/mixed-action-question';
import {
TurnActionError, closeTurnActionBattleChoice, finishTurnActionTurn, parseTurnActionLeaf,
recordTurnActionBattleChoice, turnActionBranches, turnActionValue, validateTurnActionPromises,
type TurnActionLeaf, type TurnActionPromise,
} from '../game/turn-action-promises';
const source = 'battleOrder:[2,null,0]';
const leaf = (territory = 'carthag', target = 'guild'): TurnActionLeaf =>
({kind:'battleChoice',source,territory,target});
const action = (value: TurnActionLeaf): MixedActionExpression<TurnActionLeaf> => ({kind:'action',action:value});
function promise(mixed: MixedActionExpression<TurnActionLeaf>, answer = true): TurnActionPromise {
return {turn:2,event:'answer-1',player:'atreides',asker:'emperor',answer,mixed,
compiled:compileMixedActionExpression(mixed,() => 'yes',answer),
shipment:{pending:false,event:null},progress:[],payments:[],transportClosed:true,paymentClosed:true,
battleChoice:{source,closed:false,selected:null},fulfilled:false,released:false};
}
const selected = {territory:'carthag',target:'guild'};
const seats = ['atreides','emperor','guild','fremen'];
void test('battle choice accepts only an exact canonical source and original public fields', () => {
assert.deepEqual(parseTurnActionLeaf(leaf()),leaf());
for (const value of [
{...leaf(), source:'other'}, {...leaf(), source:'battleOrder:[2,null,-1]'},
{...leaf(), source:'battleOrder:[ 2,null,0]'}, {...leaf(), source:'battleOrder:[0,null,0]'},
{...leaf(), target:''}, {...leaf(), territory:''}, {...leaf(), extra:true},
]) assert.throws(() => parseTurnActionLeaf(value),TurnActionError);
const p = promise(action(leaf())); validateTurnActionPromises([p],seats);
assert.throws(() => validateTurnActionPromises([{...p,battleChoice:{...p.battleChoice!,source:'battleOrder:[3,null,0]'}}],seats));
assert.throws(() => validateTurnActionPromises([{...p,battleChoice:{...p.battleChoice!,selected}}],seats));
});
void test('an accepted native choice settles the exact Yes; No rejects the same selection atomically', () => {
const yes = promise(action(leaf())), before = structuredClone(yes);
const [recorded] = recordTurnActionBattleChoice([yes],'atreides',2,source,selected);
assert.deepEqual(yes,before);
assert.equal(recorded.fulfilled,true); assert.equal(turnActionValue(recorded),true);
assert.deepEqual(recorded.battleChoice?.selected,selected);
validateTurnActionPromises([recorded],seats);
assert.equal(recordTurnActionBattleChoice([recorded],'atreides',2,source,selected)[0],recorded);
const no = promise(action(leaf()),false), snapshot = structuredClone(no);
assert.throws(() => recordTurnActionBattleChoice([no],'atreides',2,source,selected),TurnActionError);
assert.deepEqual(no,snapshot);
const [different] = recordTurnActionBattleChoice([no],'atreides',2,source,{territory:'arrakeen',target:'fremen'});
assert.equal(different.fulfilled,true); assert.equal(turnActionValue(different),false);
validateTurnActionPromises([different],seats);
});
void test('one source can satisfy OR alternatives, but never two different positive choices', () => {
const first = action(leaf()), second = action(leaf('arrakeen','fremen'));
const and = promise({kind:'and',terms:[first,second]});
const or = promise({kind:'or',terms:[first,second]});
assert.deepEqual([...turnActionBranches(and)],[]);
assert.equal([...turnActionBranches(or)].length,2);
const [chosen] = recordTurnActionBattleChoice([or],'atreides',2,source,selected);
assert.equal(chosen.fulfilled,true); validateTurnActionPromises([chosen],seats);
const noOr = promise({kind:'or',terms:[first,second]},false);
assert.equal([...turnActionBranches(noOr)][0].length,2);
assert.throws(() => recordTurnActionBattleChoice([noOr],'atreides',2,source,selected));
});
void test('closing the original source records no fabricated battle and turn expiry releases an unfulfilled Yes', () => {
const yes = promise(action(leaf()));
const [closed] = closeTurnActionBattleChoice([yes],'atreides',2,source);
assert.equal(closed.battleChoice?.closed,true); assert.equal(closed.battleChoice?.selected,null);
assert.equal(closed.fulfilled,false);
const [expired] = finishTurnActionTurn([closed],'atreides',2);
assert.equal(expired.released,true); validateTurnActionPromises([expired],seats);
const [notChosen] = closeTurnActionBattleChoice([promise(action(leaf()),false)],'atreides',2,source);
assert.equal(notChosen.fulfilled,true); validateTurnActionPromises([notChosen],seats);
assert.throws(() => recordTurnActionBattleChoice([yes],'atreides',3,source,selected));
});