From 2e8258b079ee821542d51a5384149648aa789bed Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Mon, 12 Oct 2026 16:26:55 -0700 Subject: [PATCH] RynthAi: a refused combat mode change is not a sent request ChangeCombatModeFor called host.ChangeCombatMode, began a paced action only on success, and then returned true either way. BuffManager and the Combat stance paths read that true as a sent request: they advanced their attempt clocks, counted a failed try and logged a retry. With the engine turning non-teardown actions away around a teleport or a death, chained refusals could reach NoWandFlipMaxFails and set _magicModeBlocked / _wandSwapExhausted. - ChangeCombatModeFor returns false on a refusal, without Begin. The other *For helpers already return the host result. The no-ChangeCombatMode host case still returns true (nothing to send or pace). - Callers stamp their bookkeeping only on true: BuffManager peace-for-kit paths (_lastCastAttempt, _healWaitKind); CorpseOpenController's peace before an open and MissileCraftingManager's peace before the first combine are asked again until accepted, inside their 2.5 s ceiling counted from the first ask; the stuck-stance clocks (BuffManager, CombatManager) start only once a stance request has gone out; ExpressionEngine's cast-stance flip throttle; the CombatManager stall-watchdog toggle, whose ladder step is taken back (CombatStallWatchdog.Unfire) when the toggle is refused. - ActionPacer tracks a streak of consecutive engine refusals (one log line when it starts, one when an accepted call ends it). After EngineRefusalFailOpenMs (30 s) ChangeCombatModeFor returns true again, so a permanent refusal (missing hook, full ring) is counted by the callers' own failure paths instead of retrying forever. A gap of more than RefuseGapMs (10 s) starts a new streak; Reset() and Forget() end it. - ActionPacer.LastEngineRefusalMs: a refusal newer than a stuck-stance clock's start restarts that clock, so a request accepted and then dropped by a teleport does not end in a re-equip UseObject on the wielded weapon. Tests: FakeHost.CombatModeRefuse; ActionPacingTests (refusals burn no try or backoff, streak, fail-open, expiry and Forget, stuck clock restart, 20 s no-wand loop never reaches _magicModeBlocked, peace-before-open retry, MissileCraftingManager), WeaponTests (equip pass keeps its backoff), CombatHookTests, CombatStallWatchdogTests (Unfire). Co-Authored-By: Claude Opus 5.5 (1M context) --- .../Combat/BuffManager.cs | 28 +- .../Combat/CombatManager.cs | 35 +- .../Combat/CombatStallWatchdog.cs | 12 + .../Combat/MissileCraftingManager.cs | 26 +- .../CorpseOpenController.cs | 11 +- .../Meta/ExpressionEngine.cs | 5 +- Plugins/Shared/ActionPacer.cs | 70 +++- .../Fakes/FakeHost.cs | 8 +- .../Tests/ActionPacingTests.cs | 334 ++++++++++++++++++ .../Tests/CombatHookTests.cs | 25 +- .../Tests/WeaponTests.cs | 24 +- .../Tests/CombatStallWatchdogTests.cs | 26 +- 12 files changed, 570 insertions(+), 34 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index f8d05be..fdd8067 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -2214,9 +2214,13 @@ public partial class BuffManager : IDisposable if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return VitalNo($"{kit.Name} under Kit Min Success %"); if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode) { - _host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the healing kit"); - _lastCastAttempt = DateTime.Now; - _healWaitKind = "peace mode for the kit"; + // 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. + if (_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the healing kit")) + { + _lastCastAttempt = DateTime.Now; + _healWaitKind = "peace mode for the kit"; + } return true; // use the kit next tick, once in peace mode } @@ -2247,8 +2251,8 @@ public partial class BuffManager : IDisposable if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return false; if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode) { - _host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the stamina kit"); - _lastCastAttempt = DateTime.Now; + if (_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the stamina kit")) + _lastCastAttempt = DateTime.Now; return true; // use the kit next tick, once in peace mode } uint playerId = _host.GetPlayerId(); @@ -4186,6 +4190,7 @@ public partial class BuffManager : IDisposable // Mirror that recovery here: visible retries, ≤2 capped re-equips per // episode, one-shot chat warn when wedged. private DateTime _buffStanceStuckSince = DateTime.MinValue; + private long _buffStanceStuckStartMs; // ActionPacer.NowMs when the clock started (a later engine refusal restarts it) private DateTime _buffStanceLastRecoverAt = DateTime.MinValue; private int _buffStanceReEquips; private bool _buffStanceWedgeWarned; @@ -4513,9 +4518,17 @@ public partial class BuffManager : IDisposable } // Deadlock episode tracking: wand wielded but mode refuses to flip. - if (_buffStanceStuckSince == DateTime.MinValue) + // The clock starts when a stance request has actually gone out (below), never on refusals: the + // engine turns stance changes away around a teleport or a death, and a clock counting through + // that would end in a re-equip UseObject on the wielded wand (a MOVE) and a burnt re-equip. + // A refusal newer than the clock's start means the request that started it was dropped (a teleport right after it went out): + // the clock restarts, so the refusals that follow are not counted as a wedged stance. + if (_buffStanceStuckSince != DateTime.MinValue && ActionPacer.LastEngineRefusalMs > _buffStanceStuckStartMs) + { _buffStanceStuckSince = DateTime.Now; - double stuckMs = (DateTime.Now - _buffStanceStuckSince).TotalMilliseconds; + _buffStanceStuckStartMs = ActionPacer.NowMs(); + } + double stuckMs = _buffStanceStuckSince == DateTime.MinValue ? 0 : (DateTime.Now - _buffStanceStuckSince).TotalMilliseconds; // Capped re-equip recovery (mirrors CombatManager): handles the rare // stale "wielded reads true" by resyncing the wield once or twice. @@ -4554,6 +4567,7 @@ public partial class BuffManager : IDisposable if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs && _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode")) { + if (_buffStanceStuckSince == DateTime.MinValue) { _buffStanceStuckSince = DateTime.Now; _buffStanceStuckStartMs = ActionPacer.NowMs(); } NoteStanceRequest(); _lastBuffStanceAttempt = DateTime.Now; _lastCastAttempt = DateTime.Now; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 972ec2f..142e762 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -65,6 +65,7 @@ public partial class CombatManager : IDisposable // equip path would only re-send ChangeCombatMode forever (it never re-equips a // "wielded" wand) — a hours-long wedge with NO m_cBusy pin so no watchdog fires. private DateTime _stanceStuckSince = DateTime.MinValue; + private long _stanceStuckStartMs; // ActionPacer.NowMs when the clock started (a later engine refusal restarts it) private DateTime _lastStanceRecoverAt = DateTime.MinValue; private const double StanceStuckRecoverMs = 8000; // Re-equip attempts spent in the CURRENT deadlock episode. ⚠ UseObject on an @@ -3440,13 +3441,22 @@ public partial class CombatManager : IDisposable // Same effect on the server as the wand heal: a mode change runs // HandleActionCancelAttack. EquipWeaponAndSetStance flips back after its // stance retry delay (~1 s with the flip backoff reset). - _host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat/Stall", "stall watchdog: toggle the mode", force: true); - _stallToggleAt = now; - ResetStanceFlipBackoff(); - lastStanceAttempt = now; - _serverAttackTargetId = 0; - lastAttackCmd = now; - _host.Log($"{head} toggle mode: peace, then back to {CombatModeName(mode)} on the next stance pass"); + // Only a toggle the engine accepted starts the flip-back bookkeeping. A refusal (a teleport, + // a death) leaves it untouched and takes the ladder step back (Unfire), so it spends no step + // and the toggle is asked for again next tick. + if (_host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat/Stall", "stall watchdog: toggle the mode", force: true)) + { + _stallToggleAt = now; + ResetStanceFlipBackoff(); + lastStanceAttempt = now; + _serverAttackTargetId = 0; + _host.Log($"{head} toggle mode: peace, then back to {CombatModeName(mode)} on the next stance pass"); + lastAttackCmd = now; + } + else + { + _stallWatch.Unfire(); + } return true; case CombatStallWatchdog.StallAction.Rewield: @@ -4548,9 +4558,15 @@ public partial class CombatManager : IDisposable // watchdog won't) and RE-EQUIP the wand (UseObject resyncs the wield; on a // truly-unwielded wand it wields it, which is the actual fix). Without this // the bot sat in NonCombat for 5h, buffs expired, never fighting (2026-06-10). - if (_stanceStuckSince == DateTime.MinValue) + // The clock starts when a stance request has actually gone out (below), never on refusals + // (see BuffManager's _buffStanceStuckSince): a clock counting through them ends in a re-equip. + // A refusal newer than the clock's start: the request that started it was dropped (a teleport), so restart the clock. + if (_stanceStuckSince != DateTime.MinValue && ActionPacer.LastEngineRefusalMs > _stanceStuckStartMs) + { _stanceStuckSince = DateTime.Now; - double stuckMs = (DateTime.Now - _stanceStuckSince).TotalMilliseconds; + _stanceStuckStartMs = ActionPacer.NowMs(); + } + double stuckMs = _stanceStuckSince == DateTime.MinValue ? 0 : (DateTime.Now - _stanceStuckSince).TotalMilliseconds; // RE-EQUIP recovery — only for the first couple of attempts in an // episode (handles a stale "wielded reads true" on a wand that // actually isn't wielded). Capped: UseObject on a genuinely wielded @@ -4586,6 +4602,7 @@ public partial class CombatManager : IDisposable if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs() && _host.ChangeCombatModeFor(desiredMode, "Combat", "stance")) { + if (_stanceStuckSince == DateTime.MinValue) { _stanceStuckSince = DateTime.Now; _stanceStuckStartMs = ActionPacer.NowMs(); } if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=true mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource}) — sending ChangeCombatMode"); } lastStanceAttempt = DateTime.Now; NoteStanceFlipSent(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs index ad229c6..3de490c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs @@ -47,6 +47,7 @@ internal sealed class CombatStallWatchdog private DateTime _lastStepAt = DateTime.MinValue; private DateTime _cooldownUntil = DateTime.MinValue; private int _step; // steps fired in the current episode (0 = none) + private DateTime _prevStepAt = DateTime.MinValue; // _lastStepAt before the newest Fire (for Unfire) private DateTime _stallRef = DateTime.MinValue; // last swing (or episode start) before the stall /// Episodes where the watchdog acted (diagnostics / status). @@ -122,6 +123,7 @@ internal sealed class CombatStallWatchdog private StallAction Fire(DateTime now) { _step++; + _prevStepAt = _lastStepAt; _lastStepAt = now; return _step switch { @@ -132,6 +134,16 @@ internal sealed class CombatStallWatchdog }; } + /// Take back the step just returned because the caller could not carry it out (the engine refused the mode change): + /// a refusal spends no ladder step. The ladder returns to where it was, so the step fires again on the next tick. + public void Unfire() + { + if (_step <= 0) return; + _step--; + _lastStepAt = _prevStepAt; + if (_step == 0 && Episodes > 0) Episodes--; + } + private void ResetEpisode() { _eligibleSince = DateTime.MinValue; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs index aa06156..adadd13 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs @@ -223,7 +223,9 @@ public class MissileCraftingManager _combinesCompleted = 0; _allCombinesDone = false; - try { _host.ChangeCombatModeFor(CombatMode.NonCombat, "Crafting", "missile crafting needs peace mode"); } catch { } + _peaceSent = false; + _peaceAskedAt = DateTime.Now; // the wait for the stance counts from the first ask + TryPeaceForCrafting(); var headItems = inv.Where(i => recipe.IsHead(i.Name)).ToList(); var shaftItems = inv.Where(i => recipe.IsShaft(i.Name)).ToList(); @@ -258,6 +260,22 @@ public class MissileCraftingManager // COMBINING // ══════════════════════════════════════════════════════════════════ + private bool _peaceSent; + private DateTime _peaceAskedAt; + private const double PeaceWaitMaxMs = 2500; + + /// Asks for Peace mode until the engine accepts (a refusal is retried, not counted as sent). + private void TryPeaceForCrafting() + { + if (_peaceSent) return; + try + { + if (_host.HasGetCurrentCombatMode && _host.GetCurrentCombatMode() == CombatMode.NonCombat) { _peaceSent = true; return; } + _peaceSent = _host.ChangeCombatModeFor(CombatMode.NonCombat, "Crafting", "missile crafting needs peace mode"); + } + catch { } + } + private void ProcessCombining() { if (_allCombinesDone) @@ -283,6 +301,12 @@ public class MissileCraftingManager return; } + if (!_peaceSent) + { + TryPeaceForCrafting(); + if (!_peaceSent && (DateTime.Now - _peaceAskedAt).TotalMilliseconds < PeaceWaitMaxMs) return; // still asking, inside the ceiling + } + if ((DateTime.Now - _lastApplyAttempt).TotalMilliseconds >= APPLY_RETRY_MS) { try diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index f2049d8..105e66f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -768,6 +768,8 @@ public sealed partial class RynthAiPlugin private const long PeaceBeforeOpenMaxMs = 2500; private int _peaceBeforeOpenFor; private long _peaceBeforeOpenSince; + /// The peace request for _peaceBeforeOpenFor was accepted by the engine (a refusal is retried). + private bool _peaceSent; /// True while the open should wait for the peace-mode swap it just asked for. private bool WantsPeaceBeforeOpen(LegacyUiSettings settings, long now) @@ -781,10 +783,13 @@ public sealed partial class RynthAiPlugin if (_peaceBeforeOpenFor != _targetCorpseId) { _peaceBeforeOpenFor = _targetCorpseId; - _peaceBeforeOpenSince = now; - Host.ChangeCombatModeFor(CombatMode.NonCombat, "Loot", "peace before opening the corpse (Peace Mode When Idle)"); - return true; + _peaceBeforeOpenSince = now; // the ceiling counts from the first ask + _peaceSent = false; } + // One accepted request per corpse. A refusal (the engine turns stance changes away around a + // teleport) or a pacing hold is asked again on the next call, inside the same ceiling. + if (!_peaceSent) + _peaceSent = Host.ChangeCombatModeFor(CombatMode.NonCombat, "Loot", "peace before opening the corpse (Peace Mode When Idle)"); return now - _peaceBeforeOpenSince < PeaceBeforeOpenMaxMs; } // Wait for busy to genuinely clear before opening the next corpse. The backstop diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index 270dc35..4b5081d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -2831,8 +2831,9 @@ internal sealed class ExpressionEngine if (_host.HasChangeCombatMode && (now - _castStanceLastFlipAt).TotalMilliseconds > CastStanceFlipGateMs) { - _host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true); - _castStanceLastFlipAt = now; + // Only a request that went out arms the flip throttle: a refusal is asked again next pulse. + if (_host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true)) + _castStanceLastFlipAt = now; } return false; } diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs index 4bd07ca..62c04bb 100644 --- a/Plugins/Shared/ActionPacer.cs +++ b/Plugins/Shared/ActionPacer.cs @@ -167,6 +167,7 @@ internal static class ActionPacer { _cur = null; _started = _answered = _timedOut = _sentOverOutstanding = _modeRefused = _modeSkipped = 0; + _refuseSince = 0; _refuseLast = 0; _refuseCount = 0; _engineRefusals = 0; _lastEngineRefusalMs = 0; _heldStarts = _heldMoves = _healsAhead = 0; _gestureHolds = _gestureLimits = 0; _swingSentMs = 0; _swingSeenBusy = false; _swingHolds = 0; _swingLogged.Clear(); @@ -213,7 +214,8 @@ internal static class ActionPacer /// Forget the outstanding action (logout, death, portal): the server dropped it. public static void Forget(string why) { - lock (Gate) { _cur = null; ClearBusyLocked(); } + // A death, portal or logout also ends a refusal streak: a refusal before it must not make one after it look like a long streak. + lock (Gate) { _cur = null; ClearBusyLocked(); _refuseSince = 0; _refuseLast = 0; _refuseCount = 0; } } // ── Recording what went out ────────────────────────────────────────────── @@ -1141,9 +1143,10 @@ internal static class ActionPacer /// mode (the engine would push a raw 0x53 to the server anyway, and on ACE every mode change /// cancels the walk/turn of a pending use and fails a cast in progress) unless /// ; and nothing while another server action is unanswered unless - /// . Returns false only when the pacing held the request back (or the - /// client already reads that mode); otherwise the request was made, as a plain ChangeCombatMode - /// call was before (whose result the callers never read), so their retry timers run as before. + /// . Returns false when nothing went out: the pacing held the request back, + /// the client already reads that mode, or the engine refused the call. True only when the request + /// was made (or the host has no ChangeCombatMode, where there is nothing to send or pace). Callers + /// count a try, a backoff step or a log line only on true. /// public static bool ChangeCombatModeFor(this RynthCoreHost host, int mode, string who, string why, bool force = false) { @@ -1177,8 +1180,63 @@ internal static class ActionPacer } } int seq = UseDoneSeqNow(host); - if (host.ChangeCombatMode(mode)) - Begin(host, PacedKind.CombatMode, 0, ModeName(mode), who, seq, mode); + if (!host.ChangeCombatMode(mode)) + return NoteEngineRefusal(host, mode); + NoteEngineAccepted(host); + Begin(host, PacedKind.CombatMode, 0, ModeName(mode), who, seq, mode); return true; } + + // -- The engine turning a mode change away ----------------------------------------------- + // ChangeCombatMode returns false when the engine refused: it turns non-teardown actions away for + // a few seconds around a teleport or a death, its action ring can be full, or the hook is + // missing. Nothing was sent, so no action is outstanding and the callers must not count a try + // or a backoff step: ChangeCombatModeFor returns false and they ask again next tick. A refusal + // that lasts longer than EngineRefusalFailOpenMs is no longer a transition (a missing hook or a + // stuck ring never recovers): the call then returns true again, which puts the callers back on + // their own failure counting (NoWandFlipMaxFails and the potion fallbacks). One log line when a + // streak starts, one when it ends; any accepted call ends it. + + /// A streak of consecutive engine refusals this long makes ChangeCombatModeFor return true again. + public const long EngineRefusalFailOpenMs = 30_000; + /// Refusals further apart than this are separate streaks (the streak never outlives a quiet spell). + public const long RefuseGapMs = 10_000; + private static long _refuseSince; // start of the current streak of engine refusals (0 = none) + private static long _refuseLast; // time of the newest refusal in the streak + private static long _lastEngineRefusalMs; + /// NowMs of the newest engine refusal (0 = none since Reset). Stuck-stance clocks restart when this is newer than their start. + public static long LastEngineRefusalMs { get { lock (Gate) return _lastEngineRefusalMs; } } + private static int _refuseCount; + private static long _engineRefusals; // lifetime + public static long EngineModeRefusals => _engineRefusals; + + private static bool NoteEngineRefusal(RynthCoreHost host, int mode) + { + bool startLine = false, failOpen; + long now = NowMs(); + lock (Gate) + { + _engineRefusals++; + if (_refuseSince != 0 && now - _refuseLast > RefuseGapMs) _refuseSince = 0; + if (_refuseSince == 0) { _refuseSince = now; _refuseCount = 0; startLine = true; } + _refuseLast = now; _lastEngineRefusalMs = now; + _refuseCount++; + failOpen = now - _refuseSince > EngineRefusalFailOpenMs; + } + if (startLine) + Log(host, $"[Pace] the engine refused the change to {ModeName(mode)} mode: asking again each tick (no try counted), counted as a failure after {EngineRefusalFailOpenMs / 1000} s"); + return failOpen; + } + + private static void NoteEngineAccepted(RynthCoreHost host) + { + int count; long span; + lock (Gate) + { + if (_refuseSince == 0) return; + count = _refuseCount; span = NowMs() - _refuseSince; + _refuseSince = 0; _refuseLast = 0; _refuseCount = 0; + } + Log(host, $"[Pace] the engine accepts mode changes again after {count} refusal(s) over {span} ms"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index 7d4b16b..38dc479 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -144,6 +144,10 @@ internal static unsafe class FakeHost /// Opt-in (set before Create): ChangeCombatMode, recorded in . public static bool CombatModeCalls; public static readonly List CombatModeRequests = new(); + /// True: ChangeCombatMode returns 0 (the engine refused, e.g. around a teleport) and records nothing in . + public static bool CombatModeRefuse; + /// ChangeCombatMode calls refused while was set. + public static int CombatModeRefusals; /// Opt-in (set before Create): WieldItem (a wield into a named slot, API v70+). The /// host then reports API version 73, so only tests that ask for it see the newer calls. public static bool WieldCalls; @@ -227,7 +231,7 @@ internal static unsafe class FakeHost SelectedItem = 0; UseOnCalls = false; UsesOn.Clear(); PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear(); - CombatModeCalls = false; CombatModeRequests.Clear(); + CombatModeCalls = false; CombatModeRequests.Clear(); CombatModeRefuse = false; CombatModeRefusals = 0; BusyCalls = false; ForceResets = 0; BusyStateValue = 0; } @@ -676,7 +680,7 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetCurrentCombatMode() => CombatModeValue; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int ChangeCombatMode(int mode) { CombatModeRequests.Add(mode); return 1; } + private static int ChangeCombatMode(int mode) { if (CombatModeRefuse) { CombatModeRefusals++; return 0; } CombatModeRequests.Add(mode); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int UseObject(uint id) { Uses.Add(id); return 1; } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs index cb643b1..f71b1cc 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs @@ -54,6 +54,16 @@ internal static class ActionPacingTests r.Add("pacing: no answer - each kind's time limit lets the next action go, logged, and nothing is force-cleared", TimeLimits); r.Add("pacing: heals (a plain heal waits for a corpse use's answer, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules); r.Add("pacing (vitals): Drakkon 07:03 - a cast whose result is in waits for its UseDone: one cast, not a too-busy flood", CastWaitsForUseDone); + r.Add("refusal: a refused mode change begins no paced action, and the next one is not held by it", RefusedBeginsNothing); + r.Add("refusal: the engine refusing for 5 s burns nothing; a streak past 30 s counts as a failure again, with one log line each end", RefusalStreakFailsOpen); + r.Add("refusal: 20 s of refusals with no wand never reach _magicModeBlocked; past 30 s the failure counting resumes and the vitals fall to the potion path", NoWandRefusalLoop); + r.Add("refusal: wand wielded, 9 s of refused stance changes - no re-equip UseObject, no burnt re-equip; the first accepted request starts the clock", WandWieldedRefusalNoReEquip); + r.Add("refusal: a refused peace-before-open is asked again inside the 2.5 s ceiling; exactly one accepted request goes out before the open", PeaceBeforeOpenRefusedRetried); + r.Add("refusal: a streak that went quiet for 10 s+ (a death, a logout) is over - 600 s later a refusal starts a fresh streak, and Forget ends one", RefusalStreakExpires); + r.Add("refusal: wand wielded, a request accepted then dropped (a teleport), 9 s of refusals - the stuck clock restarts, no re-equip UseObject", StuckClockRestartsOnRefusal); + r.Add("refusal: the stall watchdog's refused mode toggle spends no ladder step (Unfire) and is asked again next tick", StallToggleRefusedSpendsNoStep); + r.Add("refusal: missile crafting asks for peace until accepted, and combines after the 2.5 s ceiling; already in peace it combines on the first tick with no mode request", CraftingPeaceRefusal); + r.Add("pacing (stance): a refused ChangeCombatMode burns no try and no backoff step, and the next tick asks again (pacing on and off)", RefusedStanceBurnsNothing); r.Add("pacing (vitals): a heal waits for an unanswered corpse use's answer, then goes at once; the emergency stance settle is unchanged", HealLatencyKept); r.Add("pacing (looting): one open per server answer, never re-sent on top of an unanswered one", LootOneOpenPerAnswer); r.Add("pacing (looting): Drakkon's stall is still found and said once with pacing on", LootStallStillDetected); @@ -468,6 +478,330 @@ internal static class ActionPacingTests finally { PaceOff(); } } + private static void RefusedStanceBurnsNothing() + { + foreach (bool pacing in new[] { true, false }) + { + PaceOff(); + if (pacing) PaceOn(); + try + { + var r = new BuffRig(CombatMode.NonCombat); + r.S.EmergencyHealAt = 30; r.S.HealAt = 60; r.S.TopOffHP = 60; r.S.GetManaAt = 0; r.S.TopOffMana = 0; + r.V.CurrentHealth = 20; r.V.CurrentMana = 100; + var fails = typeof(BuffManager).GetField("_buffStanceConsecutiveFails", Any)!; + var last = typeof(BuffManager).GetField("_lastBuffStanceAttempt", Any)!; + DateTime lastBefore = (DateTime)last.GetValue(r.B)!; + FakeHost.CombatModeRefuse = true; // the engine turns the stance change away (a teleport, a death) + + for (int i = 0; i < 6; i++) { r.At(i * 0.2); r.B.OnHeartbeat(); } + Check.Eq(FakeHost.CombatModeRefusals, 6, $"pacing={pacing}: every tick asks again - a refusal is no try and sets no backoff"); + Check.Eq((int)fails.GetValue(r.B)!, 0, $"pacing={pacing}: _buffStanceConsecutiveFails unchanged"); + Check.True((DateTime)last.GetValue(r.B)! == lastBefore, $"pacing={pacing}: _lastBuffStanceAttempt unchanged"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, $"pacing={pacing}: nothing reached the server"); + + FakeHost.CombatModeRefuse = false; + r.At(1.4); r.B.OnHeartbeat(); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", $"pacing={pacing}: the engine accepts again and the very next tick sends Magic"); + Check.Eq((int)fails.GetValue(r.B)!, 1, $"pacing={pacing}: only a sent request counts as a try"); + } + finally { PaceOff(); } + } + } + + private static void RefusedBeginsNothing() => Paced(() => + { + var host = World(combatMode: 2); + FakeHost.CombatModeRefuse = true; + Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "refused"), "the engine refused: false"); + Check.True(ActionPacer.Current(host) == null, "no paced action was begun"); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "so nothing is held behind it"); + FakeHost.CombatModeRefuse = false; + Check.True(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "accepted"), "accepted: true"); + Check.True(ActionPacer.Current(host)?.Kind == PacedKind.CombatMode, "and now the stance change is outstanding"); + }); + + private static void RefusalStreakFailsOpen() => Paced(() => + { + var host = World(combatMode: 2); + FakeHost.CombatModeRefuse = true; + for (int s = 0; s <= 5; s++) { _t = 10_000_000 + s * 1000; Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), $"{s} s into a refusal streak: false"); } + Check.Eq(FakeHost.Logs.Count(l => l.Contains("the engine refused the change")), 1, "one line when the streak starts"); + FakeHost.CombatModeRefuse = false; + _t = 10_000_000 + 6_000; + Check.True(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "accepted"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("the engine accepts mode changes again")), 1, "one line when it ends"); + FakeHost.UseDone(0); ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => _t; + + FakeHost.CombatModeRefuse = true; + long start = _t + 1000; + bool sawOpen = false; + for (int s = 0; s <= 40; s++) + { + _t = start + s * 1000L; + bool r = host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"); + if (s <= 30) Check.False(r, $"{s} s into the streak: still false"); + else sawOpen |= r; + } + Check.True(sawOpen, "past 30 s a refusal counts as a failure again (true)"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("the engine refused the change")), 2, "the second streak logged once"); + FakeHost.CombatModeRefuse = false; + _t += 1000; + Check.True(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "any accepted call ends the streak"); + FakeHost.CombatModeRefuse = true; + _t += 5000; ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => _t; + Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "a fresh streak starts at false again"); + }); + + private static readonly BindingFlags Priv = BindingFlags.Instance | BindingFlags.NonPublic; + + private static void SetupBuffRigVitals(BuffRig r) + { + r.S.EmergencyHealAt = 30; r.S.HealAt = 60; r.S.TopOffHP = 60; r.S.GetManaAt = 0; r.S.TopOffMana = 0; + r.V.CurrentHealth = 20; r.V.CurrentMana = 100; + } + + private static void NoWandRefusalLoop() + { + PaceOff(); + try + { + var r = new BuffRig(CombatMode.NonCombat); + SetupBuffRigVitals(r); + var blocked = typeof(BuffManager).GetField("_magicModeBlocked", Priv)!; + var fails = typeof(BuffManager).GetField("_buffStanceConsecutiveFails", Priv)!; + var swapUntil = typeof(BuffManager).GetField("_vitalSwapBlockedUntil", Priv)!; + FakeHost.CombatModeRefuse = true; + bool everBlocked = false; + int ticks = 0; + for (double s = 0; s <= 20; s += 0.5) { r.At(s); r.B.OnHeartbeat(); ticks++; everBlocked |= (bool)blocked.GetValue(r.B)!; } + Check.True(FakeHost.CombatModeRefusals >= ticks / 2, $"20 s: the stance is asked again throughout ({FakeHost.CombatModeRefusals} refusals in {ticks} heartbeats; other vitals gates skip some ticks)"); + Check.False(everBlocked, "_magicModeBlocked never set by refusals"); + Check.Eq((int)fails.GetValue(r.B)!, 0, "no failure counted"); + Check.True((DateTime)swapUntil.GetValue(r.B)! < DateTime.Now, "and the vitals did not fall through to the potion path"); + + // Past 30 s of refusals the call counts again. The backoff gates run on the real clock, so + // stand in for three earlier counted tries: the very next counted try (the first past 30 s) + // is the fourth, and the one after it finds the flip blocked and hands over to the potion. + fails.SetValue(r.B, 3); + for (double s = 20.5; s <= 40; s += 0.5) { r.At(s); r.B.OnHeartbeat(); everBlocked |= (bool)blocked.GetValue(r.B)!; } + Check.True(everBlocked, "40 s: the failure counting resumed and _magicModeBlocked was reached"); + Check.True((DateTime)swapUntil.GetValue(r.B)! > DateTime.Now, "the vitals chain reached the potion/kit fallback (swap blocked, retry later)"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("the engine refused the change")), 1, "one streak, one line"); + } + finally { PaceOff(); } + } + + private static void WandWieldedRefusalNoReEquip() + { + PaceOff(); + try + { + var r = new BuffRig(CombatMode.NonCombat); + SetupBuffRigVitals(r); + FakeHost.Names[Wand] = "Academy Wand"; + FakeHost.ItemTypes[Wand] = 0x8000; + FakeHost.Ints[(Wand, 10)] = 0x01000000; // CurrentWieldedLocation: in hand + r.S.WieldUnlistedWandWhenNoneListed = true; + r.B.SetWorldObjectCache(FakeHost.MakeCache(r.Host, Player, new[] { Wand })); + var reEquips = typeof(BuffManager).GetField("_buffStanceReEquips", Priv)!; + var since = typeof(BuffManager).GetField("_buffStanceStuckSince", Priv)!; + FakeHost.CombatModeRefuse = true; + r.At(0); r.B.OnHeartbeat(); + Check.True(FakeHost.CombatModeRefusals >= 1, "set-up: the wielded-wand branch asked for the stance and was refused"); + Check.True((DateTime)since.GetValue(r.B)! == DateTime.MinValue, "the stuck clock has not started"); + System.Threading.Thread.Sleep(9_000); // BuffStanceStuckRecoverMs (8 s) runs on the real clock + r.At(9); r.B.OnHeartbeat(); + r.At(9.3); r.B.OnHeartbeat(); + Check.Eq((int)reEquips.GetValue(r.B)!, 0, "9 s of refusals: _buffStanceReEquips stays 0"); + Check.False(FakeHost.Uses.Contains(Wand), "and no UseObject(wand) - a MOVE on a wielded wand - went out"); + Check.True((DateTime)since.GetValue(r.B)! == DateTime.MinValue, "the clock still has not started"); + + FakeHost.CombatModeRefuse = false; + r.At(9.6); r.B.OnHeartbeat(); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "accepted: the Magic request goes out"); + Check.True((DateTime)since.GetValue(r.B)! != DateTime.MinValue, "and only now the stuck clock starts"); + Check.Eq((int)reEquips.GetValue(r.B)!, 0, "still no re-equip"); + Check.False(FakeHost.Uses.Contains(Wand), "still no UseObject(wand)"); + } + finally { PaceOff(); } + } + + private static void PeaceBeforeOpenRefusedRetried() + { + LootWorld(); + FakeHost.CombatModeCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + var host = FakeHost.Create(Player); + var bot = new Bot(host); + var cache = bot.Get("_objectCache"); + var cm = new CombatManager(host, bot.S, cache); + cm.SetPlayerId(Player); + bot.Set("_combatManager", cm); + bot.Set("_targetCorpseId", unchecked((int)Corpse)); + bot.S.PeaceModeWhenIdle = true; + bool Wants(long now) => (bool)bot.Call("WantsPeaceBeforeOpen", bot.S, now)!; + FakeHost.CombatModeRefuse = true; + Check.True(Wants(1_000), "first ask (refused): the open waits"); + Check.True(Wants(1_500), "asked again (refused): still waiting"); + Check.Eq(FakeHost.CombatModeRefusals, 2, "both asks reached the engine: the refusal did not use up the one shot"); + FakeHost.CombatModeRefuse = false; + Check.True(Wants(2_000), "accepted within the ceiling: waiting for the swap"); + Check.True(Wants(2_300), "waiting"); + Check.True(Wants(3_000), "waiting"); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "exactly one peace request went out"); + Check.False(Wants(3_600), "the ceiling counts from the FIRST ask (1000 + 2500): the open goes on"); + Check.Eq(FakeHost.CombatModeRequests.Count, 1, "and still exactly one"); + } + private static void RefusalStreakExpires() => Paced(() => + { + var host = World(combatMode: 2); + FakeHost.CombatModeRefuse = true; + Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "t0: a refusal opens a streak (false)"); + _t += 600_000; // a death, a logout: ten minutes of nothing, no accepted call in between + Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "a refusal 600 s later is a NEW streak (false), not a 600 s streak failing open"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("the engine refused the change")), 2, "and it logged its own start line"); + + // Refusals closer than the gap are one streak: it still fails open at 30 s. + ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => _t; + long start = _t; + bool open = false; + for (int s = 0; s <= 40; s += 5) { _t = start + s * 1000L; open |= host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"); } + Check.True(open, "refusals 5 s apart stay one streak and fail open past 30 s"); + + // Forget (portal / death / logout) ends the streak too. + ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => _t; + // Refusals 9 s apart are one streak (the gap is 10 s). Without the Forget the refusal at +36 s would be 36 s into it and fail open. + Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "streak begins"); + _t += 9_000; Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), "+9 s: same streak"); + ActionPacer.Forget("death"); + for (int s = 0; s < 3; s++) { _t += 9_000; Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "x"), $"after Forget a fresh streak, refusal {s + 1} (false)"); } + Check.True(ActionPacer.LastEngineRefusalMs > 0, "LastEngineRefusalMs records the newest refusal"); + ActionPacer.Reset(); + Check.Eq(ActionPacer.LastEngineRefusalMs, 0L, "Reset clears LastEngineRefusalMs"); + }); + + private static void StuckClockRestartsOnRefusal() + { + PaceOff(); + try + { + var r = new BuffRig(CombatMode.NonCombat); + SetupBuffRigVitals(r); + FakeHost.Names[Wand] = "Academy Wand"; + FakeHost.ItemTypes[Wand] = 0x8000; + FakeHost.Ints[(Wand, 10)] = 0x01000000; // in hand + r.S.WieldUnlistedWandWhenNoneListed = true; + r.B.SetWorldObjectCache(FakeHost.MakeCache(r.Host, Player, new[] { Wand })); + var reEquips = typeof(BuffManager).GetField("_buffStanceReEquips", Priv)!; + var since = typeof(BuffManager).GetField("_buffStanceStuckSince", Priv)!; + var lastTry = typeof(BuffManager).GetField("_lastBuffStanceAttempt", Priv)!; + + r.At(0); r.B.OnHeartbeat(); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "set-up: the first request is accepted and starts the stuck clock"); + Check.True((DateTime)since.GetValue(r.B)! != DateTime.MinValue, "set-up: the clock is running"); + + // The request was dropped by a teleport; the engine now refuses. The backoff gate (real clock) is opened by back-dating. + lastTry.SetValue(r.B, DateTime.Now.AddSeconds(-3)); + FakeHost.CombatModeRefuse = true; + r.At(2); r.B.OnHeartbeat(); + Check.True(FakeHost.CombatModeRefusals >= 1, "set-up: a later request was refused"); + + // 9 s of that: back-date the clock as if the real time had passed (the re-equip rule reads the real clock). + since.SetValue(r.B, DateTime.Now.AddSeconds(-9)); + r.At(9); r.B.OnHeartbeat(); + r.At(9.3); r.B.OnHeartbeat(); + Check.Eq((int)reEquips.GetValue(r.B)!, 0, "a refusal newer than the clock's start restarted it: _buffStanceReEquips stays 0"); + Check.False(FakeHost.Uses.Contains(Wand), "and no UseObject(wand) - a MOVE on a wielded wand - went out"); + Check.True((DateTime.Now - (DateTime)since.GetValue(r.B)!).TotalSeconds < 3, "the clock was restarted at now"); + + FakeHost.CombatModeRefuse = false; + r.At(9.6); r.B.OnHeartbeat(); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8,8", "accepted again"); + Check.Eq((int)reEquips.GetValue(r.B)!, 0, "still no re-equip"); + Check.False(FakeHost.Uses.Contains(Wand), "still no UseObject(wand)"); + } + finally { PaceOff(); } + } + + private static void StallToggleRefusedSpendsNoStep() + { + PaceOff(); + var host = World(combatMode: 2); + var s = new LegacyUiSettings { BotAction = "Combat" }; + var cm = new CombatManager(host, s, new WorldObjectCache(host)); + cm.SetPlayerId(Player); + const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic; + typeof(CombatManager).GetField("_activeTargetId", F)!.SetValue(cm, unchecked((int)Corpse)); + var watch = typeof(CombatManager).GetField("_stallWatch", F)!.GetValue(cm)!; + var wt = watch.GetType(); + DateTime now = DateTime.Now; + // The ladder stands at step 2 (re-select done 4 s ago); the next step due is the mode toggle. + wt.GetField("_eligibleSince", F)!.SetValue(watch, now.AddSeconds(-12)); + wt.GetField("_lastTick", F)!.SetValue(watch, now.AddMilliseconds(-100)); + wt.GetField("_step", F)!.SetValue(watch, 2); + wt.GetField("_lastStepAt", F)!.SetValue(watch, now.AddSeconds(-4)); + wt.GetField("_stallRef", F)!.SetValue(watch, now.AddSeconds(-12)); + int Step() => (int)wt.GetProperty("CurrentStep")!.GetValue(watch)!; + var run = typeof(CombatManager).GetMethod("RunStallWatchdog", F)!; + var lastAttack = typeof(CombatManager).GetField("lastAttackCmd", F)!; + lastAttack.SetValue(cm, DateTime.MinValue); + + FakeHost.CombatModeRefuse = true; + Check.True((bool)run.Invoke(cm, new object?[] { null, 1.0 })!, "the toggle step holds the tick"); + Check.Eq(FakeHost.CombatModeRefusals, 1, "the toggle reached the engine and was refused"); + Check.Eq(Step(), 2, "a refusal spends no ladder step: still at step 2"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "nothing was sent"); + Check.True((DateTime)lastAttack.GetValue(cm)! == DateTime.MinValue, "a refusal does not stamp the attack clock"); + + FakeHost.CombatModeRefuse = false; + Check.True((bool)run.Invoke(cm, new object?[] { null, 1.0 })!, "next tick: the toggle step is due again at once (not 3 s later)"); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "and the accepted toggle sent Peace"); + Check.Eq(Step(), 3, "now the ladder is at step 3"); + Check.True((DateTime)lastAttack.GetValue(cm)! != DateTime.MinValue, "the accepted toggle stamps the attack clock"); + } + + private static void CraftingPeaceRefusal() + { + PaceOff(); + const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic; + MissileCraftingManager Rig(int mode, bool refuse, out Action backdateAsk) + { + var host = World(combatMode: mode); + FakeHost.CombatModeRefuse = refuse; + var cm = new MissileCraftingManager(host, new LegacyUiSettings { EnableMissileCrafting = true }); + var t = typeof(MissileCraftingManager); + t.GetField("_currentRecipe", F)!.SetValue(cm, AmmoRecipes.All[0]); + t.GetField("_headBundleId", F)!.SetValue(cm, 0x5001); + t.GetField("_shaftBundleId", F)!.SetValue(cm, 0x5002); + t.GetField("_peaceSent", F)!.SetValue(cm, false); + t.GetField("_peaceAskedAt", F)!.SetValue(cm, DateTime.Now); + t.GetMethod("TryPeaceForCrafting", F)!.Invoke(cm, null); // StartCrafting's first step + t.GetMethod("SetState", F)!.Invoke(cm, new object[] { MissileCraftingManager.CraftState.Combining }); + backdateAsk = sec => t.GetField("_peaceAskedAt", F)!.SetValue(cm, DateTime.Now.AddSeconds(-sec)); + return cm; + } + + // (a) the engine always refuses: no combine inside the ceiling, the combine after it. + var a = Rig(CombatMode.Melee, true, out var backdate); + a.ProcessCrafting(); + Check.Eq(FakeHost.UsesOn.Count, 0, "(a) refused, inside 2.5 s: the combine waits"); + a.ProcessCrafting(); + Check.Eq(FakeHost.UsesOn.Count, 0, "(a) still waiting"); + Check.True(FakeHost.CombatModeRefusals >= 2, $"(a) peace was asked again each tick ({FakeHost.CombatModeRefusals} refusals)"); + backdate(2.6); + a.ProcessCrafting(); + Check.Eq(FakeHost.UsesOn.Count, 1, "(a) past the 2.5 s ceiling the combine goes out anyway"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "(a) no mode request ever reached the server"); + + // (b) already in Peace: no request at all, the combine on the first tick. + var b = Rig(CombatMode.NonCombat, true, out _); + b.ProcessCrafting(); + Check.Eq(FakeHost.UsesOn.Count, 1, "(b) already in Peace: the combine goes out on the first tick"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "(b) and no mode request was made"); + Check.Eq(FakeHost.CombatModeRefusals, 0, "(b) nor asked"); + } + // ── Looting ────────────────────────────────────────────────────────────────── private static void LootWorld() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs index 9cda84a..36b4a79 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs @@ -41,6 +41,7 @@ internal static class CombatHookTests r.Add("combat hook: Think holds the tick without stamping the attack time; the answer's cast stamps it", ThinkHoldsWithoutStamp); r.Add("combat hook: the heal handler is asked before kits; a drain at a monster goes through CastVital", HealBeforeKit); r.Add("combat hook: a declined, invalid or timed-out heal uses the kit the same check", HealFallsBack); + r.Add("refusal: a refused peace-for-the-kit change stamps no cast attempt or wait, and is asked again each tick", PeaceForKitRefused); r.Add("combat hook: the emergency step stays native (kit first, the handler not asked)", EmergencyStaysNative); r.Add("combat hook: the native table - version check, Claim/Poll/Decide/Release, Poll respects StructSize", NativeTable); r.Add("combat hook: a script attack spell the server refused is rejected next time (RynthAi's bolt instead)", AttackRefusalRemembered); @@ -595,10 +596,11 @@ internal static class CombatHookTests public readonly WorldObjectCache Cache; public readonly RynthCoreHost Host; - public HealRig(int healthPct = 40, int mode = CombatMode.Magic, int emergencyAt = 0, Action? setup = null) + public HealRig(int healthPct = 40, int mode = CombatMode.Magic, int emergencyAt = 0, bool peaceKits = false, Action? setup = null) { FakeHost.Reset(); FakeHost.WeaponCalls = true; + FakeHost.CombatModeCalls = peaceKits; // the peace-for-kits path needs ChangeCombatMode FakeHost.UseOnCalls = true; FakeHost.CombatModeValue = mode; foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); @@ -615,7 +617,7 @@ internal static class CombatHookTests { IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = emergencyAt, StaminaToHealthAt = 0, GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false, - UseKitsInMagicMode = true, PeaceModeForKits = false, KitMinSuccessPct = 0, MonsterRange = 20, + UseKitsInMagicMode = true, PeaceModeForKits = peaceKits, KitMinSuccessPct = 0, MonsterRange = 20, }; var skills = new CharacterSkills(host); skills.SetPlayerId(Player); @@ -674,6 +676,25 @@ internal static class CombatHookTests Check.Eq(FakeHost.Casts.Single(), (Player, Id("Heal Self V")), "target 0: the player"); }); + private static void PeaceForKitRefused() => Guard(() => + { + var rig = new HealRig(mode: CombatMode.Melee, peaceKits: true); + Check.True(rig.B.LastCastAttemptAt == DateTime.MinValue, "set-up: no cast attempt yet"); + FakeHost.CombatModeRefuse = true; // the engine turns the mode change away + const int N = 6; + for (int i = 0; i < N; i++) rig.B.CheckVitals(); + Check.Eq(FakeHost.CombatModeRefusals, N, "the peace request is asked again on every tick"); + Check.True(rig.B.LastCastAttemptAt == DateTime.MinValue, "_lastCastAttempt stays MinValue: a refusal is not an attempt"); + var wait = typeof(BuffManager).GetField("_healWaitKind", BindingFlags.Instance | BindingFlags.NonPublic)!; + Check.False(((string?)wait.GetValue(rig.B) ?? "").Contains("peace mode"), "no peace-mode wait is recorded"); + Check.False(rig.KitUsed, "and the kit is not used out of peace"); + + FakeHost.CombatModeRefuse = false; // accepted: now it counts + rig.B.CheckVitals(); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "the peace request goes out"); + Check.True(rig.B.LastCastAttemptAt != DateTime.MinValue, "and only now the attempt is stamped"); + }); + private static void HealFallsBack() => Guard(() => { void Case(string what, Action answer, string? log = null) diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs index a690b1a..9b88f72 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs @@ -48,6 +48,7 @@ internal static class WeaponTests r.Add("slayer: creature type unknown, the old choice", SlayerUnknownType); r.Add("slayer: the element follows the chosen weapon", SlayerElement); r.Add("slayer: read through the host (int 166, float 138, monster int 2), cached by wcid", SlayerFromHost); + r.Add("refusal: a refused stance change in combat's equip pass sets no backoff and starts no stuck clock", StanceRefusedKeepsBackoff); r.Add("weapon choice: an unlisted wand is never picked (Damage tab, learned, pack, name)", UnlistedNeverPicked); r.Add("Items list: a listed item no longer carried is reported missing (pack, hand, unknown)", MissingFromPack); r.Add("weapon swap: one in flight, confirmed, retry cap, then what's in hand", SwapOneInFlight); @@ -645,10 +646,11 @@ internal static class WeaponTests public readonly MonsterDamageStore Store = new(); public WorldObject Target; - public Rig(uint wcid, string monsterName) + public Rig(uint wcid, string monsterName, bool modeCalls = false) { FakeHost.Reset(); FakeHost.WeaponCalls = true; + FakeHost.CombatModeCalls = modeCalls; FakeHost.CombatModeValue = CombatMode.Magic; FakeHost.Names[ListedWand] = "Wand"; FakeHost.ItemTypes[ListedWand] = 0x8000; FakeHost.Ints[(ListedWand, 45)] = 0x40; // identified: Lightning @@ -698,6 +700,26 @@ internal static class WeaponTests Check.Eq(missing.Count, 0, "inventory not known yet (empty, logging in): nothing reported missing"); } + private static void StanceRefusedKeepsBackoff() + { + var rig = new Rig(1535, "Ethereal Wisp", modeCalls: true); + rig.C.InHandOverride = () => unchecked((int)ListedWand); // the wand is in hand + FakeHost.CombatModeValue = CombatMode.NonCombat; // but the stance is not Magic yet + FakeHost.Ints[(ListedWand, 10)] = 0x01000000; // CurrentWieldedLocation: reads wielded (the stuck-clock branch) + var equip = typeof(CombatManager).GetMethod("EquipWeaponAndSetStance", BindingFlags.Instance | BindingFlags.NonPublic)!; + var last = typeof(CombatManager).GetField("lastStanceAttempt", BindingFlags.Instance | BindingFlags.NonPublic)!; + var stuck = typeof(CombatManager).GetField("_stanceStuckSince", BindingFlags.Instance | BindingFlags.NonPublic)!; + FakeHost.CombatModeRefuse = true; + for (int i = 0; i < 5; i++) equip.Invoke(rig.C, new object[] { rig.Target, "Auto" }); + Check.Eq(FakeHost.CombatModeRefusals, 5, "every pass asks again: a refusal sets no backoff"); + Check.True((DateTime)last.GetValue(rig.C)! == DateTime.MinValue, "lastStanceAttempt stays put"); + Check.True((DateTime)stuck.GetValue(rig.C)! == DateTime.MinValue, "the stuck clock has not started"); + Check.Eq(FakeHost.Uses.Count, 0, "no re-equip UseObject"); + FakeHost.CombatModeRefuse = false; + equip.Invoke(rig.C, new object[] { rig.Target, "Auto" }); + Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Magic.ToString(), "accepted: the request goes out"); + Check.True((DateTime)last.GetValue(rig.C)! != DateTime.MinValue, "and only now lastStanceAttempt is stamped"); + } private static void UnlistedNeverPicked() { var rig = new Rig(1535, "Ethereal Wisp"); diff --git a/Tools/RynthCore.RynthAiTests/Tests/CombatStallWatchdogTests.cs b/Tools/RynthCore.RynthAiTests/Tests/CombatStallWatchdogTests.cs index d7098be..ecbd079 100644 --- a/Tools/RynthCore.RynthAiTests/Tests/CombatStallWatchdogTests.cs +++ b/Tools/RynthCore.RynthAiTests/Tests/CombatStallWatchdogTests.cs @@ -21,6 +21,7 @@ internal static class CombatStallWatchdogTests r.Add("stall: a swing after a step is a recovery", Recovery); r.Add("stall: a tick gap starts the count over", TickGapResets); r.Add("stall: ineligible never acts", Ineligible); + r.Add("stall: Unfire takes a step back - the same step is due again next tick, not 3 s later", UnfireRetries); } /// Ticks every 500 ms from to @@ -95,4 +96,27 @@ internal static class CombatStallWatchdogTests Check.Eq(acted, 0, "no action in a minute of ineligible ticks"); Check.Eq(w.Episodes, 0, "no episodes"); } -} + + private static void UnfireRetries() + { + var w = new CombatStallWatchdog(); + Check.Eq(RunUntilAction(w, 0, 20_000, NoEvidence), (Act.Reissue, 6000), "step 1"); + Check.Eq(RunUntilAction(w, 6500, 20_000, NoEvidence), (Act.Reselect, 9000), "step 2"); + Check.Eq(RunUntilAction(w, 9500, 20_000, NoEvidence), (Act.ToggleMode, 12000), "step 3 fires"); + + w.Unfire(); // the engine refused the toggle + Check.Eq(w.CurrentStep, 2, "Unfire: back at step 2"); + Check.Eq(RunUntilAction(w, 12_500, 20_000, NoEvidence), (Act.ToggleMode, 12_500), "the toggle is due again on the very next tick"); + Check.Eq(RunUntilAction(w, 13_000, 20_000, NoEvidence), (Act.Rewield, 15_500), "an accepted toggle then spaces step 4 a full 3 s after it"); + + // Unfire at step 1 gives the episode back too. + var v = new CombatStallWatchdog(); + Check.Eq(RunUntilAction(v, 0, 10_000, NoEvidence), (Act.Reissue, 6000), "step 1"); + Check.Eq(v.Episodes, 1, "one episode"); + v.Unfire(); + Check.Eq(v.CurrentStep, 0, "back to no step"); + Check.Eq(v.Episodes, 0, "and the episode is not counted until a step really goes out"); + Check.Eq(RunUntilAction(v, 6500, 10_000, NoEvidence), (Act.Reissue, 6500), "step 1 again next tick"); + Check.Eq(v.Episodes, 1, "one episode"); + } +} \ No newline at end of file