Vitals: hand combat the tick when no heal is landing in a fight #26

Open
AwfulWaffle wants to merge 2 commits from AwfulWaffle/RynthSuite:heal-hold into main
8 changed files with 988 additions and 25 deletions

View file

@ -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;
/// <summary>Times the hold was handed to combat (tests, status).</summary>
internal int HealHoldReleases { get; private set; }
/// <summary>True while combat has the tick because no heal has been landing (see the header).</summary>
internal bool HealHoldReleased => _hhReleasedUntil != DateTime.MinValue && Now < _hhReleasedUntil;
/// <summary>
/// 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).
/// </summary>
private bool HealUnderWay() =>
(_kitUsedAt != DateTime.MinValue && _kitLandedAt == DateTime.MinValue && _kitSawAnimating)
|| _wandSwap.Active || _pendingWieldId != 0;
/// <summary>Ends a hold episode: the next heal line starts a fresh HealHoldGiveUpMs count.</summary>
private void ResetHealHold()
{
_hhSince = DateTime.MinValue;
_hhReleasedUntil = DateTime.MinValue;
}
/// <summary>Once per heartbeat while the macro runs, before the vitals step.</summary>
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).");
}
}

View file

@ -839,6 +839,7 @@ public partial class BuffManager : IDisposable
get => _busyCount;
set
{
if (value > 0 && _busyCount <= 0) _busyRoseAt = Now; // heal grace counts from the rise (BusyHoldsHeal)
_busyCount = value;
_busyGate.NoteCount(value, UseDoneSeqNow());
}
@ -868,16 +869,32 @@ public partial class BuffManager : IDisposable
{
if (BusyCount <= 0) return false;
bool gesture = _host.HasGetCastBusyState && !_host.CanCastNow;
if (!_busyGate.IsStale(BusyCount, _host.HasUseDoneSeq, UseDoneSeqNow(), gesture)) return true;
string why;
if (_busyGate.IsStale(BusyCount, _host.HasUseDoneSeq, UseDoneSeqNow(), gesture))
why = "the server finished the action (UseDone)";
else
{
// Heal grace (ActionPacer.HealGraceMs): a count up this long goes too, timed from its rise so
// it does not stack on top of the pacer's own hold. The count can't say what it is waiting for
// (a lost UseDone leaves it up until the 5 s force-clear), and the cast gate and the pacer still
// hold a gesture that is really animating.
double upMs = (Now - _busyRoseAt).TotalMilliseconds;
if (upMs < ActionPacer.HealGraceMs) return true;
why = $"the count has been up {upMs:0} ms (heal grace)";
}
int was = BusyCount;
StaleBusyClears++;
_onStaleBusy?.Invoke($"vitals: health is under a heal line and the server finished the action (UseDone) — was {was}");
_onStaleBusy?.Invoke($"vitals: health is under a heal line and {why} - was {was}");
if (BusyCount > 0) BusyCount = 0; // no callback, or the shared mirror was already 0
_busyGate.Reset();
return false;
}
/// <summary>Times a heal found the busy count was a leftover and went ahead (tests, status).</summary>
internal int StaleBusyClears { get; private set; }
// When the busy count last rose from 0 (heal grace, BusyHoldsHeal).
private DateTime _busyRoseAt = DateTime.MinValue;
// This tick's cast gate was opened by the heal grace only: CheckVitals does the health block, nothing after it.
private bool _gateGraceTick;
/// <summary>
/// Record-only diagnostic (D4): the reason the most recent buff-decision cycle
@ -1151,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.
/// </summary>
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
@ -1336,6 +1354,8 @@ public partial class BuffManager : IDisposable
public void OnHeartbeat()
{
bool track = _settings.IsMacroRunning && _vitals.MaxHealth > 0;
_gateGraceTick = false;
NoteKitProgress();
_healHold = "";
_healHoldDetail = "";
_healWaitKind = "";
@ -1383,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();
@ -1396,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();
@ -1742,10 +1764,16 @@ public partial class BuffManager : IDisposable
// NeedsAnyBuff and is the sole writer of the "Buffing" string.
// A heal goes ahead of a busy count the server has already finished (BusyHoldsHeal);
// everything else still waits for the count to drop.
// Heal grace (ActionPacer.HealGraceMs): with health under a heal line, a gate closed this long opens
// for the vitals step (CastGateWatchdog's own backstop is 4 s, for every cast).
bool healLine = ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out _, out _).Length > 0;
bool gateOpen = _fastChainTick || CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s));
bool gateGrace = !gateOpen && healLine && CastGateWatchdog.ClosedMs >= ActionPacer.HealGraceMs;
if (gateGrace) gateOpen = true; // the heal only: no mana, stamina or buff goes this tick
_gateGraceTick = gateGrace;
bool busyHolds = BusyCount > 0
&& !_pacerLetHealAhead // the pacing let this heal go ahead of an unanswered corpse use (its rules)
&& (ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out _, out _).Length == 0 || BusyHoldsHeal());
&& (!healLine || BusyHoldsHeal());
if (!gateOpen || busyHolds)
{
LastBuffSkipReason = busyHolds ? "busy (BusyCount>0)" : "cast gate closed (CanCastNow=false / gesture animating)";
@ -1759,6 +1787,11 @@ public partial class BuffManager : IDisposable
if (_healHold.Length == 0) Hold(_healWaitKind.Length > 0 ? _healWaitKind : "vitals step busy", _vitalWhy);
return;
}
if (gateGrace)
{
Hold("cast gate (a gesture is animating)");
return;
}
// /ra swaptest: the wand swap and one cast, timed (BuffManager.SwapTest.cs). After the vitals.
if (TickSwapTest())
@ -2029,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;
@ -2120,6 +2162,10 @@ public partial class BuffManager : IDisposable
if (HealthUnderAnyLine(curHealthPct, curStamPct))
_healUnavailableUntil = RynthClock.Now.AddMilliseconds(HealUnavailableMs);
// The cast gate was opened for the heal only (heal grace, OnHeartbeat): the character may still
// be mid-gesture, so no mana or stamina action goes out on this tick.
if (_gateGraceTick) return false;
// Mana: under Get Mana At / Top Off Mana, or (a caster) under the reserve kept for Stamina
// to Mana (ManaUnderLine; see "Mana reserve" at the top).
bool manaLow = curManaPct < manaThreshold || ManaUnderLine(inCombat, out _);
@ -2440,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))
{
@ -2691,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.
@ -2729,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;
@ -2753,10 +2803,44 @@ public partial class BuffManager : IDisposable
// and used a second kit, every time (2026-10-03). After a kit, vitals wait for the
// kit's own result line (heal, fail, movement disrupted, already at full), plus
// KitLandGraceMs for the vitals to catch up, or KitResultTimeoutMs with no line at all.
//
// Heal grace ("stuck in Healing"): a kit that got no result line left the vitals waiting 8 s and
// more with the label reading Healing and nothing else healing, long enough for the character to die.
// VirindiTank re-sends a kit every 100 ms until the server plays the heal motion (3 s at most),
// then waits up to 3 s for the result line. Here (KitWaitVerdict): a kit the server shows no sign
// of having taken (no animation since the send, no UseDone, no line) is let go after
// ActionPacer.HealGraceMs and the next tick sends it again; a UseDone(0) with no line ends the
// wait after KitLandGraceMs (ACE sends the line before the UseDone, so none is coming); and a
// started kit is waited for KitResultTimeoutMs at most (3.5 s; a healthy kit answers in 2.5 s).
private DateTime _kitUsedAt = DateTime.MinValue;
private DateTime _kitLandedAt = DateTime.MinValue;
private const double KitResultTimeoutMs = 8000;
private DateTime _kitAnsweredAt = DateTime.MinValue; // a UseDone(0) since the send (no line yet)
private bool _kitSawAnimating; // the motion queue read busy since the send
// 3.5 s: the longest healthy kit answer is 2.5 s (ActionPacer's header). The same value as
// ActionPacer.ItemUseMaxMs today, but its own number: a change to the pacer's limit is not one here.
// Stamina kits share this wait (KitPending).
internal const double KitResultTimeoutMs = 3500;
private const double KitLandGraceMs = 700;
/// <summary>Kits let go with no result (heal grace or the time limit) and sent again (tests, status).</summary>
internal int KitRetries { get; private set; }
internal enum KitWaitEnd { Waiting, Landed, Answered, NotTaken, TimedOut }
/// <summary>
/// The kit wait, from what has been seen since the send (pure; ms values below 0 = not seen):
/// the result line plus KitLandGraceMs; a UseDone(0) with no line plus KitLandGraceMs; nothing
/// at all from the server (<paramref name="serverTookIt"/> false) and not animating now after
/// ActionPacer.HealGraceMs; or KitResultTimeoutMs whatever happened.
/// </summary>
internal static KitWaitEnd KitWaitVerdict(double msSinceUse, double msSinceLanded, double msSinceAnswered,
bool serverTookIt, bool animatingNow)
{
if (msSinceLanded >= 0) return msSinceLanded >= KitLandGraceMs ? KitWaitEnd.Landed : KitWaitEnd.Waiting;
if (msSinceAnswered >= KitLandGraceMs) return KitWaitEnd.Answered;
if (!serverTookIt && !animatingNow && msSinceUse >= ActionPacer.HealGraceMs) return KitWaitEnd.NotTaken;
if (msSinceUse >= KitResultTimeoutMs) return KitWaitEnd.TimedOut;
return KitWaitEnd.Waiting;
}
// A refused kit (2026-10-05): ACE answers a kit used while the character is busy (a swing, a
// cast still resolving), in the air, or on something it can't heal with a UseDone error and
@ -2777,10 +2861,36 @@ public partial class BuffManager : IDisposable
{
_kitUsedAt = RynthClock.Now;
_kitLandedAt = DateTime.MinValue;
_kitAnsweredAt = DateTime.MinValue;
_kitSawAnimating = false;
_kitIsStamina = stamina;
_kitSeqAtUse = UseDoneSeqNow();
}
private bool MotionQueueBusy => _host.HasGetCastBusyState && !_host.CanCastNow;
/// <summary>
/// The server has shown it took the kit in flight (its heal motion, or its UseDone(0)). An engine with
/// neither GetCastBusyState nor the UseDone sequence can show neither, so the kit counts as taken and
/// only KitResultTimeoutMs ends the wait (no retry at the heal grace for a kit that may be playing).
/// </summary>
private bool KitServerTookIt() =>
(!_host.HasGetCastBusyState && !_host.HasUseDoneSeq) || _kitSawAnimating || _kitAnsweredAt != DateTime.MinValue;
/// <summary>
/// Records what the server has done with the kit in flight: the heal motion playing (the client's
/// motion queue busy) or a UseDone(0). Every heartbeat (the vitals step is not reached while the
/// character animates) and from KitPending.
/// </summary>
private void NoteKitProgress()
{
if (_kitUsedAt == DateTime.MinValue || _kitLandedAt != DateTime.MinValue) return;
if (!_kitSawAnimating && MotionQueueBusy) _kitSawAnimating = true;
if (_kitAnsweredAt == DateTime.MinValue && _host.HasUseDoneSeq && _host.TryGetLastUseDone(out int seq, out uint err)
&& seq == _kitSeqAtUse + 1 && err == 0) // the first UseDone after the send (as the pacer pairs a cast)
_kitAnsweredAt = RynthClock.Now;
}
internal bool KitPending()
{
if (_kitUsedAt == DateTime.MinValue) return false;
@ -2791,12 +2901,30 @@ public partial class BuffManager : IDisposable
KitRefused($"UseDone error 0x{err:X}");
return false;
}
NoteKitProgress();
DateTime now = RynthClock.Now;
bool done = _kitLandedAt != DateTime.MinValue
? (now - _kitLandedAt).TotalMilliseconds >= KitLandGraceMs
: (now - _kitUsedAt).TotalMilliseconds >= KitResultTimeoutMs;
if (done) { _kitUsedAt = DateTime.MinValue; _kitLandedAt = DateTime.MinValue; }
return !done;
double sinceUse = (now - _kitUsedAt).TotalMilliseconds;
var end = KitWaitVerdict(sinceUse,
_kitLandedAt != DateTime.MinValue ? (now - _kitLandedAt).TotalMilliseconds : -1,
_kitAnsweredAt != DateTime.MinValue ? (now - _kitAnsweredAt).TotalMilliseconds : -1,
KitServerTookIt(), MotionQueueBusy);
if (end == KitWaitEnd.Waiting) return true;
if (end != KitWaitEnd.Landed)
{
KitRetries++;
string what = end switch
{
KitWaitEnd.Answered => "was answered (UseDone) with no result line",
KitWaitEnd.NotTaken => "shows no sign the server took it (no motion, no UseDone, no result line)",
_ => "has no result line yet",
};
_host.Log($"[RynthAi] Vitals: the {(_kitIsStamina ? "stamina" : "healing")} kit {what} {sinceUse:0} ms after use: " +
"vitals carry on (heal grace), the next tick may send it again.");
}
_kitUsedAt = DateTime.MinValue;
_kitLandedAt = DateTime.MinValue;
_kitAnsweredAt = DateTime.MinValue;
return false;
}
/// <summary>The kit in flight was refused: no result line will come, so stop waiting for one.</summary>

