Snapshot for release 2026.10.31.4 (internal b309731)

This commit is contained in:
Tom Bohar 2026-11-01 18:47:29 -05:00
commit e73d4afb04
62 changed files with 6469 additions and 497 deletions

View file

@ -45,6 +45,7 @@ internal static class Program
TestPlanBuy();
TestPlanSell();
TestPlanNotes();
TestLooseNotesAndSplits();
TestPrices();
TestSafety();
TestVendorWillBuy();
@ -480,6 +481,89 @@ internal static class Program
Eq(p6.Kind, PlanKind.Done, "alt currency: notes kept");
}
// 2026-11-01, Master Raiden Stormcaller: a one-note stack matches the profile's Keep rule for the
// vendor's listing ("ObjectClass TradeNote, Value = 250,000"), so a loose single never reached the
// sell list and every plan split another note off. Loose singles now pay first; a split's result
// is judged from what the server did; a session that can't buy says why.
private static void TestLooseNotesAndSplits()
{
Console.WriteLine("\n-- loose notes, split results, why nothing was bought --");
var v = Vendor(buy: 0.7f, sell: 1.15f);
SellItem Note(uint id, int stack, string rule = "S: Trade Note") => new()
{
Id = id, Name = "Trade Note (250,000)", Value = 250_000 * stack, StackSize = stack, Class = AcObjectClass.TradeNote,
ItemType = 0x40000, RuleName = rule, MaxStack = 250, Wcid = 20630,
};
var tapers = new List<BuyWant> { new() { Item = L(10, "Prismatic Taper", 115, value: 100, maxStack: 5000), Amount = 36, RuleName = "B: Prismatic Tapers" } };
// The owner's profile, as RynthAi judges an identified note stack.
var keepListing = Rule("B: Trade Note (250,000)", VTankLootAction.Keep, null, Cond(7, "15"), Cond(12, "250000", "19"));
var sellNotes = Rule("S: Trade Note", VTankLootAction.Sell, null, Cond(7, "15"));
var rules = new List<VTankLootRule> { keepListing, sellNotes };
var noteFacts = new ItemFacts { Appraised = true, ObjectClass = AcObjectClass.TradeNote, ItemType = 0x40000 };
var forty = AutoVendorRules.Decide(rules, JudgeFake(noteFacts, "Trade Note (250,000)", new() { [19] = 10_000_000 }));
Check(AutoVendorRules.JudgeSell(forty).Sell, "40 notes (10,000,000): the Sell rule takes them");
var one = AutoVendorRules.Decide(rules, JudgeFake(noteFacts, "Trade Note (250,000)", new() { [19] = 250_000 }));
Eq(one.Rule?.Name, "B: Trade Note (250,000)", "one note (250,000): the listing's Keep rule matches it");
Check(!AutoVendorRules.JudgeSell(one).Sell, "so a single note is never on the sell list");
// A loose single (kept by that rule) pays before any split.
var big = Note(1, 39);
var loose = Note(2, 1, "loose note");
var p1 = AutoVendorPlanner.PlanNext(v, tapers, new List<SellItem> { big }, Pack(0), new List<SellItem> { loose });
Eq(p1.Kind, PlanKind.Sell, "a loose note is sold...");
Eq(p1.Sells.Single().Id, 2u, "...the loose one");
var p2 = AutoVendorPlanner.PlanNext(v, tapers, new List<SellItem> { big }, Pack(0), new List<SellItem>());
Eq(p2.Kind, PlanKind.Split, "none loose: split one off");
var otherNote = new SellItem { Id = 3, Name = "Trade Note (100,000)", Value = 100_000, StackSize = 1, Class = AcObjectClass.TradeNote, ItemType = 0x40000, MaxStack = 250, Wcid = 2626 };
var p3 = AutoVendorPlanner.PlanNext(v, tapers, new List<SellItem> { big }, Pack(0), new List<SellItem> { otherNote });
Eq(p3.Kind, PlanKind.Split, "a loose note of another kind doesn't stand in");
var p4 = AutoVendorPlanner.PlanNext(v, new List<BuyWant>(), new List<SellItem> { big }, Pack(0), new List<SellItem> { loose });
Eq(p4.Kind, PlanKind.Done, "nothing to buy: loose notes stay too");
// Why nothing was bought.
var p5 = AutoVendorPlanner.PlanNext(v, tapers, new List<SellItem>(), Pack(0));
Eq(p5.Kind, PlanKind.Done, "can't pay: done");
Eq(p5.Message, "can't buy 36x Prismatic Taper (rule 'B: Prismatic Tapers'): 115 pyreals each, you have 0, and nothing the profile sells is here to pay for it", "...and says why");
var p6 = AutoVendorPlanner.PlanNext(v, tapers, new List<SellItem>(), Pack(0), new List<SellItem> { loose });
Check(p6.Message.Contains("no Sell rule matches a note stack here: the loose Trade Note (250,000) (loose note) stays"), "only loose notes, no sellable note stack: says they stay");
var keepAll = new List<BuyWant> { new() { Item = L(11, "Trade Note (250,000)", 287_500, 250_000, cls: AcObjectClass.TradeNote, type: 0x40000), Amount = int.MaxValue } };
Eq(AutoVendorPlanner.PlanNext(v, keepAll, new List<SellItem>(), Pack(0)).Message, string.Empty, "a Keep (all you can afford) running out of money is no failure");
Check(AutoVendorPlanner.PlanNext(v, tapers, new List<SellItem>(), Pack(1_000_000, free: 1)).Kind == PlanKind.Done
&& AutoVendorPlanner.ExplainUnmetBuy(v, tapers, new List<SellItem>(), Pack(1_000_000, free: 1)).Contains("only 1 free main-pack slot(s)"), "no room: says so");
// Where a split went.
var sibs = new Dictionary<uint, int> { [1] = 40, [5] = 1 };
var none = new HashSet<uint>();
var made = AutoVendorSplits.Resolve(1, 40, 39, sibs, new HashSet<uint> { 9 }, new[] { (1u, 39, true), (5u, 1, true), (9u, 1, false) }, false);
Eq(made.Kind, SplitOutcomeKind.NewStack, "a create of the item: the new stack");
Eq(made.StackId, 9u, "its id");
var unread = AutoVendorSplits.Resolve(25, 100, 100, sibs, new HashSet<uint> { 9 }, new[] { (1u, 100, true), (9u, 1, false) }, false);
Eq(unread.Kind, SplitOutcomeKind.Pending, "created but the count unreadable and the source unchanged: wait");
var unreadLater = AutoVendorSplits.Resolve(25, 100, 75, sibs, new HashSet<uint> { 9 }, new[] { (1u, 75, true), (9u, 1, false) }, false);
Eq(unreadLater.Kind, SplitOutcomeKind.NewStack, "...until the source shrank by the amount");
var missed = AutoVendorSplits.Resolve(1, 40, 39, sibs, none, new[] { (1u, 39, true), (9u, 1, false) }, false);
Eq(missed.Kind, SplitOutcomeKind.NewStack, "create missed: a new id with exactly the amount");
var joined = AutoVendorSplits.Resolve(1, 40, 39, sibs, none, new[] { (1u, 39, true), (5u, 2, true) }, false);
Eq(joined.Kind, SplitOutcomeKind.JoinedStack, "no new object, a stack that was there grew: joined");
Eq(joined.StackId, 5u, "the stack it joined");
Eq(joined.StackCount, 2, "now 2");
Eq(AutoVendorSplits.Resolve(1, 40, 40, sibs, none, new[] { (1u, 40, true), (5u, 1, true) }, false).Kind, SplitOutcomeKind.Pending, "nothing yet: pending");
Eq(AutoVendorSplits.Resolve(1, 40, 40, sibs, none, new[] { (1u, 40, true), (5u, 1, true) }, true).Kind, SplitOutcomeKind.Failed, "nothing in time: failed");
Eq(AutoVendorSplits.Resolve(1, 40, 39, sibs, none, new[] { (1u, 39, true), (5u, 1, true) }, false).Kind, SplitOutcomeKind.Pending, "the source shrank but the units aren't seen yet: wait");
// A server's custom letter (a writable, so Book) is never a TradeNote.
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "15"), AcObjectClass.Book, 0x2000), Tri.No, "Book with its type read: not a TradeNote");
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "15"), AcObjectClass.Book, 0), Tri.Unknown, "type unread: still unknown");
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "42"), AcObjectClass.Book, 0x2000), Tri.Unknown, "Book may still be a Scroll");
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "29"), AcObjectClass.Misc, 0x80), Tri.Unknown, "Misc may still be a healing kit");
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "16"), AcObjectClass.Misc, 0x80), Tri.No, "Misc is never a ManaStone");
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "15"), AcObjectClass.Unknown, 0x10000000), Tri.No, "an unclassified type without the note bit: not a TradeNote");
var letterFacts = new ItemFacts { Appraised = true, ObjectClass = AcObjectClass.Book, ItemType = 0x2000 };
var letter = AutoVendorRules.Decide(rules, JudgeFake(letterFacts, "Scarlet Red Letter", new() { [19] = 5 }));
Check(letter.Rule == null && letter.Certain, "the letter: no rule matches, nothing to log");
}
private static void TestPrices()
{
Console.WriteLine("\n-- prices --");

View file

@ -21,6 +21,7 @@
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Vendor\AutoVendorRules.cs" Link="Linked\AutoVendorRules.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Vendor\AutoVendorPlanner.cs" Link="Linked\AutoVendorPlanner.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Vendor\AutoVendorSplits.cs" Link="Linked\AutoVendorSplits.cs" />
</ItemGroup>
</Project>

View file

@ -103,6 +103,8 @@ internal static unsafe class FakeHost
/// <summary>Opt-in: wires TapJump (the keyboard jump, 0xF61B); calls land in <see cref="TapJumps"/>.</summary>
public static bool TapJumpCalls;
public static int TapJumps;
/// <summary>Jumps and item moves in the order they were called ("tapjump", "jump", "move:XXXXXXXX").</summary>
public static readonly List<string> Order = new();
/// <summary>TapJump returns 0 (the client refused the jump); the call still counts in TapJumps.</summary>
public static bool TapJumpRefuse;
public static int Turns;
@ -305,7 +307,7 @@ internal static unsafe class FakeHost
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
Logs.Clear(); Chat.Clear(); ChatTypes.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(); AttackSendCalls = false; AttackCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null;
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); 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; UseObjectAccepts = true;
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
@ -894,10 +896,10 @@ internal static unsafe class FakeHost
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int JumpNonAutonomous(float extent) { Jumps++; return 1; }
private static int JumpNonAutonomous(float extent) { Jumps++; Order.Add("jump"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TapJump() { TapJumps++; return TapJumpRefuse ? 0 : 1; }
private static int TapJump() { TapJumps++; Order.Add("tapjump"); return TapJumpRefuse ? 0 : 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int CastSpell(uint target, int spellId) { if (CastRefused) { CastsRefused++; return 0; } Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); AfterCastSpell?.Invoke(); return 1; }
@ -994,7 +996,7 @@ internal static unsafe class FakeHost
private static uint GetGroundContainerId() => GroundContainer;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int MoveItemExternal(uint id, uint target, int amount) { ExternalMoves.Add((id, target, amount)); return 1; }
private static int MoveItemExternal(uint id, uint target, int amount) { ExternalMoves.Add((id, target, amount)); Order.Add($"move:{id:X8}"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SalvagePanelOpen(uint tool) => 1;

View file

@ -1,6 +1,6 @@
UTL
1
135
179
***** Melee Weapons *****
0;1;1
@ -1371,6 +1371,371 @@ true
24
leave this disabled
1
(W) No Wield (29MD)
0;1;7;2005;13;13;13;1;13
4
31
10
1.29
29
10
375
160
10
355
160
10
330
160
27
Orb|Wand|Sceptre|Staff
1
10
385
160
(W) No Wield (28MD)
0;1;7;2005;13;13;13;1;13
4
31
10
1.28
29
10
375
160
10
355
160
10
330
160
27
Orb|Wand|Sceptre|Staff
1
10
385
160
(W) No Wield (27MD)
0;1;7;2005;13;13;13;1;13
4
31
10
1.27
29
10
375
160
10
355
160
10
330
160
27
Orb|Wand|Sceptre|Staff
1
10
385
160
(W) No Wield (26MD)
0;1;7;2005;13;13;13;1;13
4
31
10
1.26
29
10
375
160
10
355
160
10
330
160
27
Orb|Wand|Sceptre|Staff
1
10
385
160
(W) No Wield (25MD)
0;1;7;2005;13;13;13;1;13
4
31
10
1.25
29
10
375
160
10
355
160
10
330
160
27
Orb|Wand|Sceptre|Staff
1
10
385
160
(W) No Wield (24MD)
0;1;7;2005;13;13;13;1;13
4
31
10
1.24
29
10
375
160
10
355
160
10
330
160
27
Orb|Wand|Sceptre|Staff
1
10
385
160
(W) No Wield (23MD)
0;1;7;2005;13;13;13;1;13
4
31
10
1.23
29
10
375
160
10
355
160
10
330
160
27
Orb|Wand|Sceptre|Staff
1
10
385
160
(W) No Wield (22MD)
0;1;7;2005;13;13;13;1;13
4
31
10
1.22
29
10
375
160
10
355
160
10
330
160
27
Orb|Wand|Sceptre|Staff
1
10
385
160
(W) No Wield (21MD)
0;1;7;2005;13;13;13;1;13
4
31
10
1.21
29
10
375
160
10
355
160
10
330
160
27
Orb|Wand|Sceptre|Staff
1
10
385
160
(W) No Wield (20MD + 4MgcD)
0;1;7;2005;5;1;13;13;13;13
4
31
9
1.2
29
11
1.04
150
27
Orb|Wand|Sceptre|Staff
1
10
375
160
10
355
160
10
330
160
10
385
160
(W) No Wield (20MD + 10MC)
0;1;7;2005;13;13;13;2005;1;13
4
31
9
1.2
29
10
375
160
10
355
160
10
330
160
10
0.1
144
27
Orb|Wand|Sceptre|Staff
1
10
385
160
(W) No Wield (Creature Cantrip)
0;1;7;2005;1;13;13;13;0;2005;13;9999
4
31
10
1.15
29
27
Orb|Wand|Sceptre|Staff
1
10
375
160
10
355
160
10
330
160
49
Major Creature|Epic Creature|Legendary Creature
10
0.5
144
10
385
160
6
true
(W) No Wield (Life Cantrip)
0;1;7;2005;1;13;13;13;0;2005;13;9999
4
31
10
1.15
29
27
Orb|Wand|Sceptre|Staff
1
10
375
160
10
355
160
10
330
160
37
Major Life|Epic Life|Legendary Life
10
0.5
144
10
385
160
6
true
(W) No Wield (Item Cantrip)
0;1;7;2005;1;13;13;13;9;2005;13;9999
4
31
10
1.15
29
27
Orb|Wand|Sceptre|Staff
1
10
375
160
10
355
160
10
330
160
46
Major Item|Epic Item|Legendary Item
Tink
1
10
0.5
144
10
385
160
6
true
(W) Orb (Healer's Heart)
0;1;7;1;9;9999
4
31
8
Orb
1
38
Adja's Gift|Incantation of Heal
1
6
true
(W) Void (OD +7)
0;1;7;2005;1
@ -1733,6 +2098,361 @@ Nether
10
355
160
0;1;9999;1
6
true
24
leave this disabled
1
(W) War (OD +7)
0;1;7;2005;1
4
31
11
1.25
152
24
Baton|Sceptre|Staff
1
(W) War (OD +6)
0;1;7;2005;1
4
31
11
1.24
152
24
Baton|Sceptre|Staff
1
(W) War (OD +5)
0;1;7;2005;1
4
31
11
1.23
152
24
Baton|Sceptre|Staff
1
(W) War (OD +4)
0;1;7;2005;1
4
31
11
1.22
152
24
Baton|Sceptre|Staff
1
(W) War (OD +3)
0;1;7;2005;1
4
31
11
1.21
152
24
Baton|Sceptre|Staff
1
(W) War (OD +2)
0;1;7;2005;1
4
31
10
1.2
152
24
Baton|Sceptre|Staff
1
(W) War (OD +1)
0;1;7;2005;1
4
31
11
1.19
152
24
Baton|Sceptre|Staff
1
(W) War (amazing 355)
0;1;7;2005;1;2005;12
4
31
11
1.17
152
24
Baton|Sceptre|Staff
1
10
1.25
29
10
355
160
(W) War (18pvm + 20md)
0;1;7;2005;1;2005
4
31
11
1.18
152
24
Baton|Sceptre|Staff
1
9
1.2
29
(W) War (18pvm + 19md)
0;1;7;2005;1;2005
4
31
11
1.18
152
24
Baton|Sceptre|Staff
1
10
1.19
29
(W) War (18pvm + 18md)
0;1;7;2005;1;2005
4
31
11
1.18
152
24
Baton|Sceptre|Staff
1
10
1.18
29
(W) War (18pvm + 17md)
0;1;7;2005;1;2005
4
31
11
1.18
152
24
Baton|Sceptre|Staff
1
10
1.17
29
(W) War (18pvm + 16md)
0;1;7;2005;1;2005
4
31
11
1.18
152
24
Baton|Sceptre|Staff
1
10
1.16
29
(W) War (18pvm + 15md)
0;1;7;2005;1;2005
4
31
11
1.18
152
24
Baton|Sceptre|Staff
1
10
1.15
29
(W) War (18pvm + 4MgcD)
0;1;7;2005;1;5
4
31
11
1.18
152
24
Baton|Sceptre|Staff
1
11
1.04
150
(W) War (20md + 4MgcD)
0;1;7;5;1;2005
4
31
11
1.04
150
24
Baton|Sceptre|Staff
1
9
1.2
29
(W) War (29MD)
0;1;7;1;2005
4
31
24
Baton|Sceptre|Staff
1
10
1.29
29
(W) War (28MD)
0;1;7;1;2005
4
31
24
Baton|Sceptre|Staff
1
10
1.28
29
(W) War (27MD)
0;1;7;1;2005
4
31
24
Baton|Sceptre|Staff
1
10
1.27
29
(W) War (26MD)
0;1;7;1;2005
4
31
24
Baton|Sceptre|Staff
1
10
1.26
29
(W) War (25MD)
0;1;7;1;2005
4
31
24
Baton|Sceptre|Staff
1
10
1.25
29
(W) War (24MD)
0;1;7;1;2005
4
31
24
Baton|Sceptre|Staff
1
10
1.24
29
(W) War (23MD)
0;1;7;1;2005
4
31
24
Baton|Sceptre|Staff
1
10
1.23
29
(W) War (22MD)
0;1;7;1;2005
4
31
24
Baton|Sceptre|Staff
1
10
1.22
29
(W) War (21MD)
0;1;7;1;2005
4
31
24
Baton|Sceptre|Staff
1
10
1.21
29
(W) War (Max 385)
0;1;7;2005;1;12
4
31
11
1.18
152
24
Baton|Sceptre|Staff
1
10
385
160
(W) War (Max 375)
0;1;7;2005;1;12
4
31
11
1.15
152
24
Baton|Sceptre|Staff
1
10
375
160
(W) War (Max 355)
0;1;7;2005;1;12
4
31
11
1.13
152
24
Baton|Sceptre|Staff
1
10
355
160
***** Salvage *****
0;1;1;9999

View file

@ -60,6 +60,8 @@ internal static class Program
VTankLootTests.Register(runner);
LootRuleMatchTests.Register(runner);
LootLateIdTests.Register(runner);
LootWandTests.Register(runner);
LootRaresModeTests.Register(runner);
LootChatLineTests.Register(runner);
LootSurveyTests.Register(runner);
PropertyDumpTests.Register(runner);
@ -119,6 +121,8 @@ internal static class Program
InstallPathsTests.Register(runner);
PetRefillTests.Register(runner);
AutoStackTests.Register(runner);
AutoVendorSplitTests.Register(runner);
AutoVendorZeroRateTests.Register(runner);
BackAwayTests.Register(runner);
ServerPluginForwardTests.Register(runner);
IgnoreMonsterTests.Register(runner);
@ -147,6 +151,7 @@ internal static class Program
DeathRecallTests.Register(runner);
InventoryAttributeFilterTests.Register(runner);
StuckCastTests.Register(runner);
KillNoticeTests.Register(runner);
PacerEdgeTests.Register(runner);
RecoveryRetryTests.Register(runner);
HpFailsafeTests.Register(runner);
@ -155,8 +160,10 @@ internal static class Program
ShieldBuffTests.Register(runner);
RebuffWhenIdleTests.Register(runner);
LootPacingTests.Register(runner);
LootJumpTests.Register(runner);
CorpseCloseTests.Register(runner);
VTankHotkeyTests.Register(runner);
FightSelectedTests.Register(runner);
OneTouchHealTests.Register(runner);
SaveFailureTests.Register(runner);
EnvironmentImpactTests.Register(runner);
@ -176,6 +183,7 @@ internal static class Program
ChoresInFightTests.Register(runner);
CommandReplyTests.Register(runner);
MonsterStatsTests.Register(runner);
MetaSaveTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,392 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Vendor;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-11-01, Master Raiden Stormcaller (Conquest): AutoVendor had to sell one Trade Note (250,000)
// to pay for Prismatic Tapers. It split one note off, saw the new stack and split again 0.3 s later:
// the profile's "B: Trade Note (250,000)" Keep rule (ObjectClass TradeNote, Value = 250,000; written
// for the vendor's listing) also matches a one-note stack, so the new stack (and any note split off
// by hand) never made the sell list. The second split went onto the first one's stack: "made no new
// stack". Now a split's result is known from the server's create (or the stack it joined), the stack
// it made is sold past the rules, loose single notes count as "already have one", one split is in
// flight at a time, and a split the vendor closed on is picked up at the next open.
//
// The manager's clock (AutoVendorManager.Clock) is moved by hand; the "server" answers in the fakes.
internal static unsafe class AutoVendorSplitTests
{
private const uint Player = 0x50000A01;
private const uint Vendor = 0x70000001; // FakeHost's open vendor id
private const uint Taper = 0x70000101; // the vendor's listing
private const uint Notes = 0x80A00001, Tapers = 0x80A00002, Letter = 0x80A00003;
private const uint NewStack = 0x80A00101, HandSingle = 0x80A00102;
private const uint NoteWcid = 20630, TaperWcid = 20631;
private const uint TypeNote = 0x00040000, TypeComp = 0x00001000, TypeWritable = 0x00002000;
private const int NoteValue = 250_000;
public static void Register(Runner r)
{
r.Add("autovendor split: the split-off note is identified and sold, never split twice, then the buy goes through", SplitOffNoteIsSold);
r.Add("autovendor split: a note split off by hand is sold before any split", HandSplitSingleIsSold);
r.Add("autovendor split: a split the vendor closed on is picked up at the next open, no second split", SplitResumesNextOpen);
r.Add("autovendor split: a split that went onto another stack is recognised, not 'made no new stack'", SplitJoinedStack);
r.Add("autovendor split: no second split while one is in flight", NoSecondSplitInFlight);
r.Add("autovendor split: a session that can't buy says why (chat and log)", CantBuySaysWhy);
r.Add("autovendor split: a custom letter is no TradeNote (no 'needs Object Class data' line)", LetterIsNoTradeNote);
}
// ── The fake vendor and server ────────────────────────────────────────────
private static int _coins;
private static uint _lastRequest;
private static readonly List<(uint Id, uint Container, int Slot, int Amount)> Splits = new();
private static readonly List<uint[]> Sells = new();
private static readonly List<(uint Id, int Amount)[]> Buys = new();
private static Action<uint, int>? _onSplit;
private static Action<uint[]>? _onSell;
private static Action<(uint Id, int Amount)[]>? _onBuy;
private static void Configure(ref RynthCoreApiNative api)
{
api.Version = Math.Max(api.Version, 82u);
api.GetVendorInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorInfoNative*, int>)&GetVendorInfo;
api.GetVendorItemsFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorItemNative*, int, int>)&GetVendorItems;
api.VendorBuyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, VendorTradeEntryNative*, int, uint>)&VendorBuy;
api.VendorSellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, uint>)&VendorSell;
api.GetVendorTradeStatusFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorTradeStatusNative*, int>)&GetVendorTradeStatus;
api.SplitStackInternalFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)&SplitStackInternal;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetVendorInfo(VendorInfoNative* info)
{
*info = default;
info->VendorId = Vendor;
info->ItemTypes = TypeNote | TypeComp | TypeWritable;
info->MaxValue = 1_000_000;
info->BuyRate = 0.7f;
info->SellRate = 1.15f;
info->PlayerCoins = _coins;
info->ItemCount = 1;
info->Flags = 1; // trading available
byte[] name = Encoding.ASCII.GetBytes("Town Vendor");
for (int i = 0; i < name.Length; i++) info->Name[i] = name[i];
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetVendorItems(VendorItemNative* items, int max)
{
if (items == null || max < 1) return 1;
items[0] = default;
items[0].ObjectId = Taper;
items[0].ItemType = TypeComp;
items[0].Amount = -1;
items[0].StackSize = 1;
items[0].MaxStackSize = 5000;
items[0].Value = 100;
items[0].UnitValue = 100;
items[0].UnitPrice = 115;
items[0].Flags = 1 | 2; // unlimited, stackable
byte[] name = Encoding.ASCII.GetBytes("Prismatic Taper");
for (int i = 0; i < name.Length; i++) items[0].Name[i] = name[i];
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint VendorBuy(uint vendor, VendorTradeEntryNative* entries, int count)
{
var list = new (uint, int)[count];
for (int i = 0; i < count; i++) list[i] = (entries[i].ObjectId, entries[i].Amount);
Buys.Add(list);
_onBuy?.Invoke(list);
return ++_lastRequest;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint VendorSell(uint vendor, uint* ids, int count)
{
var list = new uint[count];
for (int i = 0; i < count; i++) list[i] = ids[i];
Sells.Add(list);
_onSell?.Invoke(list);
return ++_lastRequest;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetVendorTradeStatus(VendorTradeStatusNative* status)
{
*status = default;
if (_lastRequest == 0) return 0;
status->RequestId = _lastRequest;
status->State = (int)VendorTradeState.Done;
status->Result = (int)VendorTradeResult.Accepted;
status->VendorId = Vendor;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SplitStackInternal(uint id, uint container, int slot, int amount)
{
Splits.Add((id, container, slot, amount));
_onSplit?.Invoke(id, amount);
return 1;
}
// ── World ─────────────────────────────────────────────────────────────────
private const string Profile =
"UTL\r\n1\r\n3\r\n" +
"B: Prismatic Tapers\r\n\r\n0;10;7;1\r\n3000\r\n4\r\n12\r\n20\r\nPrismatic Taper\r\n1\r\n" +
"B: Trade Note (250,000)\r\n\r\n0;1;7;12\r\n4\r\n15\r\n12\r\n250000\r\n19\r\n" +
"S: Trade Note\r\n\r\n0;3;7\r\n4\r\n15\r\n";
private static long _now;
private static void AddStack(uint id, string name, uint type, uint wcid, int count, int unitValue, int max, bool appraised = true)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = type;
FakeHost.Wcids[id] = wcid;
FakeHost.Containers[id] = Player;
SetCount(id, count, unitValue);
FakeHost.Ints[(id, 11)] = max;
if (appraised) FakeHost.Appraised.Add(id);
}
private static void SetCount(uint id, int count, int unitValue)
{
FakeHost.Ints[(id, 12)] = count;
FakeHost.Ints[(id, 19)] = count * unitValue;
}
private static int Count(uint id) => FakeHost.Ints.TryGetValue((id, 12), out int c) ? c : 0;
private static void Remove(uint id)
{
FakeHost.Containers.Remove(id);
FakeHost.Names.Remove(id);
}
private sealed class Rig
{
public AutoVendorManager M = null!;
public WorldObjectCache Cache = null!;
public LegacyUiSettings Settings = null!;
public string ProfilePath = string.Empty;
}
/// <summary>40 notes and 2,964 of 3,000 wanted tapers in the pack, no pyreals.</summary>
private static Rig World(bool withNotes = true)
{
FakeHost.Reset();
Splits.Clear(); Sells.Clear(); Buys.Clear();
_onSplit = null; _onSell = null; _onBuy = null;
_coins = 0; _lastRequest = 0;
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.ContentsCalls = true; // the pack walk
FakeHost.Names[Player] = "Test Trader";
FakeHost.Names[Vendor] = "Town Vendor";
if (withNotes) AddStack(Notes, "Trade Note (250,000)", TypeNote, NoteWcid, 40, NoteValue, 250);
AddStack(Tapers, "Prismatic Taper", TypeComp, TaperWcid, 2964, 100, 5000);
FakeHost.ConfigureApi = Configure;
RynthCoreHost host = FakeHost.Create(Player);
var rig = new Rig();
rig.Cache = new WorldObjectCache(host);
rig.Cache.SetPlayerId(Player);
rig.Settings = new LegacyUiSettings { AutoVendorEnabled = true, AutoVendorTestMode = false, AutoVendorShowMerchantInfo = false };
// The character folder is the first place a vendor's profile is looked for: the test's
// profile there, named for the vendor, is the one every open loads.
string charDir = Path.Combine(Program.TempRoot, "autovendor-char");
Directory.CreateDirectory(Path.Combine(charDir, AutoVendorManager.ProfileSubfolder));
rig.ProfilePath = Path.Combine(charDir, AutoVendorManager.ProfileSubfolder, "Town Vendor.utl");
File.WriteAllText(rig.ProfilePath, Profile);
rig.M = new AutoVendorManager(host, rig.Settings, rig.Cache, Player, () => charDir);
return rig;
}
/// <summary>The vendor opens (or its list is re-sent): AutoVendor starts when it isn't running.</summary>
private static void Open(Rig rig) => rig.M.OnVendorOpen(Vendor);
private static readonly FieldInfo ScanAt = typeof(WorldObjectCache).GetField("_lastDirectInventoryScan", BindingFlags.Instance | BindingFlags.NonPublic)!;
/// <summary>Moves the clock and ticks; the pack walk always reads the fakes fresh.</summary>
private static void Run(Rig rig, int ticks, long stepMs = 100)
{
for (int i = 0; i < ticks; i++)
{
_now += stepMs;
ScanAt.SetValue(rig.Cache, DateTime.MinValue);
rig.M.Tick(0);
}
}
private static void Clocked(Action body)
{
var old = AutoVendorManager.Clock;
_now = 50_000_000;
AutoVendorManager.Clock = () => _now;
try { body(); }
finally { AutoVendorManager.Clock = old; FakeHost.ConfigureApi = null; }
}
/// <summary>The server's split: a new stack of <paramref name="amount"/>, not identified yet.</summary>
private static void ServerSplitsToNewStack(Rig rig, uint source, int amount, uint newId)
{
SetCount(source, Count(source) - amount, NoteValue);
AddStack(newId, "Trade Note (250,000)", TypeNote, NoteWcid, amount, NoteValue, 250, appraised: false);
rig.M.OnCreateObject(newId);
}
/// <summary>Selling a note pays 250,000 and the note leaves the pack; a taper buy lands.</summary>
private static void ServerTrades()
{
_onSell = ids => { foreach (uint id in ids) { _coins += NoteValue * Math.Max(1, Count(id)); Remove(id); } };
_onBuy = lines => { foreach (var (id, amount) in lines) if (id == Taper) { SetCount(Tapers, Count(Tapers) + amount, 100); _coins -= 115 * amount; } };
}
// ── Tests ─────────────────────────────────────────────────────────────────
private static void SplitOffNoteIsSold() => Clocked(() =>
{
var rig = World();
ServerTrades();
_onSplit = (id, amount) => ServerSplitsToNewStack(rig, id, amount, NewStack);
Open(rig);
Run(rig, 10);
Check.Eq(Splits.Count, 1, "one split sent");
Check.Eq(Splits[0].Id, Notes, "off the 40-note stack");
Check.Eq(Splits[0].Amount, 1, "one note");
Check.True(FakeHost.Logs.Any(l => l.Contains("new stack 0x80A00101")), "the new stack is known from the server's create");
Check.True(FakeHost.IdRequests.Contains(NewStack), "the new stack is identified");
Check.Eq(Sells.Count, 0, "nothing sold before the ID");
// Still no ID: AutoVendor waits instead of splitting a second note onto the first one's stack.
Run(rig, 10);
Check.Eq(Splits.Count, 1, "no second split while the split-off note is being identified");
Check.True(FakeHost.Logs.Any(l => l.Contains("waiting for the ID of Trade Note (250,000) 0x80A00101")), "the wait is logged");
FakeHost.Appraised.Add(NewStack);
Run(rig, 20);
Check.Eq(Sells.Count, 1, "one sale");
Check.True(Sells.Count > 0 && Sells[0].SequenceEqual(new[] { NewStack }), "the split-off note, though the Keep rule matches a one-note stack");
Check.Eq(Buys.Count, 1, "then the buy");
Check.True(Buys.Count > 0 && Buys[0].SequenceEqual(new[] { (Taper, 36) }), "36 tapers: 3,000 - 2,964");
Check.Eq(Splits.Count, 1, "still one split");
Check.Eq(Count(Notes), 39, "39 notes left");
Check.False(FakeHost.Logs.Any(l => l.Contains("made no new stack") || l.Contains("made no stack")), "no split failure");
});
private static void HandSplitSingleIsSold() => Clocked(() =>
{
var rig = World();
ServerTrades();
AddStack(HandSingle, "Trade Note (250,000)", TypeNote, NoteWcid, 1, NoteValue, 250); // split off by hand
_onSplit = (id, amount) => ServerSplitsToNewStack(rig, id, amount, NewStack);
Open(rig);
Run(rig, 20);
Check.Eq(Splits.Count, 0, "no split: a single note is already there");
Check.True(Sells.Count > 0 && Sells[0].SequenceEqual(new[] { HandSingle }), "the loose note is sold");
Check.Eq(Buys.Count, 1, "and the tapers bought");
Check.Eq(Count(Notes), 40, "the 40-note stack untouched");
});
private static void SplitResumesNextOpen() => Clocked(() =>
{
var rig = World();
ServerTrades();
Open(rig);
Run(rig, 5);
Check.Eq(Splits.Count, 1, "the split was sent");
// The vendor closes before the server answers; the new stack arrives afterwards.
rig.M.OnVendorClose(Vendor);
Run(rig, 2);
ServerSplitsToNewStack(rig, Notes, 1, NewStack);
FakeHost.Appraised.Add(NewStack);
Run(rig, 5);
Check.True(FakeHost.Logs.Any(l => l.Contains("new stack 0x80A00101")), "the stack is recognised with no session running");
// Next open: the split-off note is sold, nothing split again.
Open(rig);
Run(rig, 25);
Check.Eq(Splits.Count, 1, "no second split at the next open");
Check.True(Sells.Count > 0 && Sells[0].SequenceEqual(new[] { NewStack }), "the note split off last time is sold");
Check.Eq(Buys.Count, 1, "and the buy goes through");
});
private static void SplitJoinedStack() => Clocked(() =>
{
var rig = World();
ServerTrades();
// A loose note (split off by hand) sits at the split's slot, and its ID never comes back.
AddStack(HandSingle, "Trade Note (250,000)", TypeNote, NoteWcid, 1, NoteValue, 250, appraised: false);
bool resolvedBeforeSecond = true;
_onSplit = (id, amount) =>
{
if (Splits.Count >= 2 && !FakeHost.Logs.Any(l => l.Contains("went onto stack 0x80A00102")))
resolvedBeforeSecond = false;
// The server puts the split-off units onto the stack at the slot: no new object.
SetCount(id, Count(id) - amount, NoteValue);
SetCount(HandSingle, Count(HandSingle) + amount, NoteValue);
};
Open(rig);
Run(rig, 200); // the session's ID pass and the loose note's IDs run out first (~9 s)
Check.True(Splits.Count >= 1, "the split was sent once the loose note's ID gave up");
Check.True(FakeHost.Logs.Any(l => l.Contains("waiting for the ID of Trade Note (250,000) 0x80A00102")), "it waited for that ID first");
Check.True(FakeHost.Logs.Any(l => l.Contains("no new object; the units went onto stack 0x80A00102 (now x2)")), "the joined stack is recognised");
Check.False(FakeHost.Logs.Any(l => l.Contains("made no new stack")), "not the old 'made no new stack'");
Check.True(resolvedBeforeSecond, "a later split only after the first one's result was known");
});
private static void NoSecondSplitInFlight() => Clocked(() =>
{
var rig = World();
ServerTrades();
_onSplit = null; // the server never answers
Open(rig);
Run(rig, 50); // 5 s: the split's 10 s wait is not over
Check.Eq(Splits.Count, 1, "one split in flight, no second one");
Run(rig, 60); // 11 s: the wait is over, the failure says what happened, one retry
Check.True(FakeHost.Logs.Any(l => l.Contains("changed nothing (the server didn't split it; still x40)")), "the failure names the cause");
Check.Eq(Splits.Count, 2, "a retry only after the first split's wait ended");
});
private static void CantBuySaysWhy() => Clocked(() =>
{
var rig = World(withNotes: false);
Open(rig);
Run(rig, 10);
string want = "can't buy 36x Prismatic Taper (rule 'B: Prismatic Tapers'): 115 pyreals each, you have 0";
Check.True(FakeHost.Logs.Any(l => l.Contains(want)), "the log says why");
Check.True(FakeHost.Chat.Any(l => l.Contains(want)), "so does chat");
Check.True(FakeHost.Logs.Any(l => l.Contains("AutoVendor finished: Town Vendor")), "the session end is in the log");
});
private static void LetterIsNoTradeNote() => Clocked(() =>
{
var rig = World(withNotes: false);
AddStack(Letter, "Scarlet Red Letter", TypeWritable, 99001, 1, 5, 1);
Open(rig);
Run(rig, 10);
Check.False(FakeHost.Logs.Any(l => l.Contains("Scarlet Red Letter") && l.Contains("needs Object Class data")),
"a writable is never a TradeNote: the Sell rule simply doesn't match it");
Check.Eq(Sells.Count, 0, "and it isn't sold");
});
}

View file

@ -0,0 +1,33 @@
using RynthCore.Plugin.RynthAi.Vendor;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
/// <summary>
/// AutoVendor's prices for a free vendor (buy=0 sell=0, a storage vault): 0 both ways, as the engine
/// prices it since AwfulWaffle's RynthCore PR #10, so the planner never thinks a free trade costs money.
/// </summary>
internal static class AutoVendorZeroRateTests
{
public static void Register(Runner r)
{
r.Add("autovendor prices: a zero-rate (free) vendor costs and pays 0; any rate above 0 keeps ACE's 1 floor", ZeroRatePrices);
}
private static void ZeroRatePrices()
{
var free = new VendorView { BuyRate = 0f, SellRate = 0f };
Check.Eq(AutoVendorPlanner.PlayerPays(free, isNote: false, 1), 0L, "free vendor: a 1-value stack costs 0");
Check.Eq(AutoVendorPlanner.PlayerPays(free, isNote: false, 250_000), 0L, "free vendor: a big stack costs 0");
Check.Eq(AutoVendorPlanner.PlayerPays(free, isNote: true, 250_000), 0L, "free vendor: a note costs 0");
Check.Eq(AutoVendorPlanner.VendorPays(free, isNote: false, 250_000), 0L, "free vendor: pays 0");
Check.Eq(AutoVendorPlanner.VendorPays(free, isNote: true, 250_000), 0L, "free vendor: pays 0 for a note");
var shop = new VendorView { BuyRate = 0.75f, SellRate = 1.15f };
Check.Eq(AutoVendorPlanner.PlayerPays(shop, isNote: false, 100), 115L, "rate 1.15, value 100: 115");
Check.Eq(AutoVendorPlanner.VendorPays(shop, isNote: false, 100), 75L, "rate 0.75, value 100: 75");
Check.Eq(AutoVendorPlanner.PlayerPays(shop, isNote: false, 0), 1L, "a rate above 0 keeps the 1-per-stack floor");
var tiny = new VendorView { BuyRate = 0.001f, SellRate = 0.001f };
Check.Eq(AutoVendorPlanner.VendorPays(tiny, isNote: false, 1), 1L, "rate 0.001 still floors at 1");
}
}

View file

@ -95,6 +95,7 @@ internal static class CommandReplyTests
new(null, "/ra igp NoSuchProfileHere", K.Act),
new("/ra cast 1234", "/ra cast banana", K.Act),
new("/ra targetlock off", null, K.Act),
new("/ra fightselected off", "/ra fightselected banana", K.Act),
new("/ra meleelow", null, K.Act),
new("/ra meleemid", null, K.Act),
new("/ra meleehigh", null, K.Act),
@ -125,6 +126,9 @@ internal static class CommandReplyTests
new(null, "/ra settings loadchar", K.Act),
new(null, "/ra loot add banana", K.Act),
new(null, "/ra loot why", K.Act), // nothing selected: says so
new("/ra loot mode rares", "/ra loot mode banana", K.Act),
new("/ra loot mode profile", null, K.Act),
new("/ra loot mode", null, K.Query),
new(null, "/ra lootparse", K.Act),
new(null, "/ra lootcheckinv", K.Act),
new(null, "/ra autotrade", K.Act),

View file

@ -0,0 +1,424 @@
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.ItemInfo;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// "Fight the monster I select" (2026-11-01, CombatManager.SelectedTarget.cs): a monster the
// player selects in a fight is fought first, until it dies, can't be reached, or the player
// selects another monster / deselects. The bot's own selections (ItemInfo.SelfSelect) never count.
internal static class FightSelectedTests
{
private const uint Player = 0x50000F21;
private const uint Lb = 0xA9B40000;
private const uint A = 0x80000A01, B = 0x80000A02, Boss = 0x80000A03, Far = 0x80000A04,
Npc = 0x80000A05, Corpse = 0x80000A06, Skip = 0x80000A07, Never = 0x80000A08, Pk = 0x80000A09;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("fight selected: off (the default) changes nothing", OffNoChange);
r.Add("fight selected: the player's selection of a lower-priority monster wins; another selection moves it, a deselect ends it", PlayerSelectionWins);
r.Add("fight selected: the bot's own selections never count (native attack, looter, meta)", BotSelectionNeverCounts);
r.Add("fight selected: an NPC, a corpse, a player, yourself, an ignored or never-attack monster change nothing", NonMonstersNothing);
r.Add("fight selected: the chosen monster dying returns to normal priority, quietly", DeathReturnsToNormal);
r.Add("fight selected: past Disengage Range it's said once, fought if it comes close, dropped after 30 s", OutOfRange);
r.Add("fight selected: a /ra targetlock lock is never moved; /ra targetlock on the selected one makes it explicit", TargetLockInteraction);
r.Add("fight selected: the setting off releases it; /ra fightselected, the settings face, profiles, metas", SettingPlumbing);
r.Add("fight selected: /ra why says it is fighting the monster you selected", WhySaysSo);
}
// ── Rig ───────────────────────────────────────────────────────────────────
private sealed class Rig
{
public readonly CombatManager Combat;
public readonly LegacyUiSettings S;
public readonly WorldObjectCache Cache;
public readonly RynthCoreHost Host;
private DateTime _now = DateTime.Now;
public Rig(bool on = true)
{
FakeHost.Reset();
SelfSelect.Reset();
Place(Player, "Me", 96, 96, creature: false);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
Place(A, "Mob A", 96, 98);
Place(B, "Mob B", 96, 102);
Place(Boss, "Boss", 96, 100);
Place(Far, "Far Mob", 96, 136); // 40 m: past Disengage Range (20 + 3)
Place(Skip, "Harmless Bug", 96, 99);
Place(Never, "Never Mob", 96, 99);
Place(Pk, "Someone", 96, 99);
FakeHost.Wcids[Pk] = 1; // a player's weenie, classed as a monster by the cache
Place(Npc, "Town Crier", 96, 97);
FakeHost.NotAttackable.Add(Npc);
Place(Corpse, "Corpse of Mob A", 96, 97, creature: false);
FakeHost.ItemTypes[Corpse] = 0x200;
FakeHost.Bitfields[Corpse] = 0x00002000;
FakeHost.NotAttackable.Add(Corpse);
S = new LegacyUiSettings
{
MonsterRange = 20, TargetSelection = 1 /* closest */, TargetLock = true,
IsMacroRunning = true, EnableCombat = true, FightSelectedTarget = on,
};
S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
S.MonsterRules.Add(new MonsterRule { Name = "Harmless Bug", Priority = 0 });
var host = FakeHost.Create();
Host = host;
Cache = FakeHost.MakeCache(host, Player, new[] { A, B, Boss, Far, Skip, Never, Pk, Npc, Corpse });
Combat = new CombatManager(host, S, Cache);
Combat.SetPlayerId(Player);
Combat.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
Combat.TargetClock = () => _now;
}
public void Advance(double ms) => _now = _now.AddMilliseconds(ms);
public uint Pick(params (uint Id, double Dist)[] scan)
{
Combat.SetScannedTargetsForTests(scan.Select(t => new CombatManager.ScannedTarget
{
Id = unchecked((int)t.Id), Distance = t.Dist, Angle = 0, Bearing = double.NaN, Name = FakeHost.Names[t.Id],
}));
Combat.HandleCombatTrigger();
return unchecked((uint)Combat.activeTargetId);
}
/// <summary>The player selects <paramref name="id"/> (0 = deselect).</summary>
public string? Select(uint id) => Combat.OnSelectionChanged(id, SelfSelect.IsOurs(id));
public int Forced => Combat.ForcedTargetId;
}
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 int I(uint id) => unchecked((int)id);
// ── Tests ─────────────────────────────────────────────────────────────────
private static void OffNoChange()
{
Check.False(new LegacyUiSettings().FightSelectedTarget, "off by default");
var t = new Rig(on: false);
Check.Eq(t.Pick((A, 2), (B, 6)), A, "closest: A");
Check.Eq(t.Select(B), null, "selecting B: nothing");
Check.Eq(t.Forced, 0, "no lock");
Check.Eq(t.Pick((A, 2), (B, 6)), A, "still A");
t.Select(0);
Check.Eq(t.Pick((A, 2), (B, 6)), A, "a deselect: still A");
}
private static void PlayerSelectionWins()
{
var t = new Rig();
Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), Boss, "normal: the Boss's priority wins");
Check.Eq(t.Select(B), "locked", "the player selects B");
Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), B, "B (priority 1, farther) over the Boss and the closer A");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch") && l.Contains("fight the monster I select: selected by the player")),
"the switch line says why");
Check.Eq(t.Pick((A, 1), (B, 6), (Boss, 3)), B, "kept while the others come closer");
Check.Eq(t.Select(A), "locked", "the player selects A");
Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), A, "the lock moves to A");
Check.True(FakeHost.Logs.Any(l => l.Contains("(the player selected another monster,")), "the switch says so");
Check.Eq(t.Select(0), "deselected", "the player deselects");
Check.Eq(t.Forced, 0, "the lock is gone");
Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), Boss, "normal priority again: the Boss");
Check.True(t.Combat.ForcedBySelection == false, "and nothing forced");
Check.False(FakeHost.Chat.Any(c => c.Contains("Stopped fighting")), "no chat for a selection or a deselect");
// Only while the macro runs with Combat on.
t = new Rig();
t.S.IsMacroRunning = false;
Check.Eq(t.Select(B), null, "macro off: a selection isn't followed");
t.S.IsMacroRunning = true;
t.S.EnableCombat = false;
Check.Eq(t.Select(B), null, "Combat off: not followed either");
}
private static void BotSelectionNeverCounts()
{
var t = new Rig();
var bot = new Bot(t);
long clock = 1_000_000;
SelfSelect.Clock = () => clock;
try
{
Check.Eq(t.Pick((A, 2), (B, 6)), A, "fighting A");
// Combat's native attack (SelectAsBot), the looter, a meta: all marked before the select.
SelfSelect.SelectAsBot(t.Host, A);
bot.P.OnSelectedTargetChange(A, 0);
Check.Eq(t.Forced, 0, "the bot selecting its own target: not the player's");
SelfSelect.Mark(B); // e.g. a meta's selectitem
bot.P.OnSelectedTargetChange(B, A);
Check.Eq(t.Forced, 0, "the bot selecting another monster: not the player's");
Check.Eq(t.Pick((A, 2), (B, 6)), A, "still A");
// Several marks in a row: the earlier ones are still the bot's (not just the last).
SelfSelect.Mark(Boss);
bot.P.OnSelectedTargetChange(A, Boss);
Check.Eq(t.Forced, 0, "an earlier mark (A) is still ours after a later one (Boss)");
// The same monster selected by the player once the mark has expired.
clock += SelfSelect.WindowMs + 1;
bot.P.OnSelectedTargetChange(B, A);
Check.Eq(t.Forced, I(B), "the player's click on B (no fresh mark): followed");
Check.True(t.Combat.ForcedBySelection, "as a selection lock");
// The bot re-selecting its old target while the player's pick is pending changes nothing.
SelfSelect.SelectAsBot(t.Host, A);
bot.P.OnSelectedTargetChange(A, B);
Check.Eq(t.Forced, I(B), "the bot's native-attack re-select of A doesn't undo the player's B");
Check.Eq(t.Pick((A, 2), (B, 6)), B, "B is fought");
}
finally
{
SelfSelect.Clock = () => Environment.TickCount64;
SelfSelect.Reset();
}
}
private static void NonMonstersNothing()
{
var t = new Rig();
t.S.MonsterNameBlacklist.Add("Never Mob");
Check.True(t.Select(Npc)?.Contains("can't be attacked") == true, "an NPC: not followed");
Check.True(t.Select(Corpse)?.Contains("isn't a monster") == true, "a corpse: not followed");
Check.Eq(t.Select(Player), "that's you", "yourself: not followed");
Check.True(t.Select(Pk)?.Contains("is a player") == true, "a player (by weenie): not followed");
Check.True(t.Select(Skip)?.Contains("Priority 0") == true, "an ignored (Priority 0) monster: not followed");
Check.True(t.Select(Never)?.Contains("never-attack") == true, "a never-attack monster: not followed");
Check.Eq(t.Forced, 0, "no lock from any of them");
// With a selected monster being fought, those selections leave it alone.
t.Select(B);
Check.Eq(t.Pick((A, 2), (B, 6)), B, "fighting the selected B");
foreach (uint id in new[] { Npc, Corpse, Player, Pk, Skip, Never })
t.Select(id);
Check.Eq(t.Forced, I(B), "B is still the selected target");
Check.Eq(t.Pick((A, 2), (B, 6)), B, "and still fought");
Check.False(FakeHost.Logs.Any(l => l.Contains("fight-selected") && l.Contains("Corpse of")), "a corpse click isn't even logged");
}
private static void DeathReturnsToNormal()
{
var t = new Rig();
t.Select(B);
Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), B, "fighting the selected B");
t.Cache.OnUpdateHealth(B, 0f);
Check.Eq(t.Pick((A, 2), (Boss, 4)), Boss, "B died: normal priority, the Boss");
Check.Eq(t.Forced, 0, "the lock is over");
Check.True(FakeHost.Logs.Any(l => l.Contains("fight-selected") && l.Contains("ended: it died")), "logged");
Check.False(FakeHost.Chat.Any(c => c.Contains("Stopped fighting")), "no chat for the normal end");
// Its kill notice ends it too.
t = new Rig();
t.Select(Boss);
t.Pick((A, 2), (Boss, 4));
t.Combat.OnKillNotification("You killed Boss!");
Check.Eq(t.Pick((A, 2), (B, 6)), A, "killed: the closest again");
Check.Eq(t.Forced, 0, "and the lock is over");
}
private static void OutOfRange()
{
var t = new Rig();
Check.Eq(t.Select(Far), "far", "40 m away: past the 23 m reach");
Check.True(FakeHost.Chat.Any(c => c.Contains("Far Mob is 40 yd away, past Disengage Range (23 yd)") && c.Contains("not chasing")),
"said in chat: " + string.Join(" | ", FakeHost.Chat));
int lines = FakeHost.Chat.Count;
t.Select(0);
Check.Eq(t.Select(Far), "far", "selected again");
Check.Eq(FakeHost.Chat.Count, lines, "said once per monster");
Check.Eq(t.Pick((A, 2)), A, "not in the scan (it is never chased): A meanwhile");
t.Advance(10_000);
Check.Eq(t.Pick((A, 2), (Far, 15)), Far, "it comes within range: fought");
// Never comes close: dropped 30 s after the click, with one line.
t = new Rig();
t.Select(Far);
t.Advance(CombatManager.ForcedTargetLostMs - 1000);
Check.Eq(t.Pick((A, 2)), A, "29 s: A, the lock waits");
Check.Eq(t.Forced, I(Far), "still waiting");
t.Advance(2000);
Check.Eq(t.Pick((A, 2)), A, "31 s");
Check.Eq(t.Forced, 0, "dropped");
Check.True(FakeHost.Chat.Any(c => c.Contains("Stopped fighting the monster you selected (Far Mob): never in reach")),
"and says why: " + string.Join(" | ", FakeHost.Chat));
// Selected, deselected and selected again: the 30 s restart from the new click.
t = new Rig();
t.Select(Far);
t.Pick((A, 2));
t.Advance(25_000);
t.Select(0);
t.Pick((A, 2));
t.Select(Far);
t.Advance(10_000);
t.Pick((A, 2));
Check.Eq(t.Forced, I(Far), "35 s after the first click, 10 s after the second: still waiting");
}
private static void TargetLockInteraction()
{
// A /ra targetlock lock is never moved by a selection.
var t = new Rig();
t.Combat.SetForcedTarget(I(B));
Check.Eq(t.Select(A), null, "selecting A under a /ra targetlock lock: nothing");
Check.Eq(t.Select(0), null, "nor a deselect");
Check.Eq(t.Forced, I(B), "the lock stays on B");
Check.False(t.Combat.ForcedBySelection, "as the explicit lock");
Check.True(FakeHost.Logs.All(l => !l.Contains("fight-selected")), "and nothing logged for it");
// The commands.
t = new Rig();
var bot = new Bot(t);
FakeHost.SelectedItem = A;
bot.P.OnSelectedTargetChange(A, 0);
Check.True(t.Combat.ForcedBySelection && t.Forced == I(A), "the player selects A: fought by the setting");
bot.Ra("/ra targetlock");
Check.Eq(t.Forced, I(A), "/ra targetlock on it: still A (not released)");
Check.False(t.Combat.ForcedBySelection, "now the explicit lock");
Check.True(bot.LastChat.Contains("no longer moves it"), "chat: " + bot.LastChat);
FakeHost.SelectedItem = B;
bot.P.OnSelectedTargetChange(B, A);
Check.Eq(t.Forced, I(A), "selecting B doesn't move the explicit lock");
bot.Ra("/ra targetlock off");
Check.Eq(t.Forced, 0, "/ra targetlock off releases it");
// /ra targetlock off also ends a selection lock.
bot.P.OnSelectedTargetChange(A, B);
bot.P.OnSelectedTargetChange(B, A);
Check.True(t.Combat.ForcedBySelection && t.Forced == I(B), "selection lock on B");
bot.Ra("/ra targetlock off");
Check.Eq(t.Forced, 0, "/ra targetlock off ends the selection lock too");
// The Target Lock setting (keep the incumbent) is a different thing: it doesn't stop the switch.
t = new Rig();
t.S.TargetLock = true;
Check.Eq(t.Pick((A, 2), (B, 6)), A, "Target Lock (setting) holds A");
t.Select(B);
Check.Eq(t.Pick((A, 2), (B, 6)), B, "the player's selection still switches to B");
t.S.TargetLock = false;
t.Select(A);
Check.Eq(t.Pick((A, 2), (B, 6)), A, "Target Lock off: the same");
}
private static void SettingPlumbing()
{
// Turned off mid-fight: released on the next tick, quietly.
var t = new Rig();
t.Select(B);
Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), B, "fighting the selected B");
t.S.FightSelectedTarget = false;
Check.Eq(t.Pick((A, 2), (B, 6), (Boss, 4)), Boss, "the setting off: normal priority");
Check.Eq(t.Forced, 0, "released");
Check.False(FakeHost.Chat.Any(c => c.Contains("Stopped fighting")), "no chat line");
// /ra fightselected [on|off] (toggle without an argument); every reply says the state.
t = new Rig(on: false);
var bot = new Bot(t);
bot.Ra("/ra fightselected");
Check.True(bot.S.FightSelectedTarget, "toggle: on");
Check.True(bot.LastChat.Contains("Fight the monster I select: on"), bot.LastChat);
bot.Ra("/ra fightselected on");
Check.True(bot.S.FightSelectedTarget, "on: on");
bot.P.OnSelectedTargetChange(B, 0);
Check.True(t.Combat.ForcedBySelection, "selection followed");
bot.Ra("/ra fightselected off");
Check.False(bot.S.FightSelectedTarget, "off");
Check.Eq(t.Forced, 0, "off releases the selection lock at once");
Check.True(bot.LastChat.Contains("Fight the monster I select: off"), bot.LastChat);
bot.Ra("/ra fightselected banana");
Check.True(bot.LastChat.Contains("Usage: /ra fightselected [on|off]"), bot.LastChat);
Check.False(bot.S.FightSelectedTarget, "an unknown argument changes nothing");
// Profiles: an old profile loads it off; a profile's value is copied.
var loaded = System.Text.Json.JsonSerializer.Deserialize("{\"MonsterRange\":7}", RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(loaded != null && !loaded.FightSelectedTarget, "a profile saved before the setting loads it off");
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
var dst = new LegacyUiSettings();
copy.Invoke(null, new object[] { new LegacyUiSettings { FightSelectedTarget = true }, dst });
Check.True(dst.FightSelectedTarget, "a profile's value is copied");
string json = System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings { FightSelectedTarget = true }, RynthAiJsonContext.Default.LegacyUiSettings);
var back = System.Text.Json.JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(json.Contains("FightSelectedTarget") && back != null && back.FightSelectedTarget, "saved with the profile");
// The engine Settings face: sent; a save without the field leaves it alone.
var s = new LegacyUiSettings { FightSelectedTarget = true };
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
var sent = System.Text.Json.JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
Check.True(sent != null && sent.FightSelectedTarget == true, "sent to the engine face");
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.True(s.FightSelectedTarget, "an engine without the field leaves it alone");
dash.ApplySettingsJson("{\"FightSelectedTarget\":false}");
Check.False(s.FightSelectedTarget, "a save with it sets it");
// Metas: rasetsetting / ragetsetting.
var e = ExpressionTests.Engine(settings: s);
Check.Eq(e.Evaluate("rasetsetting[FightSelectedTarget, 1]"), "1", "meta sets it");
Check.True(s.FightSelectedTarget, "on");
Check.Eq(e.Evaluate("ragetsetting[FightSelectedTarget]"), "1", "meta reads it");
}
private static void WhySaysSo()
{
var t = new Rig();
var bot = new Bot(t);
bot.P.OnSelectedTargetChange(B, 0);
t.Pick((A, 2), (B, 6));
FakeHost.Chat.Clear();
bot.Ra("/ra why");
Check.True(bot.AllChat.Contains("fighting the monster you selected: Mob B"), "the target line: " + bot.AllChat);
Check.True(bot.AllChat.Contains("likely: fighting the monster you selected"), "the interpretation: " + bot.AllChat);
}
// ── Plugin harness ───────────────────────────────────────────────────────
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S;
public Bot(Rig t)
{
S = t.S;
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
Set("_objectCache", t.Cache);
Set("_playerId", Player);
Set("_combatManager", t.Combat);
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public void Ra(string line)
{
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
object[] args = { parts[1].ToLowerInvariant(), parts, 0 };
typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(P, args);
}
public string LastChat => FakeHost.Chat.Count > 0 ? FakeHost.Chat[^1] : "";
public string AllChat => string.Join(" | ", FakeHost.Chat);
}
}

