Snapshot for release 2026.10.19.1 (internal f0bdcf8)

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

View file

@ -81,10 +81,20 @@ internal sealed class LongValuePicker : ContentControl
_box.Width = 80;
_box.Margin = new Thickness(4, 0, 0, 0);
ToolTip.SetTip(_box, "Any number, named or not");
_combo = new ComboBox { HorizontalAlignment = HorizontalAlignment.Stretch, MinWidth = 160 };
_combo = new ComboBox
{
HorizontalAlignment = HorizontalAlignment.Stretch,
MinWidth = 160,
IsTextSearchEnabled = true, // type while open to jump (Olthoi, Virindi, …)
MaxDropDownHeight = 360,
};
_combo.DisplayMemberBinding = new Avalonia.Data.Binding(nameof(Opt.Display));
if (LootRuleText.ValueTableIsFlags(key))
ToolTip.SetTip(_combo, "Flags: other combinations are typed as a number in the box");
else if (key == 166)
ToolTip.SetTip(_combo, "Slayer creature type — pick by name (list is A–Z). Any slayer: use >= 1");
else
ToolTip.SetTip(_combo, "Pick by name, or type a number in the box");
_combo.SelectionChanged += (_, _) =>
{
if (_syncing || _combo.SelectedItem is not Opt { Id: int id }) return;

View file

@ -0,0 +1,192 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using RynthCore.Loot;
using RynthCore.Loot.Editing;
using RynthCore.Loot.VTank;
namespace RynthCore.LootSdkTests;
// "Add to loot profile"'s attribute checklist (2026-10-18): every attribute a clicked item has,
// grouped, each ticked or not with a comparison and a value; spells by tier; pet essences.
// The defaults (no choices) are covered by LootAddItemTests / LootAddT11Tests, which still
// expect the rules "items like this" and "Include T11 attributes" always made.
internal static partial class Program
{
private static void RunLootAddAttributeTests()
{
Console.WriteLine("\n-- LootAdd: attribute checklist --");
TestAttrRowsAndGroups();
TestAttrChoices();
TestAttrSpellTiers();
TestAttrCantripCounts();
TestAttrPetEssence();
TestAttrNativeAndWire();
TestAttrVocab();
}
private static LootItemFacts Sword() => new()
{
Id = 10, Name = "Gold Tachi", ObjectClass = (int)AcObjectClass.MeleeWeapon,
Ints = { [131] = 60, [105] = 8, [159] = 45, [44] = 52, [5] = 300, [370] = 3, [374] = 2, [160] = 400, [158] = 2 },
Doubles = { [62] = 1.18, [29] = 1.2 },
Spells = { "Legendary Blood Thirst", "Epic Heart Thirst", "Major Strength", "Blood Drinker Self VI" },
};
private static List<LootEditItemChoice> Pick(params (string Id, bool On, LootItemAttributeOp Op, string Value)[] p)
=> p.Select(x => new LootEditItemChoice { Id = x.Id, On = x.On, Op = (int)x.Op, Value = x.Value }).ToList();
private static void TestAttrRowsAndGroups()
{
LootItemRuleDraft d = BuildOk(Sword());
List<LootItemAttribute> rows = d.Attributes;
Check(rows.Count > 0, "attr: rows for an item");
Check(!rows.Any(r => r.On), "attr: name + class ticks nothing by default");
string[] groups = rows.Select(r => r.Group).Distinct().ToArray();
Eq(string.Join(",", groups), "Item,Weapon / Armor,Ratings,Spells,Requirements", "attr: groups in display order");
LootItemAttribute mat = rows.Single(r => r.Id == "L:131");
Eq(mat.ItemText, "Gold", "attr: named value shown by name");
Check(!mat.Editable && mat.Ops[0] == LootItemAttributeOp.Exactly, "attr: material is = (or !=), not typed");
LootItemAttribute burden = rows.Single(r => r.Id == "L:5");
Eq(burden.Ops[0], LootItemAttributeOp.AtMost, "attr: burden defaults to at most");
Check(rows.Any(r => r.Id == "ratings" && r.ItemText == "5"), "attr: total ratings row (3 + 2)");
Check(rows.Any(r => r.Id == "D:62") && rows.Any(r => r.Id == "D:29"), "attr: weapon modifiers (doubles)");
Check(!rows.Any(r => r.Group == LootItemAttributes.GroupPet), "attr: no pet rows on a sword");
// "Items like this" ticks what it always required, nothing more.
LootItemRuleDraft like = BuildOk(Sword(), new() { Match = LootItemMatch.Like });
Eq(string.Join(",", like.Attributes.Where(r => r.On).Select(r => r.Id)),
"L:131,L:105,L:159,L:44,ratings,spell:Legendary Blood Thirst,spell:Epic Heart Thirst,spell:Major Strength,spell:Blood Drinker Self VI",
"attr: like ticks material, workmanship, wield skill, damage, ratings, the first 4 spells");
}
private static void TestAttrChoices()
{
// Burden at most 250 (typed), attack modifier exactly (two double conditions), material !=,
// and a row the item doesn't have (ignored).
List<LootEditItemChoice> c = Pick(
("L:5", true, LootItemAttributeOp.AtMost, "250"),
("D:62", true, LootItemAttributeOp.Exactly, ""),
("L:131", true, LootItemAttributeOp.Not, ""),
("L:9999", true, LootItemAttributeOp.AtLeast, "1"));
LootItemRuleDraft d = BuildOk(Sword(), new() { Choices = c });
string conds = string.Join(" ; ", d.Rule.Conditions.Select(Lines));
Eq(conds, "7:1 ; 1:^Gold Tachi$|1 ; 13:60|131 ; 2:250|5 ; 5:1.18|62 ; 4:1.18|62",
"attr: name + class, then the ticked rows in row order with their comparisons");
Eq(d.Attributes.Single(r => r.Id == "L:5").ToWire().Value, "250", "attr: the typed value goes back to the popup");
Check(d.Notes.Count == 0, "attr: no notes");
// A bad typed value keeps the item's and says so; an op the row doesn't offer is ignored.
LootItemRuleDraft bad = BuildOk(Sword(), new() { Choices = Pick(("L:105", true, LootItemAttributeOp.SpellOrBetter, "lots")) });
Check(bad.Rule.Conditions.Any(x => Lines(x) == "3:8|105"), "attr: bad value: the item's 8, at least");
Check(bad.Notes.Any(n => n.StartsWith("Workmanship: 'lots'")), "attr: bad value: a note");
LootItemRuleDraft frac = BuildOk(Sword(), new() { Choices = Pick(("L:105", true, LootItemAttributeOp.AtLeast, "7.5")) });
Check(frac.Notes.Any(n => n.Contains("whole number")), "attr: a long row takes whole numbers only");
// "Items like this" with a row unticked: the choice wins over the default.
LootItemRuleDraft like = BuildOk(Sword(), new() { Match = LootItemMatch.Like, Choices = Pick(("L:131", false, LootItemAttributeOp.Exactly, "")) });
Check(!like.Rule.Conditions.Any(x => Lines(x) == "12:60|131"), "attr: like, material unticked");
Check(like.Rule.Conditions.Any(x => Lines(x) == "3:8|105"), "attr: like, the other defaults stay");
Check(!like.Notes.Any(n => n.Contains("more than 4 spells")), "attr: no 4-spell note once the player chooses");
}
private static void TestAttrSpellTiers()
{
Eq(LootItemAttributes.SpellPattern("Major Strength", LootItemAttributeOp.SpellOrBetter), "^(Major|Epic|Legendary) Strength$", "spell: cantrip or better");
Eq(LootItemAttributes.SpellPattern("Major Strength", LootItemAttributeOp.SpellAnyTier), "^(Minor|Major|Epic|Legendary) Strength$", "spell: cantrip any tier");
Eq(LootItemAttributes.SpellPattern("Major Strength", LootItemAttributeOp.SpellExact), "^Major Strength$", "spell: exact");
Eq(LootItemAttributes.SpellPattern("Blood Drinker Self VI", LootItemAttributeOp.SpellOrBetter), "^Blood Drinker Self (VI|VII|VIII)$", "spell: level or better");
Eq(LootItemAttributes.SpellPattern("Legendary Blood Thirst", LootItemAttributeOp.SpellOrBetter), "^(Legendary) Blood Thirst$", "spell: Legendary or better is Legendary");
Eq(LootItemAttributes.SpellPattern("Aura of Defender", LootItemAttributeOp.SpellOrBetter), "^Aura of Defender$", "spell: no tier: exact");
Eq(LootItemAttributes.SpellPattern("Major Strength (II)", LootItemAttributeOp.SpellOrBetter), "^(Major|Epic|Legendary) Strength \\(II\\)$", "spell: the rest is escaped");
string orBetter = LootItemAttributes.SpellPattern("Epic Heart Thirst", LootItemAttributeOp.SpellOrBetter);
Check(Regex.IsMatch("Legendary Heart Thirst", orBetter, RegexOptions.IgnoreCase), "spell: Legendary is better than Epic");
Check(!Regex.IsMatch("Major Heart Thirst", orBetter, RegexOptions.IgnoreCase), "spell: Major is not");
Check(!Regex.IsMatch("Epic Heart Thirsty", orBetter, RegexOptions.IgnoreCase), "spell: still the whole name");
List<LootItemAttribute> rows = BuildOk(Sword()).Attributes;
Eq(rows.Single(r => r.Id == "spell:Major Strength").Ops[0], LootItemAttributeOp.SpellOrBetter, "spell: a cantrip defaults to or better");
Eq(rows.Single(r => r.Id == "spell:Blood Drinker Self VI").Ops[0], LootItemAttributeOp.SpellExact, "spell: a leveled spell defaults to exact (as before)");
Eq(rows.Single(r => r.Id == "spell:Major Strength").ItemText, "Major cantrip", "spell: the tier is shown");
// Like with every spell ticked: no limit of four once chosen.
var many = new LootItemFacts { Name = "Robe", ObjectClass = (int)AcObjectClass.Clothing, Spells = { "Minor Focus", "Major Willpower", "Epic Strength", "Legendary Endurance", "Major Coordination" } };
LootItemRuleDraft d = BuildOk(many, new() { Match = LootItemMatch.Like, Choices = Pick(("spell:Major Coordination", true, LootItemAttributeOp.SpellAnyTier, "")) });
Eq(d.Rule.Conditions.Count(x => x.NodeType == VTankNodeTypes.SpellNameMatch), 5, "spell: a fifth spell can be ticked");
Check(d.Rule.Conditions.Any(x => Lines(x) == "0:^(Minor|Major|Epic|Legendary) Coordination$"), "spell: any tier pattern in the rule");
}
private static void TestAttrCantripCounts()
{
List<LootItemAttribute> rows = BuildOk(Sword()).Attributes;
Eq(string.Join(",", rows.Where(r => r.Id.StartsWith("cantrips:")).Select(r => r.Label + "=" + r.ItemText)),
"Legendary cantrips=1,Epic-or-better cantrips=2,Major-or-better cantrips=3", "cantrips: a row per tier the item has, highest first");
Check(rows.Any(r => r.Id == "spellcount" && r.ItemText == "4"), "cantrips: spell count");
LootItemRuleDraft d = BuildOk(Sword(), new() { Choices = Pick(("cantrips:Epic", true, LootItemAttributeOp.AtLeast, "2"), ("spellcount", true, LootItemAttributeOp.AtLeast, "3")) });
Check(d.Rule.Conditions.Any(x => Lines(x) == "9:^(Epic|Legendary) ||2"), "cantrips: Spell Match, Epic or Legendary, at least 2");
Check(d.Rule.Conditions.Any(x => Lines(x) == "8:3"), "cantrips: spell count >= 3");
Check(LootItemRules.PreviewLines(d.Rule).Any(l => l.Contains(">= 2 spells matching")), "cantrips: preview in words");
}
private static void TestAttrPetEssence()
{
var wolf = new LootItemFacts
{
Id = 20, Name = "Fire Wolf Essence", ObjectClass = (int)AcObjectClass.Misc,
Ints = { [9053] = 12, [369] = 180, [9056] = 40, [362] = 1, [9075] = 2, [9070] = 1, [9054] = 16, [370] = 5, [92] = 30, [91] = 50 },
};
List<LootItemAttribute> rows = BuildOk(wolf).Attributes;
Check(rows.Any(r => r.Group == LootItemAttributes.GroupPet), "pet: bond makes it an essence");
Eq(rows.Single(r => r.Id == "L:362").ItemText, "Primalist", "pet: mastery by name");
Eq(rows.Single(r => r.Id == "L:9054").ItemText, "Fire", "pet: captured damage type by name");
Check(rows.Any(r => r.Id == "L:92" && r.Label == "Uses left"), "pet: uses (Item group)");
LootItemRuleDraft like = BuildOk(wolf, new() { Match = LootItemMatch.Like });
string conds = string.Join(" ; ", like.Rule.Conditions.Select(Lines));
Eq(conds, "7:8 ; 2007:5 ; 3:12|9053 ; 3:180|369 ; 3:40|9056 ; 12:1|362 ; 3:2|9075",
"pet: like = class, ratings, bond, level, potency, mastery, mutations");
var flagged = new LootItemFacts { Name = "Odd Essence", ObjectClass = (int)AcObjectClass.Misc, IsPetEssence = true, Ints = { [9073] = 1 } };
Check(BuildOk(flagged).Attributes.Any(r => r.Id == "L:9073"), "pet: the plugin's IsPetEssence shows the group");
var notPet = new LootItemFacts { Name = "Jibril's Essence", ObjectClass = (int)AcObjectClass.Misc, Ints = { [9073] = 1 } };
Check(!BuildOk(notPet).Attributes.Any(r => r.Group == LootItemAttributes.GroupPet), "pet: a name alone isn't an essence");
}
private static void TestAttrNativeAndWire()
{
LootItemRuleDraft d = BuildOk(Sword(), new() { Choices = Pick(("L:5", true, LootItemAttributeOp.AtMost, ""), ("spell:Major Strength", true, LootItemAttributeOp.SpellOrBetter, ""), ("cantrips:Legendary", true, LootItemAttributeOp.AtLeast, "")) });
var dropped = new List<string>();
LootRule? n = LootItemRules.ToNative(d.Rule, dropped);
Check(n != null && n.Conditions.Any(c => c.ToString().Contains("LongValKey") || c.ToString().Contains("[5]")), "native: burden converts");
Eq(dropped.Count, 2, "native: the two spell conditions are named as left out");
var st = new LootEditState { ItemDraft = new LootEditItemDraft { Seq = 4, AttributesSupported = true } };
foreach (LootItemAttribute r in d.Attributes) st.ItemDraft.Attributes.Add(r.ToWire());
string json = System.Text.Json.JsonSerializer.Serialize(st, LootEditJsonContext.Default.LootEditState);
LootEditState? back = System.Text.Json.JsonSerializer.Deserialize(json, LootEditJsonContext.Default.LootEditState);
LootEditItemAttribute? spell = back?.ItemDraft?.Attributes.FirstOrDefault(a => a.Id == "spell:Major Strength");
Check(back?.ItemDraft?.AttributesSupported == true, "wire: attributes supported round-trips");
Check(spell != null && spell.On && spell.Op == (int)LootItemAttributeOp.SpellOrBetter && spell.Ops.Count == 3, "wire: a row round-trips");
var cmd = new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { Choices = Pick(("L:5", true, LootItemAttributeOp.AtMost, "9")) } };
string cj = System.Text.Json.JsonSerializer.Serialize(cmd, LootEditJsonContext.Default.LootEditCommand);
LootEditCommand? cb = System.Text.Json.JsonSerializer.Deserialize(cj, LootEditJsonContext.Default.LootEditCommand);
Eq(cb?.Item?.Choices?.Single().Value, "9", "wire: choices round-trip");
LootEditCommand? old = System.Text.Json.JsonSerializer.Deserialize("{\"Op\":\"item_preview\",\"Item\":{\"Match\":2}}", LootEditJsonContext.Default.LootEditCommand);
Check(old?.Item != null && old.Item.Choices == null, "wire: an older engine's ask has no choices (defaults)");
}
private static void TestAttrVocab()
{
Eq(LootRuleText.ValueName(353, "4"), "Armor Rending", "vocab: imbue names");
Eq(LootRuleText.ValueName(362, "3"), "Naturalist", "vocab: summoning mastery");
Check(LootRuleText.LongKeys.Any(k => k.Id == 9053) && LootRuleText.LongKeys.Any(k => k.Id == 9075), "vocab: pet keys named");
Check(LootRuleText.LongKeys.Any(k => k.Id == 92 && k.Name.StartsWith("UsesRemaining")), "vocab: 92 is uses remaining");
Check(LootRuleText.LongKeys.Any(k => k.Id == 107 && k.Name == "ItemCurMana") && LootRuleText.LongKeys.Any(k => k.Id == 108 && k.Name == "ItemMaxMana"), "vocab: current and max mana");
var ids = LootRuleText.LongKeys.Select(k => k.Id).ToList();
Eq(ids.Count, ids.Distinct().Count(), "vocab: no long key named twice");
}
}

