Snapshot for release 2026.10.19.1 (internal f0bdcf8)

This commit is contained in:
Tom Bohar 2026-10-19 09:11:22 -04:00
commit 39de36d3af
131 changed files with 11266 additions and 520 deletions

View file

@ -113,10 +113,16 @@ internal static unsafe class FakeHost
/// <summary>When true (the default) a give lands at once, as the server does when it isn't busy:
/// the item goes to the target. False = the server hasn't taken it (still carried).</summary>
public static bool GiveLands = true;
/// <summary>Optional: runs for every give instead of the default landing (a test's own server: NPC takes one per give, busy, ...).</summary>
public static Action<uint, uint, int>? GiveHandler;
/// <summary>Opt-in: wires StopCompletely (off by default so no other test sees it).</summary>
public static bool StopCalls;
/// <summary>StopCompletely calls (opt-in with <see cref="StopCalls"/>).</summary>
public static int Stops;
/// <summary>Opt-in: wires MeleeAttack and MissileAttack; calls land in <see cref="AttackCalls"/>.</summary>
public static bool AttackSendCalls;
/// <summary>Every melee or missile attack (kind, target, height, power), in order (opt-in with <see cref="AttackSendCalls"/>).</summary>
public static readonly List<(string Kind, uint Target, int Height, float Power)> AttackCalls = new();
/// <summary>Opt-in: wires SetMotion; calls land in <see cref="MotionCalls"/>.</summary>
public static bool SetMotionCalls;
/// <summary>Every SetMotion (motion, on), in order (opt-in with <see cref="SetMotionCalls"/>).</summary>
@ -139,6 +145,8 @@ internal static unsafe class FakeHost
/// and is counted in <see cref="RefusedIdRequests"/>, not in <see cref="IdRequests"/>.</summary>
public static bool RequestIdAccepts = true;
public static int RefusedIdRequests;
/// <summary>False = UseObject returns 0 (the engine did not send it); the use is still recorded in <see cref="Uses"/>.</summary>
public static bool UseObjectAccepts = true;
/// <summary>Opt-in (set before Create): UseObject, RequestId, HasAppraisalData and
/// GetCurrentCombatMode (answering <see cref="CombatModeValue"/>). Tests written without
/// them keep seeing those calls as absent.</summary>
@ -261,7 +269,9 @@ internal static unsafe class FakeHost
public static void Reset()
{
EquippedCalls = false; EquippedNotReady = false; Equipped.Clear();
#if !RYNTHILT_TESTS
RynthCore.Plugin.RynthAi.EquippedState.Invalidate();
#endif
Nav3DCalls = false; Nav3DRings.Clear(); Nav3DLines.Clear(); Nav3DTriangles.Clear();
Names.Clear(); Positions.Clear(); ItemTypes.Clear();
Ints.Clear(); Doubles.Clear(); Quads.Clear(); Bools.Clear(); Strings.Clear();
@ -272,9 +282,9 @@ internal static unsafe class FakeHost
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); AfterCastSpell = null;
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true;
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null;
Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1;
RequestIdAccepts = true; RefusedIdRequests = 0;
RequestIdAccepts = true; RefusedIdRequests = 0; UseObjectAccepts = true;
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false;
WeenieErrorCalls = false; WeenieErrSeq = 0; WeenieErrCode = WeenieErrEvent = WeenieErrObject = 0;
@ -349,6 +359,11 @@ internal static unsafe class FakeHost
api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&StopCompletely;
if (SetMotionCalls)
api.SetMotionFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&SetMotion;
if (AttackSendCalls)
{
api.MeleeAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, float, int>)&MeleeAttack;
api.MissileAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, float, int>)&MissileAttack;
}
if (Nav3DCalls)
{
api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&Nav3DClear;
@ -778,6 +793,12 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); Sent.Add(AutoRun ? "autorun on" : "autorun off"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int MeleeAttack(uint target, int height, float power) { AttackCalls.Add(("melee", target, height, power)); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int MissileAttack(uint target, int height, float power) { AttackCalls.Add(("missile", target, height, power)); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetMotion(uint motion, int on) { MotionCalls.Add((motion, on != 0)); Sent.Add($"motion 0x{motion:X8} {(on != 0 ? "on" : "off")}"); return 1; }
@ -803,7 +824,10 @@ internal static unsafe class FakeHost
private static int GiveObjectTo(uint item, uint target, int amount)
{
Gives.Add((item, target, amount));
if (GiveLands && amount == 0) Containers[item] = target;
if (GiveHandler != null) { GiveHandler(item, target, amount); return 1; }
// The server takes the whole object for amount 0, or for an amount that covers the stack (a single
// item has no StackCount: its stack is 1, so an explicit 1 takes it whole).
if (GiveLands && (amount == 0 || amount >= (Ints.TryGetValue((item, 12), out int stack) ? stack : 1))) Containers[item] = target;
return 1;
}
@ -813,7 +837,7 @@ internal static unsafe class FakeHost
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); OnUseObject?.Invoke(id); return 1; }
private static int UseObject(uint id) { Uses.Add(id); OnUseObject?.Invoke(id); return UseObjectAccepts ? 1 : 0; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectState(uint id, uint* state)
{

View file

@ -92,10 +92,13 @@ internal static class Program
TargetingTests.Register(runner);
LootAddItemTests.Register(runner);
GiveTests.Register(runner);
IdRefusalTests.Register(runner);
DungeonMapBakeTests.Register(runner);
MonsterEditorTests.Register(runner);
InstallPathsTests.Register(runner);
PetRefillTests.Register(runner);
AutoStackTests.Register(runner);
RingEvadeTests.Register(runner);
IgnoreMonsterTests.Register(runner);
WorldCacheTypedTests.Register(runner);
NavOverlayTests.Register(runner);
@ -128,12 +131,15 @@ internal static class Program
VTankHotkeyTests.Register(runner);
OneTouchHealTests.Register(runner);
SaveFailureTests.Register(runner);
EnvironmentImpactTests.Register(runner);
SkCombatAddonTests.Register(runner);
DoorTests.Register(runner);
ServerPolicyTests.Register(runner);
BlankLoadTests.Register(runner);
GiveProfileTests.Register(runner);
TinkerTests.Register(runner);
LauncherSwapTests.Register(runner);
MissileCraftingTests.Register(runner);
SelfRatingsTests.Register(runner);
IltClientLookupTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);

View file

@ -66,7 +66,8 @@ internal static class ActionPacingTests
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("corpse id: a refused RequestId is not recorded as asked - the next evaluation asks again and the accepted one goes out", CorpseIdRefusedRetried);
r.Add("corpse id: an accepted request with no data is asked again after 3 s (not before), once per 3 s, with no give-up cap", CorpseIdReaskedWithoutData);
r.Add("corpse id: an accepted request with no data is asked again after 3 s (not before), once per 3 s, at most 3 re-asks per corpse", CorpseIdReaskedWithoutData);
r.Add("corpse id: Loot From All Corpses needs no killer name - the first request goes out, no re-ask ever follows; My Kills Only gives up after 3 re-asks, a new corpse starts over", CorpseIdAllCorpsesNoReask);
r.Add("corpse id: two corpses in range, no data for either - only the targeted one re-asks; the other stays at one accepted request (a refused one is still retried)", CorpseIdOnlyCandidateReasks);
r.Add("corpse id: 20 uncached corpses, a refusal window, then accept - at most 2 requests in the first accepted tick, the target among them; refused retries are 250 ms apart", CorpseIdBurstCapped);
r.Add("corpse id: the open container is a candidate and re-asks; delete and the >200 prune clear every id map", CorpseIdOpenContainerAndCleanup);
@ -871,13 +872,46 @@ internal static class ActionPacingTests
Check.Eq(Asked(), 2, "1 s after the re-ask: waits");
_t += 2_000;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 3, "one re-ask per 3 s, and no cap");
Check.Eq(Asked(), 3, "one re-ask per 3 s");
_t += 3_000;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 4, "the third re-ask is the last");
for (int i = 0; i < 10; i++) { _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); }
Check.Eq(Asked(), 13, "ten more 3 s periods, ten more asks");
Check.Eq(Asked(), 4, "ten more 3 s periods, no more asks: the corpse is given up on");
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
_t += 3_000;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 13, "once the data has arrived nothing more is asked");
Check.Eq(Asked(), 4, "and once the data has arrived nothing is asked either");
});
private static void CorpseIdAllCorpsesNoReask() => Paced(() =>
{
// All Corpses: the killer name decides nothing, so no stream of requests (each accepted one
// raises the client's busy count). The one first request still goes out: the radar colours
// your own kills from the LongDesc it brings.
var (bot, obj) = CorpseIdRig();
bot.S.LootOwnership = 2;
int Asked() => FakeHost.IdRequests.Count(i => i == Corpse);
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 1, "All Corpses: the first request goes out");
for (int i = 0; i < 6; i++) { _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); }
Check.Eq(Asked(), 1, "All Corpses: no re-ask in 18 s without data");
object dec = bot.Call("EvaluateCorpseLootDecision", obj)!;
Check.True((bool)dec.GetType().GetProperty("ShouldLoot")!.GetValue(dec)!, "the corpse is looted either way");
// The same corpse in My Kills Only: the cap applies, the count is per corpse and a deleted
// corpse starts over.
bot.S.LootOwnership = 0;
_t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 2, "My Kills Only: the name is needed, so it re-asks");
for (int i = 0; i < 10; i++) { _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); }
Check.Eq(Asked(), 4, "and stops after the third re-ask");
bot.Call("HandleCorpseObjectDeleted", Corpse);
_t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 5, "a corpse that comes back (deleted and created again) starts over");
var counts = bot.Get<System.Collections.Generic.Dictionary<int, int>>("_corpseIdAskCount");
bot.Call("HandleCorpseObjectDeleted", Corpse);
Check.False(counts.ContainsKey(unchecked((int)Corpse)), "delete clears _corpseIdAskCount");
});
private static void CorpseIdOnlyCandidateReasks() => Paced(() =>
{
@ -900,7 +934,7 @@ internal static class ActionPacingTests
Check.Eq(Asked(Corpse), 1, "the candidate: refused once, then one accepted request");
Check.Eq(Asked(CorpseB), 1, "the other corpse: a refused request is retried, one accepted request");
for (int i = 0; i < 4; i++) { _t += 3_000; Both(); }
Check.Eq(Asked(Corpse), 5, "no data: the candidate re-asks once per 3 s");
Check.Eq(Asked(Corpse), 4, "no data: the candidate re-asks once per 3 s, three times at most");
Check.Eq(Asked(CorpseB), 1, "the other corpse never asks a second time");
bot.Set("_targetCorpseId", unchecked((int)CorpseB));
_t += 3_000; Both();

View file

@ -0,0 +1,38 @@
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// AutoStack (Loot/InventoryManager.cs): the group key and the merge-progress rule. From Silentkelpie's
// PR 12 (group by WCID: two stacks with the same name but different weenies never merge, and AutoStack
// retried them forever), plus the partial fill: a pair whose total is over the max is still merged
// (the server fills the target, the source survives smaller) and that counts as progress.
internal static class AutoStackTests
{
public static void Register(Runner r)
{
r.Add("autostack: stacks group by WCID; the name is only the fallback while the WCID is unknown", GroupKey);
r.Add("autostack: a partial fill (target grew, source shrank) is progress; an untouched pair is not", Progress);
}
private static void GroupKey()
{
Check.True(InventoryManager.StackGroupKey(42517, "Coalesced Mana") != InventoryManager.StackGroupKey(42518, "Coalesced Mana"),
"same name, different WCIDs: separate groups");
Check.Eq(InventoryManager.StackGroupKey(42517, "Coalesced Mana"), InventoryManager.StackGroupKey(42517, "Coalesced Mana (renamed)"),
"same WCID: one group whatever the label says");
Check.Eq(InventoryManager.StackGroupKey(0, "Taper"), InventoryManager.StackGroupKey(0, "Taper"), "no WCID: the name groups");
Check.True(InventoryManager.StackGroupKey(0, "Taper") != InventoryManager.StackGroupKey(5, "Taper"), "known and unknown WCID do not mix");
Check.True(InventoryManager.StackGroupKey(7, null).Length > 0, "a null name is safe");
}
private static void Progress()
{
// 90 + 20 over a max of 100: the server fills the target to 100 and leaves 10 in the source.
Check.True(InventoryManager.MergeProgressed(90, 20, 100, 10), "partial fill");
Check.True(InventoryManager.MergeProgressed(30, 20, 50, 20), "target grew (source count read late)");
Check.True(InventoryManager.MergeProgressed(30, 20, 30, 0), "source emptied");
Check.False(InventoryManager.MergeProgressed(30, 20, 30, 20), "nothing changed: not progress");
Check.False(InventoryManager.MergeProgressed(0, 20, 30, 20), "no recorded counts: not progress");
}
}

View file

@ -70,6 +70,7 @@ internal static class BuffTests
r.Add("buff filter: the skip line groups by reason, is capped, and repeats only when it changes", SkipLineGroupedAndCapped);
r.Add("buff filter: the weapon kit is cached for a second, and rebuilt when its inputs change", KitCached);
r.Add("buff filter: skipped buffs are named, once per run", FilterVisibility);
r.Add("buff filter: untrained skills alone never print a chat line (log, page and /ra buff skipped keep them)", UntrainedSkillIsQuiet);
r.Add("buff filter: SkipUnusableBuffs defaults on, loads, saves, bridges, is in the settings map", SkipUnusableSetting);
r.Add("buff choice: spell names the tables miss (Bludgeon Bane, Nuhmudira's, T'ing, Celdiseth's)", NameGapsResolve); // was a known failure; fixed by 940cb21
@ -93,6 +94,11 @@ internal static class BuffTests
r.Add("buff upgrade: a late line the cast tracker credits to an earlier send does not confirm the pending cast", UpgradeLateLineFromEarlierSend);
r.Add("buff upgrade: two upgrade no-shows do not park the family; its lower level running low is recast", UpgradeNoShowsDoNotPark);
r.Add("buff upgrade: two item spell upgrades with no chat do not park the family; its lower level running low is recast", UpgradeArmorNoChatDoesNotPark);
r.Add("buff upgrade: an upgrade an item spell never lands is parked, not looped; the lower level is still refreshed and the park ends", UpgradeArmorNoChatParksUpgrade);
r.Add("buff upgrade: three silent self-buff no-shows park the upgrade only; the lower level is still refreshed", UpgradeNoShowsParkUpgrade);
r.Add("buff upgrade: an in-run upgrade the server never answers is parked and the force run ends", UpgradeNoShowInRunEnds);
r.Add("buff upgrade: a confirmed upgrade resets the no-show count", UpgradeConfirmedResetsNoShows);
r.Add("buff upgrade: Cancel Buffing ends the pending upgrade", UpgradeCancelEndsPending);
r.Add("buff upgrade: an upgrade that would leave mana under the reserve waits for Stamina to Mana, then goes", UpgradeWaitsForManaReserve);
}
@ -1389,10 +1395,12 @@ internal static class BuffTests
/// <summary>Lets the pending <paramref name="id"/> reach its give-up unanswered twice (it is resent
/// in between); returns the give-ups done. Every other cast is confirmed.</summary>
private static int FailTwice(BeatRig h, int id)
private static int FailTwice(BeatRig h, int id) => FailTimes(h, id, 2);
private static int FailTimes(BeatRig h, int id, int times)
{
int gaveUp = 0;
for (int k = 0; k < 20 && gaveUp < 2; k++)
for (int k = 0; k < 20 && gaveUp < times; k++)
{
if (h.R.B.PendingSpellId != id) { if (h.Beats(40, x => x == id) == 0) break; continue; }
h.SendLongAgo(6);
@ -1448,6 +1456,133 @@ internal static class BuffTests
Check.True(h.Beats(40, id => FamilyOf(id) == fam) != 0, "running low: recast");
}
private static bool Has(BuffManager b, string field, int key) => ((System.Collections.IDictionary)Fld<object>(b, field)).Contains(key);
/// <summary>The registry as the first run left it (every player buff of the suite at tier 6), CEM with <paramref name="cemLeft"/> s left.</summary>
private static (string, double)[] SixRegistry(int cem, double cemLeft) =>
FakeHost.Casts.Select(c => c.SpellId).Where(id => !BuffManager.IsItemEnchantment(NameOf(id))).Distinct()
.Select(id => (NameOf(id), FamilyOf(id) == cem ? cemLeft : 3000.0)).ToArray();
// Review finding (PR 15): an upgrade that is a SILENT no-show was never struck, parked or counted, so it
// was recast at every give-up forever (12x/minute), and a force/batch run never ended. Now: after three in
// a row the upgrade alone is parked; the family is not blacklisted and its lower level still refreshes.
private static void UpgradeNoShowsParkUpgrade()
{
int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI");
var h = new BeatRig(300);
h.FirstRun();
FakeHost.Skills[(Player, STypeCreature)] = (340, 2);
h.R.Live(SixRegistry(cem, 3000));
int seven = h.Beats(60, id => FamilyOf(id) == cem && LevelOf(id) == 7);
Check.True(seven != 0, "CEM 7 is sent over the live VI");
Check.Eq(FailTimes(h, seven, 3), 3, "three no-shows");
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == seven), 3, "sent three times, not a fourth: the upgrade is parked");
Check.False(Parked(h.R, cem), "the family itself is not parked");
// Nothing more goes out for it, and the run (the batch the upgrade started) ends.
h.Beats(150, _ => false);
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == seven), 3, "still three after 150 more beats");
Check.False(h.R.B.GetStateSnapshot().IsForceRebuffing, "the run ends");
Check.Eq(h.R.B.PendingSpellId, 0, "nothing pending");
// The level it was cast over runs low: a normal refresh goes out (not counted as an upgrade).
int upgrades = h.R.B.BuffUpgrades;
h.R.Live(SixRegistry(cem, 100));
Check.True(h.Beats(150, id => FamilyOf(id) == cem) != 0, "the lower level running low is recast while the upgrade is parked");
Check.Eq(h.R.B.BuffUpgrades, upgrades, "and that cast is not an upgrade");
Check.False(Parked(h.R, cem), "the family is still not parked");
}
// The item spell twin (armor lost on death / weapon swapped, its lower record still unexpired).
private static void UpgradeArmorNoChatParksUpgrade()
{
var h = new BeatRig(300);
h.FirstRun();
FakeHost.Skills[(Player, STypeItem)] = (340, 2);
int item7 = h.Beats(80, id => BuffManager.IsItemEnchantment(NameOf(id)) && LevelOf(id) == 7);
Check.True(item7 != 0, "an item spell is upgraded to 7: " + NameOf(item7));
int fam = FamilyOf(item7);
Check.Eq(FailTimes(h, item7, 3), 3, "three no-chat give-ups");
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == item7), 3, "sent three times, not a fourth");
Check.False(Parked(h.R, fam), "the family itself is not parked");
h.Beats(150, _ => false);
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == item7), 3, "still three after 150 more beats");
Check.False(h.R.B.GetStateSnapshot().IsForceRebuffing, "the run ends");
// Its VI record runs low: the family is recast (a normal refresh, not an upgrade).
int upgrades = h.R.B.BuffUpgrades;
object rec = ((System.Collections.IDictionary)Fld<object>(h.R.B, "_itemSpellTimers"))[fam]!;
rec.GetType().GetField("ExpiresAt")!.SetValue(rec, DateTime.Now.AddSeconds(100));
Check.True(h.Beats(60, id => FamilyOf(id) == fam) != 0, "running low: recast while the upgrade is parked");
Check.Eq(h.R.B.BuffUpgrades, upgrades, "not an upgrade");
Check.False(Parked(h.R, fam), "the family is not parked");
// The park is time-boxed: once it ends the upgrade is tried again.
h.R.B.CancelBuffing();
rec.GetType().GetField("ExpiresAt")!.SetValue(rec, DateTime.Now.AddSeconds(3000));
((System.Collections.IDictionary)Fld<object>(h.R.B, "_upgradeParkedUntil"))[fam] = DateTime.Now.AddSeconds(-1);
Check.True(h.Beats(80, id => id == item7) != 0, "after the park ends the upgrade is cast again");
}
// An explicit force run with an upgrade the server never answers: parked after three, the run ends.
private static void UpgradeNoShowInRunEnds()
{
int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI");
var h = new BeatRig(300);
h.R.Live(("Strength Self I", 3000));
h.R.B.ForceFullRebuff();
int n = 0;
int seven = h.Beats(150, id => { if (++n == 3) FakeHost.Skills[(Player, STypeCreature)] = (340, 2); return FamilyOf(id) == cem && LevelOf(id) == 7; });
Check.True(seven != 0, "CEM 7 is sent in the run, over the VI it cast");
Check.Eq(FailTimes(h, seven, 3), 3, "three no-shows");
h.Beats(200, _ => false);
// The registry here never shows the run's VIs, so once the upgrade is parked CEM is cast as an ordinary
// buff with no timer, and the usual two-strike no-show park ends that: three upgrade sends + at most two.
int sends = FakeHost.Casts.Count(c => c.SpellId == seven);
Check.True(sends <= 3 + 2, $"bounded: {sends} sends of CEM 7");
Check.False(h.R.B.GetStateSnapshot().IsForceRebuffing, "the force run ends (it kept buffing's priority for good)");
Check.Eq(h.R.B.PendingSpellId, 0, "nothing pending");
}
// Confirmed upgrades are unchanged: they land, and they reset the count (the next upgrade starts from zero).
private static void UpgradeConfirmedResetsNoShows()
{
var h = new BeatRig(300);
h.FirstRun();
FakeHost.Skills[(Player, STypeItem)] = (340, 2);
int item7 = h.Beats(80, id => BuffManager.IsItemEnchantment(NameOf(id)) && LevelOf(id) == 7);
Check.True(item7 != 0, "an item spell is upgraded to 7");
int fam = FamilyOf(item7);
Check.Eq(FailTimes(h, item7, 2), 2, "two no-chat give-ups");
Check.Eq(h.R.B.PendingSpellId, item7, "sent again");
Check.True(Has(h.R.B, "_upgradeNoShowCounts", fam), "two are counted");
h.R.B.OnChatWindowText($"You cast {NameOf(item7)} on Rune Robe", 7); // it lands
Check.False(Has(h.R.B, "_upgradeNoShowCounts", fam), "the count is reset by the landing");
Check.False(Has(h.R.B, "_upgradeParkedUntil", fam), "nothing parked");
int sends = FakeHost.Casts.Count(c => c.SpellId == item7);
h.Beats(60, _ => false);
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == item7), sends, "landed at 7: not cast again");
// The record falls back to VI (armor swapped): the upgrade gets a full three tries again.
object rec = ((System.Collections.IDictionary)Fld<object>(h.R.B, "_itemSpellTimers"))[fam]!;
rec.GetType().GetField("SpellLevel")!.SetValue(rec, 6);
Check.True(h.Beats(80, id => id == item7) != 0, "the upgrade is cast again");
Check.Eq(FailTimes(h, item7, 2), 2, "two more no-shows");
Check.Eq(h.R.B.PendingSpellId, item7, "not parked: sent again after the second");
Check.False(Has(h.R.B, "_upgradeParkedUntil", fam), "the count started from zero");
}
// Cancelling the buff step left the pending upgrade behind.
private static void UpgradeCancelEndsPending()
{
var (rig, seven) = PendingCem7();
Check.True(seven != 0 && rig.B.PendingSpellId == seven, "CEM 7 is pending");
Check.Eq(Fld<int>(rig.B, "_pendingUpgradeSpellId"), seven, "as an upgrade");
rig.B.CancelBuffing();
Check.Eq(rig.B.PendingSpellId, 0, "cancelled");
Check.Eq(Fld<int>(rig.B, "_pendingUpgradeSpellId"), 0, "the upgrade is no longer pending");
}
// No limit and no rest, through OnHeartbeat: an always-fizzling CEM 7 is sent on
// every beat (one per answer), the late VI line confirms nothing, and nothing goes out unanswered.
private static void UpgradeCapViaHeartbeat()
@ -1637,8 +1772,15 @@ internal static class BuffTests
Check.False(rig.B.GetStateSnapshot().IsForceRebuffing, "/ra buff cancel ends it");
FakeHost.Chat.Clear();
int kitRuns = rig.B.KitComputations;
Cmd("skipped");
Check.True(FakeHost.Chat.Any(c => c.Contains("Buff filter")), "/ra buff skipped answers");
Check.Eq(FakeHost.Chat.Count, 0, "/ra buff skipped only queues the report: the command thread builds nothing and says nothing");
Check.Eq(rig.B.KitComputations, kitRuns, "and never touches the pump's weapon-kit state");
rig.B.OnHeartbeat();
Check.True(FakeHost.Chat.Any(c => c.Contains("Buff filter")), "/ra buff skipped answers from the next heartbeat");
FakeHost.Chat.Clear();
rig.B.OnHeartbeat();
Check.Eq(FakeHost.Chat.Count, 0, "once per request");
FakeHost.Chat.Clear();
Cmd();
Check.True(FakeHost.Chat.Any(c => c.Contains("/ra buff force")), "no word: the help");
@ -1751,7 +1893,8 @@ internal static class BuffTests
Check.True(lines[0].Contains("skill untrained: ") && lines[0].Contains("Heavy Weapon"), "it names the untrained mastery and why: " + lines[0]);
Check.True(lines[0].Contains("no melee or missile weapon listed: Blood Drinker"), "and the weapon aura and why: " + lines[0]);
Check.False(lines[0].Contains("Spirit Drinker"), "but not what stays");
Check.True(FakeHost.Chat.Any(c => c.Contains("Buff run skips")), "the same line goes to chat");
Check.True(FakeHost.Chat.Any(c => c.Contains("Buff run skips") && c.Contains("no melee or missile weapon listed")), "a line goes to chat for the aura");
Check.False(FakeHost.Chat.Any(c => c.Contains("Buff run skips") && c.Contains("skill untrained")), "but the untrained skill stays out of the chat line");
Check.True(rig.B.FilterSkipSummary().Contains("Swift Killer"), "the settings page reads the same list");
// The automatic batch logs it too, once.
@ -1769,6 +1912,27 @@ internal static class BuffTests
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Buff] filter skips:")), 0, "nothing skipped: no line");
}
// An untrained skill is the normal state of most characters. It must not print a chat line at every buff run.
private static void UntrainedSkillIsQuiet()
{
var rig = SuiteRig(MeleeItem, WandItem);
FakeHost.Skills[(Player, SkillHeavy)] = (10, 1); // untrained, and nothing else is skipped
rig.Live(("Strength Self I", 3000));
rig.B.ForceFullRebuff();
Check.True(rig.B.FilterSkips.Count > 0 && rig.B.FilterSkips.All(s => s.Reason == "skill untrained"), "only untrained skills are skipped");
Check.Eq(FakeHost.Chat.Count(c => c.Contains("Buff run skips")), 0, "no chat line for untrained skills alone");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Buff] filter skips:") && l.Contains("skill untrained")), 1, "the log keeps it");
Check.True(rig.B.FilterSkipSummary().Contains("skill untrained: ") && rig.B.FilterSkipSummary().Contains("Heavy Weapon"), "the Buffing page summary keeps it");
rig.B.RequestSkipReport();
rig.B.OnHeartbeat();
Check.True(FakeHost.Chat.Any(c => c.Contains("Buff filter skips: ") && c.Contains("skill untrained")), "so does /ra buff skipped");
// A later run stays quiet in chat too.
FakeHost.Chat.Clear();
rig.B.ForceFullRebuff();
Check.Eq(FakeHost.Chat.Count(c => c.Contains("Buff run skips")), 0, "still quiet");
}
private static void KitEdgeCases()
{
// A listed item the cache keeps unclassified (a Misc-typed thing): nothing is filtered.

View file

@ -28,6 +28,8 @@ internal static class CombatHookTests
public static void Register(Runner r)
{
r.Add("combat hook: the decided spell reaches the cast (hook off: RynthAi's bolt)", DecidedSpellIsCast);
r.Add("combat hook: a rule with no attack shapes enabled is not asked and not cast at, script or not", ScriptRespectsNoAttackShapes);
r.Add("combat hook: shutdown clears the UseDone reader (it captured the host)", ShutdownDropsUseDoneReader);
r.Add("combat hook: a decline casts RynthAi's own spell the same tick", DeclineGoesNative);
r.Add("combat hook: no answer by the deadline - RynthAi's spell, the timeout logged once a minute", TimeoutGoesNative);
r.Add("combat hook: a lapsed lease is native; another owner is refused while the lease is live", LeaseExpiry);
@ -236,6 +238,45 @@ internal static class CombatHookTests
Check.Eq((next.LastSeq, next.LastSpell, next.LastTarget), (req.Seq, (uint)drain, (uint)Target), "ctx.last is the previous cast");
});
// A rule with every attack shape off means no offensive cast at that monster; a script's attack is no exception.
private static void ScriptRespectsNoAttackShapes() => Guard(() =>
{
int drain = Id("Drain Health Other V");
var off = new AttackRig();
off.S.MonsterRules.Clear();
off.S.MonsterRules.Add(new MonsterRule { Name = "Default", DamageType = "Fire", UseBolt = false, UseArc = false, UseStreak = false, UseRing = false, UseBlast = false, UseWall = false });
Claim(Atk);
off.Attack();
Check.Eq(CombatHook.Attack.Opened, 0, "no shapes: the script is not even asked");
Check.Eq(off.C.LastCombatSkipReason, "no-attack-shapes", "skipped for the rule");
Check.False(off.C.ScriptHeld, "and not held for an answer");
Check.Eq(FakeHost.Casts.Count, 0, "nothing cast");
// Control: the same script with a shape on is asked and its spell is cast.
var on = new AttackRig();
Claim(Atk);
ScriptCast(on, drain);
Check.Eq(CombatHook.Attack.Opened, 1, "a shape on: the script is asked");
Check.True(FakeHost.Casts.Any(c => c.SpellId == drain), "and its spell is cast");
});
// The UseDone reader the plugin installs captures its host; a shut-down plugin must not keep it.
private static void ShutdownDropsUseDoneReader() => Guard(() =>
{
CombatHook.LastUseDone = () => (1, 0u);
CombatHookInterface.Shutdown(); // PluginExports.Shutdown calls it for every unload
Check.Null(CombatHook.LastUseDone, "the exported shutdown clears the reader");
FakeHost.Reset();
var host = FakeHost.Create(Player);
var plugin = new RynthAiPlugin();
PacerEdgeTests.SetHost(plugin, host);
CombatHook.LastUseDone = () => (1, 0u);
plugin.Shutdown();
Check.Null(CombatHook.LastUseDone, "and so does the plugin's own Shutdown");
});
private static void DeclineGoesNative() => Guard(() =>
{
var rig = new AttackRig();

View file

@ -7,6 +7,7 @@ using System.Runtime.CompilerServices;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
@ -41,6 +42,9 @@ internal static class CorpseCloseTests
r.Add("corpse close: the next corpse is opened without closing the finished one; its late close doesn't disturb the new open", NextCorpseWithoutClose);
r.Add("corpse close: a held-back close is sent when no other corpse is opened in time, and when the macro stops", DeferredCloseFallback);
r.Add("loot pickup: a pickup that merges into a pack stack is confirmed when the stack grows, not after 4 s", StackMergeConfirmed);
r.Add("loot timeout: a pickup held for a cast's answer does not time the corpse out; the pickup goes on the answer", HeldPickupKeepsCorpseClock);
r.Add("loot timeout: an unheld stall (nothing to take, nothing held) still times the corpse out", UnheldStallStillTimesOut);
r.Add("corpse close: the close is held back only when the next corpse can be claimed now (not while buffing), and a hold that starts later ends the wait", DeferredCloseNeedsClaimableCorpse);
}
private static long _now;
@ -54,6 +58,21 @@ internal static class CorpseCloseTests
finally { RynthAiPlugin.CorpseClock = old; }
}
/// <summary>The pacer (and the audits whose stop / use times it reads) on the same hand-moved clock as the loot.</summary>
private static void PacerOn()
{
ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => _now;
MoveAudit.Reset(); MoveAudit.NowMs = () => _now;
UseAudit.NowMs = () => _now;
}
private static void PacerOff()
{
ActionPacer.Enabled = false; ActionPacer.Reset(); ActionPacer.NowMs = () => Environment.TickCount64;
MoveAudit.Reset(); MoveAudit.NowMs = () => Environment.TickCount64;
UseAudit.NowMs = () => Environment.TickCount64;
}
private static void Corpse(uint id, float dx)
{
FakeHost.Names[id] = "Corpse of Olthoi Swarm Drone";
@ -227,6 +246,101 @@ internal static class CorpseCloseTests
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{CorpseA:X8}", "the last corpse is closed at once");
});
// A pickup is refused (ACE: YoureTooBusy) while the server owes an answer to a cast, so it waits
// (ActionPacer.Outstanding). The corpse's own clock (LootCorpseTimeoutMs) used to keep running
// through that wait, and the first tick after the answer abandoned an OPENED corpse, which gets
// the 30-minute completed mark: its loot was skipped.
private static void HeldPickupKeepsCorpseClock() => Clocked(() =>
{
World(twoCorpses: false);
FakeHost.ServerGates = true; // GetUseDoneSeq, GetCastBusyState
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.LootCorpseTimeoutMs = 2000;
PacerOn();
try
{
bot.Create(CorpseA, GemA);
bot.Tick();
Check.True(FakeHost.Uses.Contains(CorpseA), "corpse A is opened");
FakeHost.UseDone(0);
FakeHost.GroundContainer = CorpseA;
bot.P.OnViewObjectContents(CorpseA);
// A cast goes out and has no answer yet when the contents arrive: the pickup waits for it,
// two and a half corpse timeouts, still inside the pacer's own limit (CastMaxMs, 7 s).
ActionPacer.Begin(host, PacedKind.Cast, 0, "Bloodstone Bolt VII", "Combat", FakeHost.UseDoneSeq);
bot.TickFor(5_000);
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == GemA), "no pickup while the cast is unanswered");
Check.True(Logged("pickup waits - the server still owes an answer"), "the hold is logged");
Check.False(Logged("abandoning corpse"), "the corpse is not abandoned while the pickup is held");
Check.Eq(bot.Get<int>("_openedContainerId"), unchecked((int)CorpseA), "and stays the open corpse");
FakeHost.UseDone(0); // the cast is answered
for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == GemA); i++) { _now += 20; bot.Tick(); }
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == GemA), "the pickup goes on the answer");
FakeHost.Containers[GemA] = Player;
for (int i = 0; i < 200 && !bot.Completed(CorpseA); i++) { _now += 20; bot.Tick(); }
Check.True(bot.Completed(CorpseA), "and the corpse is completed by its loot, not by the timeout");
Check.False(Logged("abandoning corpse"), "never abandoned");
}
finally { PacerOff(); }
});
private static void UnheldStallStillTimesOut() => Clocked(() =>
{
World(twoCorpses: false);
FakeHost.ServerGates = true;
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.LootCorpseTimeoutMs = 2000;
bot.S.LootEmptyCorpseMs = 60_000; // the corpse neither shows items nor is called empty: a stall
PacerOn();
try
{
bot.Create(CorpseA); // the gem is never seen
bot.Tick();
Check.True(FakeHost.Uses.Contains(CorpseA), "corpse A is opened");
FakeHost.UseDone(0);
FakeHost.GroundContainer = CorpseA;
bot.P.OnViewObjectContents(CorpseA);
bot.TickFor(1_500);
Check.False(Logged("abandoning corpse"), "inside the timeout");
bot.TickFor(1_000);
Check.True(Logged("abandoning corpse") && Logged("(timeout)"), "an unheld stall is still abandoned on the timeout");
}
finally { PacerOff(); }
});
private static void DeferredCloseNeedsClaimableCorpse() => Clocked(() =>
{
// The next-corpse test itself: B is in range and A is done. Buffing holds every claim, so
// there is nothing to wait for.
World(twoCorpses: true);
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(CorpseA, CorpseB, GemA, GemB);
bot.Get<Dictionary<int, long>>("_completedCorpses")[unchecked((int)CorpseA)] = _now;
bool Other() => (bool)typeof(RynthAiPlugin).GetMethod("OtherCorpseToLoot", Any)!.Invoke(bot.P, new object[] { unchecked((int)CorpseA) })!;
Check.True(Other(), "B is in range and claimable: the close is worth deferring");
bot.S.BotAction = "Buffing";
Check.False(Other(), "buffing holds every claim: no deferral");
bot.S.BotAction = "Default";
Check.True(Other(), "and it is back once the hold ends");
// A hold that starts while the close is deferred ends the wait at once (not after 3 s).
World(twoCorpses: true);
var host2 = FakeHost.Create(Player);
var bot2 = new Bot(host2);
bot2.Create(CorpseA, CorpseB, GemA, GemB);
LootCorpseA(bot2);
Check.Eq(FakeHost.Closes.Count, 0, "held back while B can be claimed");
bot2.S.BotAction = "Buffing";
_now += 20; bot2.Tick(BotActivity.Looting);
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{CorpseA:X8}", "buffing began: A is closed at once, once");
Check.True(Logged("the next corpse can't be claimed now"), "and the reason is logged");
});
private static void StackMergeConfirmed() => Clocked(() =>
{
World(twoCorpses: false);

View file

@ -0,0 +1,514 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Environment-impact throttle and per-monster attack power (2026-10-12). Arrows into a wall
// ("Your missile attack hit the environment.") or war bolts stopping short of the target count
// against that target; at the limit within the window, combat stops attacking it and moves closer,
// switches target (this one skipped for a while), or moves closer once and then switches, as chosen
// separately for missile and magic combat. The only monster in reach is never skipped. A monster
// rule's Power picks High / Reckless / Variable / Reckless + Variable per monster.
internal static class EnvironmentImpactTests
{
private const uint Player = 0x50000F01;
private const uint Lb = 0xA9B40000;
private const uint A = 0x80000401, B = 0x80000402, Bolt = 0x80000499;
public static void Register(Runner r)
{
r.Add("env impact: the response decision (move closer, new target, closer then new, the only monster)", Decide);
r.Add("env impact: hits count per target inside the window; approaches are remembered", Throttle);
r.Add("env impact: a projectile is short only when it stopped away from the target and nearer the caster", Judge);
r.Add("env impact: missile lines trip New target: the attack stops, the target is skipped, the next is picked", MissileNewTarget);
r.Add("env impact: Move closer runs toward the target and stops at the goal; the only monster is never skipped", MissileApproach);
r.Add("env impact: Off, or not in Missile mode: the line is ignored", MissileOff);
r.Add("env impact: a player's copy of the missile line (their chat type, or their name in front) is not a hit", MissileSpoof);
r.Add("env impact: a bolt stopping short with no hit counts; one with a hit line, or reaching the target, doesn't", MagicShort);
r.Add("env impact: an approach Think stops driving lets go of autorun", ApproachOrphan);
r.Add("env impact (flight 63260): 3 magic casts landing nothing -> one short real sidestep; a hit resets; 30 s apart", ResyncSidestep);
r.Add("env impact: the throttle switching target restarts the re-sync's miss count", ResyncCountResetByThrottle);
r.Add("env impact: moving closer drops a wanted re-sync sidestep", ResyncDroppedByApproach);
r.Add("env impact: a re-sync sidestep holding its key finishes before the throttle runs", ResyncStepFinishesFirst);
r.Add("env impact: a re-sync sidestep Think stops driving, or a macro stop, lets go of the key", ResyncKeyReleased);
r.Add("attack power: Default/High/Reckless/Variable/Reckless + Variable, the DEFAULT line, untrained Recklessness", Power);
r.Add("attack power: an engine without the Power column keeps each rule's power", PowerCarriedOver);
}
// ── Pure rules ───────────────────────────────────────────────────────────
private static void Decide()
{
var M = EnvironmentResponse.MoveCloser; var N = EnvironmentResponse.NewTarget; var C = EnvironmentResponse.CloserThenNewTarget;
EnvironmentAction D(EnvironmentResponse r, int done, double dist, bool alt) => EnvironmentImpactPlanner.Decide(r, done, dist, 3, alt);
Check.Eq(D(EnvironmentResponse.Off, 0, 20, true), EnvironmentAction.None, "Off: nothing");
Check.Eq(D(M, 0, 20, true), EnvironmentAction.Approach, "Move closer, far: approach");
Check.Eq(D(M, 3, 20, false), EnvironmentAction.Approach, "Move closer approaches every time it trips");
Check.Eq(D(M, 0, 3.2, true), EnvironmentAction.NewTarget, "Move closer, already at the closest: new target");
Check.Eq(D(M, 0, 3.2, false), EnvironmentAction.None, "... but not the only monster: keep attacking");
Check.Eq(D(N, 0, 20, true), EnvironmentAction.NewTarget, "New target with another in reach: switch");
Check.Eq(D(N, 0, 20, false), EnvironmentAction.Approach, "New target, nothing else: approach instead of idling");
Check.Eq(D(N, 0, 2, false), EnvironmentAction.None, "New target, nothing else, already close: keep attacking");
Check.Eq(D(C, 0, 20, true), EnvironmentAction.Approach, "Closer then new: the first trip approaches");
Check.Eq(D(C, 1, 14, true), EnvironmentAction.NewTarget, "... the second switches");
Check.Eq(D(C, 1, 14, false), EnvironmentAction.Approach, "... unless it's the only monster");
Check.Eq(D(M, 0, double.NaN, true), EnvironmentAction.NewTarget, "unknown distance: no approach");
Check.Near(EnvironmentImpactPlanner.ApproachGoal(20, 6, 3), 14, 1e-9, "goal: 6 m nearer");
Check.Near(EnvironmentImpactPlanner.ApproachGoal(7, 6, 3), 3, 1e-9, "goal: never inside the closest distance");
Check.Eq(EnvironmentImpactPlanner.Parse(9), EnvironmentResponse.Off, "an out-of-range saved value is Off");
Check.Eq(EnvironmentImpactPlanner.Name(3), "Move closer, then new target", "labels follow the enum");
}
private static void Throttle()
{
var t = new EnvironmentImpactThrottle();
var t0 = new DateTime(2026, 10, 12, 12, 0, 0);
Check.Eq(t.Record(1, t0, 20), 1, "first hit");
Check.Eq(t.Record(2, t0, 20), 1, "per target");
Check.Eq(t.Record(1, t0.AddSeconds(5), 20), 2, "second hit inside the window");
Check.Eq(t.Count(1, t0.AddSeconds(21), 20), 1, "the first hit ages out");
Check.Eq(t.Count(1, t0.AddSeconds(30), 20), 0, "both aged out");
t.Record(1, t0.AddSeconds(31), 20);
t.ResetHits(1);
Check.Eq(t.Count(1, t0.AddSeconds(31), 20), 0, "reset after acting");
t.NoteApproach(1);
Check.Eq(t.Approaches(1), 1, "approach remembered");
t.Forget(1);
Check.Eq(t.Approaches(1), 0, "a deleted id forgets everything");
Check.Eq(t.Record(0, t0, 20), 0, "no target: not counted");
}
private static void Judge()
{
Check.True(ProjectileImpactJudge.StoppedShort(impactToTarget: 10, casterToImpact: 10, casterToTarget: 20), "into a wall halfway");
Check.False(ProjectileImpactJudge.StoppedShort(1.5, 18.5, 20), "at the target's surface");
Check.False(ProjectileImpactJudge.StoppedShort(3.5, 17, 20), "a big monster's surface (within 4 m)");
Check.False(ProjectileImpactJudge.StoppedShort(6, 21, 20), "past the target (a miss beyond, not a wall in front)");
Check.False(ProjectileImpactJudge.StoppedShort(double.NaN, 10, 20), "unknown: never short");
}
// ── Through CombatManager ────────────────────────────────────────────────
private sealed class Rig
{
public readonly LegacyUiSettings S;
public readonly CombatManager C;
public readonly WorldObjectCache Cache;
public DateTime Now = new(2026, 10, 12, 12, 0, 0);
/// <summary>The player at (96, 96) facing north; <paramref name="mobs"/> placed after the reset.</summary>
public Rig(int mode, Action<LegacyUiSettings> set, params (uint Id, string Name, float X, float Y)[] mobs)
: this(mode, set, setMotion: false, mobs) { }
/// <summary>As above; <paramref name="setMotion"/> installs SetMotion (the re-sync sidestep needs it).</summary>
public Rig(int mode, Action<LegacyUiSettings> set, bool setMotion, params (uint Id, string Name, float X, float Y)[] mobs)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.SetMotionCalls = setMotion;
FakeHost.CombatModeValue = mode;
Place(Player, "Me", 96, 96, creature: false);
foreach (var m in mobs) Place(m.Id, m.Name, m.X, m.Y);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.HeadingDeg = 0;
S = new LegacyUiSettings { MonsterRange = 50, IsMacroRunning = true, EnableCombat = true };
set(S);
var host = FakeHost.Create(Player); // Think measures distances from GetPlayerId
Cache = FakeHost.MakeCache(host, Player, mobs.Select(m => m.Id));
C = new CombatManager(host, S, Cache);
C.SetPlayerId(Player);
C.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
C.EnvClock = () => Now;
C.ScanNearbyTargets();
C.HandleCombatTrigger();
FakeHost.MotionCalls.Clear(); // the trigger's turn-motion clear-out isn't under test
}
public double Dist(uint id)
{
var p = FakeHost.Positions[id];
double dx = p.X - FakeHost.PlayerPose.X, dy = p.Y - FakeHost.PlayerPose.Y;
return Math.Sqrt(dx * dx + dy * dy);
}
public bool Run() => C.RunEnvironmentImpact(Cache[C.activeTargetId]!, Dist((uint)C.activeTargetId));
public void MovePlayer(float x, float y)
{
FakeHost.PlayerPose = (Lb | 0x1C, x, y, 0f);
FakeHost.Positions[Player] = FakeHost.PlayerPose;
}
}
private const string MissileLine = "Your missile attack hit the environment.";
// 20 m north of the player (the pick), and 24 m east.
private static readonly (uint, string, float, float) Skulker = (A, "Drudge Skulker", 96f, 116f);
private static readonly (uint, string, float, float) Slinker = (B, "Drudge Slinker", 120f, 96f);
private static void MissileNewTarget()
{
var r = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 2; s.EnvironmentImpactLimit = 2; s.EnvironmentSkipSec = 30; }, Skulker, Slinker);
Check.Eq((uint)r.C.activeTargetId, A, "the nearer Skulker is locked");
r.C.HandleChatForDamage(MissileLine);
Check.False(r.Run(), "one hit: attacking on");
r.Now = r.Now.AddSeconds(3);
r.C.HandleChatForDamage(MissileLine);
Check.True(FakeHost.Logs.Any(l => l.Contains("[EnvImpact] missile") && l.Contains("2/2")), "both hits logged against the target");
Check.True(r.Run(), "the limit: this tick belongs to the response");
Check.Eq(r.C.activeTargetId, 0, "the Skulker is dropped");
Check.True(FakeHost.Logs.Any(l => l.Contains("leaving") && l.Contains("skipping it 30s")), "logged with the skip");
Rescan(r);
Check.False(r.C.ScannedTargets.Any(t => (uint)t.Id == A), "the skipped Skulker is out of the scan");
r.C.HandleCombatTrigger();
Check.Eq((uint)r.C.activeTargetId, B, "the Slinker is fought next");
r.Now = r.Now.AddSeconds(31);
Rescan(r);
Check.True(r.C.ScannedTargets.Any(t => (uint)t.Id == A), "after the skip the Skulker is back");
}
/// <summary>The scan runs at most every 50 ms of real time (SCAN_INTERVAL_MS).</summary>
private static void Rescan(Rig r)
{
System.Threading.Thread.Sleep(60);
r.C.ScanNearbyTargets();
}
private static void MissileApproach()
{
// The Skulker is the only monster.
var r = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 2; s.EnvironmentImpactLimit = 2; s.EnvironmentApproachMeters = 6; s.EnvironmentMinDistance = 3; }, Skulker);
r.C.HandleChatForDamage(MissileLine);
r.C.HandleChatForDamage(MissileLine);
Check.True(r.Run(), "New target with nothing else in reach: moves closer instead");
Check.Eq((uint)r.C.activeTargetId, A, "the only monster is kept");
Check.True(FakeHost.AutoRun, "running toward it");
Check.True(r.C.EnvironmentApproachActive, "approach under way");
Check.True(FakeHost.Logs.Any(l => l.Contains("moving closer") && l.Contains("stopping at 14.0m")), "goal: 6 m nearer");
r.Now = r.Now.AddMilliseconds(500);
r.MovePlayer(96, 99); // 17 m
Check.True(r.Run(), "still short of the goal: no attack");
r.Now = r.Now.AddMilliseconds(500);
r.MovePlayer(96, 102.5f); // 13.5 m
Check.False(r.Run(), "reached: attacking again this tick");
Check.False(FakeHost.AutoRun, "autorun off");
Check.False(r.C.EnvironmentApproachActive, "approach over");
// Two more hits: already approached once, still far enough: Move closer goes again.
r.S.MissileEnvironmentResponse = 1;
r.C.HandleChatForDamage(MissileLine);
r.C.HandleChatForDamage(MissileLine);
Check.True(r.Run(), "Move closer trips again");
Check.True(FakeHost.AutoRun, "running again");
// Blocked: no ground gained for 2.5 s.
r.Now = r.Now.AddSeconds(3);
Check.False(r.Run(), "no progress: the approach gives up and combat attacks");
Check.False(FakeHost.AutoRun, "autorun off when blocked");
Check.True(FakeHost.Logs.Any(l => l.Contains("ended: no progress")), "logged as blocked");
// At the closest distance with nothing else: keep attacking.
r.MovePlayer(96, 113.2f); // 2.8 m
r.C.HandleChatForDamage(MissileLine);
r.C.HandleChatForDamage(MissileLine);
Check.False(r.Run(), "already close and the only monster: attacking on");
Check.Eq((uint)r.C.activeTargetId, A, "not dropped");
}
private static void MissileOff()
{
var off = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 0; s.EnvironmentImpactLimit = 1; }, Skulker);
off.C.HandleChatForDamage(MissileLine);
Check.False(off.Run(), "Off: nothing happens");
Check.False(FakeHost.Logs.Any(l => l.Contains("[EnvImpact]")), "Off: not even counted");
var melee = new Rig(CombatMode.Melee, s => { s.MissileEnvironmentResponse = 2; s.EnvironmentImpactLimit = 1; }, Skulker);
melee.C.HandleChatForDamage(MissileLine);
Check.False(melee.Run(), "not in Missile mode: ignored");
}
private static void MissileSpoof()
{
var r = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 2; s.EnvironmentImpactLimit = 1; }, Skulker);
r.C.HandleChatForDamage("Bob says, \"" + MissileLine + "\"", 2);
r.C.HandleChatForDamage(MissileLine, 3); // a tell, whatever its text
r.C.HandleChatForDamage("Bob " + MissileLine, 12); // an emote
r.C.HandleChatForDamage("[Allegiance] Bob says, \"" + MissileLine + "\""); // type unknown: the anchor
Check.False(r.Run(), "no spoofed line counts");
Check.False(FakeHost.Logs.Any(l => l.Contains("[EnvImpact]")), "nothing recorded");
r.C.HandleChatForDamage(MissileLine, 0); // ACE's own line is a Broadcast
Check.True(r.Run(), "the server's line still trips the limit");
}
private static void MagicShort()
{
var r = new Rig(CombatMode.Magic, s => { s.MagicEnvironmentResponse = 2; s.EnvironmentImpactLimit = 2; }, Skulker, Slinker);
Check.Eq((uint)r.C.activeTargetId, A, "the Skulker is locked");
void Cast(float stopY, bool hitLine = false) => CastBolt(r, stopY, hitLine);
Cast(105);
Check.True(FakeHost.Logs.Any(l => l.Contains("[EnvImpact] magic") && l.Contains("1/2")), "a bolt stopping 9 m out, no hit: one environment hit");
Cast(115);
Check.False(FakeHost.Logs.Any(l => l.Contains("[EnvImpact] magic") && l.Contains("2/2")), "a bolt reaching the target: not counted");
Cast(105, hitLine: true);
Check.False(FakeHost.Logs.Any(l => l.Contains("[EnvImpact] magic") && l.Contains("2/2")), "a hit line for the cast: not counted");
Cast(105);
Check.True(FakeHost.Logs.Any(l => l.Contains("[EnvImpact] magic") && l.Contains("2/2")), "a second short bolt: the limit");
Check.True(r.Run(), "the response runs");
Check.Eq(r.C.activeTargetId, 0, "the Skulker is left for the Slinker");
// Rings and other casters' projectiles aren't ours to judge.
Check.False(CombatManager.IsWatchedProjectileName("Flame Ring"), "a ring isn't watched");
Check.True(CombatManager.IsWatchedProjectileName("Nether Bolt"), "void bolts are");
Check.False(CombatManager.IsWatchedProjectileName("Drudge Skulker"), "a monster isn't");
}
private static void ApproachOrphan()
{
var r = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 1; s.EnvironmentImpactLimit = 1; }, Skulker);
r.C.HandleChatForDamage(MissileLine);
Check.True(r.Run(), "approach starts");
Check.True(FakeHost.AutoRun, "running");
r.Now = r.Now.AddSeconds(2); // Think stopped calling (buffing took over)
r.C.PollEnvironmentImpact();
Check.False(FakeHost.AutoRun, "the heartbeat lets go of autorun");
Check.False(r.C.EnvironmentApproachActive, "approach over");
r.C.HandleChatForDamage(MissileLine);
Check.True(r.Run(), "a new approach");
r.C.OnHeartbeat(); // a heartbeat sees the macro running
Check.True(FakeHost.AutoRun, "still running while Think drives it");
r.S.IsMacroRunning = false;
r.C.OnHeartbeat();
Check.False(FakeHost.AutoRun, "a macro stop ends it too");
}
// ── Attack power ─────────────────────────────────────────────────────────
private static void Power()
{
float R(string mode, int global = -1, bool reck = false, bool trained = true, int min = 50, int max = 100, double rnd = 0.5)
=> AttackPowerModes.Resolve(mode, global, reck, trained, min, max, () => rnd);
Check.Near(R("Default"), 1.0, 1e-6, "Default, Auto, no Recklessness: 100%");
Check.Near(R("Default", reck: true), 0.8, 1e-6, "Default, Auto + Use Recklessness, trained: 80%");
Check.Near(R("Default", reck: true, trained: false), 1.0, 1e-6, "... untrained: 100%");
Check.Near(R("Default", global: 65), 0.65, 1e-6, "Default, a set power: that power");
Check.Near(R("High", global: 40), 1.0, 1e-6, "High: 100% whatever the global");
Check.Near(R("Reckless"), 0.8, 1e-6, "Reckless: 80%");
Check.Near(R("Reckless", trained: false), 1.0, 1e-6, "Reckless untrained: High");
Check.Near(R("Variable", rnd: 0), 0.5, 1e-6, "Variable: the min");
Check.Near(R("Variable", rnd: 0.999), 1.0, 1e-6, "Variable: up to the max");
Check.Near(R("Variable", min: 90, max: 30, rnd: 0), 0.3, 1e-6, "Variable: a reversed range is put in order");
Check.Near(R("Reckless + Variable", rnd: 0), 0.5, 1e-6, "Reckless + Variable: the Variable min (inside the band)");
Check.Near(R("Reckless + Variable", rnd: 0.999), 0.8, 1e-6, "... capped at the band's 80%");
Check.Near(R("Reckless + Variable", min: 85, max: 100, rnd: 0), 0.2, 1e-6, "no overlap with the band: the whole band");
Check.Near(R("Reckless + Variable", trained: false, rnd: 0.999), 1.0, 1e-6, "untrained: plain Variable");
var seen = new HashSet<float>();
foreach (double d in new[] { 0.1, 0.4, 0.7 }) seen.Add(R("Variable", rnd: d));
Check.Eq(seen.Count, 3, "Variable changes with each draw");
Check.Eq(AttackPowerModes.Normalize("reckless+variable"), AttackPowerModes.RecklessVariable, "hand-typed spelling");
Check.Eq(AttackPowerModes.Normalize(null), AttackPowerModes.Default, "missing: Default");
Check.Eq(AttackPowerModes.Normalize("Huge"), AttackPowerModes.Default, "unknown: Default");
var def = new MonsterRule { Name = "Default", AttackPower = "Reckless" };
Check.Eq(AttackPowerModes.Effective(new MonsterRule { Name = "Drudge" }, def), "Reckless", "a Default rule follows the DEFAULT line");
Check.Eq(AttackPowerModes.Effective(new MonsterRule { Name = "Drudge", AttackPower = "High" }, def), "High", "its own choice wins");
Check.Eq(AttackPowerModes.Effective(null, null), "Default", "no rules: the global settings");
Check.Eq(new MonsterRule().AttackPower, "Default", "a new rule (and an old file) is Default");
// Pull-away kite (2026-10-16): Default → DEFAULT row → Off on that row.
Check.Eq(KiteModes.Normalize("pull away"), KiteModes.PullAway, "hand-typed PullAway");
Check.Eq(KiteModes.Normalize(null), KiteModes.Default, "missing kite: Default");
var kiteDef = new MonsterRule { Name = "Default", Kite = KiteModes.PullAway };
Check.Eq(KiteModes.Effective(new MonsterRule { Name = "Drudge" }, kiteDef), KiteModes.PullAway, "a Default rule follows the DEFAULT kite");
Check.Eq(KiteModes.Effective(new MonsterRule { Name = "Drudge", Kite = KiteModes.Off }, kiteDef), KiteModes.Off, "its own kite wins");
Check.Eq(KiteModes.Effective(kiteDef, kiteDef), KiteModes.PullAway, "DEFAULT row PullAway is PullAway");
Check.Eq(KiteModes.Effective(new MonsterRule { Name = "Default" }, new MonsterRule { Name = "Default" }), KiteModes.Off, "DEFAULT Default means Off");
Check.True(KiteModes.WantsPullAway(new MonsterRule { Name = "X" }, kiteDef), "WantsPullAway follows DEFAULT");
Check.Eq(new MonsterRule().Kite, "Default", "a new rule (and an old file) is Default kite");
}
private static void PowerCarriedOver()
{
var current = new List<MonsterRule>
{
new() { Name = "Default", AttackPower = "High" },
new() { Name = "Drudge", AttackPower = "Variable" },
new() { Name = "Drudge", MatchExpression = "x", AttackPower = "Reckless" },
};
var incoming = new List<MonsterRule>
{
new() { Name = "Default" }, new() { Name = "drudge" }, new() { Name = "Drudge", MatchExpression = "x" }, new() { Name = "Mosswart" },
};
LegacyDashboardRenderer.CarryAttackPower(current, incoming);
Check.Eq(incoming[0].AttackPower, "High", "Default keeps its power");
Check.Eq(incoming[1].AttackPower, "Variable", "matched by name, any case");
Check.Eq(incoming[2].AttackPower, "Reckless", "and by expression");
Check.Eq(incoming[3].AttackPower, "Default", "a new rule stays Default");
}
// ── Magic position re-sync (upstream 2026.10.12.1) and the throttle ──────
private const uint StepRight = 0x6500000F, StepLeft = 0x65000010;
/// <summary>Upstream's CastNoDamageTests.ResyncSidestep, on this file's rig.</summary>
private static void ResyncSidestep()
{
var r = new Rig(CombatMode.Magic, s => { }, setMotion: true, Skulker, Slinker);
var c = r.C;
c.TargetClock = () => r.Now;
MoveAudit.Reset();
c.MagicMissForTest(unchecked((int)A));
c.MagicMissForTest(unchecked((int)B)); // a swap to the other monster doesn't reset the count
Check.False(c.ResyncActive, "two misses: nothing yet");
c.ReportDamageOnTarget(unchecked((int)A));
c.MagicMissForTest(unchecked((int)A));
c.MagicMissForTest(unchecked((int)A));
Check.False(c.ResyncActive, "a hit reset the count");
c.MagicMissForTest(unchecked((int)A));
Check.True(c.ResyncActive, "three in a row: a re-sync is wanted");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("one short sidestep to re-sync")), 1, "said once");
Check.True(c.TickResyncStep(), "first tick: the step starts, no cast");
Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (StepRight, true) }), "sidestep right key down");
r.Now = r.Now.AddMilliseconds(200);
Check.True(c.TickResyncStep(), "still stepping at 200 ms");
r.Now = r.Now.AddMilliseconds(100);
Check.True(c.TickResyncStep(), "300 ms: key up, settling");
Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (StepRight, true), (StepRight, false) }), "key up");
r.Now = r.Now.AddMilliseconds(400);
Check.False(c.TickResyncStep(), "settled: casting may go on");
Check.Eq(c.ResyncSteps, 1, "one step");
for (int i = 0; i < 3; i++) c.MagicMissForTest(unchecked((int)A));
Check.False(c.ResyncActive, "within 30 s: no second step");
r.Now = r.Now.AddSeconds(30);
for (int i = 0; i < 3; i++) c.MagicMissForTest(unchecked((int)A));
Check.True(c.ResyncActive, "30 s later: another one");
c.TickResyncStep();
Check.True(FakeHost.MotionCalls[2] == (StepLeft, true), "the other side this time");
}
private static void ResyncCountResetByThrottle()
{
var r = new Rig(CombatMode.Magic, s => { s.MagicEnvironmentResponse = 2; s.EnvironmentImpactLimit = 2; }, setMotion: true, Skulker, Slinker);
r.C.TargetClock = () => r.Now;
r.C.MagicMissForTest(unchecked((int)A));
r.C.MagicMissForTest(unchecked((int)A));
CastBolt(r, 105);
CastBolt(r, 105);
Check.True(r.Run(), "two short bolts: the throttle switches target");
Check.Eq(r.C.activeTargetId, 0, "the Skulker is left");
r.C.MagicMissForTest(unchecked((int)B));
r.C.MagicMissForTest(unchecked((int)B));
Check.False(r.C.ResyncActive, "the misses the wall explained no longer count toward a sidestep");
r.C.MagicMissForTest(unchecked((int)B));
Check.True(r.C.ResyncActive, "three fresh misses on the new target still ask for one");
}
private static void ResyncDroppedByApproach()
{
var r = new Rig(CombatMode.Magic, s => { s.MagicEnvironmentResponse = 1; s.EnvironmentImpactLimit = 1; }, setMotion: true, Skulker);
r.C.TargetClock = () => r.Now;
for (int i = 0; i < 3; i++) r.C.MagicMissForTest(unchecked((int)A));
Check.True(r.C.ResyncActive, "a sidestep is wanted");
CastBolt(r, 105);
Check.True(r.Run(), "the throttle moves closer");
Check.True(FakeHost.AutoRun, "running toward the Skulker");
Check.False(r.C.ResyncActive, "the wanted sidestep is dropped: the run moves us anyway");
Check.True(FakeHost.Logs.Any(l => l.Contains("re-sync sidestep dropped: moving closer")), "logged");
Check.Eq(FakeHost.MotionCalls.Count, 0, "no sidestep key was sent");
}
private static void ResyncStepFinishesFirst()
{
var r = new Rig(CombatMode.Magic, s => { s.MagicEnvironmentResponse = 1; s.EnvironmentImpactLimit = 1; }, setMotion: true, Skulker);
r.C.TargetClock = () => r.Now;
for (int i = 0; i < 3; i++) r.C.MagicMissForTest(unchecked((int)A));
CastBolt(r, 105); // the throttle trips (its response waits for Think)
Check.True(r.C.TickResyncStep(), "the sidestep key goes down");
Check.True(r.Run(), "the throttle's tick: no attack");
Check.False(r.C.EnvironmentApproachActive, "but no run while the sidestep key is held");
Check.False(FakeHost.AutoRun, "autorun not sent");
r.Now = r.Now.AddMilliseconds(300);
Check.True(r.C.TickResyncStep(), "the sidestep key comes up");
Check.True(r.Run(), "now the approach runs");
Check.True(r.C.EnvironmentApproachActive, "approach under way");
Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (StepRight, true), (StepRight, false) }), "the key went up before the run");
}
private static void ResyncKeyReleased()
{
var r = new Rig(CombatMode.Magic, s => { }, setMotion: true, Skulker);
r.C.TargetClock = () => r.Now;
for (int i = 0; i < 3; i++) r.C.MagicMissForTest(unchecked((int)A));
r.C.TickResyncStep();
Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (StepRight, true) }), "key down");
r.Now = r.Now.AddSeconds(2); // Think stopped ticking it (left magic mode)
r.C.PollEnvironmentImpact();
Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (StepRight, true), (StepRight, false) }), "the heartbeat lets go of the key");
Check.False(r.C.ResyncActive, "the sidestep is over");
Check.True(FakeHost.Logs.Any(l => l.Contains("re-sync sidestep stopped: combat stopped driving it")), "logged");
r.C.OnHeartbeat(); // a heartbeat sees the macro running
r.C.MagicMissForTest(unchecked((int)A));
int before = FakeHost.MotionCalls.Count;
r.C.TickResyncStep();
Check.True(FakeHost.MotionCalls.Count == before + 1 && FakeHost.MotionCalls[^1] == (StepLeft, true), "a new sidestep, key down");
r.S.IsMacroRunning = false;
r.C.OnHeartbeat();
Check.True(FakeHost.MotionCalls[^1] == (StepLeft, false), "a macro stop lets go of it too");
Check.False(r.C.ResyncActive, "and ends it");
}
// ── Helpers ──────────────────────────────────────────────────────────────
/// <summary>One cast at the active target whose bolt flies from the caster north to <paramref name="stopY"/> and stops.</summary>
private static void CastBolt(Rig r, float stopY, bool hitLine = false)
{
r.C.RegisterCastWatch(r.C.activeTargetId, "Flame Bolt VI");
r.Now = r.Now.AddMilliseconds(800); // the windup
FakeHost.Names[Bolt] = "Flame Bolt";
FakeHost.Positions[Bolt] = (Lb | 0x1C, 96f, 97f, 0f); // spawns at the caster
r.C.OnEnvironmentObjectCreated(Bolt);
r.C.PollEnvironmentImpact();
for (float y = 99; y <= stopY; y += 2)
{
r.Now = r.Now.AddMilliseconds(100);
FakeHost.Positions[Bolt] = (Lb | 0x1C, 96f, y, 0f);
r.C.PollEnvironmentImpact();
}
if (hitLine) r.C.HandleChatForDamage("You singe Drudge Skulker for 40 points of fire damage!");
for (int i = 0; i < 15; i++) { r.Now = r.Now.AddMilliseconds(100); r.C.PollEnvironmentImpact(); }
r.C.OnObjectDeleted(Bolt);
FakeHost.Positions.Remove(Bolt);
}
private static void Place(uint id, string name, float x, float y, bool creature = true)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f);
if (creature) FakeHost.ItemTypes[id] = 0x10;
}
}

