Allow proposers to commit their own travel
Verify and publish checkpoint container / container (push) Successful in 11m23s
Verify and publish checkpoint container / container (push) Successful in 11m23s
This commit is contained in:
1 parent
235696263a
commit
13c337a24a
11 files changed
+456
-27
No files matched your search
@@ -87,8 +87,9 @@ export function publicDealOfferAction(targets: readonly string[], terms: string,
|
||||
const travelDeadline = travel && Object.hasOwn(travel, 'dueTurn') ? travel.dueTurn : undefined;
|
||||
if (travel && (!proposer || targets.includes(proposer) ||
|
||||
(groupTravel ? travelKeys !== 'actor,answer,kind,minimum,territory' ||
|
||||
typeof travel.actor !== 'string' || !targets.includes(travel.actor) :
|
||||
travelKeys !== 'answer,kind,minimum,territory') ||
|
||||
typeof travel.actor !== 'string' || ![proposer, ...targets].includes(travel.actor) :
|
||||
travelKeys !== 'answer,kind,minimum,territory' &&
|
||||
(travelKeys !== 'actor,answer,kind,minimum,territory' || travel.actor !== proposer)) ||
|
||||
(Object.hasOwn(travel, 'dueTurn') && (!Number.isSafeInteger(travelDeadline) || (travelDeadline as number) < 1 ||
|
||||
(currentTurn !== undefined && (!Number.isSafeInteger(currentTurn) || currentTurn < 1 || (travelDeadline as number) < currentTurn)))) ||
|
||||
!['ship', 'move'].includes(travel.kind) || !TERRITORIES.some(territory => territory.id === travel.territory) ||
|
||||
@@ -174,7 +175,9 @@ export function PublicDealList({ game, act, disabled }: {
|
||||
})}
|
||||
{travel && <p><strong>{travelTurn === deal.turn ? 'Current-turn travel term:' : 'Travel term:'}</strong> {name(travelActor!)} {deal.status === 'offered' || deal.status === 'declined' || deal.status === 'withdrawn' ? 'would' : 'agrees to'} {travel.answer ? 'make' : 'avoid'} {travel.kind === 'ship' ? 'a reserve shipment' : 'a ground movement'} of at least {travel.minimum} physical forces in one action to {travelDestination ?? travel.territory} during turn {travelTurn}. {travelStatus ? `Travel status: ${travelStatus}.` : deal.status === 'offered' ? 'The term becomes binding on final acceptance.' : deal.status === 'declined' || deal.status === 'withdrawn' ? 'The term did not become binding.' : 'Travel status is unavailable.'}</p>}
|
||||
{travel && travelTurn !== undefined && travelTurn > deal.turn && <p>Before turn {travelTurn}, this term reserves no forces or spice. Its status and legal options update during that turn.</p>}
|
||||
{travel && participants.length > 2 && deal.status === 'offered' && <p>{name(travelActor!)} must accept last, after the other recipients. Anyone invited may decline at any time.</p>}
|
||||
{travel && participants.length > 2 && deal.status === 'offered' && (travelActor === deal.from
|
||||
? <p>The proposer already consented to their own travel term by making this offer. All invited participants must accept; anyone invited may decline at any time.</p>
|
||||
: <p>{name(travelActor!)} must accept last, after the other recipients. Anyone invited may decline at any time.</p>)}
|
||||
{deal.status === 'offered' && <p>
|
||||
Accepted by {accepted.map(name).join(', ')}. Waiting for {participants.filter(id => !accepted.includes(id)).map(name).join(', ')}.
|
||||
</p>}
|
||||
@@ -275,7 +278,7 @@ export function PublicDeals({ game, act, busy }: {
|
||||
const travelDueValid = travelDueTurn.trim() !== '' && Number.isSafeInteger(travelTurn) && travelTurn >= game.turn;
|
||||
const travel: DealTravel | undefined = includeTravel ? {kind:travelKind, territory:travelTerritory,
|
||||
minimum:Number(travelMinimum), answer:travelAnswer,
|
||||
...(selected.length > 1 ? {actor:travelActor} : {}),
|
||||
...(selected.length > 1 ? {actor:travelActor} : travelActor === me?.id ? {actor:travelActor} : {}),
|
||||
...(travelTurn > game.turn ? {dueTurn:travelTurn} : {})} : undefined;
|
||||
const offer = legalSelection && paymentValid && (!includeTravel || travelDueValid)
|
||||
? publicDealOfferAction(selected, terms, payment, me?.id, game.turn, travel, additionalPayments, additionalImmediatePayments) : null;
|
||||
@@ -434,13 +437,13 @@ export function PublicDeals({ game, act, busy }: {
|
||||
{!includeTravel && selected.length === 0 && <p className="fine">Select at least one human recipient to add a travel term.</p>}
|
||||
{includeTravel && <fieldset>
|
||||
<legend>Travel term</legend>
|
||||
<p className="fine">This term concerns one physical action during the selected turn. The sole recipient commits to travel in a two-party deal. In a group deal, choose one recipient to commit; they accept last after all other recipients. Written terms remain player-managed.</p>
|
||||
<p className="fine">A travel term may include an immediate payment or a payment due by the end of a selected turn. Payment and travel may have different participants and turns. The payment recipient collects their share at the next Mentat opening and can use it after collection. All invited parties accept before the traveler gives final consent.</p>
|
||||
<p className="fine">This term concerns one physical action during the selected turn. Choose a participant to commit. An invited traveler accepts last after all other recipients; a proposer consents to their own travel by making the offer. Written terms remain player-managed.</p>
|
||||
<p className="fine">A travel term may include an immediate payment or a payment due by the end of a selected turn. Payment and travel may have different participants and turns. The payment recipient collects their share at the next Mentat opening and can use it after collection. All invited parties must accept.</p>
|
||||
{selected.length > 1 && <label>Committed traveler
|
||||
<select value={selected.includes(travelActor) ? travelActor : ''} disabled={disabled}
|
||||
<select value={parties.some(player => player.id === travelActor) ? travelActor : ''} disabled={disabled}
|
||||
onChange={event => setTravelActor(event.target.value)}>
|
||||
<option value="">Choose a recipient</option>
|
||||
{selectedPlayers.map(player => <option key={player.id} value={player.id}>{player.name} · {faction(player.faction).name}</option>)}
|
||||
<option value="">Choose a participant</option>
|
||||
{parties.map(player => <option key={player.id} value={player.id}>{player.name} · {faction(player.faction).name}</option>)}
|
||||
</select>
|
||||
</label>}
|
||||
<p className="fine">Travel terms are available in Basic games with classic factions and no expansions or optional modules. A current-turn term must be possible when accepted. A later-turn term reserves no forces or spice in advance; if no legal completion is found when the travel turn closes, the term may be marked void.</p>
|
||||
@@ -462,6 +465,13 @@ export function PublicDeals({ game, act, busy }: {
|
||||
{TERRITORIES.map(territory => <option key={territory.id} value={territory.id}>{territory.name}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
{selected.length === 1 && <label>Committed traveler
|
||||
<select value={travelActor === me?.id ? travelActor : ''} disabled={disabled}
|
||||
onChange={event => setTravelActor(event.target.value)}>
|
||||
<option value="">{selectedPlayers[0]?.name ?? 'Recipient'} · recipient</option>
|
||||
{me && <option value={me.id}>{me.name} · proposer (you)</option>}
|
||||
</select>
|
||||
</label>}
|
||||
<label>Minimum physical forces in one action
|
||||
<input type="number" inputMode="numeric" min={1} max={20} step={1} value={travelMinimum} disabled={disabled}
|
||||
onChange={event => setTravelMinimum(event.target.value)} />
|
||||
|
||||
@@ -17,6 +17,14 @@ open mode gates.
|
||||
|
||||
## Current checkpoint and work
|
||||
|
||||
**Proposer travel in public deals — 16 November. Prototyped / Partial.**
|
||||
The proposer may commit their own shipment or movement in a two-party or group
|
||||
offer; the offer itself is their consent, and all invitees must agree before
|
||||
the native commitment binds. Existing offers retain their default traveler.
|
||||
Thirteen related offline files pass 115 cases, and one authenticated HTTP case
|
||||
passes; the production build succeeds. Advanced and expansion combinations,
|
||||
complete games and deployed acceptance remain open. [Scope](PUBLIC_DEALS.md#proposer-travel--16-november-2026).
|
||||
|
||||
**Basic phase-bid, Movement and travel commitments — 16 November. Prototyped /
|
||||
Partial.** Supported classic Basic answers share the owned purse across bidding,
|
||||
Revival, Shipment and Movement, with connected bot guidance. Silent cache sales
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
# Public deal records
|
||||
|
||||
## Proposer travel — 16 November 2026
|
||||
|
||||
**Prototyped / Partial.** A proposer can include their own shipment or ground
|
||||
movement in a two-party or group offer. Making the offer is their consent; all
|
||||
invitees must accept before the commitment and any payments take effect. For a
|
||||
group commitment by an invited traveler, that traveler still accepts last.
|
||||
Current-turn travel must have a native funded completion at final acceptance;
|
||||
future terms retain the existing no-reservation policy. Existing pair records
|
||||
without an explicit actor still name the recipient as traveler.
|
||||
|
||||
The connected controls name the proposer as an option and explain the consent
|
||||
order. [Model](../tests/public-deals-travel-schema.test.ts), [gameplay](../tests/public-deals-proposer-travel.test.ts)
|
||||
and [controls](../tests/public-deals-proposer-travel-controls.test.tsx) cover the
|
||||
new actor, ordinary actions, payments and rejected underfunded acceptance. The
|
||||
[authenticated room case](../tests/public-deals-proposer-travel-http.test.ts)
|
||||
covers consent and the scheduled commitment through the HTTP boundary.
|
||||
Advanced, expansion combinations and deployed verification remain open.
|
||||
|
||||
## Immediate deals and unrelated debt — 16 November 2026
|
||||
|
||||
**Prototyped / Partial.** An already-unfunded due debt belonging to an
|
||||
|
||||
+9
-3
@@ -6067,6 +6067,11 @@ function publicDealImmediateSignature(deal: PublicDeal): string {
|
||||
function publicDealSettlementSignature(deal: PublicDeal, frame: NonNullable<Game['pendingPublicDealSettlement']>): string {
|
||||
return JSON.stringify([publicDealImmediateSignature(deal),frame.next,frame.initiator,frame.turn,frame.phase]);
|
||||
}
|
||||
/** Travel ledgers need another participant as the originating party. Older
|
||||
* recipient-travel deals continue to identify their original proposer. */
|
||||
function publicDealTravelAsker(deal: PublicDeal): string {
|
||||
return publicDealTravelActor(deal) === deal.from ? deal.to : deal.from;
|
||||
}
|
||||
function publicDealIntegrity(g: Game, internalSettlement?: string): void {
|
||||
if (g.deals !== undefined) publicDealRule(() => validatePublicDeals(g.deals, g.players));
|
||||
const history = g.publicDealSettlementHistory ?? [];
|
||||
@@ -6103,7 +6108,7 @@ function publicDealIntegrity(g: Game, internalSettlement?: string): void {
|
||||
const deal = g.deals?.find(entry => entry.id === row.sourceDeal);
|
||||
const term = deal?.travel;
|
||||
requireRule(deal && term && ['active', 'released'].includes(deal.status) &&
|
||||
row.player === publicDealTravelActor(deal) && row.asker === deal.from && row.turn === publicDealTravelDueTurn(deal) &&
|
||||
row.player === publicDealTravelActor(deal) && row.asker === publicDealTravelAsker(deal) && row.turn === publicDealTravelDueTurn(deal) &&
|
||||
row.answer === term.answer && row.mixed.kind === 'action' &&
|
||||
row.mixed.action.kind === term.kind && row.mixed.action.territory === term.territory &&
|
||||
row.mixed.action.minimum === term.minimum && row.mixed.action.sector === undefined &&
|
||||
@@ -24467,7 +24472,7 @@ function bindPublicDealTravel(g: Game, deal: PublicDeal) {
|
||||
}
|
||||
initializeTravelOrder(g);
|
||||
(g.travelPromises ??= []).push({ ...claim, event: crypto.randomUUID(), sourceDeal: deal.id,
|
||||
player: player.id, asker: deal.from, answer: term.answer, compiled: { kind: 'action', action },
|
||||
player: player.id, asker: publicDealTravelAsker(deal), answer: term.answer, compiled: { kind: 'action', action },
|
||||
shipment: { pending: due > g.turn || g.phase < 5 || shipmentAvailable(g, player), event: null },
|
||||
progress: [], movementClosed: false, fulfilled: false, released: false });
|
||||
appendTravelOrder(g, 'travel', g.travelPromises.length - 1);
|
||||
@@ -43888,7 +43893,8 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
|
||||
next = publicDealRule(() => releasePublicDeal(current, g.players, id, action.agree as boolean));
|
||||
} else next = publicDealRule(() => withdrawPublicDeal(current, g.players, id));
|
||||
if (current.status === 'offered' && next.status === 'active' && next.travel) {
|
||||
requireRule(id === publicDealTravelActor(next), 'The traveler must give the final consent.');
|
||||
requireRule(publicDealTravelActor(next) === next.from || id === publicDealTravelActor(next),
|
||||
'The traveler must give the final consent.');
|
||||
bindPublicDealTravel(g, next);
|
||||
}
|
||||
if (current.status === 'active' && next.status === 'released' && next.travel) {
|
||||
|
||||
+11
-11
@@ -24,14 +24,15 @@ export type PublicDealAdditionalPayment = {
|
||||
};
|
||||
export const MAX_ADDITIONAL_DEAL_PAYMENTS = 12;
|
||||
export const MAX_ADDITIONAL_IMMEDIATE_DEAL_PAYMENTS = 12;
|
||||
/** One invited recipient commits to one native action (or its absence).
|
||||
* Old two-party records identify that recipient through `to`. */
|
||||
/** One participant commits to one native action (or its absence).
|
||||
* Old two-party records identify the recipient through `to`. */
|
||||
export type PublicDealTravel = {
|
||||
kind: 'ship' | 'move';
|
||||
territory: string;
|
||||
minimum: number;
|
||||
answer: boolean;
|
||||
/** Present only in a multi-party term; the selected recipient accepts last. */
|
||||
/** Explicit in a group term or when a pair names its traveler. An invited
|
||||
* traveler accepts last; the proposer already consents by making the offer. */
|
||||
actor?: string;
|
||||
/** Absent on existing terms: their original offer turn is the due turn. */
|
||||
dueTurn?: number;
|
||||
@@ -148,7 +149,7 @@ export function parsePublicDealPayment(value: unknown, parties: readonly string[
|
||||
amount: value.amount, dueTurn: value.dueTurn };
|
||||
}
|
||||
|
||||
/** Parse an exact travel claim; the multi-party actor is validated against the deal. */
|
||||
/** Parse an exact travel claim; any explicit actor is validated against the deal. */
|
||||
export function parsePublicDealTravel(value: unknown): PublicDealTravel {
|
||||
const keys = object(value) ? Object.keys(value).sort().join(',') : '';
|
||||
requireDeal(object(value) && (keys === 'answer,kind,minimum,territory' ||
|
||||
@@ -212,13 +213,12 @@ export function validatePublicDeals(value: unknown, players: readonly PublicDeal
|
||||
const travel = parsePublicDealTravel(deal.travel);
|
||||
requireDeal(travel.dueTurn === undefined || travel.dueTurn >= (deal.turn as number),
|
||||
'Choose a travel turn no earlier than the offer turn.');
|
||||
requireDeal(multi
|
||||
? !!travel.actor && travel.actor !== deal.from && parties.includes(travel.actor)
|
||||
: !Object.hasOwn(travel, 'actor'),
|
||||
'Choose an invited traveler and an optional bribe between participants.');
|
||||
// The actor's final acceptance is checked privately. An unfinished offer
|
||||
// cannot already contain that vote, even after a decline or withdrawal.
|
||||
if (multi && deal.status !== 'active' && deal.status !== 'released')
|
||||
requireDeal(multi ? !!travel.actor && parties.includes(travel.actor)
|
||||
: !travel.actor || parties.includes(travel.actor),
|
||||
'Choose a deal participant as traveler and an optional bribe between participants.');
|
||||
// An invited actor's final acceptance is checked privately. The proposer
|
||||
// has already consented by making the offer and remains in its votes.
|
||||
if (multi && travel.actor !== deal.from && deal.status !== 'active' && deal.status !== 'released')
|
||||
requireDeal(!(deal.acceptVotes as string[]).includes(travel.actor!),
|
||||
'The committed traveler accepts after all other invited participants.');
|
||||
}
|
||||
|
||||
@@ -168,7 +168,7 @@ for (const answer of [true, false]) void test(`group movement ${answer ? 'requir
|
||||
|
||||
void test('the traveler may decline early; malformed or uninvited actors and invalid payments reject', () => {
|
||||
const initial = fixture(), term:Term = {actor:traveler, kind:'ship', territory:'polar_sink', minimum:1, answer:true};
|
||||
for (const bad of [proposer, second, 'unknown'])
|
||||
for (const bad of [second, 'unknown'])
|
||||
reject(initial, proposer, {type:'dealOffer', targets:[first, traveler], terms:'Terms', travel:{...term, actor:bad}});
|
||||
reject(initial, proposer, {type:'dealOffer', targets:[first, traveler], terms:'Terms', travel:term,
|
||||
payment:{kind:'deferredBribe', payer:proposer, recipient:proposer, amount:1, dueTurn:initial.turn}});
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { runInNewContext } from 'node:vm';
|
||||
import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import * as jsxRuntime from 'react/jsx-runtime';
|
||||
import ts from 'typescript';
|
||||
import * as board from '../game/board';
|
||||
import * as catalog from '../game/catalog';
|
||||
import * as coalitionAlliance from '../game/coalition-alliance';
|
||||
import * as publicDeals from '../game/public-deals';
|
||||
import { PublicDealList, PublicDeals, publicDealOfferAction, publicDealRequests } from '../components/public-deals';
|
||||
import type { Action, GameView } from '../game/engine';
|
||||
|
||||
type Element = ReactElement<{ children?: ReactNode; [key: string]: unknown }>;
|
||||
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)];
|
||||
}
|
||||
const players = [
|
||||
{id:'a',name:'Alice',faction:'atreides',ally:null},
|
||||
{id:'b',name:'Basil',faction:'harkonnen',ally:null},
|
||||
{id:'c',name:'Cora',faction:'emperor',ally:null},
|
||||
];
|
||||
const base = {status:'playing',turn:2,me:'a',roomControl:null,coalitionState:null,
|
||||
players,deals:[],dealTravelStatus:{}} as unknown as GameView;
|
||||
const travel = {kind:'ship',territory:'carthag',minimum:1,answer:true} as const;
|
||||
|
||||
void test('proposer travel packets preserve pair defaults and validate participant identity', () => {
|
||||
assert.deepEqual(publicDealOfferAction(['b'],'Terms',undefined,'a',2,travel),
|
||||
{type:'dealOffer',target:'b',terms:'Terms',travel});
|
||||
assert.deepEqual(publicDealOfferAction(['b'],'Terms',undefined,'a',2,{...travel,actor:'a'}),
|
||||
{type:'dealOffer',target:'b',terms:'Terms',travel:{...travel,actor:'a'}});
|
||||
assert.deepEqual(publicDealOfferAction(['b','c'],'Terms',undefined,'a',2,{...travel,actor:'a',dueTurn:4}),
|
||||
{type:'dealOffer',targets:['b','c'],terms:'Terms',travel:{...travel,actor:'a',dueTurn:4}});
|
||||
assert.equal(publicDealOfferAction(['b'],'Terms',undefined,'a',2,{...travel,actor:'c'}),null);
|
||||
assert.equal(publicDealOfferAction(['b','c'],'Terms',undefined,'a',2,{...travel,actor:'outsider'}),null);
|
||||
});
|
||||
|
||||
/** Exercise the real stateful authoring callbacks without a browser. */
|
||||
function form() {
|
||||
const states:unknown[] = [], sent:Action[] = [];
|
||||
let cursor = 0;
|
||||
const exported:{PublicDeals?:typeof PublicDeals} = {};
|
||||
runInNewContext(ts.transpileModule(readFileSync(new URL('../components/public-deals.tsx',import.meta.url),'utf8'), {
|
||||
compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX},
|
||||
}).outputText, {exports:exported,require(name:string) {
|
||||
if (name === 'react/jsx-runtime') return jsxRuntime;
|
||||
if (name === 'react') return {useState(initial:unknown) {
|
||||
const index = cursor++;
|
||||
if (!(index in states)) states[index] = typeof initial === 'function' ? initial() : initial;
|
||||
return [states[index],(next:unknown) => {states[index] = typeof next === 'function' ? next(states[index]) : next;}];
|
||||
},useRef:() => ({current:null}),useEffect:() => {}};
|
||||
if (name === '@/components/ui/button') return {Button:'button'};
|
||||
if (name === '@/game/board') return board;
|
||||
if (name === '@/game/catalog') return catalog;
|
||||
if (name === '@/game/coalition-alliance') return coalitionAlliance;
|
||||
if (name === '@/game/public-deals') return publicDeals;
|
||||
throw new Error(`Unexpected import ${name}`);
|
||||
}});
|
||||
assert.ok(exported.PublicDeals);
|
||||
const render = () => {cursor = 0; return elements(exported.PublicDeals!({game:base,busy:false,act(action) {sent.push(action);}}));};
|
||||
const checkbox = (index:number) => {
|
||||
const input = render().filter(row => row.type === 'input' && row.props.type === 'checkbox')[index];
|
||||
assert.ok(input); (input.props.onChange as (event:{target:{checked:boolean}}) => void)({target:{checked:true}});
|
||||
};
|
||||
const select = (index:number,value:string) => {
|
||||
const input = render().filter(row => row.type === 'select')[index]; assert.ok(input);
|
||||
(input.props.onChange as (event:{target:{value:string}}) => void)({target:{value}});
|
||||
};
|
||||
const submit = () => {
|
||||
const button = render().find(row => row.type === 'button' && row.props.type === 'submit');
|
||||
assert.ok(button); assert.equal(button.props.disabled,false);
|
||||
const node = render().find(row => row.type === 'form'); assert.ok(node);
|
||||
(node.props.onSubmit as (event:{preventDefault():void}) => void)({preventDefault() {}});
|
||||
return JSON.parse(JSON.stringify(sent.at(-1))) as Action;
|
||||
};
|
||||
const terms = () => {
|
||||
const node = render().find(row => row.type === 'textarea'); assert.ok(node);
|
||||
(node.props.onChange as (event:{target:{value:string}}) => void)({target:{value:'My travel'}});
|
||||
};
|
||||
return {render,checkbox,select,submit,terms};
|
||||
}
|
||||
|
||||
void test('two-player authoring defaults to recipient and can select the proposer', () => {
|
||||
const ui = form();
|
||||
ui.checkbox(0); // Basil.
|
||||
ui.checkbox(3); // Travel after two recipients and payment toggle.
|
||||
ui.select(2,'carthag'); ui.terms();
|
||||
assert.deepEqual(ui.submit(),{type:'dealOffer',target:'b',terms:'My travel',travel});
|
||||
ui.select(3,'a');
|
||||
assert.deepEqual(ui.submit(),{type:'dealOffer',target:'b',terms:'My travel',travel:{...travel,actor:'a'}});
|
||||
ui.select(3,'');
|
||||
assert.deepEqual(ui.submit(),{type:'dealOffer',target:'b',terms:'My travel',travel});
|
||||
});
|
||||
|
||||
void test('group authoring lets the proposer commit and keeps all invited parties', () => {
|
||||
const ui = form();
|
||||
ui.checkbox(0); ui.checkbox(1); ui.checkbox(3);
|
||||
ui.select(0,'a'); ui.select(3,'carthag'); ui.terms();
|
||||
assert.deepEqual(ui.submit(),{type:'dealOffer',targets:['b','c'],terms:'My travel',travel:{...travel,actor:'a'}});
|
||||
});
|
||||
|
||||
void test('group offer identifies proposer consent and lets invitees accept without a final proposer vote', () => {
|
||||
const deal = {id:'deal',from:'a',to:'b',participants:['a','b','c'],acceptVotes:['a'],
|
||||
terms:'My travel',turn:2,status:'offered',releaseVotes:[],travel:{...travel,actor:'a'}};
|
||||
const game = {...base,me:'b',deals:[deal]} as unknown as GameView;
|
||||
const html = renderToStaticMarkup(createElement(PublicDealList,{game,disabled:false,act() {}}));
|
||||
assert.match(html,/Alice \(Atreides\) would make a reserve shipment/);
|
||||
assert.match(html,/proposer already consented to their own travel term/);
|
||||
assert.doesNotMatch(html,/must accept last/);
|
||||
assert.deepEqual(publicDealRequests(game),[['offer','deal']]);
|
||||
const sent:Action[] = [];
|
||||
const nodes = elements(PublicDealList({game,disabled:false,act(action) {sent.push(action);}}));
|
||||
const accept = nodes.find(row => row.props.children === 'Accept deal'); assert.ok(accept);
|
||||
assert.equal(accept.props.disabled,false);
|
||||
(accept.props.onClick as () => void)();
|
||||
assert.deepEqual(sent,[{type:'dealRespond',deal:'deal',accept:true}]);
|
||||
const last = {...game,me:'c',deals:[{...deal,acceptVotes:['a','b']}]} as unknown as GameView;
|
||||
const lastAccept = elements(PublicDealList({game:last,disabled:false,act() {}}))
|
||||
.find(row => row.props.children === 'Accept deal');
|
||||
assert.ok(lastAccept); assert.equal(lastAccept.props.disabled,false);
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
// @dune-suite integration
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import type { GameView } from '../game/engine';
|
||||
import type { PublicDeal } from '../game/public-deals';
|
||||
|
||||
const base = process.env.DUNE_TEST_URL ?? 'http://localhost:3000';
|
||||
async function request(path: string, cookie?: string, body?: unknown, selected?: string) {
|
||||
const response = await fetch(base + path, {
|
||||
method: body === undefined ? 'GET' : 'POST', signal: AbortSignal.timeout(15_000),
|
||||
headers: {
|
||||
...(body === undefined ? {} : {'Content-Type':'application/json'}),
|
||||
...(cookie ? {cookie} : {}),
|
||||
...(selected ? {'X-Dune-Seat':selected} : {}),
|
||||
},
|
||||
...(body === undefined ? {} : {body:JSON.stringify(body)}),
|
||||
});
|
||||
return {status:response.status, cookie:response.headers.get('set-cookie')?.split(';')[0],
|
||||
data:await response.json() as GameView & {error?:string}};
|
||||
}
|
||||
|
||||
/** Creates a fresh authenticated test room; never reuses or removes a saved
|
||||
* room. The real proposer submits its own next-turn travel and both players
|
||||
* view the same offer and scheduled commitment after the recipient consents. */
|
||||
void test('authenticated proposer can offer their own travel for recipient consent', async () => {
|
||||
const host = await request('/api/rooms',undefined,{
|
||||
name:'Proposer traveler',faction:'harkonnen',advanced:false,expansions:[],
|
||||
});
|
||||
assert.equal(host.status,201,JSON.stringify(host.data)); assert.ok(host.cookie);
|
||||
const path = `/api/rooms/${host.data.code}`;
|
||||
const guest = await request(path,undefined,{type:'join',name:'Travel recipient',faction:'atreides'});
|
||||
assert.equal(guest.status,200,JSON.stringify(guest.data)); assert.ok(guest.cookie);
|
||||
const seats = [{id:host.data.me,cookie:host.cookie},{id:guest.data.me,cookie:guest.cookie}];
|
||||
let view = guest.data;
|
||||
const act = async (cookie: string, action: object) => {
|
||||
const next = await request(path,cookie,{version:view.version,action});
|
||||
assert.equal(next.status,200,JSON.stringify(next.data)); view = next.data;
|
||||
};
|
||||
for (const seat of seats) await act(seat.cookie,{type:'ready'});
|
||||
await act(host.cookie,{type:'start'});
|
||||
for (const seat of seats) {
|
||||
const own = await request(path,seat.cookie);
|
||||
assert.equal(own.status,200,JSON.stringify(own.data)); view = own.data;
|
||||
const choices = own.data.players.find(player => player.id === seat.id)?.traitorChoices;
|
||||
if (choices?.length) await act(seat.cookie,{type:'traitor',leader:choices[0]});
|
||||
}
|
||||
assert.equal(view.status,'playing');
|
||||
const dueTurn = view.turn+1;
|
||||
const travel = {actor:host.data.me,kind:'ship',territory:'polar_sink',minimum:1,answer:true,dueTurn};
|
||||
const payment = {kind:'deferredBribe',payer:host.data.me,recipient:guest.data.me,amount:1,dueTurn};
|
||||
await act(host.cookie,{type:'dealOffer',target:guest.data.me,
|
||||
terms:'I will ship to Polar Sink and pay one spice next turn.',travel,payment});
|
||||
const offered = view.deals.at(-1); assert.ok(offered);
|
||||
assert.equal(offered.status,'offered'); assert.deepEqual(offered.travel,travel);
|
||||
assert.deepEqual(offered.payment,payment);
|
||||
const acceptance = {type:'dealRespond',deal:offered.id,accept:true};
|
||||
const self = await request(path,host.cookie,{version:view.version,action:acceptance});
|
||||
assert.equal(self.status,409,JSON.stringify(self.data));
|
||||
const forged = await request(path,host.cookie,{version:view.version,action:acceptance},guest.data.me);
|
||||
assert.equal(forged.status,409,JSON.stringify(forged.data));
|
||||
await act(guest.cookie,acceptance);
|
||||
for (const seat of seats) {
|
||||
const read = await request(path,seat.cookie);
|
||||
assert.equal(read.status,200,JSON.stringify(read.data));
|
||||
const active: PublicDeal | undefined = read.data.deals.find(deal => deal.id === offered.id); assert.ok(active);
|
||||
assert.equal(active.status,'active'); assert.equal(active.paymentStatus,'pending');
|
||||
assert.deepEqual(active.travel,travel); assert.deepEqual(active.payment,payment);
|
||||
assert.equal(read.data.dealTravelStatus[offered.id],'scheduled');
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createGame, joinGame, newPlayer, viewGame, type Action, type Game } from '../game/engine';
|
||||
import { actTruthTravel as act, createTruthTravelFixture as fixture, settleTruthTravel as settle,
|
||||
truthTravelClean as clean, truthTravelInventory as inventory, truthTravelPlayer as player } from './fixture-truth-travel';
|
||||
import { nextStrongholdFactionsNativeStep as nextNative } from './fixture-stronghold-factions';
|
||||
|
||||
function reject(game: Game, actor: string, action: Action) {
|
||||
const before = structuredClone(game);
|
||||
assert.throws(() => act(game, actor, action));
|
||||
assert.deepEqual(game, before, 'Rejected consent leaves the original game intact.');
|
||||
}
|
||||
function row(game: Game, id: string) {
|
||||
const found = game.deals?.find(deal => deal.id === id); assert.ok(found); return found;
|
||||
}
|
||||
function promise(game: Game, id: string) {
|
||||
const found = game.travelPromises?.find(entry => entry.sourceDeal === id); assert.ok(found); return found;
|
||||
}
|
||||
function respond(game: Game, seat: string, id: string) {
|
||||
return act(game, seat, {type:'dealRespond',deal:id,accept:true});
|
||||
}
|
||||
|
||||
/** The native fixture runs a real Basic start and stops at the target's paid
|
||||
* shipment. Only unopened card/Spice order is selected by the source. */
|
||||
void test('legacy two-party travel without an actor still binds the invited recipient', () => {
|
||||
const f = fixture();
|
||||
let game = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'Ship to the agreed territory.',
|
||||
travel:{kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true}});
|
||||
const id = game.deals!.at(-1)!.id;
|
||||
game = respond(game,f.target,id);
|
||||
assert.equal(promise(game,id).player,f.target);
|
||||
assert.equal(promise(game,id).asker,f.asker);
|
||||
game = settle(act(game,f.target,f.shipmentAction));
|
||||
assert.equal(viewGame(game,f.target).dealTravelStatus[id],'fulfilled');
|
||||
assert.equal(player(game,f.target).forces['polar_sink:0'],1);
|
||||
assert.deepEqual(inventory(game),f.originalCards);
|
||||
});
|
||||
|
||||
void test('two-party proposer travels and pays a deferred bribe using the same purse', () => {
|
||||
const f = fixture(), traveler = f.target, recipient = f.asker;
|
||||
const cash = player(f.game,traveler).spice, bribes = player(f.game,recipient).bribes;
|
||||
assert.ok(cash >= f.shipmentCost + 1);
|
||||
let game = act(f.game,traveler,{type:'dealOffer',target:recipient,terms:'Pay and ship to the agreed territory.',
|
||||
travel:{actor:traveler,kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true},
|
||||
payment:{kind:'deferredBribe',payer:traveler,recipient,amount:1,dueTurn:f.game.turn}});
|
||||
const id = game.deals!.at(-1)!.id;
|
||||
assert.equal(game.travelPromises?.some(entry => entry.sourceDeal === id) ?? false,false);
|
||||
game = respond(game,recipient,id);
|
||||
assert.equal(row(game,id).status,'active');
|
||||
assert.equal(promise(game,id).player,traveler);
|
||||
assert.equal(promise(game,id).asker,recipient);
|
||||
reject(game,traveler,f.currentEnd);
|
||||
game = act(game,traveler,{type:'dealPay',deal:id});
|
||||
game = settle(act(game,traveler,f.shipmentAction));
|
||||
assert.equal(viewGame(game,traveler).dealTravelStatus[id],'fulfilled');
|
||||
assert.equal(row(game,id).paymentStatus,'paid');
|
||||
assert.equal(player(game,recipient).bribes,bribes+1);
|
||||
assert.equal(player(game,traveler).spice,cash-1-f.shipmentCost);
|
||||
assert.deepEqual(inventory(game),f.originalCards);
|
||||
});
|
||||
|
||||
void test('unaffordable proposer-traveler and payment reject final pair consent atomically', () => {
|
||||
const f = fixture(), traveler = f.target, recipient = f.asker, cash = player(f.game,traveler).spice;
|
||||
assert.ok(cash > 0 && f.shipmentCost > 0);
|
||||
const offered = act(f.game,traveler,{type:'dealOffer',target:recipient,terms:'Pay and ship.',
|
||||
travel:{actor:traveler,kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true},
|
||||
payment:{kind:'deferredBribe',payer:traveler,recipient,amount:cash,dueTurn:f.game.turn}});
|
||||
const id = offered.deals!.at(-1)!.id;
|
||||
reject(offered,recipient,{type:'dealRespond',deal:id,accept:true});
|
||||
assert.equal(row(offered,id).status,'offered');
|
||||
assert.equal(offered.travelPromises?.some(entry => entry.sourceDeal === id) ?? false,false);
|
||||
assert.equal(player(offered,traveler).spice,cash);
|
||||
});
|
||||
|
||||
const traveler = 'emperor', first = 'atreides', second = 'harkonnen';
|
||||
function reach(game: Game, until: (state: Game) => boolean): Game {
|
||||
for (let count = 0; count < 1600; count++) {
|
||||
if (until(game)) return game;
|
||||
assert.notEqual(game.status,'finished');
|
||||
const step = nextNative(game); assert.ok(step, `A native action is needed at ${game.turn}/${game.phase}`);
|
||||
game = act(game,step.actor,step.action);
|
||||
}
|
||||
throw Error('The group source did not reach its requested boundary.');
|
||||
}
|
||||
/** Four human seats, original Basic setup and real phase-five turn. The
|
||||
* starting deal and two unopened Spice cards are the only selected order. */
|
||||
function groupFixture(): Game {
|
||||
let game = createGame('PROPOSERTRAVEL',newPlayer(first,'Atreides','atreides'),false,[]);
|
||||
for (const [id,faction] of [[traveler,'emperor'],[second,'harkonnen'],['fremen','fremen']] as const)
|
||||
joinGame(game,newPlayer(id,id,faction));
|
||||
for (const seat of game.players) game = act(game,seat.id,{type:'ready'});
|
||||
game = act(game,first,{type:'start'});
|
||||
const cards = game.deck.filter(card => ['projectile','poison','shield','snooper'].includes(card.kind)).slice(0,4);
|
||||
assert.equal(cards.length,4);
|
||||
for (const [position,card] of cards.entries()) {
|
||||
const from = game.deck.findIndex(row => row.id === card.id); assert.ok(from >= position);
|
||||
[game.deck[position],game.deck[from]] = [game.deck[from],game.deck[position]];
|
||||
}
|
||||
game = reach(game,state => state.status === 'playing');
|
||||
for (let position = 0; position < 2; position++) {
|
||||
const from = game.spiceDeck.findIndex((card,index) => index >= position && 'territory' in card && !card.discovery);
|
||||
assert.ok(from >= position);
|
||||
game.spiceDeck.splice(position,0,game.spiceDeck.splice(from,1)[0]);
|
||||
}
|
||||
return reach(game,state => state.turn === 1 && state.phase === 5 && state.active === traveler && clean(state));
|
||||
}
|
||||
function groupOffer(game: Game, amount = 1): Game {
|
||||
return act(game,traveler,{type:'dealOffer',targets:[first,second],terms:'Pay and ship to Polar Sink.',
|
||||
travel:{actor:traveler,kind:'ship',territory:'polar_sink',minimum:1,answer:true},
|
||||
payment:{kind:'deferredBribe',payer:traveler,recipient:first,amount,dueTurn:game.turn}});
|
||||
}
|
||||
for (const voters of [[first,second],[second,first]]) void test(
|
||||
`proposer's group travel activates only after both invited votes (${voters.join(' then ')})`, () => {
|
||||
const initial = groupFixture(), cards = inventory(initial), cash = player(initial,traveler).spice;
|
||||
assert.ok(cash >= 3);
|
||||
let game = groupOffer(initial);
|
||||
const id = game.deals!.at(-1)!.id;
|
||||
assert.deepEqual(row(game,id).acceptVotes,[traveler]);
|
||||
reject(game,traveler,{type:'dealRespond',deal:id,accept:true});
|
||||
game = respond(game,voters[0],id);
|
||||
assert.equal(row(game,id).status,'offered');
|
||||
assert.equal(game.travelPromises?.some(entry => entry.sourceDeal === id) ?? false,false);
|
||||
game = respond(game,voters[1],id);
|
||||
assert.equal(row(game,id).status,'active');
|
||||
assert.equal(promise(game,id).player,traveler);
|
||||
assert.equal(promise(game,id).asker,row(game,id).to);
|
||||
assert.notEqual(promise(game,id).asker,traveler);
|
||||
game = act(game,traveler,{type:'dealPay',deal:id});
|
||||
game = reach(act(game,traveler,{type:'ship',territory:'polar_sink',sector:0,amount:1,elite:0,allyPayment:0}),
|
||||
state => clean(state) && !state.pendingShipment);
|
||||
assert.equal(viewGame(game,traveler).dealTravelStatus[id],'fulfilled');
|
||||
assert.equal(row(game,id).paymentStatus,'paid');
|
||||
assert.equal(player(game,traveler).forces['polar_sink:0'],1);
|
||||
assert.equal(player(game,traveler).spice,cash-3);
|
||||
assert.deepEqual(inventory(game),cards);
|
||||
},
|
||||
);
|
||||
|
||||
void test('an unaffordable proposer group offer keeps its first vote when final consent fails', () => {
|
||||
const initial = groupFixture(), cash = player(initial,traveler).spice;
|
||||
let game = groupOffer(initial,cash);
|
||||
const id = game.deals!.at(-1)!.id;
|
||||
game = respond(game,first,id);
|
||||
reject(game,second,{type:'dealRespond',deal:id,accept:true});
|
||||
assert.equal(row(game,id).status,'offered');
|
||||
assert.deepEqual(row(game,id).acceptVotes,[traveler,first]);
|
||||
assert.equal(game.travelPromises?.some(entry => entry.sourceDeal === id) ?? false,false);
|
||||
assert.equal(player(game,traveler).spice,cash);
|
||||
});
|
||||
@@ -47,7 +47,8 @@ void test('the offer packet retains legacy two-party terms and validates an expl
|
||||
{type:'dealOffer', targets:['b','c'], terms:'Terms', travel:{...travel,actor:'c',dueTurn:4}});
|
||||
for (const dueTurn of [0, 1, 2.5, Number.NaN, undefined])
|
||||
assert.equal(publicDealOfferAction(['b'], 'Terms', undefined, 'a', 2, {...travel,dueTurn}), null);
|
||||
assert.equal(publicDealOfferAction(['b','c'], 'Terms', undefined, 'a', 2, {...travel, actor:'a'}), null);
|
||||
assert.deepEqual(publicDealOfferAction(['b','c'], 'Terms', undefined, 'a', 2, {...travel, actor:'a'}),
|
||||
{type:'dealOffer', targets:['b','c'], terms:'Terms', travel:{...travel, actor:'a'}});
|
||||
assert.equal(publicDealOfferAction(['b','c'], 'Terms', undefined, 'a', 2, {...travel, actor:'d'}), null);
|
||||
assert.equal(publicDealOfferAction(['b'], 'Terms', undefined, 'a', 2, {...travel, actor:'b'}), null);
|
||||
assert.deepEqual(publicDealOfferAction(['b','c'], 'Terms', payment, 'a', 2, {...travel, actor:'c'}),
|
||||
|
||||
@@ -119,7 +119,7 @@ void test('travel requires an actor for multiparty offers and cannot replace an
|
||||
assert.throws(() => setPublicDealTravel(deal, term, seats), PublicDealError);
|
||||
for (const invalid of [
|
||||
{ ...multi, travel: term },
|
||||
{ ...fresh(), travel: {...term, actor:'b'} },
|
||||
{ ...fresh(), travel: {...term, actor:'c'} },
|
||||
{ ...fresh(), travel: undefined }, { ...fresh(), travel: { ...term, sector: 0 } },
|
||||
{ ...offered, paymentStatus: 'pending' }, { ...offered, travelStatus: 'pending' },
|
||||
]) assert.throws(() => validatePublicDeals([invalid], seats), PublicDealError);
|
||||
@@ -160,7 +160,7 @@ void test('multiparty travel requires the committed recipient to accept last and
|
||||
|
||||
void test('multiparty travel rejects forged actors, early votes and nonfresh offers', () => {
|
||||
const multi = createMultipartyPublicDeal(seats, 'a', ['b','c'], 'Terms', 3, 'multi');
|
||||
for (const actor of ['a','d','',undefined]) {
|
||||
for (const actor of ['d','',undefined]) {
|
||||
const invalid = {...term, actor};
|
||||
assert.throws(() => setPublicDealTravel(multi, invalid, seats), PublicDealError);
|
||||
assert.throws(() => validatePublicDeals([{...multi, travel:invalid}], seats), PublicDealError);
|
||||
@@ -174,6 +174,48 @@ void test('multiparty travel rejects forged actors, early votes and nonfresh off
|
||||
assert.equal(respondPublicDeal(acceptedOther, seats, 'b', true).status, 'active');
|
||||
});
|
||||
|
||||
void test('the proposer can be the explicitly named traveler in a two-party or group offer', () => {
|
||||
const payment = {kind:'deferredBribe', payer:'b', recipient:'a', amount:2, dueTurn:4} as const;
|
||||
const pair = setPublicDealTravel(createPublicDeal(seats, 'a', 'b', 'I will ship.', 3, 'self-pair', payment),
|
||||
{...term, actor:'a', dueTurn:4}, seats);
|
||||
assert.equal(publicDealTravelActor(pair), 'a');
|
||||
assert.deepEqual(pair.travel, {...term, actor:'a', dueTurn:4});
|
||||
const pairActive = respondPublicDeal(pair, seats, 'b', true);
|
||||
assert.equal(pairActive.status, 'active');
|
||||
const pairReleased = releasePublicDeal(releasePublicDeal(pairActive, seats, 'b', true), seats, 'a', true);
|
||||
assert.equal(pairReleased.status, 'released');
|
||||
|
||||
const group = setPublicDealTravel(createMultipartyPublicDeal(seats, 'a', ['b','c'], 'I will ship.', 3, 'self-group'),
|
||||
{...term, actor:'a'}, seats);
|
||||
assert.deepEqual(group.acceptVotes, ['a']);
|
||||
const partial = respondPublicDeal(group, seats, 'c', true);
|
||||
assert.equal(partial.status, 'offered');
|
||||
assert.deepEqual(partial.acceptVotes, ['a','c']);
|
||||
const active = respondPublicDeal(partial, seats, 'b', true);
|
||||
assert.equal(active.status, 'active');
|
||||
assert.deepEqual(active.acceptVotes, ['a','b','c']);
|
||||
assert.equal(respondPublicDeal(group, seats, 'b', false).status, 'declined');
|
||||
assert.equal(withdrawPublicDeal(group, seats, 'a').status, 'withdrawn');
|
||||
const released = releasePublicDeal(releasePublicDeal(releasePublicDeal(active, seats, 'a', true),
|
||||
seats, 'b', true), seats, 'c', true);
|
||||
for (const snapshot of [pair,pairActive,pairReleased,group,partial,active,released]) {
|
||||
const copy = JSON.parse(JSON.stringify(snapshot)) as PublicDeal;
|
||||
validatePublicDeals([copy], seats);
|
||||
assert.equal(publicDealTravelActor(copy), 'a');
|
||||
}
|
||||
});
|
||||
|
||||
void test('explicit pair actors must be participants and legacy absent actors still name the invitee', () => {
|
||||
for (const actor of ['a','b']) {
|
||||
const offered = setPublicDealTravel(fresh(), {...term, actor}, seats);
|
||||
assert.equal(publicDealTravelActor(offered), actor);
|
||||
assert.equal(publicDealTravelActor(respondPublicDeal(offered, seats, 'b', true)), actor);
|
||||
}
|
||||
for (const actor of ['c','unknown'])
|
||||
assert.throws(() => setPublicDealTravel(fresh(), {...term, actor}, seats), PublicDealError);
|
||||
assert.equal(publicDealTravelActor(setPublicDealTravel(fresh(), term, seats)), 'b');
|
||||
});
|
||||
|
||||
for (const [payer, recipient] of [['a', 'b'], ['b', 'a']] as const) void test(`a ${payer}-to-${recipient} immediate payment can accompany travel through the complete deal lifecycle`, () => {
|
||||
const payment = { kind: 'immediateBribe', payer, recipient, amount: 3 } as const;
|
||||
const original = createPublicDeal(seats, 'a', 'b', 'Payment for travel.', 3, 'paid-travel', payment);
|
||||
|
||||
Reference in new issue
Block a user