View file

@ -39,12 +39,19 @@ internal static partial class Program
{
("skills", LootRuleText.Skills), ("wield requirements", LootRuleText.WieldRequirements),
("materials", LootRuleText.Materials), ("damage types", LootRuleText.DamageTypes),
("creature types", LootRuleText.CreatureTypes),
})
{
Eq(table.Select(t => t.Id).Distinct().Count(), table.Length, $"{label}: ids unique");
Check(table.All(t => t.Name.Length > 0 && t.Name.All(ch => ch >= 32 && ch < 128)), $"{label}: names ASCII");
Eq(table.Select(t => t.Name).Distinct().Count(), table.Length, $"{label}: names unique");
}
Check(ReferenceEquals(LootRuleText.ValueTableFor(166), LootRuleText.CreatureTypes), "166 Slayer Type -> creature types");
Eq(LootRuleText.LongKeys.First(k => k.Id == 166).Name, "Slayer Type", "166 player-facing name");
Eq(LootRuleText.ValueName(166, "1"), "Olthoi", "ValueName 166/1 Olthoi");
Check(LootRuleText.CreatureTypes.Select(t => t.Name)
.SequenceEqual(LootRuleText.CreatureTypes.Select(t => t.Name).OrderBy(n => n, StringComparer.OrdinalIgnoreCase)),
"creature types listed alphabetically");
// Retail / ACE numbering (the old table had Light Weapons at 47, which is Missile Weapons).
string Skill(int id) => LootRuleText.Skills.First(s => s.Id == id).Name;

View file

@ -46,6 +46,7 @@ internal static partial class Program
RunLootAddTests(args);
RunT11Tests();
RunLootAddT11Tests();
RunLootAddAttributeTests();
RunUnknownNodeTests();
Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed.");

View file

@ -255,6 +255,18 @@
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!-- Kite / pull-away -->
<DataGridTemplateColumn Header="Kite" Width="90" MinWidth="70">
<DataGridTemplateColumn.CellTemplate><DataTemplate>
<TextBlock Text="{Binding Kite}" Padding="3,1" VerticalAlignment="Center"
ToolTip.Tip="Default = DEFAULT row. Off = fight in place. PullAway = tag then run until pulled clear, then kill."/>
</DataTemplate></DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate><DataTemplate>
<ComboBox ItemsSource="{Binding $parent[Window].((local:MainWindow)DataContext).KiteOptions}"
SelectedItem="{Binding Kite, Mode=TwoWay}"/>
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!-- Delete -->
<DataGridTemplateColumn Header="Del" Width="34" CanUserResize="False" CanUserSort="False">
<DataGridTemplateColumn.CellTemplate><DataTemplate>

View file

@ -29,6 +29,9 @@ public partial class MainWindow : Window
{ "None", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
public string[] PetOptions { get; } =
{ "PAuto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
/// <summary>RynthAi KiteModes: Default follows the DEFAULT row; PullAway tags then runs clear.</summary>
public string[] KiteOptions { get; } =
{ "Default", "Off", "PullAway" };
private string _charFolder = string.Empty;
private string _monstersPath = string.Empty;

View file

@ -23,6 +23,7 @@ public class MonsterRule : INotifyPropertyChanged
private int _offhandId;
private int _preferredAmmoItemId;
private string _petDamage = "PAuto";
private string _kite = "Default";
public string Name { get => _name; set { _name = value; OnPropertyChanged(); } }
/// <summary>The plugin's rule group label. Kept and editable here (before 2026-10-05 an
@ -58,6 +59,8 @@ public class MonsterRule : INotifyPropertyChanged
/// <summary>Optional loose ammo stack id for missile combat while this rule matches (0 = auto).</summary>
public int PreferredAmmoItemId { get => _preferredAmmoItemId; set { _preferredAmmoItemId = value; OnPropertyChanged(); } }
public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } }
/// <summary>Pull-away kite: Default (follow DEFAULT row), Off, or PullAway. RynthAi KiteModes.</summary>
public string Kite { get => _kite; set { _kite = value ?? "Default"; OnPropertyChanged(); } }
/// <summary>Every field in the file this class doesn't know (e.g. the plugin's CustomDebuffs,
/// or one added later), written back unchanged.</summary>
@ -94,6 +97,7 @@ public class MonsterRule : INotifyPropertyChanged
OffhandId = _offhandId,
PreferredAmmoItemId = _preferredAmmoItemId,
PetDamage = _petDamage,
Kite = _kite,
};
}
@ -122,6 +126,7 @@ public class MonsterRule : INotifyPropertyChanged
OffhandId = src.OffhandId;
PreferredAmmoItemId = src.PreferredAmmoItemId;
PetDamage = src.PetDamage;
Kite = src.Kite;
}
public event PropertyChangedEventHandler? PropertyChanged;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -20,6 +20,8 @@ internal static class Program
CreatureWeaknessTests.Register(runner);
MonsterDamageTierTests.Register(runner);
LootBaselineTests.Register(runner);
PetCaptureRulesTests.Register(runner);
ChatClassifierTests.Register(runner);
return runner.Run("RynthAi tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -30,6 +30,9 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\CreatureData\PlayerWeenies.cs" Link="Linked\PlayerWeenies.cs" />
<!-- Loot: the measured loot-timer baseline and its [LootSettings] log line. -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\LootBaseline.cs" Link="Linked\LootBaseline.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\MiniRemote\PetCaptureRules.cs" Link="Linked\PetCaptureRules.cs" />
<!-- RynthChat: the channel classifier (no dependencies). -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthChat\ChatClassifier.cs" Link="Linked\ChatClassifier.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -0,0 +1,46 @@
// RynthChat's channel classifier: a line's [General]/[Trade]/... tag decides the Channels tab (ILT delivers
// those as chat type 0x1C), and the type map covers 0x1C too. Ported from SilentKelpie's PR 12.
using RynthCore.Plugin.RynthChat;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiTests.Tests;
internal static class ChatClassifierTests
{
public static void Register(Runner r)
{
r.Add("chat classifier: a [General]/[Trade]/... tag puts the line on Channels whatever its chat type", TaggedLines);
r.Add("chat classifier: type 0x1C is a channel; the old type map is unchanged", TypeMap);
r.Add("chat classifier: untagged system and combat lines stay where they were", UntaggedLines);
}
private static void TaggedLines()
{
foreach (string tag in new[] { "[General]", "[Trade]", "[LFG]", "[Roleplay]", "[Society]", "[Celestial Hand]", "[Eldrytch Web]", "[Radiant Blood]", "[Admin]" })
{
Check.Eq(ChatClassifier.ChannelFor(tag + " Someone says, \"hi\"", 0x1C), ChatClassifier.Channels, tag + " at 0x1C");
Check.Eq(ChatClassifier.ChannelFor(tag.ToLowerInvariant() + " x", 0x00), ChatClassifier.Channels, tag + " in lower case at type 0");
}
Check.False(ChatClassifier.IsChannelTagged("[Bank] Balance: 5"), "[Bank] is not a channel tag");
Check.False(ChatClassifier.IsChannelTagged(null), "null");
Check.False(ChatClassifier.IsChannelTagged(""), "empty");
Check.False(ChatClassifier.IsChannelTagged("General says hi"), "no bracket");
}
private static void TypeMap()
{
Check.Eq(ChatClassifier.ChannelForType(0x1C), ChatClassifier.Channels, "0x1C");
Check.Eq(ChatClassifier.ChannelForType(0x08), ChatClassifier.Channels, "0x08");
Check.Eq(ChatClassifier.ChannelForType(0x09), ChatClassifier.Channels, "0x09");
Check.Eq(ChatClassifier.ChannelForType(0x03), ChatClassifier.Chat, "tell");
Check.Eq(ChatClassifier.ChannelForType(0x06), ChatClassifier.Combat, "combat");
Check.Eq(ChatClassifier.ChannelForType(0x01), ChatClassifier.Other, "unknown");
}
private static void UntaggedLines()
{
Check.Eq(ChatClassifier.ChannelFor("You are hungry.", 0x00), ChatClassifier.System, "system line");
Check.Eq(ChatClassifier.ChannelFor("You hit the Drudge for 5.", 0x06), ChatClassifier.Combat, "combat line");
Check.Eq(ChatClassifier.ChannelFor("[Bank] Balance: 5", 0x00), ChatClassifier.System, "a [Bank] line keeps its type");
}
}

View file

@ -0,0 +1,108 @@
// ACECustom MonsterCapture health / range / lens table — matches Source/ACE.Server/Entity/MonsterCapture.cs.
using RynthCore.Plugin.RynthAi.MiniRemote;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiTests.Tests;
internal static class PetCaptureRulesTests
{
public static void Register(Runner r)
{
r.Add("pet capture: health gate matches ACECustom (≤20% or under 20 HP)", HealthGate);
r.Add("pet capture: Asheron's Lens bypasses the health gate", AsheronsBypass);
r.Add("pet capture: range is 5 m; dead creatures are never capturable", RangeAndDead);
r.Add("pet capture: lens WCIDs match PetGuideController", LensWcids);
r.Add("pet capture: a creature is left alone after 5 tries with no capture, then retried after the block", ThrottlePerTarget);
r.Add("pet capture: 15 lens uses with no capture anywhere trip the backstop; a success resets it", ThrottleBackstop);
}
private static void HealthGate()
{
// Full health — refuse.
Check.False(PetCaptureRules.IsWeakEnough(100, 100), "100/100 too strong");
Check.False(PetCaptureRules.IsWeakEnough(21, 100), "21% and ≥20 HP too strong");
// Fraction gate.
Check.True(PetCaptureRules.IsWeakEnough(20, 100), "20% exactly is allowed");
Check.True(PetCaptureRules.IsWeakEnough(1, 100), "1% allowed");
// Absolute HP gate (high % but under 20 HP).
Check.True(PetCaptureRules.IsWeakEnough(15, 50), "15/50 = 30% but under 20 HP");
Check.True(PetCaptureRules.IsWeakEnough(19, 19), "19/19 under 20 HP");
// Ratio-only path (no absolute HP): only the fraction half.
Check.True(PetCaptureRules.IsWeakEnoughRatio(0.20f), "ratio 0.20");
Check.False(PetCaptureRules.IsWeakEnoughRatio(0.21f), "ratio 0.21");
Check.False(PetCaptureRules.IsWeakEnoughRatio(0f), "ratio 0 = dead");
Check.False(PetCaptureRules.IsWeakEnough(0, 100), "0 current = dead");
}
private static void AsheronsBypass()
{
var asheron = PetCaptureRules.LensAt(4);
Check.Eq(asheron.Wcid, 78780012u, "Asheron's WCID");
Check.True(asheron.BypassesHealthGate, "bypasses health");
Check.True(PetCaptureRules.CanAttempt(asheron, 100, 100), "full health ok for Asheron's");
Check.False(PetCaptureRules.CanAttempt(asheron, 0, 100), "still not when dead");
var flawed = PetCaptureRules.LensAt(0);
Check.False(PetCaptureRules.CanAttempt(flawed, 100, 100), "Flawed refuses full health");
Check.True(PetCaptureRules.CanAttempt(flawed, 10, 100), "Flawed at 10%");
}
private static void RangeAndDead()
{
Check.Eq(PetCaptureRules.CaptureRangeM, 5.0f, "5 m range");
Check.True(PetCaptureRules.InRange(0), "at feet");
Check.True(PetCaptureRules.InRange(5.0), "at 5 m");
Check.False(PetCaptureRules.InRange(5.01), "past 5 m");
Check.False(PetCaptureRules.InRange(-1), "unknown distance");
}
private static void LensWcids()
{
Check.Eq(PetCaptureRules.Lenses.Length, 5, "five selectable lenses");
Check.Eq(PetCaptureRules.LensAt(0).Wcid, 78780001u, "Flawed");
Check.Eq(PetCaptureRules.LensAt(1).Wcid, 78780002u, "Pristine");
Check.Eq(PetCaptureRules.LensAt(2).Wcid, 78780003u, "Perfect");
Check.Eq(PetCaptureRules.LensAt(3).Wcid, 78780010u, "Resonance");
Check.Eq(PetCaptureRules.LensAt(4).Wcid, 78780012u, "Asheron's");
Check.Eq(PetCaptureRules.LensNames.Length, PetCaptureRules.Lenses.Length, "combo labels match");
}
private static void ThrottlePerTarget()
{
var t = new PetCaptureThrottle();
long now = 1000;
for (int i = 0; i < PetCaptureThrottle.MaxTriesPerTarget; i++)
{
Check.True(t.MayAttempt(7, now), $"try {i + 1} allowed");
t.RecordAttempt(7, now);
now += 2500;
}
Check.False(t.MayAttempt(7, now), "5 tries used: blocked");
Check.True(t.BlockedSecondsLeft(7, now) > 0, "block time left reported");
Check.True(t.MayAttempt(8, now), "another creature is not blocked");
Check.False(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs - 3000), "still blocked just before the block ends");
Check.True(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 1), "block served: tries again");
t.RecordAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 1);
Check.True(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 2), "a fresh set of tries after the block");
}
private static void ThrottleBackstop()
{
var t = new PetCaptureThrottle();
long now = 0;
for (int i = 0; i < PetCaptureThrottle.MaxTriesWithoutSuccess; i++)
{
Check.False(t.Exhausted, $"not exhausted before use {i + 1}");
t.RecordAttempt(100 + i, now); // a new creature each time: per-target never trips
now += 2500;
}
Check.True(t.Exhausted, "15 uses over many creatures, no capture: exhausted");
Check.False(t.MayAttempt(999, now), "nothing more is allowed");
t.RecordSuccess();
Check.False(t.Exhausted, "a capture reply resets the backstop");
Check.True(t.MayAttempt(100, now), "and the per-target blocks");
}
}

View file

