Builds replayable combat logs with first-class undo/redo, unified verification tooling, fast indexed log queries, and stricter CI.
feat(combat): add first-class undo and redo controls Add undo and redo controls to the combat UI so the DM can recover from recent actions without leaving the encounter view. Undo and redo operate on the current encounter's combat history. Empty stacks produce clear feedback instead of failing silently. Redo order follows normal stack behavior after multiple undos. This makes combat history actionable during play, not just visible in the log. feat(logs): make combat logs replayable Replace plain combat log messages with structured combat events that can be used by the UI, exported as JSON, replayed, and verified. Each new log entry records the action type, encounter identity, participant identity, a small action delta, undo intent, and a turn snapshot. Download and copy now export the event stream as JSON so a saved combat log is useful for offline analysis and debugging. Legacy logs remain viewable, but new logs use the structured event format. feat(logs): make undo and redo transactional Apply undo and redo as single storage operations so the encounter state and log state cannot drift apart. Server storage applies the encounter update and the log undone flag inside one SQLite transaction. Firebase storage uses a batch write for the same behavior. The storage contract now includes undo/redo semantics. This replaces fragile multi-write undo behavior where a failure could update the encounter without marking the log, or mark the log without updating the encounter. feat(combat): add unified replay and verification tool Add one combat CLI for replaying live combat and verifying combat logs. Replay drives the live backend through the same shared combat logic used by the app, writes a JSON event log to an explicit output path, and automatically verifies the result. Verification checks for DM-visible combat problems such as skipped turns, double actions, bad round changes, and unexpected turn order changes. The tool uses the same JSON event stream produced by log downloads, supports verbose turn output, and handles Ctrl-C by ending the encounter, writing the partial log, and verifying what was captured. fix(perf): keep long combat logging fast Remove the combat-time log query bottleneck that made long replays slow as log volume grew. Combat controls no longer subscribe to the log collection just to keep undo and redo state warm. Undo and redo now query the latest matching encounter log only when clicked. Server collection queries support exact filters, ordering, limits, and offsets, and SQLite indexes keep latest-log and per-encounter log lookups fast. Also fix duplicate WebSocket handler registration so realtime updates do not double-fire under write load. fix(turns): make toggle active a status change Make toggle active a roster/status edit instead of a turn advance. Deactivating the current participant no longer passes the turn or increments the round. The current turn stays where it is until the DM explicitly clicks Next Turn, and Next Turn skips inactive participants during normal rotation. This matches the initiative design: slot order is stable, toggle active does not move participants, and round changes only come from explicit turn advance. chore(ci): make warnings and hangs fail fast Tighten test and build checks so failures are visible instead of noisy or silent. Builds run with CI enabled so warnings fail production builds. The full test command runs app, shared, and server suites with hard timeouts so hangs fail quickly. Static eslint coverage fails on warnings as well as errors. Tests were updated around the new async combat logging flow, structured log events, transactional undo, replay verification, and toggle-active semantics.
This commit is contained in:
@@ -7,7 +7,7 @@ import React from 'react';
|
||||
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import '@testing-library/jest-dom';
|
||||
import { getCalls, MOCK_DB } from '../__mocks__/firebase/_mock-db';
|
||||
import { renderApp, createCampaignViaUI, selectCampaignByName } from './testHelpers';
|
||||
import { renderApp, createCampaignViaUI, selectCampaignByName, setupReady, startCombatViaUI, addMonsterViaUI } from './testHelpers';
|
||||
|
||||
function findCall(fn, pathSub) {
|
||||
return getCalls().find(c => c.fn === fn && (pathSub ? c.path.includes(pathSub) : true));
|
||||
@@ -139,4 +139,53 @@ describe('Campaign -> Firebase', () => {
|
||||
const delCall = findCall('deleteDoc', `/campaigns/${cid}`);
|
||||
expect(delCall).toBeDefined();
|
||||
});
|
||||
|
||||
test('deleteCampaign: cascade-deletes logs for campaign encounters (BUG)', async () => {
|
||||
const { setupReady, startCombatViaUI } = require('./testHelpers');
|
||||
await setupReady('Doomed', 'Enc');
|
||||
await addMonsterViaUI('Gob', 5, 2);
|
||||
await startCombatViaUI();
|
||||
// log written on start
|
||||
await waitFor(() => {
|
||||
const logWrites = findCalls('addDoc').filter(c => c.path.includes('/logs'));
|
||||
expect(logWrites.length).toBeGreaterThan(0);
|
||||
});
|
||||
const cid = Object.keys(MOCK_DB.collection('campaigns').reduce((m,c)=>(m[c.id]=c,m),{}))[0];
|
||||
|
||||
// delete campaign
|
||||
const allDeletes = screen.getAllByText(/Delete/i);
|
||||
fireEvent.click(allDeletes[allDeletes.length - 1]);
|
||||
fireEvent.click(await screen.findByRole('button', { name: /Confirm/i }));
|
||||
await waitFor(() => findCall('deleteDoc', `/campaigns/${cid}`));
|
||||
|
||||
// logs MUST be deleted via batch or deleteDoc on each log path
|
||||
const logDeletes = getCalls().filter(c =>
|
||||
(c.fn === 'deleteDoc' && c.path.includes('/logs/')) ||
|
||||
(c.fn === 'batch.delete' && c.path.includes('/logs/'))
|
||||
);
|
||||
expect(logDeletes.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('deleteEncounter: cascade-deletes logs for encounter (BUG)', async () => {
|
||||
const { setupReady, startCombatViaUI } = require('./testHelpers');
|
||||
await setupReady('Camp', 'DoomedEnc');
|
||||
await addMonsterViaUI('Gob', 5, 2);
|
||||
await startCombatViaUI();
|
||||
await waitFor(() => {
|
||||
expect(findCalls('addDoc').filter(c => c.path.includes('/logs')).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// delete encounter
|
||||
const allDeletes = screen.getAllByText(/Delete/i);
|
||||
fireEvent.click(allDeletes[0]);
|
||||
fireEvent.click(await screen.findByRole('button', { name: /Confirm/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
const logDeletes = getCalls().filter(c =>
|
||||
(c.fn === 'deleteDoc' && c.path.includes('/logs/')) ||
|
||||
(c.fn === 'batch.delete' && c.path.includes('/logs/'))
|
||||
);
|
||||
expect(logDeletes.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+119
-165
@@ -3,55 +3,41 @@
|
||||
//
|
||||
// Does 100 ROUNDS (not turns). A round = one full pass through initiative
|
||||
// (every active participant acts once); round counter increments at wrap.
|
||||
// See docs/GLOSSARY.md. Previous version lied: called nextTurn 100× (~100
|
||||
// turns, ~12 rounds). Now loops by actual round-wrap count.
|
||||
//
|
||||
// Exercises ALL combat paths deterministically (less random than replay):
|
||||
// Exercises ALL combat paths deterministically:
|
||||
// startEncounter, nextTurn, togglePause, addParticipant, addParticipants,
|
||||
// updateParticipant, removeParticipant, toggleParticipantActive,
|
||||
// applyHpChange (damage/heal), deathSave (incl. 3-success → isDying),
|
||||
// toggleCondition, reorderParticipants (drag same-init tie), endEncounter,
|
||||
// activateDisplay, clearDisplay, toggleHidePlayerHp.
|
||||
// applyHpChange (damage/heal), deathSave, toggleCondition,
|
||||
// reorderParticipants, endEncounter.
|
||||
//
|
||||
// New API: funcs async, take ctx {storage, encPath, logPath, displayPath},
|
||||
// write encounter + log internally, return newEnc. Mock storage captures writes.
|
||||
// Display lifecycle now async too — but test keeps inline display writes (mirrors App.js).
|
||||
//
|
||||
// Failing assertions do NOT abort the run: each phase wrapped in try/catch,
|
||||
// failures collected, final expect reports all.
|
||||
|
||||
const path = require('path');
|
||||
const { createMockStorage, mockCtx, readyEnc } = require('../../shared/tests/_helpers');
|
||||
const {
|
||||
makeParticipant,
|
||||
buildCharacterParticipant,
|
||||
buildMonsterParticipant,
|
||||
startEncounter,
|
||||
nextTurn,
|
||||
togglePause,
|
||||
addParticipant,
|
||||
addParticipants,
|
||||
updateParticipant,
|
||||
removeParticipant,
|
||||
toggleParticipantActive,
|
||||
applyHpChange,
|
||||
deathSave,
|
||||
toggleCondition,
|
||||
reorderParticipants,
|
||||
endEncounter,
|
||||
activateDisplay,
|
||||
clearDisplay,
|
||||
toggleHidePlayerHp,
|
||||
} = require('../../shared');
|
||||
|
||||
// aliases for combat funcs that clash with local helper names
|
||||
const {
|
||||
applyHpChange: combatApplyHpChange,
|
||||
startEncounter, nextTurn, togglePause, endEncounter,
|
||||
addParticipant, addParticipants, updateParticipant, removeParticipant,
|
||||
toggleParticipantActive: combatToggleActive,
|
||||
toggleCondition: combatToggleCondition,
|
||||
applyHpChange: combatApplyHpChange,
|
||||
deathSave: combatDeathSave,
|
||||
toggleCondition: combatToggleCondition,
|
||||
reorderParticipants,
|
||||
} = require('../../shared');
|
||||
|
||||
// ---------- scenario state (mirrors two firestore docs) ----------
|
||||
// ---------- scenario state ----------
|
||||
|
||||
const ROUNDS = 100;
|
||||
const ENCOUNTER_ID = 'enc-1';
|
||||
|
||||
// encounter doc
|
||||
let enc = {
|
||||
id: ENCOUNTER_ID,
|
||||
name: 'BigBoss',
|
||||
participants: [],
|
||||
isStarted: false,
|
||||
@@ -60,7 +46,7 @@ let enc = {
|
||||
currentTurnParticipantId: null,
|
||||
turnOrderIds: [],
|
||||
};
|
||||
// activeDisplay/status doc
|
||||
// display tracked via mock storage displayPath doc; simple local mirror.
|
||||
let display = {
|
||||
activeCampaignId: null,
|
||||
activeEncounterId: null,
|
||||
@@ -68,222 +54,200 @@ let display = {
|
||||
hideNpcHp: false,
|
||||
};
|
||||
const CAMPAIGN_ID = 'camp-1';
|
||||
const ENCOUNTER_ID = 'enc-1';
|
||||
const roster = [];
|
||||
|
||||
function applyEnc(patch) {
|
||||
if (!patch) return;
|
||||
for (const [k, v] of Object.entries(patch)) enc[k] = v;
|
||||
}
|
||||
function applyDisplay(patch) {
|
||||
if (!patch) return;
|
||||
for (const [k, v] of Object.entries(patch)) display[k] = v;
|
||||
}
|
||||
let storage, ctx;
|
||||
const DISPLAY_PATH = 'activeDisplay/status';
|
||||
|
||||
const RESULTS = [];
|
||||
function record(phase, fn) {
|
||||
try { fn(); RESULTS.push({ phase, ok: true }); }
|
||||
catch (err) { RESULTS.push({ phase, ok: false, err: err.message }); }
|
||||
}
|
||||
async function recordAsync(phase, fn) {
|
||||
async function record(phase, fn) {
|
||||
try { await fn(); RESULTS.push({ phase, ok: true }); }
|
||||
catch (err) { RESULTS.push({ phase, ok: false, err: err.message }); }
|
||||
}
|
||||
|
||||
// ---------- helpers (shared, no React) ----------
|
||||
// ---------- helpers ----------
|
||||
|
||||
const alive = (name) => enc.participants.find(p => p.name === name && p.currentHp > 0);
|
||||
const any = (name) => enc.participants.find(p => p.name === name);
|
||||
const idOf = (name) => { const p = any(name); return p ? p.id : null; };
|
||||
const anyById = (id) => enc.participants.find(p => p.id === id);
|
||||
|
||||
function addCharacterViaUI(name, maxHp, initMod) {
|
||||
roster.push({ id: `char-${name}`, name, defaultMaxHp: maxHp, defaultInitMod: initMod });
|
||||
}
|
||||
function addMonsterParticipant(name, maxHp, initMod, isNpc = false) {
|
||||
|
||||
async function addMonsterParticipant(name, maxHp, initMod, isNpc = false) {
|
||||
const { participant } = buildMonsterParticipant({ name, maxHp, initMod, isNpc });
|
||||
applyEnc(addParticipant(enc, participant).patch);
|
||||
enc = await addParticipant(enc, participant, ctx);
|
||||
}
|
||||
function addCharacterParticipant(charName) {
|
||||
async function addCharacterParticipant(charName) {
|
||||
const character = roster.find(c => c.name === charName);
|
||||
if (!character) throw new Error(`char not found: ${charName}`);
|
||||
if (enc.participants.some(p => p.type === 'character' && p.originalCharacterId === character.id)) {
|
||||
throw new Error(`${charName} already in encounter`);
|
||||
}
|
||||
const { participant } = buildCharacterParticipant(character);
|
||||
applyEnc(addParticipant(enc, participant).patch);
|
||||
enc = await addParticipant(enc, participant, ctx);
|
||||
}
|
||||
function addAllCharacters() {
|
||||
async function addAllCharacters() {
|
||||
const toAdd = roster
|
||||
.filter(c => !enc.participants.some(p => p.type === 'character' && p.originalCharacterId === c.id))
|
||||
.map(c => buildCharacterParticipant(c).participant);
|
||||
applyEnc(addParticipants(enc, toAdd).patch);
|
||||
enc = await addParticipants(enc, toAdd, ctx);
|
||||
}
|
||||
function startCombat() {
|
||||
applyEnc(startEncounter(enc).patch);
|
||||
applyDisplay(activateDisplay({ campaignId: CAMPAIGN_ID, encounterId: ENCOUNTER_ID }).patch);
|
||||
async function startCombat() {
|
||||
enc = await startEncounter(enc, ctx);
|
||||
display.activeCampaignId = CAMPAIGN_ID;
|
||||
display.activeEncounterId = ENCOUNTER_ID;
|
||||
await storage.updateDoc(DISPLAY_PATH, { activeCampaignId: CAMPAIGN_ID, activeEncounterId: ENCOUNTER_ID });
|
||||
}
|
||||
function endCombat() {
|
||||
applyEnc(endEncounter(enc).patch);
|
||||
applyDisplay(clearDisplay().patch);
|
||||
async function endCombat() {
|
||||
enc = await endEncounter(enc, ctx);
|
||||
display.activeCampaignId = null;
|
||||
display.activeEncounterId = null;
|
||||
await storage.updateDoc(DISPLAY_PATH, { activeCampaignId: null, activeEncounterId: null });
|
||||
}
|
||||
function nextTurnAction() { applyEnc(nextTurn(enc).patch); }
|
||||
function pauseCombat() { applyEnc(togglePause(enc).patch); if (!enc.isPaused) throw new Error('not paused'); }
|
||||
function resumeCombat() { applyEnc(togglePause(enc).patch); if (enc.isPaused) throw new Error('not resumed'); }
|
||||
async function nextTurnAction() { enc = await nextTurn(enc, ctx); }
|
||||
async function pauseCombat() { enc = await togglePause(enc, ctx); if (!enc.isPaused) throw new Error('not paused'); }
|
||||
async function resumeCombat() { enc = await togglePause(enc, ctx); if (enc.isPaused) throw new Error('not resumed'); }
|
||||
|
||||
function applyDamage(name, amount) {
|
||||
async function applyDamage(name, amount) {
|
||||
const p = any(name);
|
||||
if (!p || p.currentHp <= 0) return; // dead = skip (button hidden in UI)
|
||||
applyEnc(combatApplyHpChange(enc, p.id, 'damage', amount).patch);
|
||||
if (!p || p.currentHp <= 0) return;
|
||||
enc = await combatApplyHpChange(enc, p.id, 'damage', amount, ctx);
|
||||
}
|
||||
function applyHeal(name, amount) {
|
||||
async function applyHeal(name, amount) {
|
||||
const p = any(name);
|
||||
if (!p) return; // removed (death) = skip (no button in UI)
|
||||
applyEnc(combatApplyHpChange(enc, p.id, 'heal', amount).patch);
|
||||
if (!p) return;
|
||||
enc = await combatApplyHpChange(enc, p.id, 'heal', amount, ctx);
|
||||
}
|
||||
function toggleActive(name) {
|
||||
async function toggleActive(name) {
|
||||
const p = any(name);
|
||||
if (!p) throw new Error(`no active target: ${name}`);
|
||||
applyEnc(combatToggleActive(enc, p.id).patch);
|
||||
enc = await combatToggleActive(enc, p.id, ctx);
|
||||
}
|
||||
function toggleConditionAction(name, label) {
|
||||
async function toggleConditionAction(name, label) {
|
||||
const p = any(name);
|
||||
if (!p) throw new Error(`no condition target: ${name}`);
|
||||
applyEnc(combatToggleCondition(enc, p.id, label).patch);
|
||||
enc = await combatToggleCondition(enc, p.id, label, ctx);
|
||||
}
|
||||
function editParticipant(name, patch) {
|
||||
async function editParticipant(name, patch) {
|
||||
const p = any(name);
|
||||
if (!p) throw new Error(`no edit target: ${name}`);
|
||||
applyEnc(updateParticipant(enc, p.id, patch).patch);
|
||||
enc = await updateParticipant(enc, p.id, patch, ctx);
|
||||
}
|
||||
function removeParticipantByName(name) {
|
||||
async function removeParticipantByName(name) {
|
||||
const p = any(name);
|
||||
if (!p) throw new Error(`no remove target: ${name}`);
|
||||
applyEnc(removeParticipant(enc, p.id).patch);
|
||||
enc = await removeParticipant(enc, p.id, ctx);
|
||||
}
|
||||
function deathSaveAction(name, type, saveNum) {
|
||||
async function deathSaveAction(name, type, saveNum) {
|
||||
const p = any(name);
|
||||
if (!p) throw new Error(`no deathsave target: ${name}`);
|
||||
applyEnc(combatDeathSave(enc, p.id, type, saveNum).patch);
|
||||
const r = await combatDeathSave(enc, p.id, type, saveNum, ctx);
|
||||
enc = r.enc;
|
||||
}
|
||||
function dragTie(draggedName, targetName) {
|
||||
async function dragTie(draggedName, targetName) {
|
||||
const d = any(draggedName), t = any(targetName);
|
||||
if (!d || !t) throw new Error('drag target missing');
|
||||
applyEnc(reorderParticipants(enc, d.id, t.id).patch);
|
||||
enc = await reorderParticipants(enc, d.id, t.id, ctx);
|
||||
}
|
||||
function toggleHidePlayerHpAction() {
|
||||
applyDisplay(toggleHidePlayerHp(display.hidePlayerHp).patch);
|
||||
async function toggleHidePlayerHpAction() {
|
||||
display.hidePlayerHp = !display.hidePlayerHp;
|
||||
await storage.updateDoc(DISPLAY_PATH, { hidePlayerHp: display.hidePlayerHp });
|
||||
}
|
||||
|
||||
// ---------- scenario ----------
|
||||
|
||||
beforeEach(() => {
|
||||
({ storage, ctx } = mockCtx());
|
||||
enc = {
|
||||
id: ENCOUNTER_ID, name: 'BigBoss', participants: [],
|
||||
isStarted: false, isPaused: false, round: 0,
|
||||
currentTurnParticipantId: null, turnOrderIds: [],
|
||||
};
|
||||
display = { activeCampaignId: null, activeEncounterId: null, hidePlayerHp: true, hideNpcHp: false };
|
||||
roster.length = 0;
|
||||
RESULTS.length = 0;
|
||||
});
|
||||
|
||||
test('full 100-round combat scenario (shared, no React)', async () => {
|
||||
// roster
|
||||
await recordAsync('addChar Fighter', () => addCharacterViaUI('Fighter', 30, 2));
|
||||
await recordAsync('addChar Cleric', () => addCharacterViaUI('Cleric', 24, 1));
|
||||
await recordAsync('addChar Rogue', () => addCharacterViaUI('Rogue', 22, 3));
|
||||
await record('addChar Fighter', () => addCharacterViaUI('Fighter', 30, 2));
|
||||
await record('addChar Cleric', () => addCharacterViaUI('Cleric', 24, 1));
|
||||
await record('addChar Rogue', () => addCharacterViaUI('Rogue', 22, 3));
|
||||
|
||||
// monsters + npcs
|
||||
await recordAsync('addMonster Goblin1', () => addMonsterParticipant('Goblin1', 8, 2));
|
||||
await recordAsync('addMonster Goblin2', () => addMonsterParticipant('Goblin2', 8, 2));
|
||||
await recordAsync('addMonster OrcBoss', () => addMonsterParticipant('OrcBoss', 60, 1));
|
||||
await recordAsync('addMonster Wolf', () => addMonsterParticipant('Wolf', 14, 3));
|
||||
await recordAsync('addNpc Merchant', () => addMonsterParticipant('Merchant', 12, 0, true));
|
||||
await record('addMonster Goblin1', () => addMonsterParticipant('Goblin1', 8, 2));
|
||||
await record('addMonster Goblin2', () => addMonsterParticipant('Goblin2', 8, 2));
|
||||
await record('addMonster OrcBoss', () => addMonsterParticipant('OrcBoss', 60, 1));
|
||||
await record('addMonster Wolf', () => addMonsterParticipant('Wolf', 14, 3));
|
||||
await record('addNpc Merchant', () => addMonsterParticipant('Merchant', 12, 0, true));
|
||||
|
||||
// add chars into encounter
|
||||
await recordAsync('addCharParticipant Fighter', () => addCharacterParticipant('Fighter'));
|
||||
await recordAsync('addCharParticipant Cleric', () => addCharacterParticipant('Cleric'));
|
||||
await recordAsync('addCharParticipant Rogue', () => addCharacterParticipant('Rogue'));
|
||||
await recordAsync('addAllChars', () => addAllCharacters()); // bulk add path
|
||||
await record('addCharParticipant Fighter', () => addCharacterParticipant('Fighter'));
|
||||
await record('addCharParticipant Cleric', () => addCharacterParticipant('Cleric'));
|
||||
await record('addCharParticipant Rogue', () => addCharacterParticipant('Rogue'));
|
||||
await record('addAllChars', () => addAllCharacters());
|
||||
|
||||
// hidden hp toggle x2 (back to default)
|
||||
record('toggleHidePlayerHp', () => toggleHidePlayerHpAction());
|
||||
record('toggleHidePlayerHp back', () => toggleHidePlayerHpAction());
|
||||
await record('toggleHidePlayerHp', () => toggleHidePlayerHpAction());
|
||||
await record('toggleHidePlayerHp back', () => toggleHidePlayerHpAction());
|
||||
|
||||
await recordAsync('startCombat', () => startCombat());
|
||||
await record('startCombat', () => startCombat());
|
||||
|
||||
// ---------- 100 ROUNDS (loop by actual round-wrap count) ----------
|
||||
// ---------- 100 ROUNDS ----------
|
||||
let roundsDone = 0;
|
||||
let prevRound = enc.round;
|
||||
let turnInRound = 0;
|
||||
let turnTotal = 0;
|
||||
|
||||
while (roundsDone < ROUNDS) {
|
||||
turnTotal++;
|
||||
const actor = anyById(enc.currentTurnParticipantId);
|
||||
const r = enc.round;
|
||||
|
||||
// per-turn deterministic actions keyed by round + actor type
|
||||
// damage OrcBoss every even round
|
||||
if (r % 2 === 0 && turnInRound === 0) {
|
||||
await recordAsync(`r${r} damage OrcBoss`, () => applyDamage('OrcBoss', 3));
|
||||
}
|
||||
// heal Cleric every 3 rounds
|
||||
if (r % 3 === 0 && turnInRound === 1) {
|
||||
record(`r${r} heal Cleric`, () => applyHeal('Cleric', 2));
|
||||
}
|
||||
// condition on Fighter every 5 rounds
|
||||
if (r % 5 === 0 && turnInRound === 2) {
|
||||
record(`r${r} condition Fighter stunned`, () => toggleConditionAction('Fighter', 'Stunned'));
|
||||
}
|
||||
// toggleActive Goblin2 every 7 rounds (toggle off, next 7 toggle on)
|
||||
if (r % 7 === 0 && turnInRound === 3) {
|
||||
record(`r${r} toggleActive Goblin2`, () => toggleActive('Goblin2'));
|
||||
}
|
||||
// edit Wolf initiative every 13 rounds
|
||||
if (r % 13 === 0 && turnInRound === 4) {
|
||||
record(`r${r} edit Wolf init`, () => editParticipant('Wolf', { initiative: 15 }));
|
||||
}
|
||||
if (r % 2 === 0 && turnInRound === 0) await record(`r${r} damage OrcBoss`, () => applyDamage('OrcBoss', 3));
|
||||
if (r % 3 === 0 && turnInRound === 1) await record(`r${r} heal Cleric`, () => applyHeal('Cleric', 2));
|
||||
if (r % 5 === 0 && turnInRound === 2) await record(`r${r} condition Fighter stunned`, () => toggleConditionAction('Fighter', 'Stunned'));
|
||||
if (r % 7 === 0 && turnInRound === 3) await record(`r${r} toggleActive Goblin2`, () => toggleActive('Goblin2'));
|
||||
if (r % 13 === 0 && turnInRound === 4) await record(`r${r} edit Wolf init`, () => editParticipant('Wolf', { initiative: 15 }));
|
||||
|
||||
// pause/resume + add reinforcement + edit every 10 rounds
|
||||
if (r % 10 === 0 && turnInRound === 0) {
|
||||
await recordAsync(`r${r} pause`, () => pauseCombat());
|
||||
await recordAsync(`r${r} addReinforcement`, () => addMonsterParticipant(`Reinforce${r}`, 10, 1));
|
||||
await recordAsync(`r${r} edit Rogue initiative`, () => editParticipant('Rogue', { initiative: 20 }));
|
||||
await recordAsync(`r${r} resume`, () => resumeCombat());
|
||||
await record(`r${r} pause`, () => pauseCombat());
|
||||
await record(`r${r} addReinforcement`, () => addMonsterParticipant(`Reinforce${r}`, 10, 1));
|
||||
await record(`r${r} edit Rogue initiative`, () => editParticipant('Rogue', { initiative: 20 }));
|
||||
await record(`r${r} resume`, () => resumeCombat());
|
||||
}
|
||||
|
||||
// create a same-init tie + drag every 15 rounds (exercises reorderParticipants)
|
||||
if (r % 15 === 0 && turnInRound === 5) {
|
||||
const g1 = any('Goblin1');
|
||||
if (g1 && alive('Goblin2')) {
|
||||
record(`r${r} tie Goblin2->Goblin1 init`, () => editParticipant('Goblin2', { initiative: g1.initiative }));
|
||||
record(`r${r} drag Goblin2 before Goblin1`, () => dragTie('Goblin2', 'Goblin1'));
|
||||
await record(`r${r} tie Goblin2->Goblin1 init`, () => editParticipant('Goblin2', { initiative: g1.initiative }));
|
||||
await record(`r${r} drag Goblin2 before Goblin1`, () => dragTie('Goblin2', 'Goblin1'));
|
||||
}
|
||||
}
|
||||
|
||||
// death scenarios: drop a PC to 0, death saves, revive
|
||||
if (r === 25 && turnInRound === 0) {
|
||||
await recordAsync(`r${r} drop Rogue`, () => applyDamage('Rogue', 99));
|
||||
record(`r${r} deathSave1 Rogue`, () => deathSaveAction('Rogue', 'fail', 1));
|
||||
record(`r${r} revive Rogue`, () => applyHeal('Rogue', 22));
|
||||
await record(`r${r} drop Rogue`, () => applyDamage('Rogue', 99));
|
||||
await record(`r${r} deathSave1 Rogue`, () => deathSaveAction('Rogue', 'fail', 1));
|
||||
await record(`r${r} revive Rogue`, () => applyHeal('Rogue', 22));
|
||||
}
|
||||
// round 50: full 3-success death-save path (isDying) on Cleric, then remove
|
||||
if (r === 50 && turnInRound === 0) {
|
||||
await recordAsync(`r${r} drop Cleric`, () => applyDamage('Cleric', 99));
|
||||
await recordAsync(`r${r} deathSave Cleric x3 (isDying)`, async () => {
|
||||
deathSaveAction('Cleric', 'fail', 1);
|
||||
deathSaveAction('Cleric', 'fail', 2);
|
||||
deathSaveAction('Cleric', 'fail', 3); // → dead
|
||||
await record(`r${r} drop Cleric`, () => applyDamage('Cleric', 99));
|
||||
await record(`r${r} deathSave Cleric x3 (isDying)`, async () => {
|
||||
await deathSaveAction('Cleric', 'fail', 1);
|
||||
await deathSaveAction('Cleric', 'fail', 2);
|
||||
await deathSaveAction('Cleric', 'fail', 3);
|
||||
});
|
||||
const cl = any('Cleric');
|
||||
if (cl && cl.isDying) record(`r${r} remove dying Cleric`, () => removeParticipantByName('Cleric'));
|
||||
if (cl && cl.isDying) await record(`r${r} remove dying Cleric`, () => removeParticipantByName('Cleric'));
|
||||
}
|
||||
|
||||
// remove a reinforcement every 30 rounds
|
||||
if (r % 30 === 0 && turnInRound === 1) {
|
||||
const rein = any(`Reinforce${r - 10}`);
|
||||
if (rein) record(`r${r} remove Reinforce${r - 10}`, () => removeParticipantByName(`Reinforce${r - 10}`));
|
||||
if (rein) await record(`r${r} remove Reinforce${r - 10}`, () => removeParticipantByName(`Reinforce${r - 10}`));
|
||||
}
|
||||
|
||||
// toggle hide hp every 20 rounds
|
||||
if (r % 20 === 0 && turnInRound === 0) {
|
||||
record(`r${r} toggleHidePlayerHp`, () => toggleHidePlayerHpAction());
|
||||
record(`r${r} toggleHidePlayerHp back`, () => toggleHidePlayerHpAction());
|
||||
await record(`r${r} toggleHidePlayerHp`, () => toggleHidePlayerHpAction());
|
||||
await record(`r${r} toggleHidePlayerHp back`, () => toggleHidePlayerHpAction());
|
||||
}
|
||||
|
||||
// rotation integrity check every 10 rounds at round start
|
||||
if (turnInRound === 0 && r % 10 === 0) {
|
||||
record(`r${r} rotation-check`, () => {
|
||||
await record(`r${r} rotation-check`, () => {
|
||||
const order = enc.turnOrderIds || [];
|
||||
const uniq = new Set(order);
|
||||
if (uniq.size !== order.length) throw new Error(`turnOrderIds dup: ${JSON.stringify(order)}`);
|
||||
@@ -297,11 +261,9 @@ test('full 100-round combat scenario (shared, no React)', async () => {
|
||||
});
|
||||
}
|
||||
|
||||
// advance turn
|
||||
await recordAsync(`r${r} turn${turnInRound} nextTurn`, () => nextTurnAction());
|
||||
await record(`r${r} turn${turnInRound} nextTurn`, () => nextTurnAction());
|
||||
turnInRound++;
|
||||
|
||||
// round wrap detected
|
||||
if (enc.round > prevRound) {
|
||||
roundsDone++;
|
||||
prevRound = enc.round;
|
||||
@@ -309,9 +271,8 @@ test('full 100-round combat scenario (shared, no React)', async () => {
|
||||
}
|
||||
}
|
||||
|
||||
await recordAsync('endCombat', () => endCombat());
|
||||
await record('endCombat', () => endCombat());
|
||||
|
||||
// ---------- report ----------
|
||||
const failed = RESULTS.filter(x => !x.ok);
|
||||
if (failed.length > 0) {
|
||||
const msg = failed.map(f => `FAIL [${f.phase}]: ${f.err}`).join('\n');
|
||||
@@ -321,14 +282,7 @@ test('full 100-round combat scenario (shared, no React)', async () => {
|
||||
expect(failed).toEqual([]);
|
||||
expect(roundsDone).toBe(ROUNDS);
|
||||
|
||||
// lifecycle assertions (activeDisplay mirrors combat state)
|
||||
expect(enc.isStarted).toBe(false);
|
||||
expect(enc.round).toBe(0);
|
||||
expect(enc.currentTurnParticipantId).toBeNull();
|
||||
expect(display.activeCampaignId).toBeNull();
|
||||
expect(display.activeEncounterId).toBeNull();
|
||||
});
|
||||
|
||||
function anyById(id) {
|
||||
return enc.participants.find(p => p.id === id);
|
||||
}
|
||||
|
||||
@@ -34,18 +34,22 @@ describe('Logs -> Firebase', () => {
|
||||
await waitFor(() => findLogCalls().some(c => /Combat started/.test(c.data.message)));
|
||||
const logCall = findLogCalls().find(c => /Combat started/.test(c.data.message));
|
||||
expect(logCall.data).toHaveProperty('message');
|
||||
expect(logCall.data).toHaveProperty('timestamp');
|
||||
expect(logCall.data).toHaveProperty('ts');
|
||||
expect(logCall.data.message).toMatch(/Combat started/);
|
||||
});
|
||||
|
||||
test('logAction: includes undo payload', async () => {
|
||||
test('logAction: includes lean undo data', async () => {
|
||||
await setupReady('UndoCamp', 'UndoEnc');
|
||||
await addMonsterViaUI('Mob', 10, 2);
|
||||
await startCombatViaUI();
|
||||
await waitFor(() => findLogCalls().some(c => /Combat started/.test(c.data.message)));
|
||||
const logCall = findLogCalls().find(c => /Combat started/.test(c.data.message));
|
||||
expect(logCall.data.undo).toBeTruthy();
|
||||
expect(logCall.data.undo).toHaveProperty('updates');
|
||||
expect(logCall.data.undo).toHaveProperty('isStarted', false);
|
||||
expect(logCall.data.undo).toHaveProperty('round', 0);
|
||||
expect(logCall.data.type).toBe('start_encounter');
|
||||
expect(logCall.data).toHaveProperty('snapshot');
|
||||
expect(logCall.data.undone).toBe(false);
|
||||
});
|
||||
|
||||
test('clearLogs: writeBatch deletes all log docs', async () => {
|
||||
@@ -69,26 +73,25 @@ describe('Logs -> Firebase', () => {
|
||||
expect(batchDeletes.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('undo: updateDoc on encounter path + marks log undone', async () => {
|
||||
test('undo: tx batch marks log undone + updates encounter', async () => {
|
||||
// seed log via combat start
|
||||
await setupReady('UndoFlowCamp', 'UndoFlowEnc');
|
||||
await addMonsterViaUI('Mob', 10, 2);
|
||||
await startCombatViaUI();
|
||||
await waitFor(() => findLogCalls().length > 0);
|
||||
const logId = findLogCalls()[0].path.split('/').pop();
|
||||
|
||||
await goToLogs();
|
||||
const undoBtns = await screen.findAllByRole('button', { name: /Undo/i });
|
||||
fireEvent.click(undoBtns[0]);
|
||||
|
||||
// tx undo = batch.update on log (undone:true) + encounter
|
||||
await waitFor(() => {
|
||||
const und = getCalls().find(c => c.fn === 'updateDoc' && c.path.includes('/logs/') && c.data.undone === true);
|
||||
const und = getCalls().find(c => c.fn === 'batch.update' && c.path.includes('/logs/') && c.data.undone === true);
|
||||
return und;
|
||||
});
|
||||
const markUndone = getCalls().find(c => c.fn === 'updateDoc' && c.path.includes('/logs/') && c.data.undone === true);
|
||||
const markUndone = getCalls().find(c => c.fn === 'batch.update' && c.path.includes('/logs/') && c.data.undone === true);
|
||||
expect(markUndone.data.undone).toBe(true);
|
||||
// encounter path updated with undo payload (any encounter update after undo click)
|
||||
const encUndo = getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/'));
|
||||
const encUndo = getCalls().filter(c => c.fn === 'batch.update' && c.path.includes('/encounters/'));
|
||||
expect(encUndo.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user