View file

@ -0,0 +1,309 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.CreatureData;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-11-01: looting mid-fight, and lesser monsters fought while a top-priority one stood by.
// A kill notice carries only the dead monster's name. In a pack of same-named monsters two things
// matched it to the wrong one:
// - in Melee mode a dual-wield or multi-strike weapon's second hit (about 0.3 s after the first)
// was handed to the nearest other monster of that name by the spell "volley" rule, so a
// neighbour we never touched counted as hit by us;
// - some kills brought two notices 1-2 ms apart (one corpse); the second was matched to that
// neighbour.
// The neighbour was kept out of the scan for 4 s while alive: with no other monster scanned the
// arbiter gave Looting the tick (a corpse opened with the monster 3 m away), and in a mixed pack
// the top tier was empty, so a lower-priority monster was locked.
internal static class KillNoticeTests
{
private const uint Player = 0x50000F01;
private const uint Lb = 0xA9B40000;
private const uint SentryWcid = 2001, LesserWcid = 2002;
private const string Sentry = "Drumtaken Sentry";
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("kill notice (melee): a dual-wield second hit stays on the fight target, not a same-named neighbour", MeleeSecondHitStaysOnTarget);
r.Add("kill notice (melee): the fight target's notice drops it even with stale server health", MeleeKillDropsTargetNotNeighbour);
r.Add("kill notice: a second notice for the same death is an echo - no one hidden, one kill", EchoHidesNoOne);
r.Add("kill notice: a death matched by name holds combat (no looting) until confirmed or 2 s", GuessedDeathHoldsCombat);
r.Add("kill notice: the fight is over when the last monster dies - looting gets the tick", FightOverLoots);
r.Add("targeting: a top-priority monster's tier holds while its death is only a guess", GuessedDeathHoldsTier);
r.Add("targeting (melee): after a kill and its echo the same-named top priority is next, not a lesser one", EchoKeepsTopPriorityNext);
}
// ── The rig ──────────────────────────────────────────────────────────────
private sealed class Rig
{
public readonly LegacyUiSettings S = new() { MonsterRange = 10, TargetSelection = 1, TargetLock = true, EnableCombat = true };
public readonly MonsterDamageStore Store = new();
public CombatManager C = null!;
public WorldObjectCache Cache = null!;
public DateTime Now = RynthClock.Now;
private readonly List<uint> _ids = new();
private uint _next = 0x80000501;
public Rig(int mode)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true; // installs GetCurrentCombatMode
FakeHost.CombatModeValue = mode;
FakeHost.Names[Player] = "Me";
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
}
public uint Mob(string name, uint wcid, float north, float east = 0)
{
uint id = _next++;
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x1C, 96f + east, 96f + north, 0f);
FakeHost.ItemTypes[id] = 0x10;
FakeHost.Wcids[id] = wcid;
_ids.Add(id);
return id;
}
public void Build(uint fightTarget = 0)
{
var host = FakeHost.Create();
Cache = FakeHost.MakeCache(host, Player, _ids);
C = new CombatManager(host, S, Cache);
C.SetPlayerId(Player);
C.SetDamageStores(null, Store);
C.TargetClock = () => Now;
if (fightTarget != 0) C.EngageForTest(unchecked((int)fightTarget));
}
public void Rescan()
{
typeof(CombatManager).GetField("_lastScanTime", Any)!.SetValue(C, DateTime.MinValue);
C.ScanNearbyTargets();
}
public bool Scanned(uint id) => C.ScannedTargets.Any(t => t.Id == unchecked((int)id));
public bool Suppressed(uint id) => C.IsKillSuppressed(unchecked((int)id));
public int Kills(uint wcid) => Store.Snapshot().Where(r => r.Wcid == wcid).Sum(r => r.KillSamples);
/// <summary>The arbiter's pick with this combat state, a lootable corpse and a route.</summary>
public BotActivity Decide()
{
var inputs = new ArbiterInputs(true, false, S.EnableCombat && C.HasEngageableTarget, true, false, true,
combatEngaged: C.IsUnderCloseAttack);
return ActivityArbiter.Decide(in inputs);
}
}
private static int Id(uint id) => unchecked((int)id);
// ── Melee: one swing, one monster ────────────────────────────────────────
private static void MeleeSecondHitStaysOnTarget()
{
var rig = new Rig(CombatMode.Melee);
uint target = rig.Mob(Sentry, SentryWcid, 2);
uint twin = rig.Mob(Sentry, SentryWcid, 3);
rig.Build(target);
rig.Store.SetManualHp(SentryWcid, 200);
// Main hand, then off hand 0.3 s later (inside the 0.8 s volley window).
rig.C.HandleChatForDamage("You blister Drumtaken Sentry for 10 points of acid damage!");
rig.C.HandleChatForDamage("You numb Drumtaken Sentry for 12 points of cold damage!");
Check.False(rig.Cache.IsHealthEstimated(Id(twin)), "the neighbour gets no damage estimate (it was never hit)");
Check.Near(rig.Cache.GetHealthRatio(Id(twin)), -1, 1e-6, "its health stays unknown");
// The same two lines in Magic mode still go to two monsters (a ring or chain: one line each).
var magic = new Rig(CombatMode.Magic);
uint mt = magic.Mob(Sentry, SentryWcid, 2);
uint mtwin = magic.Mob(Sentry, SentryWcid, 3);
magic.Build(mt);
magic.Store.SetManualHp(SentryWcid, 200);
magic.C.HandleChatForDamage("You blast Drumtaken Sentry for 100 points with Flame Ring VI.");
magic.C.HandleChatForDamage("You blast Drumtaken Sentry for 50 points with Flame Ring VI.");
Check.True(magic.Cache.IsHealthEstimated(Id(mtwin)), "magic: the second line of a volley is the neighbour's");
}
private static void MeleeKillDropsTargetNotNeighbour()
{
var rig = new Rig(CombatMode.Melee);
uint target = rig.Mob(Sentry, SentryWcid, 2);
uint twin = rig.Mob(Sentry, SentryWcid, 3);
rig.Build(target);
rig.Cache.OnUpdateHealth(target, 0.38f); // the last health the server sent; no 0 came with the killing blow
rig.C.OnCombatDamage(40, 1, false, true);
rig.C.HandleChatForDamage("You blister Drumtaken Sentry for 40 points of acid damage!");
rig.C.HandleChatForDamage("You numb Drumtaken Sentry for 30 points of cold damage!");
rig.C.OnKillNotification("You knock Drumtaken Sentry into next Morningthaw!");
Check.Eq(rig.C.activeTargetId, 0, "the fight target is the one that died: dropped");
Check.True(rig.Suppressed(target), "and kept off the scan while its corpse forms");
Check.False(rig.Suppressed(twin), "the neighbour (never hit) is not taken for it");
Check.False(FakeHost.Logs.Any(l => l.Contains("keeping the target")), "no 'a neighbour we hit died' guess");
rig.Rescan();
Check.True(rig.Scanned(twin), "the neighbour is still a candidate");
}
// ── Two notices, one death ───────────────────────────────────────────────
private static void EchoHidesNoOne()
{
var rig = new Rig(CombatMode.Melee);
uint target = rig.Mob(Sentry, SentryWcid, 2);
uint twin = rig.Mob(Sentry, SentryWcid, 3);
rig.Build(target);
rig.C.OnCombatDamage(40, 1, false, true); // one landed hit: the kill is credited to this fight
rig.C.HandleChatForDamage("You blister Drumtaken Sentry for 40 points of acid damage!");
rig.C.OnKillNotification("You killed Drumtaken Sentry!");
rig.C.OnKillNotification("Drumtaken Sentry suffers a frozen fate!"); // the same death, 1-2 ms later
Check.False(rig.Suppressed(twin), "the echo hides no one");
Check.True(FakeHost.Logs.Any(l => l.Contains("[KillDbg] how=echo")), "it is logged as an echo");
Check.Eq(rig.Kills(SentryWcid), 1, "one death, one kill counted");
rig.Rescan();
Check.True(rig.Scanned(twin), "the live neighbour is scanned");
Check.True(rig.C.HasEngageableTarget, "combat wants the tick");
Check.Eq(rig.Decide(), BotActivity.Combat, "the arbiter keeps Combat: no looting with the neighbour 3 m away");
// Later than the echo window, a notice is a death of its own.
rig.Now = rig.Now.AddMilliseconds(KillNoticeWindow + 50);
rig.C.EngageForTest(Id(twin));
rig.C.OnCombatDamage(40, 1, false, true);
rig.C.HandleChatForDamage("You blister Drumtaken Sentry for 40 points of acid damage!");
System.Threading.Thread.Sleep((int)KillNoticeWindow + 50); // the echo window runs on RynthClock
rig.C.OnKillNotification("Drumtaken Sentry died!");
Check.Eq(rig.C.activeTargetId, 0, "the neighbour's own death later drops it");
Check.Eq(rig.Kills(SentryWcid), 2, "and counts");
}
private static double KillNoticeWindow => CombatManager.KillEchoMs;
// ── A death matched by name only ─────────────────────────────────────────
/// <summary>Magic: a ring hits the target and its twin; the target dies (health 0), then a
/// notice of that name comes that may be the twin's.</summary>
private static Rig RingKillThenGuess(out uint target, out uint twin)
{
var rig = new Rig(CombatMode.Magic);
target = rig.Mob(Sentry, SentryWcid, 2);
twin = rig.Mob(Sentry, SentryWcid, 3);
rig.Build(target);
rig.C.HandleChatForDamage("You blast Drumtaken Sentry for 100 points with Flame Ring VI.");
rig.C.HandleChatForDamage("You blast Drumtaken Sentry for 100 points with Flame Ring VI.");
rig.Cache.OnUpdateHealth(target, 0f);
rig.C.OnKillNotification("Drumtaken Sentry died!");
rig.C.OnKillNotification("Drumtaken Sentry's death is preceded by a sharp, stabbing pain!");
return rig;
}
private static void GuessedDeathHoldsCombat()
{
var rig = RingKillThenGuess(out _, out uint twin);
Check.True(rig.Suppressed(twin), "the twin was hit by the ring: the notice is taken for it");
rig.Rescan();
Check.False(rig.Scanned(twin), "it is kept off the scan for now");
Check.True(rig.C.HasTargets, "but still counts as a monster in range");
Check.True(rig.C.HasCloseThreat(RynthAiPlugin.LootStarveCloseYards), "and as a close threat (no starved loot turn)");
Check.Eq(rig.Decide(), BotActivity.Combat, "so the arbiter keeps Combat, not Looting");
// No word of its death in 2 s: it is alive, a target again.
rig.Now = rig.Now.AddMilliseconds(2100);
rig.Rescan();
Check.True(rig.Scanned(twin), "after 2 s it is scanned again");
Check.True(FakeHost.Logs.Any(l => l.Contains("matched by name") && l.Contains("still alive: it is a target again")),
"and the log says the guess was wrong");
// A hit on it ends the hold at once.
rig = RingKillThenGuess(out _, out twin);
rig.C.HandleChatForDamage("You blast Drumtaken Sentry for 80 points with Flame Ring VI.");
Check.False(rig.Suppressed(twin), "a damage line on it says it is alive");
}
private static void FightOverLoots()
{
// The guessed twin really died: its corpse (health 0) ends the hold, and the fight is over.
var rig = RingKillThenGuess(out _, out uint twin);
rig.Cache.OnUpdateHealth(twin, 0f);
rig.Rescan();
Check.False(rig.C.HasTargets, "both dead: nothing in range");
Check.False(rig.C.HasEngageableTarget, "combat lets the tick go");
Check.Eq(rig.Decide(), BotActivity.Looting, "looting gets the tick");
// A lone kill: looting right after it.
var lone = new Rig(CombatMode.Melee);
uint mob = lone.Mob(Sentry, SentryWcid, 2);
lone.Build(mob);
lone.C.OnCombatDamage(40, 1, false, true);
lone.C.OnKillNotification("You killed Drumtaken Sentry!");
lone.C.OnKillNotification("Drumtaken Sentry suffers a frozen fate!");
lone.Rescan();
Check.False(lone.C.HasEngageableTarget, "the last monster died: no combat");
Check.Eq(lone.Decide(), BotActivity.Looting, "the arbiter loots");
}
// ── Priority ─────────────────────────────────────────────────────────────
private static void UseRules(Rig rig)
=> rig.S.MonsterRules = new List<MonsterRule>
{
new MonsterRule { Name = "Default", Priority = 1 },
new MonsterRule { Name = Sentry, Priority = 5 },
};
private static void GuessedDeathHoldsTier()
{
var rig = new Rig(CombatMode.Magic);
UseRules(rig);
uint target = rig.Mob(Sentry, SentryWcid, 2);
uint twin = rig.Mob(Sentry, SentryWcid, 4);
uint lesser = rig.Mob("Drumtaken Lesser Siraluun", LesserWcid, 3);
rig.Build(target);
rig.C.HandleChatForDamage("You blast Drumtaken Sentry for 100 points with Flame Ring VI.");
rig.C.HandleChatForDamage("You blast Drumtaken Sentry for 100 points with Flame Ring VI.");
rig.Cache.OnUpdateHealth(target, 0f);
rig.C.OnKillNotification("Drumtaken Sentry died!");
rig.C.OnKillNotification("Drumtaken Sentry's death is preceded by a sharp, stabbing pain!");
rig.Rescan();
Check.True(rig.Scanned(lesser) && !rig.Scanned(twin), "the scan has only the Priority 1 monster");
rig.C.HandleCombatTrigger();
Check.Eq(rig.C.activeTargetId, 0, "the Priority 1 monster isn't locked while the Priority 5 twin may be alive");
rig.Now = rig.Now.AddMilliseconds(2100);
rig.Rescan();
rig.C.HandleCombatTrigger();
Check.Eq(rig.C.activeTargetId, Id(twin), "the twin was alive: it is the target, not the lesser one");
}
private static void EchoKeepsTopPriorityNext()
{
var rig = new Rig(CombatMode.Melee);
UseRules(rig);
uint target = rig.Mob(Sentry, SentryWcid, 2);
uint twin = rig.Mob(Sentry, SentryWcid, 4);
uint lesser = rig.Mob("Drumtaken Lesser Siraluun", LesserWcid, 3);
rig.Build(target);
rig.C.OnCombatDamage(40, 1, false, true);
rig.C.HandleChatForDamage("You blister Drumtaken Sentry for 40 points of acid damage!");
rig.C.HandleChatForDamage("You numb Drumtaken Sentry for 30 points of cold damage!");
rig.C.OnKillNotification("You killed Drumtaken Sentry!");
rig.C.OnKillNotification("Drumtaken Sentry suffers a frozen fate!");
rig.Rescan();
rig.C.HandleCombatTrigger();
Check.Eq(rig.C.activeTargetId, Id(twin), "the Priority 5 twin is next (it was 4 s out of the scan before)");
Check.True(rig.Scanned(lesser), "the lesser one was a candidate too");
}
}

