From ebeec58ee7092bb0098d4f42ed803f37a230083a Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 08:46:00 -0800 Subject: [PATCH] Vitals: hand combat the tick when no heal is landing in a fight Health under a heal line holds the arbiter on Buffing by itself. A melee character with a shield was held in Buffing for 17 s with no heal landing (a used-up kit re-sent), stopped attacking the boss and died. Now, in a fight (a monster within Monster Range), 6 s under a heal line with no heal landing (health up 3 points, the HP failsafe's test) hands combat the tick for 5 s, then the vitals hold it again; a heal landing or health over the line ends the episode. 6 s is VirindiTank's give-up for one kit (3 s to start, 3 s for the result). - The vitals step still runs every tick meanwhile (kits and potions go), but makes no stance change or wield for a vital while combat has the tick: no wand swap for Heal Self, and no peace switch for a kit in any stance (Magic included, with Use Kits in Magic Mode). A caster already in Magic stance casts its heal spell as before. - With no peace switch going out, Kit Min Success (and Stamina Kit Min Success) is computed in the current stance, not as if in peace. - A release waits for a heal under way: a kit whose heal motion has played (heal grace's NoteKitProgress), or a wand wield in flight. - The hold resets whenever the macro is off (the stop, and the HP failsafe's recall stop), so a restart in a fight starts a fresh count. Tests: HealHoldTests (new, 6). Co-Authored-By: Claude Opus 5.5 --- .../Combat/BuffManager.HealHold.cs | 113 +++++++ .../Combat/BuffManager.cs | 30 +- Tools/RynthCore.RynthAiHostTests/Program.cs | 1 + .../Tests/HealHoldTests.cs | 298 ++++++++++++++++++ 4 files changed, 435 insertions(+), 7 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealHold.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/HealHoldTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealHold.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealHold.cs new file mode 100644 index 0000000..3b5b56f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealHold.cs @@ -0,0 +1,113 @@ +// ============================================================================ +// RynthSuite - Combat/BuffManager.HealHold.cs +// The Buffing hold for a heal, capped when no heal is landing. +// +// Health under a heal line wins the arbiter by itself (WantsVitalRecharge, ahead of combat and +// nav). That is right while heals land, and wrong when none does: a melee character with a shield +// went to Buffing at 48% health, stopped attacking the boss, and stood there 17 s re-sending a +// healing kit the server no longer had until it died. Nothing healed, and nothing fought either. +// +// VirindiTank's give-up for one kit: re-sent until the heal motion starts, given up after 3 s, +// then up to 3 s for its result. So: HealHoldGiveUpMs (6 s) under a heal line with no heal landing +// (health up FailsafeRiseMinPct, the HP failsafe's own test) hands combat the tick for +// HealHoldReleaseMs (5 s, HealUnavailableMs, the backoff after "nothing could heal"), then the +// vitals hold it again. A heal landing, or health back over the line, ends the episode. Only in a +// fight (InCombatNow): with no monster in range there is nothing for combat to do with the tick. +// +// The vitals step still runs every tick meanwhile (OnHeartbeat runs whatever the arbiter decides): +// kits and potions keep going. What it does not do while combat has the tick is change stance or +// wield for a heal (a wand swap for Heal Self, peace mode for a kit, in any stance): combat would take the weapon +// back on its next tick and the two would trade the hands for nothing. A caster already in Magic +// stance casts as before. The cast in flight (PendingSpellId) still holds the arbiter by itself. +// ============================================================================ + +using System; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +public partial class BuffManager +{ + internal const double HealHoldGiveUpMs = 6000; + internal const double HealHoldReleaseMs = 5000; + + private DateTime _hhSince = DateTime.MinValue; + private int _hhLow; + private DateTime _hhReleasedUntil = DateTime.MinValue; + // Set for one CheckVitals while combat has the tick and the character is out of Magic stance. + private bool _vitalsNoStanceChange; + // Set for one CheckVitals while combat has the tick, in any stance: a kit sends no peace switch. + private bool _vitalsNoPeaceSwitch; + + /// Times the hold was handed to combat (tests, status). + internal int HealHoldReleases { get; private set; } + + /// True while combat has the tick because no heal has been landing (see the header). + internal bool HealHoldReleased => _hhReleasedUntil != DateTime.MinValue && Now < _hhReleasedUntil; + + /// + /// A heal already under way that a release would starve: a kit in flight whose heal motion has + /// played (NoteKitProgress), or the wand swap for a heal spell in flight (TickWandSwap's state, or + /// the wand's wield sent and not answered). + /// + private bool HealUnderWay() => + (_kitUsedAt != DateTime.MinValue && _kitLandedAt == DateTime.MinValue && _kitSawAnimating) + || _wandSwap.Active || _pendingWieldId != 0; + + /// Ends a hold episode: the next heal line starts a fresh HealHoldGiveUpMs count. + private void ResetHealHold() + { + _hhSince = DateTime.MinValue; + _hhReleasedUntil = DateTime.MinValue; + } + + /// Once per heartbeat while the macro runs, before the vitals step. + private void TickHealHold() + { + DateTime now = Now; + int hp = _vitals.HealthPct; + // Only in a fight (a monster within Monster Range): with nothing to fight, handing the tick on + // would give it to nav or looting at low health, walking on into the next pull. + // The macro being off is handled by the caller: HeartbeatCore returns before this tick then, and + // calls ResetHealHold instead, so a restart in a fight starts a fresh count. + if (_vitals.MaxHealth == 0 || Portaling() || !HealthUnderAnyLine(hp, _vitals.StaminaPct) || !InCombatNow()) + { + ResetHealHold(); + return; + } + if (_hhSince == DateTime.MinValue) + { + _hhSince = now; + _hhLow = hp; + return; + } + if (hp >= _hhLow + FailsafeRiseMinPct) + { + // A heal landed: the heals work, the vitals hold the tick again and the count starts over. + if (HealHoldReleased) + _host.Log($"[Vitals] Heal hold: a heal landed ({_hhLow}% -> {hp}%): the vitals hold the tick again."); + _hhSince = now; + _hhLow = hp; + _hhReleasedUntil = DateTime.MinValue; + return; + } + if (hp < _hhLow) _hhLow = hp; + if (_hhReleasedUntil != DateTime.MinValue) + { + if (now < _hhReleasedUntil) return; + // The window is over: hold again, and count the next HealHoldGiveUpMs from here. + _hhReleasedUntil = DateTime.MinValue; + _hhSince = now; + return; + } + double heldMs = (now - _hhSince).TotalMilliseconds; + if (heldMs < HealHoldGiveUpMs) return; + // A heal the server is playing is not cut off: combat would re-stance or re-wield over it. The + // release waits for it (a removed kit never animates, so that case still releases). + if (HealUnderWay()) return; + _hhReleasedUntil = now.AddMilliseconds(HealHoldReleaseMs); + HealHoldReleases++; + _host.Log($"[Vitals] Heal hold: health {hp}% under a heal line and no heal landed in {heldMs / 1000:0.#} s: " + + $"combat gets the tick for {HealHoldReleaseMs / 1000:0} s (kits and potions keep going; no stance change for a heal)."); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 36146f5..d23cb64 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -1168,7 +1168,8 @@ public partial class BuffManager : IDisposable /// and they need the same mid-cast protection a buff gets. Side-effect free: /// CheckVitals repopulates these flags every cycle it reaches. /// - public bool WantsVitalRecharge => _isHealingSelf || _isRechargingMana || _isRechargingStamina || WantsHealNow() || WantsManaNow(); + public bool WantsVitalRecharge => (!HealHoldReleased && (_isHealingSelf || WantsHealNow())) + || _isRechargingMana || _isRechargingStamina || WantsManaNow(); // Health below a heal line wins the arbiter's tick by itself. The flags above are only set on // a tick where CheckVitals actually ran and acted, and it doesn't run while the client is busy @@ -1402,7 +1403,7 @@ public partial class BuffManager : IDisposable TickRechargeRequest(); // /ra recharge: one vitals pass, macro on or off (BuffManager.Recharge.cs) TickOneTouchRequest(); // /ra heal, /ra stam, /ra mana: one-touch recharge, macro on or off (BuffManager.OneTouch.cs) - if (!_settings.IsMacroRunning) { DropWandSwap("the macro stopped"); return; } + if (!_settings.IsMacroRunning) { DropWandSwap("the macro stopped"); ResetHealHold(); return; } // A wand swap's next step goes as soon as the server has answered the last (before the cast gates). NoteModeChange(); @@ -1415,7 +1416,9 @@ public partial class BuffManager : IDisposable // Heals failing at Emergency Heal At: break the cast, then recall (BuffManager.HpFailsafe.cs). TickHpFailsafe(); - if (!_settings.IsMacroRunning) return; + if (!_settings.IsMacroRunning) { ResetHealHold(); return; } // the failsafe stopped it for a recall + // No heal landing under a heal line: combat gets the tick for a while (BuffManager.HealHold.cs). + TickHealHold(); // A Magic stance we asked for: watch the client's mode every tick (see ObserveStance). ObserveStance(); @@ -2059,6 +2062,15 @@ public partial class BuffManager : IDisposable } internal bool CheckVitals() // internal for the host tests (VitalsTests) + { + // Combat has the tick (BuffManager.HealHold.cs): no stance change or wield for a vital this pass. + _vitalsNoStanceChange = HealHoldReleased && CurrentCombatMode != CombatMode.Magic; + _vitalsNoPeaceSwitch = HealHoldReleased; // no peace switch for a kit either, Magic stance included + try { return CheckVitalsCore(); } + finally { _vitalsNoStanceChange = false; _vitalsNoPeaceSwitch = false; } + } + + private bool CheckVitalsCore() { int curHealthPct = _vitals.HealthPct; int curManaPct = _vitals.ManaPct; @@ -2474,6 +2486,8 @@ public partial class BuffManager : IDisposable return VitalNo(recoveryWhy); if (CurrentCombatMode != CombatMode.Magic && RynthClock.Now < _vitalSwapBlockedUntil) return VitalNo("wand swap blocked, retrying shortly"); + if (_vitalsNoStanceChange) + return VitalNo("combat has the tick (no heal landed): no wand swap for a spell"); bool urgentHeal = label == LabelHealing && (_oneTouchHealthScope || HealIsUrgent(_vitals.HealthPct, _vitals.StaminaPct)); if (!EnsureMagicMode(urgentHeal: urgentHeal)) { @@ -2725,8 +2739,9 @@ public partial class BuffManager : IDisposable if (KitRetryWait(out string kitWait)) return VitalNo(kitWait); // Too likely to fail on what's missing (KitMinSuccessPct): let the spell have it. uint missing = _vitals.MaxHealth > _vitals.CurrentHealth ? _vitals.MaxHealth - _vitals.CurrentHealth : 0; - if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits, _settings.KitMinSuccessPct)) return VitalNo($"{kit.Name} under Kit Min Success %"); - if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode) + // Released (BuffManager.HealHold.cs): no peace switch goes out, so the chance is the stance it is in. + if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits && !_vitalsNoPeaceSwitch, _settings.KitMinSuccessPct)) return VitalNo($"{kit.Name} under Kit Min Success %"); + if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && !_vitalsNoPeaceSwitch) { // Only a request that went out starts the wait: a refusal (the engine turns stance changes away // around a teleport) leaves no pacing state, so the next tick asks again. @@ -2763,8 +2778,9 @@ public partial class BuffManager : IDisposable if (KitRetryWait(out _)) return false; uint missing = _vitals.MaxStamina > _vitals.CurrentStamina ? _vitals.MaxStamina - _vitals.CurrentStamina : 0; // Its own line (Stamina Kit Min Success %): below it Revitalize Self or a potion goes. - if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits, _settings.StaminaKitMinSuccessPct)) return false; - if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode) + // Released (BuffManager.HealHold.cs): no peace switch goes out, so the chance is the stance it is in. + if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits && !_vitalsNoPeaceSwitch, _settings.StaminaKitMinSuccessPct)) return false; + if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && !_vitalsNoPeaceSwitch) { if (_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the stamina kit")) _lastCastAttempt = RynthClock.Now; diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 9b44e45..22dab0d 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -192,6 +192,7 @@ internal static class Program MonsterStatsTests.Register(runner); MetaSaveTests.Register(runner); HealGraceTests.Register(runner); + HealHoldTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HealHoldTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HealHoldTests.cs new file mode 100644 index 0000000..2ebb69e --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HealHoldTests.cs @@ -0,0 +1,298 @@ +using System; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The Buffing hold: health under Heal At held the +// arbiter on Buffing for 17 s with no heal landing (a used-up kit re-sent), the character stopped +// attacking the boss and died. In a fight, 6 s under a heal line with no heal landing now hands combat +// the tick for 5 s (BuffManager.HealHold.cs). +internal static class HealHoldTests +{ + private const uint Player = 0x500000B6; + private const uint ListedKit = 0x80088BDA; // the stack the Consumables rule was added from + private const uint Kit1 = 0x80073C1B; + private const uint Kit2 = 0x80073C1A; + private const string KitName = "Treated Healing Kit"; + + public static void Register(Runner r) + { + r.Add("heal hold: 6 s under a heal line with no heal landing hands combat the tick for 5 s; a heal landing holds it again", HealHoldReleases); + r.Add("heal hold: while combat has the tick a heal makes no stance change or wand swap; a caster in Magic still casts", HealHoldNoStanceChange); + r.Add("heal hold: a macro stop resets the hold; the first heartbeat after a restart in a fight does not release", HealHoldResetsOnMacroStop); + r.Add("heal hold: no release at 6 s while a kit in flight is animating; a kit that never animates still releases", HealHoldWaitsForAnimatingKit); + r.Add("heal hold: no release at 6 s while a wand wield is in flight; released once it is done", HealHoldWaitsForWield); + r.Add("heal hold: while combat has the tick, Kit Min Success is computed in the current stance, not peace", ReleasedKitChanceNotPeace); + } + + private static BuffManager MeleeSpellRig(out PlayerVitalsCache v, out Func setNow, int mode = CombatMode.Melee, + bool monsterInRange = true) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeCalls = true; + FakeHost.CombatModeValue = mode; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, 33)] = (400, 2); // Life Magic + var host = FakeHost.Create(Player); + var s = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 75, TopOffHP = 75, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false, + }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 48, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, v); + b.SetCharacterSkills(skills); + b.MarkLiveBuffsReadyForTests(); + b.InCombatOverride = () => monsterInRange; // the boss within Monster Range + DateTime now = new DateTime(2026, 1, 1, 12, 0, 50); + b.Clock = () => now; + setNow = t => now = t; + RigSettings = s; + return b; + } + + /// The settings of the last rig built (MeleeSpellRig or KitRig). + private static LegacyUiSettings RigSettings = new(); + + /// A melee character with two healing kits and Life Magic untrained: kits are the only heal. + private static BuffManager KitRig(int mode = CombatMode.Melee, bool modeCalls = false) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeCalls = modeCalls; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.UseOnCalls = true; + FakeHost.CombatModeValue = mode; + FakeHost.Names[Kit1] = KitName; + FakeHost.Names[Kit2] = KitName; + // Life Magic untrained (a read, not the capable stub): kits are the only heal, no Heal Self. + FakeHost.Skills[(Player, 33)] = (10, 1); + var host = FakeHost.Create(Player); + var s = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false, + KitMinSuccessPct = 0, PeaceModeForKits = false, + }; + s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)ListedKit), Name = KitName, Type = "HealthKit" }); + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, v); + b.SetCharacterSkills(skills); + b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, new[] { Kit1, Kit2 })); + RigSettings = s; + return b; + } + + private static void SetHealth(BuffManager b, int hp) + { + var f = typeof(BuffManager).GetField("_vitals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!; + ((PlayerVitalsCache)f.GetValue(b)!).CurrentHealth = (uint)hp; + } + + // HeartbeatCore returns before TickHealHold while the macro is off, so the hold's timer must be reset + // there: a restart in a fight (the HP failsafe's recall turning it back on, too) released at once. + private static void HealHoldResetsOnMacroStop() + { + var b = MeleeSpellRig(out _, out var setNow, CombatMode.Magic); + var t0 = new DateTime(2026, 1, 1, 12, 0, 50); + setNow(t0); b.OnHeartbeat(); + setNow(t0.AddMilliseconds(5000)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5 s under the line: held"); + RigSettings.IsMacroRunning = false; + setNow(t0.AddMilliseconds(10_000)); b.OnHeartbeat(); + RigSettings.IsMacroRunning = true; + setNow(t0.AddMilliseconds(15_000)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "macro back on in the fight: the vitals hold the tick (a fresh count)"); + Check.Eq(b.HealHoldReleases, 0, "no release on the first heartbeat after the restart"); + setNow(t0.AddMilliseconds(20_900)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5.9 s after the restart: still held"); + setNow(t0.AddMilliseconds(21_000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "6 s after the restart with nothing landing: released"); + } + + private static void HealHoldReleases() + { + // A caster in Magic stance: its Heal Self goes out with no stance step, so nothing but the + // hold itself (no wand-flip backoff) decides what WantsVitalRecharge reads. + var b = MeleeSpellRig(out var v, out var setNow, CombatMode.Magic); + var t0 = new DateTime(2026, 1, 1, 12, 0, 50); + setNow(t0); + b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "48% under Heal At 75%: vitals want the tick"); + setNow(t0.AddMilliseconds(5900)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5.9 s with no heal landing: still held"); + setNow(t0.AddMilliseconds(6000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "6 s with no heal landing: combat gets the tick"); + Check.True(FakeHost.Logs.Any(l => l.Contains("no heal landed", StringComparison.Ordinal)), "logged"); + setNow(t0.AddMilliseconds(10_900)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "4.9 s into the 5 s window: combat still has it"); + setNow(t0.AddMilliseconds(11_000)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "the window over: vitals hold the tick again"); + setNow(t0.AddMilliseconds(16_900)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5.9 s into the next hold: held"); + setNow(t0.AddMilliseconds(17_000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "6 s again with nothing landing: released again"); + + // A heal landing (health up 3 points or more) ends a release and restarts the count. + v.CurrentHealth = 52; + setNow(t0.AddMilliseconds(18_000)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "a heal landed (48 -> 52): the vitals hold the tick again"); + v.CurrentHealth = 50; + setNow(t0.AddMilliseconds(23_900)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5.9 s after the landing: held"); + setNow(t0.AddMilliseconds(24_000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "6 s after it with nothing more: released"); + + // Over the line ends the episode; a new dip starts a fresh 6 s count. + v.CurrentHealth = 90; + setNow(t0.AddMilliseconds(25_000)); b.OnHeartbeat(); + v.CurrentHealth = 40; + setNow(t0.AddMilliseconds(26_000)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "a new dip: held from the start"); + setNow(t0.AddMilliseconds(31_900)); b.OnHeartbeat(); + Check.True(b.WantsVitalRecharge, "5.9 s into the new dip: held (the count restarted)"); + setNow(t0.AddMilliseconds(32_000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "6 s into the new dip: released"); + + // No monster within Monster Range: nothing to fight, the vitals keep the tick. + var q = MeleeSpellRig(out _, out var setNowQ, CombatMode.Magic, monsterInRange: false); + setNowQ(t0); q.OnHeartbeat(); + setNowQ(t0.AddMilliseconds(20_000)); q.OnHeartbeat(); + Check.True(q.WantsVitalRecharge, "no monster in range: 20 s with no heal landing, still held (nav and loot don't get it)"); + Check.Eq(q.HealHoldReleases, 0, "never released"); + } + + private static void HealHoldNoStanceChange() + { + var b = MeleeSpellRig(out _, out var setNow); + var t0 = new DateTime(2026, 1, 1, 12, 0, 50); + setNow(t0); + Check.True(b.CheckVitals(), "control: melee, no kit: Heal Self starts its stance change"); + Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 1, "control: Magic mode was asked for"); + b.OnHeartbeat(); + int before = FakeHost.CombatModeRequests.Count; + int wieldsBefore = FakeHost.Wields.Count; + // The heartbeat that releases the hold runs the vitals step too (the flip's 2 s backoff is over). + setNow(t0.AddMilliseconds(6000)); b.OnHeartbeat(); + Check.False(b.WantsVitalRecharge, "the rig: combat has the tick"); + setNow(t0.AddMilliseconds(7000)); + b.CheckVitals(); + Check.Eq(FakeHost.CombatModeRequests.Count, before, "while combat has the tick: no stance change for Heal Self"); + Check.Eq(FakeHost.Wields.Count, wieldsBefore, "and no wield"); + + // A caster already in Magic stance needs no change: its Heal Self still goes. + var c = MeleeSpellRig(out _, out var setNowC, CombatMode.Magic); + setNowC(t0); + c.OnHeartbeat(); + setNowC(t0.AddMilliseconds(6000)); c.OnHeartbeat(); + Check.False(c.WantsVitalRecharge, "caster rig: combat has the tick"); + int casts = FakeHost.Casts.Count; + c.CheckVitals(); + Check.True(FakeHost.Casts.Count > casts, "caster in Magic: Heal Self is cast while combat has the tick"); + + // A caster in Magic stance with Use Kits in Magic Mode and Peace Mode for Kits: the kit's peace + // switch is a stance change too. Control first (not released): it goes out. + foreach (bool released in new[] { false, true }) + { + var k = KitRig(CombatMode.Magic, modeCalls: true); + RigSettings.UseKitsInMagicMode = true; + RigSettings.PeaceModeForKits = true; + var t1 = new DateTime(2026, 1, 1, 12, 1, 0); + k.Clock = () => t1; + if (released) + typeof(BuffManager).GetField("_hhReleasedUntil", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .SetValue(k, t1.AddMilliseconds(5000)); + k.CheckVitals(); + int peace = FakeHost.CombatModeRequests.Count(m => m == CombatMode.NonCombat); + if (released) + { + Check.Eq(peace, 0, "Magic stance, combat has the tick: no peace switch for the kit"); + Check.Eq(FakeHost.UsesOn.Count, 1, "the kit is used in the stance it is in"); + } + else + Check.Eq(peace, 1, "control, Magic stance, not released: the kit's peace switch goes out"); + } + } + + // A release must not cut off a heal the server is already playing. A kit that has animated + // (heal grace's NoteKitProgress), or a wand wield in flight, holds the release back; a removed kit + // never animates, so it still releases. + private static void HealHoldWaitsForAnimatingKit() + { + foreach (bool animating in new[] { true, false }) + { + string how = animating ? "animating kit" : "kit with no motion"; + var b = KitRig(); + b.InCombatOverride = () => true; + var t0 = new DateTime(2026, 1, 1, 12, 0, 58); + DateTime now = t0; + b.Clock = () => now; + FakeHost.UseDoneSeq = 10; + b.OnHeartbeat(); // the hold starts counting + if (FakeHost.UsesOn.Count == 0) b.CheckVitals(); + Check.Eq(FakeHost.UsesOn.Count, 1, $"{how}: the kit is in flight"); + FakeHost.CastBusy = animating ? 1 : 0; + now = t0.AddMilliseconds(6000); + b.OnHeartbeat(); + FakeHost.CastBusy = 0; + if (animating) + { + Check.Eq(b.HealHoldReleases, 0, "6 s, the kit's heal motion playing: no release"); + Check.True(b.WantsVitalRecharge, "the vitals keep the tick for it"); + } + else + Check.Eq(b.HealHoldReleases, 1, "6 s, a kit the server never animated (the live failure): released"); + } + } + + private static void HealHoldWaitsForWield() + { + var b = MeleeSpellRig(out _, out var setNow); + var t0 = new DateTime(2026, 1, 1, 12, 0, 50); + var pending = typeof(BuffManager).GetField("_pendingWieldId", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!; + setNow(t0); b.OnHeartbeat(); + pending.SetValue(b, unchecked((int)0x80084C1E)); // the wand's wield sent, the server not done yet + setNow(t0.AddMilliseconds(6000)); b.OnHeartbeat(); + Check.Eq(b.HealHoldReleases, 0, "6 s, a wand wield in flight: no release"); + Check.True(b.WantsVitalRecharge, "the vitals keep the tick"); + pending.SetValue(b, 0); + setNow(t0.AddMilliseconds(6100)); b.OnHeartbeat(); + Check.Eq(b.HealHoldReleases, 1, "the wield done, still nothing landed: released"); + } + + private static void ReleasedKitChanceNotPeace() + { + var b = KitRig(); + FakeHost.Skills[(Player, 21)] = (75, 2); // Healing (STypeSkill 21), trained + RigSettings.PeaceModeForKits = true; + RigSettings.KitMinSuccessPct = 30; + SetHealth(b, 34); // 66 missing + var t0 = new DateTime(2026, 1, 1, 12, 1, 3); + b.Clock = () => t0; + typeof(BuffManager).GetField("_hhReleasedUntil", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .SetValue(b, t0.AddMilliseconds(5000)); // combat has the tick + Check.True(b.HealHoldReleased, "the rig: released"); + b.CheckVitals(); + // (75 + 25) x 1.1 = 110 against 66 x 2 x 1.1 = 145 in melee: 25%, under 30. In peace it would be + // 66 x 2 = 132: 34%, over it. No peace switch goes out while released, so melee is the stance. + Check.True(FakeHost.Logs.Any(l => l.Contains("would work 25% of the time on 66 missing (skill 110 vs 145)", StringComparison.Ordinal)), + "the chance is the melee one: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("would work", StringComparison.Ordinal)))); + } +}