View file

@ -28,12 +28,36 @@ internal static class GiveTests
r.Add("give: /mt give hands over only the first match", MtGivesFirst);
r.Add("give: /ub givep matches part of the name", UbGivePartial);
r.Add("give: the next give waits until the server took the last (it answers extra gives 'too busy')", WaitsForServer);
r.Add("give: a whole stack to an NPC that takes one per give keeps giving until it is gone, one give per tick", NpcStackOneAtATime);
r.Add("give: the answer and the next give share one tick (the interval is only a minimum gap between sends)", NextGiveSameTick);
r.Add("give: busy refusals re-send with no cap", BusyResendsUncapped);
r.Add("give: a permanent refusal skips the stack at once and moves on", PermanentSkips);
r.Add("give: item not found after a re-send counts as given", ItemNotFoundAfterResendCounts);
r.Add("give: the summary counts items, not stacks", SummaryCountsItems);
r.Add("give: no answer at all re-sends once, then skips", NoAnswerSkips);
r.Add("give: an unreadable stack count is no information, not a shrink", UnreadableStackIsNotAShrink);
r.Add("give: an item unreadable for one tick is not gone; for two it is", OneTickUnreadableIsNotGone);
r.Add("give: speech lines never answer a give; item not found with the stack unchanged is a skip", SpeechIgnoredAndNotFoundNeedsGone);
r.Add("give: busy notice after 10 s, busy logging throttled, unclassified lines logged (max 10)", BusyNoticeAndLogThrottle);
r.Add("give: a counted give from one stack goes through the queue (NPC one per give, player split once)", CountedSingleStack);
r.Add("give: cancel in the middle of a busy wait stops everything", CancelMidBusy);
r.Add("give: an accept line does not shorten the two-tick rule for an unreadable item", AcceptLineDoesNotAbandon);
r.Add("give: a failed stack read on a stackable item sends nothing until it reads", FailedStackReadOnStackableWaits);
r.Add("give: a container we cannot place is unreadable, not gone", UnplaceableContainerIsUnreadable);
r.Add("give: a stack count that never reads holds the queue for 2 s, then the give goes out and the queue moves on", UnreadableStackFallsBackAfterTwoSeconds);
r.Add("give: an unreadable stack never turns a counted give into a whole-object give; only give-all goes out whole", UnreadableStackNeverGivesWholeForACount);
r.Add("give: a count-1 stackable whose count property is absent still gets through", CountOneStackableWithoutCountGetsThrough);
r.Add("give: /ub givea queues a give-all (0), so an unreadable count there sends the whole object", GiveAllQueuesWholeStack);
r.Add("give: a target that stays busy for a minute is skipped and counted", BusyGivesUpAfterAMinute);
r.Add("give: a no-answer re-send that could not go out still counts as a try", FailedResendCountsAsATry);
}
private sealed class World
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new() { GiveQueueIntervalMs = 0 };
/// <summary>The queue's fake millisecond clock.</summary>
public long Now;
public readonly WorldObjectCache Cache;
public World()
@ -67,6 +91,7 @@ internal static class GiveTests
Set("_playerId", Player);
Set("_initialized", true);
Set("_loginComplete", true);
Set("_giveClock", (Func<long>)(() => Now));
foreach (uint id in new[] { Npc, Mote1, Mote2, Mote3, WornMote, Other }) Cache.OnCreateObject(id);
Cache.Tick();
}
@ -82,6 +107,36 @@ internal static class GiveTests
for (int i = 0; i < 20; i++) Call("DrainGiveQueue");
}
/// <summary>Advances the clock, then runs one tick of the give queue.</summary>
public void Tick(long advanceMs = 0) { Now += advanceMs; Call("DrainGiveQueue"); }
public void Chat(string text, int chatType = 0) => Call("NoteGiveChat", text, chatType);
/// <summary>Adds a carried stack the cache knows about.</summary>
public void AddStack(uint id, string name, int count)
{
FakeHost.Names[id] = name;
FakeHost.Containers[id] = Player;
FakeHost.ItemTypes[id] = 0x80;
FakeHost.Ints[(id, 12)] = count; // StackCount
Cache.OnCreateObject(id);
Cache.Tick();
}
/// <summary>An NPC with a Give emote: each give takes ONE item from the stack (ACE: acceptAll ? amount : 1).</summary>
public void NpcTakesOnePerGive()
{
FakeHost.GiveHandler = (item, target, amount) =>
{
if (!FakeHost.Ints.TryGetValue((item, 12), out int n)) { FakeHost.Containers[item] = target; return; } // a single item goes whole
if (n <= 0) return;
FakeHost.Ints[(item, 12)] = n - 1;
if (n - 1 <= 0) FakeHost.Containers[item] = target;
};
}
public bool ChatHas(string part) => FakeHost.Chat.Any(c => c.Contains(part, StringComparison.Ordinal));
public uint[] GivenItems => FakeHost.Gives.Select(g => g.Item).ToArray();
}
@ -135,4 +190,490 @@ internal static class GiveTests
Check.Eq(FakeHost.Gives.Count, 3, "then the other two, each after the last landed");
Check.Eq(FakeHost.Gives.Select(g => g.Item).Distinct().Count(), 3, "no item sent twice");
}
private const uint Carapace = 0x80281301;
// 2026-10-12: Olthoi Carapace stack of 100 to a Collector NPC: the server takes ONE per give, the
// stack stays in the pack, and the queue used to wait 3 s, re-send once and skip.
private static void NpcStackOneAtATime()
{
var w = new World();
w.AddStack(Carapace, "Olthoi Slayer Carapace", 5);
w.NpcTakesOnePerGive();
w.Call("EnqueueGive", Carapace, Npc, 5);
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "the first give goes out");
for (int expected = 2; expected <= 5; expected++)
{
w.Tick(); // the stack shrank: the same item goes again, in this very tick
Check.Eq(FakeHost.Gives.Count, expected, $"give #{expected} sent on the tick that saw the shrink");
}
Check.True(FakeHost.Gives.All(g => g.Item == Carapace && g.Target == Npc), "always the same stack, to the NPC");
w.Tick();
Check.Eq(FakeHost.Gives.Count, 5, "the stack is gone: nothing more is sent");
Check.False(w.ChatHas("didn't take"), "never reported as not taken");
}
private static void NextGiveSameTick()
{
var w = new World();
w.S.GiveQueueIntervalMs = 150; // a saved old default: only a minimum gap between SENDS
w.Run("/ub give Mana Mote to Town Crier");
Check.Eq(FakeHost.Gives.Count, 1, "one give out, the server not yet heard from at t=0");
// The first landed at once in the fake. Less than the gap since the send: the next must wait.
w.Tick(100);
Check.Eq(FakeHost.Gives.Count, 1, "inside the minimum gap the next send waits");
// A round trip longer than the gap: answer observed and the next give leaves in the same tick.
w.Tick(60);
Check.Eq(FakeHost.Gives.Count, 2, "answer seen and the next give sent on one tick");
w.Tick(200);
Check.Eq(FakeHost.Gives.Count, 3, "and again for the third");
}
private static void BusyResendsUncapped()
{
var w = new World();
FakeHost.GiveLands = false;
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Tick();
for (int busy = 1; busy <= 6; busy++)
{
int before = FakeHost.Gives.Count;
w.Chat("You're too busy!");
w.Tick(100);
Check.Eq(FakeHost.Gives.Count, before, $"busy #{busy}: not re-sent before the short delay");
w.Tick(300);
Check.Eq(FakeHost.Gives.Count, before + 1, $"busy #{busy}: re-sent after it");
}
Check.False(w.ChatHas("didn't take"), "no cap: never skipped");
FakeHost.GiveLands = true;
FakeHost.Containers[Mote1] = Npc; // finally taken
w.Tick(100);
Check.True(w.ChatHas("1 item(s) given"), "then it lands and counts");
Check.Eq(FakeHost.Gives.Count, 7, "seven sends: the first plus six re-sends");
}
private static void PermanentSkips()
{
var w = new World();
FakeHost.GiveLands = false;
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Call("EnqueueGive", Mote2, Npc, 1);
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "first stack out");
w.Chat("Town Crier is not accepting gifts right now.");
w.Tick();
Check.Eq(FakeHost.Gives.Count, 2, "refused for good: the next stack is sent on that same tick");
Check.Eq(FakeHost.Gives[1].Item, Mote2, "the second stack, not a retry of the first");
FakeHost.Containers[Mote2] = Npc;
w.Tick();
Check.True(w.ChatHas("1 item(s) given, 1 stack(s) skipped"), "summary: one given, one skipped with its reason");
}
private static void ItemNotFoundAfterResendCounts()
{
var w = new World();
FakeHost.GiveLands = false;
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Tick();
w.Tick(3001); // no answer: sent once more
Check.Eq(FakeHost.Gives.Count, 2, "re-sent after the confirm time");
FakeHost.Containers[Mote1] = Npc; // the first send did land: the item is gone from the pack
w.Chat("Item not found!");
w.Tick();
Check.Eq(FakeHost.Gives.Count, 2, "no third send");
Check.True(w.ChatHas("1 item(s) given, 0 stack(s) skipped"), "the earlier send landed: counted as given, not skipped");
}
private static void SummaryCountsItems()
{
var w = new World();
w.AddStack(Carapace, "Olthoi Slayer Carapace", 5);
w.NpcTakesOnePerGive();
w.Call("EnqueueGive", Carapace, Npc, 5);
w.Call("EnqueueGive", Mote1, Npc, 1);
for (int i = 0; i < 12; i++) w.Tick(50);
Check.True(w.ChatHas("Give queue complete: 6 item(s) given, 0 stack(s) skipped"), "5 carapaces + 1 mote = 6 items from 2 stacks");
}
private static void NoAnswerSkips()
{
var w = new World();
FakeHost.GiveLands = false;
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Tick();
w.Tick(3001);
w.Tick(3001);
Check.Eq(FakeHost.Gives.Count, 2, "two tries, then it gives up");
Check.True(w.ChatHas("didn't take"), "and says so");
Check.True(w.ChatHas("1 stack(s) skipped"), "the summary counts it as skipped");
}
private static void UnreadableStackIsNotAShrink()
{
var w = new World();
FakeHost.GiveHandler = (_, _, _) => { }; // the server has not answered yet
w.AddStack(Carapace, "Olthoi Slayer Carapace", 5);
w.Call("EnqueueGive", Carapace, Npc, 5);
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "sent");
FakeHost.Ints.Remove((Carapace, 12)); // the engine read fails for a tick
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "a failed read is not a shrink of 4: no second give while the first is in flight");
FakeHost.Ints[(Carapace, 12)] = 5;
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "read again, unchanged: still waiting");
Check.False(w.ChatHas("item(s) given"), "nothing credited");
FakeHost.Ints[(Carapace, 12)] = 4; // now a real shrink
w.Tick();
Check.Eq(FakeHost.Gives.Count, 2, "a real shrink gives again");
}
private static void OneTickUnreadableIsNotGone()
{
var w = new World();
FakeHost.GiveHandler = (_, _, _) => { };
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Call("EnqueueGive", Mote2, Npc, 1);
w.Tick();
FakeHost.Containers[Mote1] = 0; // one unreadable tick
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "Container 0 for one tick is not gone");
FakeHost.Containers[Mote1] = Player;
w.Tick();
FakeHost.Containers[Mote1] = 0;
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "the streak restarted after a good read");
w.Tick();
Check.Eq(FakeHost.Gives.Count, 2, "unreadable on two ticks in a row: gone, the next stack goes");
}
private static void SpeechIgnoredAndNotFoundNeedsGone()
{
var w = new World();
FakeHost.GiveHandler = (_, _, _) => { };
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Call("EnqueueGive", Mote2, Npc, 1);
w.Tick();
w.Chat("<Tell:IIDString:1:Bob>Bob<\\Tell> says, \"Town Crier doesn't want that\"", 17);
w.Chat("Bob says, \"Town Crier doesn't want that\"", 0); // shape alone is enough
w.Chat("Bob tells you, \"not accepting gifts\"", 3);
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "other players' words are no answer: still in flight, nothing skipped");
Check.False(w.ChatHas("skipped"), "no summary yet");
w.Tick(3001); // re-sent
w.Chat("Item not found!");
w.Tick(); // the item is still carried, stack unchanged: a skip, not a delivery
Check.Eq(FakeHost.Gives.Count, 3, "item not found with the item still in the pack skips it; the next stack goes");
FakeHost.Containers[Mote2] = Npc;
w.Tick();
Check.True(w.ChatHas("1 item(s) given, 1 stack(s) skipped"), "one skipped as item not found, one given");
}
private static void BusyNoticeAndLogThrottle()
{
var w = new World();
FakeHost.GiveHandler = (_, _, _) => { };
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Tick();
w.Chat("You cast Inner Calm on yourself", 7); // magic lines never take a slot
for (int i = 0; i < 12; i++) w.Chat("Something odd " + i);
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Give] unclassified chat:")), 10, "at most 10 unclassified lines logged per give");
int busyCycles = 0;
long start = w.Now;
while (w.Now - start < 9000)
{
w.Chat("You're too busy!");
w.Tick(0);
w.Tick(300);
busyCycles++;
}
Check.False(w.ChatHas("still retrying"), "no notice before 10 s of busy waiting");
while (w.Now - start < 10700)
{
w.Chat("You're too busy!");
w.Tick(0);
w.Tick(300);
busyCycles++;
}
Check.Eq(FakeHost.Chat.Count(c => c.Contains("Town Crier is busy - still retrying (/ra givea stop to cancel).")), 1, "one notice at about 10 s");
int busyLogs = FakeHost.Logs.Count(l => l.Contains("Give answer: busy"));
Check.True(busyCycles >= 30 && busyLogs <= busyCycles / 10 + 1, $"busy logging throttled: {busyLogs} lines for {busyCycles} busy answers");
Check.True(busyLogs >= 1, "the first busy is logged");
}
private static void CountedSingleStack()
{
var w = new World();
w.AddStack(Carapace, "Olthoi Slayer Carapace", 5);
w.NpcTakesOnePerGive();
w.Run("/ub give 3 Olthoi Slayer Carapace to Town Crier");
Check.Eq(FakeHost.Gives.Count, 3, "3 of 5 to a one-per-give NPC: three gives");
Check.Eq(FakeHost.Ints[(Carapace, 12)], 2, "two left in the pack");
Check.Eq(FakeHost.Containers[Carapace], Player, "the stack stays");
var w2 = new World();
const uint Friend = 0x50000F02;
FakeHost.Names[Friend] = "Friend";
FakeHost.Positions[Friend] = (0x1048002Au, 101f, 101f, 0f);
FakeHost.ItemTypes[Friend] = 0x10;
w2.Cache.OnCreateObject(Friend);
w2.Cache.Tick();
w2.AddStack(Carapace, "Olthoi Slayer Carapace", 5);
FakeHost.GiveHandler = (item, target, amount) =>
{
FakeHost.Ints[(item, 12)] -= amount == 0 ? FakeHost.Ints[(item, 12)] : amount; // a player takes what is asked
};
w2.Run("/ub give 3 Olthoi Slayer Carapace to Friend");
Check.Eq(FakeHost.Gives.Count, 1, "to a player: one give");
Check.Eq(FakeHost.Gives[0].Amount, 3, "carrying the count (the server splits)");
Check.Eq(FakeHost.Ints[(Carapace, 12)], 2, "two left");
}
private static void CancelMidBusy()
{
var w = new World();
FakeHost.GiveHandler = (_, _, _) => { };
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Call("EnqueueGive", Mote2, Npc, 1);
w.Tick();
w.Chat("You're too busy!");
w.Tick(100); // busy seen, re-send armed
w.Call("CancelGiveQueue");
for (int i = 0; i < 20; i++) w.Tick(500);
Check.Eq(FakeHost.Gives.Count, 1, "nothing is sent after the cancel: no re-send, no next stack");
Check.True(w.ChatHas("Give queue cancelled"), "cancel reported");
}
private static void AcceptLineDoesNotAbandon()
{
var w = new World();
FakeHost.GiveHandler = (_, _, _) => { };
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Call("EnqueueGive", Mote2, Npc, 1);
w.Tick();
w.Chat("You give Town Crier Mana Mote.");
FakeHost.Containers[Mote1] = 0; // one unreadable tick
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "an accept line plus one unreadable tick does not abandon the stack");
FakeHost.Containers[Mote1] = Player;
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "read again, still carried");
}
private static void FailedStackReadOnStackableWaits()
{
var w = new World();
FakeHost.GiveHandler = (_, _, _) => { };
w.AddStack(Carapace, "Olthoi Slayer Carapace", 5);
FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100;
FakeHost.Ints.Remove((Carapace, 12)); // the stack read fails
w.Call("EnqueueGive", Carapace, Npc, 1);
w.Tick();
w.Tick();
Check.Eq(FakeHost.Gives.Count, 0, "a stackable item with an unreadable stack is not sent (amount 1 would hand over the whole stack)");
FakeHost.Ints[(Carapace, 12)] = 5;
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "sent on the first tick that reads it");
Check.Eq(FakeHost.Gives[0].Amount, 1, "one item, not the whole object");
}
private static void UnplaceableContainerIsUnreadable()
{
const uint Pack = 0x80281F01, Stranger = 0x80281F02;
var w = new World();
FakeHost.GiveHandler = (_, _, _) => { };
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Call("EnqueueGive", Mote2, Npc, 1);
w.Tick();
// In a side pack that itself reads as inside the player's pack: carried.
FakeHost.Containers[Pack] = Player;
FakeHost.Containers[Mote1] = Pack;
w.Tick(); w.Tick(); w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "a pack the player carries: still carried");
// In a container whose own container reads 0: unreadable, needs two ticks.
FakeHost.Containers.Remove(Stranger);
FakeHost.Containers[Mote1] = Stranger;
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "one tick of an unplaceable container is not gone");
FakeHost.Containers[Mote1] = Pack;
w.Tick();
FakeHost.Containers[Mote1] = Stranger;
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "the streak restarts after a good read");
w.Tick();
Check.Eq(FakeHost.Gives.Count, 2, "two unreadable ticks in a row: gone");
}
// Review of PR 18: a stackable item whose StackCount read stayed absent made SendGive return false on
// every tick, for ever, with nothing logged and nothing behind it in the queue ever sent.
private static void UnreadableStackFallsBackAfterTwoSeconds()
{
var w = new World();
w.Now = 1000;
w.AddStack(Carapace, "Olthoi Slayer Carapace", 5);
FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100;
FakeHost.Ints.Remove((Carapace, 12)); // the stack read never succeeds
FakeHost.GiveHandler = (item, target, _) => FakeHost.Containers[item] = target; // the server takes it
w.Call("EnqueueGive", Carapace, Npc, 0); // a genuine give-all
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Tick();
w.Tick(1500);
Check.Eq(FakeHost.Gives.Count, 0, "inside the 2 s the unreadable stack still waits");
w.Tick(600); // 2.1 s after the first failed read
Check.Eq(FakeHost.Gives.Count, 1, "after 2 s the give goes out anyway");
Check.Eq(FakeHost.Gives[0].Item, Carapace, "the stack that would not read");
Check.Eq(FakeHost.Gives[0].Amount, 0, "as a plain give (it was a give-all)");
Check.True(FakeHost.Logs.Any(l => l.Contains("unreadable for", StringComparison.Ordinal)), "and the log says why");
w.Tick();
Check.Eq(FakeHost.Gives.Count, 2, "the queue moved on to the next item");
Check.Eq(FakeHost.Gives[1].Item, Mote1, "the one behind it");
// A counted give keeps its explicit amount.
var w2 = new World();
w2.Now = 1000;
w2.AddStack(Carapace, "Olthoi Slayer Carapace", 5);
FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100;
FakeHost.Ints.Remove((Carapace, 12));
FakeHost.GiveHandler = (_, _, _) => { };
w2.Call("EnqueueGive", Carapace, Npc, 3);
w2.Tick();
w2.Tick(2001);
Check.Eq(FakeHost.Gives.Count, 1, "a counted give goes out after 2 s too");
Check.Eq(FakeHost.Gives[0].Amount, 3, "with its explicit amount");
}
// Review of PR 18 (follow-up): after the 2 s fallback, an amount of 1 used to go out as a plain give, which hands
// over the WHOLE object: a "give 1" of a stack that is really 99 would have sent all 99.
private static void UnreadableStackNeverGivesWholeForACount()
{
var w = new World();
w.Now = 1000;
w.AddStack(Carapace, "Olthoi Slayer Carapace", 99);
FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100;
FakeHost.Ints.Remove((Carapace, 12)); // really 99, but the count will not read
int sent = 0;
FakeHost.GiveHandler = (_, _, amount) => sent += amount; // the server hands over what is asked
w.Call("EnqueueGive", Carapace, Npc, 1);
w.Tick();
w.Tick(1500);
Check.Eq(FakeHost.Gives.Count, 0, "still waiting inside 2 s");
w.Tick(600);
Check.Eq(FakeHost.Gives.Count, 1, "after 2 s the give goes out");
Check.Eq(FakeHost.Gives[0].Amount, 1, "as an explicit 1, never as a whole-object give (0)");
Check.Eq(sent, 1, "one item reached the target, not the stack");
// A re-send (no answer) keeps the explicit amount too.
w.Tick(3001);
Check.Eq(FakeHost.Gives.Count, 2, "no answer: re-sent");
Check.Eq(FakeHost.Gives[1].Amount, 1, "the re-send is still an explicit 1");
// A stackable the cache has no MaxStackSize for (unknown, so no wait): the explicit count still goes out as asked.
var w2 = new World();
w2.AddStack(Carapace, "Olthoi Slayer Carapace", 99);
FakeHost.Ints.Remove((Carapace, 12));
FakeHost.GiveHandler = (_, _, _) => { };
w2.Call("EnqueueGive", Carapace, Npc, 1);
w2.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "unknown MaxStackSize: no wait");
Check.Eq(FakeHost.Gives[0].Amount, 1, "and an explicit 1");
// A give-all with the count unreadable is the one that goes out whole, and a re-send of it stays whole.
var w3 = new World();
w3.Now = 1000;
w3.AddStack(Carapace, "Olthoi Slayer Carapace", 99);
FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100;
FakeHost.Ints.Remove((Carapace, 12));
FakeHost.GiveHandler = (_, _, _) => { };
w3.Call("EnqueueGive", Carapace, Npc, 0);
w3.Tick();
w3.Tick(2001);
Check.Eq(FakeHost.Gives.Count, 1, "give-all: out after 2 s");
Check.Eq(FakeHost.Gives[0].Amount, 0, "as a whole-object give");
w3.Tick(3001);
Check.Eq(FakeHost.Gives.Count, 2, "no answer: re-sent");
Check.Eq(FakeHost.Gives[1].Amount, 0, "still a give-all, not an explicit 1");
}
private static void CountOneStackableWithoutCountGetsThrough()
{
var w = new World();
w.Now = 1000;
w.AddStack(Carapace, "Olthoi Slayer Carapace", 1);
FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100;
FakeHost.Ints.Remove((Carapace, 12)); // a stack of one: the property is simply absent
FakeHost.GiveHandler = (item, target, _) => FakeHost.Containers[item] = target; // the server takes it
w.Call("EnqueueGive", Carapace, Npc, 1);
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Tick();
w.Tick(2100);
Check.Eq(FakeHost.Gives.Count, 1, "the lone stackable goes out after the read wait");
Check.Eq(FakeHost.Gives[0].Item, Carapace, "it is the stack that would not read");
Check.Eq(FakeHost.Gives[0].Amount, 1, "as an explicit 1");
w.Tick(); w.Tick();
Check.Eq(FakeHost.Gives.Count, 2, "it left the pack: counted given, the queue moved on");
Check.False(w.ChatHas("didn't take"), "and nothing was skipped");
}
private static void GiveAllQueuesWholeStack()
{
var w = new World();
w.AddStack(Carapace, "Olthoi Slayer Carapace", 7);
FakeHost.GiveHandler = (item, target, _) => FakeHost.Containers[item] = target;
w.Run("/ub give Olthoi Slayer Carapace to Town Crier");
Check.Eq(FakeHost.Gives.Count, 1, "one give");
Check.Eq(FakeHost.Gives[0].Amount, 0, "the whole stack");
}
// Review of PR 18: a target that is never free (a player in a trade) was re-sent every 300 ms for ever,
// printing the server's "too busy" line in that player's chat about three times a second.
private static void BusyGivesUpAfterAMinute()
{
var w = new World();
w.Now = 1000;
FakeHost.GiveLands = false;
w.Call("EnqueueGive", Mote1, Npc, 1);
w.Call("EnqueueGive", Mote2, Npc, 1);
w.Tick();
long start = w.Now;
int guard = 0;
while (FakeHost.Gives.Count(g => g.Item == Mote2) == 0 && guard++ < 1000)
{
w.Chat("You're too busy!");
w.Tick(0);
w.Tick(300);
}
long waited = w.Now - start;
Check.True(FakeHost.Gives.Any(g => g.Item == Mote2), "after the cap the next stack is sent");
Check.True(waited >= 59000 && waited <= 61500, $"given up after about a minute of busy, not before ({waited} ms)");
Check.True(FakeHost.Gives.Count(g => g.Item == Mote1) <= 210, "the first stack was not re-sent past the cap");
Check.True(w.ChatHas("stayed busy"), "the player is told");
FakeHost.Containers[Mote2] = Npc;
w.Tick();
Check.True(w.ChatHas("1 item(s) given, 1 stack(s) skipped"), "the summary counts the busy skip");
Check.True(w.ChatHas("busy too long"), "with its reason");
}
// Review of PR 18: when the no-answer re-send could not go out (unreadable stack) the try was not
// counted, so GiveMaxTries + 1 sends could happen.
private static void FailedResendCountsAsATry()
{
var w = new World();
w.Now = 1000;
w.AddStack(Carapace, "Olthoi Slayer Carapace", 5);
FakeHost.Ints[(Carapace, (uint)(int)LongValueKey.MaxStackSize)] = 100;
FakeHost.GiveHandler = (_, _, _) => { }; // never answers
w.Call("EnqueueGive", Carapace, Npc, 5);
w.Tick();
Check.Eq(FakeHost.Gives.Count, 1, "sent");
FakeHost.Ints.Remove((Carapace, 12)); // the read fails when the re-send is due
w.Tick(3001);
Check.Eq(FakeHost.Gives.Count, 1, "the re-send could not go out");
FakeHost.Ints[(Carapace, 12)] = 5;
w.Tick();
Check.Eq(FakeHost.Gives.Count, 2, "it goes out on the next tick that reads");
w.Tick(3001);
Check.Eq(FakeHost.Gives.Count, 2, "two tries in all (GiveMaxTries), then it gives up");
Check.True(w.ChatHas("didn't take"), "and says so");
}
}