@ -5,12 +5,216 @@ namespace RynthILT.Tests;
// The Lugian-hammer aetheria rules (Hub/IltChunkClap.cs): Infinite Leaftide aetheria goes up to
// level 10, and aetheria carrying a C, CD or CDR rating is kept unless its keep switch is off.
// The cap covers levelled Coalesced Aetheria; an unlevelled one chunks, as in ub-IT. Corrupted
// weapons follow ub-IT's hard rules and its optional keep rules, and /clap needs a colour with its
// own trinket.
internal static class AetheriaChunkTests
{
public static void Register(Runner r)
{
r.Add("aetheria: the chunk cap runs to one past ILT's level 10", Cap);
r.Add("aetheria: C / CD / CDR ratings are kept by default, each with its own switch", Ratings);
r.Add("aetheria: rating level - at or above keeps, below chunks (Coalesced too)", RatingLevel);
r.Add("aetheria: the level cap applies to levelled Coalesced Aetheria; unlevelled Coalesced chunks (ub-IT)", CoalescedCap);
r.Add("aetheria: a failed read is not 'unlevelled': unreadable pieces are kept, levelled Coalesced keeps its cap", UnreadableAetheria);
r.Add("aetheria: never-chunk, tinker / imbue, item XP, ratings and the cap each keep a piece", AetheriaRules);
r.Add("chunk: kind by class and name; chunks and powder are clap material", Kinds);
r.Add("corrupted: ub-IT hard rules (workmanship, cleave 1, or 2 on two-handed non-thrust)", CorruptedHardRules);
r.Add("corrupted: ub-IT keep rules, all off by default", CorruptedKeepRules);
r.Add("corrupted: a failed read is kept; two-handed cleave 2 chunks and other cleave 2 does not", UnreadableCorrupted);
r.Add("chunk: busy blocks peace mode, not combat with chunk-in-combat on (ub-IT v2.0.1059)", BusyGate);
r.Add("chunk: a target that leaves the pack counts as chunked; still carried after 10 s times out", WaitOutcome);
r.Add("clap: the server's WCIDs, each colour paired with its trinket, Coalesced only unrevealed level 1-3", ClapPairs);
}
/// <summary>
/// Coalesced Aetheria has its level from loot (ACECustom 1-10, ratings at 6+); it used to skip
/// the cap, so a cap of 9 still chunked a level 10 Coalesced piece.
/// </summary>
private static void CoalescedCap()
{
Check.True(IltChunkClap.UnderChunkCap(8, 9), "level 8 under a cap of 9");
Check.False(IltChunkClap.UnderChunkCap(9, 9), "level 9 is not below 9");
Check.False(IltChunkClap.UnderChunkCap(10, 9), "a level 10 Coalesced piece is kept");
Check.True(IltChunkClap.UnderChunkCap(10, 11), "11 chunks every level");
Check.False(IltChunkClap.UnderChunkCap(0, 11), "revealed aetheria with no level read: never chunked");
Check.False(IltChunkClap.UnderChunkCap(9, 9, coalesced: true), "a levelled Coalesced piece keeps the cap");
Check.True(IltChunkClap.UnderChunkCap(0, 4, coalesced: true), "an unlevelled Coalesced piece chunks (it used to be kept forever)");
Check.True(IltChunkClap.UnderChunkCap(0, 1, coalesced: true), "even with the lowest cap");
}
private static readonly IltChunkClap.AetheriaFacts PlainCoalesced = new(
Coalesced: true, MaxLevel: 0, NeverChunk: false, ItemXp: 0, Tinkers: 0, Imbue: 0, Crit: 0, CritDamage: 0, CritDamageResist: 0);
private static void AetheriaRules()
{
var g = new IltGearState();
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced), null, "a plain unlevelled Coalesced piece chunks");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 3 }), null, "level 3 under the default cap of 4");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 4 }), "level at or above the cap", "level 4 at the default cap");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { NeverChunk = true }), "never-chunk flag", "bool 9030");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Tinkers = 1 }), "tinkered or imbued", "tinkered");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Imbue = 4 }), "tinkered or imbued", "imbued");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { ItemXp = 100 }), "has item XP", "levelled by use");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Crit = 2 }), "kept for its C / CD / CDR rating", "a C 2 piece is kept by default");
g.KeepAetheriaWithCrit = false;
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Crit = 2 }), null, "C switch off: a C 2 piece chunks");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Coalesced = false }), "no level read", "revealed aetheria needs a level");
}
/// <summary>
/// The rules read 0 for "the item has none" and for "the host could not read it". An unlevelled
/// Coalesced piece is chunked (ub-IT), but only when its level was truly read as none; a piece whose
/// properties could not be read is kept, whatever the numbers say.
/// </summary>
private static void UnreadableAetheria()
{
var g = new IltGearState();
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced), null, "read as unlevelled: chunks");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Unreadable = "no appraisal" }),
"item data unreadable (no appraisal)", "the same piece with failed reads: kept");
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 2, Unreadable = "no item XP" }),
"item data unreadable (no item XP)", "a levelled piece with failed reads: kept");
Check.Eq(IltChunkClap.AetheriaSkip(new IltGearState { ChunkAetheriaUnderLevel = 1 }, PlainCoalesced), null, "unlevelled chunks at the lowest cap too");
// Levelled Coalesced pieces keep the cap.
var cap9 = new IltGearState { ChunkAetheriaUnderLevel = 9 };
Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 8 }), null, "levelled 8 under a cap of 9");
Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 9 }), "level at or above the cap", "levelled 9 at a cap of 9");
Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 10 }), "level at or above the cap", "levelled 10 over a cap of 9");
Check.Eq(IltChunkClap.AetheriaSkip(new IltGearState { ChunkAetheriaUnderLevel = 11 }, PlainCoalesced with { MaxLevel = 10 }), null, "cap 11 chunks every level");
}
private static void UnreadableCorrupted()
{
var g = new IltGearState();
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Unreadable = "no appraisal" }),
"item data unreadable (no appraisal)", "failed reads: kept (they would read as a plain weapon)");
var keepCb = new IltGearState { KeepCorruptedCrushingBlow = true };
Check.Eq(IltChunkClap.CorruptedSkip(keepCb, PlainSword with { Unreadable = "float properties" }),
"item data unreadable (float properties)", "a keep rule whose float cannot be read keeps the weapon");
var twoHanded = PlainSword with { WieldSkill = 41, Cleaving = 2 };
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded), null, "two-handed cleave 2 chunks");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 2 }), "cleave over the limit", "other cleave 2 is kept");
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { WieldSkill = 0, WeaponType = 11 }), null, "WeaponType two-handed counts");
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { AttackType = 2 }), "cleave over the limit", "two-handed thrust keeps the 1 limit");
}
private static void Kinds()
{
var gem = RynthCore.Loot.AcObjectClass.Gem;
Check.Eq(IltChunkClap.KindOf(gem, "Coalesced Aetheria"), IltChunkClap.ChunkKind.Aetheria, "Coalesced");
Check.Eq(IltChunkClap.KindOf(gem, "Blue Aetheria"), IltChunkClap.ChunkKind.Aetheria, "revealed sigil");
Check.Eq(IltChunkClap.KindOf(gem, "Red Aetheria Chunk"), IltChunkClap.ChunkKind.None, "chunk");
Check.Eq(IltChunkClap.KindOf(gem, "Aetheria Powder"), IltChunkClap.ChunkKind.None, "powder");
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MeleeWeapon, "Corrupted Greatsword"), IltChunkClap.ChunkKind.Corrupted, "melee");
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MissileWeapon, "Corrupted Bow"), IltChunkClap.ChunkKind.Corrupted, "missile");
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.WandStaffOrb, "Corrupted Orb"), IltChunkClap.ChunkKind.None, "casters are not chunked (ub-IT)");
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MeleeWeapon, "Greatsword"), IltChunkClap.ChunkKind.None, "not corrupted");
}
private static readonly IltChunkClap.CorruptedFacts PlainSword = new() { Workmanship = 6, AttackType = 4, WieldSkill = 45 };
private static void CorruptedHardRules()
{
var g = new IltGearState();
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword), null, "a plain corrupted sword chunks");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Workmanship = 0 }), "no workmanship", "workmanship 0");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Tinkers = 1 }), "tinkered or imbued", "tinkered");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Imbue = 1 }), "tinkered or imbued", "imbued");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { NeverChunk = true }), "never-chunk flag", "bool 9030");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 1 }), null, "one-handed cleave 1");
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 2 }), "cleave over the limit", "one-handed cleave 2");
var twoHanded = PlainSword with { WieldSkill = 41, Cleaving = 2 };
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded), null, "two-handed cleave 2 chunks (it never did before)");
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { Cleaving = 3 }), "cleave over the limit", "two-handed cleave 3");
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { AttackType = 2 }), "cleave over the limit", "a two-handed thrust weapon keeps the 1 limit");
Check.Eq(IltChunkClap.MaxChunkCleave(0, 11, 4), 2, "WeaponType TwoHanded counts too");
Check.Eq(IltChunkClap.MaxChunkCleave(45, 0, 4), 1, "one-handed");
}
private static void CorruptedKeepRules()
{
var g = new IltGearState();
var loaded = PlainSword with
{
CritFrequency = 0.1, CritMultiplier = 1.5, IgnoreArmor = 0.2, Slayer = 5, AttackType = 160,
ElementalBonus = 10, MaxDamage = 400, Spells = new[] { 2072 },
};
Check.Eq(IltChunkClap.CorruptedSkip(g, loaded), null, "every keep rule is off by default");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedCrushingBlow = true }, loaded), "kept: Crushing Blow", "Crushing Blow");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedBitingStrike = true }, loaded), "kept: Biting Strike", "Biting Strike");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedArmorCleaving = true }, loaded), "kept: Armor Cleaving", "Armor Cleaving");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedAnySlayer = true }, loaded), "kept: slayer", "slayer");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMultiStrike = true }, loaded), "kept: multi-strike", "multi-strike 160");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMultiStrike = true }, PlainSword), null, "a single slash is not multi-strike");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedElementalBonus = true }, loaded), "kept: elemental bonus", "elemental");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMaxDamageAtLeast = 400 }, loaded), "kept: max damage", "max damage at the limit");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMaxDamageAtLeast = 401 }, loaded), null, "max damage under the limit");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedAnySpell = true }, loaded), "kept: has a spell", "any spell");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedSpellIds = "100, 2072" }, loaded), "kept: listed spell", "listed spell id");
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedSpellIds = "100 200" }, loaded), null, "other spell ids");
Check.Eq(IltChunkClap.ParseSpellIds("1, 2;3 x -4 0").Count, 3, "positive ids only, any separator");
Check.Eq(IltChunkClap.ParseSpellIds(null).Count, 0, "no list");
}
/// <summary>
/// Silentkelpie 2026-10-18: a Coalesced piece was chunked (Red Aetheria Chunk arrived) with no
/// result line, and it was filed as skipped after 10 s instead of counted.
/// </summary>
private static void WaitOutcome()
{
Check.Eq(IltChunkClap.WaitOutcome(500, targetStillCarried: true), IltChunkClap.ChunkWait.Waiting, "still carried, within the wait");
Check.Eq(IltChunkClap.WaitOutcome(1_100, targetStillCarried: false), IltChunkClap.ChunkWait.Gone, "gone from the pack: chunked");
Check.Eq(IltChunkClap.WaitOutcome(12_000, targetStillCarried: false), IltChunkClap.ChunkWait.Gone, "gone beats the timeout");
Check.Eq(IltChunkClap.WaitOutcome(10_000, targetStillCarried: true), IltChunkClap.ChunkWait.TimedOut, "still carried at 10 s: timed out");
}
private static void BusyGate()
{
Check.True(IltChunkClap.AllowsChunkWhileBusy(isBusy: false, isPeace: true, chunkInCombat: false), "idle in peace");
Check.False(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: true, chunkInCombat: true), "busy in peace waits");
Check.True(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: false, chunkInCombat: true), "busy swinging with chunk-in-combat");
Check.False(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: false, chunkInCombat: false), "busy in combat without it");
}
/// <summary>
/// ACECustom /clap: red (Coalesced 42636 at 1-3, chunk 310147, powder 42644) with Empyrean
/// Trinkets (34276); blue (42635, 310149, 300019) with Falatacot (34277). 42635/42636 were taken
/// for chunks, and one side alone counted, so auto-clap sent /clap with nothing to pair.
/// </summary>
private static void ClapPairs()
{
const string Co = "Coalesced Aetheria";
Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 2), IltChunkClap.ClapPart.Red, "red Coalesced level 2");
Check.Eq(IltChunkClap.ClapPartOf(42635, Co, 3), IltChunkClap.ClapPart.Blue, "blue Coalesced level 3");
Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 0), IltChunkClap.ClapPart.Red, "level not read yet: the server decides");
Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 4), IltChunkClap.ClapPart.None, "level 4 Coalesced is not clapped");
Check.Eq(IltChunkClap.ClapPartOf(42636, "Aetheria", 1), IltChunkClap.ClapPart.None, "revealed aetheria is not clapped");
Check.Eq(IltChunkClap.ClapPartOf(42637, Co, 1), IltChunkClap.ClapPart.None, "yellow has no clap use");
Check.Eq(IltChunkClap.ClapPartOf(310147, "Red Aetheria Chunk", 0), IltChunkClap.ClapPart.Red, "red chunk");
Check.Eq(IltChunkClap.ClapPartOf(310149, "Blue Aetheria Chunk", 0), IltChunkClap.ClapPart.Blue, "blue chunk");
Check.Eq(IltChunkClap.ClapPartOf(310150, "Yellow Aetheria Chunk", 0), IltChunkClap.ClapPart.None, "yellow chunk");
Check.Eq(IltChunkClap.ClapPartOf(42644, "Aetheria Powder", 0), IltChunkClap.ClapPart.Red, "red powder");
Check.Eq(IltChunkClap.ClapPartOf(300019, "Aetheria Powder", 0), IltChunkClap.ClapPart.Blue, "blue powder");
Check.Eq(IltChunkClap.ClapPartOf(34276, "Ancient Empyrean Trinket", 0), IltChunkClap.ClapPart.Empyrean, "Empyrean trinket");
Check.Eq(IltChunkClap.ClapPartOf(34277, "Ancient Falatacot Trinket", 0), IltChunkClap.ClapPart.Falatacot, "Falatacot trinket");
Check.Eq(IltChunkClap.ClapPartOf(0, "Red Aetheria Chunk", 0), IltChunkClap.ClapPart.Red, "no WCID yet: the chunk name");
Check.Eq(IltChunkClap.ClapPartOf(0, Co, 1), IltChunkClap.ClapPart.None, "no WCID yet: a Coalesced piece's colour is unknown");
Check.Eq(IltChunkClap.ClapPartOf(273, "Pyreal", 0), IltChunkClap.ClapPart.None, "anything else");
var R = IltChunkClap.ClapPart.Red; var B = IltChunkClap.ClapPart.Blue;
var E = IltChunkClap.ClapPart.Empyrean; var F = IltChunkClap.ClapPart.Falatacot;
Check.True(IltChunkClap.CanClap(new[] { R, E }), "red + Empyrean");
Check.True(IltChunkClap.CanClap(new[] { B, F }), "blue + Falatacot");
Check.False(IltChunkClap.CanClap(new[] { R, F }), "red needs Empyrean, not Falatacot");
Check.False(IltChunkClap.CanClap(new[] { B, E }), "blue needs Falatacot, not Empyrean");
Check.False(IltChunkClap.CanClap(new[] { E, F }), "trinkets alone");
Check.False(IltChunkClap.CanClap(new[] { R, B }), "aetheria alone");
Check.False(IltChunkClap.CanClap(System.Array.Empty<IltChunkClap.ClapPart>()), "nothing carried");
}
private static void Cap()
@ -39,4 +243,35 @@ internal static class AetheriaChunkTests
g.KeepAetheriaWithCritDamageResist = false;
Check.False(IltChunkClap.KeptForRatings(g, 3, 3, 3), "every switch off: ratings don't protect");
}
/// <summary>
/// The rating level: a C / CD / CDR rating at or above it keeps the piece, a lower one chunks
/// (if the level cap allows). The default of 1 keeps any rating, as before.
/// </summary>
private static void RatingLevel()
{
var g = new IltGearState();
Check.Eq(g.KeepAetheriaRatingAtLeast, 1, "default: any rating keeps");
Check.True(IltChunkClap.KeptForRatings(g, 1, 0, 0), "C 1 kept at the default");
g.KeepAetheriaRatingAtLeast = 2;
Check.False(IltChunkClap.KeptForRatings(g, 1, 0, 0), "C 1 below level 2: chunks");
Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C 2 at level 2: kept");
Check.True(IltChunkClap.KeptForRatings(g, 3, 0, 0), "C 3 above level 2: kept");
Check.True(IltChunkClap.KeptForRatings(g, 1, 0, 2), "CDR 2 keeps a C 1 + CDR 2 piece");
Check.False(IltChunkClap.KeptForRatings(g, 1, 1, 1), "every rating below the level: chunks");
g.KeepAetheriaWithCrit = false;
Check.False(IltChunkClap.KeptForRatings(g, 5, 0, 0), "a switch that is off ignores the level");
Check.Eq(IltChunkClap.ClampRatingLevel(0), 1, "below 1 clamps to 1");
Check.Eq(IltChunkClap.ClampRatingLevel(99), IltChunkClap.MaxRatingLevel, "clamped to the maximum");
var coalescedC1 = PlainCoalesced with { Crit = 1 };
var level2 = new IltGearState { KeepAetheriaRatingAtLeast = 2 };
Check.Eq(IltChunkClap.AetheriaSkip(level2, coalescedC1), null, "an unlevelled C 1 Coalesced piece chunks at rating level 2");
Check.Eq(IltChunkClap.AetheriaSkip(level2, PlainCoalesced with { Crit = 2 }), "kept for its C / CD / CDR rating", "a C 2 one is kept");
Check.Eq(IltChunkClap.AetheriaSkip(level2, coalescedC1 with { MaxLevel = 6 }), "level at or above the cap",
"a low rating does not override the level cap");
}
}

