feat(turn): D&D 5e death saves — success/fail tracking

Old model broken: single deathSaves counter, 3=revive. No fails tracked,
successes conflated with fails. DM couldn't model real death save outcomes.

New model (D&D 5e):
- deathSave(enc, id, type, n) — type='success'|'fail', n=1|2|3
- Participant fields: deathSaves (successes), deathFails, isStable, isDying
- 3 successes = stable (0hp unconscious, safe until healed)
- 3 failures = dead (isDying, caller animates removal)
- Toggling same pip = undo that pip
- Returns { patch, log, status } — status: 'stable'|'dead'|'pending'
  isDying back-compat flag kept for App.js removal animation

App.js:
- UI split into green ✓ saves row + red ✕ fails row
- Status badges: Stabilized (emerald) / Dying (red pulse)
- handleDeathSaveChange(participantId, type, saveNumber) — new sig
- makeParticipant init: deathFails + isStable defaults

Data loss: old single-counter participants lose saves (feature didn't work,
no real state to preserve). User confirmed acceptable.

Tests:
- turn.deathsave.test.js: RED-then-GREEN, 3-success stable, 3-fail dead,
  independent tracking, new signature
- Updated 6 callers across characterization/combat/dead-skip/logging/scenario
- Logs UI tests: new title selectors (Success N / Fail N)