View file

@ -12,7 +12,7 @@ namespace RynthCore.RynthAiHostTests.Tests;
// HP failsafe: under Emergency Heal At with heals failing (here: every heal sent and never answered,
// as in a client log's hung casts), the character must not sit and die. 3 rounds of 2.5 s with no
// rise: a forced jump (ActionPacer.ForceBreak), then healing again; 3 more: the macro stops and
// "/lifestone" goes out (HpFailsafeRecall, default on).
// "/lifestone" goes out (HpFailsafeRecall, default off; the tests turn it on).
internal static class HpFailsafeTests
{
private const uint Player = 0x50000B31;
@ -30,6 +30,10 @@ internal static class HpFailsafeTests
r.Add("hp failsafe: a death drops the pending recall (0 health, and the plugin's death hold): no /lifestone, the macro stays off", DeathDropsRecall);
r.Add("hp failsafe: a failed recall does not switch the macro back on past a VTank yield", VTankYieldRespected);
r.Add("hp failsafe: our name unreadable: the recall line is taken as ours, and that is logged once", RecallNameUnreadable);
r.Add("hp failsafe: HP Failsafe Recall is off by default; a profile with no saved value loads off, one that saved true keeps it", RecallOffByDefault);
r.Add("hp failsafe: a character that cannot heal at all (no spell, kit or potion) never jumps or recalls", NoHealCapabilityNeverFires);
r.Add("hp failsafe: a character that can heal (a known Heal Self) and is stuck still jumps, then recalls when the option is on", CapableStuckStillRecalls);
r.Add("hp failsafe: a heal that went out proves the character can heal (a listed potion, no spell)", PotionSentProvesCapability);
r.Add("vitals (L8):a heal the server leaves unanswered is not re-sent at the 2.5 s give-up after a 'too busy' answer", VitalResendObeysLatch);
r.Add("vitals: under Emergency Heal At with a weapon out and no usable kit, a health potion before Heal Self's wand swap", EmergencyPotionBeforeWandSwap);
r.Add("low components: tapers at 10, a scarab at 2 (not Diamond), kinds never carried ignored, a kind run out still counts", LowComponentsRule);
@ -132,7 +136,7 @@ internal static class HpFailsafeTests
public readonly RynthCore.PluginSdk.RynthCoreHost Host;
public int MacroStops;
public Rig(int healthPct = 20)
public Rig(int healthPct = 20, bool canHeal = true, bool recall = true)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
@ -143,14 +147,24 @@ internal static class HpFailsafeTests
FakeHost.Names[Player] = "Mira";
FakeHost.PlayerPose = (0x6347028Au, 100f, 100f, 0f);
FakeHost.Positions[Player] = FakeHost.PlayerPose;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
if (canHeal)
{
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
}
else
{
// A warm spellbook that holds no heal (an empty one reads as "not loaded yet").
FakeHost.Spellbook.Add((uint)SpellTable.Rows.First(row => !row.Name.Contains("Heal", StringComparison.OrdinalIgnoreCase)
&& !row.Name.Contains("Health", StringComparison.OrdinalIgnoreCase)).Id);
}
var host = Host = FakeHost.Create(Player);
S = new LegacyUiSettings
{
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 30, StaminaToHealthAt = 0,
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false,
EnableBuffing = false, SpellCastIntervalMs = 100,
HpFailsafeRecall = recall, // off by default now; most tests here are about the recall
};
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
@ -202,6 +216,113 @@ internal static class HpFailsafeTests
MoveAudit.NowMs = () => Environment.TickCount64;
}
private static void CopySettings(LegacyUiSettings src, LegacyUiSettings dst) =>
typeof(RynthCore.Plugin.RynthAi.LegacyUi.LegacyDashboardRenderer).GetMethod("CopySettings",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)!
.Invoke(null, new object[] { src, dst });
private static void RecallOffByDefault()
{
Check.False(new LegacyUiSettings().HpFailsafeRecall, "a new settings object has the recall off");
var ctx = RynthAiJsonContext.Default.LegacyUiSettings;
// A profile with no saved value for it: off.
var node = System.Text.Json.Nodes.JsonNode.Parse(System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings(), ctx))!.AsObject();
Check.True(node.Remove("HpFailsafeRecall"), "the key is a serialized setting");
var noKey = System.Text.Json.JsonSerializer.Deserialize(node.ToJsonString(), ctx)!;
var live = new LegacyUiSettings { HpFailsafeRecall = true };
CopySettings(noKey, live);
Check.False(live.HpFailsafeRecall, "no saved value: the recall loads off");
// A profile that saved true (the owner turned it on, or the earlier default was saved): kept.
node["HpFailsafeRecall"] = true;
var saved = System.Text.Json.JsonSerializer.Deserialize(node.ToJsonString(), ctx)!;
var live2 = new LegacyUiSettings();
CopySettings(saved, live2);
Check.True(live2.HpFailsafeRecall, "a saved true stays on");
}
// A melee character with nothing to heal with (no spell, kit or potion), resting or out-healed at
// low health, must not be jumped around and sent to the lifestone: there is nothing to retry.
private static void NoHealCapabilityNeverFires()
{
try
{
var r = new Rig(healthPct: 20, canHeal: false);
r.Run(0, 40);
Check.Eq(FakeHost.Casts.Count, 0, "nothing to cast with");
Check.Eq(FakeHost.TapJumps, 0, "no failsafe jump");
Check.Eq(r.B.HpFailsafeBreaks, 0, "nothing counted");
Check.Eq(FakeHost.ChatCommands.Count, 0, "no /lifestone");
Check.Eq(r.B.HpFailsafeRecalls, 0, "no recall");
Check.True(r.S.IsMacroRunning, "the macro keeps running");
// Life Magic trained but no Heal Self known, and a potion listed with Use Potions off: still nothing.
const uint Potion = 0x80001234;
var p = new Rig(healthPct: 20, canHeal: false);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
FakeHost.Names[Potion] = "Healing Elixir";
p.S.UsePotions = false;
p.S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Potion), Name = "Healing Elixir", Type = "HealthPotion" });
var cache = new WorldObjectCache(p.Host);
cache.SetPlayerId(Player);
cache.OnCreateObject(Player);
_ = cache[unchecked((int)Potion)];
cache.Tick();
p.B.SetWorldObjectCache(cache);
p.Run(0, 40);
Check.Eq(FakeHost.TapJumps, 0, "no spell known, potions off: no jump");
Check.Eq(FakeHost.ChatCommands.Count, 0, "and no recall");
Check.True(p.S.IsMacroRunning, "the macro keeps running");
}
finally { Done(); }
}
// The gate does not switch the failsafe off for a character that can heal: stuck heals still break, then recall.
private static void CapableStuckStillRecalls()
{
try
{
var r = new Rig(healthPct: 20, canHeal: true, recall: true);
r.Run(0, 15.0);
Check.Eq(FakeHost.TapJumps, 1, "capable + stuck: the jump");
Check.False(r.S.IsMacroRunning, "capable + stuck + recall on: the macro stops");
r.Run(15.1, 16.0);
Check.Eq(FakeHost.ChatCommands.Count, 1, "and /lifestone goes out");
// The option off (the default): the jump only, the macro keeps running.
var d = new Rig(healthPct: 20, canHeal: true, recall: false);
d.Run(0, 30.0);
Check.Eq(FakeHost.TapJumps, 1, "recall off: the jump still");
Check.True(d.S.IsMacroRunning, "recall off: no stop");
Check.Eq(FakeHost.ChatCommands.Count, 0, "recall off: no /lifestone");
}
finally { Done(); }
}
// No spell, but a listed health potion with Use Potions on: the potion goes out (a heal sent), so
// the failsafe can arm when the potion does not raise health.
private static void PotionSentProvesCapability()
{
const uint Potion = 0x80001234;
try
{
var r = new Rig(healthPct: 20, canHeal: false);
FakeHost.Names[Potion] = "Healing Elixir";
r.S.UsePotions = true;
r.S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Potion), Name = "Healing Elixir", Type = "HealthPotion" });
var cache = new WorldObjectCache(r.Host);
cache.SetPlayerId(Player);
cache.OnCreateObject(Player);
_ = cache[unchecked((int)Potion)];
cache.Tick();
r.B.SetWorldObjectCache(cache);
r.Run(0, 15.0);
Check.True(FakeHost.Uses.Contains(Potion), "the potion is drunk");
Check.Eq(FakeHost.TapJumps, 1, "it did not raise health: the failsafe jump");
Check.False(r.S.IsMacroRunning, "and the recall stage");
}
finally { Done(); }
}
private static void BreakThenRecall()
{
try

View file

@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The engine refuses RequestId around a death or a portal (it returns false). A caller that marks an item
// "already asked" before the call, or counts the refusal as an attempt, never asks again; these callers
// record the request only when the engine took it.
internal static class IdRefusalTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("id refusal: the worn-gear appraisal asks again after the engine refused, and once it is taken", EquipmentAppraisalRetried);
r.Add("id refusal: the weapon identify pump does not count a refused request", WeaponPumpRetried);
}
private static void EquipmentAppraisalRetried()
{
const uint Player = 0x50000F01, Helm = 0x80000A01;
FakeHost.Reset();
FakeHost.WeaponCalls = true; // wires RequestId / HasAppraisalData
FakeHost.PlayerIdValue = Player;
FakeHost.Names[Helm] = "Helm";
FakeHost.Containers[Helm] = Player;
FakeHost.ItemTypes[Helm] = 0x2;
var host = FakeHost.Create(playerId: Player);
var plugin = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi });
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
typeof(RynthAiPlugin).GetField("_objectCache", Any)!.SetValue(plugin, cache);
cache.OnCreateObject(Helm);
cache.Tick();
var equip = new List<(string Name, uint Id, int Slot)> { ("Helm", Helm, 1) };
void Pass() => typeof(RynthAiPlugin).GetMethod("AppraiseEquipment", Any)!.Invoke(plugin, new object[] { equip });
FakeHost.RequestIdAccepts = false; // a portal in progress
Pass();
Check.True(FakeHost.RefusedIdRequests >= 1, "the engine refused the first request");
Check.Eq(FakeHost.IdRequests.Count, 0, "so nothing went out");
FakeHost.RequestIdAccepts = true;
Pass();
Check.Eq(FakeHost.IdRequests.Count(i => i == Helm), 1, "the next pass asked again and it was taken");
Pass();
Check.Eq(FakeHost.IdRequests.Count(i => i == Helm), 1, "a taken request is not repeated");
}
private static void WeaponPumpRetried()
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
var host = FakeHost.Create();
DateTime t = new(2026, 10, 18, 12, 0, 0);
var tr = new WeaponElementTracker(host, () => t);
int[] ids = { 0x60000051 };
FakeHost.RequestIdAccepts = false;
Check.Eq(tr.Pump(ids), 0, "refused: nothing asked for");
Check.Eq(tr.RequestsSent, 0, "and not counted");
FakeHost.RequestIdAccepts = true;
t = t.AddMilliseconds(500);
Check.Eq(tr.Pump(ids), 0, "inside the gap the retry is paced");
t = t.AddMilliseconds(2000);
Check.Eq(tr.Pump(ids), ids[0], "after the gap it is asked again");
t = t.AddMilliseconds(5100);
Check.Eq(tr.Pump(ids), ids[0], "unanswered: the second (and last) ask still available, the refusal cost none");
t = t.AddMilliseconds(5100);
Check.Eq(tr.Pump(ids), 0, "at most twice per weapon");
}
}