View file

@ -31,6 +31,8 @@ internal static class AttributeRaiserTests
r.Add("attr raiser: by-hand +1 / +10 priced like UB, refused when unaffordable, costs read on tab open", ByHandPriced);
r.Add("aug planner: /aug pulled on tab open, totals, reset targets, copy texts", AugPlanner);
r.Add("aug refresh: banner alone does not end /aug; Current updates from level lines", AugRefreshWaitsForLevelLines);
r.Add("aug refresh: a probe that left Current empty retries /aug once; a click during the probe runs after it", AugProbeRetry);
r.Add("aug lines: separators in the level (4,300 / 4.300 / 4 300 / 4'300) and trailing notes read", AugLineValues);
r.Add("aug costs: UB's ILT model (tier starts at its S level) in closed form", AugCostModel);
r.Add("aug costs: per-server multipliers and rules, saved and reset", AugCostSettings);
}
@ -225,6 +227,63 @@ internal static class AttributeRaiserTests
}), "Current updates once Creature:/Item: lines arrive");
}
// Silentkelpie (PR #12): the login probe could end on the banner alone (chat-hold backlog) and leave
// Current empty with nothing to retry it; a Refresh current click during the probe was dropped.
private static void AugProbeRetry()
{
var hub = NewHub("InfiniteLeaftide", new IltSettings(), "aug-probe-retry", out _);
var prog = hub.Progression;
// Probe reply: the banner and no level lines. The tap runs ApplyAugLines then AfterExternalAugCapture.
prog.ApplyAugLines(new List<string> { "---------------------------", "Advanced Augmentation Levels:" });
prog.AfterExternalAugCapture();
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "Current still empty: /aug is sent again");
prog.AfterExternalAugCapture(); // the retry is in flight, and was the one retry
prog.ApplyAugLines(new List<string> { "Advanced Augmentation Levels:" });
prog.AfterExternalAugCapture();
for (int i = 0; i < 20; i++) { hub.Tick(); Thread.Sleep(25); }
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 1, "only one retry");
Reply(hub, "Creature:4,300", "Item:100");
Check.True(TickUntil(hub, () =>
{
var sb = new System.Text.StringBuilder();
prog.AppendSnapshotJson(sb);
return sb.ToString().Contains("\"cur\":4300", StringComparison.Ordinal);
}), "the retry's level lines fill Current");
// A probe with levels needs no retry.
var hub2 = NewHub("InfiniteLeaftide", new IltSettings(), "aug-probe-ok", out _);
hub2.Progression.ApplyAugLines(new List<string> { "Creature: 12" });
hub2.Progression.AfterExternalAugCapture();
for (int i = 0; i < 20; i++) { hub2.Tick(); Thread.Sleep(25); }
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 0, "levels present: no retry");
}
private static void AugLineValues()
{
Check.True(IltParse.AugLine.IsMatch("Creature:4,300") && IltParse.AugLine.IsMatch("Creature: 4.300")
&& IltParse.AugLine.IsMatch("Creature: 4 300") && IltParse.AugLine.IsMatch("Creature: 4'300"), "the regex matches each grouping");
Check.False(IltParse.AugLine.IsMatch("Creature: none") || IltParse.AugLine.IsMatch("Advanced Augmentation Levels:"), "and not a line with no number");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature:4,300").Groups[2].Value), 4300L, "comma");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4.300").Groups[2].Value), 4300L, "period");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4 300").Groups[2].Value), 4300L, "space");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4'300").Groups[2].Value), 4300L, "apostrophe");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 1,234,567").Groups[2].Value), 1234567L, "two groups");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Duration: 5 (adds 3)").Groups[2].Value), 5L, "a trailing note");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Specialize: 2").Groups[2].Value), 2L, "plain");
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Item: 2750").Groups[2].Value), 2750L, "no separator");
Check.Eq(IltParse.ParseAugValue(""), 0L, "empty");
var hub = NewHub("InfiniteLeaftide", new IltSettings(), "aug-values", out _);
hub.Progression.ApplyAugLines(new List<string> { "Creature: 2 750", "Item: 1.200", "Life: 300" });
var sb = new System.Text.StringBuilder();
hub.Progression.AppendSnapshotJson(sb);
string snap = sb.ToString();
Check.True(snap.Contains("\"cur\":2750", StringComparison.Ordinal) && snap.Contains("\"cur\":1200", StringComparison.Ordinal)
&& snap.Contains("\"cur\":300", StringComparison.Ordinal), "the planner takes the grouped levels whole");
}
private static void Patterns()
{
Check.True(ServerFeatureGate.Matches("InfiniteLeaftide", "InfiniteLeaftide"), "exact");

View file

@ -16,6 +16,7 @@ internal static class BankCommandTests
r.Add("bank: one item table matches ACECustom's handler (deposit / withdraw / transfer)", ItemTable);
r.Add("bank: transfer commands, trade notes by denomination, quoted names", Transfers);
r.Add("bank: transfer replies (notes' equivalent, bound prestige coins) are recognised", TransferReplies);
r.Add("bank: only the balance dump is backstop-eaten, and only just after a quiet refresh", LeakedDump);
}
private static int TransferIndex(string code) =>
@ -117,4 +118,29 @@ internal static class BankCommandTests
Check.False(IltBankCommands.IsActionReply("Bob tells you, \"Deposited 5 pyreals\""), "a tell is not");
Check.False(IltBankCommands.IsActionReply(""), "empty");
}
/// <summary>
/// SilentKelpie's backstop for a quiet refresh whose reply leaked into chat, narrowed: the dump's
/// header and "Label: N" lines only, never errors, bound-coin notes or Transferred / Received lines,
/// and never a balance read outside the window after a quiet refresh (a macro's or plugin's /bank).
/// </summary>
private static void LeakedDump()
{
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Your balances are:"), "header");
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Pyreals: 1,000"), "pyreals");
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Luminance: 2,500,000"), "luminance");
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Weakly Enlightened Coins: 3"), "weakly enlightened coins");
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Prestige Coins: 2 (bound to you and cannot be traded)"), "prestige coins");
Check.False(IltBanking.IsBalanceDumpLine("[BANK] Too many parameters"), "an error");
Check.False(IltBanking.IsBalanceDumpLine("[BANK] Prestige Coins are bound to you and cannot be transferred."), "the bound-coin note");
Check.False(IltBanking.IsBalanceDumpLine("Transferred 1,000,000 Pyreals to Bob"), "a transfer reply");
Check.False(IltBanking.IsBalanceDumpLine("Received 5 Pyreals from Bob"), "a received line");
Check.False(IltBanking.IsBalanceDumpLine("Bob tells you, \"[BANK] Pyreals: 5\""), "a tell quoting a dump");
const long Win = IltBanking.QuietBalanceWindowMs;
Check.True(IltBanking.EatLeakedDump(true, 1_000, 1_000 + Win), "a dump line inside the window is eaten");
Check.False(IltBanking.EatLeakedDump(true, 1_000 + Win + 1, 1_000 + Win), "after the window it shows (a macro's /bank)");
Check.False(IltBanking.EatLeakedDump(true, 1_000, 0), "no quiet refresh out: it shows (typed /bank, loud refresh, other plugins)");
Check.False(IltBanking.EatLeakedDump(false, 1_000, 1_000 + Win), "a non-dump [BANK] line inside the window still shows");
}
}

View file

