diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 66272b3..22300af 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -3755,6 +3755,11 @@ public class BuffManager : IDisposable name.Contains("Bane")) return AcSkillType.ItemEnchantment; + // Tinkering skill buffs (Armor Tinkering Expertise, Prodigal Armor Expertise) are Creature + // Enchantment; checked before the Life Magic "Armor" match below. + if (name.Contains("Tinkering") || name.Contains("Armor Expertise")) + return AcSkillType.CreatureEnchantment; + if (name.Contains("Protection") || name.Contains("Armor") || name.Contains("Regeneration") || name.Contains("Rejuvenation") || name.Contains("Renewal") || name == "Harlune's Blessing" || diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index ba75bd4..3d9bd5d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -567,8 +567,11 @@ public sealed partial class RynthAiPlugin return; // Keep our target, just wait — don't ResetCorpseTarget } - // Loot work is actually running this tick — the timeout clock counts again. - _corpseHoldFrozenAge = -1; + // The timeout clock counts again only where loot work really runs: an open container + // below, or an open the arbiter lets out (the Looting check further down). Resetting it + // here, before that check, let every tick Combat owned age the claim (2026-10-09: + // with Boost Loot Priority on, Drakkon dropped 20 corpses in an Olthoi spawn, each + // claimed between kills and abandoned 12 s later, never opened). // ── Active corpse work — pause navigation ──────────────────────── if (_openedContainerId != 0 || _targetCorpseId != 0) @@ -576,6 +579,7 @@ public sealed partial class RynthAiPlugin if (_openedContainerId != 0) { + _corpseHoldFrozenAge = -1; StopCorpseMovement(); TickOpenCorpseLooting(settings); return; @@ -686,7 +690,12 @@ public sealed partial class RynthAiPlugin // 06:18:44, the first failed open of the day's stall). One tick later the stop goes // out first (PauseNavigationForCorpse) and the open after it. if (_activity != BotActivity.Looting) + { + // Combat (or anything else) owns the tick: the claim waits, its clock stopped. + FreezeCorpseTimeout(now); return; + } + _corpseHoldFrozenAge = -1; // One server action at a time (2026-10-06, ActionPacer): no open while the server is still // answering another action - a kit, a cast, a stance change, or the last open itself (a @@ -701,6 +710,13 @@ public sealed partial class RynthAiPlugin && Host.HasGetGroundContainerId && unchecked((int)Host.GetGroundContainerId()) == _closeSentFor) return; + // Peace Mode When Idle: into peace before the open, not during it. Combat holds its own + // idle swap while looting has work (LootHoldsIdlePeace: a mode change cancels the + // server's walk/turn to a corpse being opened), so the character looted in combat + // stance (2026-10-09). Here no open is out yet, so the swap can't cancel anything. + if (WantsPeaceBeforeOpen(settings, now)) + return; + // Farther than reach: just use the corpse. The server walks the character to it and turns // it (as a player's double-click does); steering there ourselves looked awkward and // turned slowly (owner, 2026-10-04). Our own movement stays off so it can't cancel that @@ -745,6 +761,32 @@ public sealed partial class RynthAiPlugin } private long _corpseOpenBusyWaitSince; + + // Peace before the open: one request per claimed corpse, only with no monster within + // LootStarveCloseYards (the same test that gives looting its turn while combat still has a + // target), and the open goes out anyway after PeaceBeforeOpenMaxMs. + private const long PeaceBeforeOpenMaxMs = 2500; + private int _peaceBeforeOpenFor; + private long _peaceBeforeOpenSince; + + /// True while the open should wait for the peace-mode swap it just asked for. + private bool WantsPeaceBeforeOpen(LegacyUiSettings settings, long now) + { + // Not HasTargets: a target combat locked but can't reach kept it on (2026-10-09, Drakkon looted + // in Magic mode with a target unattacked for 82 s and nothing within 5 yd). + if (!settings.PeaceModeWhenIdle || _combatManager == null || _combatManager.HasCloseThreat(LootStarveCloseYards) + || _combatManager.CurrentCombatMode == CombatMode.NonCombat + || _lastCorpseOpenAttemptAt != 0) // an open is already out: no mode change now + return false; + if (_peaceBeforeOpenFor != _targetCorpseId) + { + _peaceBeforeOpenFor = _targetCorpseId; + _peaceBeforeOpenSince = now; + Host.ChangeCombatModeFor(CombatMode.NonCombat, "Loot", "peace before opening the corpse (Peace Mode When Idle)"); + return true; + } + return now - _peaceBeforeOpenSince < PeaceBeforeOpenMaxMs; + } // Wait for busy to genuinely clear before opening the next corpse. The backstop // only exists so a leaked/desynced count can't freeze looting — CheckBusyTimeout // now force-clears a leak in 2s during the corpse approach/open phase (lootOpenUrgent), @@ -2598,6 +2640,15 @@ public sealed partial class RynthAiPlugin { if (!Host.HasTapJump) return false; + // Not with monsters about (2026-10-09): mid-fight, an open is answered without opening + // because a swing, a hit or a stance change cancels the server's walk/turn to the + // corpse - not the stuck queue the jump clears - and the jump looked like the nav's + // stuck fix firing while the character was busy. The retry still goes out, unjumped. + if (_combatManager?.HasNearbyMonsters == true) + { + Log($"[RynthAi] Use check: no jump {why} - monsters nearby (a fight cancels opens; it isn't the stuck queue)."); + return false; + } if (ActionPacer.Outstanding(Host, out var pending) && pending != null) { Log($"[RynthAi] Use check: no jump {why} - the server still owes an answer to {ActionPacer.Describe(pending.Kind, pending.Label)}."); diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs index ae8c4f5..6b4d217 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs @@ -38,7 +38,8 @@ internal static class ItemInfoText // STypeFloat (ACE PropertyFloat numbering). internal const uint FloatDamageVariance = 22, FloatMeleeDefense = 29, FloatWeaponOffense = 62, FloatDamageMod = 63, - FloatManaConversion = 144, FloatMissileDefense = 149, FloatMagicDefense = 150, FloatElementalDamage = 152; + FloatManaConversion = 144, FloatMissileDefense = 149, FloatMagicDefense = 150, FloatElementalDamage = 152, + FloatCriticalMultiplier = 136, FloatCriticalFrequency = 147; /// Gear ratings (STypeInt 370-389) and their short tags, in print order. internal static readonly (uint Key, string Tag)[] Ratings = @@ -211,6 +212,15 @@ internal static class ItemInfoText if (Int(item, IntElementalBonus) is int elemBonus and > 0) parts.Add("+" + elemBonus.ToString(Inv) + " elemental dmg"); if (weapon && item.TryInt(IntWeaponTime, out int speed) && speed > 0) parts.Add("Speed " + speed.ToString(Inv)); + // Crushing Blow and Biting Strike, the way the client's appraisal names them (shown as + // SilentKelpie's fork shows them, rynth/RynthSuite PR #3). ACE deals a crit as damage x + // (1 + CriticalMultiplier) (DamageEvent), so 2.66 reads "Crushing Blow 3.66x"; 1.0 is an + // ordinary crit. CriticalFrequency is the weapon's own crit chance (default 10%, 5% casters). + if (weapon && item.TryFloat(FloatCriticalMultiplier, out double critMult) && critMult > 1.0) + parts.Add("Crushing Blow " + (1.0 + critMult).ToString("0.##", Inv) + "x"); + if (weapon && item.TryFloat(FloatCriticalFrequency, out double critFreq) && critFreq > 0 && critFreq < 1) + parts.Add("Biting Strike " + (critFreq * 100.0).ToString("0.#", Inv) + "%"); + // Modifiers: 1.18 = +18%. Missile launchers' damage mod and casters' elemental mod too. var mods = new List(6); AddPercent(item, FloatWeaponOffense, "atk", mods, weapon); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index f56e36b..9709190 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -1561,7 +1561,9 @@ internal sealed class LegacyDashboardRenderer var tmp = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings); if (tmp == null) return; - // Copy all serialized fields manually (the source generator guarantees coverage) + // Every serialized field must be listed here, or loading a profile silently drops it and + // the next autosave writes the default back. "profile: every saved setting survives + // loading" (RynthAiHostTests, ProfileLoadTests) fails for any field that is missing. dst.EnableBuffing = tmp.EnableBuffing; dst.EnableCombat = tmp.EnableCombat; dst.EnableNavigation = tmp.EnableNavigation; @@ -1666,6 +1668,7 @@ internal sealed class LegacyDashboardRenderer dst.SummonPets = tmp.SummonPets; dst.CustomPetRange = tmp.CustomPetRange; dst.PetMinMonsters = tmp.PetMinMonsters; + dst.PetAutoRefill = tmp.PetAutoRefill; dst.AdvancedOptions = tmp.AdvancedOptions; dst.MineOnly = tmp.MineOnly; dst.ShowEditor = tmp.ShowEditor; @@ -1715,6 +1718,7 @@ internal sealed class LegacyDashboardRenderer dst.TargetFPSBackground = tmp.TargetFPSBackground; // MonsterRule deep-copy preserves Category + MatchExpression via JSON round-trip dst.MonsterRules = tmp.MonsterRules; + dst.MonsterNameBlacklist = tmp.MonsterNameBlacklist ?? new(); dst.ItemRules = tmp.ItemRules; dst.ConsumableRules = tmp.ConsumableRules; dst.BuffRules = tmp.BuffRules; @@ -1803,6 +1807,10 @@ internal sealed class LegacyDashboardRenderer dst.RadarWallPaintRadius = tmp.RadarWallPaintRadius; dst.RadarCircular = tmp.RadarCircular; dst.RadarClickThrough = tmp.RadarClickThrough; + dst.RadarPosX = tmp.RadarPosX; + dst.RadarPosY = tmp.RadarPosY; + dst.RadarSizeX = tmp.RadarSizeX; + dst.RadarSizeY = tmp.RadarSizeY; dst.SuppressRetailPowerbar = tmp.SuppressRetailPowerbar; dst.ShowRynthChat = tmp.ShowRynthChat; dst.ChatOpacity = tmp.ChatOpacity; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index a3421c9..1621319 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -1074,15 +1074,78 @@ internal sealed class ExpressionEngine return NewList(items); } + // List text: "[item,item,...]". An item that is itself a whole list is written as is, so + // lists nest ("[a,[b,c]]"); any other item has '\', ',', '[' and ']' escaped with '\'. + // Items without those characters are written exactly as before ("[a,b]"). private static string NewList(IEnumerable? items = null) - => items != null ? "[" + string.Join(",", items) + "]" : "[]"; + { + if (items == null) return "[]"; + var sb = new System.Text.StringBuilder("["); + bool first = true; + foreach (string? item in items) + { + if (!first) sb.Append(','); + first = false; + AppendListItem(sb, item ?? ""); + } + return sb.Append(']').ToString(); + } + + private static void AppendListItem(System.Text.StringBuilder sb, string item) + { + if (IsWholeList(item)) { sb.Append(item); return; } + foreach (char c in item) + { + if (c is '\\' or ',' or '[' or ']') sb.Append('\\'); + sb.Append(c); + } + } + + /// True when is one list: its first '[' closes on the last character (escapes skipped). + private static bool IsWholeList(string s) + { + if (s.Length < 2 || s[0] != '[' || s[s.Length - 1] != ']') return false; + int depth = 0; + for (int i = 0; i < s.Length; i++) + { + char c = s[i]; + if (c == '\\') { i++; continue; } + if (c == '[') depth++; + else if (c == ']' && --depth == 0) return i == s.Length - 1; + } + return false; + } private static List? GetList(string handle) { handle = handle.Trim(); if (handle.Length < 2 || handle[0] != '[' || handle[handle.Length - 1] != ']') return null; string inner = handle.Substring(1, handle.Length - 2); - return inner.Length == 0 ? new List() : new List(inner.Split(',')); + var items = new List(); + if (inner.Length == 0) return items; + + // Split on commas outside nested lists. Escapes are undone for this list's own items; + // a nested list keeps them for when it is read as a list itself. Only "\\", "\,", "\[" + // and "\]" are escapes (all NewList writes); any other backslash is plain text, so a + // list saved before escaping existed ("[c:\d]") reads back unchanged. + var cur = new System.Text.StringBuilder(); + int depth = 0; + for (int i = 0; i < inner.Length; i++) + { + char c = inner[i]; + if (c == '\\' && i + 1 < inner.Length && inner[i + 1] is '\\' or ',' or '[' or ']') + { + if (depth > 0) cur.Append(c); + cur.Append(inner[++i]); + continue; + } + if (c == '[') depth++; + else if (c == ']' && depth > 0) depth--; + else if (c == ',' && depth == 0) { items.Add(cur.ToString()); cur.Clear(); continue; } + cur.Append(c); + } + items.Add(cur.ToString()); + return items; } private static string StripBackticks(string s) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs index 9f247de..f001174 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs @@ -36,8 +36,15 @@ internal sealed class MetaManager /// for a fake clock; the plugin never changes it. internal Func Clock { get; set; } = static () => DateTime.Now; private bool _lastMacroRunning; - // PSecsInStateGE's clock: restarts on a real state entry, not on macro stop/start. + // PSecsInStateGE's clock: seconds spent in the current state. Restarts when the meta moves to + // a different state or a meta is loaded; keeps running over a macro stop/start and a SetState + // to the same state; pauses while the state has Called another and resumes on the Return. private DateTime _statePStartTime = DateTime.Now; + // Seconds the calling state had on its P clock, one entry per _stateStack entry (null when the + // Return goes to a different state than the one that called). + private readonly Stack _statePPaused = new(); + // Set by ReturnFromCall; applied when the tick sees the state change. + private double? _statePResume; // Observability (GetStateSnapshot / §3.4). Written on the plugin-tick thread // inside the locked rule-eval pass; read by the bridge under the same lock. @@ -71,6 +78,17 @@ internal sealed class MetaManager // ── Call stack (CallMetaState / ReturnFromCall) ────────────────────────── private readonly Stack _stateStack = new(); + /// + /// Pushes the state a Return goes back to, with the calling state's P seconds when the Return + /// goes back to that same state (so PSecsInStateGE resumes there instead of restarting). + /// + private void PushCall(string returnState) + { + _stateStack.Push(returnState); + bool backHere = string.Equals(returnState, _settings.CurrentState, StringComparison.OrdinalIgnoreCase); + _statePPaused.Push(backHere ? (Clock() - _statePStartTime).TotalSeconds : null); + } + // ── Watchdog ───────────────────────────────────────────────────────────── private bool _watchdogActive; private string _watchdogState = ""; @@ -260,10 +278,11 @@ internal sealed class MetaManager return; } - // A real state entry (anything but a bare macro stop/start) restarts the - // persistent seconds-in-state clock too. - bool realStateEntry = _settings.ForceStateReset - || !string.Equals(_settings.CurrentState, _lastState, StringComparison.OrdinalIgnoreCase); + // A real state entry (anything but a bare macro stop/start) is logged. The persistent + // seconds-in-state clock only restarts on a move to another state or a meta load. + bool stateChanged = !string.Equals(_settings.CurrentState, _lastState, StringComparison.OrdinalIgnoreCase); + bool realStateEntry = _settings.ForceStateReset || stateChanged; + bool metaReloaded = _settings.MetaCallStackReset; // Macro just started — force reset so rules re-evaluate even if state // name matches where we stopped. Otherwise HasFired stays latched across @@ -278,6 +297,7 @@ internal sealed class MetaManager { _settings.MetaCallStackReset = false; _stateStack.Clear(); + _statePPaused.Clear(); } // ── State change / forced reset ────────────────────────────────────── @@ -292,7 +312,11 @@ internal sealed class MetaManager _host.Log($"[Meta] state '{_lastState}' -> '{_settings.CurrentState}' after {(Clock() - _stateStartTime).TotalSeconds:0}s"); _stateStartTime = Clock(); _watchdogActive = false; - if (realStateEntry) _statePStartTime = Clock(); + if (metaReloaded) + _statePStartTime = Clock(); + else if (stateChanged) + _statePStartTime = _statePResume is double resumed ? Clock().AddSeconds(-resumed) : Clock(); + _statePResume = null; _settings.ForceStateReset = false; lock (_settings.MetaRulesLock) foreach (var r in _settings.MetaRules) r.HasFired = false; @@ -330,7 +354,7 @@ internal sealed class MetaManager { _watchdogActive = false; // VTank calls the watchdog state: a Return in it re-enters this one. - _stateStack.Push(_settings.CurrentState); + PushCall(_settings.CurrentState); _settings.CurrentState = _watchdogState; _settings.ForceStateReset = true; _host.WriteToChat($"[RynthAi] WATCHDOG TRIGGERED \u2192 {_watchdogState}", 1); @@ -482,8 +506,9 @@ internal sealed class MetaManager case MetaConditionType.SecondsInState_GE: return double.TryParse(rule.ConditionData, out double reqSecs) && secondsInState >= reqSecs; - // VTank: "Persistent timer; does not reset if meta is stopped/started." - // It still restarts when the state is entered again (SetState, Call, Return). + // VTank: "Persistent timer; does not reset if meta is stopped/started." As RynthScript + // documents it, it also survives re-entry: a SetState to the same state, and a Call + // and Return (paused while away). See _statePStartTime. case MetaConditionType.SecondsInStateP_GE: return double.TryParse(rule.ConditionData, out double reqPSecs) && (Clock() - _statePStartTime).TotalSeconds >= reqPSecs; @@ -850,7 +875,7 @@ internal sealed class MetaManager { // VTank pushes the rule's ReturnState; empty (older RynthAi rules) = this state. string ret = ProcessData(rule.CallReturnState); - _stateStack.Push(string.IsNullOrEmpty(ret) ? _settings.CurrentState : ret); + PushCall(string.IsNullOrEmpty(ret) ? _settings.CurrentState : ret); _settings.CurrentState = callState; _settings.ForceStateReset = true; } @@ -860,6 +885,7 @@ internal sealed class MetaManager if (_stateStack.Count > 0) { _settings.CurrentState = _stateStack.Pop(); + _statePResume = _statePPaused.Count > 0 ? _statePPaused.Pop() : null; _settings.ForceStateReset = true; } break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs index 9b6c5ef..73a462c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs @@ -98,11 +98,11 @@ public sealed partial class RynthAiPlugin } if (!quiet && _itemInfoPendingId != 0 && _itemInfoPendingId != id) - ChatLine($"[RynthAi] Item info: stopped waiting for {ObjectNameOr(_itemInfoPendingId)}."); + ChatLine($"{ItemPrefix}Item info: stopped waiting for {ObjectNameOr(_itemInfoPendingId)}."); if (Host.HasRequestId) Host.RequestId(id); _itemInfoPendingId = id; _itemInfoDeadline = ItemInfoClock() + ItemInfoTimeoutMs; - if (!quiet) ChatLine($"[RynthAi] Item info: identifying {ObjectNameOr(id)}..."); + if (!quiet) ChatLine($"{ItemPrefix}Item info: identifying {ObjectNameOr(id)}..."); } // Item Info On Select: the item the player just selected, for the next tick (0 = none). @@ -112,12 +112,14 @@ public sealed partial class RynthAiPlugin /// Selection change (OnSelectedTargetChange): queues Item Info for an item the player /// selected. Skips non-items and RynthAi's own selections (the looter, metas). /// - private void QueueItemInfoOnSelect(uint id, WorldObject? obj) + /// Queues item info for the player's pick; true when it will print (Item Info On Select). + private bool QueueItemInfoOnSelect(uint id, WorldObject? obj) { - if (id == 0 || _dashboard?.Settings is not { ItemInfoOnSelect: true }) return; - if (obj == null || !IsLootableClass(obj.ObjectClass)) return; - if (SelfSelect.IsOurs(id)) return; + if (id == 0 || _dashboard?.Settings is not { ItemInfoOnSelect: true }) return false; + if (obj == null || !IsLootableClass(obj.ObjectClass)) return false; + if (SelfSelect.IsOurs(id)) return false; System.Threading.Interlocked.Exchange(ref _itemInfoSelectId, id); + return true; } /// @@ -140,10 +142,17 @@ public sealed partial class RynthAiPlugin private string ObjectNameOr(uint id) => Host.TryGetObjectName(id, out string n) && n.Length > 0 ? n : $"0x{id:X8}"; + /// + /// Item info lines carry their own prefix so RynthChat files them under its Items tab + /// (ChatClassifier.IsItemInfo, 2026-10-09); it still starts "[Rynth", so other chat + /// windows treat it as RynthAi output. + /// + internal const string ItemPrefix = "[RynthAi Item] "; + private void PrintItemInfo(uint id, bool identified) { var source = new HostItemInfoSource(Host, id); - ChatLine("[RynthAi] " + ItemInfoText.Describe(source, SpellDatabase.GetSpellName, identified)); + ChatLine(ItemPrefix + ItemInfoText.Describe(source, SpellDatabase.GetSpellName, identified)); } /// The live appraisal through the host (tick thread). diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index d4dedb8..35e55db 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -2018,10 +2018,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { int sid = unchecked((int)currentTargetId); WorldObject? obj = _objectCache?[sid]; + // Item info on select replaces the loot verdict line: one line per pick, not two + // (as SilentKelpie's fork does, rynth/RynthSuite PR #3). /ra lootcheck still prints it. + bool itemInfo = QueueItemInfoOnSelect(currentTargetId, obj); // Skip non-items (monsters, players, NPCs, doors, corpses, portals, etc.) - if (_lootInspectMode && obj != null && IsLootableClass(obj.ObjectClass)) + if (!itemInfo && _lootInspectMode && obj != null && IsLootableClass(obj.ObjectClass)) InspectLootRuleForItem(sid, quiet: true); - QueueItemInfoOnSelect(currentTargetId, obj); } } diff --git a/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs b/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs index 9b633b0..bf8dc30 100644 --- a/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs +++ b/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs @@ -27,8 +27,8 @@ internal sealed class ChatBuffer internal void Add(string? text, int chatType) { if (string.IsNullOrEmpty(text)) return; - string channel = ChatClassifier.IsRynthOutput(text) - ? ChatClassifier.Rynth + string channel = ChatClassifier.IsItemInfo(text) ? ChatClassifier.Items + : ChatClassifier.IsRynthOutput(text) ? ChatClassifier.Rynth : ChatClassifier.ChannelFor(chatType); string? sender = ChatClassifier.SenderFor(text, chatType); string ts = DateTime.Now.ToString("HH:mm:ss"); diff --git a/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs b/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs index 280bb54..02cc6a0 100644 --- a/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs +++ b/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs @@ -12,10 +12,11 @@ internal static class ChatClassifier internal const string System = "System"; internal const string Combat = "Combat"; internal const string Rynth = "Rynth"; // Any RynthCore/RynthAi/RynthChat plugin output ("[Rynth…]") + internal const string Items = "Items"; // RynthAi's item info ("[RynthAi Item] ", on select or /ra iteminfo) internal const string Other = "Other"; internal static readonly string[] AllChannels = - { Chat, Channels, System, Combat, Rynth, Other }; + { Chat, Channels, System, Combat, Rynth, Items, Other }; /// /// True for output emitted by the Rynth stack itself — every Rynth plugin tags @@ -27,6 +28,10 @@ internal static class ChatClassifier internal static bool IsRynthOutput(string text) => text.StartsWith("[Rynth", StringComparison.OrdinalIgnoreCase); + /// RynthAi's item info (RynthAiPlugin.ItemPrefix): its own Items tab (2026-10-09). + internal static bool IsItemInfo(string text) => + text.StartsWith("[RynthAi Item] ", StringComparison.Ordinal); + // ── Channel classification ───────────────────────────────────────────── internal static string ChannelFor(int chatType) => (uint)chatType switch diff --git a/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs index 5914e29..9171b56 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs @@ -47,6 +47,9 @@ public static unsafe class PluginExports [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); + // Inventory change triggers (the scan's poll catches the rest, e.g. moves from a corpse). [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })] public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId); diff --git a/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs b/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs index e9675e6..43c25f2 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs @@ -47,6 +47,11 @@ public sealed class RynthInventoryPlugin : RynthPluginBase private InventoryView? _view; private readonly ConcurrentQueue _commands = new(); + // The Aelrynth account vault (/mule-data), read a few seconds after login and every VaultRefreshMs. + private const long VaultFirstAskMs = 8_000, VaultRefreshMs = 10 * 60_000; + private VaultFeed? _vault; + private long _nextVaultAskMs; + private bool _identityKnown; private long _loginMs; private long _nextIdentityTryMs; @@ -82,6 +87,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase _c.RequestReload = () => { _reloadWanted = true; _files.Clear(); }; _c.Forget = ForgetCharacter; _ui.Log = msg => Host.Log(msg); + _vault = new VaultFeed(text => Host.InvokeChatParser(text)); _view = new InventoryView(_c); _window = _ui.Add(new UiWindow("RynthInventory/Main", "Global Inventory") @@ -106,6 +112,8 @@ public sealed class RynthInventoryPlugin : RynthPluginBase _c.LastSavedUtc = default; _c.LastSaveError = string.Empty; _scanner.Reset(); + _vault?.Reset(); + _nextVaultAskMs = 0; CloseStorage(); _lastViewed = 0; _lastWriteMs = 0; @@ -215,6 +223,11 @@ public sealed class RynthInventoryPlugin : RynthPluginBase case "keep": KeepOpenContainer(); break; + case "vault": + if (_vault == null || !Host.HasInvokeChatParser) { _c.Print("This engine can't send commands for the plugin, so the vault can't be read."); break; } + _nextVaultAskMs = Environment.TickCount64 + VaultRefreshMs; + _c.Print(_vault.Ask(Environment.TickCount64, force: true) ? "Reading the vault (/mule-data)..." : "The vault is already being read: " + _vault.Describe()); + break; case "reload": _reloadWanted = true; _files.Clear(); @@ -225,7 +238,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase break; case "help": case "?": - _c.Print("/ginv (window), /ginv (search), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv reload, /ginv status"); + _c.Print("/ginv (window), /ginv (search), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv vault (read the Aelrynth account vault now), /ginv reload, /ginv status"); break; default: _view?.SetSearch(arg); @@ -245,6 +258,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase int items = _c.Live?.Items.Count ?? 0, storage = _c.Live?.Storage.Count ?? 0; string saved = _c.LastSavedUtc == default ? "not saved yet" : "saved " + InventoryIndex.Age(_c.LastSavedUtc, DateTime.UtcNow); _c.Print($"{who}: {items} items carried, {storage} storage container(s), {saved}. {_c.Index?.Characters.Count ?? 0} characters in {_c.Store.Root}."); + if (_vault != null) _c.Print("Aelrynth vault: " + _vault.Describe() + "."); if (_c.LastSaveError.Length > 0) _c.Print("Last save failed: " + _c.LastSaveError); } @@ -327,6 +341,49 @@ public sealed class RynthInventoryPlugin : RynthPluginBase if (_openStorage != 0 && now >= _nextStorageScanMs) ScanStorage(now, final: false); + + TickVault(now); + } + + // ── The account vault ─────────────────────────────────────────────────── + + /// + /// Asks the server for the vault after login and now and then, and files what comes back with the + /// character's storage (one record, the same id on every character of the account). + /// + private void TickVault(long now) + { + VaultFeed? v = _vault; + if (v == null || _c.Live == null || !Host.HasInvokeChatParser) return; + + if (_nextVaultAskMs == 0) _nextVaultAskMs = now + VaultFirstAskMs; + else if (now >= _nextVaultAskMs && v.Status != VaultFeed.State.Unsupported) + { + _nextVaultAskMs = now + VaultRefreshMs; + v.Ask(now); + } + + v.Tick(now, _c.Account); + if (v.TakeChanged() && v.Record != null) FileVault(v.Record, now); + } + + private void FileVault(StorageRecord vault, long now) + { + if (_c.Live == null) return; + var storage = new List(_c.Live.Storage); + int i = storage.FindIndex(s => s.Id == vault.Id); + if (i >= 0) storage[i] = vault; else storage.Add(vault); + CharacterSnapshot snap = NewSnapshot(_c.Live.Items, storage); + snap.ScannedUtc = _c.Live.ScannedUtc; + _c.Live = snap; + _indexDirty = true; + _scheduler.ContentChanged(now, snap.ContentHash()); + } + + // May run on AC's thread: the feed only queues. + public override void OnChatWindowText(string? text, int chatType, ref int eat) + { + if (eat == 0 && _vault != null && _vault.ShouldEat(text)) eat = 1; } private void StartCharacter(long now, uint player, string server, string account, string character) diff --git a/Plugins/RynthCore.Plugin.RynthInventory/Scanning/VaultFeed.cs b/Plugins/RynthCore.Plugin.RynthInventory/Scanning/VaultFeed.cs new file mode 100644 index 0000000..bffee66 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthInventory/Scanning/VaultFeed.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Globalization; +using System.Text.Json; +using RynthCore.Plugin.RynthInventory.Data; + +namespace RynthCore.Plugin.RynthInventory.Scanning; + +/// +/// The Aelrynth account vault (the Aeshnidae.Mule mod): item storage the retail client is never +/// shown, so the only way to see inside is to ask. The plugin types /mule-data, exactly as a +/// player could, and the server answers one chat line a page: +/// +/// ~ael1 {"t":"mule","ready":true,"page":1,"pages":3,"count":57,"max":1000,"items":[{...}]} +/// +/// (the same "~ael1" lines the Aelrynth Companion reads; only lines whose "t" is "mule" are ours). +/// The pages are collected into one StorageRecord and kept with the character's storage, so the +/// vault is searched, shown with icons and merged across characters like any other storage; the +/// newest copy wins, and a vault belongs to the account, so every character sees the same one. +/// +/// A server without the command is asked once after login; its "Unknown command" reply is eaten +/// and the plugin stays quiet. A vault the server says is not ready yet is asked again a few +/// times, and is never recorded as empty. +/// +/// Threads: may run on AC's thread (it only queues); everything else runs +/// on the plugin tick. +/// +internal sealed class VaultFeed +{ + public const string Command = "/mule-data"; + public const string Prefix = "~ael1 "; + public const string Label = "Account vault"; + public const string VaultName = "Aelrynth vault"; + + public enum State { Idle, Asking, Unsupported, Waiting } + + private const long AnswerWindowMs = 15_000, RetryReadyMs = 3_000; + private const int MaxReadyRetries = 6, MaxPages = 80; + private const string UnknownMarker = "\u0001unknown"; + + private readonly Func _send; + private readonly ConcurrentQueue _lines = new(); + + private long _sentAtMs; + private volatile bool _expecting; + private int _readyTries; + private long _retryAtMs; + private readonly List _pages = new(); + private bool _changed; + + public VaultFeed(Func send) => _send = send; + + public State Status { get; private set; } = State.Idle; + /// The vault once a full read finished (null until then). + public StorageRecord? Record { get; private set; } + public int Max { get; private set; } + + /// For /ginv status. + public string Describe() => Status switch + { + State.Unsupported => "no vault on this server", + State.Asking => "reading the vault...", + State.Waiting => "the vault is still loading on the server", + _ => Record == null ? "vault not read yet" : $"vault: {Record.Items.Count} item(s)" + (Max > 0 ? $" of {Max}" : ""), + }; + + /// True once after was replaced. + public bool TakeChanged() { bool c = _changed; _changed = false; return c; } + + public void Reset() + { + Status = State.Idle; + _expecting = false; + _pages.Clear(); + _readyTries = 0; + while (_lines.TryDequeue(out _)) { } + } + + /// Starts a read from page 1, unless one is under way or the server has no vault ( asks anyway). + public bool Ask(long nowMs, bool force = false) + { + if (Status == State.Asking || Status == State.Waiting) return false; + if (Status == State.Unsupported && !force) return false; + _readyTries = 0; + _pages.Clear(); + return SendPage(nowMs, 1); + } + + private bool SendPage(long nowMs, int page) + { + _sentAtMs = nowMs; + Status = State.Asking; + _expecting = true; + if (_send(page <= 1 ? Command : Command + " " + page.ToString(CultureInfo.InvariantCulture))) return true; + _expecting = false; + Status = State.Idle; + return false; + } + + /// True for a line this feed answers, so the caller keeps it out of the chat window. Cheap; any thread. + public bool ShouldEat(string? text) + { + if (string.IsNullOrEmpty(text)) return false; + int at = text.IndexOf(Prefix, StringComparison.Ordinal); + if (at >= 0) + { + // Only our own kind: another plugin's ~ael1 line (the Companion's) stays visible to it. + if (text.IndexOf("\"t\":\"mule\"", at, StringComparison.Ordinal) < 0) return false; + _lines.Enqueue(text.Substring(at + Prefix.Length)); + return true; + } + // The reply of a server that has no such command: swallowed only while we wait for one. + if (_expecting && text.IndexOf("Unknown command", StringComparison.OrdinalIgnoreCase) >= 0 + && text.IndexOf("mule-data", StringComparison.OrdinalIgnoreCase) >= 0) + { + _lines.Enqueue(UnknownMarker); + return true; + } + return false; + } + + /// Applies what arrived and decides what to send next. Plugin tick. + public void Tick(long nowMs, string account) + { + while (_lines.TryDequeue(out string? line)) Apply(line, nowMs, account); + + if (Status == State.Waiting && nowMs >= _retryAtMs) SendPage(nowMs, 1); + else if (Status == State.Asking && nowMs - _sentAtMs > AnswerWindowMs) + { + // Nothing came back: a server without the mod, or a lost line. The next /ginv vault retries. + _expecting = false; + Status = State.Idle; + _pages.Clear(); + } + } + + private void Apply(string line, long nowMs, string account) + { + if (line == UnknownMarker) + { + if (Status == State.Asking) { _expecting = false; Status = State.Unsupported; _pages.Clear(); } + return; + } + if (Status != State.Asking) return; // a line we did not ask for (typed by hand, say) + _expecting = false; + + try + { + using JsonDocument doc = JsonDocument.Parse(line); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) { Status = State.Idle; return; } + + if (!(root.TryGetProperty("ready", out JsonElement ready) && ready.ValueKind == JsonValueKind.True)) + { + string why = Str(root, "why"); + if (why == "loading" && ++_readyTries <= MaxReadyRetries) { Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; } + else Status = State.Idle; // closed / fault / error: try again at the next refresh + _pages.Clear(); + return; + } + + int page = Int(root, "page", 1), pages = Math.Min(Math.Max(Int(root, "pages", 1), 1), MaxPages); + Max = Int(root, "max", Max); + int count = Int(root, "count", 0); + if (page == 1) _pages.Clear(); + if (root.TryGetProperty("items", out JsonElement items) && items.ValueKind == JsonValueKind.Array) + foreach (JsonElement e in items.EnumerateArray()) + if (e.ValueKind == JsonValueKind.Object) _pages.Add(Item(e)); + + if (page < pages) { SendPage(nowMs, page + 1); return; } + + // Last page. A total that disagrees with what was read means the vault changed under + // the read (a deposit between pages): keep the old copy and read again shortly. + if (count != _pages.Count && _readyTries++ < MaxReadyRetries) + { + Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; _pages.Clear(); return; + } + Record = new StorageRecord + { + Id = VaultId(account), + Name = VaultName, + Label = Label, + Cell = 0, + SeenUtc = DateTime.UtcNow, + Items = new List(_pages), + }; + _pages.Clear(); + _changed = true; + Status = State.Idle; + } + catch (JsonException) + { + Status = State.Idle; + _pages.Clear(); + } + } + + private static ItemRecord Item(JsonElement e) + { + var it = new ItemRecord + { + Id = UInt(e, "o"), + Wcid = UInt(e, "w"), + Name = Str(e, "n"), + Icon = UInt(e, "i"), + Underlay = UInt(e, "u"), + Overlay = UInt(e, "v"), + Stack = Math.Max(1, Int(e, "s", 1)), + MaxStack = Int(e, "m", 0), + ItemType = UInt(e, "y"), + Place = ItemPlace.Storage, + }; + it.Category = ItemCategory.FromItemType(it.ItemType); + return it; + } + + /// + /// A stand-in container id for the account's vault. Storage is merged by (server, id) with the + /// newest copy winning, so the same id on every character of the account shows ONE vault. It is + /// in the top of the id space, where no object the client has seen lives. + /// + public static uint VaultId(string account) + { + uint h = 2166136261u; + foreach (char c in (account ?? "").Trim().ToLowerInvariant()) { h ^= c; h *= 16777619u; } + return 0xFF000000u | (h & 0x00FFFFFFu); + } + + private static int Int(JsonElement e, string name, int fallback) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback; + + private static uint UInt(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetUInt32(out uint u) ? u : 0u; + + private static string Str(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; +} diff --git a/Shared/RynthCore.LootSdk/LootModel.cs b/Shared/RynthCore.LootSdk/LootModel.cs index 95311c8..c8a89ea 100644 --- a/Shared/RynthCore.LootSdk/LootModel.cs +++ b/Shared/RynthCore.LootSdk/LootModel.cs @@ -95,6 +95,8 @@ public sealed class LootRule : System.ComponentModel.INotifyPropertyChanged [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.Never)] public bool Enabled { get; set; } = true; public LootAction Action { get; set; } = LootAction.Keep; + // Always written: the context skips default values, and a skipped "Keep # 0" would load back as 1. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.Never)] public int KeepCount { get; set; } = 1; public List Conditions { get; set; } = new(); diff --git a/Shared/RynthCore.LootSdk/SalvageCombineSettings.cs b/Shared/RynthCore.LootSdk/SalvageCombineSettings.cs index d5e5ef6..5f7ec5b 100644 --- a/Shared/RynthCore.LootSdk/SalvageCombineSettings.cs +++ b/Shared/RynthCore.LootSdk/SalvageCombineSettings.cs @@ -12,6 +12,8 @@ namespace RynthCore.Loot; /// public sealed class SalvageCombineSettings { + // Always written: LootJsonContext skips default values, and a skipped false would load back as true. + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.Never)] public bool Enabled { get; set; } = true; /// Default bands applied to materials with no per-material override. diff --git a/Tools/RynthCore.LootSdkTests/LootAddItemTests.cs b/Tools/RynthCore.LootSdkTests/LootAddItemTests.cs index e0f9f70..3d863f8 100644 --- a/Tools/RynthCore.LootSdkTests/LootAddItemTests.cs +++ b/Tools/RynthCore.LootSdkTests/LootAddItemTests.cs @@ -411,7 +411,7 @@ internal static partial class Program Eq(back.Rules[0].Name, "Keep gems", $"{label}: rule 1 kept"); Check(!back.Rules[2].Enabled && back.Rules[2].Action == LootAction.Sell && back.Rules[2].Conditions[0].ToString() == orig.Rules[1].Conditions[0].ToString(), $"{label}: disabled rule kept as it was"); - Eq(back.Rules[3].KeepCount, 1, $"{label}: (KeepCount 0 reads back as 1 in the native loader, before and after alike)"); + Eq(back.Rules[3].KeepCount, 0, $"{label}: KeepCount 0 is written and reads back as 0, before and after alike"); Eq(LootProfile.Load(path + ".bak").Rules[2].KeepCount, back.Rules[3].KeepCount, $"{label}: same as the original reads"); Eq(string.Join(" ; ", back.Rules[3].Conditions), string.Join(" ; ", orig.Rules[2].Conditions), $"{label}: rule 3's conditions kept"); Eq(back.SalvageCombine?.DefaultBands, "1-6, 7-10", $"{label}: salvage combine kept"); diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index efff52e..3073038 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -86,6 +86,7 @@ internal static class Program HazardEscapeTests.Register(runner); ManaStoneChoiceTests.Register(runner); CustomDebuffTests.Register(runner); + ProfileLoadTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs index e996a29..1671d0f 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs @@ -62,9 +62,7 @@ internal static class BuffTests r.Add("buff choice: a mastery whose name has several spell ids", MultiIdMastery); // was a known failure; fixed by 0aedcee r.Add("buff timers: tier-8 weapon auras last 90 minutes", TierEightAuras); // was a known failure; fixed by 9a317a8 r.Add("buff chat: another player's speech can't record a buff timer", SpeechIsNotACast); // was a known failure; fixed by 0e384d2 - r.KnownFailure("buff school: Armor Tinkering Expertise is a Creature Enchantment spell", - "SkillForBuff matches \"Armor\" first and files it under Life Magic: its tier comes from Life Magic, and a character without Life Magic never casts it (not fixed on any branch)", - ArmorTinkeringSchool); + r.Add("buff school: Armor Tinkering Expertise is a Creature Enchantment spell", ArmorTinkeringSchool); // was a known failure } // ── Rig ─────────────────────────────────────────────────────────────────── @@ -401,7 +399,12 @@ internal static class BuffTests private static void ArmorTinkeringSchool() { - Check.Eq(BuffManager.SkillForBuff("Armor Tinkering Expertise"), AcSkillType.CreatureEnchantment, "Armor Tinkering Expertise"); + foreach (string n in new[] { "Armor Tinkering Expertise", "Item Tinkering Expertise", "Weapon Tinkering Expertise", + "Magic Item Tinkering Expertise", "Prodigal Armor Expertise", "Incantation of Armor Tinkering Expertise" }) + Check.Eq(BuffManager.SkillForBuff(n), AcSkillType.CreatureEnchantment, n); + // The "Armor" keyword still files real Life Magic armor buffs under Life. + foreach (string n in new[] { "Armor", "Incantation of Armor", "Prodigal Armor", "Blade Protection", "Regeneration" }) + Check.Eq(BuffManager.SkillForBuff(n), AcSkillType.LifeMagic, n); } private static void ItemEnchantments() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs index c02f7c4..4a5e11b 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs @@ -53,9 +53,8 @@ internal static class ExpressionTests r.Add("expr: chat and echo", ChatFunctions); r.Add("expr: $name reads an unset variable like getvar[name]", DollarMatchesGetvar); // was a known failure; fixed by 79a39b7 r.Add("expr: arithmetic that gives negative zero is false", NegativeZeroIsFalse); // was a known failure; fixed by 92a6318 - r.KnownFailure("expr: list items may contain commas or be lists", - "lists are stored as \"[a,b]\" and split on every comma, so an item with a comma (or a nested list) becomes several items", - ListItemsWithCommas); + r.Add("expr: list items may contain commas or be lists", ListItemsWithCommas); // was a known failure + r.Add("expr: list text saved before escaping reads the same", OldListTextReadsTheSame); r.Add("expr: # takes a regex pattern without backticks, as documented", RegexOperatorUnquoted); // was a known failure; fixed by c34b39c r.Add("expr: vitae[] reports no penalty when it cannot read vitae", VitaeWithoutHost); // was a known failure; fixed by 33f23f7 } @@ -914,6 +913,48 @@ internal static class ExpressionTests var e = Engine(); Check.Eq(e.Evaluate("listcount[listcreate[`a,b`, c]]"), "2", "an item holding a comma"); Check.Eq(e.Evaluate("listcount[listadd[listcreate[a], listcreate[b,c]]]"), "2", "a list added to a list"); + + // The items come back whole, and a nested list reads as a list again. + Check.Eq(e.Evaluate("listgetitem[listcreate[`a,b`, c], 0]"), "a,b", "the comma item reads back unescaped"); + Check.Eq(e.Evaluate("listgetitem[listadd[listcreate[a], listcreate[b,c]], 1]"), "[b,c]", "the nested list reads back as a list"); + Check.Eq(e.Evaluate("listcount[listgetitem[listadd[listcreate[a], listcreate[b,c]], 1]]"), "2", "and has its own two items"); + Check.Eq(e.Evaluate("listcontains[listcreate[`a,b`, c], `a,b`]"), "1", "listcontains finds the comma item"); + Check.Eq(e.Evaluate("listindexof[listcreate[x, `a,b`], `a,b`]"), "1", "listindexof finds it at 1"); + + // Brackets and backslashes in plain text survive too; plain lists keep their old text. + Check.Eq(e.Evaluate("listgetitem[listcreate[`x[1`, `c:\\d`], 0]"), "x[1", "an unbalanced bracket"); + Check.Eq(e.Evaluate("listgetitem[listcreate[`x[1`, `c:\\d`], 1]"), "c:\\d", "a backslash"); + Check.Eq(e.Evaluate("listcreate[a, b, c]"), "[a,b,c]", "a plain list is written as before"); + + // A nested list holding a comma item: the escape survives the nesting. + e.Evaluate("setvar[inner, listcreate[`p,q`, r]]"); + e.Evaluate("setvar[outer, listadd[listcreate[z], getvar[inner]]]"); + Check.Eq(e.Evaluate("listgetitem[listgetitem[getvar[outer], 1], 0]"), "p,q", "two levels down"); + } + + private static void OldListTextReadsTheSame() + { + // List text a meta built by hand, or saved in a pvar before escaping existed, reads the same. + var e = Engine(); + e.Evaluate("setvar[old, `[a,b,c]`]"); + Is(e, "listcount[getvar[old]]", "3"); + Is(e, "listgetitem[getvar[old], 1]", "b"); + Is(e, "listcount[`[a,,b,]`]", "4"); // empty items kept, as with Split + Is(e, "listgetitem[`[a,,b,]`, 1]", ""); + Is(e, "listreduce[`[1,2,3]`, `$2 + $1`]", "6"); + Is(e, "listsort[`[b,a,c]`]", "[a,b,c]"); + Is(e, "listmap[`[1,2]`, `$1 * 2`]", "[2,4]"); + Is(e, "listadd[`[a,b]`, c]", "[a,b,c]"); + Is(e, "listremove[`[a,b,c]`, b]", "[a,c]"); + Is(e, "listreverse[`[1,2,3]`]", "[3,2,1]"); + Is(e, "listfromrange[1, 3]", "[1,2,3]"); + + // A backslash that is not an escape is plain text (a path saved before escaping existed)... + Is(e, "listcount[`[c:\\d,x]`]", "2"); + Is(e, "listgetitem[`[c:\\d,x]`, 0]", "c:\\d"); + // ...and writing the list again escapes it, which reads back the same. + Is(e, "listadd[`[c:\\d]`, y]", "[c:\\\\d,y]"); + Is(e, "listgetitem[listadd[`[c:\\d]`, y], 0]", "c:\\d"); } private static void RegexOperatorUnquoted() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs index 427b42f..0b1e8bf 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs @@ -25,6 +25,7 @@ internal static class ItemInfoTests public static void Register(Runner r) { r.Add("iteminfo: a weapon's damage, mods, imbue, slayer, spells and wield line", WeaponLine); + r.Add("iteminfo: Crushing Blow as the dealt crit multiplier, Biting Strike as a crit chance", CritStats); r.Add("iteminfo: armor's set, AL, ratings, tinks and wield level", ArmorLine); r.Add("iteminfo: jewelry with mana, diff and craft; a bare item stays short", JewelryAndBareItem); r.Add("iteminfo: a selected item already appraised prints at once, no ID", SelectedAppraised); @@ -103,6 +104,30 @@ internal static class ItemInfoTests Check.False(s.Contains("not identified"), "identified: no note"); } + private static void CritStats() + { + var w = new Fake { Name = "Ornate Katar" }; + w.Ints[ItemInfoText.IntItemType] = 0x1; + w.Ints[ItemInfoText.IntDamage] = 77; + w.Ints[ItemInfoText.IntWeaponTime] = 30; + w.Floats[ItemInfoText.FloatCriticalMultiplier] = 2.66; + w.Floats[ItemInfoText.FloatCriticalFrequency] = 0.15; + w.Floats[ItemInfoText.FloatWeaponOffense] = 1.18; + string s = ItemInfoText.Describe(w, Spell); + InOrder(s, new[] { "Dmg 77", "Speed 30", "Crushing Blow 3.66x", "Biting Strike 15%", "(+18% atk)" }, "crit stats"); + + w.Floats[ItemInfoText.FloatCriticalMultiplier] = 1.0; // an ordinary crit + w.Floats[ItemInfoText.FloatCriticalFrequency] = 0.125; + s = ItemInfoText.Describe(w, Spell); + Check.False(s.Contains("Crushing Blow"), "a 1.0 multiplier is an ordinary crit: not shown"); + Check.True(s.Contains("Biting Strike 12.5%"), "a fractional crit chance keeps one decimal"); + + var a = new Fake { Name = "Chainmail Tassets" }; + a.Ints[ItemInfoText.IntItemType] = 0x2; + a.Floats[ItemInfoText.FloatCriticalMultiplier] = 3.0; + Check.False(ItemInfoText.Describe(a, Spell).Contains("Crushing Blow"), "only weapons show crit stats"); + } + private static void ArmorLine() { var a = new Fake { Name = "Chainmail Tassets" }; @@ -203,7 +228,8 @@ internal static class ItemInfoTests public void Tick() => typeof(RynthAiPlugin).GetMethod("TickItemInfo", Any)!.Invoke(P, null); - public string[] InfoLines => FakeHost.Chat.Where(c => c.StartsWith("[RynthAi] ", StringComparison.Ordinal)).ToArray(); + public string[] InfoLines => FakeHost.Chat.Where(c => c.StartsWith("[RynthAi] ", StringComparison.Ordinal) + || c.StartsWith(RynthAiPlugin.ItemPrefix, StringComparison.Ordinal)).ToArray(); } private static void Done() => RynthAiPlugin.ItemInfoClock = () => Environment.TickCount64; @@ -319,13 +345,13 @@ internal static class ItemInfoTests FakeHost.Appraised.Add(Ring); w.Command("/ra iteminfo mana scarab"); w.Tick(); - Check.True(w.InfoLines.Last().StartsWith("[RynthAi] Mana Scarab", StringComparison.Ordinal), $"exact name, any case: {w.InfoLines.Last()}"); + Check.True(w.InfoLines.Last().StartsWith("[RynthAi Item] Mana Scarab", StringComparison.Ordinal), $"exact name, any case: {w.InfoLines.Last()}"); w.Command("/ra iteminfo Scarab"); w.Tick(); Check.True(w.InfoLines.Last().Contains("Scarab") && !w.InfoLines.Last().Contains("not in your"), "a partial name finds a scarab"); w.Command("/ra iteminfo ring"); w.Tick(); - Check.True(w.InfoLines.Last().StartsWith("[RynthAi] Gold Ring", StringComparison.Ordinal), "partial: Gold Ring"); + Check.True(w.InfoLines.Last().StartsWith("[RynthAi Item] Gold Ring", StringComparison.Ordinal), "partial: Gold Ring"); Check.Eq(FakeHost.SelectedItem, 0u, "a named lookup doesn't need a selection"); } finally { Done(); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs index 5259fc1..b09696a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs @@ -54,9 +54,8 @@ internal static class MetaTests r.Add("meta: state snapshot", Snapshot); r.Add("meta: VendorClosed fires after a vendor closes", VendorClosedFires); // was a known failure; fixed by ef68455 r.Add("meta: InventoryItemCount counts stack sizes", InventoryCountsStacks); // was a known failure; fixed by 716f16d - r.KnownFailure("meta: SecondsInStateP keeps counting across a call and return", - "SecondsInStateP_GE survives a macro stop/start since 1ee6145, but still restarts whenever the state is re-entered (SetState, Call, Return), as VTank documents it; RynthScript says it survives re-entry. Open compatibility call (2026-09-30 audit, question 16)", - SecondsInStatePPersists); + r.Add("meta: SecondsInStateP keeps counting across a call and return", SecondsInStatePPersists); // was a known failure (2026-09-30 audit, question 16: RynthScript's re-entry rule) + r.Add("meta: SecondsInStateP pauses in a call, survives SetState to itself, restarts on a new state or meta", SecondsInStatePRules); r.Add("meta: MainHealthPHE / MainManaPHE mean 'percent >='", PercentConditionsAreGE); // was a known failure; fixed by a7c4618 r.Add("meta: a negative vital threshold never holds", NegativeVitalThreshold); // was a known failure; fixed by 6f72b67 r.Add("meta edit: saving a rule keeps the running meta's state, clocks and latch", EditKeepsRunningMeta); @@ -1105,6 +1104,78 @@ internal static class MetaTests Check.Eq(rig.Var("p"), "1", "SecondsInStateP_GE 25 after 25 s spent in Default around a 1 s call"); } + private static void SecondsInStatePRules() + { + // Paused while Default has Called Sub: 25 s of wall time is only 15 s in Default. + var call = new Rig(rules: new[] + { + Mark("Default", C.SecondsInStateP_GE, "20", "p"), + Rule("Default", C.SecondsInState_GE, "10", A.CallMetaState, "Sub"), + Rule("Sub", C.SecondsInState_GE, "10", A.ReturnFromCall, ""), + }); + call.Tick(); // T0: Default + call.Tick(10); // T0+10: call Sub + call.Tick(); + call.Tick(10); // T0+20: return + call.Tick(); + call.Tick(5); // T0+25: 15 s in Default + Check.False(call.Has("p"), "15 s in Default (10 s in Sub not counted)"); + call.Tick(5); // T0+30: 20 s in Default + Check.Eq(call.Var("p"), "1", "20 s in Default"); + + // In the called state the P clock is that state's own, from its entry. + var inSub = new Rig(rules: new[] + { + Rule("Default", C.SecondsInState_GE, "30", A.CallMetaState, "Sub"), + Mark("Sub", C.SecondsInStateP_GE, "5", "sub"), + }); + inSub.Tick(); + inSub.Tick(30); // call Sub after 30 s in Default + inSub.Tick(); + inSub.Tick(4); + Check.False(inSub.Has("sub"), "4 s into Sub"); + inSub.Tick(1); + Check.Eq(inSub.Var("sub"), "1", "5 s into Sub"); + + // SetState to the state it is already in: the plain clock restarts, the P clock does not. + var self = new Rig(rules: new[] + { + Mark("Default", C.SecondsInStateP_GE, "15", "p"), + Rule("Default", C.SecondsInState_GE, "10", A.SetMetaState, "Default"), + }); + self.Tick(); + self.Tick(10); // SetState Default + self.Tick(); + self.Tick(5); // 15 s since Default was entered + Check.Eq(self.Var("p"), "1", "SetState to the same state keeps the P clock"); + + // A move to another state restarts it. + var move = new Rig(rules: new[] + { + Rule("Default", C.SecondsInState_GE, "10", A.SetMetaState, "Hunt"), + Mark("Hunt", C.SecondsInStateP_GE, "3", "h"), + }); + move.Tick(); + move.Tick(10); + move.Tick(); + move.Tick(2.9); + Check.False(move.Has("h"), "2.9 s into Hunt (restarted on the move)"); + move.Tick(0.1); + Check.Eq(move.Var("h"), "1", "3 s into Hunt"); + + // Loading a meta restarts it, even when the start state has the same name. + var load = new Rig(rules: Mark("Default", C.SecondsInStateP_GE, "15", "p")); + load.Tick(); + load.Tick(10); + load.S.ForceStateReset = true; + load.S.MetaCallStackReset = true; // what a meta load sets + load.Tick(); + load.Tick(10); // 20 s in Default, 10 s since the load + Check.False(load.Has("p"), "10 s since the meta load"); + load.Tick(5); + Check.Eq(load.Var("p"), "1", "15 s since the meta load"); + } + private static void PercentConditionsAreGE() { var rig = new Rig(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NativeLootTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NativeLootTests.cs index 96b858b..f6e3a04 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/NativeLootTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NativeLootTests.cs @@ -42,9 +42,8 @@ internal static class NativeLootTests r.Add("loot native: profile JSON round trip keeps rules and order", JsonRoundTrip); r.Add("loot native: malformed or missing JSON profile", MalformedJson); r.Add("loot native: an invalid regex in a String rule does not match", InvalidRegexDoesNotThrow); // was a known failure; fixed by a2902c3 - r.KnownFailure("loot native: Keep # with a count of 0 survives a save and load", - "LootJsonContext skips default values when writing, so KeepCount 0 is left out and loads back as the initializer's 1", - KeepCountZeroRoundTrip); + r.Add("loot native: Keep # with a count of 0 survives a save and load", KeepCountZeroRoundTrip); // was a known failure + r.Add("loot native: salvage combine turned off survives a save and load", SalvageCombineOffRoundTrip); } private static LootRule Rule(string name, LootAction action, params LootCondition[] conds) @@ -366,4 +365,16 @@ internal static class NativeLootTests Profile(rule).Save(path); Check.Eq(LootProfile.Load(path).Rules[0].KeepCount, 0, "KeepCount after reload"); } + + /// LootJsonContext skips default values: SalvageCombine.Enabled = false was left out and loaded back as true. + private static void SalvageCombineOffRoundTrip() + { + var p = Profile(Rule("any", LootAction.Salvage)); + p.SalvageCombine = new SalvageCombineSettings { Enabled = false }; + string path = TempFile("combine-off.json"); + p.Save(path); + var loaded = LootProfile.Load(path); + Check.NotNull(loaded.SalvageCombine, "SalvageCombine after reload"); + Check.False(loaded.SalvageCombine?.Enabled ?? true, "SalvageCombine.Enabled stays off"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ProfileLoadTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ProfileLoadTests.cs new file mode 100644 index 0000000..bfd28b2 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ProfileLoadTests.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text.Json; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Loading a profile (login, profile switch) runs LegacyDashboardRenderer.CopySettings, which +// copies the loaded file into the live settings one field at a time. A field with no copy line +// keeps its in-memory default, and the next autosave writes that default over the profile. +// PetAutoRefill, MonsterNameBlacklist and the radar placement were dropped that way. +// - every serialized LegacyUiSettings member set to a non-default value comes through +// CopySettings (catches any field added later without a copy line); +// - a profile written to disk and loaded back serializes unchanged. +internal static class ProfileLoadTests +{ + private const BindingFlags Any = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("profile: every saved setting survives loading (CopySettings lists each serialized field)", EverySavedFieldIsCopied); + r.Add("profile: settings survive a save and a reload through the profile file", SettingsSurviveReload); + } + + /// LegacyDashboardRenderer.CopySettings(src, dst): what LoadSettings / SwitchProfile run. + private static void CopySettings(LegacyUiSettings src, LegacyUiSettings dst) => + typeof(LegacyDashboardRenderer).GetMethod("CopySettings", Any)!.Invoke(null, new object[] { src, dst }); + + /// A different value of the member's type that CopySettings' normalizing keeps distinct from the default. + private static bool TryMutate(string name, Type type, object? value, out object? mutated) + { + mutated = null; + if (name == nameof(LegacyUiSettings.OffhandDefault)) { mutated = "Shield"; return true; } // must parse as an OffhandMode + if (name == nameof(LegacyUiSettings.NavLabelMode)) { mutated = 1; return true; } // NavLabelModes.Clamp: 0..2 + Type t = Nullable.GetUnderlyingType(type) ?? type; + if (t == typeof(bool)) { mutated = !((bool?)value ?? false); return true; } + if (t == typeof(int)) { mutated = ((int?)value ?? 0) + 3; return true; } // +3: MovementMode 1/2 map back to 0 + if (t == typeof(long)) { mutated = ((long?)value ?? 0) + 3; return true; } + if (t == typeof(uint)) { mutated = ((uint?)value ?? 0) + 3; return true; } + if (t == typeof(float)) { mutated = ((float?)value ?? 0f) + 3f; return true; } + if (t == typeof(double)) { mutated = ((double?)value ?? 0.0) + 3.0; return true; } + if (t == typeof(string)) { mutated = (string?)value + "x"; return true; } + if (t.IsEnum) + { + foreach (object v in Enum.GetValues(t)) + if (!v.Equals(value)) { mutated = v; return true; } + } + return false; + } + + private static void EverySavedFieldIsCopied() + { + var info = RynthAiJsonContext.Default.LegacyUiSettings; + var defaults = new LegacyUiSettings(); + var src = new LegacyUiSettings(); + var dst = new LegacyUiSettings(); + + // Reference members (lists, option objects): dst must end up with a new instance. + var dstOriginal = new Dictionary(); + var skipped = new List(); + foreach (var p in info.Properties) + { + if (p.Get == null || p.Set == null) continue; + Type t = p.PropertyType; + if (t.IsValueType || t == typeof(string)) + { + if (TryMutate(p.Name, t, p.Get(src), out object? m)) p.Set(src, m); + else skipped.Add(p.Name); + } + else + { + dstOriginal[p.Name] = p.Get(dst); + } + } + + CopySettings(src, dst); + + int members = 0; + var missing = new List(); + foreach (var p in info.Properties) + { + if (p.Get == null || p.Set == null) continue; + members++; + if (dstOriginal.TryGetValue(p.Name, out object? before)) + { + if (before != null && ReferenceEquals(p.Get(dst), before)) missing.Add(p.Name); + } + else if (!skipped.Contains(p.Name) + && Equals(p.Get(dst), p.Get(defaults)) && !Equals(p.Get(src), p.Get(defaults))) + { + missing.Add(p.Name); + } + } + + Check.True(members > 100, $"the JSON metadata lists the settings ({members} members)"); + Check.Eq(skipped.Count, 0, "every value member has a test value (no test value for: " + string.Join(", ", skipped) + ")"); + Check.Eq(missing.Count, 0, "members CopySettings leaves at their default: " + string.Join(", ", missing)); + } + + private static void SettingsSurviveReload() + { + var saved = new LegacyUiSettings(); + saved.ItemInfoOnSelect = !saved.ItemInfoOnSelect; + saved.PetAutoRefill = !saved.PetAutoRefill; + saved.MonsterNameBlacklist.Add("Drudge Skulker"); + saved.RadarPosX = 120f; + saved.RadarSizeY = 300f; + + string path = Path.Combine(Program.TempRoot, "profile-load", "Default.json"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, JsonSerializer.Serialize(saved, RynthAiJsonContext.Default.LegacyUiSettings)); + + // LoadSettings: read the file, copy it into the live settings object (a fresh session). + var loaded = JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.LegacyUiSettings)!; + var live = new LegacyUiSettings(); + CopySettings(loaded, live); + + Check.Eq(live.ItemInfoOnSelect, saved.ItemInfoOnSelect, "describe items when selected"); + Check.Eq(live.PetAutoRefill, saved.PetAutoRefill, "pet auto refill"); + Check.True(live.MonsterNameBlacklist.Contains("Drudge Skulker"), "monster blacklist"); + Check.Eq(live.RadarPosX, 120f, "radar position"); + Check.Eq(live.RadarSizeY, 300f, "radar size"); + + // Unchanged JSON means the autosave right after login has nothing to write over the file. + Check.Eq(JsonSerializer.Serialize(live, RynthAiJsonContext.Default.LegacyUiSettings), + JsonSerializer.Serialize(saved, RynthAiJsonContext.Default.LegacyUiSettings), + "the reloaded profile saves back unchanged (autosave writes nothing different)"); + } +} diff --git a/Tools/RynthInventory.Tests/Program.cs b/Tools/RynthInventory.Tests/Program.cs index b159407..026e083 100644 --- a/Tools/RynthInventory.Tests/Program.cs +++ b/Tools/RynthInventory.Tests/Program.cs @@ -28,7 +28,7 @@ namespace RynthCore.Engine.UI.ScriptWindows namespace RynthInventory.Tests { - internal static class Program + internal static partial class Program { private static int _pass, _fail; private static string _temp = ""; @@ -64,6 +64,7 @@ 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); } finally { diff --git a/Tools/RynthInventory.Tests/VaultFeedTests.cs b/Tools/RynthInventory.Tests/VaultFeedTests.cs new file mode 100644 index 0000000..3892f1c --- /dev/null +++ b/Tools/RynthInventory.Tests/VaultFeedTests.cs @@ -0,0 +1,138 @@ +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 Sent) NewVault() + { + var sent = new List(); + 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 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 server without the command. + { + (VaultFeed v, List 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 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"); + } + } + } +}