243 tests green.
This commit is contained in:
david raistrick
2026-07-04 17:56:14 -04:00
parent f2797595f4
commit 9c90c1500c
10 changed files with 214 additions and 72 deletions
+6 -3
View File
@@ -38,9 +38,12 @@ Backlog of bugs + long-term items. Milestones live in REWORK_PLAN.md.
format for new entries. format for new entries.
- Related: BUG-7 (reorder no undo). - Related: BUG-7 (reorder no undo).
### Death saves: need fails counter ### Death saves: D&D 5e model (FIXED)
- Current: saves only (`deathSaves` counter, 3 saves = revive). No fails. - FIXED — separate success/fail tracking. `deathSave(enc, id, type, n)`
- D&D 5e: 3 saves = stable, 3 fails = dead. Track both. type='success'|'fail'. Fields: `deathSaves`, `deathFails`, `isStable`,
`isDying`. 3 success=stable, 3 fail=dead. Returns `{patch, log, status}`.
Old single-counter broken (successes missing, treated saves as fails).
Old data lost (user OK — feature didn't work). UI: green ✓ row + red ✕ row.
### Custom condition field ### Custom condition field
- Conditions hardcoded list. No way for DM to add custom. - Conditions hardcoded list. No way for DM to add custom.
+12 -12
View File
@@ -247,22 +247,22 @@ describe('applyHpChange', () => {
}); });
describe('deathSave', () => { describe('deathSave', () => {
test('increments saves', () => { test('increments fails', () => {
const ps = [p('a', 10, { currentHp: 0, deathSaves: 0 })]; const ps = [p('a', 10, { currentHp: 0, deathFails: 0 })];
const { patch } = deathSave(enc(ps), 'a', 1); const { patch } = deathSave(enc(ps), 'a', 'fail', 1);
expect(patch.participants[0].deathSaves).toBe(1); expect(patch.participants[0].deathFails).toBe(1);
}); });
test('clicking same save decrements (toggle)', () => { test('clicking same fail decrements (toggle)', () => {
const ps = [p('a', 10, { currentHp: 0, deathSaves: 2 })]; const ps = [p('a', 10, { currentHp: 0, deathFails: 2 })];
const { patch } = deathSave(enc(ps), 'a', 2); const { patch } = deathSave(enc(ps), 'a', 'fail', 2);
expect(patch.participants[0].deathSaves).toBe(1); expect(patch.participants[0].deathFails).toBe(1);
}); });
test('third save sets isDying', () => { test('third fail sets isDying', () => {
const ps = [p('a', 10, { currentHp: 0, deathSaves: 2 })]; const ps = [p('a', 10, { currentHp: 0, deathFails: 2 })];
const result = deathSave(enc(ps), 'a', 3); const result = deathSave(enc(ps), 'a', 'fail', 3);
expect(result.patch.participants[0].deathSaves).toBe(3); expect(result.patch.participants[0].deathFails).toBe(3);
expect(result.patch.participants[0].isDying).toBe(true); expect(result.patch.participants[0].isDying).toBe(true);
expect(result.isDying).toBe(true); expect(result.isDying).toBe(true);
}); });
+1 -1
View File
@@ -162,7 +162,7 @@ describe('combat integrity (100 rounds, full op coverage)', () => {
} }
// 5. deathSave // 5. deathSave
if (actor && actor.currentHp <= 0 && !actor.isNpc) { if (actor && actor.currentHp <= 0 && !actor.isNpc) {
try { e = apply(e, deathSave(e, actor.id, 1)); } catch (err) {} try { e = apply(e, deathSave(e, actor.id, 'fail', 1)); } catch (err) {}
} }
// 6. removeParticipant // 6. removeParticipant
if (totalTurns % 5 === 0) { if (totalTurns % 5 === 0) {
+2 -2
View File
@@ -56,10 +56,10 @@ describe('unified: death deactivates, dead skipped in rotation', () => {
// kill b (current = a) // kill b (current = a)
e = { ...e, ...applyHpChange(e, 'b', 'damage', 100).patch }; e = { ...e, ...applyHpChange(e, 'b', 'damage', 100).patch };
// b is dead: DM can still fire deathSave (manual action) // b is dead: DM can still fire deathSave (manual action)
const r = deathSave(e, 'b', 1); const r = deathSave(e, 'b', 'fail', 1);
expect(r.patch).toBeTruthy(); expect(r.patch).toBeTruthy();
const b = r.patch.participants.find(x => x.id === 'b'); const b = r.patch.participants.find(x => x.id === 'b');
expect(b.deathSaves).toBe(1); expect(b.deathFails).toBe(1);
}); });
// D1 unification: shared now matches App main — death flips isActive=false. // D1 unification: shared now matches App main — death flips isActive=false.
+90
View File
@@ -0,0 +1,90 @@
// Death saves: broken model. Current = single counter, 3=dying. D&D 5e needs
// separate success/fail tracking:
// 3 successes = stable (0hp unconscious, safe until healed)
// 3 failures = dead
// Current tracks "saves" (really fails via red X UI), no successes at all.
// "Stable" state doesn't exist.
//
// RED: prove current can't model 3-success stability.
'use strict';
const shared = require('@ttrpg/shared');
const { makeParticipant, startEncounter, applyHpChange, deathSave } = shared;
function p(id) {
return makeParticipant({ id, name: id, type: 'character',
initiative: 10, maxHp: 100, currentHp: 100 });
}
function enc(ps, extra = {}) {
return { name:'t', participants:ps, isStarted:false, isPaused:false,
round:0, currentTurnParticipantId:null, turnOrderIds:[], ...extra };
}
const apply = (e, r) => r && r.patch ? { ...e, ...r.patch } : e;
describe('death saves: missing success/stable model', () => {
test('3 successes makes character stable (not dead, not dying)', () => {
// Character at 0hp. Roll 3 successful death saves.
let e = enc([p('a')]);
e = apply(e, startEncounter(e));
e = apply(e, applyHpChange(e, 'a', 'damage', 100)); // 0hp
expect(e.participants[0].currentHp).toBe(0);
// Roll 3 successful saves. Should mark stable.
e = apply(e, deathSave(e, 'a', 'success', 1));
e = apply(e, deathSave(e, 'a', 'success', 2));
const r3 = deathSave(e, 'a', 'success', 3);
e = apply(e, r3);
// RED: current deathSave signature = (enc, id, saveNumber). No type arg.
// Will throw or misbehave. Want: status field.
expect(r3.status).toBe('stable');
expect(e.participants[0].isDying).toBe(false);
expect(e.participants[0].isStable).toBe(true);
expect(e.participants[0].deathFails).toBe(0);
});
test('3 failures makes character dead (isDying for removal)', () => {
let e = enc([p('a')]);
e = apply(e, startEncounter(e));
e = apply(e, applyHpChange(e, 'a', 'damage', 100));
const r1 = deathSave(e, 'a', 'fail', 1);
e = apply(e, r1);
const r2 = deathSave(e, 'a', 'fail', 2);
e = apply(e, r2);
const r3 = deathSave(e, 'a', 'fail', 3);
e = apply(e, r3);
expect(r3.status).toBe('dead');
expect(e.participants[0].isDying).toBe(true);
expect(e.participants[0].deathFails).toBe(3);
});
test('successes and fails tracked independently', () => {
// Mixed: 1 success, 2 fails, then 2 more successes = stable.
let e = enc([p('a')]);
e = apply(e, startEncounter(e));
e = apply(e, applyHpChange(e, 'a', 'damage', 100));
e = apply(e, deathSave(e, 'a', 'success', 1));
expect(e.participants[0].deathSaves).toBe(1);
expect(e.participants[0].deathFails).toBe(0);
e = apply(e, deathSave(e, 'a', 'fail', 1));
e = apply(e, deathSave(e, 'a', 'fail', 2));
expect(e.participants[0].deathSaves).toBe(1);
expect(e.participants[0].deathFails).toBe(2);
// 2 more successes → total 3 successes → stable
e = apply(e, deathSave(e, 'a', 'success', 2));
const r = deathSave(e, 'a', 'success', 3);
expect(r.status).toBe('stable');
expect(e.participants[0].deathFails).toBe(2); // fails unchanged
});
test('deathSave signature: (enc, id, type, n)', () => {
// type = 'success' | 'fail'. n = 1|2|3.
expect(deathSave.length).toBe(4);
});
});
+1 -1
View File
@@ -93,7 +93,7 @@ describe('Logging contract: mutating ops', () => {
test('deathSave logs', () => { test('deathSave logs', () => {
const started = apply(e, startEncounter(e)); const started = apply(e, startEncounter(e));
const dying = apply(started, applyHpChange(started, 'b', 'damage', 100)); const dying = apply(started, applyHpChange(started, 'b', 'damage', 100));
const r = deathSave(dying, 'b', 1); const r = deathSave(dying, 'b', 'fail', 1);
expectLogged(r); expectLogged(r);
}); });
+49 -25
View File
@@ -129,7 +129,9 @@ function makeParticipant(opts) {
isNpc: opts.isNpc || false, isNpc: opts.isNpc || false,
conditions: opts.conditions || [], conditions: opts.conditions || [],
isActive: opts.isActive !== undefined ? opts.isActive : true, isActive: opts.isActive !== undefined ? opts.isActive : true,
deathSaves: opts.deathSaves || 0, deathSaves: opts.deathSaves || 0, // successes (0-3)
deathFails: opts.deathFails || 0, // failures (0-3)
isStable: opts.isStable || false,
isDying: opts.isDying || false, isDying: opts.isDying || false,
}; };
} }
@@ -492,41 +494,63 @@ function applyHpChange(encounter, participantId, changeType, amount) {
}; };
} }
// DEATH_SAVE — verbatim from ParticipantManager.handleDeathSaveChange // DEATH_SAVE — D&D 5e model. Separate success/fail tracking.
// saveNumber: 1 | 2 | 3. Returns isDying flag if 3rd save hit (client triggers removal animation). // type: 'success' | 'fail'
function deathSave(encounter, participantId, saveNumber) { // n: 1 | 2 | 3 (which pip clicked)
// 3 successes = stable (0hp unconscious, safe). 3 fails = dead (isDying,
// caller animates removal). Toggling same pip = undo that pip.
// Returns { patch, log, status } where status: 'stable'|'dead'|'pending'.
function deathSave(encounter, participantId, type, n) {
const participant = (encounter.participants || []).find(p => p.id === participantId); const participant = (encounter.participants || []).find(p => p.id === participantId);
if (!participant) throw new Error('Participant not found.'); if (!participant) throw new Error('Participant not found.');
const currentSaves = participant.deathSaves || 0; if (type !== 'success' && type !== 'fail') {
const newSaves = currentSaves === saveNumber ? saveNumber - 1 : saveNumber; throw new Error(`deathSave type must be 'success' or 'fail', got "${type}".`);
}
const name = participant.name; const name = participant.name;
const undo = { participants: encounter.participants || [] }; const undo = { participants: encounter.participants || [] };
if (newSaves === 3) { // Toggle: clicking current-value pip decrements (undo that pip).
// Mark dying — caller waits for animation, then calls removeParticipant. const current = type === 'success'
const updatedParticipants = (encounter.participants || []).map(p => ? (participant.deathSaves || 0)
p.id === participantId ? { ...p, deathSaves: newSaves, isDying: true } : p : (participant.deathFails || 0);
); const next = current === n ? n - 1 : n;
return {
patch: { participants: updatedParticipants }, const field = type === 'success' ? 'deathSaves' : 'deathFails';
log: { const updates = { [field]: next };
message: `${name} failed 3 death saves — dying`,
undo, // Clear terminal flags on any change (re-eval below).
}, let status = 'pending';
isDying: true, const newSuccesses = type === 'success' ? next : (participant.deathSaves || 0);
}; const newFails = type === 'fail' ? next : (participant.deathFails || 0);
if (newSuccesses >= 3) {
updates.isStable = true;
updates.isDying = false;
status = 'stable';
} else if (newFails >= 3) {
updates.isStable = false;
updates.isDying = true;
status = 'dead';
} else {
updates.isStable = false;
updates.isDying = false;
} }
const updatedParticipants = (encounter.participants || []).map(p => const updatedParticipants = (encounter.participants || []).map(p =>
p.id === participantId ? { ...p, deathSaves: newSaves } : p p.id === participantId ? { ...p, ...updates } : p
); );
const message = status === 'stable'
? `${name} stabilized (3 death saves)`
: status === 'dead'
? `${name} failed 3 death saves — dead`
: `${name} death ${type}: ${next}/3`;
return { return {
patch: { participants: updatedParticipants }, patch: { participants: updatedParticipants },
log: { log: { message, undo },
message: `${name} death save: ${newSaves}/3`, status,
undo, isDying: status === 'dead', // back-compat for App.js handler
},
isDying: false,
}; };
} }
+40 -15
View File
@@ -873,6 +873,8 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
conditions: [], conditions: [],
isActive: true, isActive: true,
deathSaves: 0, deathSaves: 0,
deathFails: 0,
isStable: false,
isDying: false, isDying: false,
}; };
@@ -930,6 +932,8 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
isActive: true, isActive: true,
isNpc: false, isNpc: false,
deathSaves: 0, deathSaves: 0,
deathFails: 0,
isStable: false,
isDying: false, isDying: false,
}; };
}); });
@@ -1053,10 +1057,10 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
} }
}; };
const handleDeathSaveChange = async (participantId, saveNumber) => { const handleDeathSaveChange = async (participantId, type, saveNumber) => {
if (!db) return; if (!db) return;
try { try {
const { patch, isDying } = combatDeathSave(encounter, participantId, saveNumber); const { patch, isDying } = combatDeathSave(encounter, participantId, type, saveNumber);
await storage.updateDoc(encounterPath, patch); await storage.updateDoc(encounterPath, patch);
if (isDying) { if (isDying) {
setTimeout(async () => { setTimeout(async () => {
@@ -1370,20 +1374,41 @@ function ParticipantManager({ encounter, encounterPath, campaignCharacters }) {
<span>HP: {p.currentHp}/{p.maxHp}</span> <span>HP: {p.currentHp}/{p.maxHp}</span>
</div> </div>
{/* Death Saves - only player characters make death saving throws */} {/* Death saves - D&D 5e: successes + fails separate */}
{isDead && encounter.isStarted && p.type === 'character' && ( {isDead && encounter.isStarted && p.type === 'character' && (
<div className="mt-2 flex items-center space-x-2"> <div className="mt-2 flex flex-col space-y-1">
<span className="text-xs text-red-300 font-medium">Death Saves:</span> {p.isStable && (
{[1, 2, 3].map(saveNum => ( <div className="text-xs text-emerald-300 font-medium">Stabilized</div>
<button )}
key={saveNum} {p.isDying && !p.isStable && (
onClick={() => handleDeathSaveChange(p.id, saveNum)} <div className="text-xs text-red-400 font-medium animate-pulse">Dying</div>
className={`w-6 h-6 rounded border-2 transition-all ${(p.deathSaves || 0) >= saveNum ? 'bg-red-600 border-red-500' : 'bg-stone-800 border-stone-600 hover:border-red-400'} ${saveNum === 3 && (p.deathSaves || 0) === 3 ? 'animate-pulse' : ''}`} )}
title={`Death save ${saveNum}`} <div className="flex items-center space-x-2">
> <span className="text-xs text-emerald-300 font-medium w-10">Saves:</span>
{(p.deathSaves || 0) >= saveNum && <span className="text-white text-sm"></span>} {[1, 2, 3].map(saveNum => (
</button> <button
))} key={saveNum}
onClick={() => handleDeathSaveChange(p.id, 'success', saveNum)}
className={`w-6 h-6 rounded border-2 transition-all ${(p.deathSaves || 0) >= saveNum ? 'bg-emerald-600 border-emerald-500' : 'bg-stone-800 border-stone-600 hover:border-emerald-400'}`}
title={`Success ${saveNum}`}
>
{(p.deathSaves || 0) >= saveNum && <span className="text-white text-sm"></span>}
</button>
))}
</div>
<div className="flex items-center space-x-2">
<span className="text-xs text-red-300 font-medium w-10">Fails:</span>
{[1, 2, 3].map(failNum => (
<button
key={failNum}
onClick={() => handleDeathSaveChange(p.id, 'fail', failNum)}
className={`w-6 h-6 rounded border-2 transition-all ${(p.deathFails || 0) >= failNum ? 'bg-red-600 border-red-500' : 'bg-stone-800 border-stone-600 hover:border-red-400'} ${failNum === 3 && (p.deathFails || 0) >= 3 ? 'animate-pulse' : ''}`}
title={`Fail ${failNum}`}
>
{(p.deathFails || 0) >= failNum && <span className="text-white text-sm"></span>}
</button>
))}
</div>
</div> </div>
)} )}
+6 -6
View File
@@ -160,10 +160,10 @@ function removeParticipantByName(name) {
if (!p) throw new Error(`no remove target: ${name}`); if (!p) throw new Error(`no remove target: ${name}`);
applyEnc(removeParticipant(enc, p.id).patch); applyEnc(removeParticipant(enc, p.id).patch);
} }
function deathSaveAction(name, saveNum) { function deathSaveAction(name, type, saveNum) {
const p = any(name); const p = any(name);
if (!p) throw new Error(`no deathsave target: ${name}`); if (!p) throw new Error(`no deathsave target: ${name}`);
applyEnc(combatDeathSave(enc, p.id, saveNum).patch); applyEnc(combatDeathSave(enc, p.id, type, saveNum).patch);
} }
function dragTie(draggedName, targetName) { function dragTie(draggedName, targetName) {
const d = any(draggedName), t = any(targetName); const d = any(draggedName), t = any(targetName);
@@ -254,16 +254,16 @@ test('full 100-round combat scenario (shared, no React)', async () => {
// death scenarios: drop a PC to 0, death saves, revive // death scenarios: drop a PC to 0, death saves, revive
if (r === 25 && turnInRound === 0) { if (r === 25 && turnInRound === 0) {
await recordAsync(`r${r} drop Rogue`, () => applyDamage('Rogue', 99)); await recordAsync(`r${r} drop Rogue`, () => applyDamage('Rogue', 99));
record(`r${r} deathSave1 Rogue`, () => deathSaveAction('Rogue', 1)); record(`r${r} deathSave1 Rogue`, () => deathSaveAction('Rogue', 'fail', 1));
record(`r${r} revive Rogue`, () => applyHeal('Rogue', 22)); record(`r${r} revive Rogue`, () => applyHeal('Rogue', 22));
} }
// round 50: full 3-success death-save path (isDying) on Cleric, then remove // round 50: full 3-success death-save path (isDying) on Cleric, then remove
if (r === 50 && turnInRound === 0) { if (r === 50 && turnInRound === 0) {
await recordAsync(`r${r} drop Cleric`, () => applyDamage('Cleric', 99)); await recordAsync(`r${r} drop Cleric`, () => applyDamage('Cleric', 99));
await recordAsync(`r${r} deathSave Cleric x3 (isDying)`, async () => { await recordAsync(`r${r} deathSave Cleric x3 (isDying)`, async () => {
deathSaveAction('Cleric', 1); deathSaveAction('Cleric', 'fail', 1);
deathSaveAction('Cleric', 2); deathSaveAction('Cleric', 'fail', 2);
deathSaveAction('Cleric', 3); // → isDying true deathSaveAction('Cleric', 'fail', 3); // → dead
}); });
const cl = any('Cleric'); const cl = any('Cleric');
if (cl && cl.isDying) record(`r${r} remove dying Cleric`, () => removeParticipantByName('Cleric')); if (cl && cl.isDying) record(`r${r} remove dying Cleric`, () => removeParticipantByName('Cleric'));
+7 -7
View File
@@ -125,7 +125,7 @@ describe('DeathSave -> Firebase', () => {
await waitFor(() => lastEncCall()?.data?.participants?.[0]?.currentHp === 0); await waitFor(() => lastEncCall()?.data?.participants?.[0]?.currentHp === 0);
// death save buttons appear // death save buttons appear
const save1 = screen.getByTitle('Death save 1'); const save1 = screen.getByTitle('Success 1');
fireEvent.click(save1); fireEvent.click(save1);
await waitFor(() => lastEncCall()?.data?.participants?.[0]?.deathSaves === 1); await waitFor(() => lastEncCall()?.data?.participants?.[0]?.deathSaves === 1);
expect(lastEncCall().data.participants[0].deathSaves).toBe(1); expect(lastEncCall().data.participants[0].deathSaves).toBe(1);
@@ -159,13 +159,13 @@ describe('DeathSave -> Firebase', () => {
fireEvent.click(screen.getByTitle('Damage')); fireEvent.click(screen.getByTitle('Damage'));
await waitFor(() => lastEncCall()?.data?.participants?.[0]?.currentHp === 0); await waitFor(() => lastEncCall()?.data?.participants?.[0]?.currentHp === 0);
fireEvent.click(screen.getByTitle('Death save 1')); fireEvent.click(screen.getByTitle('Fail 1'));
await waitFor(() => lastEncCall()?.data?.participants?.[0]?.deathSaves === 1); await waitFor(() => lastEncCall()?.data?.participants?.[0]?.deathFails === 1);
fireEvent.click(screen.getByTitle('Death save 2')); fireEvent.click(screen.getByTitle('Fail 2'));
await waitFor(() => lastEncCall()?.data?.participants?.[0]?.deathSaves === 2); await waitFor(() => lastEncCall()?.data?.participants?.[0]?.deathFails === 2);
fireEvent.click(screen.getByTitle('Death save 3')); fireEvent.click(screen.getByTitle('Fail 3'));
await waitFor(() => lastEncCall()?.data?.participants?.[0]?.isDying === true); await waitFor(() => lastEncCall()?.data?.participants?.[0]?.isDying === true);
expect(lastEncCall().data.participants[0].isDying).toBe(true); expect(lastEncCall().data.participants[0].isDying).toBe(true);
expect(lastEncCall().data.participants[0].deathSaves).toBe(3); expect(lastEncCall().data.participants[0].deathFails).toBe(3);
}); });
}); });