View file

@ -21,6 +21,7 @@ internal static class IgnoreMonsterTests
public static void Register(Runner r)
{
r.Add("monster ignore: a profile with a Priority 0 row logs and says in chat what Priority 0 means now, once", PriorityZeroIsAnnounced);
r.Add("monster ignore: a Priority 0 monster is never targeted", NotTargeted);
r.Add("monster ignore: a Priority 0 monster holds nothing up (nav, combat, close-threat gates)", HoldsNothingUp);
r.Add("monster ignore: the kill-shot swap does not count a Priority 0 monster as an alternate", KillShotAlternate);
@ -28,6 +29,41 @@ internal static class IgnoreMonsterTests
r.Add("monster ignore: Priority 1, no rule and the Default row behave as before", UnchangedForOtherPriorities);
}
// -- 0. the owner is told what Priority 0 means now -----------------------
private static int Notices() => FakeHost.Logs.Count(l => l.Contains("Priority 0 now means"));
private static void PriorityZeroIsAnnounced()
{
var c = World(GrubIgnored(), out var ids, (Grub, 3f));
var s = (LegacyUiSettings)typeof(CombatManager).GetField("_settings", Any)!.GetValue(c)!;
s.IsMacroRunning = true;
c.OnHeartbeat(); // the macro runs: the first check
c.OnHeartbeat();
c.NotePriorityZeroRules();
Check.Eq(Notices(), 1, "one log line for the profile's Priority 0 row, however often it is checked");
Check.True(FakeHost.Logs.Any(l => l.Contains("Priority 0 now means") && l.Contains("never attacked or tracked") && l.Contains(Grub)), "it says what it means and names the row");
Check.Eq(FakeHost.Chat.Count(l => l.Contains("Priority 0 now means")), 1, "and one chat notice");
Check.False(Scanned(c, ids[0]), "behavior unchanged: the Priority 0 monster is still never scanned");
// Another profile loads with the same Priority 0 rule: nothing new to say.
s.MonsterRules = GrubIgnored();
c.NotePriorityZeroRules();
Check.Eq(Notices(), 1, "the same Priority 0 set again: not repeated");
// A different Priority 0 row: said again.
s.MonsterRules = new() { new MonsterRule { Name = "Default", Priority = 1 }, new MonsterRule { Name = Soldier, Priority = 0 } };
c.NotePriorityZeroRules();
Check.Eq(Notices(), 2, "a different set of Priority 0 rows: said again");
// No Priority 0 row: silent.
var none = World(new() { new MonsterRule { Name = "Default", Priority = 1 }, new MonsterRule { Name = Grub, Priority = 2 } }, out _, (Grub, 3f));
none.NotePriorityZeroRules();
Check.Eq(Notices(), 0, "no Priority 0 row: no notice");
var noRules = World(null, out _, (Grub, 3f));
noRules.NotePriorityZeroRules();
Check.Eq(Notices(), 0, "default rules: no notice");
}
private static uint _next;
private static void Place(uint id, string name, float north)