View file

@ -43,6 +43,33 @@ internal static class LootAddItemTests
r.Add("loot add: unsaved edits in the Loot Editor block the add (nothing saved behind them)", BridgeRefusesUnderEdits);
r.Add("loot add: the popup says when RynthAi's built-in looting takes the item (Mana Tap, mana stones)", BuiltInReasons);
r.Add("loot: Mana Tap takes a high-mana wand like any other item (they drain)", ManaTapTakesWands);
r.Add("loot profile load (R-20261101-133624-7eeb): a rule with no conditions is named in chat; a normal profile says nothing", UnconditionalRuleWarned);
}
// A 'Trade Note' that lost its Name condition keeps every item silently; loading says so.
private static void UnconditionalRuleWarned()
{
var bot = new Bot();
string broken = Temp("broken-trade-note.utl", Utl(
"UTL", "1", "2",
"Trade Note", "", "0;1",
"Keep pyreals", "", "0;1;1", "0", "^Pyreal$", "1"));
bot.S.CurrentLootPath = broken;
FakeHost.Chat.Clear();
object?[] load = { string.Empty, null, null };
Check.True((bool)typeof(RynthAiPlugin).GetMethod("TryLoadLootProfile", Any)!.Invoke(bot.P, load)!, "it loads");
string chat = bot.ChatText;
Check.True(chat.Contains("1 rule(s) have no conditions") && chat.Contains("'Trade Note' (rule 1, Keep)") && chat.Contains("will be Keep"),
"the unconditional rule is named: " + chat);
Check.Eq(VTankLootEvaluator.FirstMatch(bot.Get<VTankLootProfile>("_loadedLootProfile")!, bot.Item(Opal), null, out _)?.Name, "Trade Note",
"and it does keep a gem (what the report showed)");
var ok = new Bot();
ok.S.CurrentLootPath = Temp("sell-gems.utl", SellGems);
FakeHost.Chat.Clear();
object?[] load2 = { string.Empty, null, null };
Check.True((bool)typeof(RynthAiPlugin).GetMethod("TryLoadLootProfile", Any)!.Invoke(ok.P, load2)!, "a normal profile loads");
Check.False(ok.ChatText.Contains("no conditions"), "and says nothing about it");
}
// ── World and plugin ──────────────────────────────────────────────────────