View file

@ -30,6 +30,10 @@ internal static class CastGateWatchdog
private static DateTime _closedSince = DateTime.MinValue;
private static bool _overriding;
/// <summary>How long the raw gate has read closed (0 = open), as of the last CanCastNow call.
/// A heal under a heal line goes past ActionPacer.HealGraceMs of it (BuffManager).</summary>
public static double ClosedMs => _closedSince == DateTime.MinValue ? 0 : (RynthClock.Now - _closedSince).TotalMilliseconds;
/// <summary>
/// Effective "clear to cast": the raw engine gate plus a stuck backstop.
/// Call with <c>_host.CanCastNow</c>; optionally pass a logger for the

View file

@ -147,6 +147,14 @@ internal static class ActionPacer
public const long NoUseDoneFallbackMs = 600;
/// <summary>The longest one ask for the player's turn holds RynthAi (RynthAiYieldApiV1.MaxHoldMs).</summary>
public const long PlayerHoldMaxMs = 3000;
/// <summary>
/// Heal grace (the "stuck in Healing" report): the longest a heal under a heal line waits on
/// an item use nobody answered, on the character's animation, or on the 'too busy' probe. Past it the heal
/// goes (a refusal is an answer too, and the next heal retries), as VirindiTank does: it re-sends a kit
/// until the server starts it and never parks on the client's busy state. Corpse/door uses and our own
/// casts keep their rules (a server turn to stop; a cast the server would refuse).
/// </summary>
public const long HealGraceMs = 2000;
private static readonly object Gate = new();
private static PacedAction? _cur;
@ -157,6 +165,7 @@ internal static class ActionPacer
private static long _gestureHolds, _gestureLimits;
private static long _gestureBusySince; // when the client's motion queue was first seen busy (0 = clear)
private static bool _gestureOverride; // the hold limit passed: open until the queue reads clear
private static bool _gestureHealGrace; // the heal grace let a heal through this busy spell (logged once)
private static readonly HashSet<string> _gestureLogged = new();
private static long _maxWaitMs;
private static string _maxWaitWhat = "";
@ -195,6 +204,7 @@ internal static class ActionPacer
_swingSentMs = 0; _swingSeenBusy = false; _swingHolds = 0; _swingLogged.Clear();
_gestureBusySince = 0;
_gestureOverride = false;
_gestureHealGrace = false;
_gestureLogged.Clear();
_maxWaitMs = 0;
_maxWaitWhat = "";
@ -529,6 +539,15 @@ internal static class ActionPacer
lock (Gate) _healsAhead++;
return true;
}
// An item use (a kit, a potion, a wield) still unanswered after HealGraceMs: the heal goes (see
// HealGraceMs). Its own pack has no server turn to stop; a lost or swallowed kit is re-sent here.
if (a.Kind == PacedKind.ItemUse && age >= HealGraceMs)
{
bool logAhead;
lock (Gate) { _healsAhead++; logAhead = a.LoggedWaits.Add(who + "/heal-grace"); }
if (logAhead) Log(host, $"[Pace] {who}: the heal goes ahead of {Describe(a.Kind, a.Label)} (unanswered for {age} ms, heal grace {HealGraceMs} ms)");
return true;
}
}
why = $"{Describe(a.Kind, a.Label)} sent {age} ms ago by {a.Who} has no answer yet";
@ -570,6 +589,7 @@ internal static class ActionPacer
line = "[Pace] the character's animation queue reads clear again";
_gestureBusySince = 0;
_gestureOverride = false;
_gestureHealGrace = false;
_gestureLogged.Clear();
}
else
@ -592,6 +612,17 @@ internal static class ActionPacer
line = $"[Pace] {who}: emergency heal after {age} ms of animation - going on";
busy = false;
}
else if (heal == HealNeed.Heal && age >= HealGraceMs)
{
// Once per busy spell: logged and counted when the grace first lets a heal through.
if (!_gestureHealGrace)
{
_gestureHealGrace = true;
_gestureLimits++;
line = $"[Pace] {who}: heal after {age} ms of animation (heal grace) - going on";
}
busy = false;
}
else
{
_gestureHolds++;
@ -915,8 +946,11 @@ internal static class ActionPacer
// use would send first every time and the heal would see the next slot, up to BusyProbeMaxMs later).
if (heal == HealNeed.Heal && _busySince != 0) _healWaitAt = now;
bool healWaiting = heal != HealNeed.Heal && _healWaitAt != 0 && now - _healWaitAt < HealWaitFreshMs;
// A waiting heal's probe comes at least every HealGraceMs (the doubling would reach BusyProbeMaxMs).
long probeWait = Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs);
if (heal == HealNeed.Heal) probeWait = Math.Min(probeWait, HealGraceMs);
if (!attackRepeat && stuck == null && _busySince != 0 && _stage == BreakStage.None && !healWaiting
&& now - Math.Max(_busySince, _lastProbeAt) >= Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs))
&& now - Math.Max(_busySince, _lastProbeAt) >= probeWait)
{
probe = true; // spent in MayStart once the start passes its other checks (SpendTryAfterBusy)
}