View file

@ -40,6 +40,7 @@ internal static class MiniRemoteMoveTests
r.Add("mini remote: without RynthILT there are no ILT tabs, bits or verbs", NoRynthIlt);
r.Add("mini remote: /ra hub|quests|pets stay RynthAi's; quest windows point to RynthOracle; ILT verbs say RynthILT is needed", Commands);
r.Add("mini remote: the pyreal refill path never spends without RynthILT's confirmation", RefillNeedsIlt);
r.Add("vaulted dungeons: the master switch is off by default, saved with the profile, and an older engine's save leaves it alone", VaultedMasterSwitch);
r.Add("profile: the old Server Features fields still round-trip (RynthILT migrates them)", LegacyProfileFields);
r.Add("RynthAi.Hub: table, spell names, nothing before login", HubTable);
}
@ -177,6 +178,39 @@ internal static class MiniRemoteMoveTests
Check.False(fresh.Contains("InfiniteLeaftide"), "a fresh profile no longer gets an ILT server list");
}
/// <summary>
/// "Vaulted Dungeons" (Settings > Navigation) is RynthILT's keeper's master switch and lives only in
/// RynthAi's profile: off for a new or older profile, round-tripped through the settings bridge, and
/// an engine that predates the row (it sends no such field) never flips it.
/// </summary>
private static void VaultedMasterSwitch()
{
Check.False(new LegacyUiSettings().EnableVaultedDungeons, "off by default");
var oldProfile = JsonSerializer.Deserialize("{\"BoostNavPriority\":true}", RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.False(oldProfile.EnableVaultedDungeons, "a profile saved before the switch existed has it off");
var on = new LegacyUiSettings { EnableVaultedDungeons = true };
string json = JsonSerializer.Serialize(on, RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!.EnableVaultedDungeons, "saved with the profile");
var s = new LegacyUiSettings();
var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
var flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;
typeof(LegacyDashboardRenderer).GetField("_settings", flags)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", flags)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!;
Check.True(sent.EnableVaultedDungeons == false, "the Settings face is sent the switch (off)");
dash.ApplySettingsJson("{\"EnableVaultedDungeons\":true}");
Check.True(s.EnableVaultedDungeons, "the Settings checkbox turns it on");
dash.ApplySettingsJson("{\"NavRingThickness\":6}");
Check.True(s.EnableVaultedDungeons, "an older engine's save (no such field) leaves it on");
dash.ApplySettingsJson("{\"EnableVaultedDungeons\":false}");
Check.False(s.EnableVaultedDungeons, "the checkbox turns it off");
dash.ApplySettingsJson("{\"NavRingThickness\":6}");
Check.False(s.EnableVaultedDungeons, "and an older engine's save leaves it off");
}
private static unsafe void HubTable()
{
Check.Eq(HubInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "not ours");
@ -193,6 +227,8 @@ internal static class MiniRemoteMoveTests
QuestStatusV1 st;
Check.Eq(t->QuestStatus(&st), 0, "no quest tracker before login");
Check.Eq(t->MiniRemoteVisible(), 0, "no Mini Remote before login");
Check.True(t->VaultedDungeonsEnabled != null, "the Vaulted Dungeons master switch is served");
Check.Eq(t->VaultedDungeonsEnabled(), 0, "the master switch is off before login (and by default)");
SessionStatsV1 ss;
Check.Eq(t->SessionStats(&ss), 0, "no session before login");
}

View file

@ -0,0 +1,182 @@
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;
// Silentkelpie, 2026-10-15: with Missile Crafting on, combat swapped Electric Bow + arrows for
// Fire Crossbow + quarrels, and crafting kept wielding 'Infinite Deadly Prismatic Arrow' every
// 5 s (784 tries in one session). The stowed bow still read wielded (the client keeps a stowed
// item's old wielder and slot), the crossbow in hand read slot 0, the server ignored each arrow
// wield, and every try stopped the nav route while it waited.
internal static class MissileCraftingTests
{
private const uint Player = 0x50000C01;
private const uint Crossbow = 0x80000601, Bow = 0x80000602, Quarrels = 0x80000603, Arrows = 0x80000604;
private const int MissileSlot = 0x00400000, AmmoSlot = 0x00800000;
public static void Register(Runner r)
{
r.Add("missile crafting: a stowed bow that still reads wielded is not the launcher (no arrows at a crossbow)", StowedBowNotLauncher);
r.Add("missile crafting: wielded quarrels are not taken for a bow launcher", AmmoNotLauncher);
r.Add("missile crafting: an ammo wield the server ignores backs off after 2 tries", IgnoredWieldBacksOff);
r.Add("missile crafting: a bow in hand with its arrows in the pack still gets them wielded", BowInHandArrowsInPack);
}
/// <summary>Kelpie's state at 13:36: crossbow and quarrels in hand (slot 0), bow and arrows in the main pack.</summary>
private static void StowedBowNotLauncher()
{
var cm = Rig(crossbowInHand: true);
Idle(cm);
Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "crossbow with quarrels on: nothing to do");
Check.Eq(FakeHost.Uses.Count, 0, "no arrow wield");
Check.False(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no")), "no evaluation logged");
}
/// <summary>The quarrels wielded at login (slot set, typed MissileWeapon) and no launcher readable.</summary>
private static void AmmoNotLauncher()
{
var cm = Rig(crossbowInHand: false, arrange: () =>
{
FakeHost.Containers.Remove(Bow); // no bow anywhere
FakeHost.Wielded.Remove(Bow);
FakeHost.Containers.Remove(Quarrels); // the quarrels on, the crossbow in the pack
FakeHost.Wielded[Quarrels] = AmmoSlot;
});
Idle(cm);
Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "no launcher: crafting idles");
Check.Eq(FakeHost.Uses.Count, 0, "the quarrels never pass for a bow");
}
/// <summary>Bow in hand, arrows in the pack, and the server never puts them on.</summary>
private static void IgnoredWieldBacksOff()
{
var cm = BowRig();
for (int i = 0; i < 4; i++) Cycle(cm);
Check.Eq(FakeHost.Uses.Count(u => u == Arrows), 2, "two arrow wields, then no more");
Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "crafting let go");
Check.True(FakeHost.Logs.Any(l => l.Contains("didn't wield") && l.Contains("2 tries")), "the back-off is logged");
Cycle(cm);
Check.Eq(FakeHost.Uses.Count(u => u == Arrows), 2, "inside the back-off: still two");
}
/// <summary>The fix must not stop crafting doing its job: no ammo on, the pack's arrows go on.</summary>
private static void BowInHandArrowsInPack()
{
var cm = BowRig();
Cycle(cm);
Check.Eq(FakeHost.Uses.LastOrDefault(), Arrows, "UseObject(arrows)");
Check.True(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no Arrow") && l.Contains("'Longbow'")), "the launcher it saw is logged");
}
// ── The rig ─────────────────────────────────────────────────────────────
private static WorldObjectCache? _cache;
/// <param name="arrange">Changes to the fake world, made before the host and cache read it.</param>
private static MissileCraftingManager Rig(bool crossbowInHand, Action? arrange = null)
{
PaceOff();
FakeHost.Reset();
FakeHost.WeaponCalls = true; // UseObject, GetCurrentCombatMode
FakeHost.SalvageCalls = true; // GetObjectWielderInfo (answers from Wielded)
FakeHost.Names[Player] = "Silentkelpie";
Item(Crossbow, "Fire Crossbow", MissileSlot);
Item(Bow, "Electric Bow", MissileSlot);
Item(Quarrels, "Infinite Deadly Prismatic Quarrel", AmmoSlot);
Item(Arrows, "Infinite Deadly Prismatic Arrow", AmmoSlot);
// The pack listing holds only what is in the pack; the stowed bow's description still
// names the player and the missile slot.
FakeHost.Containers[Bow] = Player;
FakeHost.Containers[Arrows] = Player;
FakeHost.Wielded[Bow] = MissileSlot;
if (crossbowInHand)
{
FakeHost.Wielded[Crossbow] = 0; // wielded after login: slot reads 0
FakeHost.Wielded[Quarrels] = 0;
}
else
{
FakeHost.Containers[Crossbow] = Player;
FakeHost.Containers[Quarrels] = Player;
}
arrange?.Invoke();
var host = FakeHost.Create(Player);
_cache = FakeHost.MakeCache(host, Player, new[] { Crossbow, Bow, Quarrels, Arrows });
var cm = new MissileCraftingManager(host, new LegacyUiSettings { EnableMissileCrafting = true });
cm.SetObjectCache(_cache);
return cm;
}
/// <summary>A real bow in hand (slot set) with nothing in the ammo slot and arrows in the pack.</summary>
private static MissileCraftingManager BowRig() => Rig(crossbowInHand: false, arrange: () =>
{
FakeHost.Containers.Remove(Bow);
FakeHost.Names[Bow] = "Longbow";
});
private static void Item(uint id, string name, int validSlots)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = 0x100; // MissileWeapon, as the server types ammo too
FakeHost.Ints[(id, 9)] = validSlots;
}
private static readonly FieldInfo LastAmmoCheck =
typeof(MissileCraftingManager).GetField("_lastAmmoCheck", BindingFlags.Instance | BindingFlags.NonPublic)!;
private static readonly FieldInfo PhaseStart =
typeof(MissileCraftingManager).GetField("_phaseStart", BindingFlags.Instance | BindingFlags.NonPublic)!;
/// <summary>One idle tick with the 5 s ammo-check interval already passed.</summary>
private static void Idle(MissileCraftingManager cm)
{
LastAmmoCheck.SetValue(cm, DateTime.MinValue);
ForceRescan();
cm.ProcessCrafting();
}
/// <summary>One ammo check through to its wield (or its back-off), the clocks moved past each wait.</summary>
private static void Cycle(MissileCraftingManager cm)
{
for (int i = 0; i < 4 && (i == 0 || cm.State != MissileCraftingManager.CraftState.Idle); i++)
{
if (cm.State == MissileCraftingManager.CraftState.Idle)
{
// The back-off moves _lastAmmoCheck into the future; only an expired check is reset.
if ((DateTime)LastAmmoCheck.GetValue(cm)! <= DateTime.Now)
LastAmmoCheck.SetValue(cm, DateTime.MinValue);
}
else
{
PhaseStart.SetValue(cm, DateTime.Now.AddSeconds(-1)); // past EQUIP_DELAY_MS
}
ForceRescan();
cm.ProcessCrafting();
}
}
/// <summary>GetDirectInventory re-serves a scan under 1 s old; the test can't wait on the wall clock.</summary>
private static void ForceRescan() =>
typeof(WorldObjectCache).GetField("_lastDirectInventoryScan", BindingFlags.Instance | BindingFlags.NonPublic)!
.SetValue(_cache, DateTime.MinValue);
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;
}
}