View file

@ -579,6 +579,13 @@ internal static class LootCorpseTests
rare.Call("NoteBoostLootKill");
combat4.HandleCombatTrigger();
Check.Eq(combat4.activeTargetId, unchecked((int)Monster), "Loot Only Rare Corpses: no wait");
// Loot Mode rares (rares and needed mana stones only): the same.
var raresMode = BoostWorld(15f, withCorpse: false, out var combat5);
raresMode.S.LootMode = RynthCore.Plugin.RynthAi.Loot.LootModes.Rares;
raresMode.Call("NoteBoostLootKill");
combat5.HandleCombatTrigger();
Check.Eq(combat5.activeTargetId, unchecked((int)Monster), "Loot Mode rares: no wait");
}
private static void BoostLootWaitEndsOnKillCorpse()

View file

@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Jump-loot: the jump is the keyboard one (TapJump, 0xF61B Jump, which ACE handles), never
// JumpNonAutonomous (0xF7C9, no handler on ACE). It goes BEFORE the move, on every pickup (a
// corpse's only match included), only with the setting on and stamina above 5.
// The loot clock (RynthAiPlugin.CorpseClock) is moved by hand here.
internal static class LootJumpTests
{
private const uint Player = 0x50000F31;
private const uint CorpseA = 0x80263100;
private const uint GemA = 0x80263101;
private const uint GemA2 = 0x80263102;
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800;
private const uint LongDescKey = 16;
private const string Me = "Test Looter";
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
public static void Register(Runner r)
{
r.Add("jump loot: two-item corpse - the keyboard jump (0xF61B) goes out before the move; never the unhandled 0xF7C9", TwoItemJumpsBeforeMove);
r.Add("jump loot: a corpse's only match jumps too (one tap jump)", SingleItemJumps);
r.Add("jump loot: the setting off sends no jump", SettingOffNoJump);
r.Add("jump loot: stamina of 5 or less sends no jump", LowStaminaNoJump);
}
private static long _now;
private static void Clocked(Action body)
{
var old = RynthAiPlugin.CorpseClock;
_now = 50_000_000;
RynthAiPlugin.CorpseClock = () => _now;
try { body(); }
finally { RynthAiPlugin.CorpseClock = old; }
}
private static void Gem(uint id)
{
FakeHost.Names[id] = "Black Opal";
FakeHost.ItemTypes[id] = ItemTypeGem;
FakeHost.Containers[id] = CorpseA;
FakeHost.Appraised.Add(id);
}
private static void World(bool secondGem)
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId
FakeHost.TapJumpCalls = true;
FakeHost.Names[Player] = Me;
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
FakeHost.Names[CorpseA] = "Corpse of Olthoi Swarm Drone";
FakeHost.ItemTypes[CorpseA] = ItemTypeContainer;
FakeHost.Strings[(CorpseA, LongDescKey)] = $"Killed by {Me}.";
FakeHost.NotAttackable.Add(CorpseA);
FakeHost.Positions[CorpseA] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
Gem(GemA);
if (secondGem) Gem(GemA2);
}
/// <summary>Opens the corpse and ticks until the first pickup's move has gone out.</summary>
private static void LootUntilFirstMove(bool jumpEnabled, bool secondGem, uint stamina)
{
World(secondGem);
var host = FakeHost.Create(Player);
var bot = new RynthAiPlugin();
var s = new LegacyUiSettings
{
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
LootJumpEnabled = jumpEnabled,
};
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(bot, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(bot, v);
Set("_dashboard", dash);
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
Set("_objectCache", cache);
Set("_playerId", Player);
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = stamina, MaxMana = 100, CurrentMana = 100 });
string profile = Path.Combine(Program.TempRoot, "loot-jump-test.json");
var p = new LootProfile { Name = "gems" };
var rule = new LootRule { Name = "Gems", Action = LootAction.Keep };
rule.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
p.Rules.Add(rule);
p.Save(profile);
s.CurrentLootPath = profile;
void Tick()
{
Set("_activity", BotActivity.Looting);
typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(bot, null);
}
foreach (uint id in secondGem ? new[] { CorpseA, GemA, GemA2 } : new[] { CorpseA, GemA }) cache.OnCreateObject(id);
cache.Tick();
Tick();
Check.True(FakeHost.Uses.Contains(CorpseA), "the corpse is opened");
FakeHost.UseDone(0);
FakeHost.GroundContainer = CorpseA;
bot.OnViewObjectContents(CorpseA);
for (int i = 0; i < 200 && FakeHost.ExternalMoves.Count == 0; i++) { _now += 20; Tick(); }
Check.True(FakeHost.ExternalMoves.Count > 0, "a gem's move is sent");
}
private static string Order() => string.Join(",", FakeHost.Order);
private static void TwoItemJumpsBeforeMove() => Clocked(() =>
{
LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u);
Check.Eq(FakeHost.Order.FirstOrDefault() ?? "", "tapjump", "the keyboard jump goes first: " + Order());
Check.True(FakeHost.Order.Count >= 2 && FakeHost.Order[1].StartsWith("move:", StringComparison.Ordinal), "then the move: " + Order());
Check.Eq(FakeHost.Jumps, 0, "never JumpNonAutonomous (0xF7C9, no handler on ACE)");
});
private static void SingleItemJumps() => Clocked(() =>
{
LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u);
Check.Eq(FakeHost.Order.FirstOrDefault() ?? "", "tapjump", "single item: the jump goes first: " + Order());
Check.True(FakeHost.Order.Count >= 2 && FakeHost.Order[1].StartsWith("move:", StringComparison.Ordinal), "single item: then the move: " + Order());
Check.Eq(FakeHost.TapJumps, 1, "single item: exactly one tap jump");
Check.Eq(FakeHost.Jumps, 0, "single item: never JumpNonAutonomous");
});
private static void SettingOffNoJump() => Clocked(() =>
{
LootUntilFirstMove(jumpEnabled: false, secondGem: true, stamina: 100u);
Check.Eq(FakeHost.TapJumps + FakeHost.Jumps, 0, "jump-loot off: no jump: " + Order());
});
private static void LowStaminaNoJump() => Clocked(() =>
{
LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 5u);
Check.Eq(FakeHost.TapJumps + FakeHost.Jumps, 0, "stamina 5: no jump: " + Order());
});
}

View file