@ -0,0 +1,173 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The chunk rules end to end: a fake inventory with the Lugian Aetheria Hammer and one candidate,
// IltChunkClap.Tick, and whether the hammer was used on the candidate. These cover what the pure
// rule tests (AetheriaChunkTests) cannot: the properties as RynthILT reads them from the host, an
// item that is not appraised, and a host that cannot tell whether an appraisal arrived. The hammer
// destroys what it is used on, so "used on it" is the thing to get right.
internal static class ChunkTargetTests
{
private const uint Player = 0x50000F01;
private const uint Hammer = 0x5000A001;
private const uint Item = 0x5000A002;
private const uint ItemTypeGem = 0x00000800;
private const uint ItemTypeMelee = 0x00000001;
private const uint ItemTypeMisc = 0x00000080;
public static void Register(Runner r)
{
r.Add("chunk (live path): unlevelled Coalesced chunks only when its level was truly read as none", UnlevelledVsUnreadable);
r.Add("chunk (live path): levelled Coalesced Aetheria obeys the cap; other aetheria needs a level", LevelledCap);
r.Add("chunk (live path): corrupted two-handed cleave 2 chunks, other corrupted cleave 2 does not", CorruptedCleave);
r.Add("chunk (live path): corrupted keep rules and the rating level are off by default and protect when on", KeepRulesLive);
r.Add("chunk (live path): a busy client in combat chunks with chunk-in-combat on, not off; peace waits for idle", CombatBusy);
}
/// <summary>One chunk pass on a fake pack. Returns the targets the hammer was used on.</summary>
private static List<uint> Pass(string folder, Action<IltGearState> settings, Action<uint> candidate,
uint itemType = ItemTypeGem, string name = "Coalesced Aetheria", bool appraised = true,
bool hostCanSayAppraised = true, bool busy = false, int combatMode = 1)
{
FakeHost.Reset();
FakeHost.WorldName = "InfiniteLeaftide";
FakeHost.ContentsCalls = true;
FakeHost.UseOnCalls = true;
FakeHost.WeaponCalls = hostCanSayAppraised; // installs HasAppraisalData / RequestId / combat mode
FakeHost.BusyCalls = true;
FakeHost.BusyStateValue = busy ? 1 : 0;
FakeHost.CombatModeValue = combatMode;
FakeHost.Names[Hammer] = "Lugian Aetheria Hammer"; FakeHost.ItemTypes[Hammer] = ItemTypeMisc; FakeHost.Containers[Hammer] = Player;
FakeHost.Names[Item] = name; FakeHost.ItemTypes[Item] = itemType; FakeHost.Containers[Item] = Player;
if (appraised) FakeHost.Appraised.Add(Item);
candidate(Item);
var host = FakeHost.Create(Player);
string dir = Path.Combine(Program.TempRoot, "chunk-" + folder);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host));
var g = hub.State.Gear;
g.AutoChunkAetheria = true;
g.AutoChunkCorrupted = true;
settings(g);
hub.Gear.ChunkClap.Tick(10_000);
return FakeHost.UsesOn.Where(u => u.Source == Hammer).Select(u => u.Target).ToList();
}
private static void Ints(uint id, params (uint Key, int Value)[] values)
{
foreach (var (k, v) in values) FakeHost.Ints[(id, k)] = v;
}
private static void UnlevelledVsUnreadable()
{
// Truly unlevelled: the appraisal arrived and the item has no level (int 319), no XP, no tinks.
Check.Eq(Pass("coal-unlevelled", _ => { }, _ => { }).Count, 1, "appraised, no level: chunked (ub-IT)");
// Even with the cap at its lowest.
Check.Eq(Pass("coal-unlevelled-cap1", g => g.ChunkAetheriaUnderLevel = 1, _ => { }).Count, 1, "cap 1 does not stop an unlevelled one");
// Not appraised yet: nothing is known, so it is asked for, not hammered.
var asked = Pass("coal-unappraised", _ => { }, _ => { }, appraised: false);
Check.Eq(asked.Count, 0, "not appraised: not chunked");
Check.True(FakeHost.IdRequests.Contains(Item), "its appraisal is requested");
// The host cannot say whether an appraisal arrived: a level of 0 might be a failed read.
Check.Eq(Pass("coal-unreadable", _ => { }, _ => { }, hostCanSayAppraised: false).Count, 0,
"host cannot confirm the appraisal: kept, not chunked");
// The same unconfirmable host with a read level still keeps (no half-trusted piece is hammered).
Check.Eq(Pass("coal-unreadable-lvl", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 2)), hostCanSayAppraised: false).Count, 0,
"host cannot confirm the appraisal: even a read level 2 is kept");
// A revealed (non-Coalesced) aetheria with no level is never chunked.
Check.Eq(Pass("rev-unlevelled", _ => { }, _ => { }, name: "Blue Aetheria").Count, 0, "revealed aetheria with no level: kept");
// Item XP, tinks or the never-chunk flag keep it.
Check.Eq(Pass("coal-xp", _ => { }, id => FakeHost.Quads[(id, IltInventory.QuadItemTotalXp)] = 500).Count, 0, "has item XP: kept");
Check.Eq(Pass("coal-tinked", _ => { }, id => Ints(id, (IltInventory.IntNumTimesTinkered, 1))).Count, 0, "tinkered: kept");
Check.Eq(Pass("coal-never", _ => { }, id => FakeHost.Bools[(id, IltInventory.BoolNeverChunk)] = true).Count, 0, "never-chunk flag: kept");
}
private static void LevelledCap()
{
Check.Eq(Pass("cap-l3", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 3))).Count, 1, "level 3 under the default cap of 4");
Check.Eq(Pass("cap-l4", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 4))).Count, 0, "level 4 at the default cap of 4: kept");
Check.Eq(Pass("cap9-l8", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 8))).Count, 1, "level 8 under a cap of 9");
Check.Eq(Pass("cap9-l9", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 9))).Count, 0, "level 9 at a cap of 9: kept");
Check.Eq(Pass("cap9-l10", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 10))).Count, 0, "level 10 over a cap of 9: kept");
Check.Eq(Pass("cap11-l10", g => g.ChunkAetheriaUnderLevel = 11, id => Ints(id, (IltInventory.IntItemMaxLevel, 10))).Count, 1, "cap 11 chunks every level");
Check.Eq(Pass("rev-l2", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 2)), name: "Blue Aetheria").Count, 1, "a levelled revealed piece under the cap");
}
private static void CorruptedCleave()
{
void Weapon(uint id, int cleave, int wieldSkill = 45, int weaponType = 0, int attackType = 4) =>
Ints(id, (IltInventory.IntItemWorkmanship, 6), (IltInventory.IntCleaving, cleave), (IltInventory.IntWieldSkillType, wieldSkill),
(IltInventory.IntWeaponType, weaponType), (IltInventory.IntAttackType, attackType));
Check.Eq(Pass("cor-1h-c1", _ => { }, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword").Count, 1, "one-handed cleave 1 chunks");
Check.Eq(Pass("cor-1h-c2", _ => { }, id => Weapon(id, 2), ItemTypeMelee, "Corrupted Sword").Count, 0, "one-handed cleave 2 is kept");
Check.Eq(Pass("cor-2h-c2", _ => { }, id => Weapon(id, 2, wieldSkill: 41), ItemTypeMelee, "Corrupted Greatsword").Count, 1, "two-handed cleave 2 chunks");
Check.Eq(Pass("cor-2h-c3", _ => { }, id => Weapon(id, 3, wieldSkill: 41), ItemTypeMelee, "Corrupted Greatsword").Count, 0, "two-handed cleave 3 is kept");
Check.Eq(Pass("cor-2h-thrust", _ => { }, id => Weapon(id, 2, wieldSkill: 41, attackType: 2), ItemTypeMelee, "Corrupted Spear").Count, 0, "two-handed thrust cleave 2 is kept");
Check.Eq(Pass("cor-nowork", _ => { }, id => Ints(id, (IltInventory.IntCleaving, 1)), ItemTypeMelee, "Corrupted Sword").Count, 0, "no workmanship read: kept");
Check.Eq(Pass("cor-unreadable", _ => { }, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword", hostCanSayAppraised: false).Count, 0,
"host cannot confirm the appraisal: kept");
Check.Eq(Pass("cor-off", g => g.AutoChunkCorrupted = false, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword").Count, 0, "auto-chunk corrupted off: not touched");
}
private static void KeepRulesLive()
{
var def = new IltGearState();
Check.True(!def.KeepCorruptedCrushingBlow && !def.KeepCorruptedBitingStrike && !def.KeepCorruptedArmorCleaving
&& !def.KeepCorruptedAnySlayer && !def.KeepCorruptedMultiStrike && !def.KeepCorruptedElementalBonus
&& !def.KeepCorruptedAnySpell && def.KeepCorruptedMaxDamageAtLeast == 0 && def.KeepCorruptedSpellIds == "",
"every corrupted keep rule is off by default");
Check.Eq(def.KeepAetheriaRatingAtLeast, 1, "the rating level defaults to 1 (any rating keeps, as before)");
void Loaded(uint id)
{
Ints(id, (IltInventory.IntItemWorkmanship, 6), (IltInventory.IntCleaving, 1), (IltInventory.IntAttackType, 160),
(IltInventory.IntSlayerCreatureType, 5), (IltInventory.IntElementalDamageBonus, 10), (IltInventory.IntDamage, 400));
FakeHost.Doubles[(id, IltInventory.FloatCriticalFrequency)] = 0.1;
FakeHost.Doubles[(id, IltInventory.FloatCriticalMultiplier)] = 1.5;
FakeHost.Doubles[(id, IltInventory.FloatIgnoreArmor)] = 0.2;
FakeHost.SpellIds[id] = new uint[] { 2072 };
}
int Run(string tag, Action<IltGearState> s) => Pass("keep-" + tag, s, Loaded, ItemTypeMelee, "Corrupted Sword").Count;
Check.Eq(Run("none", _ => { }), 1, "a loaded corrupted weapon chunks while every keep rule is off");
Check.Eq(Run("crush", g => g.KeepCorruptedCrushingBlow = true), 0, "Crushing Blow on: kept");
Check.Eq(Run("bite", g => g.KeepCorruptedBitingStrike = true), 0, "Biting Strike on: kept");
Check.Eq(Run("armor", g => g.KeepCorruptedArmorCleaving = true), 0, "Armor Cleaving on: kept");
Check.Eq(Run("slayer", g => g.KeepCorruptedAnySlayer = true), 0, "slayer on: kept");
Check.Eq(Run("multi", g => g.KeepCorruptedMultiStrike = true), 0, "multi-strike on: kept");
Check.Eq(Run("elem", g => g.KeepCorruptedElementalBonus = true), 0, "elemental bonus on: kept");
Check.Eq(Run("maxdmg", g => g.KeepCorruptedMaxDamageAtLeast = 400), 0, "max damage 400 on: kept");
Check.Eq(Run("maxdmg-hi", g => g.KeepCorruptedMaxDamageAtLeast = 401), 1, "max damage above the weapon's: chunks");
Check.Eq(Run("spell", g => g.KeepCorruptedAnySpell = true), 0, "any spell on: kept");
Check.Eq(Run("spellid", g => g.KeepCorruptedSpellIds = "2072"), 0, "a listed spell id: kept");
Check.Eq(Run("spellid-other", g => g.KeepCorruptedSpellIds = "100"), 1, "another spell id: chunks");
// The rating level on a live Coalesced piece with a C 1 rating.
void C1(uint id) => Ints(id, (IltInventory.IntGearCrit, 1));
Check.Eq(Pass("rate-default", _ => { }, C1).Count, 0, "C 1 is kept at the default rating level");
Check.Eq(Pass("rate-2", g => g.KeepAetheriaRatingAtLeast = 2, C1).Count, 1, "C 1 chunks once the rating level is 2");
Check.Eq(Pass("rate-2-c2", g => g.KeepAetheriaRatingAtLeast = 2, id => Ints(id, (IltInventory.IntGearCrit, 2))).Count, 0, "C 2 is kept at level 2");
Check.Eq(Pass("rate-2-off", g => { g.KeepAetheriaRatingAtLeast = 2; g.KeepAetheriaWithCrit = false; }, id => Ints(id, (IltInventory.IntGearCrit, 5))).Count, 1,
"the C switch off ignores the rating level");
}
private static void CombatBusy()
{
Check.Eq(Pass("busy-combat-on", g => g.ChunkInCombat = true, _ => { }, busy: true, combatMode: 2).Count, 1,
"busy in combat mode with chunk-in-combat on: chunks");
Check.Eq(Pass("busy-combat-off", g => g.ChunkInCombat = false, _ => { }, busy: true, combatMode: 2).Count, 0,
"busy in combat mode with chunk-in-combat off: waits");
Check.Eq(Pass("idle-combat-on", g => g.ChunkInCombat = true, _ => { }, busy: false, combatMode: 2).Count, 1,
"idle in combat mode with chunk-in-combat on: chunks");
Check.Eq(Pass("busy-peace", g => g.ChunkInCombat = true, _ => { }, busy: true, combatMode: 1).Count, 0,
"busy in peace mode waits for idle even with chunk-in-combat on");
Check.Eq(Pass("idle-peace", g => g.ChunkInCombat = false, _ => { }, busy: false, combatMode: 1).Count, 1,
"idle in peace mode chunks");
}
}

View file

@ -367,9 +367,13 @@ internal static class MoveTests
Check.Eq(sizeof(RynthIltHubApiV1), 8 + 9 * IntPtr.Size, "RynthIltHubApiV1: header + 9 functions");
// SessionStatsMore was appended (2026-10-13); readers accept any table at least
// BaseStructSize long, so an older RynthAi still connects.
Check.Eq(sizeof(RynthAiHubApiV1), 8 + 11 * IntPtr.Size, "RynthAiHubApiV1: header + 11 functions");
// VaultedDungeonsEnabled was appended (2026-10-18): the Vaulted Dungeons master switch.
Check.Eq(sizeof(RynthAiHubApiV1), 8 + 12 * IntPtr.Size, "RynthAiHubApiV1: header + 12 functions");
Check.Eq((int)RynthAiHubApiV1.BaseStructSize, 8 + 10 * IntPtr.Size, "RynthAiHubApiV1.BaseStructSize: the first release's 10 functions");
Check.Eq(RynthAiHubApiV1.SessionStatsMoreOffset, (int)RynthAiHubApiV1.BaseStructSize, "SessionStatsMore right after the base table");
Check.Eq(RynthAiHubApiV1.VaultedDungeonsEnabledOffset, 8 + 11 * IntPtr.Size, "VaultedDungeonsEnabled right after SessionStatsMore");
Check.Eq((int)Marshal.OffsetOf<RynthAiHubApiV1>(nameof(RynthAiHubApiV1.VaultedDungeonsEnabled)), RynthAiHubApiV1.VaultedDungeonsEnabledOffset,
"VaultedDungeonsEnabledOffset is where the field really is");
Check.Eq(sizeof(QuestFlagV1), 24, "QuestFlagV1");
Check.Eq(sizeof(QuestStatusV1), 16, "QuestStatusV1");
Check.Eq(RynthIltHubApiV1.InterfaceName, "RynthILT.Hub", "interface name");
@ -437,8 +441,10 @@ internal static class MoveTests
Check.True(IltSections.MovedCommand(kept) == null, $"{IltSections.Label(kept)} is still RynthILT's");
Check.True(IltSections.IsTab(kept), $"{IltSections.Label(kept)} is a Mini Remote tab");
}
Check.True(IltSections.Tabs.SequenceEqual(new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games }),
"the tab list is Banking, Gear, Charms, Games");
Check.True(IltSections.MovedCommand(IltSection.VaultedDungeons) == null && IltSections.IsTab(IltSection.VaultedDungeons),
"Vaulted Dungeons is a RynthILT tab (shown only with the master switch, VaultedDungeonsTests)");
Check.True(IltSections.Tabs.SequenceEqual(new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, IltSection.VaultedDungeons }),
"the tab list is Banking, Gear, Charms, Games, Vaulted Dungeons");
Check.False(IltSections.IsTab(IltSection.Character) || IltSections.IsTab(IltSection.Guardian), "Character and the Guardian aren't tabs");
Check.True(IltSections.TryParse("char", out IltSection c) && c == IltSection.Character, "old Character names still parse (for the redirect)");
Check.Eq(IltSections.OracleCharacterCommand, "/ro character", "Oracle command");

View file

@ -45,7 +45,9 @@ internal static class Program
IltSettingsTests.Register(runner);
FellowshipCommandTests.Register(runner);
AetheriaChunkTests.Register(runner);
ChunkTargetTests.Register(runner);
RingChainTests.Register(runner);
VaultedDungeonsTests.Register(runner);
// Before DataApiTests: its last test releases the RynthILT.Data table, which the breeding version test queries.
BreedingTests.Register(runner);
DataApiTests.Register(runner);

View file

@ -0,0 +1,527 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The Vaulted Dungeons keeper (Hub/IltVaultedDungeons.cs, Silentkelpie's, taken in with the owner's
// safety rules): ILT only, a master switch (RynthAi's setting, off by default) that gates everything,
// no resume of Active from the saved file, a recall that waits out combat / buffing, /rc quit once per
// activation and never while gated, and a no-kill timer that restarts on kills and captures.
// The clock, the master switch, RynthAi's activity and the gem use are the module's test seams.
internal static class VaultedDungeonsTests
{
private const uint Player = 0x50000C01;
private const uint Quarry = 0x01F7; // dungeon 1: Tyrant's Quarry
private const uint Elsewhere = 0x0001;
private const string Luminance = "You've banked 1,234 Luminance.";
public static void Register(Runner r)
{
r.Add("vaulted: not an ILT world -> inert (no tick work, no recall, no quit, a 'not available' reply)", NotIlt);
r.Add("vaulted: master off -> inert even with a saved Active, Auto Start and Kill Client", MasterOff);
r.Add("vaulted: master on + explicit start -> recalls at 1 s then every 5 s outside, stops inside; a saved Active is not resumed", ExplicitStartRecalls);
r.Add("vaulted: Auto Start On Arrival is honoured only with the master on", AutoStart);
r.Add("vaulted: Kill Client fires once per activation and restarts on luminance, a killing blow and a capture", QuitOnceAndResets);
r.Add("vaulted: Kill Client is never sent once the master goes off, even between the timer and the send", QuitNeverWhenGated);
r.Add("vaulted: a busy bot (combat, buffing, server wait, client busy) defers the recall; the warning keeps its cadence", BusyDefers);
r.Add("vaulted: turning the master off mid-run stops it at once and says so once; turning it on starts Off", MasterOffMidRun);
r.Add("vaulted: the tab and /ra hub open vaulted follow ILT + the master; settings file format kept", TabAndFile);
r.Add("vaulted: capture lines are the Pets tab's own success replies", CaptureLines);
r.Add("vaulted: settings go through the source-generated JSON context (NativeAOT has no reflection serializer)", SourceGeneratedContext);
}
// ── Rig ──────────────────────────────────────────────────────────────────
private sealed class Rig
{
public IltHubController Hub = null!;
public IltVaultedDungeons V = null!;
public string Dir = "";
public long T = 1_000_000;
public bool Master;
public RynthAiActivity? Act = RynthAiActivity.None;
public int MasterCalls, AllowCalls = int.MaxValue;
public readonly List<string> GemsUsed = new();
public bool HasGem = true;
public int Quits => FakeHost.ChatCommands.Count(c => c == "/rc quit");
public int ChatCount(string part) => FakeHost.Chat.Count(c => c.Contains(part, StringComparison.OrdinalIgnoreCase));
public void Step(long ms) { T += ms; V.Tick(T); }
public void Inside() => FakeHost.PlayerPose = ((Quarry << 16) | 0x0100u, 0, 0, 0);
public void Outside() => FakeHost.PlayerPose = ((Elsewhere << 16) | 0x0100u, 0, 0, 0);
public string SettingsFile => Path.Combine(Dir, "VaultedDungeons", "settings.json");
public void WriteSettings(string json)
{
Directory.CreateDirectory(Path.GetDirectoryName(SettingsFile)!);
File.WriteAllText(SettingsFile, json);
}
}
private static Rig NewRig(string world, string folder, bool master, bool busyCalls = false)
{
FakeHost.Reset();
FakeHost.WorldName = world;
FakeHost.BusyCalls = busyCalls;
var host = FakeHost.Create(Player);
var rig = new Rig { Master = master, Dir = Path.Combine(Program.TempRoot, folder) };
Directory.CreateDirectory(rig.Dir);
rig.Hub = new IltHubController(host, rig.Dir, new IltSettings(), new RynthAiClient(host));
rig.V = rig.Hub.VaultedDungeons;
rig.V.Clock = () => rig.T;
rig.V.MasterEnabled = () => { rig.MasterCalls++; return rig.Master && rig.MasterCalls <= rig.AllowCalls; };
rig.V.Activity = () => rig.Act;
rig.V.UseGem = name => { if (!rig.HasGem) return false; rig.GemsUsed.Add(name); return true; };
rig.Outside();
return rig;
}
/// <summary>Dungeon 1 (Tyrant's Quarry), the primary gem, the given extras. "active": true is on disk to prove it is ignored.</summary>
private static string Settings(string extras = "")
=> "{ \"active\": true, \"dungeon\": 1, \"gem\": 1" + (extras.Length > 0 ? ", " + extras : "") + " }";
// ── ILT only ─────────────────────────────────────────────────────────────
private static void NotIlt()
{
var rig = NewRig("Aelrynth", "vd-notilt", master: true);
rig.WriteSettings(Settings("\"autoStart\": true, \"quit\": true, \"quitMinutes\": 1"));
string before = File.ReadAllText(rig.SettingsFile);
rig.Outside();
for (int i = 0; i < 20; i++) rig.Step(1000);
rig.Inside();
for (int i = 0; i < 10; i++) rig.Step(30_000);
Check.False(rig.V.IsActive, "not running on another world, though the master is on and Auto Start was saved");
Check.Eq(rig.GemsUsed.Count, 0, "no recall gem");
Check.Eq(rig.Quits, 0, "no /rc quit");
Check.Eq(FakeHost.ChatCommands.Count, 0, "no command of any kind (no /vt, /ub or /rc)");
Check.Eq(rig.ChatCount("[Vaulted Dungeons]"), 0, "and not a word in chat");
Check.Eq(File.ReadAllText(rig.SettingsFile), before, "the settings file wasn't even read or rewritten");
rig.V.HandleCommand(new[] { "on" });
Check.False(rig.V.IsActive, "/ilt vaulted on is refused");
Check.Eq(rig.ChatCount("Not available on this server"), 1, "with the 'not available on this server' reply");
FakeHost.Chat.Clear();
rig.V.HandleCommand(new[] { "status" });
Check.Eq(rig.ChatCount("Not available on this server"), 1, "status says the same");
Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "no tab");
Check.False(rig.Hub.SectionAvailable(IltSection.VaultedDungeons), "not available");
// The controller doesn't tick it either (and the module would refuse anyway).
rig.Hub.Tick();
Check.Eq(rig.GemsUsed.Count, 0, "the controller's tick does nothing here");
}
// ── Master switch ────────────────────────────────────────────────────────
private static void MasterOff()
{
var rig = NewRig("InfiniteLeaftide", "vd-masteroff", master: false);
rig.WriteSettings(Settings("\"autoStart\": true, \"quit\": true, \"quitMinutes\": 1, \"disableMeta\": true"));
string before = File.ReadAllText(rig.SettingsFile);
rig.Outside();
for (int i = 0; i < 20; i++) rig.Step(1000);
rig.Inside();
for (int i = 0; i < 10; i++) rig.Step(30_000); // five minutes inside: a one-minute Kill Client would have fired
Check.False(rig.V.IsActive, "off: a saved Active and Auto Start start nothing");
Check.Eq(rig.GemsUsed.Count, 0, "no recall gem");
Check.Eq(rig.Quits, 0, "no /rc quit");
Check.Eq(FakeHost.ChatCommands.Count, 0, "no arrival commands (/vt opt set ...) either");
Check.Eq(rig.ChatCount("[Vaulted Dungeons]"), 0, "silent");
Check.Eq(File.ReadAllText(rig.SettingsFile), before, "settings untouched");
Check.True(rig.Hub.Options.IsIltLikeWorld, "(it is an ILT world: the master switch is what holds it)");
Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "the tab is hidden");
Check.False(rig.Hub.SectionAvailable(IltSection.VaultedDungeons), "and not available");
rig.V.HandleCommand(new[] { "on" });
Check.False(rig.V.IsActive, "/ilt vaulted on is refused");
Check.Eq(rig.ChatCount("Settings > Navigation"), 1, "and says where the switch is");
rig.V.HandleCommand(new[] { "toggle" });
Check.False(rig.V.IsActive, "toggle too");
// Through the controller, the real wiring: nothing either.
for (int i = 0; i < 5; i++) rig.Hub.Tick();
Check.Eq(rig.GemsUsed.Count, 0, "the controller's tick does nothing while off");
// The lines that restart the timer are ignored too (nothing is running).
rig.V.OnChat(Luminance);
rig.V.OnKillNotification();
Check.Eq(rig.Quits, 0, "still nothing");
}
// ── Recalls ──────────────────────────────────────────────────────────────
private static void ExplicitStartRecalls()
{
var rig = NewRig("InfiniteLeaftide", "vd-recall", master: true);
rig.WriteSettings(Settings()); // "active": true on disk: ignored
rig.Outside();
rig.Step(0);
Check.False(rig.V.IsActive, "a saved Active is not resumed after login");
for (int i = 0; i < 10; i++) rig.Step(1000);
Check.Eq(rig.GemsUsed.Count, 0, "so nothing is recalled until the player starts it");
rig.V.HandleCommand(new[] { "on" });
Check.True(rig.V.IsActive, "an explicit start");
rig.Step(0); // first tick outside: the clock starts
rig.Step(500);
Check.Eq(rig.GemsUsed.Count, 0, "0.5 s out: too early");
rig.Step(500); // 1 s
Check.Eq(rig.GemsUsed.Count, 1, "the first recall comes 1 s after leaving");
Check.Eq(rig.GemsUsed[0], "Primary Portal Recall Gem", "the chosen gem");
rig.Step(4000);
Check.Eq(rig.GemsUsed.Count, 1, "4 s later: not yet");
rig.Step(1000); // 5 s since the last use
Check.Eq(rig.GemsUsed.Count, 2, "then every 5 s");
rig.Step(5000);
Check.Eq(rig.GemsUsed.Count, 3, "again");
rig.Inside();
rig.Step(1000);
for (int i = 0; i < 12; i++) rig.Step(1000);
Check.Eq(rig.GemsUsed.Count, 3, "inside the dungeon: no more gems");
FakeHost.Portaling = true;
rig.Outside();
rig.Step(10_000);
Check.Eq(rig.GemsUsed.Count, 3, "portal space: nothing used");
FakeHost.Portaling = false;
rig.Step(0);
rig.Step(1000);
Check.Eq(rig.GemsUsed.Count, 4, "out again: 1 s, then a recall");
rig.HasGem = false;
rig.Step(5000);
Check.Eq(rig.GemsUsed.Count, 4, "no gem in the pack: none used");
Check.True(rig.ChatCount("No Primary Portal Recall Gem") >= 1, "and it says so");
}
private static void AutoStart()
{
// Master on: arriving in the chosen dungeon switches it on, and the arrival commands go out.
var on = NewRig("InfiniteLeaftide", "vd-auto-on", master: true);
on.WriteSettings(Settings("\"autoStart\": true, \"disableMeta\": true"));
on.Inside();
on.Step(0);
Check.True(on.V.IsActive, "Auto Start On Arrival switches the keeper on (master on)");
Check.True(FakeHost.ChatCommands.Contains("/vt opt set EnableMeta False"), "and runs the arrival commands");
// Auto Start off, master on: a relog inside does not resume a saved Active.
var manual = NewRig("InfiniteLeaftide", "vd-auto-off", master: true);
manual.WriteSettings(Settings("\"disableMeta\": true"));
manual.Inside();
manual.Step(0);
Check.False(manual.V.IsActive, "no Auto Start: not resumed");
Check.Eq(FakeHost.ChatCommands.Count, 0, "and the arrival commands wait for an Active keeper");
// Master off, Auto Start saved: nothing; then the master comes on while inside.
var gated = NewRig("InfiniteLeaftide", "vd-auto-gated", master: false);
gated.WriteSettings(Settings("\"autoStart\": true"));
gated.Inside();
gated.Step(0);
Check.False(gated.V.IsActive, "master off: Auto Start does nothing");
gated.Master = true;
gated.Step(1000);
Check.True(gated.V.IsActive, "with the master on, Auto Start (the player's own saved choice) applies");
}
// ── Kill Client ──────────────────────────────────────────────────────────
private static Rig QuitRig(string folder, int minutes = 2)
{
var rig = NewRig("InfiniteLeaftide", folder, master: true);
rig.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": " + minutes));
rig.Inside();
rig.Step(0);
rig.V.HandleCommand(new[] { "on" });
rig.Step(0); // inside: the no-kill clock starts here
return rig;
}
private static void QuitOnceAndResets()
{
// Luminance line.
var rig = QuitRig("vd-quit-lum");
rig.Step(119_000);
Check.Eq(rig.Quits, 0, "just under 2 minutes: no quit");
rig.V.OnChat(Luminance);
rig.Step(119_000);
Check.Eq(rig.Quits, 0, "the luminance line restarted the timer");
rig.Step(2_000);
Check.Eq(rig.Quits, 1, "2 minutes after the last kill: /rc quit");
for (int i = 0; i < 10; i++) rig.Step(60_000);
Check.Eq(rig.Quits, 1, "and only once");
// A kill after the quit went out doesn't arm a second one (once per activation).
rig.V.OnChat(Luminance);
for (int i = 0; i < 10; i++) rig.Step(60_000);
Check.Eq(rig.Quits, 1, "still once");
// The player's own killing blow.
rig = QuitRig("vd-quit-kill");
rig.Step(110_000);
rig.V.OnKillNotification();
rig.Step(110_000);
Check.Eq(rig.Quits, 0, "a killing blow restarted the timer");
rig.Step(15_000);
Check.Eq(rig.Quits, 1, "and it fires after the next idle stretch");
// A pet capture.
rig = QuitRig("vd-quit-capture");
rig.Step(110_000);
rig.V.OnChat("You have successfully siphoned the essence of the Olthoi Warrior.");
rig.Step(110_000);
Check.Eq(rig.Quits, 0, "a capture restarted the timer");
rig.V.OnChat("The echo resonates perfectly.");
rig.Step(110_000);
Check.Eq(rig.Quits, 0, "so does the other success reply");
rig.Step(15_000);
Check.Eq(rig.Quits, 1, "then it fires");
// Lines that are not kills don't restart it.
rig = QuitRig("vd-quit-noise");
rig.Step(110_000);
rig.V.OnChat("You hit the Olthoi Warrior for 50 points of damage.");
rig.V.OnChat("The essence is not ready yet.");
rig.V.OnChat("Bob says, \"You've banked 5 Luminance.\""); // a player's chat, not the system line
rig.Step(15_000);
Check.Eq(rig.Quits, 1, "damage lines, a refused capture and someone else's chat don't count");
// The minutes are the player's setting: 1 minute here.
rig = QuitRig("vd-quit-1m", minutes: 1);
rig.Step(59_000);
Check.Eq(rig.Quits, 0, "1 minute setting: not yet");
rig.Step(2_000);
Check.Eq(rig.Quits, 1, "fires at 1 minute");
// Off -> on again is a new activation: one more quit may be sent.
rig.V.HandleCommand(new[] { "off" });
rig.V.HandleCommand(new[] { "on" });
rig.Step(0);
rig.Step(61_000);
Check.Eq(rig.Quits, 2, "a new activation gets its own single quit");
}
private static void QuitNeverWhenGated()
{
// The master goes off, the timer would have fired: nothing is sent, and it stopped.
var rig = QuitRig("vd-quit-gated");
rig.Step(100_000);
rig.Master = false;
rig.Step(30_000);
Check.Eq(rig.Quits, 0, "master off before the timer: no /rc quit");
Check.False(rig.V.IsActive, "and the keeper is off");
rig.Step(600_000);
Check.Eq(rig.Quits, 0, "ever");
// The master goes off between the timer firing and the send (asked again right before sending).
rig = QuitRig("vd-quit-race");
rig.Step(100_000);
rig.AllowCalls = rig.MasterCalls + 1; // true at the top of the next tick, false when it re-checks
rig.Step(21_000); // the timer fires in this tick
Check.Eq(rig.Quits, 0, "master off between the timer firing and the send: not sent");
Check.False(rig.V.IsActive, "the keeper stopped");
Check.Eq(rig.ChatCount("Stopped"), 1, "said once");
// Not an ILT world any more (the world name changes): same.
rig = QuitRig("vd-quit-world");
rig.Step(100_000);
FakeHost.WorldName = "Aelrynth";
rig.Step(30_000);
Check.Eq(rig.Quits, 0, "world no longer ILT: no /rc quit");
Check.False(rig.V.IsActive, "stopped");
// Not Active: the timer has nothing to do (the player turned it off).
rig = QuitRig("vd-quit-off");
rig.V.HandleCommand(new[] { "off" });
for (int i = 0; i < 10; i++) rig.Step(60_000);
Check.Eq(rig.Quits, 0, "Off: no quit");
}
// ── Combat / buff guard ──────────────────────────────────────────────────
private static void BusyDefers()
{
var rig = NewRig("InfiniteLeaftide", "vd-busy", master: true, busyCalls: true);
rig.WriteSettings(Settings());
rig.Outside();
rig.Step(0);
rig.V.HandleCommand(new[] { "on" });
rig.Act = RynthAiActivity.MacroRunning | RynthAiActivity.Combat;
rig.Step(0);
rig.Step(1000);
rig.Step(4000);
Check.Eq(rig.GemsUsed.Count, 0, "in combat: the recall is deferred");
Check.Eq(rig.ChatCount("Waiting to use the Primary Portal Recall Gem"), 1, "and says why, once");
rig.Step(20_000);
Check.Eq(rig.ChatCount("Waiting to use"), 1, "no repeat inside the 30 s warning cadence");
rig.Step(10_000);
Check.Eq(rig.ChatCount("Waiting to use"), 2, "the warning comes again after 30 s");
Check.Eq(rig.GemsUsed.Count, 0, "still nothing used");
rig.Act = RynthAiActivity.MacroRunning; // clear
rig.Step(100);
Check.Eq(rig.GemsUsed.Count, 1, "the first clear tick recalls (it was due all along)");
// Buffing, the server wait, looting, salvaging, crafting and RynthAi not answering all defer too.
foreach (RynthAiActivity? busy in new RynthAiActivity?[]
{ RynthAiActivity.Buffing, RynthAiActivity.ServerAction, RynthAiActivity.Looting, RynthAiActivity.Salvaging, RynthAiActivity.Crafting, null })
{
int before = rig.GemsUsed.Count;
rig.Act = busy;
rig.Step(6000);
Check.Eq(rig.GemsUsed.Count, before, $"busy ({(busy.HasValue ? busy.Value.ToString() : "RynthAi not ready")}): deferred");
rig.Act = RynthAiActivity.None;
rig.Step(100);
Check.Eq(rig.GemsUsed.Count, before + 1, "and used once it is clear");
}
// The client's own busy hourglass.
FakeHost.BusyStateValue = 1;
int n = rig.GemsUsed.Count;
rig.Step(6000);
Check.Eq(rig.GemsUsed.Count, n, "the client is busy: deferred");
FakeHost.BusyStateValue = 0;
rig.Step(100);
Check.Eq(rig.GemsUsed.Count, n + 1, "used when it clears");
// Busy never blocks the Kill Client (it is not a game action that can be lost).
var q = NewRig("InfiniteLeaftide", "vd-busy-quit", master: true);
q.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": 1"));
q.Inside();
q.Step(0);
q.V.HandleCommand(new[] { "on" });
q.Step(0);
q.Act = RynthAiActivity.Combat;
q.Step(61_000);
Check.Eq(q.Quits, 1, "a busy bot still gets its Kill Client");
}
// ── Master off mid-run ───────────────────────────────────────────────────
private static void MasterOffMidRun()
{
var rig = NewRig("InfiniteLeaftide", "vd-midrun", master: true);
rig.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": 1"));
rig.Outside();
rig.Step(0);
rig.V.HandleCommand(new[] { "on" });
rig.Step(0);
rig.Step(1000);
Check.Eq(rig.GemsUsed.Count, 1, "running: a recall went out");
rig.Master = false;
rig.Step(10);
Check.False(rig.V.IsActive, "the master went off: stopped on that very tick");
Check.Eq(rig.ChatCount("Stopped"), 1, "and it said so");
for (int i = 0; i < 20; i++) rig.Step(5000);
Check.Eq(rig.GemsUsed.Count, 1, "no more recalls");
Check.Eq(rig.ChatCount("Stopped"), 1, "and the notice wasn't repeated");
Check.Eq(rig.Quits, 0, "no quit");
rig.Master = true;
rig.Step(10);
Check.False(rig.V.IsActive, "turned back on: it starts Off, nothing resumes by itself");
rig.Step(10_000);
Check.Eq(rig.GemsUsed.Count, 1, "nothing recalled");
rig.V.HandleCommand(new[] { "on" });
rig.Step(0);
rig.Step(1000);
Check.Eq(rig.GemsUsed.Count, 2, "until the player starts it again");
// The Mini Remote button path (posted to the pump) re-checks the switch as well.
rig.V.HandleCommand(new[] { "off" });
rig.Master = false;
rig.Hub.Context.Post(() => rig.V.HandleCommand(new[] { "on" }));
rig.Hub.Tick();
Check.False(rig.V.IsActive, "an On click that lands after the switch went off is refused");
}
// ── Tab, commands, file ──────────────────────────────────────────────────
private static void TabAndFile()
{
var rig = NewRig("InfiniteLeaftide", "vd-tab", master: true);
Check.True(rig.Hub.TabShown(IltSection.VaultedDungeons), "ILT + master on: the tab is shown");
Check.True(IltSections.Tabs.Contains(IltSection.VaultedDungeons), "it is one of the tab-bar tabs");
Check.True(IltSections.IsTab(IltSection.VaultedDungeons), "a Mini Remote tab");
Check.Eq(IltSections.TabId(IltSection.VaultedDungeons), "vaulted", "tab id");
Check.True(IltSections.TryParse("vaulted", out var s) && s == IltSection.VaultedDungeons, "/ra hub open vaulted parses");
Check.True(IltSections.TryParse("vaulted-dungeons", out s) && s == IltSection.VaultedDungeons, "and the long names");
Check.True(RynthCore.Plugin.RynthILT.RynthILTPlugin.IsIltVerb(new[] { "hub", "open", "vaulted" }), "RynthILT takes '/ra hub open vaulted'");
rig.Master = false;
Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "master off: hidden");
// The file: the format Silentkelpie's keeper wrote, kept. A start is saved.
rig = NewRig("InfiniteLeaftide", "vd-file", master: true);
rig.WriteSettings("""{ "dungeon": 3, "gem": 2, "quit": true, "quitMinutes": 7, "autoStart": false, "attackPower": 0.5 }""");
rig.V.HandleCommand(new[] { "status" });
Check.Eq(rig.ChatCount("dungeon=Wailing Cells, gem=Secondary Portal Recall Gem, kill-client=7m"), 1, "dungeon list and gem names as upstream");
rig.V.HandleCommand(new[] { "on" });
rig.Step(0);
string saved = File.ReadAllText(rig.SettingsFile);
Check.True(saved.Contains("\"active\": true") && saved.Contains("\"quitMinutes\": 7") && saved.Contains("\"dungeon\": 3"),
"saved in the same camelCase layout");
// A new session (relog) reads it back with Active Off.
var again = NewRig("InfiniteLeaftide", "vd-file", master: true);
FakeHost.Chat.Clear();
again.V.HandleCommand(new[] { "status" });
Check.True(again.ChatCount("Off — dungeon=Wailing Cells") == 1 && !again.V.IsActive, "the next session starts Off, with the same choices");
}
// The NativeAOT build (what ships) turns reflection-based System.Text.Json off, so the keeper's
// settings must use IltVaultedDungeonsJsonContext. This project runs on the normal runtime where
// reflection would still work, so assert the generated metadata exists and that the file layout
// is what the context (not an options object) produces.
private static void SourceGeneratedContext()
{
var ctx = IltVaultedDungeonsJsonContext.Default;
Check.True(ctx.Cfg != null, "the context has metadata for the settings type (IltVaultedDungeonsJsonContext.Default.Cfg)");
Check.True(ctx.GetTypeInfo(typeof(IltVaultedDungeons.Cfg)) != null, "and resolves it by type");
var cfg = new IltVaultedDungeons.Cfg
{
Active = true, Dungeon = 3, Gem = 2, Quit = true, QuitMinutes = 7, ShowInDungeon = true,
AutoStart = true, DisableMeta = true, DisableNav = false, RepeatAttack = true, SetPower = true, AttackPower = 0.5f,
};
string json = System.Text.Json.JsonSerializer.Serialize(cfg, ctx.Cfg);
Check.True(json.Contains("\"active\": true") && json.Contains("\"quitMinutes\": 7") && json.Contains("\"attackPower\": 0.5"),
"serializes indented with camelCase names");
Check.True(json.Contains("\n"), "indented");
var back = System.Text.Json.JsonSerializer.Deserialize(json, ctx.Cfg);
Check.True(back != null, "round-trips");
Check.True(back!.Active && back.Dungeon == 3 && back.Gem == 2 && back.Quit && back.QuitMinutes == 7 && back.ShowInDungeon
&& back.AutoStart && back.DisableMeta && !back.DisableNav && back.RepeatAttack && back.SetPower && back.AttackPower == 0.5f,
"every field survives");
// The shape of the file Silentkelpie's keeper wrote (camelCase, partial) still reads.
var upstream = System.Text.Json.JsonSerializer.Deserialize(
"""{ "dungeon": 2, "gem": 1, "quit": true, "quitMinutes": 5 }""", ctx.Cfg);
Check.True(upstream != null && upstream.Dungeon == 2 && upstream.Gem == 1 && upstream.Quit && upstream.QuitMinutes == 5 && !upstream.Active,
"a partial upstream file reads, missing fields keep their defaults");
bool threw = false;
try { System.Text.Json.JsonSerializer.Deserialize("{ not json", ctx.Cfg); } catch (System.Text.Json.JsonException) { threw = true; }
Check.True(threw, "a corrupt file still throws, which the keeper's bad-file copy relies on");
}
private static void CaptureLines()
{
Check.True(PetCaptureLines.IsSuccess("You have successfully siphoned the essence."), "siphoned");
Check.True(PetCaptureLines.IsSuccess("The echo resonates perfectly."), "echo");
Check.True(PetCaptureLines.IsSuccess("The essence is captured!"), "captured");
Check.False(PetCaptureLines.IsSuccess("The creature is too strong to be siphoned."), "a refusal is not a success");
Check.False(PetCaptureLines.IsSuccess("siphon failed"), "nor a failure");
Check.False(PetCaptureLines.IsSuccess(""), "empty");
}
}