View file

@ -45,6 +45,7 @@ internal static class MonsterEditorTests
GravityWell = true, Imperil = true, Yield = true, Vuln = true, UseArc = true, UseRing = true,
UseStreak = true, UseBolt = false, UseBlast = true, UseWall = true, ExVuln = "Fire", OffhandId = 2,
PetDamage = "Cold", CustomDebuffs = "Corrosion Vulnerability Other, Fire Vulnerability Other VII",
Kite = "PullAway",
},
new PluginRule { Name = "", Category = "Expression only", MatchExpression = "wobjectfindnearestbytemplatetype[1]" },
};

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
@ -71,6 +72,7 @@ internal static class NavEngineTests
r.Add("nav engine: a Linear index past the end carries on from that end", LinearIndexOffEnd); // was a known failure; fixed by 91178c1
r.Add("nav engine: a chat point that loads another route hands over to it", ChatLoadsRoute); // was a known failure; fixed by a8e5de0
r.Add("nav engine: a recall that never fires, next waypoint far: stops instead of walking off", RecallTimeoutFar); // was a known failure; fixed by 5cfbcea
r.Add("nav engine: a portal/NPC use the engine did not send is not logged as sent and is asked again", PortalNpcUseNotSent);
}
// ── Rig ───────────────────────────────────────────────────────────────────
@ -342,6 +344,34 @@ internal static class NavEngineTests
Check.True(nav.S.EnableNavigation, "nav still on");
}
private static void PortalNpcUseNotSent()
{
FakeHost.Reset(); At(0, 0);
FakeHost.WeaponCalls = true; // UseObject
const uint Npc = 0x7A000001, Me = 0x50000F01;
var pose = FakeHost.PlayerPose;
FakeHost.Names[Me] = "Tester";
FakeHost.Positions[Me] = pose;
FakeHost.Names[Npc] = "Gateway";
FakeHost.Positions[Npc] = (pose.Cell, pose.X + 1f, pose.Y, pose.Z);
var host = FakeHost.Create(Me);
var cache = FakeHost.MakeCache(host, Me, new[] { Npc });
var nav = new Nav(Route(RT.Once, Pt(10, 0), Pt(20, 0)));
nav.E.SetWorldObjectCache(cache);
nav.E.SetPlayerId(Me);
var fire = typeof(NavigationEngine).GetMethod("FirePortalNpcUse", BindingFlags.Instance | BindingFlags.NonPublic)!;
var point = new NavPoint { Type = T.PortalNPC, TargetName = "Gateway" };
FakeHost.UseObjectAccepts = false;
Check.False((bool)fire.Invoke(nav.E, new object[] { point })!, "the engine did not send the use: not fired, the caller asks again");
Check.Eq(LogCount("UseObject portal 'Gateway' (dist="), 0, "and no 'used' line is logged");
Check.Eq(LogCount("was not sent - will retry"), 1, "the refusal is logged");
FakeHost.UseObjectAccepts = true;
Check.True((bool)fire.Invoke(nav.E, new object[] { point })!, "once the engine sends it the portal counts as fired");
Check.Eq(LogCount("UseObject portal 'Gateway' (dist="), 1, "and the 'used' line is logged");
}
private static void RecallTimeoutNear()
{
var nav = RecallRoute(30);

View file

@ -31,6 +31,35 @@ internal static class NavOverlayTests
r.Add("nav overlay: the frame is a snapshot - emptying the route afterwards changes nothing", FrameIsSnapshot);
r.Add("nav overlay: the label triangle budget holds for long names", TriangleBudget);
r.Add("nav overlay: settings round-trip; an older engine's payload leaves them alone", SettingsRoundTrip);
r.Add("nav overlay: Settings > Navigation shows the Nav panel's Breadcrumbs and Route overlay switches", SettingsLinksNavPanelSwitches);
}
/// <summary>
/// Settings > Navigation carries the Nav panel's two switches (NavOverlay.TrackBreadcrumbs and
/// ShowRouteMarkers), so either place changes the same setting. An engine that predates them
/// sends neither, and its save must leave them alone.
/// </summary>
private static void SettingsLinksNavPanelSwitches()
{
var s = new LegacyUiSettings();
s.NavOverlay.TrackBreadcrumbs = false;
s.NavOverlay.ShowRouteMarkers = true;
var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
var flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;
typeof(LegacyDashboardRenderer).GetField("_settings", flags)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", flags)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!;
Check.True(sent.TrackBreadcrumbs == false, "Breadcrumbs sent to the Settings face (off)");
Check.True(sent.ShowRouteOverlay == true, "Route overlay sent to the Settings face (on)");
dash.ApplySettingsJson("{\"TrackBreadcrumbs\":true,\"ShowRouteOverlay\":false}");
Check.True(s.NavOverlay.TrackBreadcrumbs, "Settings turns Breadcrumbs on (the Nav panel's switch)");
Check.False(s.NavOverlay.ShowRouteMarkers, "Settings turns Route overlay off (the Nav panel's switch)");
dash.ApplySettingsJson("{\"NavRingThickness\":6}");
Check.True(s.NavOverlay.TrackBreadcrumbs, "an older engine's save leaves Breadcrumbs alone");
Check.False(s.NavOverlay.ShowRouteMarkers, "an older engine's save leaves Route overlay alone");
}
// ── Rig ─────────────────────────────────────────────────────────────

View file

@ -23,6 +23,7 @@ internal static class PetRefillTests
private const uint Mob = 0x80300010;
private const uint Essence = 0x80300001;
private const uint Spirit = 0x80300002;
private const uint Essence2 = 0x80300003; // a second essence, only for the assume-window test
private const uint StructureKey = 92; // AcIntProperty.Structure
private const uint Lb = 0xA9B40000;
@ -38,6 +39,8 @@ internal static class PetRefillTests
r.Add("pets: 'not enough charges' after a confirmed refill ends the trust; refill again", TrustEndsOnEmptySummon);
r.Add("pets: refilled twice in 2 min and still empty (no reply) -> parked 5 min", SilentRefillsParked);
r.Add("pets: the server's 'full' trust expires after 30 min", TrustExpires);
r.Add("pets: a landed summon whose pet is not in the cache yet holds a second essence back for the 10 s window", LandedSummonHoldsWindow);
r.Add("pets: failed summon (no charge drop) does not assume a pet; waits the 45 s essence cooldown", FailedSummonRespectsCooldown);
}
// ── Rig ───────────────────────────────────────────────────────────────
@ -48,7 +51,7 @@ internal static class PetRefillTests
public readonly LegacyUiSettings S = new() { SummonPets = true, MonsterRange = 20, CustomPetRange = 5, PetAutoRefill = true };
public readonly PetManager Pets;
public Rig(int charges)
public Rig(int charges, bool secondEssence = false)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true; // UseObject (summon), RequestId (re-identify)
@ -61,11 +64,19 @@ internal static class PetRefillTests
FakeHost.Names[Spirit] = "Encapsulated Spirit";
FakeHost.Containers[Spirit] = Player;
SetCharges(charges);
if (secondEssence)
{
FakeHost.Names[Essence2] = "Frost Moar Essence (50)";
FakeHost.Containers[Essence2] = Player;
FakeHost.Ints[(Essence2, StructureKey)] = 50;
}
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, new[] { Mob, Essence, Spirit });
var cache = FakeHost.MakeCache(host, Player, secondEssence ? new[] { Mob, Essence, Spirit, Essence2 } : new[] { Mob, Essence, Spirit });
S.IsMacroRunning = true;
S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Essence), Name = "Fire Moar Essence (50)", Type = "Pet" });
if (secondEssence)
S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Essence2), Name = "Frost Moar Essence (50)", Type = "Pet" });
var combat = new CombatManager(host, S, cache);
combat.SetPlayerId(Player);
combat.ScanNearbyTargets();
@ -101,6 +112,7 @@ internal static class PetRefillTests
public int Refills => FakeHost.UsesOn.Count(u => u.Source == Spirit && u.Target == Essence);
public int Summons => FakeHost.Uses.Count(u => u == Essence);
public int AllSummons => FakeHost.Uses.Count(u => u == Essence || u == Essence2);
public void Dispose() => PetManager.Clock = static () => Environment.TickCount64;
}
@ -191,8 +203,49 @@ internal static class PetRefillTests
int refills = rig.Refills;
Check.Eq(refills, 1, "trusted: no second refill");
// No summon lands (no pet appears, the read never moves): each summon times out and
// parks the essence for 30 s. After 30 minutes the trust is gone and the read rules.
// parks the essence for the 45 s PetDevice cooldown. After 30 minutes the trust is gone.
rig.Run(31 * 60_000);
Check.True(rig.Refills > refills, "after 30 minutes the empty read is believed again");
}
/// <summary>
/// Kelpie 2026-10-16: Use refused (cooldown / environment) leaves Structure unchanged.
/// Must not assume a pet is out, and must wait the full ~45 s essence cooldown before retry.
/// </summary>
private static void FailedSummonRespectsCooldown()
{
using var rig = new Rig(charges: 50);
rig.Run(1500);
Check.Eq(rig.Summons, 1, "first Use fired");
// Structure never drops and no pet appears → timeout treats it as a failed Use.
Rig.SetCharges(50);
rig.Run(9_000);
Check.Eq(rig.Summons, 1, "still one Use during the 45 s cooldown (no false re-issue)");
Check.True(FakeHost.Logs.Any(l => l.Contains("failed Use", StringComparison.OrdinalIgnoreCase)
|| l.Contains("no charge drop", StringComparison.OrdinalIgnoreCase)),
"failed Use is logged");
// Park is from IssueSummon (~t=100 ms), not from the 8 s timeout. At ~44 s from start
// still cooling; a few seconds more clears the 45 s essence cooldown.
rig.Run(34_000);
Check.Eq(rig.Summons, 1, "still cooling at ~44 s from first Use");
rig.Run(4_000);
Check.Eq(rig.Summons, 2, "second Use after the 45 s essence cooldown");
}
/// <summary>
/// The charge dropped (the Use landed) but the pet is not in the landscape cache yet: the assume
/// window must keep a second essence from being summoned beside it, and lapse after 10 s.
/// </summary>
private static void LandedSummonHoldsWindow()
{
using var rig = new Rig(charges: 50, secondEssence: true);
rig.Run(1500);
Check.Eq(rig.AllSummons, 1, "first Use fired");
Rig.SetCharges(49);
FakeHost.Ints[(Essence2, StructureKey)] = 49; // whichever essence it was, its charge dropped
rig.Run(8_000);
Check.Eq(rig.AllSummons, 1, "inside the 10 s window the other essence is not used");
rig.Run(5_000);
Check.Eq(rig.AllSummons, 2, "window over and still no pet: the other essence is used");
}
}

View file

@ -28,6 +28,10 @@ internal static class ProfileLoadTests
r.Add("profile: every saved setting survives loading (CopySettings lists each serialized field)", EverySavedFieldIsCopied);
r.Add("profile: Describe Items and the Item Info options survive a save and a reload", ItemInfoSurvivesReload);
r.Add("profile: a profile with null item info / nav overlay loads defaults, not null", NullNestedOptionsLoadDefaults);
r.Add("profile: a save is atomic (temp file swapped in, no temp left) and keeps the previous profile as .bak", SaveKeepsBackup);
r.Add("profile: a profile that doesn't read loads the .bak, sets the broken file aside and puts the backup back", UnreadableLoadsBackup);
r.Add("profile: a profile that doesn't read and has no backup is kept, not overwritten by defaults until a setting changes", UnreadableKeptNotOverwritten);
r.Add("profile: switching to a profile that doesn't read keeps it (backup used when there is one)", SwitchUnreadableKept);
}
/// <summary>LegacyDashboardRenderer.CopySettings(src, dst): what LoadSettings / SwitchProfile run.</summary>
@ -169,4 +173,161 @@ internal static class ProfileLoadTests
CopySettings(edited, live2);
Check.Eq(live2.ItemInfoSettings.Prefix.Length, 32, "prefix trimmed to 32");
}
// ── Settings no longer reset after a bad read (2026-10-17, Silentkelpie's design) ──────────────
// Saving used File.WriteAllText, which empties the profile first: a client killed mid-save left an
// empty / cut-off file, the load swallowed the failed read, kept defaults and the autosave wrote
// them over the profile. Saves now swap a temp file in and keep the previous one as <profile>.json.bak;
// a profile that doesn't read loads the .bak, else is set aside as .unreadable-<time> and not
// written over until something changes. Scratch folders only: ProfilesBase / MonstersBase are
// pointed at them.
private static string NewCharDir(string name, out LegacyDashboardRenderer dash)
{
string root = Path.Combine(Program.TempRoot, "profile-reset", name);
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
LegacyDashboardRenderer.ProfilesBase = Path.Combine(root, "SettingsProfiles");
LegacyDashboardRenderer.MonstersBase = Path.Combine(root, "MonsterProfiles");
RynthCore.RynthAiHostTests.Fakes.FakeHost.Reset();
RynthCore.RynthAiHostTests.Fakes.FakeHost.WorldName = "TestWorld";
dash = new LegacyDashboardRenderer(RynthCore.RynthAiHostTests.Fakes.FakeHost.Create());
string dir = Path.Combine(LegacyDashboardRenderer.ProfilesBase, "TestWorld", "Tester");
Directory.CreateDirectory(dir);
return dir;
}
private static LegacyUiSettings SettingsOf(LegacyDashboardRenderer dash) =>
(LegacyUiSettings)typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.GetValue(dash)!;
private static string Json(LegacyUiSettings s) => JsonSerializer.Serialize(s, RynthAiJsonContext.Default.LegacyUiSettings);
private static int ChatCount(string part)
{
int n = 0;
foreach (string c in RynthCore.RynthAiHostTests.Fakes.FakeHost.Chat)
if (c.Contains(part, StringComparison.OrdinalIgnoreCase)) n++;
return n;
}
private static void SaveKeepsBackup()
{
string dir = NewCharDir("bak", out var dash);
dash.LoadSettings("Tester");
LegacyUiSettings live = SettingsOf(dash);
string path = Path.Combine(dir, "Default.json");
live.EnableGroundLoot = false;
dash.SaveSettings();
string first = File.ReadAllText(path);
Check.True(File.Exists(path) && !File.Exists(path + LegacyDashboardRenderer.BackupSuffix), "first save: the profile, no backup yet");
live.EnableGroundLoot = true;
dash.SaveSettings();
string second = File.ReadAllText(path);
Check.True(first != second, "the profile now holds the second state");
Check.Eq(File.ReadAllText(path + LegacyDashboardRenderer.BackupSuffix), first, ".bak holds the previous profile");
Check.Eq(Directory.GetFiles(dir, "*.tmp").Length, 0, "no temp file left behind");
// A failing swap leaves the profile and no temp file.
using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
live.EnableGroundLoot = false;
dash.SaveSettings();
}
Check.Eq(File.ReadAllText(path), second, "a save that can't swap in leaves the profile as it was");
Check.Eq(Directory.GetFiles(dir, "*.tmp").Length, 0, "and no temp file");
}
private static void UnreadableLoadsBackup()
{
string dir = NewCharDir("loads-bak", out var dash);
string path = Path.Combine(dir, "Default.json");
// The last good save: ground loot on. Then a save cut off mid-write.
var good = new LegacyUiSettings { EnableGroundLoot = true };
string goodJson = Json(good);
File.WriteAllText(path + LegacyDashboardRenderer.BackupSuffix, goodJson);
string cut = goodJson.Substring(0, goodJson.Length / 2);
File.WriteAllText(path, cut);
dash.LoadSettings("Tester");
LegacyUiSettings live = SettingsOf(dash);
Check.True(live.EnableGroundLoot, "the backup's settings are in use");
Check.Eq(File.ReadAllText(path), goodJson, "the backup is put back as the profile");
Check.Eq(File.ReadAllText(path + LegacyDashboardRenderer.BackupSuffix), goodJson, "and stays as the backup");
string[] kept = Directory.GetFiles(dir, "Default.json.unreadable-*");
Check.Eq(kept.Length, 1, "the broken file is kept");
Check.True(kept.Length == 1 && File.ReadAllText(kept[0]) == cut, "with its contents intact");
Check.Eq(ChatCount("restored the backup"), 1, "chat says so");
// The autosave after login may rewrite the profile normalized, but it still holds the backup's settings,
// and the .bak is still a readable profile.
dash.TickAutoSave();
var again = JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(again != null && again.EnableGroundLoot, "the profile after the autosave still holds the backup's settings");
var bak = JsonSerializer.Deserialize(File.ReadAllText(path + LegacyDashboardRenderer.BackupSuffix), RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(bak != null && bak.EnableGroundLoot, "and so does the .bak (never the broken file)");
}
private static void UnreadableKeptNotOverwritten()
{
foreach (string broken in new[] { "", "{ \"EnableGroundLoot\": tru", "not json at all" })
{
string dir = NewCharDir("kept", out var dash);
string path = Path.Combine(dir, "Default.json");
File.WriteAllText(path, broken);
dash.LoadSettings("Tester");
LegacyUiSettings live = SettingsOf(dash);
Check.Eq(ChatCount("didn't read"), 1, "chat says the file didn't read (" + (broken.Length == 0 ? "empty" : broken) + ")");
// The autosave must not write the defaults over it.
for (int i = 0; i < 3; i++) dash.TickAutoSave();
Check.Eq(File.ReadAllText(path), broken, "the unreadable profile is untouched by the autosave");
string[] kept = Directory.GetFiles(dir, "Default.json.unreadable-*");
Check.Eq(kept.Length, 1, "a copy is kept");
Check.True(kept.Length == 1 && File.ReadAllText(kept[0]) == broken, "with the original contents");
Check.False(File.Exists(path + LegacyDashboardRenderer.BackupSuffix), "no backup was invented");
// A real change is saved normally, and the kept copy is still there.
live.EnableGroundLoot = !live.EnableGroundLoot;
dash.TickAutoSave();
string now = File.ReadAllText(path);
Check.True(now.Length > 2 && now.Contains("EnableGroundLoot"), "once a setting changes the profile is written");
Check.Eq(Directory.GetFiles(dir, "Default.json.unreadable-*").Length, 1, "the kept copy is still there");
}
// A missing profile is still a fresh character: defaults, saved at once, nothing set aside.
string fresh = NewCharDir("fresh", out var dash2);
dash2.LoadSettings("Tester");
dash2.TickAutoSave();
Check.True(File.Exists(Path.Combine(fresh, "Default.json")), "a new character's profile is created");
Check.Eq(Directory.GetFiles(fresh, "*.unreadable-*").Length, 0, "nothing to set aside");
}
private static void SwitchUnreadableKept()
{
string dir = NewCharDir("switch", out var dash);
dash.LoadSettings("Tester");
LegacyUiSettings live = SettingsOf(dash);
dash.SaveSettings();
// 'Other' is unreadable and has no backup: kept, with the reason in chat.
string other = Path.Combine(dir, "Other.json");
File.WriteAllText(other, "{ broken");
dash.LoadProfile("Other");
Check.Eq(Directory.GetFiles(dir, "Other.json.unreadable-*").Length, 1, "the unreadable profile is kept");
Check.Eq(ChatCount("Profile 'Other' didn't read"), 1, "and chat says so");
// 'Third' is unreadable but has a backup: the backup is used and put back.
var good = new LegacyUiSettings { EnableGroundLoot = true, SelectedProfile = "Third" };
string goodJson = Json(good);
File.WriteAllText(Path.Combine(dir, "Third.json.bak"), goodJson);
File.WriteAllText(Path.Combine(dir, "Third.json"), "");
live.EnableGroundLoot = false;
dash.LoadProfile("Third");
Check.True(SettingsOf(dash).EnableGroundLoot, "the backup's settings are loaded");
Check.Eq(File.ReadAllText(Path.Combine(dir, "Third.json")), goodJson, "and put back as the profile");
Check.Eq(Directory.GetFiles(dir, "Third.json.unreadable-*").Length, 1, "the empty file is kept too");
}
}