@ -0,0 +1,442 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-31, owner: "We need a loot mode that only loots mana stones when it needs them and rares."
// Loot Mode "Rares and needed mana stones only" (LootModes.Rares): the loot profile is not used. One
// corpse, looted with LootSnob (Fixtures\lootsnob-excerpt.utl), in each mode:
// * a rare gem (its rare icon, IconUnderlay 0x06005B0C, from the create message; never identified),
// * a rare ring known by its RareId (identified),
// * a Blunt Crossbow (identified) that LootSnob's "(M) Xbow (OD +9)" keeps,
// * a gold Helm (identified) that LootSnob's "(Salv) Gold" salvages,
// * a Mana Stone, with tapping on and the keep count 5 (none in the pack: needed).
// The loot clock (CorpseClock) is moved by hand; the server lands each move in the pack at once.
internal static class LootRaresModeTests
{
private const uint Player = 0x50000D51;
private const uint Corpse = 0x80267100;
private const uint Xbow = 0x80267101, RareGem = 0x80267102, RareRing = 0x80267103, Stone = 0x80267104, Helm = 0x80267105;
private const uint PackStone = 0x80267106;
private const uint ItemTypeContainer = 0x200, ItemTypeMissile = 0x100, ItemTypeGem = 0x800, ItemTypeJewelry = 0x8,
ItemTypeArmor = 0x2, ItemTypeManaStone = 0x80000;
private const uint LongDescKey = 16;
private const string Me = "Test Hunter";
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private const long TickMs = 25;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
public static void Register(Runner r)
{
r.Add("loot rares mode: the rares and a needed mana stone are looted; the OD crossbow LootSnob keeps and the gold salvage are not", RaresModeCorpse);
r.Add("loot rares mode: a mana stone at the keep count is left (not needed), and the corpse's end line says the mode", StoneNotNeeded);
r.Add("loot rares mode: profile mode is unchanged (crossbow kept, helm salvaged, stone kept, the rares left)", ProfileModeUnchanged);
r.Add("loot rares mode: a rare needs no ID (rare icon) or is known by its RareId; Mana Tap takes nothing", NoIdNoTap);
r.Add("loot rares mode: the loot details line names the reason (rare, mana stone (needed))", DetailsLineNamesReason);
r.Add("loot rares mode: the setting round trip (profile file, profile switch, engine face, meta LootMode)", SettingRoundTrip);
r.Add("loot rares mode: /ra loot mode replies with the mode, or why not and the usage; /ra loot why gives the mode's verdict", Commands);
r.Add("loot rares mode: the dashboard's LOOT line and the status say the mode", ShowsTheMode);
}
// ── Clock and world ───────────────────────────────────────────────────────
private static long _now;
private static void Clocked(Action body)
{
var old = RynthAiPlugin.CorpseClock;
_now = 70_000_000;
RynthAiPlugin.CorpseClock = () => _now;
try { body(); }
finally { RynthAiPlugin.CorpseClock = old; }
}
private static void World(bool stoneInPack)
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId
FakeHost.ContentsCalls = true; // GetContainerContents: the stone count walks the pack
FakeHost.Names[Player] = Me;
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
FakeHost.Names[Corpse] = "Corpse of Olthoi Swarm Drone";
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
FakeHost.NotAttackable.Add(Corpse);
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
// The crossbow, identified: LootSnob's (M) Xbow (OD +9) keeps it (as in LootLateIdTests).
Item(Xbow, "Blunt Crossbow", ItemTypeMissile, Corpse, appraised: true);
foreach (var (k, v) in new (uint, int)[] { (1, 0x100), (9, 0x00400000), (19, 12000), (5, 600), (131, 60),
(105, 6), (353, 9), (158, 2), (159, 47), (160, 385), (204, 22), (45, 4), (48, 47) })
FakeHost.Ints[(Xbow, k)] = v;
FakeHost.Doubles[(Xbow, 63)] = 2.62;
FakeHost.Doubles[(Xbow, 29)] = 1.15;
FakeHost.SpellIds[Xbow] = new[] { (uint)SpellDatabase.GetIdByName("Legendary Blood Thirst") };
// Mana on it (an ID shows it): Mana Tap would take it in rares mode if Mana Tap were on there.
FakeHost.Ints[(Xbow, 107)] = 4000;
// A rare gem as the create message shows it: its rare icon plate, no ID.
Item(RareGem, "Pearl of Spirit Drinking", ItemTypeGem, Corpse, appraised: false);
FakeHost.DataIds[(RareGem, RareItems.IconUnderlayKey)] = 0x06005B0C;
// A rare known by its RareId (identified), without the icon plate.
Item(RareRing, "Ring of Fortitude", ItemTypeJewelry, Corpse, appraised: true);
FakeHost.Ints[(RareRing, RareItems.RareIdKey)] = 30183;
// A gold helm, identified: LootSnob's (Salv) Gold salvages it.
Item(Helm, "Helm", ItemTypeArmor, Corpse, appraised: true);
foreach (var (k, v) in new (uint, int)[] { (131, 60), (105, 6), (19, 900), (5, 300) })
FakeHost.Ints[(Helm, k)] = v;
Item(Stone, "Mana Stone", ItemTypeManaStone, Corpse, appraised: true);
FakeHost.Ints[(Stone, 107)] = 0;
if (stoneInPack)
{
Item(PackStone, "Mana Stone", ItemTypeManaStone, Player, appraised: true);
FakeHost.Ints[(PackStone, 107)] = 0;
}
}
private static void Item(uint id, string name, uint type, uint container, bool appraised)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = type;
FakeHost.Containers[id] = container;
if (appraised) FakeHost.Appraised.Add(id);
}
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new()
{
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
LootAssessWindowMs = 200, LootCorpseTimeoutMs = 12_000,
EnableManaTapping = true, ManaTapMinMana = 2500, ManaStoneKeepCount = 5,
};
public readonly WorldObjectCache Cache;
public readonly RynthCoreHost Host;
public readonly LegacyDashboardRenderer Dash;
private int _seenMoves;
public Bot(RynthCoreHost host, int mode)
{
Host = host;
S.LootMode = mode;
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
Dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(Dash, S);
Set("_dashboard", Dash);
Cache = new WorldObjectCache(host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
Set("_manaStoneManager", new ManaStoneManager(host, S, Cache));
VTankLootProfile p = VTankLootParser.Load(Path.Combine(AppContext.BaseDirectory, "Fixtures", "lootsnob-excerpt.utl"));
string path = Path.Combine(Program.TempRoot, "loot-rares-mode.utl");
File.WriteAllText(path, VTankLootWriter.Serialize(p));
S.CurrentLootPath = path;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
public void Tick()
{
_now += TickMs;
Set("_activity", BotActivity.Looting);
Call("TickCorpseOpening");
while (_seenMoves < FakeHost.ExternalMoves.Count)
{
var m = FakeHost.ExternalMoves[_seenMoves++];
FakeHost.Containers[m.Id] = m.Target;
}
}
public void Create(params uint[] ids)
{
foreach (uint id in ids) Cache.OnCreateObject(id);
for (int i = 0; i < 5; i++) Cache.Tick();
}
public void Ra(string line)
{
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
int eat = 0;
object[] args = { parts[1].ToLowerInvariant(), parts, eat };
typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(P, args);
}
public (bool Taken, string Action, string Rule, string BuiltIn) Classify(uint id)
{
MethodInfo m = typeof(RynthAiPlugin).GetMethod("ClassifyLootItem", Any)!;
object?[] args = { Cache[unchecked((int)id)]!, S, true, null, null, null, null };
bool taken = (bool)m.Invoke(P, args)!;
return (taken, (string)args[3]!, (string)args[5]!, (string)args[6]!);
}
public bool CorpseDone => Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)Corpse));
}
private static bool Said(string part) => FakeHost.Chat.Any(l => l.Contains(part, StringComparison.Ordinal));
private static string ChatDump() => string.Join(" | ", FakeHost.Chat);
private static bool Moved(uint id) => FakeHost.ExternalMoves.Any(m => m.Id == id && m.Target == Player);
private static readonly uint[] OnCorpse = { Xbow, RareGem, RareRing, Helm, Stone };
/// <summary>Opens the corpse (the server's ViewContents) and loots it to its end.</summary>
private static Bot LootCorpse(int mode, bool stoneInPack = false, Action<Bot>? setUp = null)
{
World(stoneInPack);
var host = FakeHost.Create(Player);
var bot = new Bot(host, mode);
setUp?.Invoke(bot);
var ids = new List<uint> { Corpse };
ids.AddRange(OnCorpse);
if (stoneInPack) ids.Add(PackStone);
bot.Create(ids.ToArray());
long end = _now + 30_000;
bool opened = false;
while (_now < end && !bot.CorpseDone)
{
bot.Tick();
if (!opened && FakeHost.Uses.Contains(Corpse))
{
opened = true;
FakeHost.UseDone(0);
FakeHost.GroundContainer = Corpse;
bot.P.OnViewObjectContents(Corpse);
bot.P.OnUpdateObjectInventory(Corpse);
}
}
Check.True(opened, "the corpse is opened (rares mode still opens corpses)");
Check.True(bot.CorpseDone, "the corpse is finished");
return bot;
}
// ── Tests ─────────────────────────────────────────────────────────────────
private static void RaresModeCorpse() => Clocked(() =>
{
LootCorpse(LootModes.Rares);
Check.True(Moved(RareGem), $"the rare gem is looted ({ChatDump()})");
Check.True(Moved(RareRing), "the rare ring (RareId) is looted");
Check.True(Moved(Stone), "the mana stone is looted: none in the pack, keep count 5");
Check.False(Moved(Xbow), "the OD crossbow LootSnob keeps is NOT looted (the profile isn't used)");
Check.False(Moved(Helm), "the gold helm LootSnob salvages is NOT looted");
Check.True(Said("Loot rule: Pearl of Spirit Drinking -> [Keep] Rares mode: rare"), "the pickup says why: a rare");
Check.True(Said("Loot rule: Mana Stone -> [Keep] Rares mode: mana stone (needed)"), "and: a needed mana stone");
Check.False(Said("(M) Xbow"), "no LootSnob rule is named");
Check.False(Said("(Salv) Gold"), "nor its salvage rule");
});
private static void StoneNotNeeded() => Clocked(() =>
{
LootCorpse(LootModes.Rares, stoneInPack: true, bot =>
{
bot.S.ManaStoneKeepCount = 1;
FakeHost.DataIds.Remove((RareGem, RareItems.IconUnderlayKey)); // no rares this time
FakeHost.Ints.Remove((RareRing, RareItems.RareIdKey));
});
Check.False(Moved(Stone), $"the stone is left: one in the pack, keep count 1 ({ChatDump()})");
Check.True(Said("Mana stone match: 'Mana Stone' (have 1/1) — at cap, leaving."), "and said, as in profile mode");
Check.False(OnCorpse.Any(Moved), "nothing else is looted");
Check.True(Said("[RynthAi] Nothing to loot on Corpse of Olthoi Swarm Drone: 1 item(s) match, but you already have enough."),
"the end line: the stone matched, you have enough");
// With no stone either, the end line names the mode.
LootCorpse(LootModes.Rares, stoneInPack: true, bot =>
{
bot.S.ManaStoneKeepCount = 1;
bot.S.EnableManaTapping = false; // no ManaStone rules, tapping off: no stone is a mana stone to keep
FakeHost.DataIds.Remove((RareGem, RareItems.IconUnderlayKey));
FakeHost.Ints.Remove((RareRing, RareItems.RareIdKey));
});
Check.False(OnCorpse.Any(Moved), "nothing looted");
Check.True(Said("[RynthAi] Nothing on Corpse of Olthoi Swarm Drone is a rare or a needed mana stone (Loot Mode: rares)."),
$"the end line says the mode ({ChatDump()})");
});
private static void ProfileModeUnchanged() => Clocked(() =>
{
LootCorpse(LootModes.Profile);
Check.True(Moved(Xbow), $"the crossbow is kept by LootSnob ({ChatDump()})");
Check.True(Said("Loot rule: Blunt Crossbow -> [Keep] (M) Xbow (OD +9)"), "by its (M) Xbow (OD +9) rule");
Check.True(Moved(Helm), "the gold helm is taken");
Check.True(Said("Loot rule: Helm -> [Salvage] (Salv) Gold"), "for LootSnob's (Salv) Gold");
Check.True(Moved(Stone), "the mana stone is kept by the built-in stone rule");
Check.True(Said("Loot rule: Mana Stone -> [Keep] ManaStone (Consumable, 1/5)"), "under its old label");
Check.False(Moved(RareGem), "the rare gem: no LootSnob rule takes it, so profile mode leaves it, as before");
Check.False(Said("Rares mode"), "nothing says rares mode");
});
private static void NoIdNoTap() => Clocked(() =>
{
World(stoneInPack: false);
// An empty stone in the pack: Mana Tap (profile mode) would loot a 4,000-mana item to drain.
Item(PackStone, "Mana Stone", ItemTypeManaStone, Player, appraised: true);
FakeHost.Ints[(PackStone, 107)] = 0;
var host = FakeHost.Create(Player);
var bot = new Bot(host, LootModes.Rares);
bot.Create(Corpse, Xbow, RareGem, RareRing, Helm, Stone, PackStone);
var gem = bot.Classify(RareGem);
Check.True(gem.Taken && gem.Action == "Keep" && gem.Rule == LootModes.RareRule, $"the rare gem, never identified: [{gem.Action}] {gem.Rule}");
Check.True(gem.BuiltIn.StartsWith("a rare (rare icon)", StringComparison.Ordinal), "known by its rare icon: " + gem.BuiltIn);
var ring = bot.Classify(RareRing);
Check.True(ring.Taken && ring.BuiltIn.StartsWith("a rare (RareId 30183)", StringComparison.Ordinal), "the ring by its RareId: " + ring.BuiltIn);
Check.False((bool)bot.Call("ItemNeedsAppraisalForLoot", bot.Cache[unchecked((int)RareGem)]!)!, "rares mode asks for no ID");
Check.False((bool)bot.Call("ItemNeedsAppraisalForLoot", bot.Cache[unchecked((int)Helm)]!)!, "for any item");
var xbow = bot.Classify(Xbow);
Check.False(xbow.Taken, $"the 4,000-mana crossbow is not a Mana Tap pickup in rares mode: [{xbow.Action}] {xbow.Rule}");
Check.True(xbow.BuiltIn.StartsWith("not a rare or a mana stone", StringComparison.Ordinal), "and says why: " + xbow.BuiltIn);
var stone = bot.Classify(Stone);
Check.True(stone.Taken && stone.Rule == LootModes.StoneRule, $"the stone: 1 in the pack, keep count 5: [{stone.Action}] {stone.Rule}");
Check.True(stone.BuiltIn.StartsWith("a needed mana stone, 1 of 5 kept", StringComparison.Ordinal), stone.BuiltIn);
// Profile mode, same world: no LootSnob rule takes the 4,000-mana ring, so Mana Tap does.
FakeHost.Ints[(RareRing, 107)] = 4000;
bot.S.LootMode = LootModes.Profile;
var tap = bot.Classify(RareRing);
Check.True(tap.Taken && tap.Action == "ManaTap", $"profile mode: Mana Tap as before: [{tap.Action}] {tap.Rule}");
bot.S.LootMode = LootModes.Rares;
Check.Eq(bot.Classify(RareRing).Action, "Keep", "rares mode: the same ring is kept as a rare, not drained");
});
private static void DetailsLineNamesReason() => Clocked(() =>
{
LootCorpse(LootModes.Rares, setUp: bot => bot.S.ItemInfoSettings.LootChat = true);
Check.True(Said("[RynthAi] Looted [Keep] Pearl of Spirit Drinking (Rares mode: rare)"), $"the rare's line ({ChatDump()})");
Check.True(Said("[RynthAi] Looted [Keep] Mana Stone (Rares mode: mana stone (needed))"), "the stone's line");
Check.False(Said("rule \"Rares mode"), "shown as the reason, not as a rule name");
});
private static void SettingRoundTrip()
{
// The settings profile file.
var ctx = RynthAiJsonContext.Default.LegacyUiSettings;
var back = JsonSerializer.Deserialize(JsonSerializer.Serialize(new LegacyUiSettings { LootMode = LootModes.Rares }, ctx), ctx);
Check.Eq(back?.LootMode, LootModes.Rares, "saved and loaded with the settings profile");
var old = JsonSerializer.Deserialize("{\"EnableLooting\":true}", ctx);
Check.Eq(old?.LootMode, LootModes.Profile, "a profile saved before it loads as Profile");
// A profile switch copies it.
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
var dst = new LegacyUiSettings();
copy.Invoke(null, new object[] { new LegacyUiSettings { LootMode = LootModes.Rares }, dst });
Check.Eq(dst.LootMode, LootModes.Rares, "a profile switch copies it");
Check.True(!LootModes.IsRares(7) && LootModes.Clamp(7) == LootModes.Profile, "an unknown value reads as Profile");
// The engine's Settings face: sent; a save without it leaves it alone.
var s = new LegacyUiSettings { LootMode = LootModes.Rares };
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
Check.True(sent?.LootMode == LootModes.Rares, "sent to the engine face");
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.Eq(s.LootMode, LootModes.Rares, "a save without it leaves it alone");
dash.ApplySettingsJson("{\"LootMode\":0}");
Check.Eq(s.LootMode, LootModes.Profile, "a save with 0 sets Profile");
// The meta settings map (setsetting / getsetting LootMode).
var live = new LegacyUiSettings();
var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic();
Check.True(map.TryGetValue("LootMode", out var entry), "LootMode is in the meta settings map");
Check.Eq(entry.Get(), "0", "reads 0 (Profile)");
entry.Set("1");
Check.Eq(live.LootMode, LootModes.Rares, "1 sets rares");
Check.Eq(entry.Get(), "1", "and reads 1");
entry.Set("profile");
Check.Eq(live.LootMode, LootModes.Profile, "the word 'profile' works too");
entry.Set("rares");
Check.Eq(live.LootMode, LootModes.Rares, "and 'rares'");
entry.Set("banana");
Check.Eq(live.LootMode, LootModes.Rares, "anything else changes nothing");
}
private static void Commands() => Clocked(() =>
{
World(stoneInPack: false);
var host = FakeHost.Create(Player);
var bot = new Bot(host, LootModes.Profile);
bot.Create(Corpse, Xbow, RareGem, RareRing, Helm, Stone);
FakeHost.Chat.Clear();
bot.Ra("/ra loot mode rares");
Check.Eq(bot.S.LootMode, LootModes.Rares, "/ra loot mode rares sets it");
Check.True(Said("[RynthAi] Loot Mode: Rares and needed mana stones only (mana stones up to the keep count, 5; the loot profile loot-rares-mode.utl is not used)."),
"and replies with the mode now: " + ChatDump());
FakeHost.Chat.Clear();
bot.Ra("/ra loot mode");
Check.True(Said("[RynthAi] Loot Mode: Rares and needed mana stones only") && Said("Usage: /ra loot mode profile|rares"),
"no word: says the mode now, and the usage: " + ChatDump());
FakeHost.Chat.Clear();
bot.Ra("/ra loot mode banana");
Check.Eq(bot.S.LootMode, LootModes.Rares, "a wrong word changes nothing");
Check.True(Said("[RynthAi] loot mode: 'banana'? Loot Mode is still Rares and needed mana stones only") && Said("Usage: /ra loot mode profile|rares"),
"it says why, the mode now and the usage: " + ChatDump());
// /ra loot why: the mode's verdict.
FakeHost.SelectedItem = Xbow;
FakeHost.Chat.Clear();
bot.Ra("/ra loot why");
Check.True(Said("[RynthAi] Loot why: 'Blunt Crossbow' (identified) -> left (not a rare or a mana stone (Loot Mode: rares and needed mana stones only)")
&& Said("Loot Mode: Rares and needed mana stones only"), "the crossbow: left, by the mode: " + ChatDump());
FakeHost.SelectedItem = RareGem;
FakeHost.Chat.Clear();
bot.Ra("/ra loot why");
Check.True(Said("[RynthAi] Loot why: 'Pearl of Spirit Drinking' (not identified yet) -> [Keep] Rares mode: rare (a rare (rare icon)"),
"the rare gem: kept as a rare: " + ChatDump());
FakeHost.Chat.Clear();
bot.Ra("/ra loot mode profile");
Check.Eq(bot.S.LootMode, LootModes.Profile, "/ra loot mode profile sets it back");
Check.True(Said("[RynthAi] Loot Mode: Profile (the loot profile)."), "and replies: " + ChatDump());
FakeHost.SelectedItem = Xbow;
FakeHost.Chat.Clear();
bot.Ra("/ra loot why");
Check.True(Said("-> [Keep] (M) Xbow (OD +9)"), "profile mode's loot why, as before: " + ChatDump());
});
private static void ShowsTheMode()
{
FakeHost.Reset();
var host = FakeHost.Create(Player);
var bot = new Bot(host, LootModes.Profile);
Check.Eq(bot.Dash.LootLineName(), "loot-rares-mode", "profile mode: the LOOT line is the profile's name");
bot.S.LootMode = LootModes.Rares;
Check.Eq(bot.Dash.LootLineName(), "Rares + needed mana stones (loot-rares-mode not used)", "rares mode: the LOOT line says so");
bot.S.CurrentLootPath = string.Empty;
Check.Eq(bot.Dash.LootLineName(), "Rares + needed mana stones", "with no profile picked");
bot.Set("_loginComplete", true);
string? json = (string?)bot.Call("BuildBotStatusJson");
Check.True(json != null && json.Contains("\"lootMode\":\"rares\""), "the status says lootMode rares: " + json);
bot.S.LootMode = LootModes.Profile;
json = (string?)bot.Call("BuildBotStatusJson");
Check.True(json != null && json.Contains("\"lootMode\":\"profile\""), "and profile: " + json);
}
}

View file