View file

@ -3,6 +3,8 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using RynthCore.Plugin.RynthLua;
using RynthCore.PluginCore;
@ -37,6 +39,7 @@ internal static unsafe class Program
Console.WriteLine($"=== RynthLua UtilityBelt compatibility tests ({scripts.Count} scripts) ===");
int passed = 0, checks = 0;
var failed = new List<string>();
if (filter.Length == 0 && !CheckBuiltInVerbsMatchSwitch()) failed.Add("built-in /lua verbs");
try
{
foreach (string file in scripts)
@ -125,6 +128,36 @@ internal static unsafe class Program
return (ok, Harness.Checks);
}
/// <summary>
/// RynthLuaPlugin.BuiltInLuaVerbs is kept in step with the switch in HandleLuaChatCommand by hand: a verb in
/// the switch but not the set would be shadowed by a script command of the same name (and listed as a script
/// command in the usage); a verb in the set but not the switch would be unreachable from both. This compares
/// the set with the case labels of that switch, read from the source file.
/// </summary>
private static bool CheckBuiltInVerbsMatchSwitch([System.Runtime.CompilerServices.CallerFilePath] string source = "")
{
string path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(source) ?? string.Empty, "..", "..", "Plugins", "RynthCore.Plugin.RynthLua", "ScriptManager.cs"));
if (!File.Exists(path)) { Console.WriteLine("SKIP built-in /lua verbs: ScriptManager.cs not found beside the project."); return true; }
var field = typeof(RynthLuaPlugin).GetField("BuiltInLuaVerbs", BindingFlags.NonPublic | BindingFlags.Static);
if (field?.GetValue(null) is not HashSet<string> verbs) { Console.WriteLine("FAIL built-in /lua verbs: RynthLuaPlugin.BuiltInLuaVerbs not found."); return false; }
string text = File.ReadAllText(path);
int start = text.IndexOf("switch (sub)", StringComparison.Ordinal);
int end = start < 0 ? -1 : text.IndexOf("default:", start, StringComparison.Ordinal);
if (start < 0 || end < 0) { Console.WriteLine("FAIL built-in /lua verbs: the 'switch (sub)' in HandleLuaChatCommand was not found."); return false; }
var cases = Regex.Matches(text.Substring(start, end - start), @"case\s+""([^""]+)""\s*:")
.Select(m => m.Groups[1].Value).ToHashSet(StringComparer.OrdinalIgnoreCase);
var missingFromSet = cases.Except(verbs, StringComparer.OrdinalIgnoreCase).ToList();
var missingFromSwitch = verbs.Except(cases, StringComparer.OrdinalIgnoreCase).ToList();
bool ok = cases.Count > 0 && missingFromSet.Count == 0 && missingFromSwitch.Count == 0;
Console.WriteLine($"{(ok ? "PASS" : "FAIL")} built-in /lua verbs match the dispatch switch ({cases.Count} verbs)");
if (missingFromSet.Count > 0) Console.WriteLine(" in the switch but not in BuiltInLuaVerbs: " + string.Join(", ", missingFromSet));
if (missingFromSwitch.Count > 0) Console.WriteLine(" in BuiltInLuaVerbs but not in the switch: " + string.Join(", ", missingFromSwitch));
if (cases.Count == 0) Console.WriteLine(" no case labels found (did the switch change shape?)");
return ok;
}
/// <summary>The project's own Scripts folder (so a deleted script can't linger in bin), else the copy in bin.</summary>
private static string ScriptFolder([System.Runtime.CompilerServices.CallerFilePath] string source = "")
{

View file

@ -400,6 +400,15 @@ internal static partial class Program
Check(atlas.Search("glimmering cave", null, 50).Count == 1, "case-insensitive");
Check(atlas.Search("cave glimmering", null, 50).Count == 1, "every word, any order");
// "a || b || c" (Oracle's Dynamic Stamps): the first candidate on the map, whole words only.
Check(atlas.FirstOnMap("8.8S, 53.1E || Holtburg", false, 0, 0) == "8.8S, 53.1E", "coordinates first");
Check(atlas.FirstOnMap("Nowhere Keep || Holtburg || Glimmering Cave", false, 0, 0) == "Holtburg", "the first place on the map");
Check(atlas.FirstOnMap("Cave Hermit || Holtburg", false, 0, 0) == "Holtburg", "a place with no map position is skipped");
Check(atlas.FirstOnMap("olt || Holtburg", false, 0, 0) == "Holtburg", "inside a word ('olt' in Holtburg) doesn't count");
Check(atlas.FirstOnMap("zzz || qqq", false, 0, 0) == null, "none on the map");
Check(atlas.FirstOnMap(" nowhere keep || || HOLTBURG ", false, 0, 0) == "HOLTBURG", "extra spaces, empty candidates and case are fine");
Check(atlas.FirstOnMap("", false, 0, 0) == null, "no candidates at all");
var p2 = atlas.ById(2)!;
Check(p2.HasDest && p2.DestOnMap, "portal destination");
Near(p2.DestNs, 42.08, 1e-9, "portal destination NS");

View file

@ -48,9 +48,13 @@ namespace RynthOracle.Tests
ConquestReplies();
AelrynthReplies();
Void();
TimerAlerts();
Pages();
CharacterExtras();
Events();
QuestTexts();
Refreshes();
SkillsTabs();
Console.WriteLine($"{_pass} passed, {_fail} failed");
return _fail == 0 ? 0 : 1;
}
@ -78,6 +82,42 @@ namespace RynthOracle.Tests
Check(SpellTable.TryGet(4305, out SpellInfo f) && !f.IsDebuff && f.Duration == 5400, "Incantation of Focus Self is a 5400 s buff");
}
private static void TimerAlerts()
{
// "hourly" has a 1 h timer finished at t0; "daily" finished long ago; "never" is one-time.
DateTime t0 = new(2026, 10, 18, 12, 0, 0, DateTimeKind.Utc);
long done = new DateTimeOffset(t0).ToUnixTimeSeconds();
var store = new QuestFlagStore();
store.OnChatLine($"hourly - 1 solves ({done})\"Hourly\" -1 3600", 1000);
store.OnChatLine($"daily - 1 solves ({done - 100000})\"Daily\" -1 3600", 1000);
store.OnChatLine($"never - 1 solves ({done})\"Once\" 1 0", 1000);
store.Tick(5000);
var cat = new QuestCatalog();
var tracked = new List<string> { "hourly", "daily", "never", "unknown" };
var w = new QuestTimerWatcher();
Check(w.Check(store, cat, tracked, t0.AddMinutes(10)).Count == 0, "no alert for what was ready when first seen");
Check(w.Check(store, cat, tracked, t0.AddMinutes(59)).Count == 0, "no alert while on cooldown");
var up = w.Check(store, cat, tracked, t0.AddMinutes(61));
Check(up.Count == 1 && up[0].Flag == "hourly", "alert when the timer comes up");
Check(w.Check(store, cat, tracked, t0.AddMinutes(62)).Count == 0, "alert only once");
var w2 = new QuestTimerWatcher();
w2.Check(store, cat, new List<string>(), t0.AddMinutes(10));
Check(w2.Check(store, cat, new List<string>(), t0.AddMinutes(61)).Count == 0, "an untracked quest is silent");
var w3 = new QuestTimerWatcher();
w3.Check(store, cat, null, t0.AddMinutes(10));
Check(w3.Check(store, cat, null, t0.AddMinutes(61)).Count == 1, "watching everything alerts on the repeatable only");
store.OnChatLine($"hourly - 2 solves ({done + 4000})\"Hourly\" -1 3600", 9000);
store.Tick(12000);
Check(w.Check(store, cat, tracked, t0.AddMinutes(80)).Count == 0, "a fresh completion waits again");
Check(w.Check(store, cat, tracked, t0.AddMinutes(140)).Count == 1, "and alerts again when it comes up");
// Not read yet: nothing to say.
Check(new QuestTimerWatcher().Check(new QuestFlagStore(), cat, tracked, t0).Count == 0, "no alerts before the flags are read");
}
private static void QuestLines()
{
// ACE PlayerCommands.HandleQuests: no space between ")" and the quote.
@ -632,6 +672,311 @@ namespace RynthOracle.Tests
Check(!main.Visible, "a player close hides the window");
}
/// <summary>
/// A click on a quest prints its texts in chat the way upstream's list "thinks" them: the info and
/// hint, the link, and the flag's history ("Never completed" for a flag the character lacks).
/// </summary>
private static void QuestTexts()
{
OracleContext c = Context();
var printed = new List<string>();
c.PrintSink = printed.Add;
Check(c.Catalog.TryGet("30minattributes", out Quest held), "the catalog has 30minattributes");
List<string> lines = QuestText.Lines(held, c.Flags, c.Book, c.UtcNow);
Check(lines[0].StartsWith("Attribute and Skill Redistribution (30minattributes) - "), "first line: name, flag, status: " + lines[0]);
Check(lines[1] == "30minattributes: " + held.Details() && lines[1].Contains("30 Minutes to pick up Attribute Gems"), "the info and hint text: " + lines[1]);
Check(lines[2] == "30minattributes: " + held.Url && held.Url.StartsWith("https://"), "the wiki link");
Check(lines[3].StartsWith("30minattributes: x CompletedOn:") && lines[3].Contains("Solves:4 MaxSolves:-1 RepeatTime:30m"),
"a held flag prints its history (upstream's QuestFlag text): " + lines[3]);
Check(c.Book.TryGetReward("30minattributes", out QuestReward rw) && lines[4] == "Rewards: " + rw.LongSummary(), "recorded rewards come last: " + lines[4]);
// A flag no list knows and the character lacks: says so rather than staying silent.
List<string> none = QuestText.Lines(new Quest { Flag = "madeupflag", IsNew = true }, c.Flags, c.Book, c.UtcNow);
Check(none.Count == 4 && none[0] == "Not in the quest list (madeupflag) - not done", "unknown quest header: " + none[0]);
Check(none[1] == "madeupflag: No hint available" && none[2] == "madeupflag: No url available" && none[3] == "madeupflag: Never completed",
"no hint, no link, never completed: " + string.Join(" | ", none));
// The click itself, on the Quests tab and in the Quest Timers window.
c.Settings.TabName = OracleView.TabQuests;
var view = new OracleView(c);
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
main.Begin(); view.Draw(main); main.End();
Apply(host, Event(1, 40, main.Hash, main.KeyOf("q.r.30minattributes"), new byte[] { 1, 0, 0 }));
Check(printed.Count == lines.Count && printed[1] == lines[1], $"a click on a quest prints its texts ({printed.Count} lines)");
main.Begin(); view.Draw(main); main.End();
Check(Encoding.UTF8.GetString(main.Body).Contains("Save rewards"), "the click still opens the quest below the list");
printed.Clear();
Apply(host, Event(1, 41, main.Hash, main.KeyOf("q.r.30minattributes"), new byte[] { 1, 0, 0 }));
Check(printed.Count == lines.Count, "a second click prints again (and closes it), as upstream's list did");
UiWindow timersW = host.Add(new UiWindow("RynthOracle/QuestTimers", "Quest Timers") { Visible = true });
var tv = new QuestTimersView(c);
timersW.Begin(); tv.Draw(timersW); timersW.End();
printed.Clear();
Apply(host, Event(1, 42, timersW.Hash, timersW.KeyOf("qt.r.30minattributes"), new byte[] { 1, 0, 0 }));
Check(printed.Count == lines.Count && printed[1] == lines[1], "a click on a tracked quest in the Quest Timers window prints its texts");
}
/// <summary>
/// The Skills, Attributes and Progress tabs: three more tabs, the others untouched, and the
/// /rc oracle-skills hand-off sent only when the wanted mode changes.
/// </summary>
private static void SkillsTabs()
{
// The tabs: after Character, on every server; every earlier tab is still there.
string[] earlier = { OracleView.TabQuests, OracleView.TabCharacter, OracleView.TabAugs, OracleView.TabSociety,
OracleView.TabMarkers, OracleView.TabTitles, OracleView.TabVoid, OracleView.TabFellowship, OracleView.TabAbout };
OracleContext c = Context();
var view = new OracleView(c);
foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, "" })
{
c.Server.Force(server, server);
string[] tabs = view.VisibleTabs();
string label = server.Length > 0 ? server : "other";
Check(earlier.All(tabs.Contains), $"{label}: every earlier tab is still there: " + string.Join(",", tabs));
int ch = Array.IndexOf(tabs, OracleView.TabCharacter);
Check(tabs.Skip(ch + 1).Take(3).SequenceEqual(new[] { OracleView.TabSkills, OracleView.TabAttributes, OracleView.TabProgress }),
$"{label}: Skills, Attributes, Progress follow Character");
}
Check((OracleView.TabSkills, OracleView.TabAttributes, OracleView.TabProgress) == ("Skills", "Attributes", "Progress"), "the tabs are named Skills, Attributes, Progress");
// The page: the tab strip and nothing below it (the engine fills the rest), and a click selects the tab.
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
string Draw()
{
main.Begin(); view.Draw(main); main.End();
string body = Encoding.UTF8.GetString(main.Body);
main.MarkSubmitted(true);
return body;
}
c.Settings.TabName = OracleView.TabQuests;
Draw();
Apply(host, Event(1, 500, main.Hash, main.KeyOf("tab." + OracleView.TabSkills), new byte[] { 1, 0, 0 }));
Check(view.Tab == OracleView.TabSkills, "a click on the Skills tab selects it");
main.Begin(); view.Draw(main); main.End();
string skills = Encoding.UTF8.GetString(main.Body);
ParseAll(host, "skills tab", out int ops);
main.MarkSubmitted(true);
Check(skills.Contains("tab.Attributes") && skills.Contains("tab.Progress"), "the Skills page still shows the whole tab strip");
Check(!skills.Contains("Refresh###") && !skills.Contains("page.Skills") && !skills.Contains("Log in to a character"),
"the Skills page has no Refresh row and no child covering the engine's region");
Check(ops > 5, $"skills tab parses ({ops} ops)");
c.InWorld = false;
Check(Draw().Contains("Log in to a character"), "logged out, the Skills tab says to log in (the engine is told off)");
c.InWorld = true;
// The state machine.
var sent = new List<string>();
bool accept = true;
var e = new SkillsEmbed(cmd => { sent.Add(cmd); return accept; });
long now = 10_000;
bool U(string tab, bool visible = true, bool inWorld = true) => e.Update(tab, visible, inWorld, now += 16);
for (int i = 0; i < 50; i++) U(OracleView.TabSkills, inWorld: false);
Check(sent.Count == 0 && !e.Announced, "logged out, before any command: nothing is sent");
for (int i = 0; i < 50; i++) U(OracleView.TabQuests);
Check(sent.SequenceEqual(new[] { "/rc oracle-skills off" }) && e.Announced,
"in the world on another tab: one off, the announcement that Oracle has these tabs, and no more");
sent.Clear();
for (int i = 0; i < 100; i++) U(OracleView.TabSkills);
Check(sent.SequenceEqual(new[] { "/rc oracle-skills skills" }), "Skills: one command, however many frames follow");
U(OracleView.TabAttributes); U(OracleView.TabAttributes);
U(OracleView.TabProgress); U(OracleView.TabProgress);
U(OracleView.TabSkills);
Check(sent.Skip(1).SequenceEqual(new[] { "/rc oracle-skills attrs", "/rc oracle-skills progress", "/rc oracle-skills skills" }),
"moving between the three tabs sends the new mode once each: " + string.Join(" | ", sent));
sent.Clear();
U(OracleView.TabQuests);
for (int i = 0; i < 20; i++) U(OracleView.TabQuests);
U(OracleView.TabCharacter);
Check(sent.SequenceEqual(new[] { "/rc oracle-skills off" }), "leaving for another tab sends off once");
sent.Clear();
U(OracleView.TabSkills);
U(OracleView.TabSkills, visible: false); U(OracleView.TabSkills, visible: false);
Check(sent.SequenceEqual(new[] { "/rc oracle-skills skills", "/rc oracle-skills off" }), "hiding the window (its X, /ro) sends off once");
sent.Clear();
U(OracleView.TabSkills);
Check(sent.SequenceEqual(new[] { "/rc oracle-skills skills" }), "showing it again on the same tab sends the mode again");
sent.Clear();
U(OracleView.TabSkills, inWorld: false); U(OracleView.TabSkills, inWorld: false);
Check(sent.SequenceEqual(new[] { "/rc oracle-skills off" }), "logging out sends off once");
sent.Clear();
U(OracleView.TabAbout, visible: false);
Check(sent.Count == 0 && e.Sent == SkillsEmbed.Off, "already off: nothing more is sent");
// The first command is the mode itself when the window opens on a Skills tab at login; Shutdown before any command sends nothing.
var first = new List<string>();
var fresh = new SkillsEmbed(cmd => { first.Add(cmd); return true; });
fresh.Update(OracleView.TabAttributes, true, true, 1); fresh.Update(OracleView.TabAttributes, true, true, 2);
Check(first.SequenceEqual(new[] { "/rc oracle-skills attrs" }), "a window that opens on Attributes sends attrs once, and no separate off");
var never = new SkillsEmbed(cmd => { first.Add(cmd); return true; });
first.Clear();
Check(!never.Shutdown() && first.Count == 0, "Shutdown before any command sends nothing");
// Shutdown: off if (and only if) a body is up.
Check(!e.Shutdown() && sent.Count == 0, "Shutdown while off sends nothing");
U(OracleView.TabProgress);
sent.Clear();
Check(e.Shutdown() && sent.SequenceEqual(new[] { "/rc oracle-skills off" }) && e.Sent == SkillsEmbed.Off, "Shutdown while a body is up sends off");
Check(!e.Shutdown() && sent.Count == 1, "a second Shutdown sends nothing");
// A refused send is retried, but not every frame.
sent.Clear();
accept = false;
now = 50_000;
Check(!e.Update(OracleView.TabSkills, true, true, now), "a refused send reports false");
for (int i = 0; i < 30; i++) e.Update(OracleView.TabSkills, true, true, now + i * 16);
Check(sent.Count == 1 && e.Sent == SkillsEmbed.Off, $"a refused send is not repeated every frame ({sent.Count} attempts)");
accept = true;
Check(!e.Update(OracleView.TabSkills, true, true, now + SkillsEmbed.RetryMs - 1) && sent.Count == 1, "no retry before the gap has passed");
Check(e.Update(OracleView.TabSkills, true, true, now + SkillsEmbed.RetryMs) && e.Sent == "skills", "retried after the gap, and then recorded");
accept = false;
Check(!e.Shutdown() && e.Sent == "skills", "a refused Shutdown send keeps the state");
accept = true;
Check(e.Shutdown() && e.Sent == SkillsEmbed.Off, "and a later Shutdown tries again");
// Which tab wants what.
Check(SkillsEmbed.Wanted(OracleView.TabSkills, true, true) == "skills" && SkillsEmbed.Wanted(OracleView.TabAttributes, true, true) == "attrs"
&& SkillsEmbed.Wanted(OracleView.TabProgress, true, true) == "progress", "the three modes are skills, attrs, progress");
Check(SkillsEmbed.Wanted(OracleView.TabQuests, true, true) == "off" && SkillsEmbed.Wanted(OracleView.TabAbout, true, true) == "off", "every other tab is off");
}
/// <summary>Every page has a Refresh button; each does its own reload and says what it did.</summary>
private static void Refreshes()
{
OracleContext c = Context();
var sent = new List<string>();
int quests = 0, chars = 0, titles = 0, lists = 0;
c.Send = cmd => { sent.Add(cmd); return true; };
c.RequestQuests = () => { quests++; return true; };
c.RereadCharacter = () => chars++;
c.RereadTitles = () => titles++;
c.ReloadQuestList = () => lists++;
var view = new OracleView(c);
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
uint seq = 100;
string Draw()
{
main.Begin(); view.Draw(main); main.End();
string body = Encoding.UTF8.GetString(main.Body);
main.MarkSubmitted(true);
return body;
}
void Click(string id)
{
Draw();
Apply(host, Event(1, seq++, main.Hash, main.KeyOf(id), new byte[] { 1, 0, 0 }));
}
void Press(string scope) => Click("refresh." + scope);
// A Refresh button on every tab, on every server.
foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, "" })
{
c.Server.Force(server, server);
foreach (string tab in view.VisibleTabs())
{
if (SkillsEmbed.IsEmbedTab(tab)) continue; // RynthCore draws these pages; see SkillsTabs()
c.Settings.TabName = tab;
string body = Draw();
Check(body.Contains("Refresh###refresh." + tab), $"{(server.Length > 0 ? server : "other")}/{tab} has a Refresh button");
}
}
// Quests: /myquests, and the line waits for the flags.
c.Server.Force("", "Coldeve");
c.Settings.TabName = OracleView.TabQuests;
Press("Quests");
Check(quests == 1, "Quests: Refresh asks for the quest flags");
string waiting = Draw();
Check(waiting.Contains("Asked the server for your quest flags") && waiting.Contains("Waiting for the reply"), "Quests: the line says it is waiting");
c.Flags.OnChatLine("freshflag - 1 solves (1719432000)\"x\" -1 0", c.NowMs);
c.Flags.Tick(c.NowMs + 5000);
Check(Draw().Contains("Updated "), "Quests: the line says Updated once the reply lands");
c.NowMs += 20_000;
Press("Quests");
Check(Draw().Contains("Waiting for the reply"), "Quests: a second Refresh waits again");
c.NowMs += 16_000;
Check(Draw().Contains("No reply yet"), "Quests: no reply for 15 s says so");
// Tabs built from the character: re-read it; those with quest timers ask for the flags too.
foreach ((string tab, int wantChars, int wantQuests) in new[]
{
(OracleView.TabCharacter, 1, 0), (OracleView.TabAugs, 1, 1), (OracleView.TabSociety, 1, 1),
(OracleView.TabMarkers, 0, 1), (OracleView.TabVoid, 1, 0),
})
{
chars = quests = 0;
c.Settings.TabName = tab;
Press(tab);
Check(chars == wantChars && quests == wantQuests, $"{tab}: Refresh re-reads {wantChars}x character, {wantQuests}x quest flags (got {chars}, {quests})");
Check(Draw().Contains(wantQuests > 0 ? "Waiting for the reply" : "Refreshed "), $"{tab}: the line says what happened");
}
// Titles, Fellowship, About: local reloads.
c.EarnedTitles.Add(1);
c.TitlesKnown = true;
c.Settings.TabName = OracleView.TabTitles;
Press("Titles");
Check(titles == 1 && Draw().Contains("Re-read your titles from the game: 1 held."), "Titles: re-reads the titles the engine holds");
c.Settings.TabName = OracleView.TabFellowship;
Press("Fellowship");
Check(Draw().Contains("Re-read the fellowship from the game."), "Fellowship: re-reads the member table");
c.Settings.TabName = OracleView.TabAbout;
c.NowMs += 10_000;
Press("About");
Check(lists == 1 && Draw().Contains("Reloaded the quest list"), "About: reloads the quest list files");
Press("About");
Check(lists == 1 && Draw().Contains("wait a few seconds"), "About: pressed again at once, nothing reloads");
c.NowMs += 4000;
Press("About");
Check(lists == 2, "About: allowed again after the pause");
// ConquestAC: the sub-page's own command, once per pause; the line follows the reply.
c.Server.Force(ServerTags.Conquest, "Conquest");
c.Settings.TabName = OracleView.TabConquest;
string[] want = { "/b", "/augs", "/enl augs", "/bonus", "/fship list" };
for (int v = 0; v < 6; v++)
{
Click("cq.v." + v);
sent.Clear();
quests = 0;
c.NowMs += 4000;
Press("Conquest" + v);
if (v < 5) Check(sent.Count == 1 && sent[0] == want[v], $"Conquest view {v}: Refresh sends {want[v]} (sent {string.Join(",", sent)})");
else Check(sent.Count == 0 && quests == 1, "Conquest custom quests: Refresh asks for the quest flags");
Press("Conquest" + v);
Check(sent.Count == (v < 5 ? 1 : 0), $"Conquest view {v}: a second press at once sends nothing more");
}
Click("cq.v.0");
c.NowMs += 4000;
Press("Conquest0");
System.Threading.Thread.Sleep(5);
c.Conquest.OnChatLine("[BANK] Pyreals: 2,000", c.NowMs, out _);
Check(Draw().Contains("Updated "), "Conquest bank: the line says Updated when the balances arrive");
// Boards: ConquestAC's board, then Aelrynth's three views.
c.Settings.TabName = OracleView.TabBoards;
sent.Clear();
c.NowMs += 4000;
Press(OracleView.TabBoards + "00");
Check(sent.Count == 1 && sent[0].StartsWith("/top "), "ConquestAC boards: Refresh sends /top <board>: " + string.Join(",", sent));
c.Server.Force(ServerTags.Aelrynth, "Aeshnidae");
sent.Clear();
foreach ((int viewNo, string cmd) in new[] { (0, "/top"), (1, "/top me"), (2, "/trial") })
{
Click("ab.v" + viewNo);
c.NowMs += 4000;
Press($"{OracleView.TabBoards}{viewNo}0");
Check(sent.Count > 0 && sent[^1].TrimEnd() == cmd, $"Aelrynth boards view {viewNo}: Refresh sends {cmd} (sent {sent.LastOrDefault()})");
}
}
private static byte[] Event(ushort type, uint seq, uint window, uint key, byte[] payload)
{
var e = new byte[16 + payload.Length];

View file

@ -86,6 +86,7 @@ namespace RynthSort.Tests
Run("moves: answers for moves within a pack", MoveAnswersInPlace);
Run("plan: a fixed inventory runs out of moves", Converges);
Run("loop: auto-sort tidies every pack, then stays still", ConvergesInTheLoop);
Run("remote: another plugin's \"rsort\" command reaches /rsort, anything else is not ours", RemoteCommand);
}
finally
{
@ -96,6 +97,17 @@ namespace RynthSort.Tests
return _fail == 0 ? 0 : 1;
}
// RynthAi sends ub-IT's /ub packsort as SendPluginCommand("RynthSort", "rsort", "now").
private static void RemoteCommand()
{
Eq(RynthSortPlugin.RemoteSortArgument("rsort", "now"), "now", "rsort now");
Eq(RynthSortPlugin.RemoteSortArgument("RSort", "status"), "status", "case-insensitive action");
Eq(RynthSortPlugin.RemoteSortArgument("rsort", null), "", "no value is an empty /rsort");
Check(RynthSortPlugin.RemoteSortArgument("sort", "now") == null, "another action is not ours");
Check(RynthSortPlugin.RemoteSortArgument(null, "now") == null, "no action is not ours");
Check(RynthSortPlugin.RemoteSortArgument("", "now") == null, "empty action is not ours");
}
private static void Run(string name, Action test)
{
int before = _fail;