Snapshot for release 2026.10.20.1 (internal 7116fab)

This commit is contained in:
Tom Bohar 2026-10-20 21:28:18 -04:00
commit bfcd48950d
215 changed files with 16200 additions and 2838 deletions

View file

@ -391,6 +391,50 @@ internal static class Program
var p5 = AutoVendorPlanner.PlanNext(v, none, new List<SellItem>(), Pack(0));
Eq(p5.Kind, PlanKind.Done, "nothing to do");
// A split lands on another partial stack of the same item, so the planner never splits while one
// exists (Drakkon's Gold Peas looped split-wait-split, 2026-10-19). Peas: 25,000 each, max 100.
SellItem Pea(uint id, int stack) => new() { Id = id, Name = "Gold Pea", Value = 25_000 * stack, StackSize = stack,
Class = AcObjectClass.Misc, ItemType = 0x40000000, RuleName = "S: Peas", MaxStack = 100, Wcid = 9001 };
// 88 free main slots: (88 - 2) * 25000 / 25000 = 86 peas fit.
var twoPartials = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { Pea(1, 100), Pea(2, 91), Pea(3, 88) }, Pack(0, free: 88));
Eq(twoPartials.Kind, PlanKind.Merge, "two partials: merge first");
Eq(twoPartials.SplitItem!.Id, 3u, "the smaller partial goes...");
Eq(twoPartials.MergeTarget!.Id, 2u, "...onto the bigger one");
// Right after a split: the new stack (38) fits and is sold, never merged back onto the source (62).
var justSplit = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { Pea(1, 62), Pea(2, 38), Pea(3, 100) }, Pack(0, free: 40));
Eq(justSplit.Kind, PlanKind.Sell, "the freshly split stack is sold...");
Eq(justSplit.Sells.Single().Id, 2u, "...not merged back");
var justSplit2 = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { Pea(1, 100), Pea(2, 62), Pea(3, 38) }, Pack(0, free: 40));
Eq(justSplit2.Kind, PlanKind.Sell, "same with a full stack first");
Eq(justSplit2.Sells.Single().Id, 3u, "the 38");
var onePartialFits = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { Pea(1, 100), Pea(2, 79) }, Pack(0, free: 88));
Eq(onePartialFits.Kind, PlanKind.Sell, "one partial that fits: sold whole, no split");
Eq(onePartialFits.Sells.Single().Id, 2u, "the partial");
var onePartialBig = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { Pea(1, 100), Pea(2, 95) }, Pack(0, free: 88));
Eq(onePartialBig.Kind, PlanKind.Split, "one partial too big: split...");
Eq(onePartialBig.SplitItem!.Id, 2u, "...from the partial itself (nothing else for it to join)");
Eq(onePartialBig.SplitAmount, 86, "86 fit");
var allFull = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { Pea(1, 100), Pea(2, 100) }, Pack(0, free: 88));
Eq(allFull.Kind, PlanKind.Split, "all full: plain split");
Eq(allFull.SplitItem!.Id, 1u, "from the first");
var otherItem = new SellItem { Id = 5, Name = "Silver Pea", Value = 50, StackSize = 50, MaxStack = 100, Wcid = 9002, Class = AcObjectClass.Misc, ItemType = 0x40000000 };
var notSame = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { Pea(1, 100), otherItem }, Pack(0, free: 88));
Eq(notSame.Kind, PlanKind.Split, "another item's partial doesn't count");
Eq(notSame.SplitItem!.Id, 1u, "gold split as asked");
// Stale stack values: a split leaves 100 peas' value on a small stack, a merge leaves a small value on a big one.
Eq(AutoVendorPlanner.MostCarriedUnit(new Dictionary<int, long> { [25_000] = 800, [1_250_000] = 2, [3_000] = 100 }), 25_000, "most peas carry the true price");
Eq(AutoVendorPlanner.MostCarriedUnit(new Dictionary<int, long> { [25_000] = 50, [30_000] = 50 }), 30_000, "tie: the higher value");
Eq(AutoVendorPlanner.MostCarriedUnit(new Dictionary<int, long>()), 0, "nothing: 0 (no override)");
var unknownMax = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { S(1, "Gem", 100_000, stack: 100), S(2, "Gem", 50_000, stack: 50) }, Pack(0, free: 3));
Eq(unknownMax.Kind, PlanKind.Split, "unknown max stack: the old plain split");
// Payout estimate uses the vendor's buy rate (ACE floor(value * rate + 0.1)).
var half = Vendor(buy: 0.5f);
var p6 = AutoVendorPlanner.PlanNext(half, none, new List<SellItem> { S(1, "Salvage", 101) }, Pack(0));

View file

@ -230,6 +230,16 @@ internal static unsafe class FakeHost
public static bool UseOnCalls;
/// <summary>Every UseObjectOn (source, target), in order (opt-in with <see cref="UseOnCalls"/>).</summary>
public static readonly List<(uint Source, uint Target)> UsesOn = new();
/// <summary>Opt-in (set before Create): the trade window and vendor calls (API v72 / v67). A vendor named
/// <see cref="VendorName"/> (id 0x70000001) is open; every trade action and vendor transaction is recorded.</summary>
public static bool TradeVendorCalls;
public static string VendorName = "Town Vendor";
/// <summary>Trade actions in order: "accept", "decline", "reset", "close", "add:<id>".</summary>
public static readonly List<string> TradeActions = new();
/// <summary>Every VendorSell: the vendor id and the item ids.</summary>
public static readonly List<(uint Vendor, uint[] Items)> VendorSells = new();
/// <summary>Every VendorBuy: the vendor id and the (object, amount) entries.</summary>
public static readonly List<(uint Vendor, (uint Id, int Amount)[] Entries)> VendorBuys = new();
/// <summary>Opt-in: install SendPluginCommand (the engine's plugin-command broker, API v64).</summary>
public static bool PluginCommandCalls;
/// <summary>What SendPluginCommand answers: true = delivered (the target plugin is loaded).</summary>
@ -256,6 +266,10 @@ internal static unsafe class FakeHost
public static Action<uint>? OnUseObject;
/// <summary>Runs inside UseObjectOn, after it is recorded.</summary>
public static Action<uint, uint>? OnUseObjectOn;
/// <summary>Object id -> (health, max health) for GetTargetVitals (opt-in: installed when it has entries at Create()).</summary>
public static readonly Dictionary<uint, (uint Hp, uint MaxHp)> TargetVitals = new();
/// <summary>Opt-in (set before Create): GetLiveObjectIds (API v69) lists every id in <see cref="Names"/>.</summary>
public static bool LiveObjectsCalls;
// ANSI strings handed back to tested code stay alive for the whole run.
private static readonly Dictionary<string, IntPtr> _ansi = new();
@ -301,10 +315,12 @@ internal static unsafe class FakeHost
SelectedItem = 0;
UseOnCalls = false; UsesOn.Clear();
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear();
TradeVendorCalls = false; TradeActions.Clear(); VendorSells.Clear(); VendorBuys.Clear();
CombatModeCalls = false; CombatModeRequests.Clear(); CombatModeRefuse = false; CombatModeRefusals = 0;
BusyCalls = false; ForceResets = 0; BusyStateValue = 0;
ObjectPropertiesCalls = false; PropertyRecord = null; PropertyQueries.Clear();
ObjectStates.Clear(); OnUseObject = null; OnUseObjectOn = null;
TargetVitals.Clear(); LiveObjectsCalls = false;
}
/// <summary>
@ -351,6 +367,7 @@ internal static unsafe class FakeHost
api.GetObjectInstanceIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)&GetObjectInstanceIdProperty;
api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&SetAutoRun;
api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&TurnToHeading;
api.GetPlayerHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float*, int>)&GetPlayerHeading;
api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&JumpNonAutonomous;
if (TapJumpCalls)
api.TapJumpFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&TapJump;
@ -402,6 +419,13 @@ internal static unsafe class FakeHost
}
if (CombatModeCalls)
api.ChangeCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&ChangeCombatMode;
if (TargetVitals.Count > 0)
api.GetTargetVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, uint*, uint*, uint*, int>)&GetTargetVitals;
if (LiveObjectsCalls)
{
api.Version = Math.Max(api.Version, 69u);
api.GetLiveObjectIdsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, int, int>)&GetLiveObjectIds;
}
if (BusyCalls)
{
api.ForceResetBusyCountFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&ForceResetBusyCount;
@ -409,6 +433,23 @@ internal static unsafe class FakeHost
}
if (UseOnCalls)
api.UseObjectOnFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&UseObjectOn;
if (TradeVendorCalls)
{
api.Version = Math.Max(api.Version, 82u);
api.GetVendorInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorInfoNative*, int>)&GetVendorInfo;
api.GetVendorItemsFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorItemNative*, int, int>)&GetVendorItems;
api.VendorBuyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, VendorTradeEntryNative*, int, uint>)&VendorBuy;
api.VendorSellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, uint>)&VendorSell;
api.GetVendorTradeStatusFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorTradeStatusNative*, int>)&GetVendorTradeStatus;
api.GetTradeStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, int>)&GetTradeState;
api.GetTradeItemsFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, uint*, int, int>)&GetTradeItems;
api.TradeOpenFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&TradeOpen;
api.TradeAddFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&TradeAdd;
api.TradeAcceptFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&TradeAccept;
api.TradeDeclineFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&TradeDecline;
api.TradeResetFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&TradeReset;
api.TradeCloseFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&TradeClose;
}
if (WieldCalls)
{
api.Version = 73;
@ -630,6 +671,26 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjectIsAttackable(uint id) => NotAttackable.Contains(id) ? 0 : 1;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetTargetVitals(uint id, uint* hp, uint* maxHp, uint* stam, uint* maxStam, uint* mana, uint* maxMana)
{
if (!TargetVitals.TryGetValue(id, out var v)) return 0;
*hp = v.Hp; *maxHp = v.MaxHp; *stam = 0; *maxStam = 0; *mana = 0; *maxMana = 0;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetLiveObjectIds(uint* buffer, int capacity)
{
int n = 0;
foreach (uint id in Names.Keys)
{
if (n < capacity) buffer[n] = id;
n++;
}
return n;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectIntProperty(uint id, uint key, int* v)
{
@ -806,6 +867,16 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TurnToHeading(float deg) { HeadingDeg = deg; Turns++; return 1; }
// What the engine's GetPlayerHeading really returns: 0 = East, counter-clockwise, i.e.
// 90 - the compass heading (Freya 2026-10-20: quaternion 13.9, GetPlayerHeading 76.1).
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetPlayerHeading(float* deg)
{
if (!HasPose) return 0;
*deg = (float)(((90.0 - HeadingDeg) % 360.0 + 360.0) % 360.0);
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int JumpNonAutonomous(float extent) { Jumps++; return 1; }
@ -817,6 +888,51 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int StopCompletely() { Stops++; Sent.Add("stop"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetVendorInfo(VendorInfoNative* info)
{
*info = default;
info->VendorId = 0x70000001;
byte[] name = System.Text.Encoding.ASCII.GetBytes(VendorName);
for (int i = 0; i < name.Length && i < 63; i++) info->Name[i] = name[i];
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetVendorItems(VendorItemNative* items, int max) => 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint VendorBuy(uint vendor, VendorTradeEntryNative* entries, int count)
{
var list = new (uint, int)[count];
for (int i = 0; i < count; i++) list[i] = (entries[i].ObjectId, entries[i].Amount);
VendorBuys.Add((vendor, list));
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint VendorSell(uint vendor, uint* ids, int count)
{
var list = new uint[count];
for (int i = 0; i < count; i++) list[i] = ids[i];
VendorSells.Add((vendor, list));
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetVendorTradeStatus(VendorTradeStatusNative* status) => 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetTradeState(IntPtr state) => 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetTradeItems(int side, uint* buffer, int capacity) => 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeOpen(uint target) { TradeActions.Add("open:" + target.ToString("X8")); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeAdd(uint item, uint slot) { TradeActions.Add("add:" + item.ToString("X8")); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeAccept() { TradeActions.Add("accept"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeDecline() { TradeActions.Add("decline"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeReset() { TradeActions.Add("reset"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeClose() { TradeActions.Add("close"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void ForceResetBusyCount() { ForceResets++; BusyStateValue = 0; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetBusyState() => BusyStateValue;

View file

@ -0,0 +1,168 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using RynthCore.Plugin.Shared;
namespace RynthCore.RynthAiHostTests.Fakes;
/// <summary>
/// A stand-in for a server plugin's "RynthILT.Hub" table (Plugins/Shared/RynthIltHubApi.cs), so the
/// tests can check what RynthAi does WITH a server plugin (RynthILT) as well as without one. Its
/// functions answer from the static state below; RynthAi's ServerHubClient takes the table through
/// UseTableForTests. The render functions draw nothing (no ImGui frame in the tests): they only
/// record which section was asked for. Reset() before each test that uses it.
/// </summary>
internal static unsafe class FakeServerHub
{
/// <summary>IsIltWorld's answer.</summary>
public static bool Active;
/// <summary>GetFeature: key -> -1 / 0 / 1 (missing = -1).</summary>
public static readonly Dictionary<string, int> Features = new(StringComparer.OrdinalIgnoreCase);
/// <summary>AllowSummonOnEmpty's answer.</summary>
public static bool AllowEmpty;
/// <summary>GetSubTabs(parent): parent -> (id, label) list.</summary>
public static readonly Dictionary<string, List<(string Id, string Label)>> SubTabs = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Command lines the plugin took, and which it takes (null = none).</summary>
public static readonly List<string> Commands = new();
public static Func<string, bool>? TakesCommand;
/// <summary>RenderSection ids asked for, and the ones that "draw" (return 1).</summary>
public static readonly List<string> SectionsAsked = new();
public static readonly HashSet<string> SectionsDrawn = new(StringComparer.OrdinalIgnoreCase);
/// <summary>GetSetting / SetSetting: key -> value (missing = not offered, -1; SetSetting only takes known keys).</summary>
public static readonly Dictionary<string, int> Settings = new(StringComparer.OrdinalIgnoreCase);
/// <summary>GetText: id -> text (missing = "").</summary>
public static readonly Dictionary<string, string> Texts = new(StringComparer.OrdinalIgnoreCase);
private static RynthIltHubApiV1* _table;
public static void Reset()
{
Active = false;
Features.Clear();
AllowEmpty = false;
SubTabs.Clear();
Commands.Clear();
TakesCommand = null;
SectionsAsked.Clear();
SectionsDrawn.Clear();
Settings.Clear();
Texts.Clear();
}
/// <summary>The table (allocated once, never freed: like the real one).</summary>
public static IntPtr Table
{
get
{
if (_table == null)
{
var t = (RynthIltHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltHubApiV1));
t->StructSize = (uint)sizeof(RynthIltHubApiV1);
t->IsIltWorld = &IsIltWorld;
t->GetFeature = &GetFeature;
t->GetTabs = &GetTabs;
t->RenderTab = &RenderTab;
t->RenderSection = &RenderSection;
t->Command = &Command;
t->AllowSummonOnEmpty = &AllowSummonOnEmpty;
t->GetSubTabs = &GetSubTabs;
t->GetSetting = &GetSetting;
t->SetSetting = &SetSetting;
t->GetText = &GetText;
t->Version = RynthIltHubApiV1.InterfaceVersion;
_table = t;
}
return (IntPtr)_table;
}
}
private static string? Utf8(byte* p) => p == null ? null : Marshal.PtrToStringUTF8((IntPtr)p);
private static void Write(string s, byte* dest, int capacity)
{
byte[] b = Encoding.UTF8.GetBytes(s);
int n = Math.Min(b.Length, capacity - 1);
for (int i = 0; i < n; i++) dest[i] = b[i];
dest[n] = 0;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int IsIltWorld() => Active ? 1 : 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetFeature(byte* key)
{
string? k = Utf8(key);
return k != null && Features.TryGetValue(k, out int v) ? v : -1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetTabs(IltTabV1* tabs, int capacity) => 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int RenderTab(byte* id) => 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int RenderSection(byte* id)
{
string s = Utf8(id) ?? string.Empty;
SectionsAsked.Add(s);
return SectionsDrawn.Contains(s) ? 1 : 0;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Command(byte* text)
{
string line = Utf8(text) ?? string.Empty;
if (TakesCommand?.Invoke(line) != true) return 0;
Commands.Add(line);
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSetting(byte* key)
{
string? k = Utf8(key);
return k != null && Settings.TryGetValue(k, out int v) ? v : -1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetSetting(byte* key, int value)
{
string? k = Utf8(key);
if (k == null || !Settings.ContainsKey(k)) return 0;
Settings[k] = value;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetText(byte* id, byte* buffer, int capacity)
{
string? k = Utf8(id);
if (k == null || !Texts.TryGetValue(k, out string? text) || text.Length == 0) return 0;
Write(text, buffer, capacity);
return Encoding.UTF8.GetByteCount(text);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int AllowSummonOnEmpty() => AllowEmpty ? 1 : 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSubTabs(byte* parent, IltTabV1* tabs, int capacity)
{
string p = Utf8(parent) ?? string.Empty;
if (!SubTabs.TryGetValue(p, out var list)) return 0;
if (tabs != null)
for (int i = 0; i < list.Count && i < capacity; i++)
{
Write(list[i].Id, tabs[i].Id, 24);
Write(list[i].Label, tabs[i].Label, 32);
tabs[i].Width = 0;
tabs[i].Height = 0;
tabs[i].Flags = RynthIltHub.TabShown | RynthIltHub.TabAvailable;
}
return list.Count;
}
}

View file

@ -92,13 +92,17 @@ internal static class Program
TargetingTests.Register(runner);
LootAddItemTests.Register(runner);
GiveTests.Register(runner);
UbCompatTests.Register(runner);
MetaAuditTests.Register(runner);
MetaSampleCompatTests.Register(runner);
IdRefusalTests.Register(runner);
DungeonMapBakeTests.Register(runner);
MonsterEditorTests.Register(runner);
InstallPathsTests.Register(runner);
PetRefillTests.Register(runner);
AutoStackTests.Register(runner);
RingEvadeTests.Register(runner);
BackAwayTests.Register(runner);
ServerPluginForwardTests.Register(runner);
IgnoreMonsterTests.Register(runner);
WorldCacheTypedTests.Register(runner);
NavOverlayTests.Register(runner);
@ -106,6 +110,7 @@ internal static class Program
HazardEscapeTests.Register(runner);
ManaStoneChoiceTests.Register(runner);
CustomDebuffTests.Register(runner);
DebuffRenewTests.Register(runner);
ProfileLoadTests.Register(runner);
ActivityInterfaceTests.Register(runner);
CastNoDamageTests.Register(runner);
@ -141,7 +146,8 @@ internal static class Program
LauncherSwapTests.Register(runner);
MissileCraftingTests.Register(runner);
SelfRatingsTests.Register(runner);
IltClientLookupTests.Register(runner);
ServerHubClientLookupTests.Register(runner);
UbMtSafetyTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,111 @@
using System;
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;
// The back-away combat does on a server plugin's request (CombatManager.BackAwayFrom, RynthAi.Hub
// BackAwayFrom). It was the Empyrean Handler lethal-ring evade (Silentkelpie's PR 12) until 2026-10-20,
// when the Handler's detection and its setting went to RynthILT (Infinite Leaftide content); RynthAi
// keeps the generic part: face the object, back-jump, hold attacks until it settles. Gated: only while
// the macro is running with combat on, and only inside the radius (at least Ring Range). RynthAi alone
// never reacts to the Handler's line any more.
internal static class BackAwayTests
{
private const uint Player = 0x50000D11;
private const uint Danger = 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("back away: inside the radius with the macro running and combat on, one back-jump (and none while it runs)", Jumps);
r.Add("back away: not with the macro stopped or combat off", Gated);
r.Add("back away: outside the radius (Ring Range widens it), or an object without a position: no jump", NotThese);
r.Add("back away: RynthAi alone ignores the Empyrean Handler's ring line (RynthILT's now)", HandlerLineIgnored);
}
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 bool Busy;
public Rig(float dangerYards, bool place = true)
{
FakeHost.Reset();
FakeHost.Names[Player] = "Evader";
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.Names[Danger] = "Empyrean Handler";
if (place) FakeHost.Positions[Danger] = (Lb | 0x1C, 96f, 96f + dangerYards, 0f);
FakeHost.ItemTypes[Danger] = 0x10;
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, new[] { Danger });
S.IsMacroRunning = true;
Combat = new CombatManager(host, S, cache);
Combat.SetPlayerId(Player);
Combat.ScanNearbyTargets();
Combat.RequestBackJump = (h, ms) => { Jumps++; Heading = h; Busy = true; return true; };
Combat.JumpBusy = () => Busy;
}
public int Ask(double radius = 12, int holdMs = 750) => Combat.BackAwayFrom(unchecked((int)Danger), radius, holdMs, "test");
}
private static void Jumps()
{
var rig = new Rig(dangerYards: 5);
Check.Eq(rig.Ask(), RynthAiHub.BackAwayStarted, "5 yards inside 12: started");
Check.Eq(rig.Jumps, 1, "one back-jump");
Check.True(rig.Combat.BackAwayActive, "combat holds while it runs");
Check.Eq(rig.Ask(), RynthAiHub.BackAwayNotNow, "a second request while backing away: not now");
Check.Eq(rig.Jumps, 1, "still one jump");
var refused = new Rig(5);
refused.Combat.RequestBackJump = (_, _) => false;
Check.Eq(refused.Ask(), RynthAiHub.BackAwayJumpRefused, "the jumper refused: said so");
Check.False(refused.Combat.BackAwayActive, "and combat isn't held");
}
private static void Gated()
{
var stopped = new Rig(5);
stopped.S.IsMacroRunning = false;
Check.Eq(stopped.Ask(), RynthAiHub.BackAwayNotNow, "macro stopped: not now");
Check.Eq(stopped.Jumps, 0, "no jump");
var noCombat = new Rig(5);
noCombat.S.EnableCombat = false;
Check.Eq(noCombat.Ask(), RynthAiHub.BackAwayNotNow, "combat off: not now");
Check.Eq(noCombat.Jumps, 0, "no jump");
}
private static void NotThese()
{
var far = new Rig(30);
Check.Eq(far.Ask(), RynthAiHub.BackAwayOutside, "30 yards away is outside 12");
Check.Eq(far.Jumps, 0, "no jump");
far.S.RingRange = 40;
Check.Eq(far.Ask(), RynthAiHub.BackAwayStarted, "Ring Range 40 widens the radius: 30 yards is inside");
var unknown = new Rig(5, place: false);
Check.Eq(unknown.Ask(), RynthAiHub.BackAwayUnknownObject, "no position for the object");
Check.Eq(unknown.Jumps, 0, "no jump");
}
private static void HandlerLineIgnored()
{
var rig = new Rig(5);
rig.Combat.HandleChatForDamage(RingLine, 0x0C);
rig.Combat.HandleChatForDebuffs(RingLine);
Check.Eq(rig.Jumps, 0, "the ring line alone does nothing in RynthAi (no server plugin asked)");
Check.False(rig.Combat.BackAwayActive, "and combat isn't held");
Check.True(new LegacyUiSettings().HandlerRingEvade, "the old profile field still loads (on by default; unused, for RynthILT's import)");
}
}

View file

@ -0,0 +1,94 @@
using System;
using RynthCore.Plugin.RynthAi;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-10-20: the Monsters tab's debuffs (custom ones too) were cast once per target and never
// again, so a long fight with a high-HP monster ran on without them once they wore off. A
// landed debuff is now timed by its spell's duration and cast again just before the end.
internal static class DebuffRenewTests
{
private const int Mob = 0x7A001234, Other = 0x7A005678;
public static void Register(Runner r)
{
r.Add("debuff renewal: spell durations come from the spell data (Imperil I 60 s, Incantation 300 s)", Durations);
r.Add("debuff renewal: a landed debuff is due again just before it wears off", RenewsBeforeEnd);
r.Add("debuff renewal: no duration casts once per target; three failures give up; a target switch keeps timers", OnceAndFailures);
r.Add("debuff renewal: a monster that goes takes its timers with it", ForgetTarget);
}
private static void Durations()
{
Check.Eq(SpellDatabase.DurationSeconds(SpellDatabase.GetIdByName("Imperil Other I")), 60, "Imperil Other I lasts 60 s");
Check.Eq(SpellDatabase.DurationSeconds(SpellDatabase.GetIdByName("Incantation of Imperil Other")), 300, "Incantation of Imperil Other 300 s");
Check.Eq(SpellDatabase.DurationSeconds(SpellDatabase.GetIdByName("Corrosion VII")), 16, "a damage-over-time debuff (Corrosion VII) 16 s");
Check.Eq(SpellDatabase.DurationSeconds(SpellDatabase.GetIdByName("Lifestone Recall")), 0, "a recall has none");
Check.Eq(SpellDatabase.DurationSeconds(-1), 0, "an unknown id has none");
}
private static void RenewsBeforeEnd()
{
var t = new DebuffTimers();
var now = new DateTime(2026, 10, 20, 20, 0, 0);
Check.False(t.IsOn(Mob, "Imperil", now), "nothing cast yet: due");
t.Landed(Mob, "Imperil", 240, now);
Check.True(t.IsOn(Mob, "Imperil", now.AddSeconds(200)), "on at 200 s of 240");
Check.True(t.IsOn(Mob, "Imperil", now.AddSeconds(234.9)), "still on 5 s before the end");
Check.False(t.IsOn(Mob, "Imperil", now.AddSeconds(235)), "due 5 s before it wears off");
Check.True(t.RenewAt(Mob, "Imperil") != null, "a renewal, not a first cast");
Check.False(t.IsOn(Other, "Imperil", now), "another monster has its own");
// A short damage-over-time debuff renews a fifth of its length early, not 5 s.
t.Landed(Mob, "Custom:Corrosion", 16, now);
Check.True(t.IsOn(Mob, "Custom:Corrosion", now.AddSeconds(12.7)), "Corrosion on at 12.7 s");
Check.False(t.IsOn(Mob, "Custom:Corrosion", now.AddSeconds(12.8)), "and due at 12.8 s of 16");
// The renewal lands: the timer starts over.
t.Landed(Mob, "Imperil", 240, now.AddSeconds(236));
Check.True(t.IsOn(Mob, "Imperil", now.AddSeconds(400)), "renewed at 236 s: on until 471 s");
Check.False(t.IsOn(Mob, "Imperil", now.AddSeconds(471)), "due again at 471 s");
}
private static void OnceAndFailures()
{
var t = new DebuffTimers();
var now = new DateTime(2026, 10, 20, 20, 0, 0);
t.Landed(Mob, "Custom:Odd", 0, now);
Check.True(t.IsOn(Mob, "Custom:Odd", now.AddHours(1)), "no duration: never again on this target");
Check.True(t.RenewAt(Mob, "Custom:Odd") == null, "and no timer");
Check.False(t.Failed(Mob, "Fester"), "first resist: try again");
Check.False(t.Failed(Mob, "Fester"), "second: again");
Check.False(t.IsOn(Mob, "Fester", now), "still due after two");
Check.True(t.Failed(Mob, "Fester"), "third: given up");
Check.True(t.IsOn(Mob, "Fester", now), "not cast at this target again");
t.Landed(Mob, "Yield", 240, now);
Check.False(t.Failed(Mob, "Yield"), "a renewal that fizzles once");
t.Landed(Mob, "Yield", 240, now);
Check.Eq(t.Failures(Mob, "Yield"), 0, "landing clears the count: each renewal gets three tries");
// Fighting something else and coming back: the given-up and once-only marks start over,
// the timers stay (the monster still has the debuff).
t.NewTarget(now.AddSeconds(10));
Check.False(t.IsOn(Mob, "Fester", now.AddSeconds(10)), "given up only for that engagement");
Check.False(t.IsOn(Mob, "Custom:Odd", now.AddSeconds(10)), "once-only too");
Check.True(t.IsOn(Mob, "Yield", now.AddSeconds(10)), "Yield's timer kept across the switch");
t.NewTarget(now.AddSeconds(300));
Check.Eq(t.TimerCount, 0, "a switch drops timers that fell due");
}
private static void ForgetTarget()
{
var t = new DebuffTimers();
var now = new DateTime(2026, 10, 20, 20, 0, 0);
t.Landed(Mob, "Imperil", 240, now);
t.Landed(Mob, "Vuln:Fire", 240, now);
t.Landed(Other, "Imperil", 240, now);
t.Forget(Mob);
Check.Eq(t.TimerCount, 1, "the gone monster's two timers dropped");
Check.True(t.IsOn(Other, "Imperil", now), "the other monster keeps its own");
}
}

View file

@ -42,8 +42,37 @@ internal static class DoorTests
r.Add("door: Only Doors On My Path - a door beside the way is left shut, one straight ahead is opened", PathOnlyAhead);
r.Add("door: Only Doors On My Path - on a route the door on the next leg goes, not a nearer one beside it", PathOnlyRoute);
r.Add("door: Only Doors On My Path - not a door past the range along the path, nor one behind the route's direction", PathOnlyRange);
r.Add("door: one created before its position was readable (just after a portal) is still found and opened", CreatedBeforePosition);
}
/// <summary>
/// A dungeon's objects arrive while the character is still in portal space, often before their
/// position reads: such a door was filed as inventory and never seen by the door scans (Dargoth
/// Hera, Infested Mine, 2026-10-19: Open Doors on, a closed door on the route, no use at all).
/// </summary>
private static void CreatedBeforePosition() => With(() =>
{
foreach (uint? itemType in new uint?[] { 0x80u, null }) // a readable item type, and none at all
{
var b = new Bot();
MoveDoor(Door, 40f, 0f); // the rig's door far out of range
FakeHost.Names[Door2] = "Door";
FakeHost.Bitfields[Door2] = BfDoor;
FakeHost.ObjectStates[Door2] = Closed;
if (itemType is uint t) FakeHost.ItemTypes[Door2] = t;
b.Cache.OnCreateObject(Door2); // no position yet
for (int i = 0; i < 12; i++) b.Cache.Tick(); // classified (and any retries spent) without one
Check.True(b.Cache.GetLandscapeObjects().Any(o => unchecked((uint)o.Id) == Door2),
$"a static door stays a world object without a position (item type {(itemType is null ? "unreadable" : "0x80")})");
Check.False(b.Cache.GetInventory().Any(o => unchecked((uint)o.Id) == Door2), "never filed as inventory");
FakeHost.Positions[Door2] = (Me0.Cell, Me0.X + 2f, Me0.Y, Me0.Z); // the position comes in
b.Tick();
b.Run(300);
Check.Eq(Uses(Door2), 1, "the door is used once it has a position");
}
});
// ── Rig ─────────────────────────────────────────────────────────────────
private sealed class Bot

View file

@ -41,6 +41,7 @@ internal static class ExpressionTests
r.Add("expr: control flow (iif, if, ifthen, exec) is lazy", ControlFlow);
r.Add("expr: delayexec fires on the pump when due, in order", DelayExec);
r.Add("expr: stopwatches", Stopwatches);
r.Add("expr: ub-IT's remaining functions answer (no-equivalent ones with ub-IT's empty values)", UbCompatFunctions);
r.Add("expr: object type, options and unknown functions", TypesOptionsUnknown);
r.Add("expr: RynthAi settings and meta state from expressions", SettingsAndState);
r.Add("expr: character properties, skills, vitals through the host", CharacterFunctions);
@ -516,10 +517,14 @@ internal static class ExpressionTests
var e = Engine();
long now = 5_000;
e.TickMs = () => now;
// ub-IT: delayexec returns its id (1, 2, ...), which clearexec takes.
Is(e, "delayexec[1000, `setvar[x, first]`]", "1");
Is(e, "delayexec[1000, `setvar[x, second]`]", "1");
Is(e, "delayexec[-50, `setvar[neg, 1]`]", "1");
Is(e, "delayexec[soon, `setvar[bad, 1]`]", "1");
Is(e, "delayexec[1000, `setvar[x, second]`]", "2");
Is(e, "delayexec[-50, `setvar[neg, 1]`]", "3");
Is(e, "delayexec[soon, `setvar[bad, 1]`]", "4");
Is(e, "delayexec[1000, `setvar[cancelled, 1]`]", "5");
Is(e, "clearexec[5]", "1");
Is(e, "clearexec[5]", "0"); // already gone
e.PumpDelayedExecs();
Is(e, "getvar[neg]", "1"); // negative delay: next pump
Is(e, "getvar[bad]", "1"); // unreadable delay: next pump
@ -530,16 +535,76 @@ internal static class ExpressionTests
now += 1;
e.PumpDelayedExecs();
Is(e, "getvar[x]", "second"); // both fired, in the order scheduled
Is(e, "testvar[cancelled]", "0"); // the cleared one never ran
// A delayexec scheduled by a firing one waits for a later pump.
// (\` is an escaped backtick inside a backtick string.)
Is(e, "delayexec[0, `delayexec[0, \\`setvar[chain, 1]\\`]`]", "1");
Is(e, "delayexec[0, `delayexec[0, \\`setvar[chain, 1]\\`]`]", "6");
e.PumpDelayedExecs();
Is(e, "testvar[chain]", "0");
e.PumpDelayedExecs();
Is(e, "getvar[chain]", "1");
}
private static void UbCompatFunctions()
{
FakeHost.Reset();
var settings = new LegacyUiSettings();
var e = Engine(FakeHost.Create(), settings);
// enlightenmentmaterials: levels 6-150 cost (level - 5) tokens; 1-5 and 151+ none.
Is(e, "enlightenmentmaterials[0, 10]", "15"); // 1+2+3+4+5
Is(e, "enlightenmentmaterials[149, 151]", "145"); // only 150 costs tokens
Is(e, "enlightenmentmaterials[160, 165]", "0");
Is(e, "enlightenmentmaterials[10, 5]", "0");
// Macro state, casting, quests.
settings.IsMacroRunning = true;
Is(e, "vtmacroenabled[]", "1");
settings.IsMacroRunning = false;
Is(e, "vtmacroenabled[]", "0");
Is(e, "iscasting[]", "0");
Is(e, "canrefreshquests[]", "1"); // no tracker: nothing throttles it
Is(e, "isrefreshingquestbonuses[]", "0");
Is(e, "getcooldownexpiration[515]", "0");
// Corpses opened by this character come from the plugin's hook.
e.CorpseOpenedByMe = id => id == 0x50000123;
Is(e, "hascorpsebeenopenedbyme[0x50000123]", "1");
Is(e, "hascorpsebeenopenedbyme[0x50000124]", "0");
Is(e, "getcorpsesunopenedbyme[]", "[]"); // no cache, no corpses
// Unknown or unreadable objects: ub-IT's -1 / 0.
Is(e, "wobjectgethealthvalue[0]", "-1");
Is(e, "actiontrymove[0, 0]", "0");
Is(e, "actiontrysplit[0, 5]", "0");
Is(e, "actiontrydrop[0x50000123]", "0");
// spelldata of an unknown spell is an empty dictionary.
Is(e, "dictsize[spelldata[999999]]", "0");
// XP meter: starts at zero.
Is(e, "xpreset[]", "1");
Is(e, "xptotal[]", "0");
Is(e, "lumtotal[]", "0");
Is(e, "xpavg[]", "0");
Check.True(e.Evaluate("xpmeter[]").Contains("XP/hr"), "xpmeter[] is the meter text");
// No RynthAi equivalent: they answer so the expression keeps going.
Is(e, "statushud[kills, 5]", "1");
Is(e, "statushudcolored[kills, 5, red]", "1");
Is(e, "netclients[]", "[]");
Is(e, "getcharacterindex[Bob]", "-1");
Is(e, "setnextlogin[Bob]", "0");
Is(e, "clearnextlogin[]", "1");
Is(e, "uiviewexists[myview]", "0");
Is(e, "uiviewvisible[myview]", "0");
Is(e, "statushud[a, 1] && 7", "1"); // used inside a larger expression
// A real typo is still an unknown function.
Is(e, "nosuchfunctionatall[]", "");
}
private static void Stopwatches()
{
var e = Engine();

View file

@ -1,7 +1,9 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginCore;
@ -27,6 +29,11 @@ internal static class GiveTests
r.Add("give: /ub give with a count hands over that many", UbGiveCount);
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: a meta's /ub give hands over every match too (it used to take /mt give's one)", MetaUbGivesAll);
r.Add("give: give-all never hands over RynthAi's own items, attuned or equipped ones", GiveAllSkipsProtected);
r.Add("give: a running meta's give-all also keeps what the loot profile keeps; a typed one does not", GiveAllLootKeepOnlyForMeta);
r.Add("give: give-all logs every stack it queues and caps one command at 500", GiveAllLogsAndCaps);
r.Add("give: a delayed /ub give keeps the standing of the line that queued it", DelayedGiveKeepsStanding);
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);
@ -98,6 +105,8 @@ internal static class GiveTests
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public object? Call(string m, params object?[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
public int LogWith(string text) => FakeHost.Logs.Count(l => l.Contains(text, StringComparison.Ordinal));
public int ChatWith(string text) => FakeHost.Chat.Count(c => c.Contains(text, StringComparison.Ordinal));
/// <summary>Runs the chat command, then drains the give queue.</summary>
public void Run(string command)
@ -167,6 +176,134 @@ internal static class GiveTests
Check.False(w.GivenItems.Contains(WornMote), "and never the worn one");
}
private static void MetaUbGivesAll()
{
var w = new World();
w.S.IsMacroRunning = true;
w.S.EnableMeta = true;
w.Call("HandleMetaChatCommand", "/ub give Mana Mote to Town Crier");
for (int i = 0; i < 20; i++) w.Call("DrainGiveQueue");
Check.Eq(FakeHost.Gives.Count, 3, "all three carried Mana Motes, as typed");
Check.False(FakeHost.Gives.Any(g => g.Item == WornMote), "and never the worn one");
}
private static void GiveAllSkipsProtected()
{
var w = new World();
// Mote2 is on the Weapons list, Mote3 on the Consumables list: RynthAi is using them.
w.S.ItemRules.Add(new ItemRule { Id = unchecked((int)Mote2), Name = "Mana Mote" });
w.S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Mote3), Name = "Mana Mote" });
w.Run("/ub give Mana Mote to Town Crier");
Check.Eq(FakeHost.Gives.Count, 1, "only the unprotected mote goes");
Check.Eq(FakeHost.Gives[0].Item, Mote1, "that one");
Check.Eq(w.LogWith("skipped 0x80281102 'Mana Mote': on RynthAi's Weapons list"), 1, "the Weapons-list skip is logged");
Check.Eq(w.LogWith("skipped 0x80281103 'Mana Mote': on RynthAi's Consumables list"), 1, "and the Consumables-list one");
Check.True(w.ChatWith("2 protected stack(s) skipped") == 1, "and the summary counts them");
// A monster rule's weapon is protected too.
var w2 = new World();
w2.S.MonsterRules.Add(new MonsterRule { Name = "Drudge", WeaponId = unchecked((int)Mote1), OffhandId = unchecked((int)Mote2) });
w2.Run("/ub give Mana Mote to Town Crier");
Check.True(FakeHost.Gives.Count == 1 && FakeHost.Gives[0].Item == Mote3, "a monster rule's weapon and off hand stay");
// An attuned item can't be given, and isn't tried.
var w3 = new World();
foreach (uint id in new[] { Mote1, Mote2, Mote3 }) FakeHost.Ints[(id, 114u)] = 1;
w3.Run("/ub give Mana Mote to Town Crier");
Check.Eq(FakeHost.Gives.Count, 0, "attuned motes are not given");
Check.True(w3.ChatWith("Nothing to give") == 1, "and it says why nothing was queued");
}
private static string KeepEverythingProfile()
{
string path = Path.Combine(Program.TempRoot, "give-keep-all.json");
var p = new LootProfile { Name = "keep all" };
p.Rules.Add(new LootRule { Name = "All", Action = LootAction.Keep });
p.Save(path);
return path;
}
private static void GiveAllLootKeepOnlyForMeta()
{
// Typed: the user asked for it; only the always-on protections apply.
var typed = new World();
typed.S.CurrentLootPath = KeepEverythingProfile();
typed.Run("/ub give Mana Mote to Town Crier");
Check.Eq(FakeHost.Gives.Count, 3, "typed /ub give hands over what the loot profile keeps");
// From a running meta: what the loot profile keeps stays.
var meta = new World();
meta.S.CurrentLootPath = KeepEverythingProfile();
meta.S.IsMacroRunning = true;
meta.S.EnableMeta = true;
meta.Call("HandleMetaChatCommand", "/ub give Mana Mote to Town Crier");
for (int i = 0; i < 20; i++) meta.Call("DrainGiveQueue");
Check.Eq(FakeHost.Gives.Count, 0, "a meta's /ub give leaves what the loot profile keeps");
Check.Eq(meta.LogWith("kept by the loot profile"), 3, "each skip is logged");
Check.True(meta.ChatWith("Nothing to give") == 1, "and said");
// The same meta with the macro stopped is not a running meta: the typed rules apply.
var stopped = new World();
stopped.S.CurrentLootPath = KeepEverythingProfile();
stopped.S.IsMacroRunning = false;
stopped.Call("HandleMetaChatCommand", "/ub give Mana Mote to Town Crier");
for (int i = 0; i < 20; i++) stopped.Call("DrainGiveQueue");
Check.Eq(FakeHost.Gives.Count, 3, "without a running meta it is a plain give");
}
private static void GiveAllLogsAndCaps()
{
var w = new World();
// 520 carried pebbles: more than one command may queue.
const int Pebbles = 520;
uint first = 0x80290000;
for (int i = 0; i < Pebbles; i++)
{
uint id = first + (uint)i;
FakeHost.Names[id] = "Pebble";
FakeHost.Containers[id] = Player;
FakeHost.ItemTypes[id] = 0x80;
}
for (int i = 0; i < Pebbles; i++) w.Cache.OnCreateObject(first + (uint)i);
for (int i = 0; i < 6; i++) w.Cache.Tick(); // the cache classifies 250 objects a tick
w.Call("HandleUbCommand", "/ub give Pebble to Town Crier");
var queue = (System.Collections.ICollection)typeof(RynthAiPlugin).GetField("_pendingGives", Any)!.GetValue(w.P)!;
Check.Eq(queue.Count, RynthAiPlugin.MaxGiveAllPerCommand, "one command queues at most 500");
Check.Eq(w.LogWith("[Give] queued 0x"), RynthAiPlugin.MaxGiveAllPerCommand, "one log line per stack queued");
Check.Eq(w.LogWith("the cap is 500"), 1, "the cap is logged");
Check.True(w.ChatWith("capped at 500") == 1, "and said in chat");
// Below the cap nothing is cut.
var small = new World();
small.Call("HandleUbCommand", "/ub give Mana Mote to Town Crier");
var q2 = (System.Collections.ICollection)typeof(RynthAiPlugin).GetField("_pendingGives", Any)!.GetValue(small.P)!;
Check.Eq(q2.Count, 3, "three motes, three queued");
Check.Eq(small.LogWith("the cap is"), 0, "no cap line");
}
private static void DelayedGiveKeepsStanding()
{
// A running meta that queues "/ub delay 0 /ub give ..." gives as a running meta when it fires,
// so the loot profile's Keep rules still protect; a typed delay does not.
var meta = new World();
meta.S.CurrentLootPath = KeepEverythingProfile();
meta.S.IsMacroRunning = true;
meta.S.EnableMeta = true;
meta.Call("HandleMetaChatCommand", "/ub delay 0 /ub give Mana Mote to Town Crier");
meta.Call("TickDelayedCommands");
for (int i = 0; i < 20; i++) meta.Call("DrainGiveQueue");
Check.Eq(FakeHost.Gives.Count, 0, "the delayed line still counts as the meta's");
var typed = new World();
typed.S.CurrentLootPath = KeepEverythingProfile();
typed.S.IsMacroRunning = true;
typed.S.EnableMeta = true;
typed.Call("HandleUbCommand", "/ub delay 0 /ub give Mana Mote to Town Crier");
typed.Call("TickDelayedCommands");
for (int i = 0; i < 20; i++) typed.Call("DrainGiveQueue");
Check.Eq(FakeHost.Gives.Count, 3, "a typed delay is a typed give");
}
private static void UbGivePartial()
{
var w = new World();

View file

@ -1,39 +0,0 @@
using RynthCore.Plugin.RynthAi.MiniRemote;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// RynthAi's lookup of RynthILT's "RynthILT.Hub" table (MiniRemote/IltClient.Tick). Until
// 0.5.60 the "never looked" sentinel was long.MinValue, "now - long.MinValue" overflowed to a
// negative number, the recheck gate always said "not due", and RynthAi never found RynthILT:
// no ILT tabs, sections or feature bits in the Mini Remote on Infinite Leaftide.
internal static class IltClientLookupTests
{
public static void Register(Runner r)
{
r.Add("ILT client: the first Tick (and the first after Reset) looks RynthILT up", FirstLook);
r.Add("ILT client: a live table is kept until the recheck interval", LiveTableKept);
r.Add("ILT client: no table retries every interval; a shut-down table at once", RetryRules);
}
private static void FirstLook()
{
// Any clock value, including the large tick counts of a long-running PC.
foreach (long now in new[] { 0L, 1_000L, 5_000_000L, long.MaxValue / 2 })
Check.True(IltClient.LookupDue(checkedOnce: false, checkedAt: 0, now, haveTable: false, tableLive: false),
$"never looked: due at now={now}");
}
private static void LiveTableKept()
{
Check.False(IltClient.LookupDue(true, checkedAt: 10_000, now: 11_000, haveTable: true, tableLive: true), "live table within the interval");
Check.True(IltClient.LookupDue(true, checkedAt: 10_000, now: 13_000, haveTable: true, tableLive: true), "live table after the interval");
}
private static void RetryRules()
{
Check.False(IltClient.LookupDue(true, checkedAt: 10_000, now: 12_999, haveTable: false, tableLive: false), "no table: waits the interval");
Check.True(IltClient.LookupDue(true, checkedAt: 10_000, now: 13_000, haveTable: false, tableLive: false), "no table: looks again after it");
Check.True(IltClient.LookupDue(true, checkedAt: 10_000, now: 10_001, haveTable: true, tableLive: false), "Version 0 (RynthILT shut down): looks again at once");
}
}

View file

@ -28,6 +28,7 @@ internal static class ManaStoneChoiceTests
r.Add("mana charges: refill gear even when ManaStone rules name only other stones", ChargesIgnoreStoneRules);
r.Add("mana stones: the server's 'low on Mana' refills gear whose read is stale-high", ServerLowRefills);
r.Add("mana stones: worn gear is identified again, so a stale-high read follows the gear", GearReadRefreshed);
r.Add("mana stones: worn means worn per the tracker - a packed item with a stale wield record takes no appraisals, gear it says is worn gets refilled", WornPerTracker);
r.Add("mana charges: overnight idle, the gear never runs dry (re-identify)", () => Overnight(identify: true));
r.Add("mana charges: overnight idle, the gear never runs dry (server warnings only)", () => Overnight(identify: false));
r.Add("mana tapping: one item at a time - the stone first, then one item, drained before the next", OneTapItemAtATime);
@ -140,6 +141,34 @@ internal static class ManaStoneChoiceTests
Check.Eq(rig.OnPlayer.Count, 2, "full: back to the reads (90%)");
}
/// <summary>
/// The engine's equipment tracker decides what is worn. A robe moved to the pack keeps its old wield
/// record: it used to count as worn and take the pass's appraisal ("worn=41" for 20 worn, 2026-10-20).
/// A cloak whose own wield record reads 0 but the tracker says is worn is gear like any other.
/// </summary>
private static void WornPerTracker()
{
const uint Robe = 0x80400040, Cloak = 0x80400041;
using var rig = new Rig(tapping: false, new (uint, int?)[] { (ChargeA, 1000) }, stoneName: ManaCharge, maceMana: 4500,
before: ids =>
{
FakeHost.Names[Robe] = "Old Robe";
FakeHost.Containers[Robe] = Player; // in the pack...
FakeHost.Ints[(Robe, WieldedSlotKey)] = 0x200; // ...with a stale wield record, mana unread
FakeHost.Names[Cloak] = "Cloak";
FakeHost.Wielders[Cloak] = Player;
FakeHost.Ints[(Cloak, MaxManaKey)] = 1000;
FakeHost.Ints[(Cloak, CurManaKey)] = 100; // 10%: needs a refill
ids.Add(Robe); ids.Add(Cloak);
FakeHost.EquippedCalls = true; // the tracker: mace and cloak are worn
FakeHost.Equipped[Mace] = 0x100000;
FakeHost.Equipped[Cloak] = 0x8000000;
});
rig.Run(3000);
Check.Eq(FakeHost.IdRequests.Count(i => i == Robe), 0, "no appraisal spent on the packed robe");
Check.Eq(rig.OnPlayer.Count, 1, "the cloak the tracker says is worn (10%) gets the charge");
}
private static void GearReadRefreshed()
{
using var rig = new Rig(tapping: false, new (uint, int?)[] { (ChargeA, 1000) }, stoneName: ManaCharge, maceMana: 4500);
@ -229,7 +258,7 @@ internal static class ManaStoneChoiceTests
/// <param name="identify">The engine can identify objects (RequestId).</param>
public Rig(bool tapping, (uint Id, int? Mana)[] stones, bool ringToDrain = false,
string stoneName = "Moderate Mana Stone", int maceMana = 0, bool identify = true,
bool ringArrived = true, bool contents = false)
bool ringArrived = true, bool contents = false, Action<List<uint>>? before = null)
{
FakeHost.Reset();
FakeHost.UseOnCalls = true;
@ -260,6 +289,7 @@ internal static class ManaStoneChoiceTests
ids.Add(Ring);
}
before?.Invoke(ids); // a test's own objects and host options, before the host exists
var host = FakeHost.Create(Player);
C = FakeHost.MakeCache(host, Player, ids);
S = new LegacyUiSettings { EnableManaTapping = tapping, ManaTapMinMana = 100 };

View file

@ -0,0 +1,258 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.PluginCore;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Opt-in audit (RYNTH_META_AUDIT=<folder of .met files>): what each meta asks of RynthAi - its chat
// commands through the real /vt /mt /ub dispatchers, its expression functions through the engine,
// its VTank options against the option map - and a report of what isn't supported.
internal static class MetaAuditTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
string? dir = Environment.GetEnvironmentVariable("RYNTH_META_AUDIT");
if (!string.IsNullOrEmpty(dir) && Directory.Exists(dir)) r.Add("audit: sample metas (RYNTH_META_AUDIT)", () => Run(dir));
}
private sealed class Found
{
public readonly SortedDictionary<string, SortedSet<string>> Commands = new(StringComparer.OrdinalIgnoreCase);
public readonly SortedDictionary<string, SortedSet<string>> Functions = new(StringComparer.OrdinalIgnoreCase);
public readonly SortedDictionary<string, SortedSet<string>> Options = new(StringComparer.OrdinalIgnoreCase);
public readonly SortedDictionary<string, SortedSet<string>> Kinds = new(StringComparer.OrdinalIgnoreCase);
public readonly SortedDictionary<string, SortedSet<string>> States = new(StringComparer.OrdinalIgnoreCase);
public void Add(SortedDictionary<string, SortedSet<string>> d, string key, string meta)
{
if (!d.TryGetValue(key, out var s)) d[key] = s = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
s.Add(meta);
}
}
private static readonly Regex FnRx = new(@"(?<![\$@&\w])([A-Za-z_][A-Za-z0-9_]*)\[", RegexOptions.CultureInvariant);
private static readonly Regex CmdInExprRx = new(@"/(vt|mt|ub|ra)\s+[A-Za-z0-9_]+(?:\s+[A-Za-z0-9_]+)?", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex OptFnRx = new(@"\b(vtsetsetting|vtgetsetting|vtankgetsetting)\[\s*`?([A-Za-z0-9_\-]+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static void Run(string dir)
{
var f = new Found();
var report = new StringBuilder();
var definedStates = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);
foreach (string path in Directory.GetFiles(dir, "*.met").OrderBy(p => p, StringComparer.OrdinalIgnoreCase))
{
string meta = Path.GetFileName(path);
LoadedMeta m = MetFileParser.Load(path);
report.AppendLine($"## {meta}: {m.Rules.Count} rules, {m.EmbeddedNavs.Count} navs" + (m.Warnings.Count > 0 ? ", warnings: " + string.Join(" | ", m.Warnings) : ""));
var states = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
definedStates[meta] = states;
foreach (MetaRule rule in m.Rules) { states.Add(rule.State); Walk(rule, meta, f); }
}
// Chat commands through the dispatchers.
var w = new PluginWorld();
report.AppendLine("\n# Chat commands");
foreach (var (cmd, metas) in f.Commands)
report.AppendLine($" [{Classify(cmd, w)}] {cmd} <- {string.Join(", ", metas)}");
// Expression functions through the engine.
report.AppendLine("\n# Expression functions not known to RynthAi");
FakeHost.Reset();
var host = FakeHost.Create();
foreach (var (fn, metas) in f.Functions)
{
var e = new ExpressionEngine(host);
int logs = FakeHost.Logs.Count;
try { e.Evaluate(fn + "[]"); } catch { }
bool unknown = FakeHost.Logs.Skip(logs).Any(l => l.Contains("unknown expression function '" + fn, StringComparison.OrdinalIgnoreCase));
if (unknown) report.AppendLine($" {fn} <- {string.Join(", ", metas)}");
}
report.AppendLine(" (all functions used: " + string.Join(", ", f.Functions.Keys) + ")");
// VTank options against the option map / settings map / special options.
report.AppendLine("\n# VTank options");
var mm = new MetaManager(new LegacyUiSettings(), host, new PlayerVitalsCache());
var map = (Dictionary<string, string>)typeof(MetaManager).GetField("VtOptionMap", Any)!.GetValue(null)!;
var special = typeof(MetaManager).GetMethod("IsSpecialVtOption", Any)!;
var settings = mm.Expressions.BuildSettingsMapPublic();
var settingsCi = new HashSet<string>(settings.Keys, StringComparer.OrdinalIgnoreCase);
foreach (var (opt, metas) in f.Options)
{
bool known = map.ContainsKey(opt) || settingsCi.Contains(opt) || (bool)special.Invoke(null, new object[] { opt })!;
report.AppendLine($" [{(known ? "ok" : "NOT MAPPED")}] {opt}{(map.TryGetValue(opt, out string? ra) ? " -> " + ra : "")} <- {string.Join(", ", metas)}");
}
// The same VTank values set two ways: '/vt opt set' and the vtsetsetting[] expression.
report.AppendLine("\n# /vt opt set vs vtsetsetting[] (VTank units in, RynthAi setting out)");
foreach (var (opt, val) in new[] { ("AttackDistance", "0.025"), ("ApproachDistance", "0.0208333"), ("NavCloseStopRange", "0.00625"), ("PetCustomRange", "0.0625"), ("LootOnlyRareCorpses", "1") })
{
var s1 = new LegacyUiSettings(); var m1 = new MetaManager(s1, host, new PlayerVitalsCache());
m1.TryHandleVtCommand($"/vt opt set {opt} {val}");
var s2 = new LegacyUiSettings(); var m2 = new MetaManager(s2, host, new PlayerVitalsCache());
m2.Expressions.Evaluate($"vtsetsetting[{opt},`{val}`]");
string Read(MetaManager mm2) => (string?)typeof(MetaManager).GetMethod("GetVtOption", Any)!.Invoke(mm2, new object[] { opt }) ?? "(null)";
report.AppendLine($" {opt}={val}: /vt opt set -> {Read(m1)} vtsetsetting -> {Read(m2)} (MonsterRange {s1.MonsterRange} vs {s2.MonsterRange}, ApproachRange {s1.ApproachRange} vs {s2.ApproachRange}, CustomPetRange {s1.CustomPetRange} vs {s2.CustomPetRange})");
}
report.AppendLine("\n# Rule kinds used");
foreach (var (k, metas) in f.Kinds) report.AppendLine($" {k} <- {string.Join(", ", metas)}");
report.AppendLine("\n# States set or called but not defined");
foreach (var (st, metas) in f.States)
foreach (string meta in metas)
if (definedStates.TryGetValue(meta, out var defined) && !defined.Contains(st)) report.AppendLine($" {meta}: '{st}'");
string outPath = Path.Combine(Path.GetTempPath(), "meta_audit.txt");
File.WriteAllText(outPath, report.ToString());
Console.WriteLine(" audit report: " + outPath);
Check.True(true, "audit ran");
}
private static void Walk(MetaRule r, string meta, Found f)
{
f.Add(f.Kinds, "if " + r.Condition, meta);
if (r.Condition == MetaConditionType.Expression) Expr(r.ConditionData, meta, f);
foreach (MetaRule c in r.Children) WalkCondition(c, meta, f);
Action(r, meta, f);
}
private static void WalkCondition(MetaRule c, string meta, Found f)
{
f.Add(f.Kinds, "if " + c.Condition, meta);
if (c.Condition == MetaConditionType.Expression) Expr(c.ConditionData, meta, f);
foreach (MetaRule cc in c.Children) WalkCondition(cc, meta, f);
}
private static void Action(MetaRule r, string meta, Found f)
{
f.Add(f.Kinds, "do " + r.Action, meta);
string d = r.ActionData ?? "";
switch (r.Action)
{
case MetaActionType.ChatCommand:
foreach (string line in d.Split('\n', StringSplitOptions.RemoveEmptyEntries))
{
string cmd = line.Trim();
f.Add(f.Commands, cmd, meta);
Match om = Regex.Match(cmd, @"^/vt\s+opt\s+(?:set|get)\s+(\S+)", RegexOptions.IgnoreCase);
if (om.Success) f.Add(f.Options, om.Groups[1].Value, meta);
}
break;
case MetaActionType.ExpressionAction:
case MetaActionType.ChatExpression:
Expr(d, meta, f);
break;
case MetaActionType.SetRAOption:
{ string[] p = d.Split(';', 2); f.Add(f.Options, p[0].Trim(), meta); if (p.Length > 1) Expr(p[1], meta, f); }
break;
case MetaActionType.GetRAOption:
{ string[] p = d.Split(';'); if (p.Length > 1) f.Add(f.Options, p[1].Trim(), meta); }
break;
case MetaActionType.SetMetaState:
case MetaActionType.CallMetaState:
f.Add(f.States, d.Split(';')[0].Trim(), meta);
if (r.CallReturnState.Length > 0) f.Add(f.States, r.CallReturnState, meta);
break;
}
foreach (MetaRule c in r.ActionChildren) Action(c, meta, f);
}
private static void Expr(string? text, string meta, Found f)
{
if (string.IsNullOrWhiteSpace(text)) return;
foreach (Match m in FnRx.Matches(text)) f.Add(f.Functions, m.Groups[1].Value.ToLowerInvariant(), meta);
string plain = text.Replace("\\/", "/").Replace("\\", "");
foreach (Match m in CmdInExprRx.Matches(plain)) f.Add(f.Commands, m.Value.Trim() + " (in an expression)", meta);
foreach (Match m in OptFnRx.Matches(text)) f.Add(f.Options, m.Groups[2].Value, meta);
Match setopt = Regex.Match(plain, @"/vt\s+opt\s+set\s+([A-Za-z0-9_]+)", RegexOptions.IgnoreCase);
if (setopt.Success) f.Add(f.Options, setopt.Groups[1].Value, meta);
}
/// <summary>A RynthAi plugin wired enough to run its /mt and /ub dispatchers, plus a meta manager for /vt.</summary>
private sealed class PluginWorld
{
public readonly RynthAiPlugin P = new();
public readonly MetaManager M;
public readonly HashSet<string> RaVerbs;
public PluginWorld()
{
FakeHost.Reset();
FakeHost.PluginCommandCalls = true;
FakeHost.Create(playerId: 0x50000F99);
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var s = new LegacyUiSettings();
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
Set("_dashboard", dash);
Set("_initialized", true);
Set("_loginComplete", true);
M = new MetaManager(s, FakeHost.Create(playerId: 0x50000F99), new PlayerVitalsCache());
M.SetRaCommandHandler(_ => { });
RaVerbs = ReadRaVerbs();
}
private void Set(string n, object? v) => typeof(RynthAiPlugin).GetField(n, Any)!.SetValue(P, v);
public bool Meta(string cmd) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMetaChatCommand", Any)!.Invoke(P, new object[] { cmd })!;
/// <summary>The /ra verbs: the case labels of DispatchRaCommand's switch (unknown ones are ignored silently).</summary>
private static HashSet<string> ReadRaVerbs()
{
var verbs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
string? root = AppContext.BaseDirectory;
while (root != null && !Directory.Exists(Path.Combine(root, "Plugins"))) root = Path.GetDirectoryName(root);
if (root == null) return verbs;
string src = File.ReadAllText(Path.Combine(root, "Plugins", "RynthCore.Plugin.RynthAi", "RynthAiPlugin.cs"));
int a = src.IndexOf("private void DispatchRaCommand(", StringComparison.Ordinal);
int b = a >= 0 ? src.IndexOf("\n }\n", a, StringComparison.Ordinal) : -1;
string body = a >= 0 ? src.Substring(a, (b > a ? b : src.Length) - a) : "";
foreach (Match m in Regex.Matches(body, "case \"([a-z0-9_]+)\"")) verbs.Add(m.Groups[1].Value);
return verbs;
}
}
private static string Classify(string cmd, PluginWorld w)
{
// A command an expression builds: its arguments only exist at run time, so only the
// verb was captured; running it bare says nothing.
if (cmd.EndsWith("(in an expression)", StringComparison.Ordinal)) return "built at run time (verb only)";
string c = cmd.Trim();
if (!c.StartsWith("/") && !c.StartsWith("@")) return "say (plain chat)";
string[] parts = c.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string prefix = parts[0].ToLowerInvariant();
string verb = parts.Length > 1 ? parts[1].ToLowerInvariant() : "";
try
{
switch (prefix)
{
case "/vt":
return w.M.TryHandleVtCommand(c) ? "vt ok" : "VT NOT HANDLED";
case "/mt":
case "/ub":
int chat = FakeHost.Chat.Count;
bool ok = w.Meta(c);
bool noop = FakeHost.Chat.Skip(chat).Any(l => l.Contains("no RynthAi equivalent"));
if (prefix == "/ub" && (bool)typeof(RynthAiPlugin).GetMethod("IsUbRythaiCommand", Any)!.Invoke(null, new object[] { verb, parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2) : "" })!)
return "ub-Rythai";
return !ok ? prefix.ToUpperInvariant().TrimStart('/') + " NOT HANDLED" : noop ? "accepted no-op" : prefix.TrimStart('/') + " ok";
case "/ra":
return w.RaVerbs.Contains(verb) || verb.StartsWith("jump") ? "ra ok" : "RA verb not in DispatchRaCommand (may be a hotkey verb)";
default:
return "game/server";
}
}
catch (Exception ex) { return "THREW " + (ex.InnerException ?? ex).GetType().Name + ": " + (ex.InnerException ?? ex).Message; }
}
}

View file

@ -0,0 +1,146 @@
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.PluginCore;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// What the sample metas (meta samples: PistolPete, S_Bulb/Caul/Colo/CountPhainor/Cows/Deewain,
// Willow; audited 2026-10-18 with MetaAuditTests) needed that RynthAi didn't do.
internal static class MetaSampleCompatTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("meta samples: vtsetsetting[] takes VTank distances like /vt opt set (6 yd, not the 50 yd default)", VtSetSettingDistances);
r.Add("meta samples: the options they set map to RynthAi settings (pet range, blacklist, rebuff, auto attack power)", MappedOptions);
r.Add("meta samples: /vt deletemonster is accepted", DeleteMonster);
r.Add("meta samples: /ub close corpse closes the open corpse", UbCloseCorpse);
r.Add("meta samples: /ub <expression> is evaluated (the /ub bc vtsetmetastate[] broadcast)", UbExpression);
r.Add("meta samples: /mt face and /ub face take decimals and coordinates, and hold nav while turning", Face);
}
private static (LegacyUiSettings S, MetaManager M) Meta()
{
FakeHost.Reset();
var s = new LegacyUiSettings();
var m = new MetaManager(s, FakeHost.Create(), new PlayerVitalsCache());
m.SetRaCommandHandler(_ => { });
return (s, m);
}
private static void VtSetSettingDistances()
{
var (s, m) = Meta();
m.Expressions.Evaluate("vtsetsetting[AttackDistance,`0.025`]");
Check.Eq(s.MonsterRange, 6, "vtsetsetting AttackDistance 0.025 = 6 yd (was left at 50)");
m.Expressions.Evaluate("vtsetsetting[ApproachDistance,`0.0208333`]");
Check.Eq(s.ApproachRange, 5, "ApproachDistance 0.0208333 = 5 yd");
Check.Eq(m.Expressions.Evaluate("vtgetsetting[AttackDistance]"), "0.025", "vtgetsetting reads it back in VTank units");
m.TryHandleVtCommand("/vt opt set AttackDistance 0.2166");
Check.Eq(s.MonsterRange, 52, "/vt opt set the same way");
m.Expressions.Evaluate("vtsetsetting[IdlePeaceMode,`1`]");
Check.True(s.PeaceModeWhenIdle, "a bool through vtsetsetting");
m.Expressions.Evaluate("rasetsetting[MonsterRange,`7`]");
Check.Eq(s.MonsterRange, 7, "rasetsetting keeps RynthAi's own names and units");
}
private static void MappedOptions()
{
var (s, m) = Meta();
m.Expressions.Evaluate("vtsetsetting[PetCustomRange,`0.0625`]");
Check.Eq(s.CustomPetRange, 15, "PetCustomRange 0.0625 = 15 yd");
m.Expressions.Evaluate("vtsetsetting[BlacklistMonsterTimeoutSeconds,`45`]");
Check.Eq(s.BlacklistTimeoutSec, 45, "BlacklistMonsterTimeoutSeconds");
m.TryHandleVtCommand("/vt opt set rebufftimeremainingseconds 4500");
Check.Eq(s.RebuffSecondsRemaining, 4500, "rebufftimeremainingseconds (VTank's spelling)");
// AutoAttackPower: on = automatic (-1); off = the attack bar's value.
m.TryHandleVtCommand("/vt setattackbar .9");
m.Expressions.Evaluate("vtsetsetting[AutoAttackPower,`1`]");
Check.True(s.MeleeAttackPower == -1 && s.MissileAttackPower == -1, "AutoAttackPower on: automatic");
Check.Eq(m.Expressions.Evaluate("vtgetsetting[AutoAttackPower]"), "true", "reads back on");
m.TryHandleVtCommand("/vt opt set autoattackpower false");
Check.True(s.MeleeAttackPower == 90 && s.MissileAttackPower == 90, "AutoAttackPower off: the bar's 90%");
}
private static void DeleteMonster()
{
var (_, m) = Meta();
Check.True(m.TryHandleVtCommand("/vt deletemonster"), "/vt deletemonster handled (not sent to AC as unknown)");
}
private sealed class World
{
public readonly RynthAiPlugin P = new();
public World(bool closeCalls = true)
{
FakeHost.Reset();
FakeHost.CloseContainerCalls = closeCalls;
FakeHost.Create(playerId: 0x50000F31);
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, new LegacyUiSettings());
Set("_dashboard", dash);
Set("_initialized", true);
Set("_loginComplete", true);
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public bool Ub(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleUbCommand", Any)!.Invoke(P, new object[] { line })!;
public bool Mt(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMtCommand", Any)!.Invoke(P, new object[] { line })!;
}
private static void UbCloseCorpse()
{
var w = new World();
Check.True(w.Ub("/ub close corpse"), "/ub close corpse handled with nothing open");
Check.True(FakeHost.Chat.Any(c => c.Contains("No container is currently open")), "and says so, as ub-IT");
FakeHost.GroundContainer = 0x80F00001;
w.Ub("/ub close corpse");
Check.True(FakeHost.Closes.Contains(0x80F00001), "closes the open container");
Check.False(FakeHost.Chat.Any(c => c.Contains("Unrecognized")), "never 'Unrecognized /ub command'");
}
private static void UbExpression()
{
var w = new World();
Check.True(w.Ub("/ub vtsetmetastate[NavigatingToFlowerTwo]"), "/ub <expression> handled");
Check.False(w.Ub("/ub notaverb x"), "a plain unknown verb is still unknown");
}
private static void Face()
{
var w = new World();
// No jumper (not logged in fully): one plain turn.
Check.True(w.Mt("/mt face 135.5"), "/mt face 135.5 (decimal)");
Check.True(Math.Abs(FakeHost.HeadingDeg - 135.5f) < 0.01f, "turned to 135.5");
Check.True(w.Ub("/ub face 450"), "/ub face 450");
Check.True(Math.Abs(FakeHost.HeadingDeg - 90f) < 0.01f, "450 wraps to 90");
// A coordinate: from 10N 10E, 20N 10E is due north and 10N 20E due east.
FakeHost.SetNavPosition(10, 10);
Check.True(w.Mt("/mt face 20N, 10E"), "/mt face <coords>");
Check.True(FakeHost.HeadingDeg < 0.5f || FakeHost.HeadingDeg > 359.5f, "north is 0");
Check.True(w.Ub("/ub face 10N 20E"), "/ub face <coords> (no comma)");
Check.True(Math.Abs(FakeHost.HeadingDeg - 90f) < 0.5f, "east is 90");
Check.False(w.Mt("/mt face somewhere"), "not a heading or a coordinate: not handled");
// With the jumper: nav is held while turning and given back once the heading is reached.
var s = new LegacyUiSettings { EnableNavigation = true };
var jumper = new Jumper(FakeHost.Create(playerId: 0x50000F31), s, _ => { });
w.Set("_jumper", jumper);
w.Mt("/mt face 200");
Check.False(s.EnableNavigation, "nav held while turning");
System.Threading.Thread.Sleep(120);
jumper.Tick();
Check.True(s.EnableNavigation, "nav back once facing 200");
Check.False(jumper.IsBusy, "and the jumper is free");
}
}

View file

@ -45,6 +45,7 @@ internal static class MetaTests
r.Add("meta: expression condition fails closed on errors", ExpressionCondition);
r.Add("meta: need-to-buff with no buff manager, unknown condition types", NeedToBuffAndUnknown);
r.Add("meta action: chat commands, /ra, /vt and /mt", ChatCommands);
r.Add("meta action: the /vt verbs and options the metas use that were missing (2026-10-17)", VtPortedVerbs);
r.Add("meta action: SetMetaState, CallMetaState and ReturnFromCall", CallReturn);
r.Add("meta action: All runs every child in order", AllAction);
r.Add("meta action: embedded nav route", EmbeddedNav);
@ -915,6 +916,90 @@ internal static class MetaTests
Check.Eq(reversed.S.ActiveNavIndex, 2, "index mirrored");
}
// /vt verbs and options found in ub-IT and the metas on disk (universalremote.met, SASocietyTasks.met,
// FoundryIzexi.met, DerethExploration (1).met) that RynthAi didn't handle.
private static void VtPortedVerbs()
{
FakeHost.Reset();
FakeHost.TapJumpCalls = true; // the engine's tap jump, for /vt tapjump
var rig = new Rig(FakeHost.Create(), Player);
// /vt e toggles the macro. Straight to the /vt handler: a meta doesn't run with the macro off.
rig.S.IsMacroRunning = false;
Check.True(rig.M.TryHandleVtCommand("/vt e") && rig.Ra.Contains("/ra start"), "/vt e with the macro off starts it");
rig.S.IsMacroRunning = true;
Check.True(rig.M.TryHandleVtCommand("/vt e") && rig.Ra.Contains("/ra stop"), "/vt e with the macro on stops it");
// /vt jump heading shift holdms -> /ra jump[s] heading hold; /vt tapjump -> the engine's tap jump.
RunAction(rig, A.ChatCommand, "/vt jump 90 true 750");
Check.True(rig.Ra.Contains("/ra jumps 90 750"), "/vt jump 90 true 750 -> /ra jumps 90 750");
RunAction(rig, A.ChatCommand, "/vt jump 180 false 300");
Check.True(rig.Ra.Contains("/ra jump 180 300"), "shift false -> /ra jump");
int taps = FakeHost.TapJumps;
RunAction(rig, A.ChatCommand, "/vt tapjump");
Check.Eq(FakeHost.TapJumps, taps + 1, "/vt tapjump");
// Settings profiles go to /ra settings; other /vt settings verbs are still swallowed.
RunAction(rig, A.ChatCommand, "/vt settings savechar Banes");
Check.True(rig.Ra.Contains("/ra settings savechar Banes"), "/vt settings savechar");
RunAction(rig, A.ChatCommand, "/vt settings loadchar Base Profile");
Check.True(rig.Ra.Contains("/ra settings loadchar Base Profile"), "/vt settings loadchar keeps spaces");
// looting load = loot load; equipitemsfor -> /ra equipfor.
RunAction(rig, A.ChatCommand, "/vt looting load NoSuchProfile.utl");
Check.True(FakeHost.Chat.Any(c => c.Contains("Loot profile not found: NoSuchProfile.utl")), "/vt looting load is handled as loot load");
RunAction(rig, A.ChatCommand, "/vt equipitemsfor Pyre Skeleton");
Check.True(rig.Ra.Contains("/ra equipfor Pyre Skeleton"), "/vt equipitemsfor -> /ra equipfor");
// Distances: VTank landblock units (x240) -> yards; a value over 1 is already yards.
RunAction(rig, A.ChatCommand, "/vt opt set attackdistance .01666");
Check.Eq(rig.S.MonsterRange, 4, "attackdistance .01666 -> 4 yd (was dropped: an int setter refused the decimal)");
RunAction(rig, A.ChatCommand, "/vt opt set attackrange 0.04166");
Check.Eq(rig.S.MonsterRange, 10, "attackrange 0.04166 -> 10 yd");
RunAction(rig, A.ChatCommand, "/vt opt set approachdistance 0.0175");
Check.Eq(rig.S.ApproachRange, 4, "approachdistance 0.0175 -> 4 yd");
RunAction(rig, A.ChatCommand, "/vt opt set dooropenrange 0.005");
Check.Near(rig.S.OpenDoorRange, 1.2, 1e-3, "dooropenrange 0.005 -> 1.2 yd (was 0.005 yd)");
RunAction(rig, A.ChatCommand, "/vt opt set ringdistance 0.025");
Check.Eq(rig.S.RingRange, 6, "ringdistance 0.025 -> 6 yd");
RunAction(rig, A.ChatCommand, "/vt opt set corpseapproachrange-max 0.05");
Check.Near(rig.S.CorpseApproachRangeMax, 12, 1e-3, "corpseapproachrange-max 0.05 -> 12 yd");
RunAction(rig, A.ChatCommand, "/vt opt set minimumringtargets 3");
Check.Eq(rig.S.MinRingTargets, 3, "minimumringtargets");
RunAction(rig, A.ChatCommand, "/vt opt set attackdistance 25");
Check.Eq(rig.S.MonsterRange, 25, "a value over 1 is yards already");
// An option written as a verb (DerethExploration: /vt navclosestoprange 0.005).
RunAction(rig, A.ChatCommand, "/vt navclosestoprange 0.005");
Check.Near(rig.S.FollowNavMin, 1.2, 1e-3, "/vt navclosestoprange 0.005 -> nav point reach 1.2 yd");
RunAction(rig, A.ChatCommand, "/vt opt set navclosetoprange .00625");
Check.Near(rig.S.FollowNavMin, 1.5, 1e-3, "the misspelt navclosetoprange too");
// Options whose value means something else in RynthAi.
RunAction(rig, A.ChatCommand, "/vt opt set defaultmeleeattackheight 3");
Check.Eq(rig.S.MeleeAttackHeight, 2, "VTank height 3 (high) -> RynthAi 2");
RunAction(rig, A.ChatCommand, "/vt opt set defaultmeleeattackheight 2");
Check.Eq(rig.S.MeleeAttackHeight, 1, "VTank height 2 (medium) -> RynthAi 1");
rig.S.LootOwnership = 0;
RunAction(rig, A.ChatCommand, "/vt opt set lootfellowcorpses true");
Check.Eq(rig.S.LootOwnership, 1, "lootfellowcorpses -> fellowship kills");
RunAction(rig, A.ChatCommand, "/vt opt set lootallcorpses true");
Check.Eq(rig.S.LootOwnership, 2, "lootallcorpses -> all corpses");
RunAction(rig, A.ChatCommand, "/vt opt set lootallcorpses false");
Check.Eq(rig.S.LootOwnership, 0, "lootallcorpses false -> my kills");
RunAction(rig, A.ChatCommand, "/vt opt set usearcs 3");
Check.True(rig.S.UseArcs, "usearcs 3 -> on");
RunAction(rig, A.ChatCommand, "/vt opt set usearcs 0");
Check.False(rig.S.UseArcs, "usearcs 0 -> off");
RunAction(rig, A.ChatCommand, "/vt opt set minimumhealkitsuccesschance 55");
Check.Eq(rig.S.KitMinSuccessPct, 55, "minimumhealkitsuccesschance 55 %");
RunAction(rig, A.ChatCommand, "/vt opt set minimumhealkitsuccesschance 0.8");
Check.Eq(rig.S.KitMinSuccessPct, 80, "a fraction is scaled to a percent");
RunAction(rig, A.ChatCommand, "/vt opt set defaultmeleeattackheight 3");
RunAction(rig, A.ChatCommand, "/vt opt get defaultmeleeattackheight");
Check.True(FakeHost.Chat.Any(c => c.Contains("defaultmeleeattackheight = 3")), "read back in VTank's own 1-3");
}
private static void CallReturn()
{
var rig = new Rig(rules: new[]

View file

@ -21,9 +21,6 @@ internal static class MiniRemoteMoveTests
{
private const uint Player = 0x50000E01;
[System.Runtime.CompilerServices.UnsafeAccessor(System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = "_selectBreeding")]
private static extern ref bool SelectBreedingPending(PetsTab pets);
private const string LegacyHubJson = """
{
"Bank": { "Pyreals": 99 },
@ -38,9 +35,11 @@ internal static class MiniRemoteMoveTests
{
r.Add("mini remote: Pets / Quests settings come over from ilt-hub.json once, which is never rewritten", LegacyState);
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: /ra hub|quests|pets stay RynthAi's; quest windows point to RynthOracle; other hub verbs are a server plugin's", 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("pets: ACECustom's charms, capture, refill gate and Breeding come from the server plugin (none without it)", PetsFromServerPlugin);
r.Add("mini remote: the session report's tail and the menu's server come from the server plugin", RemoteTextsFromServerPlugin);
r.Add("vaulted dungeons: the master switch is RynthILT's; RynthAi mirrors it for the engine row (none without RynthILT)", 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);
}
@ -85,13 +84,16 @@ internal static class MiniRemoteMoveTests
Check.False(fresh.Pet.HealingEnabled, "no files at all: defaults");
}
private static MiniRemoteController NewController(string folder, out RynthCoreHost host, out LegacyUiSettings settings)
private static MiniRemoteController NewController(string folder, out RynthCoreHost host, out LegacyUiSettings settings, bool serverPlugin = false)
{
FakeHost.Reset();
FakeServerHub.Reset();
host = FakeHost.Create(Player);
var s = new LegacyUiSettings();
settings = s;
var c = new MiniRemoteController(host, Folder(folder), () => null, () => s, () => null, () => { }, new IltClient(host));
var client = new ServerHubClient(host);
if (serverPlugin) client.UseTableForTests(FakeServerHub.Table);
var c = new MiniRemoteController(host, Folder(folder), () => null, () => s, () => null, () => { }, client);
string? lastTab = null;
c.MiniRemoteCommand = mode => "[Mini Remote] remote " + mode;
c.MiniRemoteTabCommand = (tab, mode) => { lastTab = tab + ":" + mode; return "tab " + lastTab; };
@ -101,16 +103,18 @@ internal static class MiniRemoteMoveTests
private static void NoRynthIlt()
{
var c = NewController("noilt", out var host, out _);
var ilt = c.Ilt;
var ilt = c.ServerHub;
ilt.Tick();
Check.False(ilt.Loaded, "no RynthILT (no plugin interfaces on this host)");
Check.False(ilt.IsIltWorld, "so never an ILT world");
Check.False(ilt.ServerActive, "so never an ILT world");
Check.Eq(ilt.Feature(RynthIltHub.FeaturePetRefill), -1, "feature bits unknown");
Check.False(ilt.IsOff(RynthIltHub.FeatureQuests), "unknown is not off (/myquests still refreshes)");
Check.Eq(ilt.Tabs().Count, 0, "no ILT tabs");
Check.False(ilt.RenderSection(RynthIltHub.SectionQuestBonus), "no ILT sections");
Check.False(ilt.Command("hub bank"), "no ILT verbs taken");
Check.False(ilt.TryGetRates(out _, out _), "no ILT rates");
Check.Eq(ilt.Text(RynthIltHub.TextSessionReport), string.Empty, "no server rates in the session report");
Check.Eq(ilt.Text(RynthIltHub.TextServerId), string.Empty, "no server of a plugin's in the menu");
Check.Eq(ilt.Setting(RynthIltHub.SettingVaultedDungeons), -1, "no server setting offered");
Check.False(c.SkipLoginQuestRefresh, "the login /myquests refresh isn't skipped");
}
@ -128,19 +132,18 @@ internal static class MiniRemoteMoveTests
Check.True(FakeHost.Chat.Any(x => x.Contains("tab pets:show")), "same tab");
FakeHost.Chat.Clear();
// The Pets tab's Breeding sub-tab is RynthILT's (Infinite Leaftide only): without RynthILT there is none.
Check.False(c.Pets.BreedingOffered, "no Breeding sub-tab without RynthILT");
Check.Eq(c.Pets.SubTabs().Count, 0, "no Pets sub-tabs without a server plugin");
Check.True(c.HandleCommand("hub", new[] { "open", "breeding" }), "hub open breeding is answered");
Check.True(FakeHost.Chat.Any(x => x.Contains(IltClient.NotLoaded)), "it says RynthILT is needed");
Check.False(FakeHost.Chat.Any(x => x.Contains("tab pets:")), "and opens nothing");
Check.False(SelectBreedingPending(c.Pets), "no Breeding sub-tab request");
Check.True(c.Pets.PendingSubTab == null, "no sub-tab request");
FakeHost.Chat.Clear();
Check.True(c.HandleCommand("hub", new[] { "tab", "Breed" }), "hub tab breed (the dashboard)");
Check.False(FakeHost.Chat.Any(), "tab switches quietly");
Check.False(SelectBreedingPending(c.Pets), "still no Breeding sub-tab request without RynthILT");
Check.True(c.Pets.PendingSubTab == null, "still no sub-tab request without a server plugin");
FakeHost.Chat.Clear();
Check.True(c.HandleCommand("hub", new[] { "bank" }), "hub bank is handled (answered)");
Check.True(FakeHost.Chat.Any(x => x.Contains("RynthILT")), "it says the ILT verbs come with RynthILT");
Check.True(FakeHost.Chat.Any(x => x.Contains("/ra hub open pets|crafting [show|hide|toggle] /ra hub open breeding")), "and lists what RynthAi still has");
Check.True(FakeHost.Chat.Any(x => x.Contains("/ra hub open pets|crafting [show|hide|toggle]")), "with the help: what RynthAi has");
Check.False(FakeHost.Chat.Any(x => x.Contains("RynthILT") || x.Contains("Leaftide")), "and nothing about ILT (a retail world's answer)");
FakeHost.Chat.Clear();
// The Quests tab moved to RynthOracle (2026-10-13): its verbs and tab names say so.
Check.True(c.HandleCommand("hub", new[] { "open", "quests" }), "hub open quests is answered");
@ -152,21 +155,73 @@ internal static class MiniRemoteMoveTests
Check.True(c.HandleCommand("quests", Array.Empty<string>()), "quests (refresh) stays RynthAi's");
Check.True(FakeHost.Chat.Any(x => x.Contains("Quest tracker not ready")), "the meta tracker's refresh (none in this test)");
FakeHost.Chat.Clear();
Check.True(c.HandleCommand("guardian", new[] { "handin" }), "guardian is answered");
Check.True(FakeHost.Chat.Any(x => x.Contains("RynthILT")), "with the RynthILT note");
FakeHost.Chat.Clear();
Check.True(c.HandleCommand("bountys", Array.Empty<string>()), "the bountys spelling too");
Check.False(c.HandleCommand("guardian", new[] { "handin" }), "guardian isn't the Mini Remote's (a server plugin's verb)");
Check.False(c.HandleCommand("bountys", Array.Empty<string>()), "nor bounty");
Check.False(c.HandleCommand("start", Array.Empty<string>()), "other verbs aren't the Mini Remote's");
Check.False(FakeHost.Chat.Any(), "and it says nothing about them");
// With a server plugin, a hub verb RynthAi doesn't have is the plugin's.
var ilt = NewController("cmds-ilt", out _, out _, serverPlugin: true);
FakeServerHub.TakesCommand = line => line.StartsWith("hub bank", StringComparison.Ordinal);
FakeHost.Chat.Clear();
Check.True(ilt.HandleCommand("hub", new[] { "bank" }), "hub bank");
Check.Eq(FakeServerHub.Commands.Count, 1, "went to the server plugin");
Check.False(FakeHost.Chat.Any(), "RynthAi adds nothing (the plugin answers itself)");
}
private static void RefillNeedsIlt()
{
var c = NewController("refill", out _, out _);
c.State.Pet.UsePyrealRefillPath = true;
FakeHost.Bools[(Player, MiniRemoteInventory.BoolPyrealRefillActive)] = true; // the server's player bool
c.State.Pet.UsePyrealRefillPath = true; // the old (obsolete) opt-in in miniremote.json
FakeHost.Bools[(Player, 9049)] = true; // ACECustom's refill player bool
Check.False(c.Pets.AllowSummonOnEmpty(), "not an ILT world (no RynthILT): an empty essence is never summoned on pyreals");
}
/// <summary>
/// The Remote tab's server texts with a server plugin (2026-10-20): the session report's tail and the
/// server its menu entries belong to come from the plugin, as they are.
/// </summary>
private static void RemoteTextsFromServerPlugin()
{
var c = NewController("texts", out _, out _, serverPlugin: true);
Check.Eq(c.ServerHub.Text(RynthIltHub.TextSessionReport), string.Empty, "nothing until the plugin says something");
FakeServerHub.Texts[RynthIltHub.TextSessionReport] = ", Coins 12/h, Pyr 3.4m/h";
FakeServerHub.Texts[RynthIltHub.TextServerId] = "ilt";
Check.Eq(c.ServerHub.Text(RynthIltHub.TextSessionReport), ", Coins 12/h, Pyr 3.4m/h", "the report's tail is the plugin's");
Check.Eq(c.ServerHub.Text(RynthIltHub.TextServerId), "ilt", "and the server its menu entries belong to");
}
/// <summary>
/// The Pets tab with and without a server plugin (2026-10-20): ACECustom's pet charms, siphon
/// auto-capture, the summon-from-empty gate and the Breeding sub-tab are RynthILT's. Without it the
/// tab asks nothing of the kind; with it the gate is RynthILT's answer and its sub-tab opens by name.
/// </summary>
private static void PetsFromServerPlugin()
{
var plain = NewController("pets-plain", out _, out _);
Check.False(plain.ServerHub.Loaded, "no server plugin");
Check.False(plain.Pets.AllowSummonOnEmpty(), "no summon from empty");
Check.Eq(plain.Pets.FindSubTab("breeding"), null, "no Breeding");
var c = NewController("pets-ilt", out _, out _, serverPlugin: true);
FakeServerHub.Active = true;
Check.True(c.ServerHub.Loaded && c.ServerHub.ServerActive, "the fake RynthILT is there, on its world");
Check.False(c.Pets.AllowSummonOnEmpty(), "RynthILT says no: no summon from empty");
FakeServerHub.AllowEmpty = true;
Check.True(c.Pets.AllowSummonOnEmpty(), "RynthILT says yes (charm on, opted in, confirmed): summon from empty");
Check.Eq(c.Pets.SubTabs().Count, 0, "no sub-tabs until RynthILT offers one");
FakeServerHub.SubTabs[RynthIltHub.TabParentPets] = new() { (RynthIltHub.SectionPetBreeding, "Breeding") };
Check.Eq(c.Pets.SubTabs().Count, 1, "RynthILT's Breeding sub-tab");
Check.Eq(c.Pets.FindSubTab("breeding"), RynthIltHub.SectionPetBreeding, "found by its short id");
Check.Eq(c.Pets.FindSubTab("Breed"), RynthIltHub.SectionPetBreeding, "and the 'breed' alias");
Check.Eq(c.Pets.FindSubTab("roster"), null, "the roster isn't a server sub-tab");
FakeHost.Chat.Clear();
Check.True(c.HandleCommand("hub", new[] { "open", "breeding" }), "hub open breeding");
Check.True(FakeHost.Chat.Any(x => x.Contains("tab pets:show")), "shows the Pets tab");
Check.Eq(c.Pets.PendingSubTab, RynthIltHub.SectionPetBreeding, "on the Breeding sub-tab");
Check.Eq(FakeServerHub.Commands.Count, 0, "RynthAi handled it itself (nothing forwarded)");
}
private static void LegacyProfileFields()
{
var s = JsonSerializer.Deserialize("{\"FeatureServerNames\":[\"MyShard\"],\"ForceServerFeatures\":true}",
@ -179,19 +234,17 @@ internal static class MiniRemoteMoveTests
}
/// <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.
/// "Vaulted Dungeons" (the engine's Settings > Navigation row) is RynthILT's keeper master switch, and
/// since 2026-10-20 RynthILT's own setting (copied once from the profile, whose old field still loads
/// and is carried, unused). RynthAi only mirrors it: without a server plugin offering it the row gets
/// null (hidden) and a save changes nothing; with one, the row shows its value and a save goes to 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 oldProfile = JsonSerializer.Deserialize("{\"EnableVaultedDungeons\":true}", RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.True(oldProfile.EnableVaultedDungeons, "an old profile's switch still loads (RynthILT copies it once)");
string json = JsonSerializer.Serialize(oldProfile, RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(json.Contains("\"EnableVaultedDungeons\": true"), "and is written back unchanged");
var s = new LegacyUiSettings();
var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
@ -200,15 +253,27 @@ internal static class MiniRemoteMoveTests
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)");
Check.True(sent.EnableVaultedDungeons == null, "no server plugin: the row is sent nothing (it hides)");
dash.ApplySettingsJson("{\"EnableVaultedDungeons\":true}");
Check.True(s.EnableVaultedDungeons, "the Settings checkbox turns it on");
Check.False(s.EnableVaultedDungeons, "and a save doesn't touch RynthAi's old field");
// A server plugin offering the switch (RynthILT, through the Mini Remote's server client).
FakeHost.Reset();
FakeServerHub.Reset();
var client = new ServerHubClient(FakeHost.Create(Player));
client.UseTableForTests(FakeServerHub.Table);
dash.ServerSettingGet = key => client.Setting(key);
dash.ServerSettingSet = (key, value) => client.SetSetting(key, value);
sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!;
Check.True(sent.EnableVaultedDungeons == null, "RynthILT not offering it (off ILT): still hidden");
FakeServerHub.Settings[RynthIltHub.SettingVaultedDungeons] = 0;
sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!;
Check.True(sent.EnableVaultedDungeons == false, "offered: the row shows RynthILT's value (off)");
dash.ApplySettingsJson("{\"EnableVaultedDungeons\":true}");
Check.Eq(FakeServerHub.Settings[RynthIltHub.SettingVaultedDungeons], 1, "the checkbox turns RynthILT's switch 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");
Check.Eq(FakeServerHub.Settings[RynthIltHub.SettingVaultedDungeons], 1, "an older engine's save (no such field) leaves it alone");
Check.False(s.EnableVaultedDungeons, "RynthAi's old field is never written");
}
private static unsafe void HubTable()
@ -229,6 +294,14 @@ internal static class MiniRemoteMoveTests
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)");
Check.True(RynthAiHubApiV1.Has(t, RynthAiHubApiV1.BackAwayFromOffset) && t->BackAwayFrom != null, "the back-away is served (appended 2026-10-20)");
Check.Eq(t->BackAwayFrom(1, 12f, 750), RynthAiHub.BackAwayNotNow, "not now before login");
Check.True(RynthAiHubApiV1.Has(t, RynthAiHubApiV1.SetPlayerCounterOffset) && t->SetPlayerCounter != null, "the wield counters are served (appended 2026-10-20)");
RynthCore.Plugin.RynthAi.Loot.T11ItemSupport.Reset();
Check.Eq(t->SetPlayerCounter(9008, 3100), 1, "item augmentations taken");
Check.Eq(RynthCore.Plugin.RynthAi.Loot.T11ItemSupport.Player.Get(RynthCore.Loot.T11.T11Counter.ItemAugmentations), 3100L, "and the loot rules see them");
Check.Eq(t->SetPlayerCounter(42, 1), 0, "not a counter: refused");
RynthCore.Plugin.RynthAi.Loot.T11ItemSupport.Reset();
SessionStatsV1 ss;
Check.Eq(t->SessionStats(&ss), 0, "no session before login");
}

View file

@ -32,6 +32,7 @@ internal static class NavEngineTests
r.Add("nav engine: a Once route ends, turns nav off, and re-runs from [0]", OnceCompletes);
r.Add("nav engine: closest approach counts as arriving; a pause forgets it", SweepPass);
r.Add("nav engine: a pause point waits its time on the clock", PausePoint);
r.Add("nav engine: standing still through a pause, the stop is sent once and then once a second (not every tick)", PauseStopsOnce);
r.Add("nav engine: a chat point sends its text once and moves on", ChatPoint);
r.Add("nav engine: a jump point jumps on arrival (heading and power clamped)", JumpPoint);
r.Add("nav engine: a recall that teleports moves on after the settle", RecallTeleports);
@ -263,6 +264,26 @@ internal static class NavEngineTests
Check.Eq(nav.Idx, 1, "3.1 s: on to [1]");
}
/// <summary>
/// Standing still through a pause, nav sends its stop once and then a reminder a second, not every
/// tick: in portal space the game thread takes none of them and 137 ran 12.7 s late, against the
/// next leg (Dargoth Hera, 2026-10-19).
/// </summary>
private static void PauseStopsOnce()
{
FakeHost.Reset(); At(0, 0);
var pause = Pt(0, 0, T.Pause); pause.PauseTimeMs = 5000;
var nav = new Nav(Route(RT.Circular, pause, Pt(20, 0)));
nav.Tick(100);
int before = FakeHost.AutoRunCalls.Count(on => !on);
nav.Run(4.5);
int during = FakeHost.AutoRunCalls.Count(on => !on) - before;
Check.True(nav.E.GetStateSnapshot().InPause, "still pausing");
Check.True(during <= 5, $"4.5 s of pause: {during} autorun-off sends (a reminder a second at most)");
Check.True(during >= 3, $"but the reminders keep coming ({during})");
Check.False(FakeHost.AutoRun, "standing still");
}
private static void ChatPoint()
{
FakeHost.Reset(); At(0, 0);

View file

@ -1,97 +0,0 @@
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

@ -9,10 +9,11 @@ namespace RynthCore.RynthAiHostTests.Tests;
// Mini Remote sections (RynthCore 2026.10.5.46+): RynthCore sends its server verdicts (V lines) and
// section rail (X lines) in the "servermenu" payload, and reads RynthAi's views from
// RynthPluginGetSectionsJson. RynthAi lists its own views (Pets, Crafting, Spells, Fellowship) and
// hosts RynthILT's ILT tabs (RynthILT.Hub: Gear, Charms, Banking, Games); Quests are RynthOracle's,
// and RynthILT's Character tab moved out (RynthOracle's Character tab, Session Stats). The manifest is checked
// against the engine's own parser and catalog (UI/Sections, linked), so the two sides can't drift.
// RynthPluginGetSectionsJson. RynthAi lists only its own views (Session Stats, Pets, Crafting, Spells,
// Fellowship): since 2026-10-20 RynthILT lists its ILT tabs (Gear, Charms, Banking, Games, Vaulted
// Dungeons) in its own manifest (RynthILT.Tests); Quests are RynthOracle's, and the Character tab moved
// out (RynthOracle's Character tab, Session Stats). The manifest is checked against the engine's own
// parser and catalog (UI/Sections, linked), so the two sides can't drift.
internal static class SectionsTests
{
public static void Register(Runner r)
@ -63,22 +64,6 @@ internal static class SectionsTests
"S\tilt\tInfinite Leaftide\t1\t/rc server ilt on\n" +
"I\tProgression\t/rc progression\tPlanners.\t\n";
/// <summary>
/// RynthILT's tabs as its GetTabs would give them (Gear not reported yet, Games hidden), plus the
/// Character tab an older RynthILT still reports: it moved out of the Mini Remote (2026-10-13)
/// and must not be placed any more.
/// </summary>
private static readonly IltTabInfo[] IltTabs =
{
new("character", "Character", 520, 440, Shown: true, Available: true),
new("banking", "Banking", 560, 520, Shown: true, Available: true),
new("gear", "Gear", 560, 520, Shown: true, Available: false),
new("charms", "Charms", 560, 520, Shown: true, Available: true),
new("games", "Games", 520, 440, Shown: false, Available: false),
new("bogus id!", "Nope", 100, 100, Shown: true, Available: true),
new("unknowntab", "Unknown", 100, 100, Shown: true, Available: true),
};
private static void ParsesVerdicts()
{
ServerMenuPayload p = ServerMenuModel.ParsePayload(Payload);
@ -117,20 +102,22 @@ internal static class SectionsTests
finally { ServerMenuModel.Apply(string.Empty); }
}
private static List<SectionsManifest.View> SomeViews() => SectionsManifest.Views(IltTabs);
private static List<SectionsManifest.View> SomeViews() => SectionsManifest.Views();
private static void ManifestRoundTrip()
{
var views = SomeViews();
Check.False(views.Any(v => v.Section == "quests"), "no Quests view: RynthOracle has them");
Check.False(views.Any(v => v.Surface == "section:games"), "a tab RynthILT doesn't show isn't listed");
Check.False(views.Any(v => v.Surface.Contains("unknowntab") || v.Surface.Contains("bogus")), "unplaced or unsafe tab ids aren't listed");
Check.True(views.All(v => v.Server.Length == 0), "every view is every world's: no server's tab is listed by RynthAi");
foreach (string tab in new[] { "gear", "charms", "banking", "games", "vaulted", "character" })
Check.False(views.Any(v => v.Surface == SectionsManifest.SurfaceOf(tab)), tab + ": not RynthAi's (RynthILT lists its own tabs)");
Check.Eq(SectionsManifest.OwnSections.Length, 0, "no section of RynthAi's own (Games went with RynthILT's tabs)");
string json = SectionsManifest.Build(views, SectionsManifest.OwnSections);
SectionManifest m = SectionManifestParser.Parse("RynthAi", json, out string error);
Check.Eq(error, string.Empty, "no parse error");
Check.Eq(m.Contributions.Length, views.Count, "every view survives");
Check.Eq(m.Sections.Length, SectionsManifest.OwnSections.Length, "own sections survive");
Check.Eq(m.Contributions.Length, 5, "Session stats, Pets, Crafting, Spells, Fellowship");
Check.Eq(m.Sections.Length, 0, "no own sections");
for (int i = 0; i < views.Count; i++)
{
SectionsManifest.View v = views[i];
@ -141,26 +128,12 @@ internal static class SectionsTests
Check.Eq(c.Enabled, v.Enabled, "enabled " + v.Surface);
Check.Eq(c.Order, v.Order, "order " + v.Surface);
}
SectionContribution gear = m.Contributions.Single(c => c.Surface == SectionsManifest.SurfaceOf("gear"));
Check.False(gear.Enabled, "unavailable Gear is disabled");
Check.True(gear.Note.Length > 0, "with a note");
Check.False(views.Any(v => v.Surface == SectionsManifest.SurfaceOf("character")), "character moved out: not placed even if RynthILT reports it");
foreach (string kept in new[] { "charms", "banking" })
{
SectionsManifest.View v = views.Single(x => x.Surface == SectionsManifest.SurfaceOf(kept));
Check.True(v.Section == "inventory" && v.Server == SectionsManifest.IltServer && v.Enabled, kept + ": an ILT view in Inventory");
}
Check.True(json.Length < SectionManifestParser.MaxJsonLength / 16, "small");
SectionsManifest.View session = views.Single(v => v.Surface == SectionsManifest.SessionSurface);
Check.Eq(session.Section, "char", "session stats in the char (Session Stats) section");
Check.Eq(session.Server, string.Empty, "every world");
Check.True(session.Primary, "a primary view (RynthCore drops its own overview)");
string noIlt = SectionsManifest.Build(SectionsManifest.Views(System.Array.Empty<IltTabInfo>()), SectionsManifest.OwnSections);
SectionManifest plain = SectionManifestParser.Parse("RynthAi", noIlt, out string error2);
Check.Eq(error2, string.Empty, "without RynthILT: no parse error");
Check.Eq(plain.Contributions.Length, 5, "without RynthILT: Session stats, Pets, Crafting, Spells, Fellowship");
}
private static void CatalogPlacement()
@ -181,36 +154,27 @@ internal static class SectionsTests
Check.True(charOff.Panes.Length == 1 && charOff.Panes[0].Contribution?.Surface == SectionsManifest.SessionSurface,
"Session Stats: RynthAi's session view replaces the engine overview");
// On Infinite Leaftide RynthAi's own manifest still adds no ILT pane: RynthILT's manifest does.
List<SectionView> on = SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn });
SectionView charOn = on.Single(v => v.Id == "char");
Check.True(charOn.Panes.Length == 1 && charOn.Panes[0].Contribution?.Surface == SectionsManifest.SessionSurface,
"Session Stats on ILT: session stats only (no ILT Character tab)");
SectionView inventoryOn = on.Single(v => v.Id == "inventory");
Check.True(inventoryOn.Panes.Any(p => p.Title == "Gear") && inventoryOn.Panes.Any(p => p.Title == "Charms")
&& inventoryOn.Panes.Any(p => p.Title == "Banking"),
"Inventory on ILT: RynthILT's Gear, Charms and Banking");
SectionView inventoryOff = off.Single(v => v.Id == "inventory");
Check.False(inventoryOff.Panes.Any(p => p.Title is "Gear" or "Charms" or "Banking"), "Inventory off ILT: none of RynthILT's tabs");
Check.False(inventoryOn.Panes.Any(p => p.Contribution?.Plugin == "RynthAi" && p.Title is "Gear" or "Charms" or "Banking"),
"Inventory on ILT: none of RynthILT's tabs come from RynthAi");
Check.False(on.Any(v => v.Id == "games" && v.Panes.Any(p => p.Contribution?.Plugin == "RynthAi")), "no Games pane from RynthAi");
Check.True(on.Single(v => v.Id == "spells").Panes.Any(p => p.Contribution?.Surface == SectionsManifest.SpellsSurface), "Spells");
Check.True(on.Single(v => v.Id == "fellowship").Panes.Any(p => p.Contribution?.Surface == SectionsManifest.FellowshipSurface), "Fellowship");
}
private static void SurfaceRoundTrip()
{
foreach (string id in new[] { "gear", "games", "charms", "banking" })
{
string surface = SectionsManifest.SurfaceOf(id);
Check.True(SectionsManifest.TryIltTabOf(surface, out string back) && back == id, "round trip " + surface);
Check.Eq(SectionManifestParser.Surface(surface), surface, "the engine accepts " + surface);
}
Check.False(SectionsManifest.TryIltTabOf(SectionsManifest.SurfaceOf("character"), out _), "character isn't a section tab any more");
Check.Eq(SectionManifestParser.Surface(SectionsManifest.SessionSurface), SectionsManifest.SessionSurface, "the engine accepts the session surface");
Check.True(SectionsManifest.TryOwnTabOf(SectionsManifest.PetsSurface, out string pets) && pets == MiniRemoteTabs.Pets, "pets is RynthAi's");
Check.True(SectionsManifest.TryOwnTabOf(SectionsManifest.CraftingSurface, out string craft) && craft == MiniRemoteTabs.Crafting, "crafting is RynthAi's");
Check.False(SectionsManifest.TryIltTabOf(SectionsManifest.PetsSurface, out _), "pets isn't an ILT tab");
Check.False(SectionsManifest.TryIltTabOf(SectionsManifest.SpellsSurface, out _), "spells isn't a tab");
Check.False(SectionsManifest.TryIltTabOf("section:nonsense", out _), "unknown");
Check.False(SectionsManifest.TryIltTabOf("banking", out _), "no prefix");
Check.False(SectionsManifest.TryIltTabOf("section:quests", out _), "Quests are RynthOracle's");
foreach (string tab in new[] { "gear", "charms", "banking", "games", "vaulted" })
Check.False(SectionsManifest.TryOwnTabOf(SectionsManifest.SurfaceOf(tab), out _), tab + " isn't RynthAi's to draw");
Check.False(SectionsManifest.TryOwnTabOf(SectionsManifest.SpellsSurface, out _), "spells isn't a tab");
Check.False(SectionsManifest.TryOwnTabOf("section:nonsense", out _), "unknown");
}
}

View file

@ -0,0 +1,40 @@
using RynthCore.Plugin.RynthAi.MiniRemote;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// RynthAi's lookup of a server plugin's hub table (MiniRemote/ServerHubClient.Tick, IltClient until
// 2026-10-20: the active server's owner under "RynthServer.Hub", else RynthILT's "RynthILT.Hub"). Until
// 0.5.60 the "never looked" sentinel was long.MinValue, "now - long.MinValue" overflowed to a
// negative number, the recheck gate always said "not due", and RynthAi never found RynthILT:
// no ILT tabs, sections or feature bits in the Mini Remote on Infinite Leaftide.
internal static class ServerHubClientLookupTests
{
public static void Register(Runner r)
{
r.Add("ILT client: the first Tick (and the first after Reset) looks RynthILT up", FirstLook);
r.Add("ILT client: a live table is kept until the recheck interval", LiveTableKept);
r.Add("ILT client: no table retries every interval; a shut-down table at once", RetryRules);
}
private static void FirstLook()
{
// Any clock value, including the large tick counts of a long-running PC.
foreach (long now in new[] { 0L, 1_000L, 5_000_000L, long.MaxValue / 2 })
Check.True(ServerHubClient.LookupDue(checkedOnce: false, checkedAt: 0, now, haveTable: false, tableLive: false),
$"never looked: due at now={now}");
}
private static void LiveTableKept()
{
Check.False(ServerHubClient.LookupDue(true, checkedAt: 10_000, now: 11_000, haveTable: true, tableLive: true), "live table within the interval");
Check.True(ServerHubClient.LookupDue(true, checkedAt: 10_000, now: 13_000, haveTable: true, tableLive: true), "live table after the interval");
}
private static void RetryRules()
{
Check.False(ServerHubClient.LookupDue(true, checkedAt: 10_000, now: 12_999, haveTable: false, tableLive: false), "no table: waits the interval");
Check.True(ServerHubClient.LookupDue(true, checkedAt: 10_000, now: 13_000, haveTable: false, tableLive: false), "no table: looks again after it");
Check.True(ServerHubClient.LookupDue(true, checkedAt: 10_000, now: 10_001, haveTable: true, tableLive: false), "Version 0 (RynthILT shut down): looks again at once");
}
}

View file

@ -0,0 +1,76 @@
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.MiniRemote;
using RynthCore.PluginCore;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// "/ra" verbs RynthAi doesn't have go to the active server plugin (2026-10-20): "/ra t11" (moved to
// RynthILT with the T11 counters), "/ra guardian", "/ra bounty". Without a server plugin they are not
// RynthAi's at all: the line is left for the server, as any unknown "/ra", and nothing ILT answers.
internal static class ServerPluginForwardTests
{
private const uint Player = 0x50000F21;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("server plugin verbs: /ra t11 and /ra guardian go to the server plugin; RynthAi's own verbs don't", Forwarded);
r.Add("server plugin verbs: without a server plugin /ra t11 is no RynthAi command (left for the server)", NoServerPlugin);
}
private static RynthAiPlugin NewPlugin(bool serverPlugin)
{
FakeHost.Reset();
FakeServerHub.Reset();
FakeHost.Names[Player] = "Tester";
var host = FakeHost.Create(Player);
var p = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, new LegacyUiSettings());
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(p, dash);
var client = new ServerHubClient(host);
if (serverPlugin) client.UseTableForTests(FakeServerHub.Table);
typeof(RynthAiPlugin).GetField("_serverHub", Any)!.SetValue(p, client);
return p;
}
/// <summary>Runs "/ra ..." through RynthAi's dispatcher; returns its eat flag (1 = RynthAi or a plugin took it).</summary>
private static int Ra(RynthAiPlugin p, string line)
{
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
object[] args = { parts[1].ToLowerInvariant(), parts, 1 };
typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(p, args);
return (int)args[2];
}
private static void Forwarded()
{
var p = NewPlugin(serverPlugin: true);
FakeServerHub.TakesCommand = line => line.StartsWith("t11", StringComparison.Ordinal) || line.StartsWith("guardian", StringComparison.Ordinal);
Check.Eq(Ra(p, "/ra t11 augs 2500"), 1, "/ra t11 is taken");
Check.Eq(FakeServerHub.Commands.Count, 1, "by the server plugin");
Check.Eq(FakeServerHub.Commands[0], "t11 augs 2500", "the words after /ra, as typed");
Check.Eq(Ra(p, "/ra guardian handin"), 1, "/ra guardian is taken");
Check.Eq(FakeServerHub.Commands[1], "guardian handin", "by the server plugin too");
Check.Eq(Ra(p, "/ra nosuchverb"), 0, "a verb nobody has is left for the server");
Check.Eq(FakeServerHub.Commands.Count, 2, "and the plugin took nothing more");
Ra(p, "/ra version");
Check.Eq(FakeServerHub.Commands.Count, 2, "RynthAi's own verbs never reach the server plugin");
}
private static void NoServerPlugin()
{
var p = NewPlugin(serverPlugin: false);
FakeHost.Chat.Clear();
Check.Eq(Ra(p, "/ra t11"), 0, "/ra t11 isn't RynthAi's: left for the server (unknown command there)");
Check.False(FakeHost.Chat.Exists(l => l.Contains("T11")), "RynthAi says nothing about T11");
Check.Eq(Ra(p, "/ra guardian"), 0, "/ra guardian likewise");
}
}

View file

@ -11,7 +11,8 @@ namespace RynthCore.RynthAiHostTests.Tests;
// T11 (ACECustom tier 11+) items through the real evaluator: the virtual T11 keys answered by
// WorldObject.Values, the wield requirement and ratings the server strips put back from the
// item text, and "Can Wield" fed by the "/aug" reply.
// item text, and "Can Wield" fed by the wield counters the server plugin reports (RynthILT reads the
// "/aug" reply and applies its item-aug override since 2026-10-20; RynthAi.Hub SetPlayerCounter).
internal static class T11LootTests
{
private const string WeaponLongDesc =
@ -35,7 +36,7 @@ internal static class T11LootTests
r.Add("loot t11: modifier ratings feed Gear* keys and TotalRatings", ModifierRatings);
r.Add("loot t11: a live rating wins over the modifier text", LiveRatingWins);
r.Add("loot t11: retail items are untouched", RetailUntouched);
r.Add("loot t11: Can Wield from the /aug reply and the override", CanWield);
r.Add("loot t11: Can Wield from the counters the server plugin reports (unknown without one)", CanWield);
r.Add("loot t11: server tier and quality properties", ServerProps);
}
@ -112,15 +113,15 @@ internal static class T11LootTests
{
T11ItemSupport.Reset();
WorldObject w = Weapon();
Check.Eq(w.Values(T11Keys.CanWield, -5), -1, "unknown before /aug");
T11ItemSupport.OnChat("Advanced Augmentation Levels:");
T11ItemSupport.OnChat("Item:2,400");
Check.Eq(w.Values(T11Keys.CanWield, -5), -1, "unknown until a server plugin reports the counters (retail: never)");
Check.True(T11ItemSupport.SetCounter((uint)T11Counter.ItemAugmentations, 2400), "RynthILT reports 2,400 item augs");
Check.Eq(w.Values(T11Keys.CanWield, -5), 0, "2,400 < 2,500");
Check.False(M(w, C(N.LongValKeyE, "1", K(T11Keys.CanWield))), "rule: wieldable fails");
T11ItemSupport.SyncOverride(2500);
Check.Eq(w.Values(T11Keys.CanWield, -5), 1, "override 2,500 meets the gate");
T11ItemSupport.SyncOverride(-1);
Check.Eq(w.Values(T11Keys.CanWield, -5), 0, "back to the /aug count");
T11ItemSupport.SetCounter((uint)T11Counter.ItemAugmentations, 2500); // RynthILT's override, applied there
Check.Eq(w.Values(T11Keys.CanWield, -5), 1, "2,500 meets the gate");
T11ItemSupport.SetCounter((uint)T11Counter.ItemAugmentations, -1);
Check.Eq(w.Values(T11Keys.CanWield, -5), -1, "reported unknown again: unknown");
Check.False(T11ItemSupport.SetCounter(12345, 7), "an id that is no wield counter is refused");
Check.Eq(new Item("T11 - Robe").Wo.Values(T11Keys.CanWield, -5), -1, "not appraised yet: unknown");
Check.Eq(new Item("T11 - Robe").Str(16, "A robe.").Wo.Values(T11Keys.CanWield, -5), 1, "appraised, no gate: wieldable");
T11ItemSupport.Reset();

View file

@ -244,7 +244,14 @@ internal static class TinkerTests
Check.Eq(p2.Count(x => x == TinkerCatalog.Serpentine), 3, "group a: its cap");
Check.Eq(p2.Count(x => x == TinkerCatalog.Steel), 4, "group b: its own cap");
Check.Eq(p2.Count(x => x == TinkerCatalog.Iron), 9, "no group, no slot: all 9");
Check.True(TinkerCatalog.IsTrinket("Ornate Compass") && !TinkerCatalog.IsTrinket("Yellow Topaz Ring"), "trinkets left to their tab");
// Which jewelry is a trinket is the server plugin's (its profile's "trinkets"; RynthILT's Leaftide list).
Check.False(TinkerCatalog.IsTrinket("Ornate Compass", null), "no server plugin: no trinkets (retail jewelry is all Jewelry)");
var leaftide = ServerTrinketRule.Parse("{\"schema\":1,\"trinkets\":{\"names\":[\"compass\",\"top\"],\"except\":[\"topaz\"]}}");
Check.True(TinkerCatalog.IsTrinket("Ornate Compass", leaftide) && !TinkerCatalog.IsTrinket("Yellow Topaz Ring", leaftide),
"with the server's rule: trinkets left to their tab, a topaz ring is no top");
Check.True(TinkerCatalog.IsTrinket("Spinning Top", leaftide), "a top is");
Check.Eq(ServerTrinketRule.Parse("{\"schema\":1,\"salvage\":[]}"), ServerTrinketRule.None, "a profile without trinkets: none");
Check.Eq(ServerTrinketRule.Parse("not json"), ServerTrinketRule.None, "unusable text: none");
}
private static void ItemRows()
@ -345,8 +352,11 @@ internal static class TinkerTests
Check.Eq(TinkerPlanner.TierOf("Minor Pyreal Salvage"), 0, "Minor");
Check.Eq(TinkerPlanner.TierOf("Salvage (100)"), -1, "no tier");
Check.True(TinkerCatalog.IsTrinket("Spinning Top") && TinkerCatalog.IsTrinket("Copper Pocket Watch")
&& !TinkerCatalog.IsTrinket("Imperial Topaz Necklace"), "trinket names (topaz isn't a top)");
// The server plugin's rule (RynthILT's Leaftide list, as its profile sends it).
var rule = new ServerTrinketRule(new[] { "compass", "goggles", "scarab", "watch", "puzzle box", "top" }, new[] { "topaz" });
Check.True(TinkerCatalog.IsTrinket("Spinning Top", rule) && TinkerCatalog.IsTrinket("Copper Pocket Watch", rule)
&& !TinkerCatalog.IsTrinket("Imperial Topaz Necklace", rule), "trinket names (topaz isn't a top)");
Check.False(TinkerCatalog.IsTrinket("Copper Pocket Watch", ServerTrinketRule.None), "without a server rule nothing is a trinket");
Check.True(TinkerCatalog.Targets(TinkerBench.Trinkets, AcObjectClass.Jewelry), "trinkets are jewelry");
}
}

View file

@ -0,0 +1,158 @@
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginCore;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// ub-IT's remaining /ub verbs (2026-10-18): metas written for ub-IT send them, so every one is
// handled: mapped where RynthAi, RynthNav, RynthSort or the server has the feature, left to
// ub-Rythai for its verbs, and accepted quietly where nothing here matches (videopatch, ...).
internal static class UbCompatTests
{
private const uint Player = 0x50000F21;
private const uint Robe = 0x80282101, WornRobe = 0x80282102;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("ub compat: ub-IT verbs with no RynthAi equivalent are accepted, said once", NoEquivalentAccepted);
r.Add("ub compat: ub-Rythai's verbs get no RynthAi reply, and a meta passes them on", UbRythaiVerbsLeftAlone);
r.Add("ub compat: aliases and features map onto RynthAi, RynthNav, RynthSort and the server", AliasesAndFeatures);
r.Add("ub compat: a meta's /ub line uses the /ub meaning, not /mt's", MetaUsesUbMeaning);
}
private sealed class World
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new();
public World()
{
FakeHost.Reset();
FakeHost.PluginCommandCalls = true;
FakeHost.SalvageCalls = true; // GetObjectWielderInfo: the worn robe reads as worn
FakeHost.Names[Player] = "Kelpie";
FakeHost.PlayerIdValue = Player;
foreach (var (id, name) in new[] { (Robe, "Faran Robe"), (WornRobe, "Faran Robe") })
{
FakeHost.Names[id] = name;
FakeHost.Containers[id] = Player;
FakeHost.ItemTypes[id] = 0x2; // clothing
}
FakeHost.Wielded[WornRobe] = 0x0400;
var host = FakeHost.Create(playerId: Player);
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
Set("_objectCache", cache);
Set("_playerId", Player);
Set("_initialized", true);
Set("_loginComplete", true);
foreach (uint id in new[] { Robe, WornRobe }) cache.OnCreateObject(id);
cache.Tick();
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public bool Ub(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleUbCommand", Any)!.Invoke(P, new object[] { line })!;
public bool Meta(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMetaChatCommand", Any)!.Invoke(P, new object[] { line })!;
public int ChatWith(string text) => FakeHost.Chat.Count(c => c.Contains(text, StringComparison.OrdinalIgnoreCase));
}
private static void NoEquivalentAccepted()
{
var w = new World();
Check.True(w.Ub("/ub soak on"), "/ub soak is handled");
Check.True(w.Ub("/ub soak off"), "again");
Check.Eq(w.ChatWith("/ub soak"), 1, "said once per session, not per meta pulse");
// /ub videopatch is not here: RynthAi already forwards it to the engine's /rc videopatch.
foreach (string line in new[] { "/ub chat max", "/ub playeroption AutoRepeatAttack on", "/ub statushud toggle", "/ub professor war 7", "/ub xp level" })
Check.True(w.Ub(line), line + " is handled");
Check.Eq(w.ChatWith("Unrecognized"), 0, "no 'Unrecognized /ub command'");
Check.False(w.Ub("/ub notaubitcommand"), "a verb ub-IT doesn't have is still unknown");
}
private static void UbRythaiVerbsLeftAlone()
{
var w = new World();
int chat = FakeHost.Chat.Count;
foreach (string line in new[] { "/ub bank status", "/ub periodic add 5 /say hi", "/ub xpmeter", "/ub portal use Aerlinthe", "/ub portal list", "/ub leaftide status" })
Check.True(w.Ub(line), line + ": not unknown");
Check.Eq(FakeHost.Chat.Count, chat, "RynthAi says nothing; ub-Rythai answers these");
// A meta hands them to the chat parser, which every plugin (ub-Rythai too) sees.
Check.False(w.Meta("/ub bank status"), "a meta's /ub bank goes on to the chat parser");
// "/ub portal <name>" is RynthAi's (the nearest portal), not a portal gem.
Check.False(RynthAiPluginIsUbRythai("portal", "Town Network"), "/ub portal <name> stays RynthAi's");
}
private static bool RynthAiPluginIsUbRythai(string cmd, string args)
=> (bool)typeof(RynthAiPlugin).GetMethod("IsUbRythaiCommand", BindingFlags.Static | BindingFlags.NonPublic)!.Invoke(null, new object[] { cmd, args })!;
private static void AliasesAndFeatures()
{
var w = new World();
// wear: the carried copy, never the worn one (using a worn item takes it off).
Check.True(w.Ub("/ub wear Faran Robe"), "/ub wear");
Check.True(FakeHost.Uses.Contains(Robe) && !FakeHost.Uses.Contains(WornRobe), "wears the carried robe only");
// Frame limits are RynthAi's FPS settings.
w.Ub("/ub globalframelimit 45");
Check.Eq(w.S.TargetFPSFocused, 45, "globalframelimit");
Check.True(w.S.EnableFPSLimit, "and the limit is on");
w.Ub("/ub bgframelimit 20");
Check.Eq(w.S.TargetFPSBackground, 20, "bgframelimit");
w.Ub("/ub globalframelimit 0");
Check.False(w.S.EnableFPSLimit, "0 turns the limit off");
// RynthNav and RynthSort through the plugin broker.
w.Ub("/ub arrow point 42.1N, 33.6E");
Check.True(FakeHost.PluginCommands.Contains(("RynthNav", "rnav", "arrow 42.1N, 33.6E")), "arrow point -> /rnav arrow");
w.Ub("/ub navgoto -12.5 40.25 walk");
Check.True(FakeHost.PluginCommands.Contains(("RynthNav", "rnav", "go 12.5S, 40.25E")), "navgoto signed coords -> /rnav go");
w.Ub("/ub packsort");
Check.True(FakeHost.PluginCommands.Contains(("RynthSort", "rsort", "now")), "packsort -> /rsort now");
// Server and engine commands go to the chat parser.
w.Ub("/ub qblist");
w.Ub("/ub augs");
w.Ub("/ub window save");
w.Ub("/ub fellow dismiss Storm");
// qblist / augs are ACECustom's commands: the server plugin's (RynthILT) since 2026-10-20.
Check.False(FakeHost.ChatCommands.Contains("/qb list") || FakeHost.ChatCommands.Contains("/aug"),
"qblist / augs: no server plugin, so nothing is sent to the server");
Check.True(FakeHost.ChatCommands.Contains("/rc window save"), "window save -> /rc window save");
Check.True(FakeHost.ChatCommands.Contains("/fellowship dismiss Storm"), "fellow dismiss -> /fellowship dismiss");
// With a server plugin they are its verbs ("ub qblist", "ub augs").
FakeServerHub.Reset();
FakeServerHub.TakesCommand = line => line.StartsWith("ub ", StringComparison.Ordinal);
var hub = new RynthCore.Plugin.RynthAi.MiniRemote.ServerHubClient(default);
hub.UseTableForTests(FakeServerHub.Table);
w.Set("_serverHub", hub);
w.Ub("/ub qblist");
w.Ub("/ub augs");
Check.True(FakeServerHub.Commands.Contains("ub qblist") && FakeServerHub.Commands.Contains("ub augs"), "qblist / augs -> the server plugin");
// stfl / getxy are the /mt strafe / cursor commands (no game window here: they say so).
Check.True(w.Ub("/ub stfl 500"), "stfl handled");
Check.True(w.Ub("/ub getxy"), "getxy handled");
}
private static void MetaUsesUbMeaning()
{
var w = new World();
// A /ub verb /mt doesn't know used to fall to the chat parser and come back round.
Check.True(w.Meta("/ub soak on"), "a meta's /ub line runs the /ub dispatcher");
Check.Eq(FakeHost.ChatCommands.Count(c => c.StartsWith("/ub", StringComparison.Ordinal)), 0, "not re-sent to the chat parser");
Check.True(w.Meta("/mt get xy"), "/mt lines still go to /mt");
}
}

View file

@ -0,0 +1,340 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The safety limits on the ub-IT / Mag-Tools meta verbs (SilentKelpie's PR 12, taken 2026-10-19):
// VTank unit conversion only where documented, loot-ownership options, /ub give limits, key
// injection off by default, vendor / trade verbs only from a running meta.
internal static class UbMtSafetyTests
{
public static void Register(Runner r)
{
r.Add("ub/mt safety: VTank distances convert only for the documented option names", VtConversionOnlyDocumentedNames);
r.Add("ub/mt safety: values above 1 are yards and are never scaled", VtValuesAboveOneUnchanged);
r.Add("ub/mt safety: loot-ownership options change LootOwnership and nothing else", VtLootOwnership);
r.Add("ub/mt safety: keystroke verbs do nothing by default, said once", KeystrokesOffByDefault);
r.Add("ub/mt safety: with the setting on the keystroke verbs reach the game window", KeystrokesWhenAllowed);
r.Add("ub/mt safety: a meta cannot switch the keystroke setting on", MetaCannotEnableKeystrokes);
r.Add("ub/mt safety: /mt trade accept and /mt vendor buy|sell refuse outside a running meta", VendorTradeRefusedOutsideMeta);
r.Add("ub/mt safety: /mt trade accept and /mt vendor sell act for a running meta, one log line each", VendorTradeFromRunningMeta);
r.Add("ub/mt safety: /mt vendor sell never sells equipped gear or RynthAi's own items", VendorSellSkipsProtected);
}
private const uint Player = 0x50000F41;
private const uint Robe = 0x80282201, Cloak = 0x80282202, Sword = 0x80282203;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
/// <summary>A RynthAi plugin wired enough to run its /mt dispatcher: a carried robe, a worn cloak, a carried sword.</summary>
private sealed class World
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new();
public readonly List<(uint Msg, uint W, uint L)> Posted = new();
public World(bool tradeVendor = false)
{
FakeHost.Reset();
FakeHost.TradeVendorCalls = tradeVendor;
FakeHost.SalvageCalls = true; // GetObjectWielderInfo: the worn cloak reads as worn
FakeHost.Names[Player] = "Kelpie";
FakeHost.PlayerIdValue = Player;
foreach (var (id, name) in new[] { (Robe, "Faran Robe"), (Cloak, "Worn Cloak"), (Sword, "Sharp Sword") })
{
FakeHost.Names[id] = name;
FakeHost.Containers[id] = Player;
FakeHost.ItemTypes[id] = 0x2;
}
FakeHost.Wielded[Cloak] = 0x0400;
var host = FakeHost.Create(playerId: Player);
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
Set("_objectCache", cache);
Set("_playerId", Player);
Set("_initialized", true);
Set("_loginComplete", true);
foreach (uint id in new[] { Robe, Cloak, Sword }) cache.OnCreateObject(id);
cache.Tick();
GameInput.TestSink = (m, w, l) => Posted.Add((m, w, l));
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
/// <summary>A line typed in the chat bar.</summary>
public bool Mt(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMtCommand", Any)!.Invoke(P, new object[] { line })!;
/// <summary>A line a meta's chat-command action sends.</summary>
public bool Meta(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMetaChatCommand", Any)!.Invoke(P, new object[] { line })!;
public int ChatWith(string text) => FakeHost.Chat.Count(c => c.Contains(text, StringComparison.OrdinalIgnoreCase));
public int LogWith(string text) => FakeHost.Logs.Count(c => c.Contains(text, StringComparison.OrdinalIgnoreCase));
public void Dispose() => GameInput.TestSink = null;
}
private static readonly string[] KeyLines =
{
"/mt send enter", "/mt send msg hello", "/mt send cntrl+a", "/mt click ok", "/mt click 10 20",
"/mt movement w 100", "/mt strafe left 100", "/mt client minimize", "/mt client restore", "/mt jump 100",
};
private static void KeystrokesOffByDefault()
{
Check.False(new LegacyUiSettings().AllowMetaKeystrokes, "the setting defaults off");
var w = new World();
try
{
int before = GameInput.PostAttempts;
foreach (string line in KeyLines)
{
Check.True(w.Meta(line), line + " is handled (so it is not sent on as an unknown command)");
w.Meta(line); // a meta pulse again
}
Check.Eq(w.Posted.Count, 0, "nothing reached the game window");
Check.Eq(GameInput.PostAttempts - before, 0, "and nothing was even attempted");
Check.Eq(w.ChatWith("'Allow metas to send keystrokes"), 6, "each of the six verbs says so once, however often a meta repeats it");
Check.Eq(w.LogWith("'Allow metas to send keystrokes"), 6, "and logs it once");
// A chat command through /mt send is not a key press: it works either way.
w.Meta("/mt send /say hello");
Check.True(FakeHost.ChatCommands.Contains("/say hello"), "/mt send /command still goes to the chat parser");
Check.Eq(w.Posted.Count, 0, "and posted no key");
// Reading the cursor posts nothing, so it is not gated.
int chat = w.ChatWith("ignored");
w.Meta("/mt get xy");
Check.Eq(w.ChatWith("ignored"), chat, "/mt get xy is not refused");
}
finally { w.Dispose(); }
}
private static (LegacyUiSettings S, MetaManager M) Meta()
{
FakeHost.Reset();
var s = new LegacyUiSettings();
var m = new MetaManager(s, FakeHost.Create(), new PlayerVitalsCache());
m.SetRaCommandHandler(_ => { });
return (s, m);
}
private static void VtConversionOnlyDocumentedNames()
{
var (s, m) = Meta();
// Documented: the VTank distance options (landblock units x240 = yards).
m.Expressions.Evaluate("vtsetsetting[AttackDistance,`0.025`]");
Check.Eq(s.MonsterRange, 6, "AttackDistance 0.025 = 6 yd");
m.TryHandleVtCommand("/vt opt set approachdistance 0.0175");
Check.Eq(s.ApproachRange, 4, "approachdistance 0.0175 = 4 yd");
// RynthAi's own names (rasetsetting, or a direct setting name) keep their units: no x240.
s.CorpseApproachRangeMax = 3;
m.Expressions.Evaluate("rasetsetting[CorpseApproachRangeMax,`0.5`]");
Check.Near(s.CorpseApproachRangeMax, 0.5, 1e-9, "rasetsetting CorpseApproachRangeMax 0.5 stays 0.5 yd");
m.Expressions.Evaluate("vtsetsetting[CorpseApproachRangeMax,`0.5`]");
Check.Near(s.CorpseApproachRangeMax, 0.5, 1e-9, "a RynthAi setting named directly is not a VTank distance");
m.TryHandleVtCommand("/vt opt set follownavmin 0.5");
Check.Near(s.FollowNavMin, 0.5, 1e-9, "follownavmin is RynthAi's own name, in yards");
// Options that are not distances are never scaled, whatever the value.
m.TryHandleVtCommand("/vt opt set minimumringtargets 1");
Check.Eq(s.MinRingTargets, 1, "minimumringtargets 1 stays 1 (not 240)");
m.Expressions.Evaluate("vtsetsetting[BlacklistMonsterTimeoutSeconds,`1`]");
Check.Eq(s.BlacklistTimeoutSec, 1, "a timeout of 1 s stays 1");
m.TryHandleVtCommand("/vt opt set rebufftimeremainingseconds 1");
Check.Eq(s.RebuffSecondsRemaining, 1, "a seconds option of 1 stays 1");
}
private static void VtValuesAboveOneUnchanged()
{
var (s, m) = Meta();
foreach (var (name, value, expect) in new[] { ("attackdistance", "25", 25), ("attackdistance", "1.5", 2), ("attackdistance", "50", 50), ("approachdistance", "30", 30), ("ringdistance", "6", 6) })
{
m.TryHandleVtCommand($"/vt opt set {name} {value}");
int got = name switch { "attackdistance" => s.MonsterRange, "approachdistance" => s.ApproachRange, _ => s.RingRange };
Check.Eq(got, expect, $"{name} {value} is yards already -> {expect}");
}
// And through the expression.
m.Expressions.Evaluate("vtsetsetting[AttackDistance,`40`]");
Check.Eq(s.MonsterRange, 40, "vtsetsetting AttackDistance 40 stays 40 yd");
// Zero is not a landblock fraction either.
m.Expressions.Evaluate("vtsetsetting[AttackDistance,`0`]");
Check.Eq(s.MonsterRange, 0, "0 stays 0");
// Read back in VTank units.
m.TryHandleVtCommand("/vt opt set attackdistance 24");
Check.Eq(m.Expressions.Evaluate("vtgetsetting[AttackDistance]"), "0.1", "24 yd reads back as 0.1");
}
private static void VtLootOwnership()
{
var (s, m) = Meta();
s.LootOwnership = 0;
m.TryHandleVtCommand("/vt opt set lootfellowcorpses true");
Check.Eq(s.LootOwnership, 1, "lootfellowcorpses true: fellowship kills");
m.TryHandleVtCommand("/vt opt set lootallcorpses true");
Check.Eq(s.LootOwnership, 2, "lootallcorpses true: all corpses");
m.TryHandleVtCommand("/vt opt set lootfellowcorpses false");
Check.Eq(s.LootOwnership, 2, "lootfellowcorpses false leaves 'all corpses' alone");
m.TryHandleVtCommand("/vt opt set lootallcorpses false");
Check.Eq(s.LootOwnership, 0, "lootallcorpses false: my kills");
s.LootOwnership = 1;
m.TryHandleVtCommand("/vt opt set lootallcorpses false");
Check.Eq(s.LootOwnership, 1, "lootallcorpses false leaves 'fellowship kills' alone");
m.TryHandleVtCommand("/vt opt set lootfellowcorpses false");
Check.Eq(s.LootOwnership, 0, "lootfellowcorpses false: my kills");
// Other options never touch it, and an unreadable value is ignored.
s.LootOwnership = 2;
m.TryHandleVtCommand("/vt opt set lootonlyrarecorpses 1");
m.TryHandleVtCommand("/vt opt set usearcs 0");
m.TryHandleVtCommand("/vt opt set lootallcorpses banana");
Check.Eq(s.LootOwnership, 2, "other options and junk values leave LootOwnership alone");
}
private static void KeystrokesWhenAllowed()
{
var w = new World();
try
{
w.S.AllowMetaKeystrokes = true;
w.Meta("/mt send enter");
Check.Eq(w.Posted.Count, 2, "send enter: key down and key up");
w.Posted.Clear();
w.Meta("/mt send msg hi");
Check.Eq(w.Posted.Count, 4, "send msg hi: two keys, down and up");
w.Posted.Clear();
w.Meta("/mt click 10 20");
Check.Eq(w.Posted.Count, 3, "click x y: move, down, up");
w.Posted.Clear();
w.Meta("/mt client minimize");
Check.Eq(w.Posted.Count, 1, "client minimize");
w.Posted.Clear();
w.Meta("/mt movement w 0");
Check.Eq(w.Posted.Count, 2, "movement w 0: pressed and released at once");
w.Posted.Clear();
w.Meta("/mt strafe right 0");
Check.Eq(w.Posted.Count, 2, "strafe right 0");
w.Posted.Clear();
w.Meta("/mt jump");
Check.Eq(w.Posted.Count, 2, "no jump hook: the space key");
Check.Eq(w.ChatWith("Allow metas to send keystrokes"), 0, "nothing was refused");
// A held key is released from the plugin tick, not a timer, and never held for ever.
w.Posted.Clear();
w.Meta("/mt movement w 99999999");
Check.Eq(w.Posted.Count, 1, "held: only the key down so far");
GameInput.Shutdown();
Check.Eq(w.Posted.Count, 2, "Shutdown releases it at once");
}
finally { w.Dispose(); }
}
private static void MetaCannotEnableKeystrokes()
{
var w = new World();
try
{
var m = new MetaManager(w.S, FakeHost.Create(playerId: Player), new PlayerVitalsCache());
m.SetRaCommandHandler(_ => { });
m.Expressions.Evaluate("rasetsetting[AllowMetaKeystrokes,`1`]");
m.Expressions.Evaluate("vtsetsetting[AllowMetaKeystrokes,`1`]");
m.TryHandleVtCommand("/vt opt set AllowMetaKeystrokes true");
w.Mt("/mt opt set AllowMetaKeystrokes true");
Check.False(w.S.AllowMetaKeystrokes, "no expression, /vt or /mt option can switch it on");
w.Meta("/mt send enter");
Check.Eq(w.Posted.Count, 0, "so the keys still go nowhere");
}
finally { w.Dispose(); }
}
private static void VendorTradeRefusedOutsideMeta()
{
var w = new World(tradeVendor: true);
try
{
w.S.IsMacroRunning = true;
w.S.EnableMeta = true;
w.Mt("/mt vendor addsell Faran Robe");
Check.Eq(w.ChatWith("Sell list"), 1, "building the list is allowed from a typed line");
// Typed lines (the chat bar, a chat line, anything that is not a running meta).
Check.True(w.Mt("/mt trade accept"), "typed /mt trade accept is handled ...");
Check.True(w.Mt("/mt vendor sell"), "typed /mt vendor sell ...");
Check.True(w.Mt("/mt vendor buy"), "typed /mt vendor buy ...");
Check.Eq(FakeHost.TradeActions.Count, 0, "... but accepted nothing");
Check.Eq(FakeHost.VendorSells.Count, 0, "... sold nothing");
Check.Eq(FakeHost.VendorBuys.Count, 0, "... bought nothing");
Check.Eq(w.ChatWith("only runs from a meta that is running"), 3, "and said why, three times");
// A meta line while the macro or the Meta switch is off is not a running meta either.
w.S.IsMacroRunning = false;
w.Meta("/mt trade accept");
w.Meta("/mt vendor sell");
w.S.IsMacroRunning = true;
w.S.EnableMeta = false;
w.Meta("/mt trade accept");
Check.Eq(FakeHost.TradeActions.Count, 0, "macro off or Meta off: no trade accept");
Check.Eq(FakeHost.VendorSells.Count, 0, "macro off: no sale");
Check.Eq(w.ChatWith("only runs from a meta that is running"), 6, "all refused with the reason");
}
finally { w.Dispose(); }
}
private static void VendorTradeFromRunningMeta()
{
var w = new World(tradeVendor: true);
try
{
w.S.IsMacroRunning = true;
w.S.EnableMeta = true;
Check.True(w.Meta("/mt trade accept"), "a running meta's trade accept");
Check.Eq(FakeHost.TradeActions.Count(a => a == "accept"), 1, "is sent");
Check.Eq(w.LogWith("/mt trade accept (from the running meta)"), 1, "with one log line");
w.Meta("/mt vendor addsell Faran Robe");
Check.True(w.Meta("/mt vendor sell"), "a running meta's vendor sell");
Check.Eq(FakeHost.VendorSells.Count, 1, "is sent once");
Check.True(FakeHost.VendorSells[0].Items.SequenceEqual(new[] { Robe }), "with the listed item");
Check.Eq(w.LogWith("/mt vendor sell (from the running meta)"), 1, "with one log line naming it");
// The other trade verbs do not need a meta.
int actions = FakeHost.TradeActions.Count;
w.Mt("/mt trade decline");
Check.Eq(FakeHost.TradeActions.Count, actions + 1, "typed /mt trade decline still works");
}
finally { w.Dispose(); }
}
private static void VendorSellSkipsProtected()
{
var w = new World(tradeVendor: true);
try
{
w.S.IsMacroRunning = true;
w.S.EnableMeta = true;
w.Meta("/mt vendor addsell Worn Cloak");
w.Meta("/mt vendor sell");
Check.Eq(FakeHost.VendorSells.Count, 0, "an equipped item is never sold");
Check.True(w.ChatWith("Nothing left to sell") == 1 && w.LogWith("equipped") >= 1, "and the skip is logged");
// An item RynthAi uses (the Weapons list) is never sold either; the others still are.
w.S.ItemRules.Add(new ItemRule { Id = unchecked((int)Sword), Name = "Sharp Sword" });
w.Meta("/mt vendor addsell Sharp Sword");
w.Meta("/mt vendor addsell Faran Robe");
w.Meta("/mt vendor sell");
Check.Eq(FakeHost.VendorSells.Count, 1, "one sale");
Check.True(FakeHost.VendorSells[0].Items.SequenceEqual(new[] { Robe }), "of the robe only");
}
finally { w.Dispose(); }
}
}

View file

@ -23,6 +23,8 @@ internal static class VitalsTests
r.Add("vitals: Stamina to Health follows its own health line and stamina floor", StaminaToHealthThresholds);
r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults);
r.Add("vitals: Re-stam To keeps a started recharge going to its line; off = one recharge as before", RestamTo);
r.Add("vitals: a recharge started in a fight finishes to Re-stam To after the fight", RestamRunOutlivesFight);
r.Add("vitals: a Re-stam To run counts casts sent, not the ticks spent waiting for one", RestamRunCountsSentCasts);
r.Add("vitals: out of Magic stance a listed stamina potion goes before Revitalize; a caster casts first", StaminaPotionFirst);
r.Add("vitals: a listed potion whose stack ran out is drunk from the next stack of that name", ListedPotionNextStack);
r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait);
@ -321,6 +323,60 @@ internal static class VitalsTests
Check.Eq(FakeHost.Casts.Count, 0, "no Revitalize while a tincture is carried");
}
// A recharge started in a fight finishes to Re-stam To when the fight ends, instead of dropping to
// a lower Top Stam (Drakkon: Re-stam At 35, To 90, Top Stam 60).
private static void RestamRunOutlivesFight()
{
var s = new LegacyUiSettings { RestamAt = 35, RestamTo = 90, TopOffStam = 60 };
bool run = false; int casts = 0;
Check.Eq(BuffManager.StaminaLine(true, 30, s, ref run, ref casts), 90, "fight, 30%: recharge to 90");
casts++;
Check.Eq(BuffManager.StaminaLine(false, 58, s, ref run, ref casts), 90, "fight over at 58%: the recharge still goes to 90");
casts++;
Check.Eq(BuffManager.StaminaLine(false, 91, s, ref run, ref casts), 60, "reached 90: done, the top-off line again");
Check.False(run, "the recharge ended");
Check.Eq(BuffManager.StaminaLine(false, 55, s, ref run, ref casts), 60, "no recharge running: idle uses Top Stam");
}
// Drakkon, 2026-10-20: every Re-stam To run stopped after one Robustification. The stamina chain also
// answers "handled" while it waits for the last cast to finish, and each such tick counted as a cast:
// the 4-cast cap was reached during the first cast's 2.3 s. Only casts actually sent count now.
private static void RestamRunCountsSentCasts()
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
var host = FakeHost.Create();
var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
GetManaAt = 0, TopOffMana = 0, RestamAt = 35, RestamTo = 90, TopOffStam = 60, UsePotions = false, EnableBuffing = false,
SpellCastIntervalMs = 0 };
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, s);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 30, MaxMana = 100, CurrentMana = 100 };
var b = new BuffManager(host, s, sm, vitals) { InCombatOverride = () => true };
b.SetCharacterSkills(skills);
Check.True(b.CheckVitals(), "30% in a fight: the recharge starts");
Check.Eq(FakeHost.Casts.Count, 1, "one Revitalize sent");
for (int i = 0; i < 12; i++) b.CheckVitals(); // its 2.3 s: the server hasn't answered yet
Check.Eq(FakeHost.Casts.Count, 1, "nothing re-cast while the first is out");
string castName = SpellTableStub.GetById(FakeHost.Casts[0].SpellId)?.Name ?? "Revitalize Self";
b.OnChatWindowText($"You cast {castName} and restore 25 points of your stamina.", 7); // the cast lands: +25
FakeHost.UseDone(0);
vitals.CurrentStamina = 55;
System.Threading.Thread.Sleep(600); // real-time gaps between vital actions
Check.True(b.CheckVitals(), "55%: under Re-stam To, the run goes on");
Check.Eq(FakeHost.Casts.Count, 2, "a second Revitalize (the waits didn't use up the run)");
}
// Tom, 2026-10-06: one Revitalize often doesn't recover enough stamina.
private static void RestamTo()
{

View file

@ -20,7 +20,6 @@ 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,7 +30,6 @@
<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>

View file

@ -12,7 +12,7 @@ namespace RynthILT.Tests;
// The pet breeding tracker (IltBreedingRules / IltBreedingEssence / IltBreedingSupplies / IltPetBreeding):
// the server's rules and where each value came from, the parsers for ACECustom's appraisal block,
// chat and "@breed-debug" (formats copied from PetDevice_Breeding.cs / PetDevice_Maturity.cs), each
// breeding gate, the pair planner's odds, the supply refusals, and the "RynthILT.Data" v2 reader JSON.
// breeding gate, the pair planner's odds, the supply refusals, and the JSON RynthOracle reads.
internal static class BreedingTests
{
public static void Register(Runner r)
@ -26,7 +26,7 @@ internal static class BreedingTests
r.Add("breeding: each gate (charges, rest, growth, neutered, shiny, bond, tier, ID)", Gates);
r.Add("breeding: pair planner blocks wrong sexes and ranges the inherited mutations", Planner);
r.Add("breeding: supplies are refused where the server would refuse them", Supplies);
r.Add("breeding: reader JSON round-trips through the shared reader view", ReaderJson);
r.Add("breeding: reader JSON round-trips through RynthOracle's view", ReaderJson);
r.Add("breeding: saved state survives the hub.json source-generated serializer", StateJson);
r.Add("breeding: RynthILT.Data v2 keeps v1 readers working", DataApiVersion);
}
@ -363,12 +363,15 @@ internal static class BreedingTests
private static unsafe void DataApiVersion()
{
Check.Eq(RynthIltDataApiV1.InterfaceVersion, 2u, "version 2");
Check.True(RynthIltDataApiV1.V1Size < (uint)sizeof(RynthIltDataApiV1), "v2 appends to v1");
// Version 3 (the Temple guardians) appends after the breeding pair; a v2 reader sees the same breeding layout.
Check.Eq(RynthIltDataApiV1.InterfaceVersion, 3u, "version 3");
Check.True(RynthIltDataApiV1.V1Size < RynthIltDataApiV1.V2Size && RynthIltDataApiV1.V2Size < (uint)sizeof(RynthIltDataApiV1),
"v2 appends to v1, v3 to v2");
Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * sizeof(IntPtr)), "v1 = two uints and four function pointers");
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1) != IntPtr.Zero, "v1 readers still get the table");
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 2) != IntPtr.Zero, "v2 readers too");
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 3) == IntPtr.Zero, "a future version isn't claimed");
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 3) != IntPtr.Zero, "v3 readers too");
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4) == IntPtr.Zero, "a future version isn't claimed");
var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1);
Check.True(t->GetPetBreedingJson != null && t->PetBreedingCommand != null, "breeding functions filled");
Check.Eq(RynthIltHub.SectionPetBreeding, "pets-breeding", "section id");

View file

@ -19,6 +19,7 @@ internal static class DataApiTests
r.Add("data: the bank JSON reads back whole: characters (current first), choices, notes, log", BankRoundTrip);
r.Add("data: the bank verb lines carry their fields in RunVerb's order", BankVerbs);
r.Add("data: bad bank JSON reads as nothing", BankBadJson);
r.Add("data: the Temple guardian JSON reads back whole (switches, answer, hand-in, rows)", GuardianRoundTrip);
// Last: Release() switches the table off for the rest of the process.
r.Add("data: the RynthILT.Data table: query, functions, release", DataTable);
}
@ -82,17 +83,53 @@ internal static class DataApiTests
Check.True(empty.Loaded && !empty.Available && empty.Enabled == -1 && empty.Characters.Count == 0, "missing fields read as nothing known");
}
/// <summary>
/// Version 3: the guardian JSON RynthILT builds (IltGuardian.BuildJson) read back by the reader
/// RynthOracle's Quests tab uses, quotes and all.
/// </summary>
private static void GuardianRoundTrip()
{
var rows = new[]
{
new IltTempleAttrStatus("Strength", "Fiun \"Big\" Strongarm", 3, "Ready", "", true, true),
new IltTempleAttrStatus("Focus", "Fiun Thinker", 1, "Cooldown", "in 5h 2m", false, false),
};
string json = IltGuardian.BuildJson("InfiniteLeaftide", chat: true, auto: false, buy: true, cooldownHours: 20,
answer: "Pyreal", npc: "Guardian of Attribute Enlightenment", answerAgeSec: 42, heard: "What is \"coin\"?",
running: true, status: "handing Pyreal to Guardian...", syncedUtc: new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), rows);
Check.True(json.All(c => c >= 0x20 && c <= 0x7E), "plain printable ASCII");
IltGuardianView v = IltGuardianView.Parse(json);
Check.True(v.Loaded && v.Available && v.World == "InfiniteLeaftide", "loaded, the world");
Check.True(v.Chat && !v.Auto && v.Buy && v.CooldownHours == 20, "the switches");
Check.True(v.Answer == "Pyreal" && v.Npc == "Guardian of Attribute Enlightenment" && v.AnswerAgeSec == 42 && v.Heard == "What is \"coin\"?",
"the last answer");
Check.True(v.Running && v.Status.StartsWith("handing Pyreal"), "the hand-in");
Check.Eq(v.SyncedUtc, new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), "the /qb read time");
Check.Eq(v.Rows.Count, 2, "both rows");
Check.True(v.Rows[0].Npc == "Fiun \"Big\" Strongarm" && v.Rows[0].Count == 3 && v.Rows[0].Ready && v.Rows[0].Exact, "an exact, ready row");
Check.True(v.Rows[1].Eta == "in 5h 2m" && !v.Rows[1].Ready && !v.Rows[1].Exact, "an estimated row on cooldown");
IltGuardianView none = IltGuardianView.Parse(IltGuardian.BuildJson("x", false, false, false, 1, "", "", -1, "", false, "idle",
DateTime.MinValue, Array.Empty<IltTempleAttrStatus>()));
Check.True(none.Answer.Length == 0 && none.AnswerAgeSec == -1 && none.SyncedUtc == DateTime.MinValue && none.Rows.Count == 0,
"no answer, no /qb read, no rows");
}
private static unsafe void DataTable()
{
Check.Eq(DataInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours");
Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 3), IntPtr.Zero, "a newer version than we have: none");
Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4), IntPtr.Zero, "a newer version than we have: none");
var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1);
Check.True(t != null, "v1 is served");
Check.Eq(t->Version, 2u, "Version 2 (v1 readers take it: it starts with the v1 table)");
Check.Eq(t->Version, 3u, "Version 3 (v1 and v2 readers take it: it starts with their tables)");
Check.Eq(t->StructSize, (uint)sizeof(RynthIltDataApiV1), "StructSize");
Check.Eq(sizeof(RynthIltDataApiV1), 8 + 6 * IntPtr.Size, "header + 6 functions (v1's 4, then the breeding pair)");
Check.Eq(sizeof(RynthIltDataApiV1), 8 + 8 * IntPtr.Size, "header + 8 functions (v1's 4, the breeding pair, the guardian pair)");
Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * IntPtr.Size), "a v1 table ends before the breeding pair");
Check.Eq(RynthIltDataApiV1.V2Size, (uint)(8 + 6 * IntPtr.Size), "a v2 table ends before the guardian pair (readers still see breeding on it)");
Check.True(t->GetCharmsJson != null && t->GetBankJson != null && t->ToggleCharm != null && t->BankCommand != null
&& t->GetPetBreedingJson != null && t->PetBreedingCommand != null, "every function is filled in");
&& t->GetPetBreedingJson != null && t->PetBreedingCommand != null
&& t->GetGuardianJson != null && t->GuardianCommand != null, "every function is filled in");
Check.Eq((IntPtr)t, DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1), "the same table each time");
// No plugin instance here (not logged in): nothing to report, every action refused.
@ -104,6 +141,8 @@ internal static class DataApiTests
Check.Eq(t->BankCommand(verb), 0, "no bank command before login");
Check.Eq(t->GetPetBreedingJson(buf, 64), 0, "no breeding JSON before login");
Check.Eq(t->PetBreedingCommand(verb), 0, "no breeding command before login");
Check.Eq(t->GetGuardianJson(buf, 64), 0, "no guardian JSON before login");
Check.Eq(t->GuardianCommand(verb), 0, "no guardian command before login");
DataInterface.Release();
Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)");

View file

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
namespace RynthILT.Tests;
/// <summary>
/// A stand-in for RynthAi's "RynthAi.Hub" table (Plugins/Shared/RynthAiHubApi.cs), so the tests can
/// check what RynthILT asks of RynthAi (RynthAiClient.UseTableForTests takes it). Only the functions
/// the moved features use answer anything; the rest are absent (null), as an old RynthAi's would be.
/// Reset() before each test that uses it.
/// </summary>
internal static unsafe class FakeAiHub
{
/// <summary>BackAwayFrom calls (object, radius, hold), and what it answers.</summary>
public static readonly List<(uint Id, float Radius, int HoldMs)> BackAways = new();
public static int BackAwayResult = RynthAiHub.BackAwayStarted;
/// <summary>SetPlayerCounter: the last value reported per counter id.</summary>
public static readonly Dictionary<uint, long> Counters = new();
/// <summary>SessionStats: the shared session's start (0 = no session: SessionStats answers 0).</summary>
public static long SessionStartTicks;
private static RynthAiHubApiV1* _table;
public static void Reset()
{
BackAways.Clear();
BackAwayResult = RynthAiHub.BackAwayStarted;
Counters.Clear();
SessionStartTicks = 0;
}
public static IntPtr Table
{
get
{
if (_table == null)
{
var t = (RynthAiHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiHubApiV1));
t->StructSize = (uint)sizeof(RynthAiHubApiV1);
t->BackAwayFrom = &BackAwayFrom;
t->SetPlayerCounter = &SetPlayerCounter;
t->SessionStats = &SessionStats;
t->Version = RynthAiHubApiV1.InterfaceVersion;
_table = t;
}
return (IntPtr)_table;
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SessionStats(SessionStatsV1* s)
{
if (SessionStartTicks == 0 || s == null) return 0;
*s = default;
s->StartUtcTicks = SessionStartTicks;
s->SessionSeconds = 60;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetPlayerCounter(uint id, long value)
{
Counters[id] = value;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int BackAwayFrom(uint id, float radius, int holdMs)
{
BackAways.Add((id, radius, holdMs));
return BackAwayResult;
}
}

View file

@ -1,7 +1,9 @@
using System;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.RynthILT;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
@ -15,7 +17,10 @@ internal static class FeatureCatalogTests
{
r.Add("features: banking, guardian, attributes, augs, paragon x3, split arrows, T11 and fellowship are listed", Listed);
r.Add("features: state follows the server bit on ILT, built-ins are on, nothing is known off ILT", States);
r.Add("features: profile JSON is valid ASCII with features and the fellowship rules", ProfileJson);
r.Add("features: the interface copies the JSON only when it fits, NUL-terminated", InterfaceWrite);
r.Add("features: the /qb list rides the profile JSON on ILT worlds only", QuestBonusJson);
r.Add("features: the RynthILT.Server table: query, filled in, release", ServerTable);
r.Add("features: the ILT profile is on with the world; a refusal in chat turns a feature off", ProfileOnWithTheWorld);
r.Add("features: probed features read checking; options ILT runs off are off until chat shows them", ProbedAndOffInIlt);
r.Add("features: charms are on with the ILT world unless refused; rows describe themselves", Charms);
@ -121,6 +126,75 @@ internal static class FeatureCatalogTests
Check.Eq(IltFeatureCatalog.FellowshipMax(false), 9, "retail fellowships hold 9");
}
private static void ProfileJson()
{
string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite \"Leaftide\"", false, "probe",
new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc),
key => key == IltFeature.FBlackjack ? IltTri.Off : IltTri.On);
bool ascii = true;
foreach (char c in json) if (c < 0x20 || c > 0x7E) ascii = false;
Check.True(ascii, "plain printable ASCII");
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
Check.True(root.GetProperty("ilt").GetBoolean(), "ilt");
Check.Eq(root.GetProperty("world").GetString(), "Infinite \"Leaftide\"", "quotes in the world name survive");
Check.Eq(root.GetProperty("checked").GetString(), "2026-10-13T21:25:37Z", "checked time in UTC");
Check.Eq(root.GetProperty("features").GetArrayLength(), IltFeatureCatalog.All.Length, "every feature in the JSON");
JsonElement fel = root.GetProperty("fellowship");
Check.Eq(fel.GetProperty("maxMembers").GetInt32(), 29, "fellowship size");
Check.Eq(fel.GetProperty("zoneShare").GetInt32(), 1, "Zone Share on (built in)");
Check.Eq(fel.GetProperty("blackjack").GetInt32(), 0, "Fellowship Blackjack off (server bit)");
string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On);
using JsonDocument d2 = JsonDocument.Parse(off);
Check.Eq(d2.RootElement.GetProperty("fellowship").GetProperty("maxMembers").GetInt32(), 9, "off ILT: retail size");
Check.Eq(d2.RootElement.GetProperty("checked").GetString(), "", "never checked: empty time");
}
private static void QuestBonusJson()
{
var qb = new IltQuestBonusInfo(false, 2, 41, "2 completed, 1 incomplete",
new[] { "flag\"one", "flagTwo" }, new[] { "flagThree" });
string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite Leaftide", false, "probe", DateTime.MinValue, _ => IltTri.On, qb);
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement q = doc.RootElement.GetProperty("questBonus");
Check.False(q.GetProperty("disabled").GetBoolean(), "enabled");
Check.Eq(q.GetProperty("generation").GetInt32(), 2, "generation");
Check.Eq(q.GetProperty("count").GetInt64(), 41L, "count");
Check.Eq(q.GetProperty("status").GetString(), "2 completed, 1 incomplete", "status");
Check.Eq(q.GetProperty("completed").GetArrayLength(), 2, "completed flags");
Check.Eq(q.GetProperty("completed")[0].GetString(), "flag\"one", "quotes in a flag survive");
Check.Eq(q.GetProperty("incomplete")[0].GetString(), "flagThree", "incomplete flags");
Check.True(doc.RootElement.TryGetProperty("fellowship", out _), "the fellowship rules are still there");
string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On, qb);
using JsonDocument d2 = JsonDocument.Parse(off);
Check.False(d2.RootElement.TryGetProperty("questBonus", out _), "off ILT: no /qb list");
}
private static unsafe void ServerTable()
{
Check.Eq(ServerInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours");
Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none");
var t = (RynthIltServerApiV1*)ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1);
Check.True(t != null && t->Version == 1 && t->StructSize == (uint)sizeof(RynthIltServerApiV1) && t->GetProfileJson != null,
"v1 is served and filled in");
// Before login the profile is the not-ILT default; the copy is NUL-terminated and valid JSON.
byte* buf = stackalloc byte[262144];
int n = t->GetProfileJson(buf, 262144);
Check.True(n > 0 && n < 262144 && buf[n] == 0, "the default profile fits and is NUL-terminated");
using JsonDocument doc = JsonDocument.Parse(Encoding.UTF8.GetString(buf, n));
Check.False(doc.RootElement.GetProperty("ilt").GetBoolean(), "not an ILT world before login");
Check.Eq(t->GetProfileJson(buf, 8), n, "too small: the length comes back");
ServerInterface.Release();
Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)");
Check.Eq(t->GetProfileJson(buf, 64), 0, "answers 0 after release");
Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1), IntPtr.Zero, "not served after release");
}
private static unsafe void InterfaceWrite()
{
const string json = "{\"ilt\":true}";

View file

@ -34,7 +34,7 @@ internal static class MoveTests
r.Add("move: off ILT nothing is sent, no tab or section shows; on ILT the login probe runs", DormantOffIlt);
r.Add("move: the charms JSON for RynthILT.Data readers carries the Guardian Hands", CharmsReaderJson);
r.Add("move: Character redirects to RynthOracle; Charms and Banking stay RynthILT's tabs", MovedSections);
r.Add("sections: RynthILT's manifest (rates, /fship, /qb) is valid schema-1 JSON with its own surfaces", SectionsManifest);
r.Add("sections: RynthILT's manifest (rates, /fship, /qb, and the ILT tabs it shows) is valid schema-1 JSON the engine places", SectionsManifest);
// Last: Release() switches the table off for the rest of the process.
r.Add("move: the RynthILT.Hub table: query, functions, release", HubTable);
}
@ -364,11 +364,28 @@ internal static class MoveTests
{
Check.Eq(sizeof(IltTabV1), 24 + 32 + 4 + 4 + 4, "IltTabV1: id, label, width, height, flags");
Check.Eq((int)Marshal.OffsetOf<IltTabV1>(nameof(IltTabV1.Flags)), 64, "IltTabV1.Flags offset");
Check.Eq(sizeof(RynthIltHubApiV1), 8 + 9 * IntPtr.Size, "RynthIltHubApiV1: header + 9 functions");
// RynthILT.Hub grew on 2026-10-20 (append-only): readers accept any table at least BaseStructSize
// long (the first release's 9 functions) and check the appended ones with Has.
Check.Eq((int)RynthIltHubApiV1.BaseStructSize, 8 + 9 * IntPtr.Size, "RynthIltHubApiV1.BaseStructSize: the first release's 9 functions");
Check.Eq(RynthIltHubApiV1.AllowSummonOnEmptyOffset, 8 + 9 * IntPtr.Size, "AllowSummonOnEmpty right after Command");
Check.Eq((int)Marshal.OffsetOf<RynthIltHubApiV1>(nameof(RynthIltHubApiV1.AllowSummonOnEmpty)), RynthIltHubApiV1.AllowSummonOnEmptyOffset,
"AllowSummonOnEmptyOffset is where the field really is");
Check.Eq((int)Marshal.OffsetOf<RynthIltHubApiV1>(nameof(RynthIltHubApiV1.GetSubTabs)), RynthIltHubApiV1.GetSubTabsOffset,
"GetSubTabsOffset is where the field really is");
Check.Eq((int)Marshal.OffsetOf<RynthIltHubApiV1>(nameof(RynthIltHubApiV1.GetSetting)), RynthIltHubApiV1.GetSettingOffset,
"GetSettingOffset is where the field really is");
Check.Eq((int)Marshal.OffsetOf<RynthIltHubApiV1>(nameof(RynthIltHubApiV1.SetSetting)), RynthIltHubApiV1.SetSettingOffset,
"SetSettingOffset is where the field really is");
// SessionStatsMore was appended (2026-10-13); readers accept any table at least
// BaseStructSize long, so an older RynthAi still connects.
// VaultedDungeonsEnabled was appended (2026-10-18): the Vaulted Dungeons master switch.
Check.Eq(sizeof(RynthAiHubApiV1), 8 + 12 * IntPtr.Size, "RynthAiHubApiV1: header + 12 functions");
// BackAwayFrom was appended (2026-10-20): the generic back-away RynthILT's Handler ring evade asks for.
// SetPlayerCounter too (2026-10-20): the T11 wield counters RynthILT reads from /aug.
Check.Eq(sizeof(RynthAiHubApiV1), 8 + 14 * IntPtr.Size, "RynthAiHubApiV1: header + 14 functions");
Check.Eq((int)Marshal.OffsetOf<RynthAiHubApiV1>(nameof(RynthAiHubApiV1.SetPlayerCounter)), RynthAiHubApiV1.SetPlayerCounterOffset,
"SetPlayerCounterOffset is where the field really is");
Check.Eq((int)Marshal.OffsetOf<RynthAiHubApiV1>(nameof(RynthAiHubApiV1.BackAwayFrom)), RynthAiHubApiV1.BackAwayFromOffset,
"BackAwayFromOffset is where the field really is");
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");
@ -456,12 +473,15 @@ internal static class MoveTests
/// </summary>
private static void SectionsManifest()
{
using var doc = System.Text.Json.JsonDocument.Parse(RynthILTPlugin.SectionsJson);
// No Hub (before the character's name is known): the always-there views only.
string bare = IltSectionsManifest.Build(IltSectionsManifest.TabsOf(null));
using var doc = System.Text.Json.JsonDocument.Parse(bare);
var root = doc.RootElement;
Check.Eq(root.GetProperty("version").GetInt32(), 1, "schema 1");
var sections = root.GetProperty("sections");
Check.Eq(sections.GetArrayLength(), 1, "one section of RynthILT's own");
Check.Eq(sections.GetArrayLength(), 2, "two sections of RynthILT's own");
Check.Eq(sections[0].GetProperty("id").GetString(), "quests", "a Quests section (the /qb list)");
Check.Eq(sections[1].GetProperty("id").GetString(), "games", "and Games (moved from RynthAi with the tabs)");
var surfaces = new System.Collections.Generic.List<string>();
foreach (var c in root.GetProperty("contributions").EnumerateArray())
{
@ -471,7 +491,38 @@ internal static class MoveTests
Check.True(surfaces.SequenceEqual(new[] { RynthILTPlugin.RatesSurface, RynthILTPlugin.FellowshipSurface, RynthILTPlugin.QuestBonusSurface }),
"rates, fellowship, quest bonus: " + string.Join(",", surfaces));
Check.True(surfaces.All(s => s.StartsWith("section:ilt-", StringComparison.Ordinal) && s.Length <= 64), "short section:ilt-* surfaces");
Check.True(RynthILTPlugin.SectionsJson.All(ch => ch < 128), "ASCII only");
Check.True(bare.All(ch => ch < 128), "ASCII only");
// The Mini Remote ILT tabs the Hub shows (RynthAi listed them until 2026-10-20): Gear not reported yet,
// Games hidden, Charms and Banking shown.
var tabs = new[]
{
new IltSectionsManifest.Tab("banking", 560, 520, Shown: true, Available: true),
new IltSectionsManifest.Tab("gear", 560, 520, Shown: true, Available: false),
new IltSectionsManifest.Tab("charms", 560, 520, Shown: true, Available: true),
new IltSectionsManifest.Tab("games", 520, 440, Shown: false, Available: false),
new IltSectionsManifest.Tab("character", 520, 440, Shown: true, Available: true),
};
string json = IltSectionsManifest.Build(tabs);
var m = RynthCore.Engine.UI.Sections.SectionManifestParser.Parse("RynthILT", json, out string error);
Check.Eq(error, string.Empty, "the engine's parser takes it");
Check.Eq(m.Contributions.Length, 6, "rates, fellowship, /qb, Banking, Gear, Charms");
var gear = m.Contributions.Single(c => c.Surface == "section:gear");
Check.True(gear.Section == "inventory" && !gear.Enabled && gear.Note.Length > 0, "Gear in Inventory, disabled with a note until reported");
Check.True(m.Contributions.Any(c => c.Surface == "section:charms" && c.Enabled) && m.Contributions.Any(c => c.Surface == "section:banking" && c.Enabled),
"Charms and Banking stay RynthILT's tabs");
Check.False(m.Contributions.Any(c => c.Surface == "section:games"), "a hidden tab isn't listed");
Check.False(m.Contributions.Any(c => c.Surface == "section:character"), "Character moved out: never placed");
var iltOn = new RynthCore.Engine.UI.Sections.ServerState("ilt", "Infinite Leaftide", true, true, RynthCore.Engine.UI.Sections.ServerForce.Auto, true, "");
var on = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn });
Check.True(on.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms" && p.Contribution?.Plugin == "RynthILT"),
"on ILT the engine shows RynthILT's Charms in Inventory (drawn by RynthILT)");
var off = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn with { Active = false } });
Check.False(off.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms"), "off ILT: none");
Check.True(IltSectionsManifest.TryTabOf("section:banking", out IltSection bank) && bank == IltSection.Banking, "section:banking draws Banking");
Check.False(IltSectionsManifest.TryTabOf("section:bank", out _), "only the tab's own id");
Check.False(IltSectionsManifest.TryTabOf("section:pets", out _), "pets is RynthAi's");
Check.False(IltSectionsManifest.TryTabOf("section:ilt-rates", out _), "not a tab");
Check.True(RynthILTPlugin.IsParsedRemoteAction("servermenu") && RynthILTPlugin.IsParsedRemoteAction("ServerMenu")
&& !RynthILTPlugin.IsParsedRemoteAction("prog"), "RynthCore's servermenu push is answered, never queued as a verb");
}
@ -520,8 +571,13 @@ internal static class MoveTests
Check.Eq(t->Version, 1u, "Version 1");
Check.Eq(t->StructSize, (uint)sizeof(RynthIltHubApiV1), "StructSize");
Check.True(t->IsIltWorld != null && t->GetFeature != null && t->GetRates != null && t->GetForceIlt != null && t->SetForceIlt != null
&& t->GetTabs != null && t->RenderTab != null && t->RenderSection != null && t->Command != null, "every function is filled in");
&& t->GetTabs != null && t->RenderTab != null && t->RenderSection != null && t->Command != null
&& t->AllowSummonOnEmpty != null && t->GetSubTabs != null && t->GetSetting != null && t->SetSetting != null,
"every function is filled in");
Check.True(RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetSubTabsOffset), "the appended functions are inside StructSize");
Check.Eq((IntPtr)t, HubInterface.Query(RynthIltHubApiV1.InterfaceName, 1), "the same table each time");
Check.Eq((IntPtr)t, HubInterface.Query(RynthIltHubApiV1.NeutralInterfaceName, 1),
"and under the server-neutral name RynthAi asks the active server's owner for (RynthServer.Hub)");
// No plugin instance here (not logged in): every function answers "nothing".
Check.Eq(t->IsIltWorld(), 0, "not ILT before login");
@ -529,6 +585,11 @@ internal static class MoveTests
Check.Eq(t->GetFeature(key), -1, "feature unknown before login");
Check.Eq(t->GetTabs(null, 0), 0, "no tabs before login");
Check.Eq(t->Command(key), 0, "no command taken before login");
Check.Eq(t->AllowSummonOnEmpty(), 0, "no summon from empty before login");
byte* pets = stackalloc byte[] { (byte)'p', (byte)'e', (byte)'t', (byte)'s', 0 };
Check.Eq(t->GetSubTabs(pets, null, 0), 0, "no Pets sub-tabs before login");
Check.Eq(t->GetSetting(pets), -1, "no setting offered before login");
Check.Eq(t->SetSetting(pets, 1), 0, "and none taken");
HubInterface.Release();
Check.Eq(t->Version, 0u, "Release zeroes Version (callers re-query)");

View file

@ -0,0 +1,189 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// ACECustom's parts of RynthAi's Pets tab moved to RynthILT on 2026-10-20 (Hub/IltPetAutomation.cs):
// the pet charms, the summon-from-empty refill gate RynthAi's PetManager asks through RynthILT.Hub,
// siphon-lens auto-capture and the Breeding sub-tab offer. Their settings are copied once from the
// character's RynthAi miniremote.json (IltMigration.ImportRynthAiSettings).
internal static class PetAutomationTests
{
private const uint Player = 0x50000A01;
private const uint Lens = 0x80000A02;
private const uint Mob = 0x80000A03;
private const uint Charm = 0x80000A04;
private const uint Lb = 0xA9B40000;
public static void Register(Runner r)
{
r.Add("pets (RynthILT): summon from empty needs the opt-in, an active refill charm and the server's word; never off ILT", RefillGate);
r.Add("pets (RynthILT): auto-capture uses the lens on a weak creature in range only, and only when switched on", Capture);
r.Add("pets (RynthILT): the Breeding sub-tab is offered on ILT unless the server reports breeding off", BreedingSubTab);
r.Add("pets (RynthILT): off ILT the Pets sections draw nothing and nothing ticks", DormantOffIlt);
r.Add("migration: the Pets tab's ACECustom options come over from RynthAi's miniremote.json once", ImportsPetSettings);
}
private static IltHubController NewHub(string world, string folder, Action? setup = null)
{
FakeHost.Reset();
FakeHost.WorldName = world;
FakeHost.ContentsCalls = true;
FakeHost.WeaponCalls = true; // UseObject, RequestId, appraisal state
FakeHost.LiveObjectsCalls = true;
FakeHost.Names[Player] = "Petter";
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
setup?.Invoke();
var host = FakeHost.Create(Player);
string dir = Path.Combine(Program.TempRoot, "pets-" + folder);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host));
hub.OnLoginComplete("Petter", forceFromMigration: false);
return hub;
}
private static void Carry(uint id, string name, uint wcid)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = 0x80; // misc
FakeHost.Containers[id] = Player;
FakeHost.Wcids[id] = wcid;
}
private static void RefillGate()
{
var hub = NewHub("InfiniteLeaftide", "refill", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true);
var pets = hub.PetAutomation;
Check.False(pets.ComputeAllowSummonOnEmpty(), "not opted in: no summon from empty");
hub.State.Pet.RefillFromEmpty = true;
Check.True(pets.ComputeAllowSummonOnEmpty(), "opted in, and the server stamped the refill bool (active and confirmed)");
var charmOnly = NewHub("InfiniteLeaftide", "refill-charm", () =>
{
Carry(Charm, "Summon Essence Refill Charm", IltInventory.WcidSummonRefillCharm);
FakeHost.Strings[(Charm, IltInventory.StrUse)] = "Toggles the refill. Status: ON";
});
charmOnly.State.Pet.RefillFromEmpty = true;
Check.True(charmOnly.PetAutomation.RefillCharmActive(), "the carried charm reads ON");
Check.False(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "but the server hasn't confirmed pet_refill: never spend");
charmOnly.Options.Set(IltFeature.PetRefill, IltTri.On);
Check.True(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "confirmed: summon from empty");
charmOnly.Tick();
Check.True(charmOnly.PetAutomation.AllowSummonOnEmpty, "the tick caches it for RynthAi (RynthILT.Hub AllowSummonOnEmpty)");
var off = NewHub("Aeshnidae", "refill-off", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true);
off.State.Pet.RefillFromEmpty = true;
Check.False(off.PetAutomation.ComputeAllowSummonOnEmpty(), "off ILT: never");
off.Tick();
Check.False(off.PetAutomation.AllowSummonOnEmpty, "and nothing cached for RynthAi");
}
private static void Capture()
{
var hub = NewHub("InfiniteLeaftide", "capture", () =>
{
Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid);
FakeHost.Names[Mob] = "Drudge Skulker";
FakeHost.ItemTypes[Mob] = 0x10; // creature
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); // 3 m
FakeHost.TargetVitals[Mob] = (100, 100);
});
var pets = hub.PetAutomation;
long now = Environment.TickCount64; // the chat replies time their back-off on the real clock
pets.TickCapture(now);
Check.Eq(FakeHost.Uses.Count, 0, "switched off: no lens used");
Check.Eq(pets.CaptureStatus, "off", "status off");
hub.State.Pet.AutoCapture = true;
pets.TickCapture(now);
Check.Eq(FakeHost.Uses.Count, 0, "a full-health creature: no lens");
Check.True(pets.CaptureStatus.Contains("Drudge Skulker") && pets.CaptureStatus.Contains("need"), "it says what it waits for");
FakeHost.TargetVitals[Mob] = (15, 100);
pets.TickCapture(now + 1000);
Check.Eq(FakeHost.Uses.Count, 1, "15%: the lens is used");
Check.Eq(FakeHost.Uses[0], Lens, "the chosen lens");
pets.TickCapture(now + 1500);
Check.Eq(FakeHost.Uses.Count, 1, "the cooldown holds the next use back");
pets.OnChat("The creature is too strong to be siphoned.");
Check.True(pets.CaptureStatus.StartsWith("refused"), "a refusal is noted");
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 110f, 0f); // 14 m
pets.TickCapture(now + 60_000);
Check.Eq(FakeHost.Uses.Count, 1, "out of range: no lens");
hub.Options.Set(RynthIltHub.FeatureMonsterCapture, IltTri.Off);
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f);
pets.TickCapture(now + 120_000);
Check.Eq(FakeHost.Uses.Count, 1, "the server reports monster capture off: no lens");
Check.True(pets.CaptureStatus.Contains("disabled"), "and says so");
}
private static void BreedingSubTab()
{
var on = NewHub("InfiniteLeaftide", "breed-on");
var tabs = on.SubTabs(RynthIltHub.TabParentPets);
Check.Eq(tabs.Length, 1, "one Pets sub-tab on ILT");
Check.Eq(tabs[0].Id, RynthIltHub.SectionPetBreeding, "Breeding, drawn as the pets-breeding section");
Check.Eq(on.SubTabs("crafting").Length, 0, "nothing for another tab");
on.Options.Set(RynthIltHub.FeaturePetBreeding, IltTri.Off);
Check.Eq(on.SubTabs(RynthIltHub.TabParentPets).Length, 0, "the server reports breeding off: none");
var off = NewHub("Aeshnidae", "breed-off");
Check.Eq(off.SubTabs(RynthIltHub.TabParentPets).Length, 0, "off ILT: none");
}
private static void DormantOffIlt()
{
var off = NewHub("Aeshnidae", "dormant", () =>
{
Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid);
FakeHost.Names[Mob] = "Drudge Skulker";
FakeHost.ItemTypes[Mob] = 0x10;
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f);
FakeHost.TargetVitals[Mob] = (1, 100);
});
off.State.Pet.AutoCapture = true;
for (int i = 0; i < 5; i++) { off.Tick(); System.Threading.Thread.Sleep(60); }
Check.Eq(FakeHost.Uses.Count, 0, "off ILT the capture never ticks (no lens used)");
Check.False(off.RenderSection(RynthIltHub.SectionPetCharms) || off.RenderSection(RynthIltHub.SectionPetCapture),
"the Pets sections draw nothing (checked before any ImGui call)");
}
private static void ImportsPetSettings()
{
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Petter");
Directory.CreateDirectory(legacy);
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}");
File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile),
"{ \"Pet\": { \"HealingEnabled\": true, \"UsePyrealRefillPath\": true, \"AutoCaptureEnabled\": true, \"CaptureLensIndex\": 3 } }");
var state = new IltHubState();
Check.False(state.Pet.RefillFromEmpty || state.Pet.AutoCapture, "RynthILT's defaults: both off");
var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter");
Check.True(state.RynthAiSettingsImported, "marked done");
Check.True(state.Pet.RefillFromEmpty, "summon from empty came over");
Check.True(state.Pet.AutoCapture, "auto-capture came over");
Check.Eq(state.Pet.CaptureLens, 3, "the lens came over");
Check.True(lines.Any(l => l.Contains("auto-capture on")), "and the log line says so");
state.Pet.AutoCapture = false; // changed in RynthILT afterwards
Check.Eq(IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter").Count, 0, "the second login does nothing");
Check.False(state.Pet.AutoCapture, "RynthILT's own change stays");
var fresh = new IltHubState();
IltMigration.ImportRynthAiSettings(fresh, "InfiniteLeaftide", "Nobody");
Check.True(fresh.RynthAiSettingsImported && !fresh.Pet.AutoCapture && !fresh.Pet.RefillFromEmpty,
"a character without RynthAi files keeps the defaults (and is marked done)");
File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile), "{ broken");
var broken = new IltHubState();
IltMigration.ImportRynthAiSettings(broken, "InfiniteLeaftide", "Petter");
Check.True(broken.RynthAiSettingsImported && !broken.Pet.AutoCapture, "an unreadable miniremote.json: defaults, no exception");
}
}

View file

@ -1,8 +1,9 @@
// ACECustom MonsterCapture health / range / lens table — matches Source/ACE.Server/Entity/MonsterCapture.cs.
using RynthCore.Plugin.RynthAi.MiniRemote;
// Moved from RynthCore.RynthAiTests with the rules (RynthILT's IltPetCaptureRules since 2026-10-20).
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiTests.Tests;
namespace RynthILT.Tests;
internal static class PetCaptureRulesTests
{

View file

@ -18,6 +18,7 @@ internal static unsafe class ProfileTests
{
r.Add("profile: RynthILT serves RynthServer.Profile for ilt", Interface);
r.Add("profile: ILT's salvage reaches the Crafting tab's reader (Leather after the cap, jewelry stack)", Salvage);
r.Add("profile: ILT's trinkets reach the Crafting tab's reader (RynthAi's TinkerCatalog rule until 2026-10-20)", Trinkets);
}
private static void Interface()
@ -45,6 +46,16 @@ internal static unsafe class ProfileTests
"before the Hub is up: not active");
}
private static void Trinkets()
{
var rule = ServerTrinketRule.Parse(ProfileInterface.CurrentJson(true, "InfiniteLeaftide"));
Check.True(rule != ServerTrinketRule.None, "the profile carries a trinket rule");
foreach (string t in new[] { "Ornate Compass", "Tinker's Goggles", "Jade Scarab", "Pocket Watch", "Puzzle Box", "Spinning Top" })
Check.True(rule.IsTrinket(t), t + " is a trinket");
foreach (string j in new[] { "Yellow Topaz Ring", "Gold Necklace", "Silver Bracelet" })
Check.False(rule.IsTrinket(j), j + " is Jewelry");
}
private static void Salvage()
{
var rows = ServerSalvageView.ParseList(ProfileInterface.CurrentJson(true, "InfiniteLeaftide"));

View file

@ -48,6 +48,12 @@ internal static class Program
ChunkTargetTests.Register(runner);
RingChainTests.Register(runner);
VaultedDungeonsTests.Register(runner);
PetCaptureRulesTests.Register(runner);
PetAutomationTests.Register(runner);
RingEvadeTests.Register(runner);
VaultedSwitchTests.Register(runner);
T11Tests.Register(runner);
RemoteTabTests.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,94 @@
using System;
using System.IO;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The ILT parts of RynthAi's Remote tab moved to RynthILT on 2026-10-20: the coin / pyreal lines under
// RynthAi's Stats ("remote-stats"), the session report's tail (GetText "session-report"), the Bank and
// Guardian sections' switches (RynthILT's own now, drawn in RynthAi's Options popup, "remote-options"),
// and the coin session restarting with RynthAi's shared session instead of RynthAi sending "rates reset".
internal static class RemoteTabTests
{
public static void Register(Runner r)
{
r.Add("remote tab (RynthILT): its texts for RynthAi (server id, the session report's coins) and none off ILT", Texts);
r.Add("remote tab (RynthILT): Bank / Guardian follow RynthILT's own switches; the stats and options draw nothing off ILT", Switches);
r.Add("remote tab (RynthILT): the coins start over when RynthAi's shared session restarts", FollowsSession);
r.Add("migration: RynthAi's huds.json Bank / Guardian switches come over once", ImportsSwitches);
}
private static IltHubController NewHub(string world, string folder)
{
FakeHost.Reset();
FakeAiHub.Reset();
FakeHost.WorldName = world;
var host = FakeHost.Create(0x50000D21);
var ai = new RynthAiClient(host);
ai.UseTableForTests(FakeAiHub.Table);
string dir = Path.Combine(Program.TempRoot, "remote-" + folder);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), ai);
hub.OnLoginComplete("Remoter", forceFromMigration: false);
return hub;
}
private static void Texts()
{
var on = NewHub("InfiniteLeaftide", "texts-on");
Check.Eq(on.GetText(RynthIltHub.TextServerId), "ilt", "its tabs belong to RynthCore's 'ilt'");
string tail = on.GetText(RynthIltHub.TextSessionReport);
Check.True(tail.StartsWith(", Coins ") && tail.Contains("/h, Pyr "), "the session report's tail: coins and pyreals per hour");
Check.Eq(on.GetText("no-such-text"), string.Empty, "an unknown id: nothing");
var off = NewHub("Aeshnidae", "texts-off");
Check.Eq(off.GetText(RynthIltHub.TextSessionReport), string.Empty, "off ILT: no coins in RynthAi's report");
}
private static void Switches()
{
var on = NewHub("InfiniteLeaftide", "switches");
Check.True(on.State.Remote.ShowBank && on.State.Remote.ShowGuardian, "both on by default");
on.State.Remote.ShowBank = false;
on.State.Remote.ShowGuardian = false;
Check.False(on.RenderSection(RynthIltHub.SectionRemoteBank), "Bank switched off: nothing drawn");
Check.False(on.RenderSection(RynthIltHub.SectionRemoteGuardian), "Guardian switched off: nothing drawn");
var off = NewHub("Aeshnidae", "switches-off");
Check.False(off.RenderSection(RynthIltHub.SectionRemoteStats) || off.RenderSection(RynthIltHub.SectionRemoteOptions)
|| off.RenderSection(RynthIltHub.SectionRemoteBank) || off.RenderSection(RynthIltHub.SectionRemoteGuardian),
"off ILT: none of the Remote tab's ILT parts draws (checked before any ImGui call)");
}
private static void FollowsSession()
{
var hub = NewHub("InfiniteLeaftide", "session");
long t1 = DateTime.UtcNow.AddMinutes(-10).Ticks;
FakeAiHub.SessionStartTicks = t1;
long now = Environment.TickCount64;
hub.Rates.Tick(now);
DateTime first = hub.Rates.SessionStartUtc;
System.Threading.Thread.Sleep(30);
hub.Rates.Tick(now + 100);
Check.Eq(hub.Rates.SessionStartUtc, first, "the same shared session: no restart");
FakeAiHub.SessionStartTicks = DateTime.UtcNow.Ticks; // RynthAi's Reset XP
hub.Rates.Tick(now + 200);
Check.True(hub.Rates.SessionStartUtc > first, "RynthAi's session restarted: the coins start over too");
}
private static void ImportsSwitches()
{
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Remoter");
Directory.CreateDirectory(legacy);
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}");
File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyHudsFile), "{ \"ShowMiniRemote\": true, \"MiniShowBank\": false }");
var state = new IltHubState();
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Remoter");
Check.False(state.Remote.ShowBank, "Bank was hidden in RynthAi: hidden here");
Check.True(state.Remote.ShowGuardian, "Guardian wasn't in the file: the default (shown)");
}
}

View file

@ -0,0 +1,134 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The Empyrean Handler's lethal ring (Hub/IltRingEvade.cs), RynthAi's CombatManager's until 2026-10-20
// (Silentkelpie's PR 12). The line "The handler briefly channels infused Empyrean hatred to release a
// lethal ring." on an ILT world, with a Handler near, makes RynthILT ask RynthAi to back away from it
// (RynthAi.Hub BackAwayFrom, 12 yards, a 750 ms jump). The setting (on by default) is RynthILT's now,
// copied once from the RynthAi profile.
internal static class RingEvadeTests
{
private const uint Player = 0x50000B01;
private const uint Handler = 0x80000B02;
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 (RynthILT): the Handler's line, and not a player's copy of it", ChannelLine);
r.Add("ring evade (RynthILT): on ILT with a Handler near, RynthAi is asked to back away (once per cooldown)", AsksRynthAi);
r.Add("ring evade (RynthILT): not with the setting off, no Handler near, off ILT, or without RynthAi", NotThese);
r.Add("migration: the RynthAi profile's Handler ring evade comes over once (on by default)", ImportsSetting);
}
private static IltHubController NewHub(string world, string folder, bool handler = true, bool withAi = true, string handlerName = "Empyrean Handler")
{
FakeHost.Reset();
FakeAiHub.Reset();
FakeHost.WorldName = world;
FakeHost.ContentsCalls = true;
FakeHost.LiveObjectsCalls = true;
FakeHost.Names[Player] = "Evader";
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
if (handler)
{
FakeHost.Names[Handler] = handlerName;
FakeHost.ItemTypes[Handler] = 0x10;
FakeHost.Positions[Handler] = (Lb | 0x1C, 96f, 101f, 0f);
}
var host = FakeHost.Create(Player);
var ai = new RynthAiClient(host);
if (withAi) ai.UseTableForTests(FakeAiHub.Table);
string dir = Path.Combine(Program.TempRoot, "ring-" + folder);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), ai);
hub.OnLoginComplete("Evader", forceFromMigration: false);
return hub;
}
private static void ChannelLine()
{
Check.True(IltRingEvade.IsChannelLine(RingLine, ChatSource.Emote), "the Handler's emote");
Check.True(IltRingEvade.IsChannelLine("handler briefly channels infused Empyrean hatred to release a lethal ring.", 0x00),
"mid-line on a system line (a client that strips 'The ')");
Check.False(IltRingEvade.IsChannelLine("Someone says, \"" + RingLine + "\"", ChatSource.Speech), "a player saying it");
Check.False(IltRingEvade.IsChannelLine("Bob tells you, \"" + RingLine + "\"", 0x00), "a tell repeating it");
Check.False(IltRingEvade.IsChannelLine("The handler waves.", ChatSource.Emote), "another Handler emote");
}
private static void AsksRynthAi()
{
var hub = NewHub("InfiniteLeaftide", "asks");
hub.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 1, "one back-away request");
var (id, radius, hold) = FakeAiHub.BackAways[0];
Check.Eq(id, Handler, "away from the Handler");
Check.Eq(radius, IltRingEvade.DangerYards, "12 yards (RynthAi widens it to Ring Range)");
Check.Eq(hold, IltRingEvade.JumpHoldMs, "a 750 ms jump");
Check.True(hub.RingEvade.LastOutcome.Contains("backs away"), "logged");
hub.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 1, "a second line inside the cooldown asks nothing");
var outside = NewHub("InfiniteLeaftide", "outside");
FakeAiHub.BackAwayResult = RynthAiHub.BackAwayOutside;
outside.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 1, "RynthAi decides the radius");
Check.True(outside.RingEvade.LastOutcome.Contains("outside"), "and its answer is logged");
var notFighting = NewHub("InfiniteLeaftide", "notnow");
FakeAiHub.BackAwayResult = RynthAiHub.BackAwayNotNow;
notFighting.OnChat(RingLine, ChatSource.Emote);
Check.True(notFighting.RingEvade.LastOutcome.Contains("isn't fighting"), "RynthAi not fighting: it says so");
}
private static void NotThese()
{
var off = NewHub("InfiniteLeaftide", "setting-off");
off.State.Combat.HandlerRingEvade = false;
off.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 0, "setting off: nothing asked");
var none = NewHub("InfiniteLeaftide", "none", handlerName: "Drudge Skulker");
none.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 0, "no Empyrean Handler near: nothing asked");
var said = NewHub("InfiniteLeaftide", "said");
said.OnChat("Someone says, \"" + RingLine + "\"", ChatSource.Speech);
Check.Eq(FakeAiHub.BackAways.Count, 0, "a player's copy: nothing asked");
var retail = NewHub("Aeshnidae", "retail");
retail.OnChat(RingLine, ChatSource.Emote);
Check.Eq(FakeAiHub.BackAways.Count, 0, "off ILT: nothing asked");
var noAi = NewHub("InfiniteLeaftide", "noai", withAi: false);
noAi.OnChat(RingLine, ChatSource.Emote);
Check.True(noAi.RingEvade.LastOutcome.Contains("RynthAi"), "without RynthAi: said in the log, no crash");
}
private static void ImportsSetting()
{
Check.True(new IltHubState().Combat.HandlerRingEvade, "on by default");
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Evader");
Directory.CreateDirectory(legacy);
File.WriteAllText(Path.Combine(legacy, "active_profile.txt"), "Farm");
File.WriteAllText(Path.Combine(legacy, "Farm.json"), "{ \"HandlerRingEvade\": false, \"MonsterRange\": 30 }");
var state = new IltHubState();
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Evader");
Check.False(state.Combat.HandlerRingEvade, "the active profile had it off: off here too");
string legacy2 = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Oldie");
Directory.CreateDirectory(legacy2);
File.WriteAllText(Path.Combine(legacy2, "Default.json"), "{ \"MonsterRange\": 30 }");
var old = new IltHubState();
IltMigration.ImportRynthAiSettings(old, "InfiniteLeaftide", "Oldie");
Check.True(old.Combat.HandlerRingEvade, "a profile from before the setting: on (the default)");
}
}

View file

@ -53,6 +53,16 @@
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\BountiesSnapshotJson.cs" Link="Engine\BountiesSnapshotJson.cs" />
</ItemGroup>
<!-- The engine's Mini Remote sections manifest parser and catalog (pure; the RynthAi host tests link the same
files), so the sections test checks RynthILT's RynthPluginGetSectionsJson against the engine's reader. -->
<ItemGroup>
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Sections\ServerForce.cs" Link="Engine\ServerForce.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Sections\SectionManifest.cs" Link="Engine\SectionManifest.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Sections\SectionCatalog.cs" Link="Engine\SectionCatalog.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" />
</ItemGroup>
<!-- The engine supplies cimgui; never copy ImGui.NET's own next to the test exe either. -->
<Target Name="RemoveBundledImGuiNative" AfterTargets="Build">
<Delete Files="$(OutputPath)cimgui.dll" Condition="Exists('$(OutputPath)cimgui.dll')" />

View file

@ -0,0 +1,113 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Loot.T11;
using RynthCore.Plugin.RynthILT;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// T11 (ACECustom tier 11+ gear) moved from RynthAi on 2026-10-20 (Hub/IltT11.cs): RynthILT reads the
// "/aug" reply's wield counters, applies its item-aug override and reports them to RynthAi's loot rules
// (RynthAi.Hub SetPlayerCounter); "/ilt t11" (and RynthAi's "/ra t11", passed on) shows and sets them.
internal static class T11Tests
{
private const uint Player = 0x50000E01;
public static void Register(Runner r)
{
r.Add("t11 (RynthILT): the /aug reply's counters go to RynthAi, with the item-aug override applied", ReportsCounters);
r.Add("t11 (RynthILT): /ilt t11 and /ra t11 are RynthILT's verbs; augs sets the override", Commands);
r.Add("t11 (RynthILT): off ILT nothing is read or reported", DormantOffIlt);
r.Add("migration: the RynthAi profile's T11 item-aug override comes over once", ImportsOverride);
}
private static IltHubController NewHub(string world, string folder)
{
FakeHost.Reset();
FakeAiHub.Reset();
FakeHost.WorldName = world;
var host = FakeHost.Create(Player);
var ai = new RynthAiClient(host);
ai.UseTableForTests(FakeAiHub.Table);
string dir = Path.Combine(Program.TempRoot, "t11-" + folder);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), ai);
hub.OnLoginComplete("Augger", forceFromMigration: false);
return hub;
}
private static void ReportsCounters()
{
var hub = NewHub("InfiniteLeaftide", "report");
hub.T11.Tick(Environment.TickCount64);
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "unknown before /aug (reported as -1)");
Check.Eq(hub.T11.LastReported, T11Catalog.CounterNames.Length, "every counter is reported");
hub.OnChat("Advanced Augmentation Levels:");
hub.OnChat("Item:2,400");
hub.OnChat("Triune Weave: 5 (adds 5 to your aug counts)");
hub.T11.Tick(Environment.TickCount64);
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "Item: 2,400 reported");
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.TriuneWeave], 5L, "Triune Weave: 5 reported");
hub.State.T11.ItemAugsOverride = 2500;
hub.T11.Tick(Environment.TickCount64);
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2500L, "the override replaces /aug's item count");
hub.State.T11.ItemAugsOverride = -1;
hub.T11.Tick(Environment.TickCount64);
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "auto again: /aug's count");
hub.OnLogout();
hub.T11.Tick(Environment.TickCount64);
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "after logout: unknown again");
}
private static void Commands()
{
Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11" }), "/ra t11 is RynthILT's (RynthAi passes it on)");
Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11", "augs", "5" }), "with its arguments");
Check.True(RynthILTPlugin.IsIltVerb(new[] { "ub", "qblist" }) && RynthILTPlugin.IsIltVerb(new[] { "ub", "augs" }),
"ub-IT's /ub qblist and /ub augs (ACECustom commands RynthAi passes on) are RynthILT's");
Check.False(RynthILTPlugin.IsIltVerb(new[] { "ub", "wear" }) || RynthILTPlugin.IsIltVerb(new[] { "ub" }), "no other /ub verb");
var hub = NewHub("InfiniteLeaftide", "cmd");
FakeHost.Chat.Clear();
hub.T11.HandleCommand(new[] { "augs", "3,000" });
Check.Eq(hub.State.T11.ItemAugsOverride, 3000, "augs 3,000 fixes the override");
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 3000L, "and reports it at once");
hub.T11.HandleCommand(new[] { "augs", "auto" });
Check.Eq(hub.State.T11.ItemAugsOverride, -1, "augs auto clears it");
FakeHost.Chat.Clear();
hub.T11.HandleCommand(Array.Empty<string>());
Check.True(FakeHost.Chat.Any(l => l.Contains("=== T11 loot")), "no argument: the status");
Check.True(FakeHost.Chat.Any(l => l.Contains("Item Augmentations") || l.Contains("unknown")), "lists the counters");
FakeHost.Chat.Clear();
hub.T11.HandleCommand(new[] { "augs", "-5" });
Check.True(FakeHost.Chat.Any(l => l.Contains("Usage")), "a bad count: usage");
}
private static void DormantOffIlt()
{
var off = NewHub("Aeshnidae", "off");
off.OnChat("Advanced Augmentation Levels:");
off.OnChat("Item:2,400");
for (int i = 0; i < 3; i++) off.Tick();
Check.Eq(FakeAiHub.Counters.Count, 0, "off ILT: no counter is reported to RynthAi");
Check.True(off.T11.Player.Get(T11Counter.ItemAugmentations) == null, "nor read");
}
private static void ImportsOverride()
{
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Augger");
Directory.CreateDirectory(legacy);
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"T11ItemAugsOverride\": 2750 }");
var state = new IltHubState();
Check.Eq(state.T11.ItemAugsOverride, -1, "automatic by default");
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Augger");
Check.Eq(state.T11.ItemAugsOverride, 2750, "the RynthAi profile's override came over");
}
}

View file

@ -0,0 +1,64 @@
using System;
using System.IO;
using RynthCore.Plugin.RynthILT.Hub;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthILT.Tests;
// The Vaulted Dungeons keeper's master switch moved from RynthAi's profile to RynthILT on 2026-10-20
// (IltHubState.VaultedDungeonsEnabled, the ILT settings view). RynthAi mirrors it into the engine's
// Settings > Navigation row through RynthILT.Hub GetSetting / SetSetting, which offer it on ILT only.
internal static class VaultedSwitchTests
{
public static void Register(Runner r)
{
r.Add("vaulted switch: RynthILT's own (off by default), what the keeper reads, offered to the engine row on ILT only", OwnSwitch);
r.Add("migration: the RynthAi profile's Vaulted Dungeons switch comes over once", ImportsSwitch);
}
private static IltHubController NewHub(string world, string folder)
{
FakeHost.Reset();
FakeHost.WorldName = world;
var host = FakeHost.Create(0x50000C01);
string dir = Path.Combine(Program.TempRoot, "vswitch-" + folder);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
Directory.CreateDirectory(dir);
var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host));
hub.OnLoginComplete("Vaulter", forceFromMigration: false);
return hub;
}
private static void OwnSwitch()
{
var hub = NewHub("InfiniteLeaftide", "own");
Check.False(hub.State.VaultedDungeonsEnabled, "off by default");
Check.False(hub.VaultedDungeons.MasterEnabled(), "the keeper reads RynthILT's own switch (no RynthAi needed)");
Check.False(hub.SectionAvailable(IltSection.VaultedDungeons), "no tab while off");
Check.Eq(hub.GetSetting(RynthIltHub.SettingVaultedDungeons), 0, "offered to the engine row: off");
Check.True(hub.SetSetting(RynthIltHub.SettingVaultedDungeons, 1), "the engine row (through RynthAi) sets it");
Check.True(hub.State.VaultedDungeonsEnabled && hub.VaultedDungeons.MasterEnabled(), "on");
Check.True(hub.SectionAvailable(IltSection.VaultedDungeons), "the tab shows on ILT");
Check.Eq(hub.GetSetting("no-such-setting"), -1, "an unknown key isn't offered");
Check.False(hub.SetSetting("no-such-setting", 1), "nor taken");
var off = NewHub("Aeshnidae", "off");
Check.Eq(off.GetSetting(RynthIltHub.SettingVaultedDungeons), -1, "off ILT: not offered (the engine row hides)");
}
private static void ImportsSwitch()
{
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Vaulter");
Directory.CreateDirectory(legacy);
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"EnableVaultedDungeons\": true }");
var state = new IltHubState();
var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter");
Check.True(state.VaultedDungeonsEnabled, "on in the RynthAi profile: on here");
Check.True(lines.Exists(l => l.Contains("Vaulted Dungeons master switch on")), "logged");
state.VaultedDungeonsEnabled = false;
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter");
Check.False(state.VaultedDungeonsEnabled, "copied once: RynthILT's later change stays");
}
}

View file

@ -64,7 +64,9 @@ namespace RynthInventory.Tests
Run("scheduler: unchanged content is not rewritten", SchedulerUnchanged);
Run("window display lists parse in the engine", Pages);
Run("window events", Events);
Run("vault feed (/mule-data)", VaultTests);
Run("banking: roster, totals and amounts", BankRosterTests);
Run("banking: the tab draws and sends RynthILT's verbs", BankingTab);
Run("storage from other plugins (StorageFeed)", StorageFeedTests);
}
finally
{
@ -633,6 +635,103 @@ namespace RynthInventory.Tests
ParseAll(host, "after forget", out _);
}
// ── Banking (the Mini Remote's Banking tab moved here 2026-10-13) ───
/// <summary>RynthILT's bank JSON for the sample index: Buffy (here) and Ghost (another account, no inventory file).</summary>
private const string BankJson = "{\"available\":true,\"enabled\":1,\"world\":\"Aelrynth\",\"character\":\"Buffy\","
+ "\"characters\":[{\"name\":\"Buffy\",\"current\":true,\"pyreals\":100,\"luminance\":2000,\"legendaryKeys\":1,\"mythicalKeys\":0,"
+ "\"enlightenedCoins\":3,\"weaklyEnlightenedCoins\":0,\"prestigeCoins\":0,\"updated\":\"2026-10-03T11:00:00Z\"},"
+ "{\"name\":\"Ghost\",\"current\":false,\"pyreals\":50,\"luminance\":0,\"legendaryKeys\":2,\"mythicalKeys\":1,"
+ "\"enlightenedCoins\":0,\"weaklyEnlightenedCoins\":4,\"prestigeCoins\":5,\"updated\":\"2026-10-01T11:00:00Z\"}],"
+ "\"deposits\":[\"Everything\",\"Pyreals\"],\"withdrawals\":[{\"label\":\"Pyreals\",\"notes\":false},{\"label\":\"Trade notes\",\"notes\":true}],"
+ "\"transfers\":[{\"label\":\"Pyreals\",\"notes\":false}],\"notes\":[{\"label\":\"MMD\",\"value\":250000}],"
+ "\"result\":\"Deposited everything.\",\"transactions\":[{\"when\":\"2026-10-03 11:30\",\"type\":\"Sent\",\"amount\":10,\"currency\":\"Pyreals\",\"player\":\"Willow\"}]}";
private static void BankRosterTests()
{
InventoryIndex index = SampleIndex(out _);
var bank = RynthCore.Plugin.Shared.IltBankView.Parse(BankJson);
List<BankRosterEntry> roster = BankRoster.Build(bank, index);
Eq(string.Join(",", roster.Select(e => e.Name)), "Buffy,Ghost,Willow", "you first, then by name; Conquest's characters left out");
Check(roster[0].Current && roster[0].Bank != null && roster[0].Account == "tom", "Buffy: RynthILT's balance and the inventory's account");
Check(roster[1].Bank != null && roster[1].Account == "", "Ghost: only RynthILT knows it (another account on this PC)");
Check(roster[2].Bank == null && roster[2].Account == "tom", "Willow: in the inventory, no bank read yet");
var total = BankRoster.Totals(roster);
Check(total.Pyreals == 150 && total.Luminance == 2000 && total.LegendaryKeys == 3 && total.PrestigeCoins == 5, "totals add every balance");
Eq(BankRoster.Build(RynthCore.Plugin.Shared.IltBankView.None, null).Count, 0, "nothing without RynthILT or the index");
var noWorld = RynthCore.Plugin.Shared.IltBankView.Parse("{\"available\":true,\"characters\":[]}");
Eq(string.Join(",", BankRoster.Build(noWorld, index).Select(e => e.Name)), "Buffy,Willow", "no world named: the server you're on");
Eq(BankRoster.ParseAmount("1,000"), 1000L, "commas allowed");
Eq(BankRoster.ParseAmount(" 25 "), 25L, "spaces trimmed");
foreach (string bad in new[] { "", "0", "-5", "1.5", "abc", "1e6" })
Eq(BankRoster.ParseAmount(bad), 0L, $"'{bad}' isn't an amount");
}
private static void BankingTab()
{
InventoryContext c = Context(false);
var sent = new List<string>();
c.BankCommand = v => { sent.Add(v); return true; };
var view = new InventoryView(c);
var host = new UiHost();
UiWindow w = host.Add(new UiWindow("RynthInventory/Main", "Global Inventory") { Visible = true });
// Without RynthILT the tab button stays hidden; /ginv bank still opens it and says why.
Draw(w, view);
Check(!BodyText(w).Contains("###tab.bank"), "no Banking button without RynthILT");
view.ShowBanking();
Draw(w, view);
Check(BodyText(w).Contains("Load RynthILT"), "asked for: says RynthILT is needed");
w.MarkSubmitted(true);
c.Bank = RynthCore.Plugin.Shared.IltBankView.Parse(BankJson);
view.Tab = InventoryView.TabSearch;
Draw(w, view);
Check(BodyText(w).Contains("###tab.bank"), "the Banking button shows on an ILT world");
Apply(host, Event(1, 1, w.Hash, w.KeyOf("tab.bank"), new byte[] { 1, 0 }));
Check(view.Tab == InventoryView.TabBanking, "a click opens it");
Draw(w, view);
ParseAll(host, "banking tab", out int ops);
string body = BodyText(w);
Check(ops > 5 && ops <= 1500, $"banking tab: {ops} ops");
Check(body.Contains("Buffy (you)") && body.Contains("Ghost") && body.Contains("Willow") && !body.Contains("Spike"),
"every character on this server, none from another");
Check(body.Contains("not read yet"), "a character without a balance says so");
Check(body.Contains("150") && body.Contains("Deposited everything."), "the total and RynthILT's last reply");
Apply(host, Event(1, 2, w.Hash, w.KeyOf("b.dep.go"), new byte[] { 1, 0 }));
Eq(sent.LastOrDefault(), "deposit 0", "Deposit sends the chosen deposit");
Apply(host, Event(5, 3, w.Hash, w.KeyOf("b.wd.amt"), TextPayload("5")));
Draw(w, view);
Apply(host, Event(1, 4, w.Hash, w.KeyOf("b.wd.go"), new byte[] { 1, 0 }));
Eq(sent.LastOrDefault(), "withdraw 0 5 0", "Withdraw sends currency, amount and note");
// A transfer asks first; only "Yes, send" sends it.
Apply(host, Event(5, 5, w.Hash, w.KeyOf("b.tx.amt"), TextPayload("1,000")));
Apply(host, Event(5, 6, w.Hash, w.KeyOf("b.tx.to"), TextPayload("Willow")));
Draw(w, view);
int before = sent.Count;
Apply(host, Event(1, 7, w.Hash, w.KeyOf("b.tx.go"), new byte[] { 1, 0 }));
Check(sent.Count == before, "one click doesn't transfer");
Draw(w, view);
Check(BodyText(w).Contains("Send 1,000 Pyreals to Willow?"), "it asks, naming amount and recipient");
Apply(host, Event(1, 8, w.Hash, w.KeyOf("b.tx.yes"), new byte[] { 1, 0 }));
Eq(sent.LastOrDefault(), "transfer 0 1000 0 Willow", "confirmed: the transfer verb");
// A bad amount is refused here, nothing sent.
Apply(host, Event(5, 9, w.Hash, w.KeyOf("b.wd.amt"), TextPayload("lots")));
Draw(w, view);
before = sent.Count;
Apply(host, Event(1, 10, w.Hash, w.KeyOf("b.wd.go"), new byte[] { 1, 0 }));
Check(sent.Count == before, "a bad amount isn't sent");
Draw(w, view);
Check(BodyText(w).Contains("Type a whole number"), "and it says why");
ParseAll(host, "banking after actions", out _);
}
// ── Helpers ─────────────────────────────────────────────────────────
private static void Draw(UiWindow w, InventoryView view)

View file

@ -30,7 +30,9 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthInventory\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthInventory\obj\**;..\..\Plugins\RynthCore.Plugin.RynthInventory\bin\**" Link="RynthInventory\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
<!-- The plugin links this one from Plugins/Shared (the glob above only covers the plugin's folder). -->
<Compile Include="..\..\Plugins\Shared\ChatSource.cs" Link="Shared\ChatSource.cs" />
<Compile Include="..\..\Plugins\Shared\StorageFeed.cs" Link="Shared\StorageFeed.cs" />
<!-- RynthILT's "RynthILT.Data" reader: the Banking tab's bank view and verbs. -->
<Compile Include="..\..\Plugins\Shared\RynthIltDataApi.cs" Link="Shared\RynthIltDataApi.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -0,0 +1,79 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthInventory;
using RynthCore.Plugin.RynthInventory.Data;
using RynthCore.Plugin.Shared;
namespace RynthInventory.Tests
{
// Storage another plugin reads for RynthInventory (Plugins/Shared/StorageFeed.cs): since 2026-10-20
// Aelrynth's account vault comes from RynthAelrynth (which reads /mule-data) instead of RynthInventory
// asking every server for it. RynthInventory only takes "storage" records and files them.
internal static partial class Program
{
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_storagePushes")]
private static extern ref ConcurrentQueue<string> StoragePushes(RynthInventoryPlugin p);
private static StorageFeedRecord Feed(uint id, string name, params StorageFeedItem[] items) => new(id, name, "Account vault", items);
private static void StorageFeedTests()
{
var vaultItem = new StorageFeedItem(2147483649u, 100, "Acid Assagai", 100667000, 100667001, 100667002, 3, 100, 1);
var coin = new StorageFeedItem(2147483650u, 101, "Pyreal", 100667003, 0, 0, 0, 0, 8192);
// The payload round-trips and becomes an ordinary storage record.
StorageFeedRecord? feed = StorageFeed.Parse(StorageFeed.ToJson(Feed(0xFF123456u, "Aelrynth vault", vaultItem, coin)), out string error);
Check(feed != null && error == "", "a sender's payload parses: " + error);
StorageRecord rec = ExternalStorage.ToRecord(feed!, Now);
Eq(rec.Id, 0xFF123456u, "id kept");
Eq(rec.Name, "Aelrynth vault", "name"); Eq(rec.Label, "Account vault", "label"); Eq(rec.Cell, 0u, "no cell (not a place in the world)");
Eq(rec.SeenUtc, Now, "seen now");
Eq(rec.Items.Count, 2, "items");
ItemRecord a = rec.Items[0];
Eq(a.Name, "Acid Assagai", "name"); Eq(a.Icon, 100667000u, "icon"); Eq(a.Underlay, 100667001u, "underlay");
Eq(a.Overlay, 100667002u, "overlay"); Eq(a.Stack, 3, "stack"); Eq(a.MaxStack, 100, "max stack");
Eq(a.Place, ItemPlace.Storage, "place");
Eq(a.Category, ItemCategory.FromItemType(1), "category from the item type");
Eq(rec.Items[1].Stack, 1, "a stack of 0 is a stack of 1");
// Filed with the character's storage: the same id replaces, a new one adds.
var storage = new List<StorageRecord> { new() { Id = 77, Name = "Chest", Label = "Chest", Items = { Item(1, "Sword") } } };
List<StorageRecord> once = ExternalStorage.FileInto(storage, rec);
Eq(once.Count, 2, "added beside the opened chest");
StorageRecord newer = ExternalStorage.ToRecord(Feed(0xFF123456u, "Aelrynth vault", coin), Now.AddMinutes(10));
List<StorageRecord> twice = ExternalStorage.FileInto(once, newer);
Eq(twice.Count, 2, "the newer copy replaces the older");
Eq(twice.Single(s => s.Id == 0xFF123456u).Items.Count, 1, "with its own contents");
Eq(storage.Count, 1, "the old list is left alone (snapshots are never changed)");
// Anything unusable is refused, never filed.
Check(StorageFeed.Parse(null, out _) == null && StorageFeed.Parse("", out _) == null, "empty");
Check(StorageFeed.Parse("{not json", out string bad) == null && bad.StartsWith("bad JSON", StringComparison.Ordinal), "broken JSON");
Check(StorageFeed.Parse("{\"v\":1,\"id\":77,\"name\":\"Chest\",\"items\":[]}", out string real) == null && real.Contains("stand-in"),
"a real object's id can't be overwritten");
Check(StorageFeed.Parse("{\"v\":2,\"id\":4278190081,\"name\":\"X\",\"items\":[]}", out _) == null, "a newer format is refused");
Check(StorageFeed.Parse("{\"v\":1,\"id\":4278190081,\"name\":\" \",\"items\":[]}", out _) == null, "a store needs a name");
string many = "{\"v\":1,\"id\":4278190081,\"name\":\"X\",\"items\":[" + string.Join(",", Enumerable.Repeat("{\"o\":1}", StorageFeed.MaxItems + 1)) + "]}";
Check(StorageFeed.Parse(many, out _) == null, "too many items");
// The receiver: only "storage" is taken, and only the newest few are kept until the tick files them.
var plugin = new RynthInventoryPlugin();
string json = StorageFeed.ToJson(Feed(0xFF000001u, "Aelrynth vault", coin));
plugin.ApplyRemoteCommand("something-else", json);
Eq(StoragePushes(plugin).Count, 0, "other commands are ignored");
plugin.ApplyRemoteCommand("storage", "");
Eq(StoragePushes(plugin).Count, 0, "an empty payload is ignored");
for (int i = 0; i < 20; i++) plugin.ApplyRemoteCommand("storage", json);
Check(StoragePushes(plugin).Count is > 0 and <= 8, $"queued, capped ({StoragePushes(plugin).Count})");
// Nothing of any one server's store is left in RynthInventory itself.
var asm = typeof(RynthInventoryPlugin).Assembly;
Check(asm.GetType("RynthCore.Plugin.RynthInventory.Scanning.VaultFeed") == null, "no vault reader (/mule-data) in RynthInventory");
Check(typeof(RynthInventoryPlugin).GetMethod(nameof(RynthInventoryPlugin.OnChatWindowText))!.DeclaringType != typeof(RynthInventoryPlugin),
"RynthInventory doesn't read chat (nothing to ask a server for, nothing to hide)");
}
}
}

View file

@ -1,157 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthInventory.Data;
using RynthCore.Plugin.RynthInventory.Scanning;
namespace RynthInventory.Tests
{
// The Aelrynth account vault: /mule-data answers, one "~ael1" line a page (Aeshnidae.Mule MuleData.cs).
internal static partial class Program
{
private static string VaultPage(int page, int pages, int count, string items, bool ready = true, string why = "") =>
ready
? "~ael1 {\"t\":\"mule\",\"ready\":true,\"page\":" + page + ",\"pages\":" + pages + ",\"count\":" + count + ",\"max\":1000,\"items\":[" + items + "]}"
: "~ael1 {\"t\":\"mule\",\"ready\":false,\"why\":\"" + why + "\"}";
private static (VaultFeed Feed, List<string> Sent) NewVault()
{
var sent = new List<string>();
return (new VaultFeed(t => { sent.Add(t); return true; }), sent);
}
private static void VaultTests()
{
const string A = "{\"o\":2147483649,\"w\":100,\"n\":\"Acid Assagai\",\"i\":100667000,\"u\":100667001,\"v\":100667002,\"s\":3,\"m\":100,\"y\":1,\"e\":1}";
const string B = "{\"o\":2147483650,\"w\":101,\"n\":\"Pyreal\",\"i\":100667003,\"y\":8192}";
// Two pages, asked one after the other, filed as one record.
{
(VaultFeed v, List<string> sent) = NewVault();
Check(v.Ask(1000), "ask starts");
Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "page 1 asked first");
Check(v.ShouldEat(VaultPage(1, 2, 2, A)), "page 1 is eaten");
v.Tick(1100, "Tom");
Eq(sent.Count == 2 ? sent[1] : "?", "/mule-data 2", "page 2 asked when page 1 came");
Check(v.Record == null, "nothing filed before the last page");
Check(v.ShouldEat(VaultPage(2, 2, 2, B)), "page 2 is eaten");
v.Tick(1200, "Tom");
StorageRecord? r = v.Record;
Check(r != null && v.TakeChanged() && !v.TakeChanged(), "filed once");
Eq(r?.Items.Count ?? -1, 2, "both pages' items");
Eq(r?.Id ?? 0, VaultFeed.VaultId("tom"), "id follows the account, case-blind");
Check((r?.Id ?? 0) >> 24 == 0xFF, "id is a stand-in, far from real objects");
Eq(r?.Label ?? "", "Account vault", "label");
ItemRecord a = r!.Items[0];
Eq(a.Name, "Acid Assagai", "name"); Eq(a.Icon, 100667000u, "icon"); Eq(a.Underlay, 100667001u, "underlay");
Eq(a.Overlay, 100667002u, "overlay"); Eq(a.Stack, 3, "stack"); Eq(a.MaxStack, 100, "max stack");
Eq(a.Place, ItemPlace.Storage, "place");
Eq(r.Items[1].Stack, 1, "no stack field is a stack of 1");
Eq(v.Status, VaultFeed.State.Idle, "idle again");
}
// Other plugins' lines are left alone.
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
Check(!v.ShouldEat("~ael1 {\"t\":\"inspect\",\"ok\":true}"), "the Companion's line stays visible");
Check(!v.ShouldEat("Welcome to Aelrynth"), "ordinary chat stays visible");
Check(!v.ShouldEat(null), "null is fine");
}
// A player imitating the server: their name is in front, or the chat type is theirs.
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
Check(!v.ShouldEat("Bob says, \"" + VaultPage(1, 1, 1, A) + "\"", 2), "spoken data line is not ours");
Check(!v.ShouldEat("Bob " + VaultPage(1, 1, 1, A), 12), "an emoted data line is not ours");
Check(!v.ShouldEat("Bob " + VaultPage(1, 1, 1, A)), "a data line not at the start is not ours, type unknown");
Check(!v.ShouldEat(VaultPage(1, 1, 1, A), 3), "a data line in a tell is not ours");
Check(!v.ShouldEat("Bob tells you, \"Unknown command: mule-data\"", 3), "a told unknown-command line is not ours");
Check(!v.ShouldEat("Unknown command: mule-data", 2), "unknown-command in speech is not ours");
Check(!v.ShouldEat("Unknown command: mule-data-ish"), "another command's refusal is not ours");
Check(v.ShouldEat("Unknown command: mule-data", 15), "ACE's real reply (Help) is ours");
}
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
Check(v.ShouldEat(" " + VaultPage(1, 1, 1, A), 0), "the server's line (Broadcast), leading space allowed");
}
// A server without the command.
{
(VaultFeed v, List<string> sent) = NewVault();
v.Ask(0);
Check(v.ShouldEat("Unknown command: /mule-data"), "the unknown-command reply is eaten while we wait");
v.Tick(100, "tom");
Eq(v.Status, VaultFeed.State.Unsupported, "unsupported");
Check(!v.Ask(200), "not asked again");
Eq(sent.Count, 1, "one probe, no more");
Check(v.Ask(300, force: true), "/ginv vault asks anyway");
}
{
(VaultFeed v, _) = NewVault();
Check(!v.ShouldEat("Unknown command: /mule-data"), "an unknown-command line we did not provoke is left alone");
}
// A vault the server is still loading is asked again, and never recorded as empty.
{
(VaultFeed v, List<string> sent) = NewVault();
v.Ask(0);
v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading"));
v.Tick(10, "tom");
Eq(v.Status, VaultFeed.State.Waiting, "waiting");
v.Tick(2000, "tom");
Eq(sent.Count, 1, "not before the retry delay");
v.Tick(3500, "tom");
Eq(sent.Count, 2, "asked again after it");
Check(v.Record == null, "never recorded");
for (int i = 0; i < 10; i++)
{
v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading"));
v.Tick(4000 + i * 4000, "tom");
}
Check(v.Status != VaultFeed.State.Asking || sent.Count < 12, "it gives up after a few tries");
Check(v.Record == null, "still never recorded");
}
// A vault that changed between pages is read again, not filed half and half.
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
v.ShouldEat(VaultPage(1, 2, 3, A));
v.Tick(10, "tom");
v.ShouldEat(VaultPage(2, 2, 3, B)); // 2 read, the server says 3
v.Tick(20, "tom");
Check(v.Record == null, "a mismatched read is not filed");
Eq(v.Status, VaultFeed.State.Waiting, "and is retried");
}
// Silence is an idle feed, not a stuck one.
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
v.Tick(20_000, "tom");
Eq(v.Status, VaultFeed.State.Idle, "no answer in time");
Check(v.Ask(21_000), "can ask again");
}
// A line typed by hand while we are not asking is eaten (it is ours) but changes nothing.
{
(VaultFeed v, _) = NewVault();
Check(v.ShouldEat(VaultPage(1, 1, 1, A)), "eaten");
v.Tick(0, "tom");
Check(v.Record == null, "ignored when we did not ask");
}
// Garbage inside a mule line does not throw.
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
v.ShouldEat("~ael1 {\"t\":\"mule\",\"ready\":tru");
v.Tick(5, "tom");
Check(v.Record == null && v.Status == VaultFeed.State.Idle, "bad JSON drops the read");
}
}
}
}

View file

@ -0,0 +1,177 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthNav;
namespace RynthNav.RouteTests;
// The goto's autorun (AutoRunGate): on 10-19 a /rnav go "Matron Hive East" sent SetAutoRun about
// 55 times a second (settling after the recall, turning at the portal, walking the Town Network)
// and filled the engine's action ring in portal space. Now sent when it changes.
internal static partial class Program
{
private static void RunAutoRunGate()
{
Run(nameof(TurnInPlaceSendsOffOnce), TurnInPlaceSendsOffOnce);
Run(nameof(RunningReassertsTwiceASecond), RunningReassertsTwiceASecond);
Run(nameof(SettleAfterATeleportSendsNothingMore), SettleAfterATeleportSendsNothingMore);
Run(nameof(HoldHaltsOnce), HoldHaltsOnce);
Run(nameof(TurnGateFlipsSendEachChange), TurnGateFlipsSendEachChange);
Run(nameof(RefusedCallIsRetriedNotEveryTick), RefusedCallIsRetriedNotEveryTick);
Run(nameof(NewGotoSendsAgain), NewGotoSendsAgain);
Run(nameof(MatronHiveTripReplay), MatronHiveTripReplay);
}
private const long GateTickMs = 18; // the plugin tick on 10-19: ~55 a second
/// <summary>The host's SetAutoRun/StopCompletely, counted; Accept = false refuses them (a full action ring).</summary>
private sealed class FakeMover
{
public long Now = 1_000_000;
public bool Accept = true;
public int On, Off, Stops, Tries;
public readonly AutoRunGate Gate;
public FakeMover()
{
Gate = new AutoRunGate(
on => { Tries++; if (!Accept) return false; if (on) On++; else Off++; return true; },
() => { Tries++; if (!Accept) return false; Stops++; return true; },
() => Now);
}
public int Sent => On + Off + Stops;
/// <summary><paramref name="each"/> once a tick for <paramref name="ms"/>.</summary>
public void For(long ms, Action each)
{
for (long end = Now + ms; Now < end; Now += GateTickMs) each();
}
}
private static void TurnInPlaceSendsOffOnce()
{
// At the Town Network portal (16:38:46): turning in place, SetAutoRun(False) every tick.
var m = new FakeMover();
m.For(4000, () => m.Gate.Run(false));
Check(m.Off == 1 && m.On == 0 && m.Stops == 0, $"4 s turning in place: one SetAutoRun(False) (sent {m.Off}/{m.On}/{m.Stops})");
}
private static void RunningReassertsTwiceASecond()
{
// Running: "on" goes out once, then again every ReassertMs (a cast or a server stop can
// turn autorun off without telling the goto).
var m = new FakeMover();
m.For(3000, () => m.Gate.Run(true));
long ticks = 3000 / GateTickMs + 1;
Check(m.On >= 3000 / AutoRunGate.ReassertMs && m.On <= 3000 / AutoRunGate.ReassertMs + 1,
$"3 s running: {m.On} SetAutoRun(True), one every {AutoRunGate.ReassertMs} ms (was {ticks}, one a tick)");
Check(m.Off == 0 && m.Stops == 0, "nothing else sent while running");
}
private static void SettleAfterATeleportSendsNothingMore()
{
// The recall lands (Stop), then portal space and the settle: SetAutoRun(False) every tick
// for 7.5 s (16:38:38-16:38:46).
var m = new FakeMover();
m.Gate.Stop();
m.For(7500, () => m.Gate.Run(false));
Check(m.Off == 1 && m.Stops == 1 && m.On == 0, $"teleport + 7.5 s settle: just the Stop (sent {m.Off}/{m.Stops}/{m.On})");
}
private static void HoldHaltsOnce()
{
// The Town Network landing wait and the exit hold: SetAutoRun(False) + StopCompletely every tick.
var m = new FakeMover();
m.For(2000, () => m.Gate.Halt());
Check(m.Off == 1 && m.Stops == 1, $"2 s holding: one halt (sent {m.Off}/{m.Stops})");
m.Gate.Run(true);
Check(m.On == 1, "running after the hold goes out");
m.Gate.Halt();
Check(m.Off == 2 && m.Stops == 2, "a hold after running halts again");
m.Gate.Run(false);
Check(m.Off == 2, "autorun is already off after a halt");
m.Gate.Stop();
Check(m.Off == 3 && m.Stops == 3, "Stop always sends (a goto's end, a teleport)");
}
private static void TurnGateFlipsSendEachChange()
{
// DriveTo's stop-to-turn hysteresis: every flip is a change and goes out at once.
var m = new FakeMover();
foreach (bool on in new[] { true, true, false, false, false, true, false })
{
m.Gate.Run(on);
m.Now += GateTickMs;
}
Check(m.On == 2 && m.Off == 2, $"run, turn, run, turn: four sends (sent {m.On} on, {m.Off} off)");
}
private static void RefusedCallIsRetriedNotEveryTick()
{
// The engine refuses a call (its action ring full): not taken as sent, tried again after
// RetryMs instead of every tick.
var m = new FakeMover { Accept = false };
m.For(1000, () => m.Gate.Run(false));
Check(m.Off == 0, "nothing went through");
Check(m.Tries >= 2 && m.Tries <= 1000 / AutoRunGate.RetryMs + 1, $"1 s refused: {m.Tries} tries, not one a tick");
m.Accept = true;
m.For(1000, () => m.Gate.Run(false));
Check(m.Off == 1, $"once it's accepted it goes out once (sent {m.Off})");
var h = new FakeMover { Accept = false };
h.For(1000, () => h.Gate.Halt());
Check(h.Tries >= 2 && h.Tries <= 2 * (1000 / AutoRunGate.RetryMs + 1), $"refused halt: {h.Tries} tries in 1 s");
h.Accept = true;
h.For(1000, () => h.Gate.Halt());
Check(h.Off == 1 && h.Stops == 1, "the halt goes out once accepted");
}
private static void NewGotoSendsAgain()
{
// Between gotos the d-pad or another plugin may have moved the character: Forget, and the
// first call of the new goto goes out even if it's the same as the last one sent.
var m = new FakeMover();
m.Gate.Run(false);
m.Gate.Forget();
m.Gate.Run(false);
Check(m.Off == 2, "after Forget the same state is sent again");
m.Gate.Halt();
m.Gate.Forget();
m.Gate.Halt();
Check(m.Stops == 2, "after Forget a halt is sent again");
}
private static void MatronHiveTripReplay()
{
// The 10-19 trip's movement calls in order (RynthNav's tick, ~55 a second), from the
// goto's start to the Baishi landing. Each phase is what the code asks for every tick.
var m = new FakeMover();
int asks = 0;
var phases = new List<(long ms, Action tick)>
{
(0, () => m.Gate.Stop()), // recall step: stop before the cast
(2300, () => { }), // casting (no movement calls)
(0, () => m.Gate.Stop()), // the recall's teleport
(7900, () => m.Gate.Run(false)), // settle: portal space and the quiet second
(4000, () => m.Gate.Run(false)), // turning to the Town Network portal
(600, () => m.Gate.Run(true)), // running at it
(1800, () => m.Gate.Run(false)), // within reach: standing, using it
(0, () => m.Gate.Stop()), // its teleport
(8000, () => m.Gate.Halt()), // landing in the Town Network (portal space, settle)
(5000, () => m.Gate.Run(true)), // the walk to the Baishi portal
(300, () => m.Gate.Run(false)), // a turn in place on the way
(5000, () => m.Gate.Run(true)),
(300, () => m.Gate.Halt()), // at the exit
(0, () => m.Gate.Stop()), // Baishi's teleport
(6000, () => m.Gate.Run(false)), // its portal space
};
foreach (var (ms, tick) in phases)
{
if (ms == 0) { tick(); asks++; continue; }
for (long end = m.Now + ms; m.Now < end; m.Now += GateTickMs) { tick(); asks++; }
}
Check(asks > 2000, $"the replay asks every tick ({asks} asks)");
Check(m.Sent < 60, $"the trip sent {m.Sent} movement calls for {asks} asks (10-19: ~4,460 SetAutoRun and 97 StopCompletely)");
Check(m.On <= 2 + 2 * (10000 / AutoRunGate.ReassertMs + 1), $"running sent {m.On} SetAutoRun(True)");
}
}

View file

@ -58,6 +58,7 @@ internal static partial class Program
RunAvoid();
RunTravelPlan();
RunTripExport();
RunAutoRunGate();
Console.WriteLine();
Console.WriteLine(_fails == 0 && _asserts > 0

View file

@ -28,6 +28,8 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TownNet.cs" Link="Linked\TownNet.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\PortalAvoid.cs" Link="Linked\PortalAvoid.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TravelPlan.cs" Link="Linked\TravelPlan.cs" />
<!-- The goto's autorun, sent when it changes (AutoRunGateTests). -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\AutoRunGate.cs" Link="Linked\AutoRunGate.cs" />
<!-- The planned trip, its path, the path markers and "save as nav route" (TripExportTests). -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPlan.cs" Link="Linked\TripPlan.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPath.cs" Link="Linked\TripPath.cs" />

View file

@ -0,0 +1,872 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using RynthCore.Plugin.RynthOracle;
using RynthCore.Plugin.RynthOracle.Data;
using RynthCore.Plugin.RynthOracle.Ui;
using RynthCore.Plugin.RynthOracle.Views;
using IltBreedingView = RynthCore.Plugin.Shared.IltBreedingView;
using IltGuardianView = RynthCore.Plugin.Shared.IltGuardianView;
namespace RynthOracle.Tests
{
// The 0.3.0 port of SilentKelpie's RynthOracle 0.6.0 (RynthSuite PR 12): the merged Quests list
// (Legendary, Markers, Dynamic Stamps and Temple guardians), Go to, the Give Parchment gate, the two
// CSV loaders, the RynthILT profile and the Charms / Pet Breeding pieces. Ported from his tests where
// they fit, adapted where our tree differs (the Refresh row, the Mini Remote keeping its tabs), and
// added for what the merge must keep (favourites, click-to-print, the Markers tab's content).
internal static partial class Program
{
// ── Helpers ──────────────────────────────────────────────────────────
private static uint _seq = 5000;
private static string Body(UiWindow w) => Encoding.UTF8.GetString(w.Body);
/// <summary>One draw of the main window, parsed by the engine's own parser (ops under the limit), body returned.</summary>
private static string Frame(UiHost host, UiWindow main, OracleView view, string what, out int ops)
{
main.Begin(); view.Draw(main); main.End();
ParseAll(host, what, out ops);
string body = Body(main);
main.MarkSubmitted(true);
return body;
}
private static string Frame(UiHost host, UiWindow main, OracleView view, string what) => Frame(host, main, view, what, out _);
private static void Click(UiHost host, UiWindow w, string id) => Apply(host, Event(1, ++_seq, w.Hash, w.KeyOf(id), new byte[] { 1, 0, 0 }));
private static void Tick(UiHost host, UiWindow w, string id, bool on) => Apply(host, Event(2, ++_seq, w.Hash, w.KeyOf(id), new byte[] { (byte)(on ? 1 : 0) }));
private static void Type(UiHost host, UiWindow w, string id, string text)
{
byte[] t = Encoding.UTF8.GetBytes(text);
var payload = new byte[3 + t.Length];
BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(1), (ushort)t.Length);
t.CopyTo(payload, 3);
Apply(host, Event(5, ++_seq, w.Hash, w.KeyOf(id), payload));
}
/// <summary>A context on a given server (a tag, or "" for retail) with the retail catalog loaded.</summary>
private static OracleContext On(string tag)
{
OracleContext c = Context();
c.Server.Force(tag, tag.Length > 0 ? tag : "Coldeve");
c.Catalog.Load(tag, null);
c.Catalog.SyncDiscoveries(c.Flags);
return c;
}
// ── The CSV lists ────────────────────────────────────────────────────
/// <summary>The Legendary list (legendary.csv) and its have / missing / timer rules.</summary>
private static void Legendary()
{
Check(LegendaryList.All.Count == 40, $"legendary quests: {LegendaryList.All.Count} (40 expected)");
Check(LegendaryList.Groups.SequenceEqual(new[] { "Graveyard", "Rynthid", "Hoshino", "Frozen Valley", "Neftet", "Random Locations" }),
"legendary groups: " + string.Join(",", LegendaryList.Groups));
Check(LegendaryList.All.All(q => q.Flags.Length > 0 && q.Luminance > 0), "every legendary quest has a flag and luminance");
var catalog = new QuestCatalog();
catalog.Load("", _ => { });
var unknown = LegendaryList.All.SelectMany(q => q.Flags).Where(f => !catalog.TryGet(f, out _)).ToList();
Check(unknown.Count == 0, "every legendary flag is a known quest flag: " + string.Join(",", unknown));
LegendaryQuest rtw = LegendaryList.All.First(q => q.CommonName == "RTW");
Check(rtw.Flags[0] == "rtwcompleted_1013" && rtw.Label == "Defeating the Curator of Torment (RTW)", "RTW row: " + rtw.Label);
var lf = new QuestFlagStore();
long t = 900_000;
long done = DateTimeOffset.UtcNow.AddHours(-2).ToUnixTimeSeconds();
long old = DateTimeOffset.UtcNow.AddDays(-3).ToUnixTimeSeconds();
// RTW done 2 h ago on a 20 h timer; End of Days done 3 days ago (ready); Lugian Assault never.
lf.OnChatLine($"rtwcompleted_1013 - 4 solves ({done})\"RTW\" -1 72000", t);
lf.OnChatLine($"eodcompleted_1013 - 1 solves ({old})\"EoD\" -1 72000", t + 1);
lf.OnChatLine($"legendaryquestcounter_0913 - 12 solves ({old})\"John\" -1 0", t + 2);
lf.Tick(t + 5_000);
DateTime now = DateTime.UtcNow;
TimeSpan? rtwLeft = rtw.TimeLeft(lf, now);
Check(rtw.Have(lf) && rtwLeft is { } l && l.TotalHours > 17.9 && l.TotalHours < 18.1, $"RTW: done, ~18 h left ({rtwLeft})");
LegendaryQuest eod = LegendaryList.All.First(q => q.CommonName == "EoD");
Check(eod.Have(lf) && eod.Status(lf, now) == "ready", "EoD: done, timer up -> ready: " + eod.Status(lf, now));
LegendaryQuest la = LegendaryList.All.First(q => q.CommonName == "LA");
Check(!la.Have(lf) && la.TimeLeft(lf, now) == null && la.Status(lf, now) == "missing", "Lugian Assault: missing");
Check(LegendaryList.JohnCount(lf) == 12, "John's counter read: " + LegendaryList.JohnCount(lf));
Check(LegendaryList.JohnCount(new QuestFlagStore()) == null, "no counter on a fresh character");
// A quest with a second timer flag: the longest wait of the two counts.
LegendaryQuest erq = LegendaryList.All.First(q => q.Name == "Empyrean Rescue Quest");
var ef = new QuestFlagStore();
ef.OnChatLine($"empyreanrescuecompleted_1010 - 1 solves ({old})\"ERQ\" -1 0", t);
ef.OnChatLine($"erqlegkeypickuptimer - 1 solves ({done})\"key\" -1 36000", t + 1);
ef.Tick(t + 5_000);
TimeSpan? erqLeft = erq.TimeLeft(ef, now);
Check(erqLeft is { } e && e.TotalHours > 7.9 && e.TotalHours < 8.1, $"ERQ: key pickup timer decides (~8 h): {erqLeft}");
}
/// <summary>The Dynamic Stamps list (dynstamps.csv), its have / missing rules, RynthNav targets and the Go to parser.</summary>
private static void DynamicStamps()
{
var all = DynamicStampList.All;
Check(all.Count == 243, $"dynamic stamps: {all.Count} (243 expected from the ExtraDyn sheet)");
Check(DynamicStampList.Areas.Count == 17 && DynamicStampList.Areas[0] == "Facility Hub" && DynamicStampList.Areas[^1] == "Candeth Keep",
"dynamic areas: " + string.Join(",", DynamicStampList.Areas));
Check(all.All(s => s.Stamp.StartsWith("dynamic_") && s.Stamp == s.Stamp.ToLowerInvariant()), "every stamp is a lower-case dynamic_ flag");
Check(all.Select(s => s.Stamp).Distinct().Count() == all.Count, "no stamp listed twice");
Check(all.All(s => s.Label.Length > 0), "every row names an NPC or a place");
DynamicStamp felscuda = all.First(s => s.Npc == "Felscuda");
Check(felscuda.Stamp == "dynamic_1_&9jiytb!" && felscuda.Place == "Folthid Cellar" && felscuda.Reward == "Healing Rabbit Pie"
&& felscuda.Note == "8.8S, 53.1E", $"Felscuda row: {felscuda.Place} / {felscuda.Reward} / {felscuda.Note}");
// /myquests keys flags as \S+ lower case, so the stamps' ! & # ^ $ survive.
var f = new QuestFlagStore();
long t = 900_000, at = DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds();
f.OnChatLine($"Dynamic_1_&9jiyTB! - 1 solves ({at})\"Dynamic\" 1 0", t);
f.OnChatLine($"Dynamic_1_ANND! - 1 solves ({at})\"Dynamic\" 1 0", t + 1); // the sheet lost the closing !
f.OnChatLine($"Dynamic_1_ZZZnewNPC! - 1 solves ({at})\"Dynamic\" 1 0", t + 2); // not on the sheet
f.OnChatLine($"rtwcompleted_1013 - 1 solves ({at})\"RTW\" -1 72000", t + 3);
f.Tick(t + 5_000);
Check(felscuda.Have(f), "Felscuda's stamp read from /myquests");
DynamicStamp annd = all.First(s => s.Stamp == "dynamic_1_annd");
Check(annd.Have(f) && annd.MatchedFlag(f) == "dynamic_1_annd!", "a stamp the sheet lost its ! on still matches");
Check(!all.First(s => s.Npc == "Raxanza Folthid").Have(f), "an NPC not done is missing");
List<string> extra = DynamicStampList.Unlisted(f);
Check(extra.Count == 1 && extra[0] == "dynamic_1_zzznewnpc!", "unlisted: only the stamp the sheet doesn't have: " + string.Join(",", extra));
DynamicStamp shortStamp = all.First(s => s.Stamp == "dynamic_1_s");
var sf = new QuestFlagStore();
sf.OnChatLine($"Dynamic_1_SomethingElse! - 1 solves ({at})\"Dynamic\" 1 0", t);
sf.Tick(t + 5_000);
Check(!shortStamp.Have(sf), "a cut-short stem under 14 characters isn't matched by prefix");
// RynthNav targets, best first (RynthNav takes the first on its map).
Check(string.Join(" | ", felscuda.NavCandidates()) == "8.8S, 53.1E | Folthid Cellar | Felscuda | Facility Hub",
"Felscuda nav: " + string.Join(" | ", felscuda.NavCandidates()));
var gerent = new DynamicStamp { Area = "Graveyard", Place = "Gerent's Compound at 87.2S, 17.5W", Npc = "Gerent" };
Check(string.Join(" | ", gerent.NavCandidates()) == "87.2S, 17.5W | Gerent's Compound | Gerent | Graveyard",
"coordinates inside the place, 'at' dropped: " + string.Join(" | ", gerent.NavCandidates()));
var lost = new DynamicStamp { Area = "Odd Stamps", Place = "Lost Wish Cottages (Arwic) 42.6n 62.4e", Npc = "Bob" };
Check(string.Join(" | ", lost.NavCandidates()) == "42.6N, 62.4E | Lost Wish Cottages (Arwic) | Lost Wish Cottages | Arwic",
"lower-case n/e, a bracketed town, no grouping area, a 3-letter NPC left out: " + string.Join(" | ", lost.NavCandidates()));
var mhoire = new DynamicStamp { Area = "Looking Around", Place = "Mhoire Castle - Great Hall" };
Check(string.Join(" | ", mhoire.NavCandidates()) == "Mhoire Castle - Great Hall | Mhoire Castle | Great Hall",
"a place's parts: " + string.Join(" | ", mhoire.NavCandidates()));
Check(all.Count(s => s.NavCandidates().Count > 0) >= 200, "most stamps have somewhere to go: " + all.Count(s => s.NavCandidates().Count > 0));
}
/// <summary>Coordinates in a quest's notes become RynthNav targets (Go to).</summary>
private static void GoToParsing()
{
var grael = NavTargets.Stops("Give Progenitor's Ichor to Hoshar. - Speak with Hoshar ibn Jalaq 59.6S 88.0W - Kill Mukkir Progenitor 86.5N 57.3E"
+ " - Speak with Hoshar ibn Jalaq - Abyssal Totem Gateway 86.5N 57.3E - Abyssal Totem Temple 86.5N 57.3E");
Check(string.Join(" | ", grael.ConvertAll(s => s.Display)) == "Speak with Hoshar ibn Jalaq - 59.6S, 88.0W | Kill Mukkir Progenitor - 86.5N, 57.3E",
"Splitting Grael stops: " + string.Join(" | ", grael.ConvertAll(s => s.Display)));
Check(grael[0].Target == "59.6S, 88.0W Speak with Hoshar ibn Jalaq", "a stop's RynthNav target is the coordinates, then its label");
var shadow = NavTargets.Stops("Xarabydun 41.8S 15.8E - Speak with Ciandra Arcanum Alchemist - Empyrean Workshop 66.9N 15.9E - Cragstone 26.0N 47.0E Speak with Bretself the Translator - Xarabydun - Shade of Farelaith 74.3N 58.6E");
Check(string.Join(" | ", shadow.ConvertAll(s => s.Label)) == "Xarabydun | Empyrean Workshop | Cragstone | Shade of Farelaith",
"Shadowfire Stone labels: " + string.Join(" | ", shadow.ConvertAll(s => s.Label)));
Check(NavTargets.Stops("Kill 20 drudges near Holtburg.").Count == 0, "no coordinates: no stops");
Check(NavTargets.Stops(null).Count == 0 && NavTargets.Stops("").Count == 0, "no text: no stops");
Check(NavTargets.Stops("Meet at 42.6n 62.4e").Count == 1 && NavTargets.Stops("Meet at 42.6n 62.4e")[0].Display == "Meet - 42.6N, 62.4E",
"lower-case letters; 'at' dropped from the label");
Check(NavTargets.FirstCoords("go to 8.8S, 53.1E now") == "8.8S, 53.1E" && NavTargets.FirstCoords("nowhere") == null, "the first coordinates in a text");
Check(NavTargets.WithoutCoords("Hall 8.8S, 53.1E door").Contains("Hall") && !NavTargets.WithoutCoords("Hall 8.8S, 53.1E door").Contains("53.1"),
"the text without its coordinates");
Check(NavTargets.Place(" Holtburg ").Target == "Holtburg", "a named place is its own target");
}
/// <summary>Both CSV loaders: counts from the shipped files, and a malformed file doesn't cost the good rows.</summary>
private static void Loaders()
{
// The shipped files: counts, and they are embedded resources (the way the other lists are).
Check(LegendaryList.All.Count == 40 && DynamicStampList.All.Count == 243, "the shipped lists load: 40 Legendary quests, 243 stamps");
Check(MarkerList.All.Count == 100, "the shipped marker list still has its 100 markers");
var rows = LegendaryList.Parse(new StringReader(
"Group,Quest,CommonName,Luminance,Flags,Url,Note,Video\n"
+ "\"G\",\"Good\",\"GD\",5000,\"a_flag;B_Flag\",\"https://x\",\"a note, with a comma\",\"\"\n"
+ "\"G\",\"\",\"\",1,\"x\",\"\",\"\",\"\"\n" // no quest name: skipped
+ "\"G\",\"ShortRow\",\"\",abc\n" // short row, luminance isn't a number
+ "\n"
+ "just one field\n"
+ "\"G\",\"After\",\"\",7,\"c_flag\"\n"));
Check(rows.Count == 3 && rows[0].Name == "Good" && rows[1].Name == "ShortRow" && rows[2].Name == "After",
"legendary: bad rows skipped, the rest kept: " + string.Join(",", rows.Select(r => r.Name)));
Check(rows[0].Flags.SequenceEqual(new[] { "a_flag", "b_flag" }) && rows[0].Luminance == 5000 && rows[0].Note == "a note, with a comma"
&& rows[0].Label == "Good (GD)", "legendary: flags lower-cased and split, quoted commas kept, the short name in the label");
Check(rows[1].Luminance == 0 && rows[1].Flags.Length == 0 && rows[1].Url == "", "legendary: a short row reads as empty, luminance 0");
Check(LegendaryList.Parse(new StringReader("")).Count == 0 && LegendaryList.Parse(new StringReader("Group,Quest\n")).Count == 0,
"legendary: an empty file is an empty list");
Check(LegendaryList.Parse(new StringReader("Quest\r\nCRLF Quest\r\n")).Single().Name == "CRLF Quest", "legendary: CRLF lines");
var stamps = DynamicStampList.Parse(new StringReader(
"Area,Place,Npc,Reward,Stamp,Note\n"
+ "\"A\",\"P\",\"Npc1\",\"R\",\"Dynamic_1_Abc!\",\"8.8S, 53.1E\"\n"
+ "\"A\",\"P\",\"Dup\",\"R\",\"dynamic_1_abc!\",\"\"\n" // the same stamp again: skipped
+ "\"A\",\"P\",\"NotDyn\",\"R\",\"something_else\",\"\"\n" // not a dynamic_ flag: skipped
+ "\"A\",\"P\",\"Short\"\n" // no stamp column: skipped
+ "\n"
+ "\"B\",\"\",\"\",\"\",\"Dynamic_2_x\",\"\"\n"));
Check(stamps.Count == 2 && stamps[0].Stamp == "dynamic_1_abc!" && stamps[1].Stamp == "dynamic_2_x",
"dynamic: bad and repeated rows skipped, the rest kept: " + string.Join(",", stamps.Select(s => s.Stamp)));
Check(stamps[0].Npc == "Npc1" && stamps[0].Note == "8.8S, 53.1E" && stamps[1].Label == "", "dynamic: fields read, a missing NPC and place leave an empty label");
Check(DynamicStampList.Parse(new StringReader("")).Count == 0, "dynamic: an empty file is an empty list");
// The markers file is the existing loader; a marker row still parses to its flag bit.
Marker m = MarkerList.All[0];
Check(m.Number == 1 && m.Flag.StartsWith("explorationmarkersfoundingroup") && m.BitMask == 1, "marker 1 keeps its quest flag bit");
}
// ── RynthILT's profile, charms and pet breeding ──────────────────────
private const string QbProfileJson = "{\"ilt\":true,\"world\":\"InfiniteLeaftide\",\"fellowship\":{\"maxMembers\":29},"
+ "\"questBonus\":{\"disabled\":false,\"generation\":3,\"count\":41,\"status\":\"2 completed, 1 incomplete\","
+ "\"completed\":[\"qbflagone\",\"qbflagtwo\"],\"incomplete\":[\"qbflagthree\"]}}";
/// <summary>RynthILT's "RynthILT.Server" profile JSON as the Quests, About and Pet Breeding pages read it.</summary>
private static void IltProfile()
{
const string json = "{\"ilt\":true,\"world\":\"InfiniteLeaftide\",\"forced\":false,\"source\":\"probe\",\"checked\":\"2026-10-13T21:25:37Z\","
+ "\"features\":[{\"key\":\"bank\",\"label\":\"Banking\",\"group\":\"Character\",\"state\":1,\"where\":\"Mini Remote > Banking tab\"},"
+ "{\"key\":\"zone_share\",\"label\":\"Zone Share\",\"group\":\"Fellowship\",\"state\":1,\"where\":\"server\"},"
+ "{\"key\":\"fellowship_blackjack\",\"label\":\"Fellowship Blackjack\",\"group\":\"Fellowship\",\"state\":0,\"where\":\"/fblackjack\"}],"
+ "\"fellowship\":{\"maxMembers\":29,\"zoneShare\":1,\"blackjack\":0,\"luminanceShare\":-1},\"later\":{\"x\":1}}";
IltServerProfile p = IltServerProfile.Parse(json);
Check(p.Available && p.Ilt && p.World == "InfiniteLeaftide" && p.Source == "probe", "ILT profile header");
Check(p.FellowshipMax == 29 && p.ZoneShare == 1 && p.Blackjack == 0 && p.LuminanceShare == -1, "ILT fellowship rules");
Check(p.Features.Count == 3 && p.InGroup("Fellowship").Count() == 2, $"ILT features: {p.Features.Count}");
Check(p.CheckedUtc == new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc), "checked time is UTC: " + p.CheckedUtc.ToString("o"));
IltServerProfile none = IltServerProfile.Parse("");
Check(!none.Available && none.FellowshipMax == 9, "no RynthILT: a retail fellowship");
Check(!IltServerProfile.Parse("not json").Available, "garbage is ignored");
Check(IltServerProfile.Parse("{\"ilt\":false}").FellowshipMax == 9, "an older profile without fellowship rules: retail size");
Check(IltServerProfile.Parse("{\"fellowship\":{\"maxMembers\":5000}}").FellowshipMax == 9, "an absurd size is not believed");
Check(IltServerProfile.StateText(1) == "on" && IltServerProfile.StateText(0) == "off" && IltServerProfile.StateText(-1) == "checking", "state words");
Check(p.QuestBonus == null, "no questBonus object: no /qb list");
IltServerProfile qb = IltServerProfile.Parse(QbProfileJson);
Check(qb.QuestBonus is { Disabled: false, Generation: 3, Count: 41 } b && b.Completed.Count == 2 && b.Incomplete.Count == 1
&& b.Incomplete[0] == "qbflagthree" && b.Status == "2 completed, 1 incomplete", "quest bonus list parsed");
// The identity: a Leaftide world name, RynthILT's own verdict, and RynthCore's "ilt" server all give the ILT tag.
Check(ServerIdentity.TagForWorld("InfiniteLeaftide") == ServerTags.InfiniteLeaftide, "InfiniteLeaftide");
Check(ServerIdentity.TagForWorld("Infinite Leaftide Staging") == ServerTags.InfiniteLeaftide, "a Leaftide staging world is ILT");
Check(ServerIdentity.TagForEngineId("ilt") == ServerTags.InfiniteLeaftide && ServerIdentity.EngineIdForTag(ServerTags.InfiniteLeaftide) == "ilt",
"RynthCore's ilt server <-> the ILT tag");
}
/// <summary>The About page's "Server features" list comes from RynthILT's profile.</summary>
private static void ServerFeatures()
{
OracleContext c = On(ServerTags.InfiniteLeaftide);
c.Settings.TabName = OracleView.TabAbout;
var view = new OracleView(c);
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
string body = Frame(host, main, view, "About, no RynthILT");
Check(body.Contains("Load RynthILT to list the Infinite Leaftide features here."), "ILT without RynthILT: says to load it");
c.Ilt.SetJson("{\"ilt\":true,\"world\":\"InfiniteLeaftide\",\"checked\":\"2026-10-13T21:25:37Z\","
+ "\"features\":[{\"key\":\"bank\",\"label\":\"Banking\",\"group\":\"Character\",\"state\":1,\"where\":\"Mini Remote > Banking tab\"},"
+ "{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":0,\"where\":\"Pets\"}]}");
body = Frame(host, main, view, "About, with RynthILT");
Check(body.Contains("Server features") && body.Contains("1 of 2 on.") && body.Contains("Character") && body.Contains("###o.feat.h.Pets"),
"the features RynthILT lists, grouped, with a count on");
Check(body.Contains("o.alert") && body.Contains("o.alertall") && body.Contains("o.readlogin"), "the About settings (quest alerts too) are all still there");
Check(body.Contains("/ro trackers") && body.Contains("/ro legendary") && body.Contains("/ro markers") && body.Contains("/ro guardians") && body.Contains("/ro breeding"),
"the About page lists the new commands on ILT");
}
private static string BreedingJson(int essences)
{
var sb = new StringBuilder("{\"available\":true,\"world\":\"InfiniteLeaftide\",\"enabled\":\"on\",\"maturity\":\"on\",\"bond\":\"on\","
+ "\"room\":\"landblock 0x0106 variant 2\",\"freeSlots\":12,\"message\":\"\",\"essences\":[");
for (int i = 0; i < essences; i++)
{
if (i > 0) sb.Append(',');
bool male = i % 2 == 0, ready = i < 2;
sb.Append("{\"id\":").Append(1000 + i).Append(",\"name\":\"Essence ").Append(i).Append("\",\"sex\":\"").Append(male ? 'M' : 'F')
.Append("\",\"tier\":125,\"bond\":100,\"ready\":").Append(ready ? "true" : "false")
.Append(",\"status\":\"").Append(ready ? "Ready" : "Rest 1h 05m").Append("\",\"readyIn\":").Append(ready ? 0 : 3900)
.Append(",\"charges\":7,\"chargesMax\":10,\"juvenile\":false,\"stage\":\"\",\"kills\":0,\"killsRequired\":300,")
.Append("\"mutations\":1,\"potencyMutations\":0,\"problems\":").Append(ready ? "[]" : "[\"resting after a breed\"]")
.Append(",\"boosters\":").Append(i == 0 ? "[\"Incense +10%\"]" : "[]").Append('}');
}
sb.Append("],\"pairs\":[{\"stud\":\"Essence 0\",\"dam\":\"Essence 1\",\"chanceBest\":0.13636,\"chanceWorst\":0.05,\"inheritMin\":1,\"inheritMax\":2}],")
.Append("\"supplies\":[{\"key\":\"incense1\",\"name\":\"Breeding Incense\",\"effect\":\"+10% mutation chance\",\"count\":2,\"price\":250000,\"apply\":true,\"targets\":[1000,1001]},")
.Append("{\"key\":\"neuter\",\"name\":\"Neutering Kit\",\"effect\":\"Permanent\",\"count\":1,\"price\":0,\"apply\":false,\"targets\":[]}],")
.Append("\"rules\":[{\"label\":\"Stud charges\",\"value\":\"10/day\",\"source\":\"seen on server\",\"help\":\"Breeds per refill.\"},")
.Append("{\"label\":\"Mutation decay\",\"value\":\"0.1\",\"source\":\"ILT profile\",\"help\":\"\"}],")
.Append("\"events\":[{\"when\":\"10-15 12:00\",\"kind\":\"birth\",\"text\":\"Congratulations! A baby pet has been born: Pup\"}],")
.Append("\"debug\":{\"when\":\"10-15 12:01\",\"enabled\":\"on\",\"location\":\"0x0106 variant 2\",\"match\":\"valid\",\"pet\":\"Essence 0\",\"sex\":\"M\",\"partners\":1}}");
return sb.ToString();
}
/// <summary>
/// The Pet Breeding tab: Infinite Leaftide only and only where the server has pet breeding; RynthILT's
/// breeding JSON drawn within the op budget; Dance and supply uses asked first, then sent as RynthILT's verbs.
/// </summary>
private static void Breeding()
{
OracleContext c = Context();
var view = new OracleView(c);
Check(!view.VisibleTabs().Contains(OracleView.TabBreeding), "Aelrynth: no Pet Breeding tab");
c.Server.Force("", "Coldeve");
Check(!view.VisibleTabs().Contains(OracleView.TabBreeding), "other servers: no Pet Breeding tab");
c.Server.Force(ServerTags.InfiniteLeaftide, "InfiniteLeaftide");
Check(view.VisibleTabs().Contains(OracleView.TabBreeding), "Infinite Leaftide: the Pet Breeding tab");
c.Ilt.SetJson("{\"ilt\":true,\"features\":[{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":0,\"where\":\"\"}]}");
Check(!view.VisibleTabs().Contains(OracleView.TabBreeding), "ILT with pet breeding off on the server: no Pet Breeding tab");
c.Ilt.SetJson("{\"ilt\":true,\"features\":[{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":1,\"where\":\"\"}]}");
Check(view.VisibleTabs().Contains(OracleView.TabBreeding), "ILT with pet breeding on: the tab");
c.Ilt.SetJson("{\"ilt\":true,\"features\":[{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":-1,\"where\":\"\"}]}");
Check(view.VisibleTabs().Contains(OracleView.TabBreeding), "ILT with pet breeding not known yet: the tab (it says what it is waiting for)");
c.Ilt.SetJson("");
IltBreedingView v = IltBreedingView.Parse(BreedingJson(2));
Check(v.Loaded && v.Available && v.Enabled == "on" && v.Room == "landblock 0x0106 variant 2" && v.FreeSlots == 12, "breeding JSON header");
Check(v.Essences.Count == 2 && v.Essences[0].Male && !v.Essences[1].Male && v.Essences[0].Ready && v.Essences[0].Boosters.Count == 1,
"breeding essences with sex, readiness and boosters");
Check(v.Pairs.Count == 1 && Math.Abs(v.Pairs[0].ChanceBest - 0.13636) < 1e-9 && v.Pairs[0].InheritMax == 2, "breeding pair odds");
Check(v.Supplies.Count == 2 && v.Supplies[0].Targets.Count == 2 && !v.Supplies[1].Apply, "breeding supplies and their targets");
Check(v.Debug is { Match: "valid", Partners: 1 }, "breeding diagnostics");
Check(!IltBreedingView.Parse("not json").Loaded && !IltBreedingView.Parse("").Loaded && !IltBreedingView.Parse("[1]").Loaded,
"bad breeding JSON is not loaded");
Check(IltBreedingView.ApplyVerb(" incense1 ", 1000) == "apply incense1 1000" && IltBreedingView.DanceVerb() == "dance", "breeding verbs");
// Nothing from RynthILT yet: the tab says to load it.
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
c.Settings.TabName = OracleView.TabBreeding;
Check(Frame(host, main, view, "Pet Breeding empty").Contains("Load RynthILT (0.3.1 or later)"), "without RynthILT: says to load it");
// 50 essences with every section open: rows cut at 40, the page still fits.
var sent = new List<string>();
string ran = "";
c.BreedingCommand = verb => { sent.Add(verb); return true; };
c.RunCommand = cmd => { ran = cmd; return true; };
c.Breeding = IltBreedingView.Parse(BreedingJson(50));
Frame(host, main, view, "Pet Breeding opening");
foreach (string header in new[] { "br.sup", "br.rules", "br.events" })
Apply(host, Event(6, ++_seq, main.Hash, main.KeyOf(header), new byte[] { 1 }));
string body = Frame(host, main, view, "Pet Breeding with 50 essences", out int ops);
Check(ops > 5 && ops < 1400, $"Pet Breeding with 50 essences: {ops} ops");
Console.WriteLine($" InfiniteLeaftide/Pet Breeding (50 essences, all open): {ops} ops, {body.Length} bytes");
Check(body.Contains("Essences (2 ready of 50)") && body.Contains("... and 10 more"), "essence rows cut at 40 with a count");
Check(body.Contains("Essence 0 x Essence 1") && body.Contains("5%-13.6%"), "the ready pair with its odds");
Check(body.Contains("Supplies (3 carried)") && body.Contains("250,000 pyreals"), "supplies with Ivo's price");
Check(body.Contains("Stud charges") && body.Contains("seen on server") && body.Contains("In the breeding room"), "rules and diagnostics");
Check(body.Contains("A baby pet has been born"), "recent events");
Check(body.Contains("###refresh.Pet Breeding"), "the page has the Refresh row every page has");
// Dance asks first; No drops it, Yes sends it.
Click(host, main, "br.dance");
Check(sent.Count == 0, "Dance asks before sending");
body = Frame(host, main, view, "Pet Breeding asking");
Check(body.Contains("Dance now?") && body.Contains("###br.yes") && body.Contains("###br.no"), "the question with Yes / No");
Click(host, main, "br.no");
body = Frame(host, main, view, "Pet Breeding no");
Check(sent.Count == 0 && !body.Contains("###br.yes"), "No drops the question");
Click(host, main, "br.dance");
Frame(host, main, view, "Pet Breeding asking again");
Click(host, main, "br.yes");
Check(sent.Count == 1 && sent[0] == "dance", "Yes sends the dance verb");
// A supply use on the selected essence (the first) asks first as well.
body = Frame(host, main, view, "Pet Breeding supplies");
Check(body.Contains("###br.use.0") && !body.Contains("###br.use.1"), "only a usable, carried supply has Use");
Click(host, main, "br.use.0");
Check(sent.Count == 1, "a supply use asks before sending");
Frame(host, main, view, "Pet Breeding supply question");
Click(host, main, "br.yes");
Check(sent.Count == 2 && sent[1] == "apply incense1 1000", "Use then Yes sends apply with the essence id: " + string.Join("|", sent));
Click(host, main, "br.debug");
Check(sent.Count == 3 && sent[2] == "debug", "Diagnostics is sent straight away (it only reads)");
Click(host, main, "br.remote");
Check(ran == "/ra hub open breeding", "Mini Remote opens Pets > Breeding: " + ran);
// The page's Refresh row asks RynthILT to appraise again.
Click(host, main, "refresh.Pet Breeding");
Check(sent.Count == 4 && sent[3] == "refresh", "Refresh sends refresh: " + string.Join("|", sent));
// Breeding switched off on the server: said in red, page still drawn.
c.Breeding = IltBreedingView.Parse("{\"available\":true,\"enabled\":\"off\",\"essences\":[]}");
Check(Frame(host, main, view, "Pet Breeding off").Contains("Pet breeding is off on this server."), "breeding off is shown");
}
/// <summary>The Character tab's Charms section (RynthILT's list, Toggle routed back to it).</summary>
private static void Charms()
{
const string charmsJson = "{\"available\":true,\"world\":\"InfiniteLeaftide\",\"acquiredCount\":2,\"activeCount\":1,"
+ "\"charms\":[{\"name\":\"Mana Barrier\",\"effect\":\"Absorbs damage\",\"acquired\":\"carried\",\"count\":1,\"tier\":3,\"maxTier\":5,"
+ "\"active\":\"on\",\"server\":\"on\",\"toggleId\":5001},"
+ "{\"name\":\"Swift Feet\",\"acquired\":\"seen\",\"lastSeen\":\"2026-10-12\",\"active\":\"unknown\",\"server\":\"off\"}],"
+ "\"hands\":[{\"id\":7001,\"name\":\"Guardian Hand\",\"active\":\"off\",\"server\":\"on\"}]}";
OracleContext c = Context();
c.Server.Force(ServerTags.InfiniteLeaftide, "InfiniteLeaftide");
c.Settings.TabName = OracleView.TabCharacter;
var view = new OracleView(c);
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
string empty = Frame(host, main, view, "Character, no RynthILT");
Check(empty.Contains("Load RynthILT to list your Infinite Leaftide charms"), "ILT without RynthILT: says to load it");
uint toggled = 0;
c.ToggleCharm = id => { toggled = id; return true; };
c.Charms = RynthCore.Plugin.Shared.IltCharmsView.Parse(charmsJson);
string body = Frame(host, main, view, "Character with charms", out int ops);
Check(ops > 5 && ops < 1400, $"Character with charms: {ops} ops");
Check(body.Contains("Charms (2)") && body.Contains("Mana Barrier") && body.Contains("T3/5") && body.Contains("seen 2026-10-12"),
"the charms RynthILT listed, with tier and acquired state");
Check(body.Contains("server off"), "a charm the server switched off is marked");
Check(body.Contains("Guardian Hands (1)"), "the Guardian Hands are listed");
Check(body.Contains("###c.charm.0") && !body.Contains("###c.charm.1"), "an uncarried charm has no Toggle");
Click(host, main, "c.charm.0");
Check(toggled == 5001, "the carried charm's Toggle goes to RynthILT with its id");
Click(host, main, "c.hand.0");
Check(toggled == 7001, "the Guardian Hand's Toggle goes to RynthILT with its id");
// Another world: RynthILT answers "not available", so no charms section at all.
c.Server.Force("", "");
c.Charms = RynthCore.Plugin.Shared.IltCharmsView.Parse("{\"available\":false,\"charms\":[]}");
Check(!Frame(host, main, view, "Character off ILT").Contains("Charms ("), "off ILT: no charms section");
}
// ── The merged Quests list ───────────────────────────────────────────
private const string GuardianJson = "{\"available\":true,\"world\":\"InfiniteLeaftide\",\"chat\":true,\"auto\":false,\"buy\":true,"
+ "\"cooldownHours\":20,\"answer\":\"Pyreal\",\"npc\":\"Guardian of Attribute Enlightenment\",\"answerAgeSec\":30,"
+ "\"heard\":\"What is the coin of the realm?\",\"running\":false,\"status\":\"idle\",\"synced\":\"2026-10-18T19:05:00Z\","
+ "\"rows\":[{\"attribute\":\"Strength\",\"npc\":\"Fiun Strongarm\",\"count\":3,\"status\":\"Ready\",\"eta\":\"\",\"ready\":true,\"exact\":true},"
+ "{\"attribute\":\"Focus\",\"npc\":\"Fiun Thinker\",\"count\":1,\"status\":\"Cooldown\",\"eta\":\"in 5h 2m\",\"ready\":false,\"exact\":false}]}";
/// <summary>The "N shown" count in a page body.</summary>
private static int Shown(string body)
{
int at = body.IndexOf(" shown", StringComparison.Ordinal);
if (at < 0) return -1;
int s = at;
while (s > 0 && char.IsDigit(body[s - 1])) s--;
return int.TryParse(body.AsSpan(s, at - s), out int n) ? n : -1;
}
/// <summary>Each source appears in the one list, per server, with its filters; Trackers only and Show narrow it.</summary>
private static void MergedList()
{
// Retail: quests, Legendary quests and markers; no stamps or guardians.
OracleContext c = On("");
var view = new OracleView(c);
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
c.Settings.TabName = OracleView.TabQuests;
int quests = c.Catalog.Quests.Count;
int leg = LegendaryList.All.Count, mrk = MarkerList.All.Count, dyn = DynamicStampList.All.Count;
Check(view.AvailableKinds().SequenceEqual(new[] { QuestKind.Quest, QuestKind.Legendary, QuestKind.Marker }), "retail kinds: quests, Legendary, markers");
string body = Frame(host, main, view, "Quests, retail, everything");
Check(Shown(body) == quests + leg + mrk, $"retail: quests + Legendary + markers in one list ({Shown(body)} shown, {quests + leg + mrk} expected)");
Check(body.Contains("###q.trackers") && body.Contains("###q.kind") && body.Contains("###q.sort") && body.Contains("###q.timers"),
"Trackers only, Show, Sort and the Quest Timers button are on the page");
Check(body.Contains("###refresh.Quests"), "the Refresh row every page has is still on the Quests page");
// Trackers only: the quests drop out, the trackers' status shows above.
Tick(host, main, "q.trackers", true);
body = Frame(host, main, view, "Quests, trackers only");
Check(Shown(body) == leg + mrk, $"Trackers only: Legendary + markers ({Shown(body)})");
Check(body.Contains("toward John") && body.Contains("markers found") && body.Contains("LEG") && !body.Contains("###q.r.30minattributes"),
"Trackers only: John's counter and the markers' progress above, no quests");
Check(!body.Contains("###dy.area") && !body.Contains("Dynamic stamps"), "retail: no stamp status or area picker");
Tick(host, main, "q.trackers", false);
// Show: one kind per source.
foreach ((QuestKind kind, int want) in new[] { (QuestKind.Quest, quests), (QuestKind.Legendary, leg), (QuestKind.Marker, mrk) })
{
view.ShowTrackers(kind);
body = Frame(host, main, view, "Quests, " + kind);
Check(Shown(body) == want, $"Show {kind}: {Shown(body)} shown ({want} expected)");
}
// Done / Not done on markers: the Markers tab's "only the ones still to find".
long at = DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds();
c.Flags.OnChatLine($"explorationmarkersfoundingroupa - 3 solves ({at})\"Markers\" 1023 0", c.NowMs);
c.Flags.Tick(c.NowMs + 5_000);
view.ShowTrackers(QuestKind.Marker);
body = Frame(host, main, view, "Markers, none filtered");
Check(Shown(body) == 100 && body.Contains("2 / 100 markers found"), "markers: bits 1 and 2 of group A found: " + (body.Contains("markers found") ? "status shown" : "no status"));
Tick(host, main, "q.notdone", true);
body = Frame(host, main, view, "Markers, not done");
Check(Shown(body) == 98, $"markers, Not done: the ones still to find ({Shown(body)})");
Tick(host, main, "q.notdone", false);
Tick(host, main, "q.done", true);
body = Frame(host, main, view, "Markers, done");
Check(Shown(body) == 2, $"markers, Done: the two found ({Shown(body)})");
Tick(host, main, "q.done", false);
// Repeatable / One-time: Legendary rows repeat, markers don't.
view.ShowTrackers(null);
Tick(host, main, "q.rep", true);
body = Frame(host, main, view, "Trackers, repeatable");
Check(Shown(body) == leg, $"Repeatable: the Legendary quests ({Shown(body)})");
Tick(host, main, "q.rep", false);
Tick(host, main, "q.one", true);
body = Frame(host, main, view, "Trackers, one-time");
Check(Shown(body) == mrk, $"One-time: the markers ({Shown(body)})");
Tick(host, main, "q.one", false);
// The quest-only filters leave the trackers out.
Tick(host, main, "q.new", true);
body = Frame(host, main, view, "Trackers, Not in list");
Check(Shown(body) == 0, "Not in list is a quests-only filter: no tracker rows");
Tick(host, main, "q.new", false);
// Search reaches the trackers' text (the notes, places, flags).
Type(host, main, "q.search", "mhoire");
body = Frame(host, main, view, "Trackers, search");
int wantSearch = LegendaryList.All.Count(l => $"{l.Label} {l.Group} {l.Note} {string.Join(" ", l.Flags)}".Contains("mhoire", StringComparison.OrdinalIgnoreCase))
+ MarkerList.All.Count(m => $"#{m.Number} {m.Name} {m.Location} {m.Hint}".Contains("mhoire", StringComparison.OrdinalIgnoreCase));
Check(Shown(body) == wantSearch && wantSearch > 0, $"Search \"mhoire\" over the trackers: {Shown(body)} shown ({wantSearch} expected)");
Type(host, main, "q.search", "");
// Favourites: tracking a quest (the * list) also marks the Legendary row of the same flag.
LegendaryQuest rtw = LegendaryList.All.First(q => q.CommonName == "RTW");
c.Book.SetTracked(rtw.Flags[0], true);
Tick(host, main, "q.tracked", true);
body = Frame(host, main, view, "Trackers, tracked");
Check(Shown(body) == 1 && body.Contains("###q.r.lg:" + rtw.Name), $"Tracked: the tracked quest's Legendary row ({Shown(body)})");
view.ShowTrackers(QuestKind.Quest);
body = Frame(host, main, view, "Quests, tracked");
Check(Shown(body) == 3 && body.Contains("###q.t.30minattributes"), $"Tracked quests are still the favourites (the * list): {Shown(body)} shown");
Tick(host, main, "q.tracked", false);
c.Book.SetTracked(rtw.Flags[0], false);
// Sorts do not throw and keep every row.
view.ShowTrackers(null);
foreach (int sort in new[] { 1, 2, 3, 4, 5, 0 })
{
Apply(host, Event(3, ++_seq, main.Hash, main.KeyOf("q.sort"), BitConverter.GetBytes(sort)));
body = Frame(host, main, view, "Trackers, sort " + sort);
Check(Shown(body) == leg + mrk, $"sort {sort} keeps every row ({Shown(body)})");
}
// Infinite Leaftide: stamps and guardians join; the area picker narrows the stamps.
OracleContext ic = On(ServerTags.InfiniteLeaftide);
var iv = new OracleView(ic);
var ihost = new UiHost();
UiWindow imain = ihost.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
ic.Settings.TabName = OracleView.TabQuests;
ic.Guardian = IltGuardianView.Parse(GuardianJson);
ic.GuardianRevision++;
int iq = ic.Catalog.Quests.Count;
body = Frame(ihost, imain, iv, "Quests, ILT, everything");
Check(Shown(body) == iq + leg + mrk + dyn + 2, $"ILT: quests + Legendary + markers + {dyn} stamps + 2 guardians ({Shown(body)}, {iq + leg + mrk + dyn + 2} expected)");
foreach ((QuestKind kind, int want, string tag) in new[] { (QuestKind.Dynamic, dyn, "DYN"), (QuestKind.Guardian, 2, "GRD") })
{
iv.ShowTrackers(kind);
body = Frame(ihost, imain, iv, "Quests, ILT, " + kind);
Check(Shown(body) == want && body.Contains(tag), $"ILT Show {kind}: {Shown(body)} shown ({want} expected)");
}
iv.ShowTrackers(QuestKind.Dynamic);
Frame(ihost, imain, iv, "Quests, ILT, stamps");
Apply(ihost, Event(3, ++_seq, imain.Hash, imain.KeyOf("dy.area"), BitConverter.GetBytes(1)));
body = Frame(ihost, imain, iv, "Quests, ILT, one area");
int areaCount = DynamicStampList.All.Count(s => s.Area == DynamicStampList.Areas[0]);
Check(Shown(body) == areaCount, $"the area picker narrows the stamps to {DynamicStampList.Areas[0]}: {Shown(body)} ({areaCount} expected)");
// A saved tab name of an old tab opens Quests; the Markers / Legendary / Dynamic Stamps tabs are gone.
ic.Settings.TabName = "Markers";
Check(iv.Tab == OracleView.TabQuests, "a saved \"Markers\" tab opens Quests");
ic.Settings.TabName = "Dynamic Stamps";
Check(iv.Tab == OracleView.TabQuests, "a saved \"Dynamic Stamps\" tab opens Quests");
string[] tabs = iv.VisibleTabs();
Check(!tabs.Contains("Markers") && !tabs.Contains("Legendary") && !tabs.Contains("Dynamic Stamps"), "no separate tracker tabs: " + string.Join(",", tabs));
}
/// <summary>Everything the old Markers tab showed is reachable from the Quests list.</summary>
private static void MarkersReachable()
{
OracleContext c = On("");
var printed = new List<string>();
c.PrintSink = printed.Add;
var navs = new List<string>();
c.SendNav = line => { navs.Add(line); return true; };
var view = new OracleView(c);
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
c.Settings.TabName = OracleView.TabQuests;
long at = DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds();
c.Flags.OnChatLine($"explorationmarkersfoundingroupa - 1 solves ({at})\"Markers\" 1023 0", c.NowMs);
c.Flags.Tick(c.NowMs + 5_000);
view.ShowTrackers(QuestKind.Marker); // /ro markers
string body = Frame(host, main, view, "Markers");
Check(body.Contains("1 / 100 markers found"), "the progress bar: markers found of 100");
Marker next = MarkerList.All[1];
Check(body.Contains("Next marker:") && body.Contains($"#{next.Number} {next.Name} ({next.Location})"), "the next marker to run to");
Check(body.Contains("###q.r.mk:1") && body.Contains("###q.r.mk:2"), "a row per marker");
// "Next marker" opens that marker, and a click prints the directions in chat (the old tab did).
Click(host, main, "m.next");
Check(printed.Count >= 2 && printed[0].StartsWith($"Marker {next.Number}: {next.Name}") && printed.Contains(next.Hint), "a click prints the marker and its directions: " + string.Join(" | ", printed.Take(3)));
body = Frame(host, main, view, "Marker opened");
Check(body.Contains("Marker 2") && body.Contains("not found yet") && body.Contains("###q.nav.go") && body.Contains("###m.sel.print") && body.Contains("###m.sel.close"),
"the marker opens below the list: status, Go to, Print, Close");
Click(host, main, "q.nav.go");
Check(navs.Count == 1 && navs[0].StartsWith("go "), "Go to sends RynthNav a go: " + string.Join("|", navs));
Click(host, main, "q.nav.route");
Click(host, main, "q.nav.arrow");
Check(navs.Count == 3 && navs[1].StartsWith("route ") && navs[2].StartsWith("arrow "), "Route and Arrow likewise");
// Print in chat from the panel; a second click on the row closes it (and prints again).
printed.Clear();
Click(host, main, "m.sel.print");
Check(printed.Count >= 2, "Print in chat from the opened marker");
printed.Clear();
Click(host, main, "q.r.mk:2");
body = Frame(host, main, view, "Marker closed");
Check(printed.Count >= 2 && !body.Contains("###m.sel.close"), "a second click on the row prints again and closes it");
}
/// <summary>Opening a Legendary quest, a marker or a quest with coordinates in its notes offers RynthNav's Go to.</summary>
private static void GoToButtons()
{
OracleContext c = On("");
var navs = new List<string>();
c.SendNav = line => { navs.Add(line); return true; };
var printed = new List<string>();
c.PrintSink = printed.Add;
var view = new OracleView(c);
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
c.Settings.TabName = OracleView.TabQuests;
// The shipped Legendary notes carry no coordinates, so a row with them is added for the test
// (first in the list, taken out again): several places give a picker first, picking plans the route.
var fake = new LegendaryQuest
{
Group = "Testing", Name = "Test Route Quest", Luminance = 1, Flags = new[] { "testroutequest" },
Note = "Speak with Hoshar 59.6S 88.0W - Kill Mukkir 86.5N 57.3E",
};
var one = new LegendaryQuest
{
Group = "Testing", Name = "Test One Place", Luminance = 1, Flags = new[] { "testoneplace" },
Note = "Speak with Hoshar 59.6S 88.0W",
};
LegendaryList.All.Insert(0, fake);
try
{
view.ShowTrackers(QuestKind.Legendary);
Frame(host, main, view, "Legendary");
Click(host, main, "q.r.lg:" + fake.Name);
string body = Frame(host, main, view, "Legendary opened");
Check(body.Contains("Go to (2 places in these notes)") && body.Contains("###q.nav.pick") && body.Contains("###q.nav.go"),
"a Legendary quest with 2 places in its notes: a picker and Go");
Check(body.Contains("###lg.sel.print") && body.Contains("###lg.sel.close") && body.Contains("Testing"), "its area, Print and Close buttons");
Apply(host, Event(3, ++_seq, main.Hash, main.KeyOf("q.nav.pick"), BitConverter.GetBytes(1)));
Check(navs.Count == 1 && navs[0] == "route 86.5N, 57.3E Kill Mukkir", "picking the second place plans its route: " + string.Join("|", navs));
Frame(host, main, view, "Legendary, second place picked");
Click(host, main, "q.nav.go");
Check(navs.Count == 2 && navs[1] == "go 86.5N, 57.3E Kill Mukkir", "Go walks the picked place: " + string.Join("|", navs));
Click(host, main, "lg.sel.print");
Check(printed.Count >= 1 && printed[0].Contains("Test Route Quest") && printed.Any(p => p.Contains("Speak with Hoshar")),
"Print in chat prints the quest and its notes: " + string.Join(" | ", printed.Take(3)));
// One place: no picker.
Click(host, main, "q.r.lg:" + fake.Name); // close
LegendaryList.All.Insert(0, one);
Type(host, main, "q.search", "Test One"); // the row list is cached per filter: a new search rebuilds it
Frame(host, main, view, "Legendary, with the one-place row");
Click(host, main, "q.r.lg:" + one.Name);
body = Frame(host, main, view, "Legendary, one place");
Check(body.Contains("Go to") && !body.Contains("###q.nav.pick") && body.Contains("###q.nav.go"), "one place: Go / Route / Arrow, no picker");
// A real Legendary quest (no coordinates in its notes): opens, no Go to.
LegendaryQuest real = LegendaryList.All.First(q => q != fake && q != one);
Click(host, main, "q.r.lg:" + one.Name); // close
Type(host, main, "q.search", "");
Frame(host, main, view, "Legendary, all rows again");
Click(host, main, "q.r.lg:" + real.Name);
body = Frame(host, main, view, "Legendary, no place");
Check(!body.Contains("###q.nav.go") && body.Contains("###lg.sel.close") && body.Contains("Area"), "no coordinates in the notes: no Go to");
}
finally
{
LegendaryList.All.Remove(fake);
LegendaryList.All.Remove(one);
}
// A plain quest whose notes have coordinates: Go to under its texts, and the click still prints.
Quest? withCoords = c.Catalog.Quests.FirstOrDefault(q => NavTargets.Stops(q.Info + " - " + q.Hint).Count > 0);
Check(withCoords != null, "some quest in the list has coordinates in its notes");
if (withCoords != null)
{
view.ShowTrackers(QuestKind.Quest);
Type(host, main, "q.search", withCoords.Flag);
Frame(host, main, view, "Quests, searched");
printed.Clear();
Click(host, main, "q.r." + withCoords.Flag);
string body = Frame(host, main, view, "Quest with coordinates");
Check(printed.Count >= 4, "a click on a quest still prints its texts in chat");
Check(body.Contains("###q.nav.go") && body.Contains("Save rewards") && body.Contains("###q.sel.track"),
"the quest opens with Go to, Track and the rewards editor");
Type(host, main, "q.search", "");
}
}
/// <summary>The guardians as rows, their controls sending RynthILT's verbs, and the stamps' opened box.</summary>
private static void Trackers()
{
var g = IltGuardianView.Parse(GuardianJson);
Check(g.Loaded && g.Chat && !g.Auto && g.Buy && g.Answer == "Pyreal" && g.AnswerAgeSec == 30 && g.SyncedUtc.Year == 2026, "guardian JSON header");
Check(g.Rows.Count == 2 && g.Rows[0].Ready && g.Rows[0].Exact && g.Rows[1].Eta == "in 5h 2m" && !g.Rows[1].Exact, "guardian rows");
Check(!IltGuardianView.Parse("nope").Loaded && !IltGuardianView.Parse("").Loaded, "bad guardian JSON is not loaded");
Check(IltGuardianView.SwitchVerb(" Auto ", true) == "auto on" && IltGuardianView.SwitchVerb("buy", false) == "buy off"
&& IltGuardianView.HandInVerb() == "handin", "guardian verbs");
OracleContext c = On(ServerTags.InfiniteLeaftide);
var view = new OracleView(c);
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
c.Settings.TabName = OracleView.TabQuests;
view.ShowTrackers(QuestKind.Guardian);
string body = Frame(host, main, view, "Guardians without RynthILT");
Check(body.Contains("RynthILT isn't loaded"), "guardians without RynthILT: says to load it");
var sent = new List<string>();
c.GuardianCommand = verb => { sent.Add(verb); return true; };
c.Guardian = g;
c.GuardianRevision++;
body = Frame(host, main, view, "Guardians");
Check(body.Contains("Temple guardians") && body.Contains("1 of 2 attribute turn-ins ready") && body.Contains("Pyreal")
&& body.Contains("###gd.handin") && body.Contains("GRD") && body.Contains("Strength (Fiun Strongarm)") && body.Contains("in 5h 2m"),
"guardian controls, answer and rows");
Click(host, main, "gd.handin");
Tick(host, main, "gd.auto", true);
Tick(host, main, "gd.buy", false);
Click(host, main, "gd.refresh");
Check(string.Join("|", sent) == "handin|auto on|buy off|refresh", "guardian controls send their verbs: " + string.Join("|", sent));
// Open a guardian row, then every kind at once under the engine's ops limit.
Click(host, main, "q.r.gd:Strength");
view.ShowTrackers(null);
body = Frame(host, main, view, "ILT trackers, a guardian opened", out int ops);
int rows = LegendaryList.All.Count + MarkerList.All.Count + DynamicStampList.All.Count + 2;
Check(Shown(body) == rows && body.Contains("Temple guardian: Strength") && body.Contains("###gd.sel.close"), $"every ILT tracker listed ({Shown(body)}), a guardian opened below");
Check(ops > 40 && ops < 1400, $"ILT Quests with every tracker and a guardian opened: {ops} ops");
Console.WriteLine($" InfiniteLeaftide/Quests, trackers only ({rows} rows, guardian opened): {ops} ops, {body.Length} bytes");
// A stamp: the nav box with Go / Arrow / Chat, RynthNav asked for the route at once.
var navs = new List<string>();
c.SendNav = line => { navs.Add(line); return true; };
var printed = new List<string>();
c.PrintSink = printed.Add;
view.ShowTrackers(QuestKind.Dynamic);
DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda");
Frame(host, main, view, "Stamps");
Click(host, main, "q.r.dy:" + felscuda.Stamp);
Check(navs.Count == 1 && navs[0] == "route 8.8S, 53.1E || Folthid Cellar || Felscuda || Facility Hub", "clicking a stamp asks RynthNav for its route: " + string.Join("|", navs));
body = Frame(host, main, view, "Stamp opened");
Check(body.Contains("Navigate to Felscuda") && body.Contains("###dy.nav.go") && body.Contains("###dy.nav.arrow") && body.Contains("###dy.nav.chat"), "the stamp's box");
Click(host, main, "dy.nav.go");
Check(navs.Count == 2 && navs[1].StartsWith("go 8.8S, 53.1E || "), "Go sends a go with every candidate");
Click(host, main, "dy.nav.chat");
Check(printed.Count >= 1 && printed[0].Contains("Felscuda") && printed[0].Contains("missing"), "Chat prints the stamp: " + string.Join(" | ", printed.Take(2)));
}
/// <summary>Give Parchment sends /ub give, and is disabled with a tooltip when RynthAi can't take it.</summary>
private static void GiveParchment()
{
OracleContext c = On(ServerTags.InfiniteLeaftide);
c.ParchmentFinder = () => "Parchment of Learning";
var ran = new List<string>();
c.RunCommand = cmd => { ran.Add(cmd); return true; };
c.SendNav = _ => true;
var view = new OracleView(c);
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
c.Settings.TabName = OracleView.TabQuests;
DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda");
view.ShowTrackers(QuestKind.Dynamic);
Frame(host, main, view, "Stamps");
Click(host, main, "q.r.dy:" + felscuda.Stamp);
// RynthAi isn't there: no button, a greyed line and the reason.
c.UbGiveAvailable = () => false;
string body = Frame(host, main, view, "Give, no RynthAi");
Check(!body.Contains("###dy.nav.give") && body.Contains("[Give Parchment of Learning]") && body.Contains("Needs RynthAi"),
"no RynthAi: Give Parchment is disabled with a tooltip");
Check(ran.Count == 0, "nothing was sent");
// RynthAi there: the button sends /ub give 1.
c.UbGiveAvailable = () => true;
body = Frame(host, main, view, "Give, RynthAi");
Check(body.Contains("###dy.nav.give") && body.Contains("Hands one Parchment of Learning to Felscuda"), "RynthAi loaded: the Give button and its tooltip");
c.NowMs = 50_000;
Click(host, main, "dy.nav.give");
Check(ran.Count == 0, "one click doesn't give anything away");
body = Frame(host, main, view, "Give, asking");
Check(body.Contains("Give one Parchment of Learning to Felscuda?") && body.Contains("###dy.nav.give.yes") && body.Contains("###dy.nav.give.no"),
"it asks, naming the item and the NPC");
Click(host, main, "dy.nav.give.no");
body = Frame(host, main, view, "Give, cancelled");
Check(ran.Count == 0 && body.Contains("###dy.nav.give") && !body.Contains("###dy.nav.give.yes"), "Cancel drops the question, nothing sent");
Click(host, main, "dy.nav.give");
Frame(host, main, view, "Give, asking again");
Click(host, main, "dy.nav.give.yes");
Check(ran.Count == 1 && ran[0] == "/ub give 1 Parchment of Learning to Felscuda", "Yes sends /ub give 1: " + string.Join("|", ran));
Check(c.UbGiveSentMs == 50_000, "the send is stamped, so a rejection can be tied to it");
// The loaded RynthAi answers "Unrecognized /ub command": the button turns itself off.
Check(!c.NoteChatLineForGive("[RynthAi] some other line", 52_000) && !c.UbGiveMissing, "an unrelated line changes nothing");
Check(!c.NoteChatLineForGive("[RynthAi] Unrecognized /ub command.", 60_000) && !c.UbGiveMissing, "a rejection long after the send is not tied to it");
Check(c.NoteChatLineForGive("[RynthAi] Unrecognized /ub command.", 52_000) && c.UbGiveMissing, "a rejection right after the send disables Give");
body = Frame(host, main, view, "Give, rejected");
Check(!body.Contains("###dy.nav.give") && body.Contains("[Give Parchment of Learning]") && body.Contains("Unrecognized /ub command"),
"rejected: disabled, the tooltip says why");
Click(host, main, "q.r.dy:" + felscuda.Stamp); // close
Click(host, main, "q.r.dy:" + felscuda.Stamp); // open again
ran.Clear();
Frame(host, main, view, "Give, rejected again");
Check(ran.Count == 0, "no further /ub give goes out");
// No Parchment carried: said, no button either way.
c.UbGiveMissing = false;
c.ParchmentFinder = () => null;
body = Frame(host, main, view, "Give, none carried");
Check(body.Contains("No Parchment in your packs") && !body.Contains("###dy.nav.give"), "no Parchment: no button, says so");
// A name with a control character can't smuggle a second command.
c.ParchmentFinder = () => "Parchment\nof /quit";
c.UbGiveAvailable = () => true;
Frame(host, main, view, "Give, odd name");
ran.Clear();
Click(host, main, "dy.nav.give");
Frame(host, main, view, "Give, odd name asking");
Click(host, main, "dy.nav.give.yes");
Check(ran.Count == 1 && !ran[0].Contains('\n') && ran[0].StartsWith("/ub give 1 "), "control characters are stripped from the command: " + (ran.Count > 0 ? ran[0].Replace("\n", "\\n") : ""));
}
/// <summary>The throttle line, and the Refresh bar on the Quests page.</summary>
private static void Throttle()
{
OracleContext c = On("");
var view = new OracleView(c);
var host = new UiHost();
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
c.Settings.TabName = OracleView.TabQuests;
c.Flags.Request(_ => true, c.NowMs);
c.Flags.OnChatLine("[MyQuests] This command may only be run once every 60 seconds.", c.NowMs + 100);
string body = Frame(host, main, view, "Quests, throttled");
Check(body.Contains("The server answers one /myquests a minute: Refresh works again in 6"), "the throttle line says when Refresh works again");
Click(host, main, "refresh.Quests");
Check(Frame(host, main, view, "Quests, Refresh while throttled").Contains("try again in 6"), "Refresh while the server's minute runs says to wait, and sends nothing");
c.NowMs += 61_000;
Check(!Frame(host, main, view, "Quests, throttle over").Contains("Refresh works again in"), "the countdown line goes once the minute is up");
}
}
}

View file

@ -24,7 +24,7 @@ namespace RynthCore.Engine.UI.ScriptWindows
namespace RynthOracle.Tests
{
internal static class Program
internal static partial class Program
{
private static int _pass, _fail;
@ -39,22 +39,37 @@ namespace RynthOracle.Tests
private static int Main()
{
// Tab clicks save the settings: into a scratch file, never the player's %APPDATA% copy.
OracleSettings.PathOverride = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N") + "-settings.json");
Lists();
QuestLines();
Catalog();
Servers();
EngineServers();
IltProfile();
ServerFeatures();
QuestNotes();
ConquestReplies();
AelrynthReplies();
Void();
TimerAlerts();
Pages();
CharacterExtras();
Charms();
Breeding();
Legendary();
DynamicStamps();
GoToParsing();
Loaders();
MergedList();
MarkersReachable();
GoToButtons();
Trackers();
GiveParchment();
Throttle();
Events();
QuestTexts();
Refreshes();
SkillsTabs();
ServerMove();
Console.WriteLine($"{_pass} passed, {_fail} failed");
return _fail == 0 ? 0 : 1;
}
@ -156,6 +171,37 @@ namespace RynthOracle.Tests
s2.NoteTypedCommand(); // the player typing it
s2.Tick(51_200);
Check(!s2.AwaitingOurs, "a typed /myquests shows its reply");
// A second reply that lost most of its lines on the way (the engine's chat queue dropped
// the head of the burst) updates the flags instead of blanking them.
var s3 = new QuestFlagStore();
long t3 = 200_000;
for (int i = 0; i < 100; i++)
s3.OnChatLine($"flag{i:D3} - 1 solves (1719432000)\"Q{i}\" -1 0", t3 + i);
s3.Tick(t3 + 5_000);
Check(s3.Flags.Count == 100, "first full reply: 100 flags");
long t4 = t3 + 120_000;
for (int i = 90; i < 100; i++)
s3.OnChatLine($"flag{i:D3} - 2 solves (1719500000)\"Q{i}\" -1 0", t4 + i);
s3.Tick(t4 + 5_000);
Check(s3.Flags.Count == 100 && s3.LastPartialReply is { Got: 10, Had: 100 },
"a cut-short reply (10 of 100) is merged, not a replacement");
Check(s3.TryGet("flag095", out QuestFlag f95) && f95.Solves == 2 && s3.TryGet("flag001", out _),
"merged reply updates the lines it had and keeps the rest");
long t5 = t4 + 120_000;
for (int i = 0; i < 95; i++)
s3.OnChatLine($"flag{i:D3} - 3 solves (1719600000)\"Q{i}\" -1 0", t5 + i);
s3.Tick(t5 + 5_000);
Check(s3.Flags.Count == 95 && !s3.TryGet("flag099", out _), "a near-full reply still replaces (a dropped flag goes away)");
// ACECustom's once-a-minute limit: the throttle line ends "Reading..." and keeps the flags.
int had = s3.Flags.Count;
long t6 = t5 + 30_000;
Check(s3.Request(_ => true, t6) && s3.AwaitingOurs, "refresh sent");
Check(s3.OnChatLine("[MyQuests] This command may only be run once every 60 seconds.", t6 + 200) == MyQuestsLine.Throttled
&& !s3.AwaitingOurs && s3.Flags.Count == had, "throttle reply: not loading, flags kept");
Check(s3.ThrottleSecondsLeft(t6 + 1_000) > 50 && !s3.Request(_ => true, t6 + 10_000), "no resend while the server's minute runs");
Check(s3.ThrottleSecondsLeft(t6 + 61_000) == 0 && s3.Request(_ => true, t6 + 61_000), "refresh allowed again after the minute");
}
private static void Catalog()
@ -224,7 +270,7 @@ namespace RynthOracle.Tests
// Identity from it.
ServerIdentity.FromEngine(st, "Launcher Profile", out string tag, out string world, out string source);
Check(tag == "" && world == "InfiniteLeaftide" && source.Contains("no RynthOracle pages"), "engine: ILT active has no Oracle tag (its screens are RynthILT's): " + source);
Check(tag == ServerTags.InfiniteLeaftide && world == "InfiniteLeaftide", "engine: ILT active is the ILT tag: " + source);
Check(source.Contains("host matches"), "engine: the reason is shown: " + source);
var picked = RynthCore.Plugin.Shared.EngineServerState.Parse(EngineJson("conquest", "ConquestAC", "RynthConquest", "conquest", "",
@ -273,7 +319,7 @@ namespace RynthOracle.Tests
Check(ServerIdentity.TagForWorld("Conquest") == ServerTags.Conquest, "Conquest");
Check(ServerIdentity.TagForWorld("Levistras") == ServerTags.Levistras, "Levistras");
Check(ServerIdentity.TagForWorld("Coldeve") == "" && ServerIdentity.TagForWorld("") == "", "other servers have no tag");
Check(ServerIdentity.TagForWorld("InfiniteLeaftide") == "", "Infinite Leaftide has no Oracle tag (RynthILT draws its screens)");
Check(ServerIdentity.TagForWorld("InfiniteLeaftide") == ServerTags.InfiniteLeaftide, "Infinite Leaftide is the ILT tag (the Quests tab's stamps and guardians, Pet Breeding)");
var id = new ServerIdentity();
id.Force("", "Coldeve");
Check(id.Allows(null) && id.Allows("") && !id.Allows(ServerTags.Conquest) && !id.Allows(ServerTags.Aelrynth), "untagged everywhere, tagged nowhere else");
@ -285,16 +331,19 @@ namespace RynthOracle.Tests
var view = new OracleView(c);
c.Server.Force("", "Coldeve");
string[] none = view.VisibleTabs();
Check(!none.Contains(OracleView.TabBoards) && !none.Contains(OracleView.TabConquest), "no server tabs on other servers: " + string.Join(",", none));
Check(!none.Contains("Leaderboards") && !none.Contains("Conquest"), "no server tabs on other servers: " + string.Join(",", none));
// A server's own pages are its server plugin's since 2026-10-20 (RynthConquest, RynthAelrynth).
c.Server.Force(ServerTags.Aelrynth, "Aeshnidae");
string[] ael = view.VisibleTabs();
Check(ael.Contains(OracleView.TabBoards) && !ael.Contains(OracleView.TabConquest), "Aelrynth: leaderboards, no Conquest tab");
Check(!ael.Contains("Leaderboards") && !ael.Contains("Conquest"), "Aelrynth: no leaderboards in RynthOracle: " + string.Join(",", ael));
c.Server.Force(ServerTags.Conquest, "Conquest");
string[] cq = view.VisibleTabs();
Check(cq.Contains(OracleView.TabBoards) && cq.Contains(OracleView.TabConquest), "ConquestAC: leaderboards and the Conquest tab");
c.Settings.TabName = OracleView.TabConquest;
c.Server.Force(ServerTags.Aelrynth, "Aeshnidae");
Check(view.Tab == OracleView.TabQuests, "a Conquest tab left selected falls back to Quests elsewhere");
Check(!cq.Contains("Leaderboards") && !cq.Contains("Conquest"), "Conquest: no Conquest tab and no leaderboards in RynthOracle: " + string.Join(",", cq));
foreach (string old in new[] { "Conquest", "Leaderboards" })
{
c.Settings.TabName = old;
Check(view.Tab == OracleView.TabQuests, $"a {old} tab saved by an older version falls back to Quests");
}
}
// Quest notes: tracking and rewards saved per character, UB's reward format and import, kill-task timers.
@ -369,101 +418,6 @@ namespace RynthOracle.Tests
}
}
private static void ConquestReplies()
{
var d = new ConquestData();
long now = 1_000_000;
d.RequestBank(now);
Check(d.OnChatLine("[BANK] Your balances:", now, out bool ours) && ours, "bank heading (ours)");
d.OnChatLine("[BANK] Pyreals: 1,039,678,533", now, out _);
d.OnChatLine("[BANK] Event Tokens [Dragon Coins] (x): 12", now, out _);
Check(d.Bank.Any(b => b.Name == "Pyreals" && b.Value.Contains("4,158 MMDs")), "pyreals with MMDs");
Check(d.Bank.Any(b => b.Name == "Dragon Coins (x)"), "event token name");
Check(!d.OnChatLine("Bob says, \"[BANK] Pyreals: 999\"", now, out _), "a pasted balance is ignored");
d.OnChatLine("[BANK] Pyreals: 5", now + 60_000, out bool late);
Check(!late, "a reply long after the request isn't ours (shows in chat)");
d.RequestAugs(now);
d.OnChatLine("Creature: 25", now, out _);
d.OnChatLine("Duration: 3", now, out _);
ConquestAug creature = d.Augs.First(a => a.Name == "Creature");
Check(creature.Count == 25 && creature.NextLuminanceCost() == 6_229_500, $"Creature 25 next costs 6,229,500 ({creature.NextLuminanceCost()})");
Check(d.DurationAugs == 3 && Math.Abs(d.VoidDurationMultiplier(5) - 2.15) < 1e-9, "void duration x(1 + 5*0.2 + 3*0.05)");
d.RequestEnl(now);
d.OnChatLine("Enlightenment Augmentations:", now, out _);
d.OnChatLine("Skill Credits: 2 (10 max)", now, out _);
d.OnChatLine("Damage: 5 (25 max)", now, out _);
Check(d.EnlAugs.Count == 2 && d.EnlAugs[0].Name == "Damage", "enlightenment augs in display order");
d.RequestBonus(now);
d.OnChatLine("=== XP Bonuses ===", now, out _);
d.OnChatLine("Quest Bonus: 14.18% (1,418 quests)", now, out _);
d.OnChatLine("Total Bonus (Kills): 0.16%", now, out _);
Check(d.Bonuses.First(b => b.Name == "Quest").Value == "14.18% (1,418 quests)" && d.Bonuses.First(b => b.Name == "Total (Kills)").Value == "0.16%", "bonuses");
d.RequestFships(now);
d.OnChatLine("Fellowships looking for members:", now, out _);
d.OnChatLine("- Heroes (Leader: Bob) [3/14] @ Bur", now, out _);
d.OnChatLine("- Quiet (Leader: Ann) [1/14]", now, out _);
Check(d.Fellowships.Count == 2 && d.Fellowships[0].Location == "Bur" && d.Fellowships[1].MemberCount == 1, "fellowship list");
ConquestBoard lvl = d.Boards.First(b => b.Key == "level");
d.RequestBoard(lvl, now);
d.OnChatLine("Top 2 Players by Level:", now, out _);
d.OnChatLine("1: 300 - Alpha", now, out _);
d.OnChatLine("2: 299 - Beta", now, out _);
d.OnChatLine("57: 250 - Me (You)", now, out _);
Check(lvl.Rows.Count == 2 && lvl.You != null && lvl.You.Rank == 57 && lvl.You.Name == "Me", "ConquestAC /top board");
Check(ConquestData.WithdrawCommand(ConquestData.Withdrawable[ConquestData.DefaultWithdraw], "10") == "/bank withdraw n 10", "withdraw MMDs");
Check(ConquestData.WithdrawCommand(ConquestData.Withdrawable[0], "-3") == null, "withdraw refuses a bad amount");
Check(ConquestData.TransferCommand(ConquestData.Transferable[2], "4", "Some One") == "/bank transfer p 1000000 \"Some One\"", "transfer MMD notes as pyreals");
Check(ConquestData.TransferCommand(ConquestData.Transferable[2], "1001", "X") == null, "transfer cap");
}
private static void AelrynthReplies()
{
var a = new AelrynthBoards();
long now = 2_000_000;
a.RequestTop("", now);
Check(a.OnChatLine("Leaderboards - 37 characters, refreshed 4 min ago. /top <board> for the top ten, /top me for yourself.", now, out bool ours) && ours, "overview header");
a.OnChatLine(" kills Creature kills: Buffy, 1,234,567", now, out _);
a.OnChatLine(" pk PK kills: nobody yet", now, out _);
Check(a.Overview.Count == 2 && a.Overview[0].Key == "kills" && a.Overview[0].Leader == "Buffy" && a.Overview[0].Value == "1,234,567"
&& a.Overview[1].Leader == "nobody yet", "overview rows");
a.RequestTop("kills", now);
a.OnChatLine("Creature kills - top 10 of 37:", now, out _);
a.OnChatLine(" 1. Buffy 1,234,567 <- you", now, out _);
a.OnChatLine(" 2. Dargoth 987,654", now, out _);
a.OnChatLine(" 3. Sal 500 12 kills per death", now, out _);
Check(a.BoardTitle == "Creature kills" && a.BoardRows.Count == 3 && a.BoardRows[0].IsYou && a.BoardRows[1].Value == "987,654"
&& a.BoardRows[2].Extra == "12 kills per death", "board rows: " + string.Join(" | ", a.BoardRows.Select(r => $"{r.Rank} {r.Name} {r.Value} [{r.Extra}] {r.IsYou}")));
a.RequestTop("me", now);
a.OnChatLine("Buffy on the boards:", now, out _);
a.OnChatLine(" Creature kills #1 of 37, 1,234,567", now, out _);
a.OnChatLine(" PK kills -", now, out _);
Check(a.Standings.Count == 2 && a.Standings[0].Rank == 1 && a.Standings[1].Rank == 0, "/top me");
Check(!a.OnChatLine(" 9. Nobody 12", now + 30_000, out _), "an entry long after its header is ignored");
a.RequestTrial("", now);
a.OnChatLine("Trials - a fresh personal copy of a listed dungeon, entered through its portal, is a timed course: ...", now, out _);
a.OnChatLine(" The Citadel Below - Trial (02F0): tier 0 12:34 by Buffy | you: tier 0 12:34 | this week: Buffy 12:34 (tier 0)", now, out _);
a.OnChatLine(" your next attempt here: in 12 min", now, out _);
a.OnChatLine("Trophy: the week's fastest clear of each dungeon, any tier - a trophy and 1,000 experience, Sunday 20:00 (2026-W40). /trial <name> for the top 10 of one dungeon.", now, out _);
Check(a.Trials.Count == 1 && a.Trials[0].Landblock == "02F0" && a.TrialLines.Count == 3, $"/trial overview ({a.Trials.Count} dungeons, {a.TrialLines.Count} lines)");
a.RequestTrial("citadel", now);
a.OnChatLine("The Citadel Below - Trial (02F0) - top 10, best per character, any tier:", now, out _);
a.OnChatLine(" 1. 12:34 Buffy (tier 0, 105 kills, 3 Oct)", now, out _);
a.OnChatLine(" you: tier 0 12:34 (105 kills)", now, out _);
Check(a.TrialRows.Count == 1 && a.TrialRows[0].Name == "Buffy" && a.TrialRows[0].Value == "12:34" && a.TrialNotes.Count == 1, "/trial dungeon top 10");
Check(!a.OnChatLine("Bob tells you, \"hello\"", now, out _), "ordinary chat is never taken");
}
private static void Void()
{
var v = new VoidTracker();
@ -526,13 +480,9 @@ namespace RynthOracle.Tests
Check(timersBody.Contains("Attribute and Skill Redistribution") && timersBody.Contains("ready"), "the Quest Timers window lists tracked quests with their timers");
// Every tab on each server, including the server-specific ones (with data in them).
c.Conquest.RequestBank(c.NowMs);
c.Conquest.OnChatLine("[BANK] Pyreals: 1,000", c.NowMs, out _);
c.Boards.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top <board> ...", c.NowMs, out _);
c.Boards.OnChatLine(" kills Creature kills: Buffy, 12", c.NowMs, out _);
c.EarnedTitles.Add(1);
c.TitlesKnown = true;
foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, "" })
foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, ServerTags.InfiniteLeaftide, "" })
{
c.Server.Force(server, server);
foreach (string tab in view.VisibleTabs())
@ -543,7 +493,7 @@ namespace RynthOracle.Tests
main.End();
ParseAll(host, $"{server}/{tab}", out int ops);
Check(ops > 5 && ops < 1400, $"{server}/{tab}: {ops} ops");
if (server == ServerTags.Aelrynth || tab is OracleView.TabConquest) Console.WriteLine($" {(server.Length > 0 ? server : "other")}/{tab}: {ops} ops, {main.Body.Length} bytes");
if (server == ServerTags.Aelrynth) Console.WriteLine($" {(server.Length > 0 ? server : "other")}/{tab}: {ops} ops, {main.Body.Length} bytes");
main.MarkSubmitted(true);
}
}
@ -565,18 +515,6 @@ namespace RynthOracle.Tests
Console.WriteLine($" Quests (opened): {openOps} ops, {main.Body.Length} bytes");
main.MarkSubmitted(true);
// The Conquest tab's sub-pages and the Aelrynth board views.
c.Server.Force(ServerTags.Conquest, "Conquest");
c.Settings.TabName = OracleView.TabConquest;
for (int v = 0; v < 6; v++)
{
main.Begin(); view.Draw(main); main.End();
Apply(host, Event(1, (uint)(100 + v), main.Hash, main.KeyOf("cq.v." + ((v + 1) % 6)), new byte[] { 1, 0, 0 }));
main.Begin(); view.Draw(main); main.End();
ParseAll(host, $"conquest view {v}", out int ops);
Check(ops > 5 && ops < 1400, $"conquest view {v}: {ops} ops");
}
// A page that can't fit: everything in the catalog on one page is cut short, still valid.
var big = new UiWindow("RynthOracle/Big", "Big") { Visible = true };
var bigHost = new UiHost();
@ -727,10 +665,10 @@ namespace RynthOracle.Tests
{
// 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 };
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, "" })
foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, ServerTags.InfiniteLeaftide, "" })
{
c.Server.Force(server, server);
string[] tabs = view.VisibleTabs();
@ -876,7 +814,7 @@ namespace RynthOracle.Tests
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, "" })
foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, ServerTags.InfiniteLeaftide, "" })
{
c.Server.Force(server, server);
foreach (string tab in view.VisibleTabs())
@ -908,7 +846,7 @@ namespace RynthOracle.Tests
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),
(OracleView.TabVoid, 1, 0),
})
{
chars = quests = 0;
@ -936,45 +874,6 @@ namespace RynthOracle.Tests
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)

View file

@ -28,6 +28,8 @@
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthOracle\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthOracle\obj\**;..\..\Plugins\RynthCore.Plugin.RynthOracle\bin\**" Link="RynthOracle\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Combat\FellowshipTracker.cs" Link="RynthOracle\Shared\FellowshipTracker.cs" />
<Compile Include="..\..\Plugins\Shared\RynthIltServerApi.cs" Link="RynthOracle\Shared\RynthIltServerApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthIltDataApi.cs" Link="RynthOracle\Shared\RynthIltDataApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiHubApi.cs" Link="RynthOracle\Shared\RynthAiHubApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiSessionClient.cs" Link="RynthOracle\Shared\RynthAiSessionClient.cs" />
<!-- RynthCore's server list and the owner plugin's profile (as in the plugin's csproj). -->
@ -47,7 +49,8 @@
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthOracle\Resources\society.csv" LogicalName="RynthOracle.society.csv" />
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthOracle\Resources\titles.csv" LogicalName="RynthOracle.titles.csv" />
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthOracle\Resources\markers.csv" LogicalName="RynthOracle.markers.csv" />
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthOracle\Resources\customquests.csv" LogicalName="RynthOracle.customquests.csv" />
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthOracle\Resources\legendary.csv" LogicalName="RynthOracle.legendary.csv" />
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthOracle\Resources\dynstamps.csv" LogicalName="RynthOracle.dynstamps.csv" />
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Combat\SpellData.txt" LogicalName="RynthOracle.SpellData.txt" />
</ItemGroup>

View file

@ -0,0 +1,112 @@
using System;
using System.IO;
using System.Text.Json;
using RynthCore.Plugin.RynthOracle;
using RynthCore.Plugin.RynthOracle.Data;
using RynthCore.Plugin.RynthOracle.Views;
namespace RynthOracle.Tests
{
// RynthOracle without one server's features (2026-10-20: Conquest's went to RynthConquest,
// Aelrynth's to RynthAelrynth): the settings file keeps what moved, so the server plugin can
// take it over once, and nothing of those servers is left in RynthOracle itself.
internal static partial class Program
{
private static void ServerMove()
{
SettingsKeepUnknown();
ConquestGone();
AelrynthGone();
}
/// <summary>Aelrynth without RynthAelrynth: no leaderboards or Trials in RynthOracle (the quest pack stays, as data).</summary>
private static void AelrynthGone()
{
Check(typeof(RynthOraclePlugin).Assembly.GetType("RynthCore.Plugin.RynthOracle.Data.AelrynthBoards") == null,
"aelrynth: the /top and /trial parser is not in RynthOracle");
Check(typeof(OracleContext).GetField("Boards") == null, "aelrynth: RynthOracle keeps no leaderboard data");
var c = new OracleContext { InWorld = true };
var view = new OracleView(c);
c.Server.Force(ServerTags.Aelrynth, "Aeshnidae");
string[] tabs = view.VisibleTabs();
Check(Array.IndexOf(tabs, "Leaderboards") < 0, "aelrynth: no Leaderboards tab in RynthOracle on Aelrynth: " + string.Join(",", tabs));
c.Catalog.Load(ServerTags.Aelrynth, null);
Check(c.Catalog.PackServer == ServerTags.Aelrynth && c.Catalog.ServerCount > 0, "aelrynth: the quest pack is still RynthOracle's (data)");
}
/// <summary>
/// Conquest without RynthConquest: no Conquest data, setting, auto-deposit or tab in RynthOracle,
/// and the Void DoT rule comes only from the server plugin's profile.
/// </summary>
private static void ConquestGone()
{
const System.Reflection.BindingFlags All = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static
| System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic;
Check(typeof(OracleSettings).GetField("ConquestAutoDeposit", All) == null, "conquest: RynthOracle has no auto-deposit setting");
Check(typeof(OracleContext).GetField("Conquest", All) == null, "conquest: RynthOracle keeps no Conquest data");
Check(typeof(RynthOraclePlugin).GetMethod("TickConquest", All) == null, "conquest: RynthOracle's tick has no Conquest part (no auto-deposit, no /augs)");
Check(typeof(RynthOraclePlugin).Assembly.GetType("RynthCore.Plugin.RynthOracle.Data.ConquestData") == null
&& typeof(RynthOraclePlugin).Assembly.GetType("RynthCore.Plugin.RynthOracle.Data.CustomQuestList") == null,
"conquest: the Conquest reply parser and custom quest list are not in RynthOracle");
// Conquest tagged by its world name (RynthConquest not installed): retail tabs only.
var c = new OracleContext { InWorld = true };
var view = new OracleView(c);
c.Server.Force(ServerTags.Conquest, "Conquest");
string[] tabs = view.VisibleTabs();
Check(Array.IndexOf(tabs, "Conquest") < 0 && Array.IndexOf(tabs, "Leaderboards") < 0,
"conquest: no Conquest pages in RynthOracle on Conquest: " + string.Join(",", tabs));
// The Void DoT rule: whatever the server plugin publishes (1 to 10), 1 without one.
Check(RynthOraclePlugin.VoidScaleFrom(null) == 1.0 && RynthOraclePlugin.VoidScaleFrom("") == 1.0, "void scale: 1 without a profile");
Check(RynthOraclePlugin.VoidScaleFrom("{\"id\":\"coldeve\",\"values\":{}}") == 1.0, "void scale: 1 for a server without the rule");
Check(Math.Abs(RynthOraclePlugin.VoidScaleFrom("{\"id\":\"conquest\",\"values\":{\"voidDotDurationScale\":2.15}}") - 2.15) < 1e-12,
"void scale: RynthConquest's value is applied");
Check(RynthOraclePlugin.VoidScaleFrom("{\"values\":{\"voidDotDurationScale\":0.5}}") == 1.0
&& RynthOraclePlugin.VoidScaleFrom("{\"values\":{\"voidDotDurationScale\":50}}") == 1.0,
"void scale: a value out of 1..10 is ignored");
var v = new VoidTracker();
v.OnChatLine("You cast Corrosion VII on Drudge Slinker", 1_000_000, _ => 0x50000001u, () => false, 2.0);
Check(v.Remaining(0x50000001u, "Drudge Slinker", VoidFamily.Corrosion, 1_001_000, out _) == 31,
"void scale: a scaled Corrosion lasts 30 s (+2 s before the first tick)");
}
/// <summary>A value this version doesn't use survives a load and a save, unchanged.</summary>
private static void SettingsKeepUnknown()
{
string? saved = OracleSettings.PathOverride;
string path = Path.Combine(Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N") + "-keep.json");
OracleSettings.PathOverride = path;
try
{
File.WriteAllText(path, "{ \"hideOwnQuestReplies\": false, \"conquestAutoDeposit\": true, \"fromTheFuture\": {\"x\": [1, \"two\"]}, \"tabName\": \"Void\" }");
var s = new OracleSettings();
s.Load();
Check(!s.HideOwnQuestReplies && s.TabName == "Void", "settings: known values read as before");
s.MainWindowOpen = true;
s.Save();
using (JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path)))
{
JsonElement r = doc.RootElement;
Check(r.TryGetProperty("conquestAutoDeposit", out JsonElement cq) && cq.ValueKind == JsonValueKind.True,
"settings: a moved setting (conquestAutoDeposit) is still in the file after a save");
Check(r.TryGetProperty("fromTheFuture", out JsonElement f) && f.GetProperty("x").GetArrayLength() == 2,
"settings: an unknown value is written back unchanged");
Check(r.GetProperty("mainWindowOpen").GetBoolean(), "settings: the change was saved");
}
var again = new OracleSettings();
again.Load();
again.Save();
again.Save();
string text = File.ReadAllText(path);
Check(text.IndexOf("fromTheFuture", StringComparison.Ordinal) == text.LastIndexOf("fromTheFuture", StringComparison.Ordinal),
"settings: kept values aren't duplicated by repeated saves");
}
finally
{
try { File.Delete(path); } catch { }
OracleSettings.PathOverride = saved;
}
}
}
}

View file

@ -0,0 +1,119 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Engine.UI.Sections;
using RynthCore.Plugin.RynthAelrynth;
using RynthCore.Plugin.ServerPack;
using RynthCore.RynthAiTests.Harness;
namespace RynthServerPack.Tests;
// RynthAelrynth's own features (Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth), moved out of
// RynthOracle on 2026-10-20: the /top and /trial reply parser (RynthOracle.Tests' old
// AelrynthReplies), the own-reply hiding, the setting taken over from rynthoracle.json and its page.
internal static class AelrynthTests
{
public static void Register(Runner r)
{
r.Add("aelrynth: the replies of /top, /top me and /trial parse", Replies);
r.Add("aelrynth: replies to RynthAelrynth's own requests are hidden, typed ones show", HideOwnReplies);
r.Add("aelrynth: RynthOracle's reply-hiding choice is taken over once", Migration);
r.Add("aelrynth: its Leaderboards page is an Aelrynth-only view of the Server section", Pages);
}
private static void Replies()
{
var a = new AelrynthBoards();
long now = 2_000_000;
a.RequestTop("", now);
Check.True(a.OnChatLine("Leaderboards - 37 characters, refreshed 4 min ago. /top <board> for the top ten, /top me for yourself.", now, out bool ours) && ours, "overview header");
a.OnChatLine(" kills Creature kills: Buffy, 1,234,567", now, out _);
a.OnChatLine(" pk PK kills: nobody yet", now, out _);
Check.True(a.Overview.Count == 2 && a.Overview[0].Key == "kills" && a.Overview[0].Leader == "Buffy" && a.Overview[0].Value == "1,234,567"
&& a.Overview[1].Leader == "nobody yet", "overview rows");
a.RequestTop("kills", now);
a.OnChatLine("Creature kills - top 10 of 37:", now, out _);
a.OnChatLine(" 1. Buffy 1,234,567 <- you", now, out _);
a.OnChatLine(" 2. Dargoth 987,654", now, out _);
a.OnChatLine(" 3. Sal 500 12 kills per death", now, out _);
Check.True(a.BoardTitle == "Creature kills" && a.BoardRows.Count == 3 && a.BoardRows[0].IsYou && a.BoardRows[1].Value == "987,654"
&& a.BoardRows[2].Extra == "12 kills per death", "board rows: " + string.Join(" | ", a.BoardRows.Select(r => $"{r.Rank} {r.Name} {r.Value} [{r.Extra}] {r.IsYou}")));
a.RequestTop("me", now);
a.OnChatLine("Buffy on the boards:", now, out _);
a.OnChatLine(" Creature kills #1 of 37, 1,234,567", now, out _);
a.OnChatLine(" PK kills -", now, out _);
Check.True(a.Standings.Count == 2 && a.Standings[0].Rank == 1 && a.Standings[1].Rank == 0, "/top me");
Check.False(a.OnChatLine(" 9. Nobody 12", now + 30_000, out _), "an entry long after its header is ignored");
a.RequestTrial("", now);
a.OnChatLine("Trials - a fresh personal copy of a listed dungeon, entered through its portal, is a timed course: ...", now, out _);
a.OnChatLine(" The Citadel Below - Trial (02F0): tier 0 12:34 by Buffy | you: tier 0 12:34 | this week: Buffy 12:34 (tier 0)", now, out _);
a.OnChatLine(" your next attempt here: in 12 min", now, out _);
a.OnChatLine("Trophy: the week's fastest clear of each dungeon, any tier - a trophy and 1,000 experience, Sunday 20:00 (2026-W40). /trial <name> for the top 10 of one dungeon.", now, out _);
Check.True(a.Trials.Count == 1 && a.Trials[0].Landblock == "02F0" && a.TrialLines.Count == 3, $"/trial overview ({a.Trials.Count} dungeons, {a.TrialLines.Count} lines)");
a.RequestTrial("citadel", now);
a.OnChatLine("The Citadel Below - Trial (02F0) - top 10, best per character, any tier:", now, out _);
a.OnChatLine(" 1. 12:34 Buffy (tier 0, 105 kills, 3 Oct)", now, out _);
a.OnChatLine(" you: tier 0 12:34 (105 kills)", now, out _);
Check.True(a.TrialRows.Count == 1 && a.TrialRows[0].Name == "Buffy" && a.TrialRows[0].Value == "12:34" && a.TrialNotes.Count == 1, "/trial dungeon top 10");
Check.False(a.OnChatLine("Bob tells you, \"hello\"", now, out _), "ordinary chat is never taken");
}
private static void HideOwnReplies()
{
var f = new AelrynthFeature();
long now = 3_000_000;
f.Boards.RequestTop("", now);
Check.True(f.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top <board> ...", 0, now), "a reply to RynthAelrynth's /top is hidden");
Check.True(f.OnChatLine(" kills Creature kills: Buffy, 12", 0, now), "and its rows");
Check.False(f.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top <board> ...", 0, now + 60_000), "a typed /top's reply shows");
Check.False(f.OnChatLine(" kills Creature kills: Ann, 14", 0, now + 60_000), "and its rows");
Check.True(f.Boards.Overview.Count == 1 && f.Boards.Overview[0].Leader == "Ann", "read either way");
f.HideOwnReplies = false;
f.Boards.RequestTrial("", now);
Check.False(f.OnChatLine("Trials - a fresh personal copy of a listed dungeon ...", 0, now), "with hiding off, own replies show too");
Check.False(f.OnChatLine("Bob says, \"hi\"", 0, now), "ordinary chat shows");
f.Reset();
Check.True(f.Boards.Overview.Count == 0 && f.Boards.Trials.Count == 0, "login/logout clears the boards");
}
private static void Migration()
{
string dir = ServerPackHooksTests.TempDir();
try
{
string oracle = Path.Combine(dir, "rynthoracle.json"), mine = Path.Combine(dir, "rynthaelrynth.json");
File.WriteAllText(oracle, "{ \"hideOwnQuestReplies\": false }");
var s = new ServerPackSettings(mine);
s.Load();
Check.True(AelrynthFeature.Migrate(s, oracle), "taken over the first time");
var f = new AelrynthFeature();
f.LoadSettings(s);
Check.False(f.HideOwnReplies, "the player's choice (shown) came over");
Check.False(AelrynthFeature.Migrate(s, oracle), "never twice");
var fresh = new ServerPackSettings(Path.Combine(dir, "fresh.json"));
fresh.Load();
AelrynthFeature.Migrate(fresh, Path.Combine(dir, "none.json"));
var g = new AelrynthFeature();
g.LoadSettings(fresh);
Check.True(g.HideOwnReplies, "default: hidden");
}
finally { try { Directory.Delete(dir, true); } catch { } }
}
private static void Pages()
{
var pages = ServerPackPages.Validate(AelrynthFeature.PageList.Select(p => new ServerPage(p.Id, p.Label, p.Tooltip, () => { })));
Check.Eq(pages.Count, 1, "one page");
ServerPackInfo info = new("aelrynth", "Aelrynth", new[] { "aelrynth.com" }, new[] { "Aelrynth*", "Aeshnidae*" });
SectionManifest m = SectionManifestParser.Parse("RynthAelrynth", ServerPackModel.BuildSectionsJson(info, "RynthAelrynth", pages), out string error);
Check.Eq(error, "", "RynthCore parses the manifest");
SectionContribution view = m.Contributions.Single(c => c.Primary);
Check.True(view.Server == "aelrynth" && view.Label == "Leaderboards" && view.Surface == "section:server-aelrynth.boards",
"Leaderboards, only while Aelrynth is active");
}
}

View file

@ -0,0 +1,216 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Engine.UI.Sections;
using RynthCore.Plugin.RynthConquest;
using RynthCore.Plugin.RynthOracle.Data;
using RynthCore.Plugin.ServerPack;
using RynthCore.RynthAiTests.Harness;
namespace RynthServerPack.Tests;
// RynthConquest's own features (Plugins\RynthCore.Plugin.RynthConquest\Conquest), moved out of
// RynthOracle on 2026-10-20: the reply parser (RynthOracle.Tests' old ConquestReplies), the
// own-reply hiding, the login /augs, the auto-deposit, the settings taken over from rynthoracle.json,
// the Void DoT rule it publishes, the custom quest list and its pages.
internal static class ConquestTests
{
public static void Register(Runner r)
{
r.Add("conquest: the replies of /b, /augs, /enl augs, /bonus, /fship list and /top parse", Replies);
r.Add("conquest: replies to RynthConquest's own requests are hidden, typed ones show", HideOwnReplies);
r.Add("conquest: /augs once after login, then never again", LoginAugs);
r.Add("conquest: the auto-deposit is off unless turned on, then once per ten-minute mark", AutoDeposit);
r.Add("conquest: RynthOracle's settings are taken over once (defaults kept without them)", Migration);
r.Add("conquest: the Void DoT rule for RynthOracle's timers", VoidRule);
r.Add("conquest: the custom quest worklist and its status", CustomQuests);
r.Add("conquest: its pages are Conquest-only views of the Server section", Pages);
}
private static void Replies()
{
var d = new ConquestData();
long now = 1_000_000;
d.RequestBank(now);
Check.True(d.OnChatLine("[BANK] Your balances:", now, out bool ours) && ours, "bank heading (ours)");
d.OnChatLine("[BANK] Pyreals: 1,039,678,533", now, out _);
d.OnChatLine("[BANK] Event Tokens [Dragon Coins] (x): 12", now, out _);
Check.True(d.Bank.Any(b => b.Name == "Pyreals" && b.Value.Contains("4,158 MMDs")), "pyreals with MMDs");
Check.True(d.Bank.Any(b => b.Name == "Dragon Coins (x)"), "event token name");
Check.False(d.OnChatLine("Bob says, \"[BANK] Pyreals: 999\"", now, out _), "a pasted balance is ignored");
d.OnChatLine("[BANK] Pyreals: 5", now + 60_000, out bool late);
Check.False(late, "a reply long after the request isn't ours (shows in chat)");
d.RequestAugs(now);
d.OnChatLine("Creature: 25", now, out _);
d.OnChatLine("Duration: 3", now, out _);
ConquestAug creature = d.Augs.First(a => a.Name == "Creature");
Check.True(creature.Count == 25 && creature.NextLuminanceCost() == 6_229_500, $"Creature 25 next costs 6,229,500 ({creature.NextLuminanceCost()})");
Check.True(d.DurationAugs == 3 && Math.Abs(d.VoidDurationMultiplier(5) - 2.15) < 1e-9, "void duration x(1 + 5*0.2 + 3*0.05)");
d.RequestEnl(now);
d.OnChatLine("Enlightenment Augmentations:", now, out _);
d.OnChatLine("Skill Credits: 2 (10 max)", now, out _);
d.OnChatLine("Damage: 5 (25 max)", now, out _);
Check.True(d.EnlAugs.Count == 2 && d.EnlAugs[0].Name == "Damage", "enlightenment augs in display order");
d.RequestBonus(now);
d.OnChatLine("=== XP Bonuses ===", now, out _);
d.OnChatLine("Quest Bonus: 14.18% (1,418 quests)", now, out _);
d.OnChatLine("Total Bonus (Kills): 0.16%", now, out _);
Check.True(d.Bonuses.First(b => b.Name == "Quest").Value == "14.18% (1,418 quests)" && d.Bonuses.First(b => b.Name == "Total (Kills)").Value == "0.16%", "bonuses");
d.RequestFships(now);
d.OnChatLine("Fellowships looking for members:", now, out _);
d.OnChatLine("- Heroes (Leader: Bob) [3/14] @ Bur", now, out _);
d.OnChatLine("- Quiet (Leader: Ann) [1/14]", now, out _);
Check.True(d.Fellowships.Count == 2 && d.Fellowships[0].Location == "Bur" && d.Fellowships[1].MemberCount == 1, "fellowship list");
ConquestBoard lvl = d.Boards.First(b => b.Key == "level");
d.RequestBoard(lvl, now);
d.OnChatLine("Top 2 Players by Level:", now, out _);
d.OnChatLine("1: 300 - Alpha", now, out _);
d.OnChatLine("2: 299 - Beta", now, out _);
d.OnChatLine("57: 250 - Me (You)", now, out _);
Check.True(lvl.Rows.Count == 2 && lvl.You != null && lvl.You.Rank == 57 && lvl.You.Name == "Me", "Conquest /top board");
Check.Eq(ConquestData.WithdrawCommand(ConquestData.Withdrawable[ConquestData.DefaultWithdraw], "10"), "/bank withdraw n 10", "withdraw MMDs");
Check.Null(ConquestData.WithdrawCommand(ConquestData.Withdrawable[0], "-3"), "withdraw refuses a bad amount");
Check.Eq(ConquestData.TransferCommand(ConquestData.Transferable[2], "4", "Some One"), "/bank transfer p 1000000 \"Some One\"", "transfer MMD notes as pyreals");
Check.Null(ConquestData.TransferCommand(ConquestData.Transferable[2], "1001", "X"), "transfer cap");
}
private static void HideOwnReplies()
{
var f = new ConquestFeature();
f.Login(0);
long now = 100_000;
f.Data.RequestBank(now);
Check.True(f.OnChatLine("[BANK] Pyreals: 1,000", now), "a reply to RynthConquest's /b is hidden");
Check.False(f.OnChatLine("[BANK] Pyreals: 1,000", now + 60_000), "the same reply long after (typed /b) shows");
Check.False(f.OnChatLine("Bob says, \"hello\"", now), "ordinary chat shows");
f.HideOwnReplies = false;
f.Data.RequestBank(now);
Check.False(f.OnChatLine("[BANK] Pyreals: 1,000", now), "with hiding off, own replies show too");
f.HideOwnReplies = true;
// /myquests: only RynthConquest's own request's reply is hidden; the flags are read either way.
Check.True(f.Flags.Request(_ => true, now), "own /myquests sent");
Check.True(f.OnChatLine("assaultonaimaru - 1 solves (1719432000)\"x\" -1 0", now), "its reply is hidden");
f.Flags.Tick(now + 2000);
Check.True(f.Flags.TryGet("assaultonaimaru", out _), "and read");
Check.False(f.OnChatLine("ghostdencompleted - 1 solves (1719432000)\"x\" -1 0", now + 3000), "a reply nobody here asked for shows");
Check.True(f.Data.AutoDeposit(now).Length > 0 && f.OnChatLine("Deposited 12 items.", now), "the auto-deposit's reply is hidden");
}
private static void LoginAugs()
{
var f = new ConquestFeature();
f.Login(1000);
Check.Null(f.LoginAugsDue(1000 + ConquestFeature.AugsReadDelayMs), "not before the delay");
Check.Eq(f.LoginAugsDue(1001 + ConquestFeature.AugsReadDelayMs), "/augs", "/augs after it");
Check.Null(f.LoginAugsDue(5_000_000), "only once");
f.Login(9_000_000);
Check.Eq(f.LoginAugsDue(9_000_001 + ConquestFeature.AugsReadDelayMs), "/augs", "again for the next login");
}
private static void AutoDeposit()
{
var f = new ConquestFeature();
f.Login(0);
var at = new DateTime(2026, 10, 20, 14, 0, 5, DateTimeKind.Local);
Check.False(f.AutoDeposit, "off by default (as it was in RynthOracle)");
Check.Null(f.AutoDepositDue(at, 0), "off: no deposit at :00");
f.AutoDeposit = true;
Check.Eq(f.AutoDepositDue(at, 0), "/bank deposit", "on: /bank deposit at :00");
Check.Null(f.AutoDepositDue(at.AddSeconds(30), 0), "once per mark");
Check.Null(f.AutoDepositDue(at.AddMinutes(5), 0), "not at :05");
Check.Eq(f.AutoDepositDue(at.AddMinutes(10), 0), "/bank deposit", "again at :10");
long block = -1;
Check.True(ConquestFeature.DepositDue(new DateTime(2026, 1, 1, 0, 20, 0), ref block), "the schedule: :20");
Check.False(ConquestFeature.DepositDue(new DateTime(2026, 1, 1, 0, 21, 0), ref block), "the schedule: not :21");
}
private static void Migration()
{
string dir = ServerPackHooksTests.TempDir();
try
{
string oracle = Path.Combine(dir, "rynthoracle.json"), mine = Path.Combine(dir, "rynthconquest.json");
File.WriteAllText(oracle, "{ \"hideOwnQuestReplies\": false, \"conquestAutoDeposit\": true, \"tabName\": \"Conquest\" }");
var s = new ServerPackSettings(mine);
s.Load();
Check.True(ConquestFeature.Migrate(s, oracle), "taken over the first time");
var f = new ConquestFeature();
f.LoadSettings(s);
Check.True(f.AutoDeposit, "auto-deposit came over (on)");
Check.False(f.HideOwnReplies, "hiding came over (off)");
// Turned off here later: a newer rynthoracle.json never turns it back on.
f.AutoDeposit = false;
f.SaveSettings(s);
var again = new ServerPackSettings(mine);
again.Load();
Check.False(ConquestFeature.Migrate(again, oracle), "never taken over twice");
var g = new ConquestFeature();
g.LoadSettings(again);
Check.False(g.AutoDeposit, "the player's choice here stands");
// A new player (no RynthOracle settings): the defaults.
string fresh = Path.Combine(dir, "fresh.json");
var n = new ServerPackSettings(fresh);
n.Load();
Check.True(ConquestFeature.Migrate(n, Path.Combine(dir, "missing.json")), "runs (nothing to take)");
var h = new ConquestFeature();
h.LoadSettings(n);
Check.True(!h.AutoDeposit && h.HideOwnReplies, "defaults: auto-deposit off, own replies hidden");
Check.True(new ServerPackSettings(fresh) is var reread && Reload(reread) && reread.GetBool(ConquestFeature.MigrationMarker, false),
"the marker is saved");
}
finally { try { Directory.Delete(dir, true); } catch { } }
}
private static bool Reload(ServerPackSettings s) { s.Load(); return true; }
private static void VoidRule()
{
var f = new ConquestFeature();
f.Login(0);
Check.Eq(f.VoidScale, 1.0, "no augs, no Archmage's Endurance: x1");
f.ArchmagesEndurance = 5;
f.Data.RequestAugs(0);
f.Data.OnChatLine("Duration: 3", 0, out _);
Check.Near(f.VoidScale, 2.15, 1e-9, "x(1 + 5*0.2 + 3*0.05)");
Check.Eq(ConquestFeature.VoidScaleKey, "voidDotDurationScale", "the profile value RynthOracle reads");
}
private static void CustomQuests()
{
Check.Eq(CustomQuestList.All.Count, 6, "six custom quests (customquests.csv, embedded)");
Check.True(CustomQuestList.All.All(q => q.Server == "Conquest" && q.Flag.Length > 0 && q.Flag == q.Flag.ToLowerInvariant()), "Conquest rows, flags in lower case");
var flags = new QuestFlagStore();
CustomQuest darsh = CustomQuestList.All.First(q => q.Flag == "assaultonaimaru");
DateTime now = DateTime.UtcNow;
Check.False(darsh.IsComplete(flags, now), "not done without the flag");
Check.Eq(darsh.Status(flags, now), "ready", "ready without the flag");
long done = DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 60;
flags.OnChatLine($"assaultonaimaru - 1 solves ({done})\"x\" -1 3600", 0);
flags.Tick(5000);
Check.True(darsh.IsComplete(flags, now), "a repeatable on cooldown counts as done");
Check.True(darsh.Status(flags, now) is not ("ready" or "completed") && darsh.Status(flags, now).Contains('m'), "its status is the time left: " + darsh.Status(flags, now));
}
private static void Pages()
{
var pages = ServerPackPages.Validate(ConquestFeature.PageList.Select(p => new ServerPage(p.Id, p.Label, p.Tooltip, () => { })));
Check.Eq(pages.Count, ConquestFeature.PageList.Length, "every page is valid");
Check.True(pages.Select(p => p.Label).SequenceEqual(new[] { "Conquest", "Leaderboards" }), "the Conquest and Leaderboards pages");
ServerPackInfo info = new("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest", "ConquestAC" });
SectionManifest m = SectionManifestParser.Parse("RynthConquest", ServerPackModel.BuildSectionsJson(info, "RynthConquest", pages), out string error);
Check.Eq(error, "", "RynthCore parses the manifest");
SectionContribution[] views = m.Contributions.Where(c => c.Primary).ToArray();
Check.Eq(views.Length, 2, "two pages in the Mini Remote");
Check.True(views.All(c => c.Server == "conquest"), "shown only while Conquest is active");
Check.True(views.Select(c => c.Surface).SequenceEqual(new[] { "section:server-conquest.main", "section:server-conquest.boards" }), "their surfaces");
}
}

View file

@ -13,6 +13,10 @@ internal static class Program
var runner = new Runner();
ServerPackModelTests.Register(runner);
ServerProjectsTests.Register(runner);
ServerPackHooksTests.Register(runner);
ConquestTests.Register(runner);
AelrynthTests.Register(runner);
VaultTests.Register(runner);
return runner.Run("RynthServerPack tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -23,6 +23,26 @@
<ItemGroup>
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackInfo.cs" Link="Plugin\ServerPackInfo.cs" />
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackModel.cs" Link="Plugin\ServerPackModel.cs" />
<!-- The hooks for a server's own features: pages, the settings file, the own-reply window. -->
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackPages.cs" Link="Plugin\ServerPackPages.cs" />
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackSettings.cs" Link="Plugin\ServerPackSettings.cs" />
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerChatRequest.cs" Link="Plugin\ServerChatRequest.cs" />
<!-- RynthConquest's own features (pure parts) and the RynthOracle sources it links. -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Conquest\ConquestData.cs" Link="Conquest\ConquestData.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Conquest\ConquestFeature.cs" Link="Conquest\ConquestFeature.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Conquest\CustomQuests.cs" Link="Conquest\CustomQuests.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthOracle\Data\QuestFlags.cs" Link="Oracle\QuestFlags.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthOracle\Data\TimeText.cs" Link="Oracle\TimeText.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthOracle\Data\Csv.cs" Link="Oracle\Csv.cs" />
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Resources\customquests.csv" LogicalName="RynthConquest.customquests.csv" />
<!-- RynthAelrynth's own features (pure parts). -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth\AelrynthBoards.cs" Link="Aelrynth\AelrynthBoards.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth\AelrynthFeature.cs" Link="Aelrynth\AelrynthFeature.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth\VaultFeed.cs" Link="Aelrynth\VaultFeed.cs" />
<Compile Include="..\..\Plugins\Shared\ChatSource.cs" Link="Shared\ChatSource.cs" />
<Compile Include="..\..\Plugins\Shared\StorageFeed.cs" Link="Shared\StorageFeed.cs" />
<!-- RynthCore's own sections-manifest parser (pure), so the manifest is checked the way the engine reads it. -->
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Sections\SectionManifest.cs" Link="Engine\SectionManifest.cs" />
<!-- "RynthServer.Profile": the profile JSON, and the shared reader's parser that consumes it. -->
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackProfile.cs" Link="Plugin\ServerPackProfile.cs" />
<Compile Include="..\..\Plugins\Shared\EngineServerState.cs" Link="Shared\EngineServerState.cs" />

View file

@ -0,0 +1,210 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using RynthCore.Engine.UI.Sections;
using RynthCore.Plugin.ServerPack;
using RynthCore.RynthAiTests.Harness;
namespace RynthServerPack.Tests;
// The shared hooks a server plugin's own features use (2026-10-20, when RynthOracle's and
// RynthInventory's Conquest and Aelrynth features moved into RynthConquest and RynthAelrynth):
// pages beside the server card, the plugin's own settings file (with a one-time migration), live
// numbers in the "RynthServer.Profile" JSON, and the own-reply window.
internal static class ServerPackHooksTests
{
public static void Register(Runner r)
{
r.Add("hooks: page ids, surfaces and the surface a page is drawn under", PageNames);
r.Add("hooks: bad, duplicate and surplus pages are left out", PageValidation);
r.Add("hooks: pages are server-only primary views of the Server section, accepted by RynthCore's parser", PagesInManifest);
r.Add("hooks: settings round-trip and keep values the plugin doesn't know", SettingsRoundTrip);
r.Add("hooks: settings migration runs once, and a broken file means defaults", SettingsMigration);
r.Add("hooks: profile values are published, validated and read back", ProfileValues);
r.Add("hooks: the own-reply window opens, stretches and closes", ReplyWindow);
}
internal static string TempDir()
{
string dir = Path.Combine(Path.GetTempPath(), "RynthServerPack.Tests", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
return dir;
}
private static void PageNames()
{
Check.True(ServerPackPages.IsValidId("bank") && ServerPackPages.IsValidId("top-10"), "plain ids");
Check.False(ServerPackPages.IsValidId("") || ServerPackPages.IsValidId("Bank") || ServerPackPages.IsValidId("a.b")
|| ServerPackPages.IsValidId(new string('a', 17)), "empty, capitals, dots and long ids are refused");
Check.Eq(ServerPackPages.SurfaceFor("conquest", "bank"), "section:server-conquest.bank", "surface");
Check.Eq(ServerPackPages.PageIdOf("section:server-conquest.bank", "conquest"), "bank", "page from its surface");
Check.Eq(ServerPackPages.PageIdOf("section:server-conquest.bank:popout", "conquest"), "bank", "popped out");
Check.Null(ServerPackPages.PageIdOf("section:server-conquest", "conquest"), "the card is not a page");
Check.Null(ServerPackPages.PageIdOf("section:server-aelrynth.top", "conquest"), "another server's page");
Check.Null(ServerPackPages.PageIdOf("section:server-conquest.Bad!", "conquest"), "a malformed page id");
Check.Null(ServerPackPages.PageIdOf(null, "conquest"), "null");
string longest = ServerPackPages.SurfaceFor(new string('a', 32), new string('b', ServerPackPages.MaxIdLength));
Check.True(longest.Length <= SectionManifestParser.MaxSurfaceLength, "the longest surface fits RynthCore's cap: " + longest.Length);
}
private static void PageValidation()
{
Action draw = () => { };
var notes = new List<string>();
var pages = new List<ServerPage>
{
new("one", "One", "", draw), new("one", "Again", "", draw), new("Two", "Two", "", draw),
new("three", " ", "", draw), new("four", "Four", "tip", null!),
};
for (int i = 0; i < 8; i++) pages.Add(new ServerPage("p" + i, "Page " + i, "", draw));
List<ServerPage> kept = ServerPackPages.Validate(pages, notes.Add);
Check.Eq(kept.Count, ServerPackPages.MaxPages, "capped");
Check.Eq(kept[0].Id, "one", "first kept");
Check.Eq(kept.Count(p => p.Id == "one"), 1, "a duplicate id is dropped");
Check.False(kept.Any(p => p.Id is "Two" or "three" or "four"), "bad id, no label, nothing to draw");
Check.True(notes.Count == pages.Count - kept.Count, "every dropped page is reported: " + string.Join(" | ", notes));
Check.Eq(ServerPackPages.Validate(null).Count, 0, "no pages");
string label = new string('x', 60);
Check.Eq(ServerPackPages.Validate(new[] { new ServerPage("x", label, "", draw) })[0].Label.Length, ServerPackPages.MaxLabelLength, "label capped");
}
private static void PagesInManifest()
{
ServerPackInfo info = new("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest" });
var pages = ServerPackPages.Validate(new[]
{
new ServerPage("main", "Conquest", "Bank, augs and more", () => { }),
new ServerPage("boards", "Leaderboards", "", () => { }),
});
string json = ServerPackModel.BuildSectionsJson(info, "RynthConquest", pages);
SectionManifest m = SectionManifestParser.Parse("RynthConquest", json, out string error);
Check.Eq(error, "", "RynthCore parses it");
Check.Eq(m.Contributions.Length, 3, "the card and two pages");
SectionContribution card = m.Contributions.Single(c => !c.Primary);
Check.Eq(card.Surface, "section:server-conquest", "the card keeps its surface");
SectionContribution[] views = m.Contributions.Where(c => c.Primary).ToArray();
Check.True(views.All(c => c.Section == ServerPackModel.SectionId && c.Server == "conquest" && c.IsSurface),
"pages: primary views of the Server section, only on Conquest");
Check.Eq(views[0].Surface, "section:server-conquest.main", "page surface");
Check.Eq(views[0].Label, "Conquest", "page label");
Check.Eq(views[0].Tooltip, "Bank, augs and more", "page tooltip");
Check.Eq(views[1].Tooltip, "Leaderboards (RynthConquest)", "a default tooltip");
Check.True(views[0].Order < views[1].Order, "pages keep their order");
Check.True(views[0].Width > 0 && views[0].Height > 0, "pages say their size");
// Without pages the manifest is byte for byte what it was.
Check.Eq(ServerPackModel.BuildSectionsJson(info, "RynthConquest", null), ServerPackModel.BuildSectionsJson(info, "RynthConquest"),
"no pages: the old manifest");
Check.Eq(SectionManifestParser.Parse("x", ServerPackModel.BuildSectionsJson(info, "RynthConquest"), out _).Contributions.Length, 1,
"no pages: only the card");
}
private static void SettingsRoundTrip()
{
string dir = TempDir();
try
{
string path = Path.Combine(dir, "rynthtest.json");
File.WriteAllText(path, "{ \"future\": {\"a\":[1,2]}, \"flag\": false, \"name\": \"x\" }");
var s = new ServerPackSettings(path);
s.Load();
Check.Eq(s.LastError, "", "read");
Check.False(s.GetBool("flag", true), "a stored false");
Check.True(s.GetBool("missing", true), "a missing value falls back");
Check.True(s.GetBool("name", true), "a value of another type falls back");
Check.Eq(s.GetString("name", "?"), "x", "text");
Check.True(s.SetBool("flag", true), "a change says so");
Check.False(s.SetBool("flag", true), "the same value is no change");
s.SetString("quote", "a \"b\" \\ c");
Check.True(s.Save(), "saved");
var again = new ServerPackSettings(path);
again.Load();
Check.True(again.GetBool("flag", false), "the change was kept");
Check.Eq(again.GetString("quote", ""), "a \"b\" \\ c", "text escaped and read back");
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path));
Check.Eq(doc.RootElement.GetProperty("future").GetProperty("a").GetArrayLength(), 2, "an unknown value is written back as it was");
Check.False(File.Exists(path + ".tmp"), "no temporary file left");
Check.True(ServerPackSettings.DefaultPath("RynthConquest").EndsWith(Path.Combine("RynthCore", "rynthconquest.json"), StringComparison.Ordinal),
"%APPDATA%\\RynthCore\\<plugin>.json");
}
finally { try { Directory.Delete(dir, true); } catch { } }
}
private static void SettingsMigration()
{
string dir = TempDir();
try
{
string old = Path.Combine(dir, "old.json"), mine = Path.Combine(dir, "mine.json");
File.WriteAllText(old, "{ \"moved\": true, \"text\": \"t\" }");
Check.Eq(ServerPackSettings.ReadBoolFrom(old, "moved"), (bool?)true, "the old home's value");
Check.Null(ServerPackSettings.ReadBoolFrom(old, "text"), "not a true/false value");
Check.Null(ServerPackSettings.ReadBoolFrom(old, "absent"), "missing value");
Check.Null(ServerPackSettings.ReadBoolFrom(Path.Combine(dir, "nope.json"), "moved"), "missing file");
var s = new ServerPackSettings(mine);
s.Load();
int runs = 0;
Action<ServerPackSettings> migrate = t => { runs++; if (ServerPackSettings.ReadBoolFrom(old, "moved") is bool b) t.SetBool("moved", b); };
Check.True(s.MigrateOnce("migratedFromOld", migrate), "runs the first time");
Check.True(s.GetBool("moved", false), "imported");
File.WriteAllText(old, "{ \"moved\": false }");
var later = new ServerPackSettings(mine);
later.Load();
Check.False(later.MigrateOnce("migratedFromOld", migrate), "never again (the marker was saved)");
Check.True(later.GetBool("moved", false), "later changes to the old home don't come over");
Check.Eq(runs, 1, "ran once");
File.WriteAllText(mine, "{ not json");
var broken = new ServerPackSettings(mine);
broken.Load();
Check.True(broken.LastError.Length > 0 && broken.GetBool("moved", true), "a broken file reads as defaults");
}
finally { try { Directory.Delete(dir, true); } catch { } }
}
private static void ProfileValues()
{
var v = new ServerProfileValues();
int r0 = v.Revision;
Check.True(v.Set("voidDotDurationScale", 1.35), "set");
Check.True(v.Revision > r0, "a change bumps the revision");
int r1 = v.Revision;
Check.True(v.Set("voidDotDurationScale", 1.35) && v.Revision == r1, "the same value is no change");
Check.False(v.Set("bad key", 1) || v.Set("", 1) || v.Set("x", double.NaN) || v.Set("y", double.PositiveInfinity), "bad keys and numbers");
ServerPackInfo info = new("conquest", "Conquest", new[] { "h" }, new[] { "Conquest" });
string json = ServerPackProfile.BuildJson(info, "RynthConquest", "0.2.0", true, "Conquest", v.Snapshot(out int rev));
Check.Eq(rev, v.Revision, "the snapshot's revision");
Check.Near(RynthCore.Plugin.Shared.ServerProfileView.Value(json, "voidDotDurationScale", 1), 1.35, 1e-12, "a reader gets the value");
Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value(json, "other", 7), 7.0, "a missing value falls back");
Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("", "voidDotDurationScale", 1), 1.0, "no profile falls back");
Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("{\"values\":{\"k\":\"2\"}}", "k", 1), 1.0, "text is not a number");
Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("{broken", "k", 3), 3.0, "broken JSON falls back");
using (JsonDocument doc = JsonDocument.Parse(ServerPackProfile.BuildJson(info, "RynthConquest", "0.2.0", true, "Conquest")))
Check.Eq(doc.RootElement.GetProperty("values").EnumerateObject().Count(), 0, "no values: an empty object");
Check.True(v.Remove("voidDotDurationScale") && !v.Remove("voidDotDurationScale"), "remove");
v.Set("a", 1);
int r2 = v.Revision;
v.Clear();
Check.True(v.Revision > r2 && v.Snapshot(out _).Length == 0, "clear (logout)");
}
private static void ReplyWindow()
{
var req = new ServerChatRequest();
Check.False(req.Awaiting(0), "nothing asked");
req.Sent(1000);
Check.True(req.Awaiting(1000 + ServerChatRequest.WindowMs - 1), "inside the window");
Check.False(req.Awaiting(1000 + ServerChatRequest.WindowMs), "the window closes");
req.Sent(1000);
req.Extend(5500);
Check.True(req.Awaiting(7000), "a reply line stretches it");
req.Clear();
Check.False(req.Awaiting(1001), "cleared");
}
}

View file

@ -19,6 +19,36 @@ internal static class ServerProjectsTests
r.Add("server projects: ids, plugin names and hosts are unique", Unique);
r.Add("server projects: no server's host is claimed by another server's list", NoHostOverlap);
r.Add("server projects: each new server plugin has ServerData.cs and imports the shared props", Layout);
r.Add("server projects: RynthOracle and RynthInventory send no server's own commands (they live in its plugin)", SharedPluginsServerFree);
}
/// <summary>
/// Since 2026-10-20 a server's own features live in its server plugin (RynthConquest, RynthAelrynth):
/// the shared plugins' sources hold none of those servers' commands or chat markers, and use the
/// server tags only to pick a quest pack (data, RynthOracle's ServerIdentity.cs).
/// </summary>
private static void SharedPluginsServerFree()
{
string[] commands = { "\"/bank", "\"/b\"", "\"/augs", "\"/enl augs", "\"/bonus", "\"/fship list", "\"/top", "\"/trial", "\"/mule-data", "\"~ael1" };
foreach (string plugin in new[] { "RynthCore.Plugin.RynthOracle", "RynthCore.Plugin.RynthInventory" })
{
string dir = Path.Combine(PluginsDir(), plugin);
var files = Directory.GetFiles(dir, "*.cs", SearchOption.AllDirectories)
.Where(f => !f.Contains(Path.DirectorySeparatorChar + "obj" + Path.DirectorySeparatorChar)
&& !f.Contains(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar))
.ToList();
Check.True(files.Count > 10, plugin + ": its sources were found (" + files.Count + ")");
foreach (string file in files)
{
string text = File.ReadAllText(file);
string name = plugin + "/" + Path.GetRelativePath(dir, file);
foreach (string c in commands)
Check.False(text.Contains(c, StringComparison.Ordinal), $"{name} sends no server command {c.TrimStart('"')}");
if (!file.EndsWith("ServerIdentity.cs", StringComparison.Ordinal))
Check.False(text.Contains("ServerTags.Conquest", StringComparison.Ordinal) || text.Contains("ServerTags.Aelrynth", StringComparison.Ordinal),
$"{name} has no Conquest or Aelrynth feature");
}
}
}
private sealed record Project(string Dir, string PluginName, string Id, string Name, string[] Hosts, string[] Worlds, bool Shared);

View file

@ -0,0 +1,229 @@
using System.Collections.Generic;
using RynthCore.Plugin.RynthAelrynth;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiTests.Harness;
namespace RynthServerPack.Tests;
// The Aelrynth account vault: /mule-data answers, one "~ael1" line a page (Aeshnidae.Mule MuleData.cs).
// Moved with the feed from RynthInventory.Tests on 2026-10-20: RynthAelrynth reads the vault now and
// hands it to RynthInventory through the storage feed (Plugins/Shared/StorageFeed.cs).
internal static class VaultTests
{
public static void Register(Runner r)
{
r.Add("vault: pages are asked one after the other and filed as one record", Pages);
r.Add("vault: other plugins' lines and players' imitations are left alone", Imitations);
r.Add("vault: a server without the command is asked once", Unsupported);
r.Add("vault: loading, changed and silent vaults are never filed half or empty", Retries);
r.Add("vault: RynthAelrynth asks after login, every ten minutes and on /rserver vault", Schedule);
r.Add("vault: the record reaches RynthInventory's format intact (plain ASCII)", HandOff);
}
private const string A = "{\"o\":2147483649,\"w\":100,\"n\":\"Acid Assagai\",\"i\":100667000,\"u\":100667001,\"v\":100667002,\"s\":3,\"m\":100,\"y\":1,\"e\":1}";
private const string B = "{\"o\":2147483650,\"w\":101,\"n\":\"Pyreal\",\"i\":100667003,\"y\":8192}";
private static string VaultPage(int page, int pages, int count, string items, bool ready = true, string why = "") =>
ready
? "~ael1 {\"t\":\"mule\",\"ready\":true,\"page\":" + page + ",\"pages\":" + pages + ",\"count\":" + count + ",\"max\":1000,\"items\":[" + items + "]}"
: "~ael1 {\"t\":\"mule\",\"ready\":false,\"why\":\"" + why + "\"}";
private static (VaultFeed Feed, List<string> Sent) NewVault()
{
var sent = new List<string>();
return (new VaultFeed(t => { sent.Add(t); return true; }), sent);
}
private static void Pages()
{
(VaultFeed v, List<string> sent) = NewVault();
Check.True(v.Ask(1000), "ask starts");
Check.Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "page 1 asked first");
Check.True(v.ShouldEat(VaultPage(1, 2, 2, A)), "page 1 is eaten");
v.Tick(1100, "Tom");
Check.Eq(sent.Count == 2 ? sent[1] : "?", "/mule-data 2", "page 2 asked when page 1 came");
Check.Null(v.Record, "nothing filed before the last page");
Check.True(v.ShouldEat(VaultPage(2, 2, 2, B)), "page 2 is eaten");
v.Tick(1200, "Tom");
StorageFeedRecord? r = v.Record;
Check.True(r != null && v.TakeChanged() && !v.TakeChanged(), "filed once");
Check.Eq(r?.Items.Count ?? -1, 2, "both pages' items");
Check.Eq(r?.Id ?? 0, VaultFeed.VaultId("tom"), "id follows the account, case-blind");
Check.True(StorageFeed.IsStandInId(r?.Id ?? 0), "id is a stand-in, far from real objects");
Check.Eq(r?.Label ?? "", "Account vault", "label");
Check.Eq(r?.Name ?? "", "Aelrynth vault", "name");
StorageFeedItem a = r!.Items[0];
Check.Eq(a.Name, "Acid Assagai", "name"); Check.Eq(a.Icon, 100667000u, "icon"); Check.Eq(a.Underlay, 100667001u, "underlay");
Check.Eq(a.Overlay, 100667002u, "overlay"); Check.Eq(a.Stack, 3, "stack"); Check.Eq(a.MaxStack, 100, "max stack");
Check.Eq(a.ItemType, 1u, "item type");
Check.Eq(r.Items[1].Stack, 1, "no stack field is a stack of 1");
Check.Eq(v.Status, VaultFeed.State.Idle, "idle again");
Check.Eq(VaultFeed.VaultId("Tom"), 0xFF000000u | (FnvOf("tom") & 0x00FFFFFFu), "the id RynthInventory used before the move (no second vault)");
}
private static uint FnvOf(string s)
{
uint h = 2166136261u;
foreach (char c in s) { h ^= c; h *= 16777619u; }
return h;
}
private static void Imitations()
{
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
Check.False(v.ShouldEat("~ael1 {\"t\":\"inspect\",\"ok\":true}"), "the Companion's line stays visible");
Check.False(v.ShouldEat("Welcome to Aelrynth"), "ordinary chat stays visible");
Check.False(v.ShouldEat(null), "null is fine");
}
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
Check.False(v.ShouldEat("Bob says, \"" + VaultPage(1, 1, 1, A) + "\"", 2), "spoken data line is not ours");
Check.False(v.ShouldEat("Bob " + VaultPage(1, 1, 1, A), 12), "an emoted data line is not ours");
Check.False(v.ShouldEat("Bob " + VaultPage(1, 1, 1, A)), "a data line not at the start is not ours, type unknown");
Check.False(v.ShouldEat(VaultPage(1, 1, 1, A), 3), "a data line in a tell is not ours");
Check.False(v.ShouldEat("Bob tells you, \"Unknown command: mule-data\"", 3), "a told unknown-command line is not ours");
Check.False(v.ShouldEat("Unknown command: mule-data", 2), "unknown-command in speech is not ours");
Check.False(v.ShouldEat("Unknown command: mule-data-ish"), "another command's refusal is not ours");
Check.True(v.ShouldEat("Unknown command: mule-data", 15), "ACE's real reply (Help) is ours");
}
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
Check.True(v.ShouldEat(" " + VaultPage(1, 1, 1, A), 0), "the server's line (Broadcast), leading space allowed");
}
{
(VaultFeed v, _) = NewVault();
Check.True(v.ShouldEat(VaultPage(1, 1, 1, A)), "a line typed by hand while we are not asking is eaten");
v.Tick(0, "tom");
Check.Null(v.Record, "but ignored when we did not ask");
}
}
private static void Unsupported()
{
{
(VaultFeed v, List<string> sent) = NewVault();
v.Ask(0);
Check.True(v.ShouldEat("Unknown command: /mule-data"), "the unknown-command reply is eaten while we wait");
v.Tick(100, "tom");
Check.Eq(v.Status, VaultFeed.State.Unsupported, "unsupported");
Check.False(v.Ask(200), "not asked again");
Check.Eq(sent.Count, 1, "one probe, no more");
Check.True(v.Ask(300, force: true), "/rserver vault asks anyway");
}
{
(VaultFeed v, _) = NewVault();
Check.False(v.ShouldEat("Unknown command: /mule-data"), "an unknown-command line we did not provoke is left alone");
}
}
private static void Retries()
{
// A vault the server is still loading is asked again, and never recorded as empty.
{
(VaultFeed v, List<string> sent) = NewVault();
v.Ask(0);
v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading"));
v.Tick(10, "tom");
Check.Eq(v.Status, VaultFeed.State.Waiting, "waiting");
v.Tick(2000, "tom");
Check.Eq(sent.Count, 1, "not before the retry delay");
v.Tick(3500, "tom");
Check.Eq(sent.Count, 2, "asked again after it");
Check.Null(v.Record, "never recorded");
for (int i = 0; i < 10; i++)
{
v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading"));
v.Tick(4000 + i * 4000, "tom");
}
Check.True(v.Status != VaultFeed.State.Asking || sent.Count < 12, "it gives up after a few tries");
Check.Null(v.Record, "still never recorded");
}
// A vault that changed between pages is read again, not filed half and half.
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
v.ShouldEat(VaultPage(1, 2, 3, A));
v.Tick(10, "tom");
v.ShouldEat(VaultPage(2, 2, 3, B)); // 2 read, the server says 3
v.Tick(20, "tom");
Check.Null(v.Record, "a mismatched read is not filed");
Check.Eq(v.Status, VaultFeed.State.Waiting, "and is retried");
}
// Silence is an idle feed, not a stuck one.
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
v.Tick(20_000, "tom");
Check.Eq(v.Status, VaultFeed.State.Idle, "no answer in time");
Check.True(v.Ask(21_000), "can ask again");
}
// Garbage inside a mule line does not throw.
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
v.ShouldEat("~ael1 {\"t\":\"mule\",\"ready\":tru");
v.Tick(5, "tom");
Check.True(v.Record == null && v.Status == VaultFeed.State.Idle, "bad JSON drops the read");
}
}
private static void Schedule()
{
var sent = new List<string>();
var f = new AelrynthFeature { SendCommand = t => { sent.Add(t); return true; } };
f.Reset();
long login = 50_000;
Check.Null(f.VaultTick(login, "tom"), "nothing at login");
Check.Eq(sent.Count, 0, "not asked at once");
f.VaultTick(login + VaultFeed.FirstAskMs - 1, "tom");
Check.Eq(sent.Count, 0, "not before the first delay");
f.VaultTick(login + VaultFeed.FirstAskMs, "tom");
Check.Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "asked after the first delay");
Check.True(f.OnChatLine(VaultPage(1, 1, 1, A), 0, login + VaultFeed.FirstAskMs + 10), "its reply is always hidden");
StorageFeedRecord? read = f.VaultTick(login + VaultFeed.FirstAskMs + 20, "tom");
Check.True(read != null && read.Items.Count == 1, "the finished read is handed back once");
Check.Null(f.VaultTick(login + VaultFeed.FirstAskMs + 30, "tom"), "and only once");
f.VaultTick(login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs, "tom");
Check.Eq(sent.Count, 2, "read again ten minutes later");
f.OnChatLine(VaultPage(1, 1, 1, A), 0, login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs + 1);
f.VaultTick(login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs + 2, "tom");
Check.True(f.VaultAskNow(login + 700_000) && sent.Count == 3, "/rserver vault reads it now");
// A server without the command: one probe per login, then quiet.
var g = new AelrynthFeature { SendCommand = t => { sent.Add(t); return true; } };
g.Reset();
int before = sent.Count;
g.VaultTick(0, "tom");
g.VaultTick(VaultFeed.FirstAskMs, "tom");
g.OnChatLine("Unknown command: mule-data", 0, VaultFeed.FirstAskMs + 1);
g.VaultTick(VaultFeed.FirstAskMs + 2, "tom");
g.VaultTick(VaultFeed.FirstAskMs + 3 * VaultFeed.RefreshMs, "tom");
Check.Eq(sent.Count - before, 1, "no vault on the server: asked once, then never on a timer");
g.Reset();
Check.Eq(g.Vault.Status, VaultFeed.State.Idle, "the next login asks again");
}
private static void HandOff()
{
var items = new List<StorageFeedItem>
{
new(2147483649u, 100, "Acid \"Assagai\" \\ é", 100667000, 100667001, 100667002, 3, 100, 1),
new(2147483650u, 101, "Pyreal", 100667003, 0, 0, 1, 0, 8192),
};
var rec = new StorageFeedRecord(VaultFeed.VaultId("tom"), VaultFeed.VaultName, VaultFeed.Label, items);
string json = StorageFeed.ToJson(rec);
bool ascii = true;
foreach (char c in json) if (c > 0x7e || c < 0x20) ascii = false;
Check.True(ascii, "plain ASCII (the broker carries ANSI)");
StorageFeedRecord? back = StorageFeed.Parse(json, out string error);
Check.Eq(error, "", "parsed");
Check.True(back != null && back.Id == rec.Id && back.Name == rec.Name && back.Label == rec.Label && back.Items.Count == 2, "the record");
Check.Eq(back!.Items[0], items[0], "an item, name escapes included");
Check.Eq(back.Items[1], items[1], "another");
Check.Eq(StorageFeed.TargetPlugin + "/" + StorageFeed.Action, "RynthInventory/storage", "sent to RynthInventory's \"storage\" command");
}
}