View file

@ -0,0 +1,97 @@
using System;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Empyrean Handler lethal-ring evade (CombatManager.HandleChatForRingEvade; Silentkelpie's PR 12). The line
// "The handler briefly channels infused Empyrean hatred to release a lethal ring." makes combat back-jump
// away from a Handler inside the ring radius. The base adds a gate: only while the macro is running with
// combat on, and a setting (HandlerRingEvade) turns it off.
internal static class RingEvadeTests
{
private const uint Player = 0x50000D11;
private const uint Handler = 0x80300110;
private const uint Lb = 0xA9B40000;
private const string RingLine = "The handler briefly channels infused Empyrean hatred to release a lethal ring.";
public static void Register(Runner r)
{
r.Add("ring evade: the Handler's ring line back-jumps when it is in range and the macro runs with combat on", Jumps);
r.Add("ring evade: not with the setting off, the macro stopped, or combat off", Gated);
r.Add("ring evade: not for a Handler out of range, no Handler, or a player's copy of the line", NotThese);
}
private sealed class Rig
{
public readonly LegacyUiSettings S = new() { MonsterRange = 40, EnableCombat = true };
public readonly CombatManager Combat;
public int Jumps;
public float Heading = -1;
public Rig(float handlerYards, string handlerName = "Empyrean Handler")
{
FakeHost.Reset();
FakeHost.Names[Player] = "Evader";
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.Names[Handler] = handlerName;
FakeHost.Positions[Handler] = (Lb | 0x1C, 96f, 96f + handlerYards, 0f);
FakeHost.ItemTypes[Handler] = 0x10;
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, new[] { Handler });
S.IsMacroRunning = true;
Combat = new CombatManager(host, S, cache);
Combat.SetPlayerId(Player);
Combat.ScanNearbyTargets();
Combat.RequestBackJump = (h, ms) => { Jumps++; Heading = h; return true; };
Combat.JumpBusy = () => false;
}
}
private static void Jumps()
{
var rig = new Rig(handlerYards: 5);
rig.Combat.HandleChatForRingEvade(RingLine, 0x0C);
Check.Eq(rig.Jumps, 1, "a Handler 5 yards away: one back-jump");
rig.Combat.HandleChatForRingEvade(RingLine, 0x0C);
Check.Eq(rig.Jumps, 1, "a second line inside the cooldown does nothing");
}
private static void Gated()
{
var off = new Rig(5);
off.S.HandlerRingEvade = false;
off.Combat.HandleChatForRingEvade(RingLine, 0x0C);
Check.Eq(off.Jumps, 0, "setting off: no jump");
var stopped = new Rig(5);
stopped.S.IsMacroRunning = false;
stopped.Combat.HandleChatForRingEvade(RingLine, 0x0C);
Check.Eq(stopped.Jumps, 0, "macro stopped: no jump");
var noCombat = new Rig(5);
noCombat.S.EnableCombat = false;
noCombat.Combat.HandleChatForRingEvade(RingLine, 0x0C);
Check.Eq(noCombat.Jumps, 0, "combat off: no jump");
Check.True(new LegacyUiSettings().HandlerRingEvade, "on by default (it is gated)");
}
private static void NotThese()
{
var far = new Rig(30);
far.Combat.HandleChatForRingEvade(RingLine, 0x0C);
Check.Eq(far.Jumps, 0, "a Handler 30 yards away is outside the ring");
var none = new Rig(5, handlerName: "Drudge Skulker");
none.Combat.HandleChatForRingEvade(RingLine, 0x0C);
Check.Eq(none.Jumps, 0, "no Empyrean Handler nearby");
var said = new Rig(5);
said.Combat.HandleChatForRingEvade("Someone says, \"" + RingLine + "\"", 0x03);
Check.Eq(said.Jumps, 0, "a player's copy of the line is ignored");
}
}

View file

@ -23,6 +23,8 @@ internal static class SectionsTests
r.Add("sections: the engine catalog places RynthAi's views by server", CatalogPlacement);
r.Add("sections: tab surfaces map back to their tabs; foreign ids are refused", SurfaceRoundTrip);
r.Add("sections: Character redirects to RynthOracle; Charms and Banking stay RynthILT's tabs", MovedTabRedirects);
r.Add("mini remote: Options left-click runs the Settings command with a chat parser, else the popup", OptionsClickRouting);
r.Add("mini remote: the header row (V/H, Options, gear) fits the narrowest remote", HeaderRowFits);
}
private static void MovedTabRedirects()
@ -35,6 +37,24 @@ internal static class SectionsTests
Check.Eq(MovedTabs.Diagnostics, "/rc diagnostics", "the engine's Diagnostics command");
}
private static void OptionsClickRouting()
{
Check.Eq(MiniRemoteHeader.OptionsLeftClickCommand(true), "/rc ui open Settings", "a chat parser: the engine opens RynthAi Settings");
Check.Eq(MiniRemoteHeader.OptionsLeftClickCommand(true), MovedTabs.Settings, "through MovedTabs.Settings");
Check.True(MiniRemoteHeader.OptionsLeftClickCommand(false) == null, "no chat parser: no command, the click opens the Mini Remote popup");
Check.True(MovedTabs.CommandFor("settings") == null, "Settings is not a moved Mini Remote tab");
Check.Eq(MovedTabs.HomeOf(MovedTabs.Settings), "RynthAi Settings (Advanced Settings)", "its words");
}
private static void HeaderRowFits()
{
// The remote's own item spacing is 4 (MiniRemoteHud pushes it); allow a theme up to 12.
foreach (float spacing in new[] { 3f, 4f, 8f, 12f })
Check.True(MiniRemoteHeader.RowWidth(spacing) <= MiniRemoteHud.MinColumnWidth,
$"header row {MiniRemoteHeader.RowWidth(spacing)} fits {MiniRemoteHud.MinColumnWidth} at spacing {spacing}");
Check.True(MiniRemoteHeader.GearButtonWidth >= 20f, "the gear stays clickable");
}
private const string Payload =
"V\tilt\tInfinite Leaftide\t1\ton\t0\n" +
"V\taelrynth\tAelrynth\t0\tauto\t0\n" +

View file

@ -0,0 +1,492 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// SilentKelpie's combat additions (RynthSuite PR 12, taken 2026-10-19), through CombatManager and
// the settings bridges rather than the pure planners (EnvironmentImpactTests has those):
// - per-monster attack power reaches the attack the server is sent, and with no rule asking for
// one the global Melee/Missile Power is sent exactly as before;
// - the per-monster Kite choice (Default / Off / PullAway) is kept by the Monsters bridge, an
// older Monsters panel can't wipe it, and with nothing set combat never runs or turns;
// - the new settings ride the Settings bridge, an engine without them leaves them alone;
// - the environment-hit throttle trips only after N hits inside its window.
internal static class SkCombatAddonTests
{
private const uint Player = 0x50000F01;
private const uint Lb = 0xA9B40000;
private const uint A = 0x80000401, B = 0x80000402;
private const string MissileLine = "Your missile attack hit the environment.";
public static void Register(Runner r)
{
r.Add("sk combat: no rule asks for a power: the global Melee Power is sent exactly as before", PowerDefaultsUnchanged);
r.Add("sk combat: a rule's Power reaches the attack sent to the server (High, Reckless, Variable)", PowerReachesAttack);
r.Add("sk combat: Reckless needs Recklessness trained; untrained it sends High, Reckless + Variable sends Variable", PowerRespectsTraining);
r.Add("sk combat: Variable power changes attack to attack and stays inside Min..Max", PowerVariableRange);
r.Add("sk combat: Kite Default/Off never runs or turns; PullAway tags (or not), runs, and gives up when it makes no ground", KiteFlow);
r.Add("sk combat: the Kite and Power choices survive the Monsters bridge; an older panel can't wipe them", KiteBridgePersisted);
r.Add("sk combat: the new settings ride the Settings bridge; an engine without them leaves them alone", SettingsBridge);
r.Add("sk combat: every new setting is off / unchanged by default", SettingsDefaults);
r.Add("sk combat: environment hits trip only after N inside the window; older ones age out; a response then does what it says", EnvironmentWindow);
}
// ── A melee rig ──────────────────────────────────────────────────────────
private sealed class Rig
{
public readonly LegacyUiSettings S;
public readonly CombatManager C;
public readonly WorldObjectCache Cache;
public DateTime Now = new(2026, 10, 19, 12, 0, 0);
public Rig(int mode, Action<LegacyUiSettings> set, params (uint Id, string Name, float X, float Y)[] mobs)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.AttackSendCalls = true;
FakeHost.CombatModeValue = mode;
Place(Player, "Me", 96, 96, creature: false);
foreach (var m in mobs) Place(m.Id, m.Name, m.X, m.Y);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.HeadingDeg = 0;
S = new LegacyUiSettings { MonsterRange = 50, IsMacroRunning = true, EnableCombat = true };
set(S);
var host = FakeHost.Create(Player);
Cache = FakeHost.MakeCache(host, Player, mobs.Select(m => m.Id));
C = new CombatManager(host, S, Cache);
C.SetPlayerId(Player);
C.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
C.EnvClock = () => Now;
C.KiteClock = () => Now;
C.ScanNearbyTargets();
C.HandleCombatTrigger();
FakeHost.AttackCalls.Clear();
}
/// <summary>Thinks until an attack reaches the server (false if none does in 30 ticks).</summary>
public bool ThinkToAttack()
{
int before = FakeHost.AttackCalls.Count;
for (int i = 0; i < 30 && FakeHost.AttackCalls.Count == before; i++)
{
LastAttackCmd.SetValue(C, DateTime.MinValue); // the attack cadence runs on the real clock
C.Think();
Now = Now.AddMilliseconds(400);
}
return FakeHost.AttackCalls.Count > before;
}
public float LastPower => FakeHost.AttackCalls[^1].Power;
private static readonly FieldInfo LastAttackCmd = typeof(CombatManager).GetField("lastAttackCmd", BindingFlags.NonPublic | BindingFlags.Instance)!;
}
private static void Place(uint id, string name, float x, float y, bool creature = true)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f);
if (creature) FakeHost.ItemTypes[id] = 0x10;
}
private static readonly (uint, string, float, float) Drudge = (A, "Drudge Skulker", 96f, 99f); // 3 m north
private static MonsterRule Default(string power = "Default", string kite = "Default") =>
new() { Name = "Default", AttackPower = power, Kite = kite };
// ── Attack power ─────────────────────────────────────────────────────────
private static void PowerDefaultsUnchanged()
{
// Auto power, no Recklessness: 100%.
var auto = new Rig(CombatMode.Melee, s => s.MonsterRules = new List<MonsterRule> { Default() }, Drudge);
Check.True(auto.ThinkToAttack(), "auto: an attack goes out");
Check.Near(auto.LastPower, 1.0, 1e-6, "auto: 100% as before");
Check.Eq(FakeHost.AttackCalls[^1].Kind, "melee", "it is a melee attack");
Check.False(FakeHost.Logs.Any(l => l.Contains("[AttackPower]")), "auto: nothing logged about a power choice");
// Auto + Use Recklessness, trained: 80% as before.
var reck = new Rig(CombatMode.Melee, s => { s.UseRecklessness = true; s.MonsterRules = new List<MonsterRule> { Default() }; }, Drudge);
reck.ThinkToAttack();
Check.Near(reck.LastPower, 0.8, 1e-6, "auto + Use Recklessness (trained): 80% as before");
// A set power: that power.
var set = new Rig(CombatMode.Melee, s => { s.MeleeAttackPower = 65; s.MonsterRules = new List<MonsterRule> { Default() }; }, Drudge);
set.ThinkToAttack();
Check.Near(set.LastPower, 0.65, 1e-6, "a set Melee Power: that power");
// No rules at all: the same.
var none = new Rig(CombatMode.Melee, s => { s.MeleeAttackPower = 40; s.MonsterRules = new List<MonsterRule>(); }, Drudge);
none.ThinkToAttack();
Check.Near(none.LastPower, 0.4, 1e-6, "no rules: the global setting");
// A new rule and a saved-before one are Default.
Check.Eq(new MonsterRule().AttackPower, "Default", "a new rule is Default power");
Check.Eq(new MonsterRule().Kite, "Default", "a new rule is Default kite");
Check.Eq(JsonSerializer.Deserialize("{\"Name\":\"Old\"}", RynthAiJsonContext.Default.MonsterRule)!.AttackPower, "Default", "a rule saved before loads as Default power");
}
private static void PowerReachesAttack()
{
Rig R(MonsterRule rule, MonsterRule? def = null, Action<LegacyUiSettings>? more = null) =>
new(CombatMode.Melee, s => { s.MonsterRules = new List<MonsterRule> { def ?? Default(), rule }; more?.Invoke(s); }, Drudge);
var high = R(new MonsterRule { Name = "Drudge Skulker", AttackPower = "High" }, more: s => s.MeleeAttackPower = 30);
high.ThinkToAttack();
Check.Near(high.LastPower, 1.0, 1e-6, "High: 100% whatever the global");
Check.True(FakeHost.Logs.Any(l => l.Contains("[AttackPower]") && l.Contains("High")), "the first attack on it is logged");
var reckless = R(new MonsterRule { Name = "Drudge Skulker", AttackPower = "Reckless" }, more: s => s.MeleeAttackPower = 30);
reckless.ThinkToAttack();
Check.Near(reckless.LastPower, 0.8, 1e-6, "Reckless: 80%");
// The DEFAULT line's choice covers a Default rule; a rule's own wins.
var viaDefault = R(new MonsterRule { Name = "Drudge Skulker" }, def: Default("Reckless"));
viaDefault.ThinkToAttack();
Check.Near(viaDefault.LastPower, 0.8, 1e-6, "a Default rule follows the DEFAULT line");
var own = R(new MonsterRule { Name = "Drudge Skulker", AttackPower = "High" }, def: Default("Reckless"));
own.ThinkToAttack();
Check.Near(own.LastPower, 1.0, 1e-6, "a rule's own choice wins over the DEFAULT line");
// Another monster's rule doesn't touch this one.
var other = R(new MonsterRule { Name = "Banderling", AttackPower = "Reckless" }, more: s => s.MeleeAttackPower = 55);
other.ThinkToAttack();
Check.Near(other.LastPower, 0.55, 1e-6, "a rule for another monster: the global power");
}
private static void PowerRespectsTraining()
{
const uint Reckl = 50; // AcSkillType.Recklessness
FakeHost.Reset();
// Trained (2) and specialized (3): the reckless band applies.
foreach (int training in new[] { 2, 3 })
{
var rig = new Rig(CombatMode.Melee, s => s.MonsterRules = new List<MonsterRule> { Default(), new MonsterRule { Name = "Drudge Skulker", AttackPower = "Reckless" } }, Drudge);
FakeHost.Skills[(Player, Reckl)] = (200, training);
rig.C.SetCharacterSkills(MakeSkills());
rig.ThinkToAttack();
Check.Near(rig.LastPower, 0.8, 1e-6, $"Reckless with Recklessness at training {training}: 80%");
}
// Untrained (1): Reckless falls back to High, Reckless + Variable to Variable.
var untrainedReckless = new Rig(CombatMode.Melee, s => s.MonsterRules = new List<MonsterRule> { Default(), new MonsterRule { Name = "Drudge Skulker", AttackPower = "Reckless" } }, Drudge);
FakeHost.Skills[(Player, Reckl)] = (10, 1);
untrainedReckless.C.SetCharacterSkills(MakeSkills());
untrainedReckless.ThinkToAttack();
Check.Near(untrainedReckless.LastPower, 1.0, 1e-6, "Reckless, Recklessness untrained: High (100%)");
Check.True(FakeHost.Logs.Any(l => l.Contains("[AttackPower]") && l.Contains("untrained")), "and the log says why");
var untrainedBoth = new Rig(CombatMode.Melee, s =>
{
s.VariablePowerMin = 30; s.VariablePowerMax = 100;
s.MonsterRules = new List<MonsterRule> { Default(), new MonsterRule { Name = "Drudge Skulker", AttackPower = "Reckless + Variable" } };
}, Drudge);
FakeHost.Skills[(Player, Reckl)] = (10, 1);
untrainedBoth.C.SetCharacterSkills(MakeSkills());
untrainedBoth.C.PowerRandom = () => 0.999;
untrainedBoth.ThinkToAttack();
Check.Near(untrainedBoth.LastPower, 1.0, 1e-6, "Reckless + Variable, untrained: plain Variable (up to Max, past the 80% band)");
// The global "Use Recklessness" with Auto power follows the training too.
var autoUntrained = new Rig(CombatMode.Melee, s => { s.UseRecklessness = true; s.MonsterRules = new List<MonsterRule> { Default() }; }, Drudge);
FakeHost.Skills[(Player, Reckl)] = (10, 1);
autoUntrained.C.SetCharacterSkills(MakeSkills());
autoUntrained.ThinkToAttack();
Check.Near(autoUntrained.LastPower, 1.0, 1e-6, "Use Recklessness, untrained, Auto power: 100% as before");
static RynthCore.Plugin.RynthAi.CharacterSkills MakeSkills()
{
var sk = new RynthCore.Plugin.RynthAi.CharacterSkills(FakeHost.Create(Player));
sk.SetPlayerId(Player);
return sk;
}
}
private static void PowerVariableRange()
{
var rig = new Rig(CombatMode.Melee, s =>
{
s.VariablePowerMin = 60; s.VariablePowerMax = 90;
s.MonsterRules = new List<MonsterRule> { Default(), new MonsterRule { Name = "Drudge Skulker", AttackPower = "Variable" } };
}, Drudge);
var draws = new Queue<double>(new[] { 0.0, 0.5, 0.999, 0.25, 0.75 });
rig.C.PowerRandom = () => draws.Count > 0 ? draws.Dequeue() : 0.5;
var seen = new List<float>();
for (int i = 0; i < 5; i++)
{
Check.True(rig.ThinkToAttack(), $"attack {i + 1} goes out");
seen.Add(rig.LastPower);
}
Check.True(seen.All(p => p >= 0.60f - 1e-6 && p <= 0.90f + 1e-6), "every attack inside 60..90%: " + string.Join(", ", seen.Select(p => p.ToString("0.00"))));
Check.True(seen.Distinct().Count() >= 4, "and it differs from attack to attack");
Check.Near(seen[0], 0.60, 1e-6, "a draw of 0 sends Min");
Check.Near(seen[2], 0.90, 1e-6, "a draw near 1 sends Max");
// Reckless + Variable stays in the 20..80 band and the range.
var both = new Rig(CombatMode.Melee, s =>
{
s.VariablePowerMin = 60; s.VariablePowerMax = 100;
s.MonsterRules = new List<MonsterRule> { Default(), new MonsterRule { Name = "Drudge Skulker", AttackPower = "Reckless + Variable" } };
}, Drudge);
both.C.PowerRandom = () => 0.999;
both.ThinkToAttack();
Check.Near(both.LastPower, 0.80, 1e-6, "Reckless + Variable: capped by the band's 80%");
both.C.PowerRandom = () => 0.0;
both.ThinkToAttack();
Check.Near(both.LastPower, 0.60, 1e-6, "Reckless + Variable: floored by the range's Min (60%)");
}
// ── Kite ─────────────────────────────────────────────────────────────────
private static void KiteFlow()
{
// Default and Off: combat attacks where the mob stands, never runs or turns away.
foreach (string kite in new[] { "Default", "Off" })
{
var rig = new Rig(CombatMode.Melee, s => s.MonsterRules = new List<MonsterRule> { Default(kite: kite) }, Drudge);
rig.ThinkToAttack();
Check.False(FakeHost.AutoRunCalls.Any(on => on), $"Kite {kite}: never autoruns");
Check.False(rig.C.KiteActive, $"Kite {kite}: not kiting");
Check.False(FakeHost.Logs.Any(l => l.Contains("[Kite]")), $"Kite {kite}: nothing logged");
}
// PullAway without tagging: runs at once, no attack while running.
var run = new Rig(CombatMode.Melee, s =>
{
s.KitePullMeters = 20; s.KiteTagFirst = false;
s.MonsterRules = new List<MonsterRule> { Default(), new MonsterRule { Name = "Drudge Skulker", Kite = "PullAway" } };
}, Drudge);
run.C.Think();
Check.True(run.C.KiteActive, "PullAway: the pull starts");
Check.True(FakeHost.AutoRun, "it autoruns");
Check.Eq(FakeHost.AttackCalls.Count, 0, "and sends no attack while it runs");
Check.True(FakeHost.Logs.Any(l => l.Contains("[Kite] pull-away start")), "logged");
Check.Near(FakeHost.HeadingDeg, 180.0, 1.0, "facing away from the mob (it is north, heading 0)");
// The mob never follows: after the no-progress time the pull gives up and combat attacks in place.
run.Now = run.Now.AddSeconds(5);
run.C.Think();
Check.False(run.C.KiteActive, "no ground gained for 4 s: the pull gives up");
Check.False(FakeHost.AutoRun, "autorun off");
Check.True(FakeHost.Logs.Any(l => l.Contains("[Kite] pull-away done") && l.Contains("no progress")), "logged as no progress");
Check.True(run.ThinkToAttack(), "and it attacks where the mob stands");
run.C.Think();
Check.False(run.C.KiteActive, "it doesn't start a second pull on the same mob");
// PullAway with Tag Before Fleeing: attacks first (aggro sticks), runs once tagged or after 2.5 s.
var tag = new Rig(CombatMode.Melee, s =>
{
s.KiteTagFirst = true;
s.MonsterRules = new List<MonsterRule> { Default(), new MonsterRule { Name = "Drudge Skulker", Kite = "PullAway" } };
}, Drudge);
Check.True(tag.ThinkToAttack(), "tag first: the attack goes out");
Check.True(tag.C.KiteActive, "... with the pull begun");
Check.False(FakeHost.AutoRun, "... and no running yet");
tag.Now = tag.Now.AddSeconds(3);
tag.C.Think();
Check.True(FakeHost.AutoRun, "after the tag window it runs");
Check.True(FakeHost.Logs.Any(l => l.Contains("fleeing (tag timed out)")), "logged as fleeing after the tag");
// Pulled far enough: the mob moves away from where it stood.
var pull = new Rig(CombatMode.Melee, s =>
{
s.KitePullMeters = 10; s.KiteTagFirst = false;
s.MonsterRules = new List<MonsterRule> { Default(), new MonsterRule { Name = "Drudge Skulker", Kite = "PullAway" } };
}, Drudge);
pull.C.Think();
Check.True(pull.C.KiteActive, "second mob: pull starts");
FakeHost.Positions[A] = (Lb | 0x1C, 96f, 112f, 0f); // dragged 13 m from where it stood
pull.Now = pull.Now.AddMilliseconds(500);
pull.C.Think();
Check.False(pull.C.KiteActive, "dragged past the pull distance: done");
Check.True(FakeHost.Logs.Any(l => l.Contains("[Kite] pull-away done") && l.Contains("pulled")), "logged as pulled");
// The macro stopping, or the target dropping, ends a pull and lets go of autorun.
var stop = new Rig(CombatMode.Melee, s =>
{
s.KiteTagFirst = false;
s.MonsterRules = new List<MonsterRule> { Default(kite: "PullAway") };
}, Drudge);
stop.C.Think();
Check.True(stop.C.KiteActive && FakeHost.AutoRun, "DEFAULT line PullAway covers every monster");
// Think stops driving it (another activity took over): the pump-thread watch lets go.
stop.Now = stop.Now.AddSeconds(2);
stop.C.PollKite();
Check.False(stop.C.KiteActive, "Think stopped driving the pull for 1.5 s: it ends");
Check.False(FakeHost.AutoRun, "autorun released");
// The macro stopping ends one too (the heartbeat sees the transition).
var macro = new Rig(CombatMode.Melee, s =>
{
s.KiteTagFirst = false;
s.MonsterRules = new List<MonsterRule> { Default(kite: "PullAway") };
}, Drudge);
macro.C.OnHeartbeat();
macro.C.Think();
Check.True(macro.C.KiteActive && FakeHost.AutoRun, "pull under way");
macro.S.IsMacroRunning = false;
macro.C.OnHeartbeat();
Check.False(macro.C.KiteActive, "macro stopped: the pull ends");
Check.False(FakeHost.AutoRun, "autorun released");
}
// ── Bridges ──────────────────────────────────────────────────────────────
private static LegacyDashboardRenderer Dash(LegacyUiSettings s)
{
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
return dash;
}
private static void KiteBridgePersisted()
{
var s = new LegacyUiSettings
{
MonsterRules = new List<MonsterRule>
{
new() { Name = "Default", Kite = "Off", AttackPower = "High" },
new() { Name = "Drudge", MatchExpression = "x", Kite = "PullAway", AttackPower = "Reckless + Variable" },
},
};
// Saved file: both choices round-trip.
string saved = JsonSerializer.Serialize(s.MonsterRules, RynthAiJsonContext.Default.MonsterRuleList);
var back = JsonSerializer.Deserialize(saved, RynthAiJsonContext.Default.MonsterRuleList)!;
Check.Eq(back[1].Kite, "PullAway", "the Kite choice is saved and loaded");
Check.Eq(back[1].AttackPower, "Reckless + Variable", "the Power choice is saved and loaded");
// An older Monsters panel (no Kite, no AttackPower in what it sends) keeps both.
var dash = Dash(s);
dash.ApplyMonstersJson("{\"rules\":[{\"Name\":\"Default\"},{\"Name\":\"Drudge\",\"MatchExpression\":\"x\",\"Priority\":3}]}");
Check.Eq(s.MonsterRules.Count, 2, "the rules were taken");
Check.Eq(s.MonsterRules[1].Priority, 3, "the panel's own edit was taken");
Check.Eq(s.MonsterRules[1].Kite, "PullAway", "an older panel can't wipe a rule's Kite");
Check.Eq(s.MonsterRules[1].AttackPower, "Reckless + Variable", "an older panel can't wipe a rule's Power");
Check.Eq(s.MonsterRules[0].Kite, "Off", "nor the DEFAULT line's");
// A panel that has the columns is believed.
dash.ApplyMonstersJson("{\"rules\":[{\"Name\":\"Default\",\"Kite\":\"Default\",\"AttackPower\":\"Default\"},{\"Name\":\"Drudge\",\"MatchExpression\":\"x\",\"Kite\":\"Off\",\"AttackPower\":\"High\"}]}");
Check.Eq(s.MonsterRules[1].Kite, "Off", "a newer panel's Kite is taken");
Check.Eq(s.MonsterRules[1].AttackPower, "High", "a newer panel's Power is taken");
Check.Eq(s.MonsterRules[0].Kite, "Default", "including a change back to Default");
// The VTank importer's rule copy keeps both.
var src = new MonsterRule { Name = "X", Kite = "PullAway", AttackPower = "Variable" };
var field = typeof(RynthCore.Plugin.RynthAi.ProfileImport.VirindiTankProfileImporter).GetMethod("CloneMonsterRule", BindingFlags.NonPublic | BindingFlags.Static);
if (field != null)
{
var clone = (MonsterRule)field.Invoke(null, new object[] { src })!;
Check.Eq(clone.Kite, "PullAway", "the importer's clone keeps Kite");
Check.Eq(clone.AttackPower, "Variable", "the importer's clone keeps Power");
}
else Check.True(false, "CloneMonsterRule not found");
}
private static void SettingsDefaults()
{
var s = new LegacyUiSettings();
Check.Eq(s.MissileEnvironmentResponse, 0, "Missile Response: Off");
Check.Eq(s.MagicEnvironmentResponse, 0, "Magic Response: Off");
Check.Eq(s.VariablePowerMin, 50, "Variable Min 50");
Check.Eq(s.VariablePowerMax, 100, "Variable Max 100");
Check.Eq(s.EnvironmentImpactLimit, 2, "Hits to trip 2");
Check.Eq(s.EnvironmentImpactWindowSec, 20, "Window 20 s");
Check.Eq(s.EnvironmentApproachMeters, 6, "Move closer by 6 m");
Check.Eq(s.EnvironmentMinDistance, 3, "Closest 3 m");
Check.Eq(s.EnvironmentSkipSec, 30, "Skip target 30 s");
Check.Eq(s.KitePullMeters, 20, "Pull distance 20 m");
Check.True(s.KiteTagFirst, "Tag before fleeing on");
Check.True(s.MonsterRules.All(r => r.Kite == "Default" && r.AttackPower == "Default"), "no stock rule asks for a power or a kite");
Check.Eq(KiteModes.Effective(new MonsterRule { Name = "Default" }, new MonsterRule { Name = "Default" }), KiteModes.Off, "Default kite on the DEFAULT line is Off");
}
private static void SettingsBridge()
{
var s = new LegacyUiSettings
{
VariablePowerMin = 40, VariablePowerMax = 90, MissileEnvironmentResponse = 2, MagicEnvironmentResponse = 3,
EnvironmentImpactLimit = 4, EnvironmentImpactWindowSec = 45, EnvironmentApproachMeters = 8, EnvironmentMinDistance = 5,
EnvironmentSkipSec = 60, KitePullMeters = 33, KiteTagFirst = false,
};
var dash = Dash(s);
// Sent to the engine face, nullable on the wire.
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!;
Check.True(sent.VariablePowerMin == 40 && sent.VariablePowerMax == 90, "Variable range sent");
Check.True(sent.MissileEnvironmentResponse == 2 && sent.MagicEnvironmentResponse == 3, "responses sent");
Check.True(sent.EnvironmentImpactLimit == 4 && sent.EnvironmentImpactWindowSec == 45 && sent.EnvironmentApproachMeters == 8
&& sent.EnvironmentMinDistance == 5 && sent.EnvironmentSkipSec == 60, "throttle numbers sent");
Check.True(sent.KitePullMeters == 33 && sent.KiteTagFirst == false, "kite settings sent");
// An engine without the rows saves without them: nothing changes.
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.True(s.VariablePowerMin == 40 && s.VariablePowerMax == 90 && s.MissileEnvironmentResponse == 2 && s.MagicEnvironmentResponse == 3, "an older engine's save leaves power and responses alone");
Check.True(s.EnvironmentImpactLimit == 4 && s.EnvironmentImpactWindowSec == 45 && s.EnvironmentSkipSec == 60, "... and the throttle numbers");
Check.True(s.KitePullMeters == 33 && !s.KiteTagFirst, "... and the kite settings");
// The same save with explicit nulls (what the engine's mirror sends for a value it never got).
dash.ApplySettingsJson("{\"PatrolOnLogin\":false,\"VariablePowerMin\":null,\"KitePullMeters\":null,\"KiteTagFirst\":null,\"MagicEnvironmentResponse\":null}");
Check.True(s.VariablePowerMin == 40 && s.KitePullMeters == 33 && !s.KiteTagFirst && s.MagicEnvironmentResponse == 3, "nulls leave the values alone");
// An engine with the rows: its values are taken, kite distance clamped.
dash.ApplySettingsJson("{\"VariablePowerMin\":10,\"VariablePowerMax\":20,\"MissileEnvironmentResponse\":1,\"KitePullMeters\":500,\"KiteTagFirst\":true,\"EnvironmentSkipSec\":15}");
Check.True(s.VariablePowerMin == 10 && s.VariablePowerMax == 20, "a newer engine's Variable range is taken");
Check.Eq(s.MissileEnvironmentResponse, 1, "its Missile Response is taken");
Check.Eq(s.KitePullMeters, 100, "the pull distance is clamped to 100");
Check.True(s.KiteTagFirst, "Tag before fleeing is taken");
Check.Eq(s.EnvironmentSkipSec, 15, "Skip target is taken");
}
// ── Environment hits: the window ─────────────────────────────────────────
private static void EnvironmentWindow()
{
var skulker = (A, "Drudge Skulker", 96f, 116f);
var slinker = (B, "Drudge Slinker", 120f, 96f);
// Two hits 25 s apart (window 20 s): the first aged out, the limit is not reached.
var r = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 2; s.EnvironmentImpactLimit = 2; s.EnvironmentImpactWindowSec = 20; }, skulker, slinker);
r.C.HandleChatForDamage(MissileLine);
r.Now = r.Now.AddSeconds(25);
r.C.HandleChatForDamage(MissileLine);
Check.False(r.C.RunEnvironmentImpact(r.Cache[unchecked((int)A)]!, 20), "two hits 25 s apart do not trip a 20 s window");
Check.Eq((uint)r.C.activeTargetId, A, "still on the Skulker");
r.Now = r.Now.AddSeconds(5);
r.C.HandleChatForDamage(MissileLine);
Check.True(r.C.RunEnvironmentImpact(r.Cache[unchecked((int)A)]!, 20), "a second hit inside the window trips it");
Check.Eq(r.C.activeTargetId, 0, "New target: the Skulker is dropped");
// Move closer, then new target: the first trip approaches, the next switches (another monster is in reach).
var c = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 3; s.EnvironmentImpactLimit = 1; s.EnvironmentApproachMeters = 6; s.EnvironmentMinDistance = 3; }, skulker, slinker);
c.C.HandleChatForDamage(MissileLine);
Check.True(c.C.RunEnvironmentImpact(c.Cache[unchecked((int)A)]!, 20), "Move closer then new: the first trip takes the tick");
Check.True(FakeHost.AutoRun && c.C.EnvironmentApproachActive, "and approaches");
Check.Eq((uint)c.C.activeTargetId, A, "keeping the target");
c.Now = c.Now.AddSeconds(1);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 102.5f, 0f);
FakeHost.Positions[Player] = FakeHost.PlayerPose;
c.C.RunEnvironmentImpact(c.Cache[unchecked((int)A)]!, 13.5);
Check.False(c.C.EnvironmentApproachActive, "the approach ends at its goal");
c.C.HandleChatForDamage(MissileLine);
Check.True(c.C.RunEnvironmentImpact(c.Cache[unchecked((int)A)]!, 13.5), "the next trip");
Check.Eq(c.C.activeTargetId, 0, "switches target after the one approach");
// The only monster in reach is never skipped, even on New target.
var one = new Rig(CombatMode.Missile, s => { s.MissileEnvironmentResponse = 2; s.EnvironmentImpactLimit = 1; s.EnvironmentMinDistance = 3; }, (A, "Drudge Skulker", 96f, 98.5f));
one.C.HandleChatForDamage(MissileLine);
Check.False(one.C.RunEnvironmentImpact(one.Cache[unchecked((int)A)]!, 2.5), "the only monster, already close: attacking on");
Check.Eq((uint)one.C.activeTargetId, A, "never skipped");
}
}