View file

@ -191,6 +191,8 @@ internal static class Program
CommandReplyTests.Register(runner);
MonsterStatsTests.Register(runner);
MetaSaveTests.Register(runner);
HealGraceTests.Register(runner);
HealHoldTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,360 @@
using System;
using System.Linq;
using System.Reflection;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Heal grace ("stuck in Healing"): a heal under a heal line waits on nothing pending for more than
// ActionPacer.HealGraceMs. A healing kit with no result line used to leave 8 s with nothing healing
// (the kit wait's old timeout), long enough to die.
// VirindiTank re-sends a kit until the server starts it, never parking on the busy state.
internal static class HealGraceTests
{
private const uint Player = 0x50000E41;
private const uint Corpse = 0x80068AD1;
private const uint Kit = 0x8004BF01;
private const uint Pack = Player;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
public static void Register(Runner r)
{
r.Add("heal grace: the kit wait ends on its line, a UseDone(0) with no line, 2 s with no sign the server took it, or 3.5 s", KitWaitVerdicts);
r.Add("heal grace: a heal goes ahead of an item use nobody answered after 2 s; a corpse use and a non-heal still wait", PacerItemUseGrace);
r.Add("heal grace: a plain heal waits at most 2 s on the character's animation; a non-heal still waits", PacerGestureGrace);
r.Add("heal grace: a live busy count holds a heal 2 s at most from its rise (not on top of the pacer's hold)", BusyCountGrace);
r.Add("heal grace: KitPending lets a kit with no sign from the server go at 2 s (a retry)", KitNoProgressRetried);
r.Add("heal grace: KitPending waits for a kit the server started up to 3.5 s", KitStartedWaitsToLimit);
r.Add("heal grace: with neither GetCastBusyState nor the UseDone sequence, a kit waits the 3.5 s limit (no retry at 2 s)", KitNoSignalsWaitsToLimit);
r.Add("heal grace: KitPending ends 700 ms after the kit's own UseDone(0) with no line; a later UseDone is not its answer", KitAnsweredNoLine);
r.Add("heal grace: the heartbeat heals once the cast gate has been closed 2 s", GateGraceHeals);
r.Add("heal grace: a gate opened for the heal sends no Stamina to Mana when nothing heals", GateGraceNoManaCast);
}
private static void KitWaitVerdicts()
{
const double G = ActionPacer.HealGraceMs;
Check.Eq(BuffManager.KitWaitVerdict(500, -1, -1, false, false), BuffManager.KitWaitEnd.Waiting, "500 ms, nothing yet: wait");
Check.Eq(BuffManager.KitWaitVerdict(G - 1, -1, -1, false, false), BuffManager.KitWaitEnd.Waiting, "just under the grace: wait");
Check.Eq(BuffManager.KitWaitVerdict(G, -1, -1, false, false), BuffManager.KitWaitEnd.NotTaken, "the grace with no sign from the server: let go (sent again)");
Check.Eq(BuffManager.KitWaitVerdict(G + 500, -1, -1, false, true), BuffManager.KitWaitEnd.Waiting, "animating now: the kit may be playing, wait");
Check.Eq(BuffManager.KitWaitVerdict(G + 500, -1, -1, true, false), BuffManager.KitWaitEnd.Waiting, "the heal motion was seen: wait for its line");
Check.Eq(BuffManager.KitWaitVerdict(3500, -1, -1, true, true), BuffManager.KitWaitEnd.TimedOut, "3.5 s whatever happened: let go");
Check.Eq(BuffManager.KitWaitVerdict(1200, -1, 699, true, false), BuffManager.KitWaitEnd.Waiting, "UseDone(0) 699 ms ago, no line: wait");
Check.Eq(BuffManager.KitWaitVerdict(1200, -1, 700, true, false), BuffManager.KitWaitEnd.Answered, "UseDone(0) 700 ms ago, no line: none is coming");
Check.Eq(BuffManager.KitWaitVerdict(1200, 300, -1, true, false), BuffManager.KitWaitEnd.Waiting, "line seen 300 ms ago: the vitals grace runs");
Check.Eq(BuffManager.KitWaitVerdict(9000, 300, -1, true, false), BuffManager.KitWaitEnd.Waiting, "a line seen: its grace runs out even past the limit");
Check.Eq(BuffManager.KitWaitVerdict(1200, 700, -1, true, false), BuffManager.KitWaitEnd.Landed, "line seen 700 ms ago: done");
}
private static long _t;
private static RynthCoreHost PacedWorld()
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.SalvageCalls = true;
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.UseOnCalls = true;
FakeHost.CombatModeCalls = true;
FakeHost.StopCalls = true;
FakeHost.BusyCalls = true;
FakeHost.CombatModeValue = 2;
FakeHost.Names[Player] = "Tester";
FakeHost.Names[Corpse] = "Corpse of Drumtaken Ursuin";
FakeHost.Names[Kit] = "Treated Healing Kit";
FakeHost.Bitfields[Corpse] = 0x2000;
FakeHost.Containers[Kit] = Pack;
_t = 20_000_000;
ActionPacer.Reset();
ActionPacer.Enabled = true;
ActionPacer.NowMs = () => _t;
UseAudit.Reset("RynthAi", () => true);
UseAudit.NowMs = () => _t;
MoveAudit.Reset();
MoveAudit.NowMs = () => _t;
var rec = typeof(RynthAiPlugin).GetMethod("RecordUseForPacing", Any)!;
UseAudit.AfterSend = (h, u) => rec.Invoke(null, new object[] { h, u });
return FakeHost.Create(Player);
}
private static void PaceOff()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
UseAudit.Reset("?", null);
UseAudit.NowMs = () => Environment.TickCount64;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
FakeHost.CastBusy = 0;
}
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
private static void PacerItemUseGrace()
{
try
{
var host = PacedWorld();
host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself");
Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "the kit is the outstanding action");
_t += ActionPacer.HealGraceMs - 1;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "1 ms under the grace: the heal waits for the kit's answer");
_t += 1;
Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "at the grace: a non-heal still waits");
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "at the grace: the heal goes (the kit is sent again)");
Check.True(Logged("heal grace"), "logged");
// A corpse use keeps its rule: a plain heal waits for its answer (the server's turn to it).
host.UseFor(Corpse, "Loot", "open");
_t += 3900;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a corpse use at 3.9 s: the plain heal still waits");
FakeHost.UseDone(0);
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "answered: the heal goes");
}
finally { PaceOff(); }
}
private static void PacerGestureGrace()
{
try
{
var host = PacedWorld();
FakeHost.CastBusy = 1; // the client's motion queue reads busy
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "animating: the heal waits");
_t += ActionPacer.HealGraceMs - 1;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "1 ms under the grace: still waits");
_t += 1;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "at the grace: a buff still waits (its limit is GestureHoldMaxMs)");
long limitsBefore = ActionPacer.GestureLimits;
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "at the grace: the heal goes");
_t += 100;
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "and on the next tick of the same busy spell");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("of animation (heal grace)", StringComparison.Ordinal)), 1, "logged once per busy spell");
Check.Eq(ActionPacer.GestureLimits - limitsBefore, 1L, "counted once per busy spell");
FakeHost.CastBusy = 0;
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "the queue reads clear: the spell ends");
FakeHost.CastBusy = 1;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a new busy spell: the heal waits again");
_t += ActionPacer.HealGraceMs;
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "its grace: goes");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("of animation (heal grace)", StringComparison.Ordinal)), 2, "logged once for the new spell");
}
finally { PaceOff(); }
}
private static void BusyCountGrace()
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
var host = FakeHost.Create();
var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0, UsePotions = false };
var sm = new SpellManager(host, s);
sm.InitializeNatively();
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
var b = new BuffManager(host, s, sm, v);
var t0 = new DateTime(2026, 1, 1, 12, 0, 0);
DateTime now = t0;
b.Clock = () => now;
var resets = new System.Collections.Generic.List<string>();
b.SetStaleBusyCallback(why => resets.Add(why));
FakeHost.UseDoneSeq = 5;
b.BusyCount = 1; // rises at t0: a count with no UseDone since, real as far as anyone can tell
Check.True(b.BusyHoldsHeal(), "t=0: the count holds the heal");
// The pacer held the heal for 1.9 s meanwhile, so BusyHoldsHeal was not asked: the grace still
// counts from the rise, not from the first time the count held the heal.
now = t0.AddMilliseconds(ActionPacer.HealGraceMs - 1);
Check.True(b.BusyHoldsHeal(), "1 ms under the grace from the rise: held");
now = t0.AddMilliseconds(ActionPacer.HealGraceMs);
Check.False(b.BusyHoldsHeal(), "2 s after the rise: the heal goes");
Check.Eq(b.StaleBusyClears, 1, "cleared once");
Check.Eq(b.BusyCount, 0, "the count is reset");
Check.True(resets.Count == 1 && resets[0].Contains("heal grace", StringComparison.Ordinal), "through the stale-busy callback, saying why");
// First asked 1.9 s after the rise (the pacer's hold): the count holds it only 0.1 s more.
now = t0.AddMilliseconds(10_000);
b.BusyCount = 1;
now = t0.AddMilliseconds(11_900);
Check.True(b.BusyHoldsHeal(), "first asked 1.9 s after the rise: held");
now = t0.AddMilliseconds(12_000);
Check.False(b.BusyHoldsHeal(), "2.0 s after the rise: goes (no 2 s more on top of the pacer's hold)");
// A count that only goes up further (1 -> 2) keeps its rise time.
now = t0.AddMilliseconds(20_000);
b.BusyCount = 1;
now = t0.AddMilliseconds(21_000);
b.BusyCount = 2;
now = t0.AddMilliseconds(22_000);
Check.False(b.BusyHoldsHeal(), "2 s after the first rise, 1 s after 1 -> 2: goes");
}
// -- KitPending, NoteKitProgress and the gate grace, driven through BuffManager (real time:
// the kit wait and CastGateWatchdog read RynthClock) ----------------------------------
private sealed class Rig
{
public readonly BuffManager B;
public readonly LegacyUiSettings S;
public readonly RynthCoreHost H;
public Rig(int healthPct = 40, int manaPct = 100, bool healSelfKnown = true, bool serverGates = true)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.ServerGates = serverGates; // GetCastBusyState and the UseDone sequence
FakeHost.LastUseDoneCalls = serverGates;
FakeHost.CombatModeValue = CombatMode.Magic;
int healCat = SpellTable.Named("Heal Self I").First().Category;
foreach (var row in SpellTable.Rows)
if (healSelfKnown || row.Category != healCat) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, 33)] = (400, 2); // Life Magic
var host = FakeHost.Create();
H = host;
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,
};
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 = (uint)healthPct, MaxStamina = 100, CurrentStamina = 100,
MaxMana = 100, CurrentMana = (uint)manaPct,
};
B = new BuffManager(host, S, sm, v);
B.SetCharacterSkills(skills);
B.MarkLiveBuffsReadyForTests();
CastGateWatchdog.CanCastNow(true); // the watchdog is static: start from an open gate
}
}
private static int CastsOf(string firstLevelName)
{
int cat = SpellTable.Named(firstLevelName).First().Category;
return FakeHost.Casts.Count(c => SpellTable.ById(c.SpellId)?.Category == cat);
}
private static void SleepUntil(System.Diagnostics.Stopwatch sw, long ms)
{
long left = ms - sw.ElapsedMilliseconds;
if (left > 0) System.Threading.Thread.Sleep((int)left);
}
private static void KitNoProgressRetried()
{
var r = new Rig();
var sw = System.Diagnostics.Stopwatch.StartNew();
r.B.MarkKitUsed();
Check.True(r.B.KitPending(), "kit just used: waiting");
SleepUntil(sw, 1700);
Check.True(r.B.KitPending(), "1.7 s, nothing from the server: still waiting");
SleepUntil(sw, (long)ActionPacer.HealGraceMs + 100);
Check.False(r.B.KitPending(), "past the heal grace with no motion, UseDone or line: let go");
Check.Eq(r.B.KitRetries, 1, "counted as a retry");
Check.True(FakeHost.Logs.Any(l => l.Contains("shows no sign the server took it", StringComparison.Ordinal)), "logged");
}
// An engine with neither GetCastBusyState nor the UseDone sequence can't show the server took a kit:
// no retry at the heal grace (the kit may be playing), only the 3.5 s limit.
private static void KitNoSignalsWaitsToLimit()
{
var r = new Rig(serverGates: false);
Check.False(r.H.HasGetCastBusyState || r.H.HasUseDoneSeq, "the rig: neither capability");
var sw = System.Diagnostics.Stopwatch.StartNew();
r.B.MarkKitUsed();
SleepUntil(sw, (long)ActionPacer.HealGraceMs + 300);
Check.True(r.B.KitPending(), "past the heal grace: still waiting (nothing could show the server took it)");
Check.Eq(r.B.KitRetries, 0, "no retry at 2 s");
SleepUntil(sw, 3500 + 150);
Check.False(r.B.KitPending(), "past 3.5 s: let go");
}
private static void KitStartedWaitsToLimit()
{
var r = new Rig();
var sw = System.Diagnostics.Stopwatch.StartNew();
r.B.MarkKitUsed();
FakeHost.CastBusy = 1; // the heal motion plays
r.B.OnHeartbeat(); // the heartbeat records it (NoteKitProgress)
FakeHost.CastBusy = 0;
SleepUntil(sw, 3300);
Check.True(r.B.KitPending(), "the server took it: 3.3 s, still waiting for its line");
SleepUntil(sw, 3500 + 150); // the 3.5 s limit, as a literal: the test must not follow the constant
Check.False(r.B.KitPending(), "past 3.5 s: let go");
Check.Eq(r.B.KitRetries, 1, "counted");
}
private static void KitAnsweredNoLine()
{
var r = new Rig();
FakeHost.UseDoneSeq = 10;
var sw = System.Diagnostics.Stopwatch.StartNew();
r.B.MarkKitUsed();
FakeHost.UseDone(0); // the kit's own answer (seq + 1), no result line
Check.True(r.B.KitPending(), "answered just now: the line could still be in flight");
SleepUntil(sw, 550);
Check.True(r.B.KitPending(), "550 ms after the answer: waiting");
SleepUntil(sw, 850);
Check.False(r.B.KitPending(), "700 ms after a UseDone(0) with no line: none is coming, let go");
// Not the kit's own answer: two UseDones since the send (another action's, then one more).
var o = new Rig();
FakeHost.UseDoneSeq = 20;
var sw2 = System.Diagnostics.Stopwatch.StartNew();
o.B.MarkKitUsed();
FakeHost.UseDone(0);
FakeHost.UseDone(0);
Check.True(o.B.KitPending(), "seq + 2 is not the kit's answer");
SleepUntil(sw2, 850);
Check.True(o.B.KitPending(), "850 ms: still waiting (not taken as answered)");
}
private static void GateGraceHeals()
{
var r = new Rig(healthPct: 40);
try
{
FakeHost.CastBusy = 1; // the client's gesture gate reads closed
r.B.OnHeartbeat();
Check.Eq(CastsOf("Heal Self I"), 0, "gate just closed: no heal");
System.Threading.Thread.Sleep((int)ActionPacer.HealGraceMs + 100);
r.B.OnHeartbeat();
Check.Eq(CastsOf("Heal Self I"), 1, "gate closed past the heal grace: Heal Self goes");
}
finally { FakeHost.CastBusy = 0; CastGateWatchdog.CanCastNow(true); }
}
private static void GateGraceNoManaCast()
{
var r = new Rig(healthPct: 40, manaPct: 10, healSelfKnown: false);
r.S.GetManaAt = 50; r.S.TopOffMana = 50;
try
{
FakeHost.CastBusy = 1;
r.B.OnHeartbeat();
System.Threading.Thread.Sleep((int)ActionPacer.HealGraceMs + 100);
r.B.OnHeartbeat();
Check.Eq(CastsOf("Heal Self I"), 0, "no Heal Self known: nothing heals");
Check.Eq(CastsOf("Stamina to Mana Self I"), 0, "the gate opened for the heal only: no Stamina to Mana mid-gesture");
// Control: with the gate really open the same state does cast Stamina to Mana.
FakeHost.CastBusy = 0;
r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self I"), 1, "control: gate open, Stamina to Mana goes");
}
finally { FakeHost.CastBusy = 0; CastGateWatchdog.CanCastNow(true); }
}
}