@ -47,6 +47,13 @@ internal static class LootRetryTimingTests
r.Add("loot retry (R-20261029-122319-321f): a refusal on arrival is 'too busy' (free resend), one after the pickup is the pack's answer", RefusalTiming);
r.Add("loot retry (R-20261029-122319-321f): the answer wait grows with the server's measured answers, within 4-8 s", AnswerWaitAdapts);
r.Add("loot retry (R-20261029-122319-321f): PackRefusals keeps confirmed marks and drops the unconfirmed ones with the item", PackRefusalMarks);
r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): a treasure map the server refuses (quest timer, no object named) is left after one try; the next item is picked up and the corpse completes", QuestTimerMapFirst);
r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): with the map last, the items before it land, the map is left, the corpse completes", QuestTimerMapLast);
r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): maps on corpse after corpse, no side pack: each map one try, every other item lands, no pack marked", QuestTimerMapsCorpseAfterCorpse);
r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): a quest refusal naming the item is left at once too, no pack blamed", NeedsQuestNamedItem);
r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): an item refused 'for room' in every pack it tries takes its pack marks with it; the next item lands", RefusedInEveryPackWithdrawn);
r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): a refusal with an error code counts as a try but not against the pack", CodedRefusalNotThePack);
r.Add("loot pickup timer (#rynth-issues 'Stopped looting'): PackRefusals withdraws an item's own marks, keeps the ones another item backs", PackRefusalWithdraw);
}
// ── Clock and world ───────────────────────────────────────────────────────
@ -160,7 +167,16 @@ internal static class LootRetryTimingTests
/// one pending inventory request: a move sent while one is unanswered never leaves the client.
/// <see cref="Lag"/>: extra delay before the server takes up an item's first move (a lag spike);
/// <see cref="NeverAnswer"/>: items whose moves the server never answers. The engine empties a
/// pending request that has had no answer for 10 s (ClientActionGates.PendingTimeoutMs).
/// pending request that has had no answer for 10 s (ClientActionGates.PendingTimeoutMs), and
/// /rc unlockactions empties it at once.
/// <see cref="QuestTimer"/>: items with a pickup timer (2026-11-01, #rynth-issues "Stopped looting":
/// Conquest treasure maps). After the pickup motion ACE's VerifyQuest refuses them with
/// "You have solved this quest too recently!" + InventoryServerSaveFailed(object 0,
/// YouHaveSolvedThisQuestTooRecently) (QuestManager.HandleSolveError): naming no object, the
/// answer leaves the client's pending request in place. <see cref="NeedsQuest"/>: the same
/// refusal naming the item (ItemRequiresQuestToBePickedUp, HandleNoQuestError).
/// <see cref="RefusedForItem"/>: refused after the motion like a full pack (no error code),
/// whatever pack the move names: a pickup timer that says no more than a full pack does.
/// </summary>
private sealed class SlowAce
{
@ -168,6 +184,8 @@ internal static class LootRetryTimingTests
public readonly Dictionary<uint, int> Room = new(); // the server's free slots per pack (absent: plenty)
public readonly Dictionary<uint, long> Lag = new();
public readonly HashSet<uint> NeverAnswer = new();
public readonly HashSet<uint> QuestTimer = new(), NeedsQuest = new(), RefusedForItem = new();
public int QuestRefusals, Unlocks;
public long ClientPendingTimeoutMs = 10_000;
public int TooBusy, LocalRefused, Queued, RoomRefusals;
public readonly List<(uint Id, uint Pack, long At)> Landed = new();
@ -178,6 +196,7 @@ internal static class LootRetryTimingTests
private int _seenMoves;
private uint _clientPending;
private long _clientPendingAt;
private int _seenCommands;
private readonly List<(long At, int Seq, Action Act)> _events = new();
private int _seq;
@ -185,6 +204,8 @@ internal static class LootRetryTimingTests
public void Step(long now)
{
while (_seenCommands < FakeHost.ChatCommands.Count)
if (FakeHost.ChatCommands[_seenCommands++] == "/rc unlockactions") { _clientPending = 0; Unlocks++; }
while (_seenMoves < FakeHost.ExternalMoves.Count)
{
var m = FakeHost.ExternalMoves[_seenMoves++];
@ -232,7 +253,22 @@ internal static class LootRetryTimingTests
private void Finish(uint id, uint pack, long ts)
{
_st = St.Return;
if (Room.TryGetValue(pack, out int free) && free <= 0)
if (QuestTimer.Contains(id) || NeedsQuest.Contains(id))
{
QuestRefusals++;
bool named = NeedsQuest.Contains(id);
At(ts + Rtt / 2, () =>
{
if (named)
{
FakeHost.WeenieError(0x0445, 0x00A0, id); // ItemRequiresQuestToBePickedUp
Answered(id);
}
else
FakeHost.WeenieError(0x043E, 0x00A0, 0); // YouHaveSolvedThisQuestTooRecently, no object: the slot stays
});
}
else if (RefusedForItem.Contains(id) || (Room.TryGetValue(pack, out int free) && free <= 0))
{
RoomRefusals++;
At(ts + Rtt / 2, () =>
@ -243,7 +279,7 @@ internal static class LootRetryTimingTests
}
else
{
if (Room.ContainsKey(pack)) Room[pack] = free - 1;
if (Room.TryGetValue(pack, out int left)) Room[pack] = left - 1;
At(ts + Rtt / 2, () =>
{
FakeHost.Containers[id] = pack;
@ -470,4 +506,196 @@ internal static class LootRetryTimingTests
r.Accepted(1);
Check.False(r.IsRefused(1, 10), "an item landing there ends a confirmed mark");
}
// ── 7. Items the server won't hand over yet (#rynth-issues "Stopped looting") ────────────
// "I've experienced this when it's reached its loot attempt limit on some obscure item with
// pickup timers. It looks like from then on out it just selects another item in the
// container, but doesn't pick it up. Example: CQ Treasure Maps." ACE (Player.VerifyQuest,
// QuestManager.HandleSolveError) refuses such an item after the pickup motion with
// InventoryServerSaveFailed naming object 0: RynthAi saw no answer, and the client's one
// pending request stayed full, so the retries and the next item's move never left the client.
// An answer naming the item was taken for a full pack, and a pack after another was left out.
private const uint QuestMap = 0x80263151; // the lowest id on its corpse: tried first
/// <summary>The map among normal gems (the profile keeps every gem; a treasure map is one).</summary>
private static void NameMap(uint map) => FakeHost.Names[map] = "Treasure Map";
private static void QuestTimerMapFirst() => Clocked(() =>
{
const uint G2 = 0x80263152;
World(sidePack: true, QuestMap, G2);
NameMap(QuestMap);
var sim = new SlowAce();
sim.QuestTimer.Add(QuestMap);
var bot = Open(sim, sidePack: true, QuestMap, G2);
Run(bot, () => bot.Completed, 60_000);
Check.True(FakeHost.ExternalMoves.Count > 0 && FakeHost.ExternalMoves[0].Id == QuestMap, "the map is tried first");
Check.Eq(bot.MovesOf(QuestMap), 1, "the map is sent once: a retry would be refused the same way for its timer");
Check.Eq(sim.QuestRefusals, 1, "the server refused it once");
Check.True(Logged("the server won't hand over 0x80263151") && Logged("pickup timer"), "logged as refused for the item (its pickup timer)");
Check.True(FakeHost.Chat.Any(c => c.Contains("Can't loot Treasure Map")), "the player is told");
Check.True(FakeHost.ChatCommands.Contains("/rc unlockactions"), "the client's pending request (the answer named no object) is emptied");
Check.Eq(bot.MovesOf(G2), 1, "the next item is sent once");
Check.True(sim.Landed.Any(l => l.Id == G2 && l.Pack == Player), "and lands in the main pack");
Check.Eq(sim.LocalRefused, 0, "no move dropped by the client's one-request slot");
Check.False(Logged("took none of"), "no pack judged full");
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now) || bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "no pack marked");
Check.False(Logged("no pack has a free slot"), "looting does not stop for want of a pack");
Check.True(bot.Completed, "the corpse completes");
});
private static void QuestTimerMapLast() => Clocked(() =>
{
const uint G1 = 0x80263141, G2 = 0x80263142, Map = 0x80263159;
World(sidePack: true, G1, G2, Map);
NameMap(Map);
var sim = new SlowAce();
sim.QuestTimer.Add(Map);
var bot = Open(sim, sidePack: true, G1, G2, Map);
Run(bot, () => bot.Completed, 60_000);
Check.True(FakeHost.ExternalMoves.Count > 0 && FakeHost.ExternalMoves[^1].Id == Map, "the map is tried last");
Check.True(sim.Landed.Any(l => l.Id == G1) && sim.Landed.Any(l => l.Id == G2), "the items before it land");
Check.Eq(bot.MovesOf(Map), 1, "the map is sent once");
Check.True(Logged("the server won't hand over 0x80263159"), "and left for its pickup timer");
Check.False(Logged("pickup failed"), "no item runs out of tries");
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), "the main pack is not marked");
Check.True(bot.Completed, "the corpse completes");
});
private static void QuestTimerMapsCorpseAfterCorpse() => Clocked(() =>
{
// One corpse after another, each with a map (first) and a gem; no side pack, so a wrong
// mark on the main pack would stop all looting.
World(sidePack: false);
var sim = new SlowAce();
static (uint Corpse, uint Map, uint Gem) Ids(int n) { uint c = 0x80263200u + (uint)n * 0x10; return (c, c + 1, c + 2); }
for (int n = 0; n < 3; n++)
{
var (corpse, map, gem) = Ids(n);
FakeHost.Names[corpse] = "Corpse of Brier Wasp";
FakeHost.ItemTypes[corpse] = ItemTypeContainer;
FakeHost.Strings[(corpse, LongDescKey)] = $"Killed by {Me}.";
FakeHost.NotAttackable.Add(corpse);
FakeHost.Positions[corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
foreach (uint item in new[] { map, gem })
{
FakeHost.Names[item] = item == map ? "Treasure Map" : $"Gem {item & 0xFF}";
FakeHost.ItemTypes[item] = ItemTypeGem;
FakeHost.Containers[item] = corpse;
FakeHost.Appraised.Add(item);
}
sim.QuestTimer.Add(map);
}
var bot = new Bot(FakeHost.Create(Player)) { Sim = sim };
for (int n = 0; n < 3; n++)
{
var (corpse, map, gem) = Ids(n);
foreach (uint id in new[] { corpse, map, gem }) bot.Cache.OnCreateObject(id);
for (int i = 0; i < 50; i++) bot.Cache.Tick();
bot.TickUntil(() => FakeHost.Uses.Contains(corpse), 10_000);
Check.True(FakeHost.Uses.Contains(corpse), $"corpse {n + 1} is opened");
FakeHost.UseDone(0);
FakeHost.GroundContainer = corpse;
bot.P.OnViewObjectContents(corpse);
bool Done() => bot.Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)corpse));
bot.TickUntil(Done, 60_000);
Check.True(Done(), $"corpse {n + 1} completes");
Check.Eq(bot.MovesOf(map), 1, $"corpse {n + 1}: the map is sent once");
Check.True(sim.Landed.Any(l => l.Id == gem && l.Pack == Player), $"corpse {n + 1}: the gem lands in the main pack");
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), $"corpse {n + 1}: the main pack is not marked");
FakeHost.GroundContainer = 0;
bot.P.OnStopViewingObjectContents(corpse); // the server closes it
}
Check.Eq(sim.LocalRefused, 0, "no move dropped by the client's one-request slot");
Check.False(Logged("no pack has a free slot"), "looting never stops for want of a pack");
Check.False(Logged("took none of"), "no pack judged full");
});
private static void NeedsQuestNamedItem() => Clocked(() =>
{
const uint G2 = 0x80263152;
World(sidePack: true, QuestMap, G2);
NameMap(QuestMap);
var sim = new SlowAce();
sim.NeedsQuest.Add(QuestMap);
var bot = Open(sim, sidePack: true, QuestMap, G2);
Run(bot, () => bot.Completed, 60_000);
Check.Eq(bot.MovesOf(QuestMap), 1, "sent once");
Check.True(Logged("needs a quest flag"), "left: it needs a quest flag");
Check.False(FakeHost.ChatCommands.Contains("/rc unlockactions"), "the answer named the item: the client empties its own request");
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), "the main pack is not marked (it was taken for the pack's answer before)");
Check.True(sim.Landed.Any(l => l.Id == G2 && l.Pack == Player), "the next item lands in the main pack");
Check.True(bot.Completed, "the corpse completes");
});
private static void RefusedInEveryPackWithdrawn() => Clocked(() =>
{
const uint G2 = 0x80263152;
World(sidePack: true, QuestMap, G2);
NameMap(QuestMap);
var sim = new SlowAce();
sim.RefusedForItem.Add(QuestMap); // refused like a full pack, whichever pack
var bot = Open(sim, sidePack: true, QuestMap, G2);
Run(bot, () => bot.Completed, 90_000);
var mapMoves = FakeHost.ExternalMoves.Where(m => m.Id == QuestMap).ToList();
Check.Eq(mapMoves.Count(m => m.Target == Player), 3, "three tries into the main pack");
Check.Eq(mapMoves.Count(m => m.Target == SidePack), 3, "three into the side pack");
Check.True(Logged("pickup failed for 0x80263151"), "then the map is given up");
Check.True(Logged("it is refusing the item, not the packs") && Logged("the main pack and pack 0x80263001 are no longer treated as full"),
"both marks go with the map");
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now) || bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "no pack marked");
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == G2) && FakeHost.ExternalMoves.Where(m => m.Id == G2).All(m => m.Target == Player), "the next item goes into the main pack");
Check.True(sim.Landed.Any(l => l.Id == G2 && l.Pack == Player), "and lands");
Check.False(Logged("no pack has a free slot"), "looting does not stop for want of a pack");
Check.True(bot.Completed, "the corpse completes");
});
private static void CodedRefusalNotThePack() => Clocked(() =>
{
const uint G1 = 0x80263161;
World(sidePack: false, G1);
var bot = Open(new SlowAce(), sidePack: false, G1);
bot.Sim = null; // the answers are given by hand here
bot.TickUntil(() => bot.MovesOf(G1) > 0, 2000);
Check.Eq(bot.MovesOf(G1), 1, "the move is sent");
FakeHost.CastBusy = 1;
bot.TickUntil(() => false, 1800);
FakeHost.WeenieError(0x0036, 0x00A0, G1); // refused after the pickup ran, with a code (ActionCancelled)
bot.Tick();
FakeHost.CastBusy = 0;
bot.TickUntil(() => bot.MovesOf(G1) > 1, 3000);
Check.Eq(bot.MovesOf(G1), 2, "sent again");
Check.Eq(bot.Get<int>("_currentLootItemMoveAttempts"), 2, "counted as a try");
Check.Eq(bot.Get<int>("_currentLootItemDestRefusals"), 0, "but not against the main pack");
Check.True(Logged("for the item (error 0x36), not the pack"), "logged as the item's refusal");
});
private static void PackRefusalWithdraw()
{
var r = new RynthCore.Plugin.RynthAi.Loot.PackRefusals();
r.Refuse(1, 0, confirmed: true, itemId: 100);
r.Refuse(2, 0, confirmed: true, itemId: 100);
r.Refuse(3, 0, confirmed: true, itemId: 200);
r.Refuse(3, 0, confirmed: true, itemId: 100); // pack 3: refused for two items
var back = r.Withdraw(100, 10);
Check.True(back.Contains(1) && back.Contains(2) && !back.Contains(3), $"item 100's own marks are withdrawn ({string.Join(",", back)})");
Check.False(r.IsRefused(1, 10) || r.IsRefused(2, 10), "packs 1 and 2 are tried again");
Check.True(r.IsConfirmed(3, 10), "pack 3, refused for another item as well, stays marked");
r.Refuse(1, 20, confirmed: true, itemId: 300); // another item refused in pack 1 after all: it is the pack
Check.Eq(r.Withdraw(300, 30).Count, 0, "a pack two items were refused in is not withdrawn");
Check.True(r.IsConfirmed(1, 30), "pack 1 stays marked");
r.Refuse(4, 0); // no item said: never withdrawn
Check.Eq(r.Withdraw(0, 10).Count, 0, "nothing for item 0");
Check.True(r.IsConfirmed(4, 10), "a mark with no item stays");
}
}

View file

@ -12,8 +12,8 @@ using N = RynthCore.Loot.VTank.VTankNodeTypes;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-31: "a +9 bludg xbow that rynth sees as gold salvage", with LootSnob, which VTank keeps.
// Fixtures\lootsnob-excerpt.utl is LootSnobV4's melee head, missile and void wand sections and six
// of its Salvage rules (switched on, as players have them), in the file's own order.
// Fixtures\lootsnob-excerpt.utl is LootSnobV4's melee head, missile and wand (No Wield, Void, War)
// sections and six of its Salvage rules (switched on, as players have them), in the file's own order.
// Two causes:
// 1. "Calc'd Buffed Missile Damage" read max damage x the wand elemental modifier (152). A launcher
// has no max damage, so it was 0 and every one of LootSnob's 33 missile damage keeps failed; the
@ -35,7 +35,9 @@ internal static class LootRuleMatchTests
r.Add("loot rule match: tinked damage and tinked target melee (VTank's worked examples)", TinkedNodes);
r.Add("loot rule match: which conditions need the ID", ConditionsNeedingId);
r.Add("loot rule match: Decide passes over a rule a known condition fails, in any order", DecideOrder);
r.Add("loot rule match (R-20261101-133624-7eeb): a name rule 'Trade Note' first keeps none of a corpse's plain items, ID or not", TradeNoteRuleFirst);
r.Add("loot rule match: /ra loot why lists the rules above that came close, with the value read", LootWhyExplains);
r.Add("loot rule match: /ra loot why's words, in chat and in the 'Why this loot rule?' window", LootWhyReportWords);
}
private static VTankLootProfile Excerpt()
@ -246,6 +248,47 @@ internal static class LootRuleMatchTests
Check.Eq(i3, -1, "index -1");
}
// R-20261101-133624-7eeb (Conquest, 2026.10.31.3): every item on a corpse was kept by a rule named
// 'Trade Note' (Imperial Topaz, Frost Child Essence and Pyreal with no ID; Gloves and Flagon with
// it). LootSnob's 'Trade Note' is one StringValueMatch on the Name ("Trade Note", key 1): it keeps
// none of them, with or without the ID, here and through the whole fixture. A rule with no
// conditions keeps everything (VTank's unconditional rule), so a 'Trade Note' that lost its
// condition in the player's own profile would do exactly what the report shows.
private static void TradeNoteRuleFirst()
{
FakeHost.Reset();
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
var tradeNote = new VTankLootRule { Name = "Trade Note", Action = VTankLootAction.Keep };
tradeNote.Conditions.Add(C(N.StringValueMatch, "Trade Note", "1"));
var p = new VTankLootProfile();
p.Rules.Add(tradeNote);
p.Rules.AddRange(Excerpt().Rules);
var items = new (Item Item, bool Id)[]
{
(new Item("Imperial Topaz", AcObjectClass.Gem).Int(1, 0x800).Int(19, 6094), false),
(new Item("Frost Child Essence (180)", AcObjectClass.Misc).Int(1, 0x80).Int(19, 9000), false),
(new Item("Pyreal", AcObjectClass.Money).Int(1, 0x40).Int(19, 693).Int(12, 693), false),
(new Item("Gloves", AcObjectClass.Clothing).Int(1, 0x4).Int(19, 24429).Int(105, 5), true),
(new Item("Flagon", AcObjectClass.MissileWeapon).Int(1, 0x100).Int(19, 12741).Int(105, 4), true),
};
foreach (var (item, id) in items)
{
VTankLootVerdict v = VTankLootEvaluator.Decide(p, item, Ctx(), hasIdData: id, out int idx);
Check.True(!(v == VTankLootVerdict.Match && idx == 0), $"{item.Wo.Name}: not kept by 'Trade Note' ({v}{(idx >= 0 ? " at " + p.Rules[idx].Name.Trim() : "")})");
Check.True(VTankLootEvaluator.FirstMatch(p, item, Ctx(), out int fi)?.Name != "Trade Note", $"{item.Wo.Name}: FirstMatch not 'Trade Note' ({fi})");
}
var note = new Item("Trade Note (250,000)", AcObjectClass.TradeNote).Int(1, 0x80);
Check.Eq(VTankLootEvaluator.Decide(p, note, Ctx(), hasIdData: false, out int ni), VTankLootVerdict.Match, "a trade note is kept with no ID");
Check.Eq(ni, 0, "by 'Trade Note'");
// The same rule with its condition gone keeps everything: what the report looks like.
var empty = new VTankLootRule { Name = "Trade Note", Action = VTankLootAction.Keep };
var broken = new VTankLootProfile();
broken.Rules.Add(empty);
Check.Eq(VTankLootEvaluator.FirstMatch(broken, items[0].Item, Ctx(), out _)?.Name, "Trade Note", "a 'Trade Note' with no condition keeps a topaz (unconditional rule)");
}
private static void LootWhyExplains()
{
FakeHost.Reset();
@ -268,4 +311,50 @@ internal static class LootRuleMatchTests
Check.Eq(wait.Verdict, VTankLootVerdict.NeedsId, "no ID: waits");
Check.Eq(wait.RuleName, "(M) Bow (OD +10)", "names the rule that needs it");
}
// 2026-10-31: the same answer as a report the chat lines and the window are both made from.
private static void LootWhyReportWords()
{
FakeHost.Reset();
VTankLootProfile p = Excerpt();
var plain = PlusNineXbow();
FakeHost.SpellIds.Remove(unchecked((uint)plain.Wo.Id));
LootWhy.Result why = LootWhy.Explain(p, plain, Ctx(), hasIdData: true);
LootWhy.Report r = LootWhy.Describe("Blunt Crossbow", true, "[Salvage] (Salv) Gold", "lootsnob.utl", p.Rules.Count, why, askedForId: false);
Check.True(r.Ok && r.RuleDetail, "a VTank profile: rule-by-rule");
Check.Eq(r.Headline, "'Blunt Crossbow' (identified) -> [Salvage] (Salv) Gold", "the headline: the item, its ID, the looter");
Check.True(r.Decision.StartsWith($"lootsnob.utl: rule {why.Index + 1} of {p.Rules.Count} '(Salv) Gold' [", StringComparison.Ordinal), $"the decision names the rule ({r.Decision})");
Check.Eq(r.NearMisses.Count, why.NearMisses.Count, "every near miss is in the report (the window lists them all)");
var lines = LootWhy.ChatLines(r, 2);
Check.Eq(lines[0], "[RynthAi] Loot why: " + r.Headline, "chat line 1: the headline");
Check.Eq(lines[1], "[RynthAi] " + r.Decision, "chat line 2: the decision");
Check.True(lines[2].Contains($"{r.NearMisses.Count} rule(s) above it came close"), "then how many came close");
Check.Eq(lines[3], "[RynthAi] " + LootWhy.NearMissLine(r.NearMisses[0]), "then each, as #N 'name': failed");
Check.True(r.NearMisses.Count <= 2 || lines[^1].Contains($"{r.NearMisses.Count - 2} more in the log"), "past the chat's limit: the rest are counted (the log has them)");
Check.Eq(lines.Count, 3 + Math.Min(2, r.NearMisses.Count) + (r.NearMisses.Count > 2 ? 1 : 0), "no other lines");
Check.True(LootWhy.NearMissLine(new LootWhy.NearMiss(4, "Rule", "x: read 1")) == "#5 'Rule': x: read 1", "a near miss counts from 1");
LootWhy.Result wait = LootWhy.Explain(p, PlusNineXbow(withId: false), Ctx(), hasIdData: false);
LootWhy.Report w = LootWhy.Describe("Blunt Crossbow", false, "left", "lootsnob.utl", p.Rules.Count, wait, askedForId: true);
Check.True(w.Decision.EndsWith("needs the item's ID to decide", StringComparison.Ordinal) && w.Headline.Contains("(not identified yet)"), "no ID: which rule waits for it");
Check.True(LootWhy.ChatLines(w, 10).Contains("[RynthAi] Asked for its ID; /ra loot why again once it's in."), "and that it asked for it");
LootWhy.Report native = LootWhy.Describe("Blunt Crossbow", true, "[Keep] Xbows", "", 0, null, false);
Check.False(native.RuleDetail, "RynthAi's own (.json) profile: no rule-by-rule detail");
var one = LootWhy.ChatLines(native, 10);
Check.Eq(one.Count, 1, "one chat line");
Check.True(one[0].EndsWith("(Rule-by-rule detail is for VTank .utl profiles.)", StringComparison.Ordinal), "that says so");
LootWhy.Report rares = LootWhy.ModeOnly("Blunt Crossbow", true, "left", "Loot Mode: Rares and needed mana stones only (the loot profile isn't used)");
Check.True(rares.Ok && !rares.RuleDetail, "rares mode: the mode decides, no rule detail");
Check.Eq(LootWhy.ChatLines(rares, 10).Single(),
"[RynthAi] Loot why: 'Blunt Crossbow' (identified) -> left. Loot Mode: Rares and needed mana stones only (the loot profile isn't used).",
"chat: one line naming the Loot Mode, not the .utl note");
LootWhy.Report fail = LootWhy.Report.Fail("select an item first");
Check.False(fail.Ok, "a failed report");
Check.Eq(fail.Headline, "select an item first", "its headline is the reason");
Check.Eq(LootWhy.ChatLines(fail, 10).Single(), "[RynthAi] loot why: select an item first", "chat: one line, the reason");
}
}

View file