View file

@ -30,6 +30,10 @@ internal static class StuckCastTests
r.Add("stuck cast: StuckCastMs 0 turns nothing and breaks nothing; no TapJump -> Peace mode", BreakerOffAndNoJump);
r.Add("move settle: no start in the tick of a movement change; 150 ms and a clear motion queue (or 600 ms) let it go", MoveSettle);
r.Add("stuck cast: the HP failsafe's forced break jumps once and holds starts until landed", ForcedBreak);
r.Add("pacer: an emergency heal is not held by the 'too busy' latch (a refused pickup, a hung cast); a plain heal and other starts still are", EmergencyHealThroughLatch);
r.Add("pacer: an emergency heal does not wait for the movement settle, and still obeys an unanswered action in flight", EmergencyHealSkipsSettle);
r.Add("pacer: while a plain heal waits on the 'too busy' latch, a start that is no heal does not take the probe slot", HealKeepsProbeSlot);
r.Add("pacer: a 'too busy' UseDone that came while the macro was off does not latch the server as busy at the macro start", StaleUseDoneAtMacroStart);
r.Add("stuck cast: a script's cast is not jumped before ScriptCastMinBreakMs (6 s): answered at 5.5 s, no jump; RynthAi's own is jumped at 5 s", ScriptCastGetsNudgeWindow);
}
@ -81,6 +85,192 @@ internal static class StuckCastTests
private static void Run(RynthCoreHost host, long ms) { for (long s = 0; s < ms; s += 100) { _t += 100; May(host); } }
private static bool MayAs(RynthCoreHost host, string who, HealNeed heal) =>
ActionPacer.MayStart(host, who, heal, out _);
// Emergency Heal At: the heal is not held by the 'too busy' latch, whatever set it. A door/corpse use or a
// pickup the server refused (UseDone 0x1D) latched every start before, the heal included.
private static void EmergencyHealThroughLatch()
{
var host = Setup();
ActionPacer.StuckCastMs = 0;
try
{
Check.True(May(host), "free"); // the observer's baseline
Cast(host, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr); // any refused action latches the server as busy
Check.False(MayAs(host, "Loot", HealNeed.None), "a corpse use is held by the latch");
Check.False(MayAs(host, "Buff", HealNeed.Heal), "a plain heal is held too (it waits for the probe)");
Check.True(MayAs(host, "Buff", HealNeed.Emergency), "the emergency heal goes at once");
Check.True(MayAs(host, "Buff", HealNeed.Emergency), "and keeps going (not a probe slot)");
Check.False(MayAs(host, "Loot", HealNeed.None), "the latch still holds the others");
Check.True(ActionPacer.ServerBusy, "still taken as busy");
Check.True(FakeHost.Logs.Any(l => l.Contains("the emergency heal goes ahead of the server's 'too busy' answer")), "logged");
Check.True(ActionPacer.EmergencyThroughLatch >= 2, "counted");
}
finally { Done(); }
// A hung cast (no UseDone in CastMaxMs) is a latch too.
var hung = Setup();
ActionPacer.StuckCastMs = 0;
try
{
Cast(hung);
_t += ActionPacer.CastMaxMs + 100;
Check.False(MayAs(hung, "Loot", HealNeed.None), "a hung cast holds a corpse use");
Check.True(MayAs(hung, "Buff", HealNeed.Emergency), "but not the emergency heal");
}
finally { Done(); }
// The in-flight rules still apply: our own unanswered cast (inside CastMaxMs) holds even an emergency heal.
var open = Setup();
ActionPacer.StuckCastMs = 0;
try
{
Cast(open);
_t += 500;
Check.False(MayAs(open, "Buff", HealNeed.Emergency), "an unanswered cast of ours holds the heal (no result yet)");
}
finally { Done(); }
}
// The 150-600 ms wait after any movement call RynthAi sends does not delay an emergency heal.
private static void EmergencyHealSkipsSettle()
{
var host = Setup();
try
{
FakeHost.AutoRun = true;
host.SetAutoRunBy("Nav", true);
_t += 1000;
host.SetAutoRunBy("Nav", false); // nav's stop goes out this tick
Check.False(MayAs(host, "Buff", HealNeed.Heal), "a plain heal waits for the settle");
Check.False(MayAs(host, "Loot", HealNeed.None), "other starts too");
Check.True(MayAs(host, "Buff", HealNeed.Emergency), "the emergency heal does not");
FakeHost.CastBusy = 1; // the client still animates the stop
Check.False(MayAs(host, "Buff", HealNeed.Heal), "the plain heal: still held while the queue is busy");
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _, animationGate: false), "the emergency heal (animation gate off): goes");
FakeHost.CastBusy = 0;
}
finally { Done(); }
// It still waits for an action the server has not answered.
var inflight = Setup();
try
{
Cast(inflight);
_t += 100;
Check.False(MayAs(inflight, "Buff", HealNeed.Emergency), "an unanswered cast in flight: the emergency heal waits (pacing in-flight rule)");
}
finally { Done(); }
}
// The probe after a 'too busy' latch is one start per 1.5 s, doubling. A plain heal waiting on the latch gets
// it; a corpse or door use that happens to be evaluated first no longer takes it.
private static void HealKeepsProbeSlot()
{
var host = Setup();
ActionPacer.StuckCastMs = 0;
try
{
Check.True(May(host), "free"); // the observer's baseline
Cast(host, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr);
Check.False(MayAs(host, "Buff", HealNeed.Heal), "latched");
_t += ActionPacer.BusyProbeMs - 100;
Check.False(MayAs(host, "Buff", HealNeed.Heal), "the heal waits (marks it as waiting)");
_t += 100; // the probe is due
Check.False(MayAs(host, "Door", HealNeed.None), "the door use does not take the slot while a heal waits");
Check.True(MayAs(host, "Buff", HealNeed.Heal), "the heal gets the probe");
Check.False(MayAs(host, "Door", HealNeed.None), "one probe only");
}
finally { Done(); }
// No heal waiting: the first start of any kind still takes the probe (the latch is not left to the 15 s expiry).
var plain = Setup();
ActionPacer.StuckCastMs = 0;
try
{
Check.True(May(plain), "free"); // the observer's baseline
Cast(plain, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr);
Check.False(MayAs(plain, "Door", HealNeed.None), "latched");
_t += ActionPacer.BusyProbeMs;
Check.True(MayAs(plain, "Door", HealNeed.None), "no heal waiting: a door use takes the probe");
}
finally { Done(); }
// The mark goes stale: a heal that stopped asking does not hold the slot from the others.
var stale = Setup();
ActionPacer.StuckCastMs = 0;
try
{
Check.True(May(stale), "free"); // the observer's baseline
Cast(stale, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr);
Check.False(MayAs(stale, "Buff", HealNeed.Heal), "latched, a heal waited");
_t += ActionPacer.BusyProbeMs;
Check.True(MayAs(stale, "Door", HealNeed.None), "the heal has not asked for over HealWaitFreshMs: the door use takes the probe");
}
finally { Done(); }
}
// The macro was off (nothing checked UseDones); the player's own action was refused 0x1D. At the macro start the
// pacer's observer took that for a fresh answer and held every start for the probe wait.
private static void StaleUseDoneAtMacroStart()
{
var host = Setup();
ActionPacer.StuckCastMs = 0;
try
{
Check.True(May(host), "macro running: the observer's baseline");
FakeHost.UseDone(ActionPacer.TooBusyErr); // while the macro is off: a refused player action
_t += 60_000;
ActionPacer.NoteMacroStart(); // the macro is switched on
Check.True(May(host), "the stale 0x1D is not news: nothing is held");
Check.False(ActionPacer.ServerBusy, "not latched");
FakeHost.UseDone(ActionPacer.TooBusyErr); // a real refusal after the start still latches
Check.False(May(host), "a 0x1D after the start latches as before");
Check.True(ActionPacer.ServerBusy, "latched");
}
finally { Done(); }
// Control: without the macro-start note the same stale 0x1D latches (what the review found).
var ctl = Setup();
ActionPacer.StuckCastMs = 0;
try
{
Check.True(May(ctl), "baseline");
FakeHost.UseDone(ActionPacer.TooBusyErr);
_t += 60_000;
Check.False(May(ctl), "no note: held (the old behaviour)");
}
finally { Done(); }
// The plugin notes the off-to-on edge of IsMacroRunning (and only that).
var plugin = new RynthCore.Plugin.RynthAi.RynthAiPlugin();
var note = typeof(RynthCore.Plugin.RynthAi.RynthAiPlugin).GetMethod("NoteMacroForPacer",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
var edge = Setup();
ActionPacer.StuckCastMs = 0;
try
{
note.Invoke(plugin, new object[] { false });
Check.True(May(edge), "macro off: baseline");
FakeHost.UseDone(ActionPacer.TooBusyErr);
note.Invoke(plugin, new object[] { true }); // switched on
Check.True(May(edge), "off to on: the stale 0x1D is dropped");
FakeHost.UseDone(ActionPacer.TooBusyErr);
note.Invoke(plugin, new object[] { true }); // still running: no edge
Check.False(May(edge), "running on: a 0x1D is a 0x1D");
}
finally { Done(); }
}
private static void ScriptCastGetsNudgeWindow()
{
// Control: RynthAi's own cast of a spell with no learned cycle (3 s) is jumped at cycle + 2 s.