View file

@ -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<DateTime, DateTime> 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;
}
/// <summary>The settings of the last rig built (MeleeSpellRig or KitRig).</summary>
private static LegacyUiSettings RigSettings = new();
/// <summary>A melee character with two healing kits and Life Magic untrained: kits are the only heal.</summary>
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))));
}
}

View file

@ -375,31 +375,55 @@ internal static class StuckCastTests
private static void ProbeWhenNothingOpen()
{
// A start that is no heal: a waiting heal's probe is capped at ActionPacer.HealGraceMs (below).
bool Start(RynthCoreHost h) => MayAs(h, "Buff", HealNeed.None);
var host = Setup();
try
{
Check.True(May(host), "free");
Check.True(Start(host), "free");
Cast(host, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused: the server is busy with something of no UseDone (a pickup)
Check.False(May(host), "held right after the 0x1D");
Check.False(Start(host), "held right after the 0x1D");
_t += ActionPacer.BusyProbeMs - 1;
Check.False(May(host), "held until BusyProbeMs");
Check.False(Start(host), "held until BusyProbeMs");
_t += 1;
Check.True(May(host), "one probe at BusyProbeMs");
Check.False(May(host), "only one");
Check.True(Start(host), "one probe at BusyProbeMs");
Check.False(Start(host), "only one");
Cast(host, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again
_t += ActionPacer.BusyProbeMs * 2 - 101;
Check.False(May(host), "the next probe waits twice as long");
Check.False(Start(host), "the next probe waits twice as long");
_t += 1;
Check.True(May(host), "second probe at 2 x BusyProbeMs");
Check.True(Start(host), "second probe at 2 x BusyProbeMs");
Check.Eq(FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "no breaker: no cast of ours was left open");
Cast(host, "Heart Rend");
_t += 900;
FakeHost.UseDone(0);
Check.True(May(host), "a UseDone(0) clears it");
Check.True(Start(host), "a UseDone(0) clears it");
}
finally { Done(); }
// Heal grace: a plain heal's probe comes at least every HealGraceMs, where the doubling would make it 3 s.
var heal = Setup();
try
{
Check.True(May(heal), "free");
Cast(heal, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr);
Check.False(May(heal), "held right after the 0x1D");
_t += ActionPacer.BusyProbeMs;
Check.True(May(heal), "the heal's first probe at BusyProbeMs");
Cast(heal, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again
Check.False(May(heal), "held right after the second 0x1D");
_t += ActionPacer.HealGraceMs - 101;
Check.False(May(heal), "1 ms under the heal grace: held");
_t += 1;
Check.True(May(heal), "the heal's second probe at HealGraceMs, not 2 x BusyProbeMs");
}
finally { Done(); }
}