@ -0,0 +1,347 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-11-01: "damage on wands isn't being read by the loot properly; someone thinks it's missing
// them". Casters through LootSnobV4's own wand rules (Fixtures\lootsnob-excerpt.utl: its No Wield,
// Void and War sections, as LootSnob ships them), with tier 8 values as ACE's caster mutations make
// them: elemental damage vs monsters (152) 1.10-1.18 at wield 355/375/385, melee defense (29) 1.0x,
// mana conversion (144), magic defense (150), and the cantrips that add to them (Spirit Thirst,
// Defender, Hermetic Link). The values are read after the ID, through the host, on a corpse too.
//
// What was wrong:
// - Until 2026.10.31.2 a "Buffed Double Key" read the plain value without the item's cantrips. A
// loot caster tops out at 1.18, so every "(W) War/Void (OD +1..+7)" rule (1.19-1.25) failed; on
// Conquest's CQ_Lootsnob_lite, whose War and Void rules are nearly all OD rules, no war or void
// wand was kept (the 10-19 report, on 2026.10.17.1). Fixed there; checked here.
// - The installed LootSnobV4 on the PC has the War "Max 385/375/355", "18pvm + NNmd", "amazing 355",
// "25MD"-"21MD" and Void "Max" rules switched off in the Loot Editor (the stock file has them on),
// so typical tier 8 war wands were left. A profile matter, but nothing said so: /ra loot why
// skipped switched-off rules and the log said "leave". Both now name the switched-off rule that
// would take the item.
internal static class LootWandTests
{
private const uint Player = 0x50000E41;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
// Property ids (ACE PropertyInt / PropertyFloat).
private const int ItemType = 1, Burden = 5, ValidLoc = 9, Value = 19, DamageType = 45, Workmanship = 105, Material = 131,
WieldReq = 158, WieldSkill = 159, WieldDiff = 160;
private const int MeleeDef = 29, ManaConv = 144, MissileDef = 149, MagicDef = 150, VsMonsters = 152;
private const int WarMagic = 34, VoidMagic = 43, Ebony = 73; // Ebony: no Salvage rule in the excerpt
public static void Register(Runner r)
{
r.Add("loot wands: tier 8 war and void casters get LootSnob's own wand rules (Max 385/375/355, OD, MD, MC)", WandsGetTheirRules);
r.Add("loot wands: the cantrips count (Spirit Thirst OD +2/+5, Defender, Hermetic Link), as floats", WandCantrips);
r.Add("loot wands: without its ID a caster waits for it; elemental damage is ID data", WandWithoutId);
r.Add("loot wands: a switched-off rule that would take the wand is named (/ra loot why, chat, window)", SwitchedOffRuleNamed);
r.Add("loot wands: on a corpse the wand's damage is read from the host after its ID and it is kept", CorpseWandKept);
r.Add("loot wands: on a corpse, a wand left because its rule is switched off says so in the log", CorpseWandSwitchedOff);
}
private static VTankLootProfile Excerpt()
=> VTankLootParser.Load(Path.Combine(AppContext.BaseDirectory, "Fixtures", "lootsnob-excerpt.utl"));
private static VTankLootContext Ctx() => new(FakeHost.Create(), Player);
private static uint Spell(string name)
{
int id = SpellDatabase.GetIdByName(name);
if (id == 0) throw new InvalidOperationException($"spell '{name}' is not in SpellData.txt");
return (uint)id;
}
/// <summary>A caster as ACE's tier 8 caster mutations make it, identified.</summary>
private static Item Caster(string name, int skill, int wield, double vsMonsters, double def, double manaConv = 0.06,
double magicDef = 1.02, params string[] spells)
{
var c = new Item(name, AcObjectClass.WandStaffOrb)
.Int(ItemType, 0x8000).Int(ValidLoc, 0x01000000).Int(Value, 25000).Int(Burden, 50).Int(Material, Ebony)
.Int(Workmanship, 6).Dbl(MeleeDef, def).Dbl(ManaConv, manaConv).Dbl(MissileDef, 1.03).Dbl(MagicDef, magicDef);
if (wield > 0) c.Int(WieldReq, 2).Int(WieldSkill, skill).Int(WieldDiff, wield);
if (vsMonsters > 0) c.Dbl(VsMonsters, vsMonsters).Int(DamageType, skill == VoidMagic ? 0x400 : 0x10);
if (spells.Length > 0) FakeHost.SpellIds[unchecked((uint)c.Wo.Id)] = spells.Select(Spell).ToArray();
return c;
}
private static string? First(VTankLootProfile p, Item item) => VTankLootEvaluator.FirstMatch(p, item, Ctx(), out _)?.Name.Trim();
private static void WandsGetTheirRules()
{
FakeHost.Reset();
VTankLootProfile p = Excerpt();
Check.Eq(First(p, Caster("Fire Sceptre", WarMagic, 385, 1.18, 1.12)), "(W) War (Max 385)", "1.18 at 385: War (Max 385)");
Check.Eq(First(p, Caster("Frost Baton", WarMagic, 375, 1.15, 1.10)), "(W) War (Max 375)", "1.15 at 375: War (Max 375)");
Check.Eq(First(p, Caster("Acid Staff", WarMagic, 355, 1.13, 1.08)), "(W) War (Max 355)", "1.13 at 355: War (Max 355)");
Check.Null(First(p, Caster("Fire Baton", WarMagic, 375, 1.14, 1.08)), "1.14 at 375, 1.08 defense: no rule (LootSnob leaves it)");
Check.Eq(First(p, Caster("Blunt Sceptre", WarMagic, 385, 1.18, 1.20)), "(W) War (18pvm + 20md)", "1.18 and 1.20 defense");
Check.Eq(First(p, Caster("Piercing Sceptre", WarMagic, 355, 1.17, 1.25)), "(W) War (amazing 355)", "1.17 at 355 with 1.25 defense");
Check.Eq(First(p, Caster("Slashing Sceptre", WarMagic, 385, 1.10, 1.26)), "(W) War (26MD)", "a war caster on defense alone");
Check.Eq(First(p, Caster("Nether Sceptre", VoidMagic, 385, 1.18, 1.12)), "(W) Void (Max 385)", "void 1.18 at 385");
Check.Eq(First(p, Caster("Nether Baton", VoidMagic, 375, 1.18, 1.17)), "(W) Void (18pvm + 17md)", "void 1.18 and 1.17 defense");
Check.Null(First(p, Caster("Nether Staff", VoidMagic, 355, 1.12, 1.05)), "void 1.12 at 355: under Void (Max 355)'s 1.13");
// The name filters are LootSnob's: War wants Baton|Sceptre|Staff, Void wants Nether.
Check.Null(First(p, Caster("Fire Wand", WarMagic, 385, 1.18, 1.12)), "a war caster named 'Wand' is outside LootSnob's War names");
Check.Eq(First(p, Caster("Orb", 0, 0, 0, 1.24)), "(W) No Wield (24MD)", "an orb with no wield requirement on defense");
Check.Eq(First(p, Caster("Orb", 0, 0, 0, 1.20, manaConv: 0.10, magicDef: 1.0)), "(W) No Wield (20MD + 10MC)", "20 defense and 10% mana conversion");
Check.Eq(First(p, Caster("Orb", 0, 0, 0, 1.20, manaConv: 0.05, magicDef: 1.04)), "(W) No Wield (20MD + 4MgcD)", "20 defense and 4% magic defense");
Check.Null(First(p, Caster("Orb", 0, 0, 0, 1.20, manaConv: 0.05, magicDef: 1.0)), "20 defense alone");
Check.Null(First(p, Caster("Orb", WarMagic, 330, 0, 1.24)), "an orb with a wield requirement (330) is not 'No Wield', and War wants Baton|Sceptre|Staff");
}
private static void WandCantrips()
{
FakeHost.Reset();
VTankLootProfile p = Excerpt();
Check.Eq(First(p, Caster("Electric Baton", WarMagic, 385, 1.17, 1.10, spells: "Major Spirit Thirst")), "(W) War (OD +2)",
"1.17 + Major Spirit Thirst 0.03 = 1.20 (as floats)");
Check.Eq(First(p, Caster("Nether Sceptre", VoidMagic, 385, 1.16, 1.10, spells: "Legendary Spirit Thirst")), "(W) Void (OD +5)",
"1.16 + Legendary Spirit Thirst 0.07 = 1.23");
Check.Eq(First(p, Caster("Fire Baton", WarMagic, 375, 1.14, 1.10, spells: "Epic Spirit Thirst")), "(W) War (OD +1)",
"1.14 + Epic Spirit Thirst 0.05 = 1.19");
Check.Eq(First(p, Caster("Frost Baton", WarMagic, 375, 1.14, 1.10, spells: "Minor Spirit Thirst")), "(W) War (Max 375)",
"Max 375 reads the buffed value too: 1.14 + 0.01");
Check.Eq(First(p, Caster("Orb", 0, 0, 0, 1.17, spells: "Epic Defender")), "(W) No Wield (24MD)", "1.17 + Epic Defender 0.07");
Check.Null(First(p, Caster("Orb", 0, 0, 0, 1.20, manaConv: 0.08, magicDef: 1.0, spells: "Minor Hermetic Link")),
"0.08 x Minor Hermetic Link 1.10 = 0.088: under 10% mana conversion");
Check.Eq(First(p, Caster("Orb", 0, 0, 0, 1.20, manaConv: 0.08, magicDef: 1.0, spells: "Legendary Hermetic Link")), "(W) No Wield (20MD + 10MC)",
"0.08 x Legendary Hermetic Link 1.30 = 0.104");
// A castable item spell is not a cantrip: it adds nothing.
Check.Eq(First(p, Caster("Fire Sceptre", WarMagic, 385, 1.18, 1.12, spells: "Flame Bolt VI")), "(W) War (Max 385)", "its own war spell adds nothing");
}
private static void WandWithoutId()
{
FakeHost.Reset();
VTankLootProfile p = Excerpt();
// What the CreateObject shows: name, class, value, burden, material. No 152, wield or defense.
var bare = new Item("Fire Sceptre", AcObjectClass.WandStaffOrb).Int(ItemType, 0x8000).Int(ValidLoc, 0x01000000)
.Int(Value, 25000).Int(Burden, 50).Int(Material, Ebony);
Check.Eq(VTankLootEvaluator.Decide(p, bare, Ctx(), hasIdData: false, out int idx), VTankLootVerdict.NeedsId, "a caster waits for its ID");
Check.Eq(p.Rules[idx].Name.Trim(), "(W) No Wield (29MD)", "at LootSnob's first wand rule");
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
Check.True(VTankLootEvaluator.ConditionNeedsId(C(VTankNodeTypes.BuffedDoubleValKeyGE, "1.18", "152")), "buffed elemental damage needs the ID");
Check.True(VTankLootEvaluator.ConditionNeedsId(C(VTankNodeTypes.DoubleValKeyGE, "1.18", "152")), "plain elemental damage too");
Check.True(VTankLootEvaluator.ConditionNeedsId(C(VTankNodeTypes.LongValKeyE, "385", "160")), "and the wield difficulty");
Check.Null(VTankLootEvaluator.FirstMatch(p, bare, Ctx(), out _), "judged with 0s nothing takes it (why it must wait)");
}
private static VTankLootProfile WithOff(params string[] names)
{
VTankLootProfile p = Excerpt();
foreach (VTankLootRule r in p.Rules)
if (names.Contains(r.Name.Trim())) LootEditSessionOff(r);
return p;
}
// As the Loot Editor switches a rule off (LootEditSession.SetEnabled: a DisabledRule node "true" at the end).
private static void LootEditSessionOff(VTankLootRule r)
=> r.Conditions.Add(new VTankLootCondition(VTankNodeTypes.DisabledRule, "0", new[] { "true" }));
private static void SwitchedOffRuleNamed()
{
FakeHost.Reset();
VTankLootProfile p = WithOff("(W) War (Max 385)", "(W) War (18pvm + 20md)");
var wand = Caster("Fire Sceptre", WarMagic, 385, 1.18, 1.12);
Check.Null(First(p, wand), "with War (Max 385) off, nothing takes the 1.18 / 385 sceptre");
int off = VTankLootEvaluator.FirstSwitchedOffMatch(p, wand, Ctx());
Check.True(off >= 0 && p.Rules[off].Name.Trim() == "(W) War (Max 385)", $"the switched-off rule that would take it ({(off >= 0 ? p.Rules[off].Name : "none")})");
Check.Eq(VTankLootEvaluator.FirstSwitchedOffMatch(p, Caster("Fire Baton", WarMagic, 375, 1.14, 1.08), Ctx()), -1, "none for a wand no rule wants");
Check.Eq(VTankLootEvaluator.FirstSwitchedOffMatch(Excerpt(), wand, Ctx()), -1,
"LootSnob's own switched-off rules (the 'leave this disabled' separators, Creature Cantrip ...) don't take it");
Check.True(VTankLootEvaluator.FirstSwitchedOffMatch(p, wand, Ctx(), end: off) == -1, "only rules above the end count");
LootWhy.Result why = LootWhy.Explain(p, wand, Ctx(), hasIdData: true);
Check.Eq(why.Verdict, VTankLootVerdict.NoMatch, "no rule matches");
Check.Eq(why.SwitchedOffName, "(W) War (Max 385)", "why names the switched-off rule");
Check.Eq(why.SwitchedOffAction, VTankLootAction.Keep, "and what it does");
Check.True(why.NearMisses.Any(m => m.RuleName == "(W) War (OD +7)" && m.Failed.Contains("read 1.18")),
"the OD rules came close, reading its 1.18 (" + string.Join(" | ", why.NearMisses.Take(3).Select(LootWhy.NearMissLine)) + ")");
LootWhy.Report r = LootWhy.Describe("Fire Sceptre", true, "left", "LootSnobV4.utl", p.Rules.Count, why, askedForId: false);
string expect = $"#{off + 1} '(W) War (Max 385)' [Keep]";
Check.Eq(r.SwitchedOff, expect, "the report carries it");
var lines = LootWhy.ChatLines(r, 3);
Check.Eq(lines[2], "[RynthAi] Switched off in the profile: " + expect
+ " would take it. Switch that rule on in the Loot Editor to loot items like this.", "chat says so, after the decision");
Check.True(lines.Count > 3 && lines[3].Contains("came close"), "then the near misses as before");
// A rule that takes the item comes first: a switched-off rule below the winner isn't named.
VTankLootProfile q = WithOff("(W) War (Max 375)");
LootWhy.Result kept = LootWhy.Explain(q, wand, Ctx(), hasIdData: true);
Check.Eq(kept.RuleName, "(W) War (Max 385)", "kept by Max 385");
Check.Eq(kept.SwitchedOffIndex, -1, "Max 375 (off, below it) isn't named");
Check.Eq(LootWhy.Describe("Fire Sceptre", true, "[Keep] (W) War (Max 385)", "x.utl", q.Rules.Count, kept, false).SwitchedOff, "",
"nothing switched off in its report");
// LootSnob ships its Salvage rules off: /ra loot why names one (the player may want it), the
// looter's log line (keeps only) doesn't, or nearly every left item would carry one.
VTankLootProfile s = Excerpt();
var ebony = new VTankLootRule { Name = "(Salv) Ebony", Action = VTankLootAction.Salvage };
ebony.Conditions.Add(new VTankLootCondition(VTankNodeTypes.LongValKeyE, "0", new[] { Ebony.ToString(), Material.ToString() }));
LootEditSessionOff(ebony);
s.Rules.Add(ebony);
var plainBaton = Caster("Fire Baton", WarMagic, 375, 1.14, 1.08);
Check.Eq(VTankLootEvaluator.FirstSwitchedOffMatch(s, plainBaton, Ctx()), s.Rules.Count - 1, "any action: the switched-off Ebony salvage");
Check.Eq(VTankLootEvaluator.FirstSwitchedOffMatch(s, plainBaton, Ctx(), keepsOnly: true), -1, "keeps only: none");
Check.Eq(LootWhy.Explain(s, plainBaton, Ctx(), hasIdData: true).SwitchedOffAction, VTankLootAction.Salvage, "/ra loot why names the salvage rule");
// Without the ID its stats read 0: no switched-off rule is judged.
var bare = new Item("Fire Sceptre", AcObjectClass.WandStaffOrb).Int(ItemType, 0x8000).Int(Value, 25000);
Check.Eq(LootWhy.Explain(p, bare, Ctx(), hasIdData: false).SwitchedOffIndex, -1, "no ID: none named");
}
// ── On a corpse: the looter, the host's reads, the log ───────────────────
private const uint Corpse = 0x80265100;
private const uint Wand = 0x80265101;
private const uint LongDescKey = 16;
private const string Me = "Test Looter";
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
private static long _now;
private static void Clocked(Action body)
{
var old = RynthAiPlugin.CorpseClock;
_now = 70_000_000;
RynthAiPlugin.CorpseClock = () => _now;
try { body(); }
finally { RynthAiPlugin.CorpseClock = old; }
}
private static void World()
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.Names[Player] = Me;
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
FakeHost.Names[Corpse] = "Corpse of Tusker Guard";
FakeHost.ItemTypes[Corpse] = 0x200;
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
FakeHost.NotAttackable.Add(Corpse);
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
// The CreateObject: name, type, slot, value, burden, material.
FakeHost.Names[Wand] = "Fire Sceptre";
FakeHost.ItemTypes[Wand] = 0x8000;
FakeHost.Containers[Wand] = Corpse;
foreach (var (k, v) in new (uint, int)[] { (1, 0x8000), (9, 0x01000000), (19, 28640), (5, 50), (131, Ebony) })
FakeHost.Ints[(Wand, k)] = v;
}
/// <summary>The ID lands: wield 385 War Magic, fire, workmanship 6; 1.18 vs monsters, 1.12 defense.</summary>
private static void Identify()
{
foreach (var (k, v) in new (uint, int)[] { (105, 6), (158, 2), (159, WarMagic), (160, 385), (45, 0x10) })
FakeHost.Ints[(Wand, k)] = v;
FakeHost.Doubles[(Wand, VsMonsters)] = 1.18;
FakeHost.Doubles[(Wand, MeleeDef)] = 1.12;
FakeHost.Doubles[(Wand, ManaConv)] = 0.06;
FakeHost.Doubles[(Wand, MissileDef)] = 1.03;
FakeHost.Doubles[(Wand, MagicDef)] = 1.02;
FakeHost.SpellIds[Wand] = new[] { Spell("Flame Bolt VI") };
FakeHost.Appraised.Add(Wand);
}
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new()
{
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
LootAssessWindowMs = 200, LootCorpseTimeoutMs = 12_000,
};
public readonly WorldObjectCache Cache;
public Bot(RynthCoreHost host, VTankLootProfile profile, string file)
{
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
Cache = new WorldObjectCache(host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
string path = Path.Combine(Program.TempRoot, file);
File.WriteAllText(path, VTankLootWriter.Serialize(profile));
S.CurrentLootPath = path;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
public void Tick()
{
Set("_activity", BotActivity.Looting);
typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(P, null);
}
public bool Completed(uint corpse) =>
Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)corpse));
}
private static bool Moved() => FakeHost.ExternalMoves.Any(m => m.Id == Wand);
private static Bot OpenCorpse(VTankLootProfile profile, string file)
{
World();
var host = FakeHost.Create(Player);
var bot = new Bot(host, profile, file);
bot.Cache.OnCreateObject(Corpse);
bot.Cache.OnCreateObject(Wand);
bot.Cache.Tick();
bot.Tick();
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
FakeHost.UseDone(0);
bot.P.OnViewObjectContents(Corpse);
for (int i = 0; i < 5; i++) { _now += 20; bot.Tick(); }
Check.True(FakeHost.IdRequests.Contains(Wand), "the wand's ID is asked for (LootSnob's wand rules need it)");
Check.False(Moved(), "not taken before its ID");
return bot;
}
private static void CorpseWandKept() => Clocked(() =>
{
var bot = OpenCorpse(Excerpt(), "loot-wand-stock.utl");
Identify();
// Read through the host as the looter reads it: the WorldObject in the cache, no overlay.
WorldObject? wo = bot.Cache[unchecked((int)Wand)];
Check.NotNull(wo, "the wand is in the cache");
Check.Near(wo?.Values((DoubleValueKey)VsMonsters, 0.0) ?? 0, 1.18, 1e-9, "elemental damage vs monsters read from the host after the ID");
for (int i = 0; i < 200 && !Moved(); i++) { _now += 20; bot.Tick(); }
Check.True(Moved(), "taken once the ID is in");
Check.True(FakeHost.Chat.Any(c => c.Contains("Loot rule: Fire Sceptre -> [Keep] (W) War (Max 385)")),
"by LootSnob's War (Max 385) (chat: " + string.Join(" | ", FakeHost.Chat.Where(c => c.Contains("Loot rule"))) + ")");
});
private static void CorpseWandSwitchedOff() => Clocked(() =>
{
VTankLootProfile p = WithOff("(W) War (Max 385)");
var bot = OpenCorpse(p, "loot-wand-off.utl");
Identify();
for (int i = 0; i < 1000 && !bot.Completed(Corpse); i++) { _now += 20; bot.Tick(); }
Check.False(Moved(), "left: the rule that wants it is off");
int off = p.Rules.FindIndex(r => r.Name.Trim() == "(W) War (Max 385)");
string note = $"-> leave (switched-off rule #{off + 1} '(W) War (Max 385)' [Keep] would take it)";
Check.True(FakeHost.Logs.Any(l => l.Contains("[LootEval] 'Fire Sceptre'") && l.Contains(note)),
"the log's leave line names the switched-off rule (" + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("[LootEval] 'Fire Sceptre'"))) + ")");
});
}

View file

@ -0,0 +1,309 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-11-01, "still having trouble editing metas and the changes not saving". Meta edits go:
// the engine's Meta panel -> RynthPluginSendMetaCommand -> HandleMetaCommand -> DrainMetaCommands ->
// ApplyMetaCommand -> MetaSaver (or RynthAi's own Macro Rules window -> TryAutoSaveMeta -> MetaSaver).
// Before: no save logged anything, a save that didn't happen (no file, a stale rule index, a command
// that threw) returned silently, and at login a meta ran the copy of its rules kept in the settings
// profile, not its file. These tests drive the commands in the engine's wire format (MetaData.cs
// MetaCmd and MetaRuleDto.cs: PascalCase, LastFiredMs included) on scratch files only.
internal static class MetaSaveTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private const string TwoRules =
"STATE: {Default} ~~ {\n\tIF:\tAlways\n\t\tDO:\tChat {/say one}\n\tIF:\tNever\n\t\tDO:\tChat {/say two}\n~~ }\n";
public static void Register(Runner r)
{
r.Add("meta save: an engine update_rule rewrites the .af and logs it once (path, rule count)", EngineUpdateSaves);
r.Add("meta save: a write that fails says why (status, log, snapshot) and the next edit saves", FailedWriteSays);
r.Add("meta save: an edit to a meta with no file is refused with the reason, not silently", NoFileRefused);
r.Add("meta save: an update for a rule index the meta doesn't have is refused and logged", StaleIndexRefused);
r.Add("meta save: a command that doesn't read is logged, not swallowed", GarbageCommandLogged);
r.Add("meta save: Save As (save_file) writes, logs and switches to the new file", SaveAsSwitches);
r.Add("meta save: the Macro Rules window's autosave shows Saved / NOT saved in its status line", LegacyStatusLine);
r.Add("meta save: at login the meta runs its file's rules, not the profile's old copy", LoginUsesFile);
r.Add("meta save: an edit after login is written on top of the newer file, not over it", EditAfterLoginKeepsFile);
r.Add("meta save: a profile whose last meta save failed keeps its copy at login and says so", UnsavedProfileCopyKept);
r.Add("meta save: a missing meta file at login keeps the profile's copy (logged)", MissingFileKeepsCopy);
}
// ── helpers ──────────────────────────────────────────────────────────────
private static string Dir(string name)
{
string dir = Path.Combine(Program.TempRoot, "meta-save", name);
if (Directory.Exists(dir))
{
foreach (string f in Directory.GetFiles(dir, "*", SearchOption.AllDirectories)) File.SetAttributes(f, FileAttributes.Normal);
Directory.Delete(dir, recursive: true);
}
Directory.CreateDirectory(dir);
return dir;
}
private static LegacyMetaUi MetaUi(LegacyDashboardRenderer dash) =>
(LegacyMetaUi)typeof(LegacyDashboardRenderer).GetField("_metaUi", Any)!.GetValue(dash)!;
private static MetaSaver Saver(LegacyDashboardRenderer dash) =>
(MetaSaver)typeof(LegacyDashboardRenderer).GetField("_metaSaver", Any)!.GetValue(dash)!;
/// <summary>A dashboard with <c>farm.af</c> (two rules) loaded from a scratch folder.</summary>
private static string NewMeta(string name, out LegacyDashboardRenderer dash)
{
string path = Path.Combine(Dir(name), "farm.af");
File.WriteAllText(path, TwoRules);
FakeHost.Reset();
DataWriteGuard.Reset();
dash = new LegacyDashboardRenderer(FakeHost.Create());
var ui = MetaUi(dash);
Check.True(ui.LoadMacroFile(path), "loads: " + ui.LastLoadStatus);
return path;
}
private static string RuleJson(string say, string state = "Default") =>
"{\"State\":\"" + state + "\",\"Condition\":1,\"ConditionData\":\"\",\"Action\":1,\"ActionData\":\"" + say + "\"," +
"\"Children\":[],\"ActionChildren\":[],\"Enabled\":true,\"Name\":\"\",\"LastFiredMs\":99999}";
private static string Cmd(string op, int index = -1, string? rule = null, string path = "") =>
"{\"Op\":\"" + op + "\",\"Index\":" + index + ",\"Value\":\"\",\"Path\":\"" + path.Replace("\\", "\\\\") + "\",\"Text\":\"\"" +
(rule != null ? ",\"Rule\":" + rule : "") + "}";
private static void Send(LegacyDashboardRenderer dash, string json)
{
dash.HandleMetaCommand(json);
dash.DrainMetaCommands();
}
private static int LogCount(string part)
{
int n = 0;
foreach (string l in FakeHost.Logs)
if (l.Contains(part, StringComparison.OrdinalIgnoreCase)) n++;
return n;
}
private static string LogWith(string part)
{
foreach (string l in FakeHost.Logs)
if (l.Contains(part, StringComparison.OrdinalIgnoreCase)) return l;
return "(no log line with '" + part + "'; log: " + string.Join(" | ", FakeHost.Logs) + ")";
}
/// <summary>The snapshot's saveResult, as the engine panel reads it.</summary>
private static (long Seq, bool Ok, string Text, string Path) SaveResult(LegacyDashboardRenderer dash)
{
using var doc = JsonDocument.Parse(dash.BuildMetaJson());
JsonElement r = doc.RootElement.GetProperty("saveResult");
return (r.GetProperty("seq").GetInt64(), r.GetProperty("ok").GetBoolean(),
r.GetProperty("text").GetString() ?? "", r.GetProperty("path").GetString() ?? "");
}
// ── engine panel commands ────────────────────────────────────────────────
private static void EngineUpdateSaves()
{
string path = NewMeta("update", out var dash);
var loadedResult = SaveResult(dash);
Check.True(loadedResult.Ok && loadedResult.Text.Contains("Loaded farm.af"), "the load is the last result: " + loadedResult.Text);
long s0 = loadedResult.Seq;
Send(dash, Cmd("update_rule", 0, RuleJson("/say edited")));
Check.Eq(dash.Settings.MetaRules[0].ActionData, "/say edited", "applied in memory");
Check.True(File.ReadAllText(path).Contains("/say edited"), "written to the file");
Check.Eq(LogCount("Meta saved"), 1, "one log line for the save");
string line = LogWith("Meta saved");
Check.True(line.Contains(path) && line.Contains("2 rules"), "names the path and the rule count: " + line);
var r = SaveResult(dash);
Check.True(r.Seq == s0 + 1 && r.Ok && r.Text.Contains("Saved farm.af") && r.Path == path, $"snapshot says saved: {r}");
Send(dash, Cmd("add_rule", -1, RuleJson("/say three")));
Check.True(File.ReadAllText(path).Contains("/say three"), "add_rule written");
Check.True(SaveResult(dash).Seq == s0 + 2 && LogWith("Meta saved: " + path + " (3 rules").Contains("3 rules"), "add_rule logged with the new count");
// A move with nothing to swap still answers (the panel isn't left waiting), and writes nothing.
int saves = LogCount("Meta saved");
Send(dash, Cmd("move_up", 0));
var moved = SaveResult(dash);
Check.True(moved.Seq == s0 + 3 && moved.Ok && moved.Text.Contains("Nothing to move"), "no-op move answered: " + moved.Text);
Check.Eq(LogCount("Meta saved"), saves, "and wrote nothing");
}
private static void FailedWriteSays()
{
string path = NewMeta("fail", out var dash);
using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
Send(dash, Cmd("update_rule", 1, RuleJson("/say held")));
var r = SaveResult(dash);
Check.False(r.Ok, "snapshot says not saved");
Check.True(r.Text.Contains("NOT saved") && r.Text.Contains("open in another program"), "says why: " + r.Text);
Check.True(LogWith("Meta NOT saved").Contains(path), "logged with the path");
Check.True(dash.Settings.MetaUnsaved, "the profile's copy is marked as the newer one");
}
Check.True(DataWriteGuard.PendingCount == 1, "and the once-per-folder chat line is queued");
Check.False(File.ReadAllText(path).Contains("/say held"), "file untouched while held");
Send(dash, Cmd("set_rule_enabled", 0) .Replace("\"Value\":\"\"", "\"Value\":\"true\""));
Check.True(SaveResult(dash).Ok && File.ReadAllText(path).Contains("/say held"), "the next edit saves everything");
Check.False(dash.Settings.MetaUnsaved, "and clears the mark");
}
private static void NoFileRefused()
{
FakeHost.Reset();
var dash = new LegacyDashboardRenderer(FakeHost.Create());
Check.True(MetaUi(dash).LoadMacroFile(""), "a new, empty meta");
Send(dash, Cmd("add_rule", -1, RuleJson("/say lonely")));
Check.Eq(dash.Settings.MetaRules.Count, 1, "the rule is added");
var r = SaveResult(dash);
Check.True(!r.Ok && r.Text.Contains("no file") && r.Text.Contains("Save As"), "says it has no file and what to do: " + r.Text);
Check.True(LogCount("no file") == 1, "logged: " + LogWith("no file"));
}
private static void StaleIndexRefused()
{
string path = NewMeta("stale", out var dash);
string before = File.ReadAllText(path);
long s0 = SaveResult(dash).Seq;
Send(dash, Cmd("update_rule", 5, RuleJson("/say ghost")));
var r = SaveResult(dash);
Check.True(!r.Ok && r.Text.Contains("rule 6 isn't in the meta"), "says which rule and why: " + r.Text);
Check.True(LogWith("update_rule").Contains("isn't in the meta"), "logged");
Check.Eq(File.ReadAllText(path), before, "file untouched");
Send(dash, Cmd("delete_rule", 9));
Check.True(SaveResult(dash).Seq == s0 + 2 && !SaveResult(dash).Ok, "delete of a missing rule is refused too");
Check.Eq(dash.Settings.MetaRules.Count, 2, "nothing deleted");
}
private static void GarbageCommandLogged()
{
NewMeta("garbage", out var dash);
Send(dash, "{\"Op\":\"update_rule\",\"Index\":\"zero\"}");
var r = SaveResult(dash);
Check.True(!r.Ok && r.Text.Contains("Edit not applied"), "said: " + r.Text);
Check.True(LogWith("Edit not applied").Contains("Exception"), "the exception is logged: " + LogWith("Edit not applied"));
}
private static void SaveAsSwitches()
{
string path = NewMeta("saveas", out var dash);
string copy = Path.Combine(Path.GetDirectoryName(path)!, "farm2.af");
Send(dash, Cmd("save_file", path: copy));
Check.True(File.Exists(copy) && File.ReadAllText(copy).Contains("/say two"), "the copy is written");
Check.Eq(dash.Settings.CurrentMetaPath, copy, "editing continues in the copy");
Check.True(LogWith("Meta saved: " + copy).Contains("Save As"), "logged");
Send(dash, Cmd("update_rule", 0, RuleJson("/say in copy")));
Check.True(File.ReadAllText(copy).Contains("/say in copy") && !File.ReadAllText(path).Contains("/say in copy"), "later edits go to the copy");
}
// ── RynthAi's own Macro Rules window ─────────────────────────────────────
private static void LegacyStatusLine()
{
string path = NewMeta("legacy", out var dash);
var ui = MetaUi(dash);
MethodInfo autosave = typeof(LegacyMetaUi).GetMethod("TryAutoSaveMeta", Any)!;
dash.Settings.MetaRules[0].ActionData = "/say window";
autosave.Invoke(ui, null);
Check.True(ui.StatusLine.StartsWith("Saved farm.af"), "status line: " + ui.StatusLine);
Check.True(File.ReadAllText(path).Contains("/say window"), "written");
Check.True(LogWith("Meta saved").Contains("Macro Rules"), "logged through the dashboard's saver");
using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
autosave.Invoke(ui, null);
Check.True(ui.StatusLine.Contains("NOT saved"), "a failure shows: " + ui.StatusLine);
Check.True(ReferenceEquals(ui.Saver, Saver(dash)), "one saver for both editors");
}
// ── login: the file is the meta ──────────────────────────────────────────
/// <summary>A character whose profile names <c>farm.af</c> and holds a copy of its two rules.</summary>
private static string ProfileWithMeta(string name, out string metaPath, Action<LegacyUiSettings>? tweak = null)
{
string root = Dir(name);
LegacyDashboardRenderer.ProfilesBase = Path.Combine(root, "SettingsProfiles");
LegacyDashboardRenderer.MonstersBase = Path.Combine(root, "MonsterProfiles");
metaPath = Path.Combine(root, "farm.af");
File.WriteAllText(metaPath, TwoRules);
FakeHost.Reset();
FakeHost.WorldName = "TestWorld";
var dash = new LegacyDashboardRenderer(FakeHost.Create());
dash.LoadSettings("Tester");
Check.True(MetaUi(dash).LoadMacroFile(metaPath), "loads");
tweak?.Invoke(dash.Settings);
dash.SaveSettings();
return root;
}
private static LegacyDashboardRenderer Relog()
{
FakeHost.Reset();
FakeHost.WorldName = "TestWorld";
var dash = new LegacyDashboardRenderer(FakeHost.Create());
dash.LoadSettings("Tester");
return dash;
}
private static void LoginUsesFile()
{
ProfileWithMeta("login-file", out string meta);
// Changed elsewhere: another client, the rmeta tool, a text editor.
File.WriteAllText(meta, TwoRules.Replace("/say two", "/say changed elsewhere"));
var dash = Relog();
Check.Eq(dash.Settings.CurrentMetaPath, meta, "same meta");
Check.Eq(dash.Settings.MetaRules.Count, 2, "two rules");
Check.Eq(dash.Settings.MetaRules[1].ActionData, "/say changed elsewhere", "the file's rules run, not the profile's old copy");
Check.True(LogWith("differs from the copy").Contains(meta), "logged");
dash.SaveSettings(); // what the autosave does next: the profile's copy is the file's now
var again = Relog();
Check.Eq(LogCount("differs from the copy"), 0, "an unchanged file loads quietly");
Check.Eq(again.Settings.MetaRules[1].ActionData, "/say changed elsewhere", "still the file's");
}
private static void EditAfterLoginKeepsFile()
{
ProfileWithMeta("login-edit", out string meta);
File.WriteAllText(meta, TwoRules.Replace("/say two", "/say newer file"));
var dash = Relog();
Send(dash, Cmd("update_rule", 0, RuleJson("/say my edit")));
string text = File.ReadAllText(meta);
Check.True(text.Contains("/say my edit") && text.Contains("/say newer file"), "the edit lands on the newer file: " + text);
}
private static void UnsavedProfileCopyKept()
{
ProfileWithMeta("login-unsaved", out string meta, s =>
{
s.MetaRules[1].ActionData = "/say edit that never reached the file";
s.MetaUnsaved = true;
});
var dash = Relog();
Check.Eq(dash.Settings.MetaRules[1].ActionData, "/say edit that never reached the file", "the profile's copy is kept");
Check.True(LogWith("wasn't saved to the file").Contains(meta), "logged");
Check.True(FakeHost.Chat.Exists(c => c.Contains("wasn't saved to its file")), "and said in chat");
Send(dash, Cmd("set_rule_enabled", 0).Replace("\"Value\":\"\"", "\"Value\":\"true\""));
Check.True(File.ReadAllText(meta).Contains("/say edit that never reached the file"), "the next save writes it");
Check.False(dash.Settings.MetaUnsaved, "mark cleared");
}
private static void MissingFileKeepsCopy()
{
ProfileWithMeta("login-missing", out string meta);
File.Delete(meta);
var dash = Relog();
Check.Eq(dash.Settings.MetaRules.Count, 2, "the profile's copy runs");
Check.True(LogWith("isn't there").Contains(meta), "logged");
}
}

View file

@ -36,6 +36,9 @@ internal static class TargetingTests
r.Add("targeting: a higher priority out of sight is named as passed over, once per reason", PassedOverOutOfSight);
r.Add("targeting: a higher priority just past Monster Range is named on the lock line", PassedOverBeyondRange);
r.Add("targeting: nothing is named when no higher priority was left out", PassedOverNothingHigher);
r.Add("targeting: lock off keeps a target that blinks out of the scan (no switch on stale values)", LockOffNoSwitchOnStale);
r.Add("targeting: lock off holds right after a cast goes out, before it is judged", LockOffHoldsJustSentCast);
r.Add("targeting: a higher priority just past Monster Range is logged once while fighting, and /ra why names it", BeyondRangeWhileEngaged);
}
// ── Schemes ───────────────────────────────────────────────────────────────
@ -317,6 +320,59 @@ internal static class TargetingTests
Check.False(FakeHost.Logs.Any(l => l.Contains("passed over")), "the target itself out of sight isn't 'passed over'");
}
// ── R-20261031-201214-8be7: a switch on stale values, 124 ms after a bolt went out ─────
private static void LockOffNoSwitchOnStale()
{
var t = new Rig(Closest, false);
Check.Eq(t.Pick((A, 4.3, 0)), A, "A, a swarm closing in, is locked at 4.3 m");
Check.Eq(t.Pick((B, 2.4, 0)), A, "A blinks out of the scan (its last value 4.3 m): kept, not judged on it");
Check.False(FakeHost.Logs.Any(l => l.Contains("another is clearly better")), "no 'clearly better' switch");
Check.Eq(t.Pick((A, 1.9, 0), (B, 2.4, 0)), A, "back in the scan at 1.9 m: still A");
t.Advance(2000);
Check.Eq(t.Pick((B, 2.4, 0)), B, "gone past the scan grace: B");
}
private static void LockOffHoldsJustSentCast()
{
var t = new Rig(Closest, false);
Check.Eq(t.Pick((A, 3, 0)), A, "A is locked");
t.Combat.NoteCastSent(unchecked((int)A)); // the bolt went out; no judgement yet
Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), A, "a cast just sent at A: B (2.5 m closer) waits");
t.Combat.ReportDamageOnTarget(unchecked((int)A));
Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), B, "the cast landed: the switch goes ahead");
t = new Rig(Closest, false);
t.Pick((A, 3, 0));
t.Combat.NoteCastSent(unchecked((int)A));
t.Advance(4100);
Check.Eq(t.Pick((A, 3, 0), (B, 0.5, 0)), B, "past the 4 s flight window with nothing landed: switch");
}
private static void BeyondRangeWhileEngaged()
{
var t = new ScanPick(monsterRange: 10);
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
t.Place(A, "Mob A", north: 2);
t.Place(Boss, "Boss", north: -40);
Check.Eq(t.Tick(), A, "Mob A is locked; the Boss is far off");
Check.False(FakeHost.Logs.Any(l => l.Contains("passed over")), "nothing named yet");
t.Place(Boss, "Boss", north: -12); // the Boss walks up, still past Monster Range 10
Check.Eq(t.Tick(), A, "the Boss at 12 m is not a candidate: the target stays (intended)");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] passed over 0x80000404 'Boss' priority 5, 12.0 m: beyond Monster Range (10 m), the Monster Range setting")
&& l.Contains("the target stays 0x80000401 'Mob A' priority 1")),
"logged: the setting is why");
int lines = PassedLines();
t.Tick();
Check.Eq(PassedLines(), lines, "once");
string? why = t.C.DescribeHigherPriorityPassedOver();
Check.True(why != null && why.Contains("'Boss' priority 5") && why.Contains("beyond Monster Range (10 m)"), $"/ra why names it ({why})");
t.Place(Boss, "Boss", north: -9);
Check.Eq(t.Tick(), Boss, "inside Monster Range: the Boss takes over at once");
}
private static int PassedLines() => FakeHost.Logs.Count(l => l.Contains("[CombatTarget] passed over"));
/// <summary>The real scan (ScanNearbyTargets) over placed monsters, then the pick.</summary>
@ -326,6 +382,7 @@ internal static class TargetingTests
public readonly HashSet<uint> Blocked = new();
private readonly List<uint> _ids = new();
private CombatManager? _c;
public CombatManager C => _c!;
private static readonly FieldInfo LastScan =
typeof(CombatManager).GetField("_lastScanTime", BindingFlags.NonPublic | BindingFlags.Instance)!;

View file

@ -511,6 +511,38 @@ internal static partial class Program
Check(back.Recent.Count == AtlasStore.MaxRecent && back.Recent[0].Name == "P5", "recent survives in order");
Near(back.Favorites[0].Ns, 42.08, 1e-9, "coordinates survive");
Check(back.RemoveFavorite("HOLTBURG") && back.Favorites.Count == 0, "remove by name");
// Every client saves atlas.txt: a save applies this client's changes to the file on disk
// (MergeInto), so another client's favorite survives (2026-11-01).
var exp = new SavedPlace { Name = "Abandoned Experiment (Conquest)", Type = "Dungeon", Ns = 42.45, Ew = 56.05 };
var yaraq = new SavedPlace { Name = "Yaraq", Type = "Town", Ns = -21.5, Ew = -1.8 };
var a = new AtlasStore(); // the client that adds the dungeon
a.ToggleFavorite(exp);
var disk = AtlasStore.Parse(a.Serialize());
a.MergeInto(disk);
var b = AtlasStore.Parse(new AtlasStore().Serialize()); // another client, loaded before that save
b.Touch(yaraq);
b.MergeInto(AtlasStore.Parse(a.Serialize()));
Check(b.IsFavorite(exp), "another client's save keeps the favorite it never had");
Check(b.Recent.Count == 1 && b.Recent[0].Name == "Yaraq", "and puts its own trip in Recent");
var c = AtlasStore.Parse(b.Serialize());
c.RemoveFavorite("Abandoned Experiment (Conquest)");
c.MergeInto(AtlasStore.Parse(b.Serialize()));
Check(!c.IsFavorite(exp), "a removal on one client sticks (the disk copy still had it)");
var d = AtlasStore.Parse(b.Serialize());
d.ClearRecent();
d.MergeInto(AtlasStore.Parse(b.Serialize()));
Check(d.Recent.Count == 0 && d.IsFavorite(exp), "Clear recent sticks; favorites stay");
var e = new AtlasStore();
e.MergeInto(AtlasStore.Parse(b.Serialize()));
e.MergeInto(AtlasStore.Parse(e.Serialize()));
Check(e.Favorites.Count == 1 && e.Recent.Count == 1, "merging the same file twice adds nothing");
// Names find favorites, with or without a bracketed tag.
Check(b.FindFavorite("abandoned experiment")?.SameAs(exp) == true, "a favorite by its name without the tag");
Check(b.FindFavorite("Abandoned Experiment (Conquest)")?.SameAs(exp) == true, "and with it");
Check(b.FindFavorite("Abandoned") == null, "not by part of a word");
Check(b.FindFavorite("") == null, "nothing for nothing");
}
/// <summary>