diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 2a6d242..d711fd2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -1946,7 +1946,7 @@ internal sealed partial class LegacyDashboardRenderer dst.ShowTerrainPassability = tmp.ShowTerrainPassability; dst.NavLabelMode = NavLabelModes.Clamp(tmp.NavLabelMode); dst.NavGuideLine = tmp.NavGuideLine; - dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs; + dst.GiveQueueIntervalMs = LegacyUiSettings.MigrateGiveQueueIntervalMs(tmp.GiveQueueIntervalMs); dst.T11ItemAugsOverride = tmp.T11ItemAugsOverride; dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs; dst.StuckCastBreakMs = tmp.StuckCastBreakMs; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index adb527a..1ef4543 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -398,6 +398,9 @@ public sealed class LegacyUiSettings public List MonsterNameBlacklist { get; set; } = new(); public int GiveQueueIntervalMs = 0; + /// A saved GiveQueueIntervalMs: the old default (150) becomes 0 (the interval is now only a + /// minimum gap between sends; a round trip is longer than 150 ms anyway). Any other value is kept. + public static int MigrateGiveQueueIntervalMs(int saved) => saved == 150 ? 0 : saved; /// /// Item augmentation count used for T11 wield gates in loot rules ("T11: Can Wield"). diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 0bcec58..6294e76 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -2626,8 +2626,8 @@ public sealed partial class RynthAiPlugin } if (gives.Count == 1) { - GiveItem((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount, - Math.Max(1, gives[0].Item.Values(LongValueKey.StackCount, 1))); + // Through the queue: an NPC that takes one item per give needs the repeat-until-met loop. + EnqueueGive((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount); ChatLine($"[RynthAi] Giving {gives[0].Amount} x '{gives[0].Item.Name}' to {target.Name}"); } else diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index f941781..be1fff1 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -133,10 +133,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // Give queue — drained one item per tick with a cooldown (interval comes from settings) private readonly Queue<(uint itemId, uint targetId, int stackSize)> _pendingGives = new(); - private DateTime _lastGiveAt = DateTime.MinValue; // The give the server hasn't answered yet (0 = none): the next one waits for it. private uint _giveInFlightId, _giveInFlightTarget; - private int _giveInFlightAmount, _giveInFlightStack, _giveInFlightTries; + private int _giveInFlightStack, _giveInFlightTries; private long _giveInFlightAt; private const long GiveConfirmMs = 3000; private const int GiveMaxTries = 2; @@ -150,9 +149,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // A busy refusal re-sends the same give after this long, with no cap. private const long GiveBusyRetryMs = 300; private long _giveBusyRetryAt; // 0 = not waiting on a busy re-send + // Continuous busy waiting on one give: since when, how many busy answers, when the player was last told. + private long _giveBusySince, _giveBusyNoticeAt; + private int _giveBusyCount; + private const long GiveBusyNoticeMs = 10000; + // Consecutive ticks the in-flight item read as unreadable (no cache entry, Container 0); 2 = gone. + private int _giveGoneStreak; + private int _giveUnclassified; // unclassified chat lines logged for this give (max 5) // Chat verdict on the in-flight give, set by OnChatWindowText and read on the tick. private enum GiveChat { None, Busy, Permanent, ItemNotFound } - private GiveChat _giveChat = GiveChat.None; + private int _giveChatVerdict; // a GiveChat, handed from OnChatWindowText to the tick with Interlocked private string _giveChatLine = string.Empty; private bool _giveSawAcceptLine; // A stack that shrank but is still carried goes again before anything else in the queue. @@ -160,7 +166,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // Run summary (reset when the queue empties). private bool _giveRunActive; private long _giveRunStartAt, _giveRunLastAnswerAt; - private int _giveRunItems, _giveRunStacksDone; + private int _giveRunItems; private readonly List _giveRunSkips = new(); // Test seam: a fake millisecond clock. private Func? _giveClock; @@ -2327,7 +2333,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase else _dashboard?.PushChatLine(text, chatType); OnChatLocalFeatures(text, chatType, ref eat); try { NoteHotspotChat(text, chatType); } catch (Exception ex) { Host.Log($"[RynthAi] Hazard chat check failed: {ex.Message}"); } - NoteGiveChat(text); + NoteGiveChat(text, chatType); _buffManager?.OnChatWindowText(text, chatType); _manaStoneManager?.OnChatWindowText(text); _salvageManager?.OnChatWindowText(text); @@ -3420,7 +3426,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase internal void CancelGiveQueue() { - int count = _pendingGives.Count + (_giveRedo.HasValue ? 1 : 0); + var redo = _giveRedo; + int count = _pendingGives.Count + (redo.HasValue ? 1 : 0); _pendingGives.Clear(); ResetGiveState(); ChatLine(count > 0 @@ -3434,9 +3441,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _giveInFlightId = 0; _giveRedo = null; _giveBusyRetryAt = 0; - _giveChat = GiveChat.None; + _giveBusySince = 0; + _giveBusyCount = 0; + _giveGoneStreak = 0; + Interlocked.Exchange(ref _giveChatVerdict, 0); _giveRunActive = false; - _giveRunItems = _giveRunStacksDone = 0; + _giveRunItems = 0; _giveRunSkips.Clear(); } @@ -3458,15 +3468,46 @@ public sealed partial class RynthAiPlugin : RynthPluginBase return GiveChat.None; } - /// OnChatWindowText: only records the verdict; every send happens in DrainGiveQueue. - private void NoteGiveChat(string text) + /// + /// Speech, tells and emotes are other players' words, never the server's answer to a give. The engine + /// reports the client's own chat type: another player's speech arrives as 17 (DecalBridge log lines + /// "chat type=17 ... says, ..."), system notices as 0. Tells and emotes are not in any log, so the + /// text shape backs the type up. + /// + private static bool IsGiveChatSpeech(string text, int chatType) + { + if (chatType == 17) return true; + string t = text.ToLowerInvariant(); + return t.Contains(" says, \"") || t.Contains(" tells you, \"") || t.Contains(" asks, \"") + || t.Contains(" exclaims, \"") || t.Contains(" yells, \"") || t.Contains(" whispers, \"") + || t.StartsWith("you say, ", StringComparison.Ordinal) || t.StartsWith("you tell ", StringComparison.Ordinal) + || t.StartsWith("you whisper", StringComparison.Ordinal) || t.StartsWith("you exclaim", StringComparison.Ordinal) + || t.StartsWith("you yell", StringComparison.Ordinal) || t.StartsWith("you ask", StringComparison.Ordinal); + } + + /// + /// OnChatWindowText: only records the verdict; every send happens in DrainGiveQueue. The engine + /// dispatches chat from ProcessPendingActions and the plugin tick from TickAll, back to back in + /// one driver (EntryPoint.cs:1120-1122, ImGui/EngineFrameController.cs:461-467 in RynthCore-autoid), + /// so this is one thread in practice; the verdict still goes through Interlocked. + /// + private void NoteGiveChat(string text, int chatType = 0) { if (_giveInFlightId == 0) return; + if (IsGiveChatSpeech(text, chatType)) return; if (text.StartsWith("You give ", StringComparison.Ordinal)) { _giveSawAcceptLine = true; return; } var kind = ClassifyGiveChat(text); - if (kind == GiveChat.None) return; - // Busy outranks a permanent verdict already noted for this give; otherwise the first one stands. - if (_giveChat == GiveChat.None) { _giveChat = kind; _giveChatLine = text; } + if (kind == GiveChat.None) + { + if (_giveUnclassified < 5) + { + _giveUnclassified++; + Host.Log($"[Give] unclassified chat: type={chatType} '{text}'"); + } + return; + } + // The first verdict noted for this give stands until the tick takes it. + if (Interlocked.CompareExchange(ref _giveChatVerdict, (int)kind, 0) == 0) _giveChatLine = text; } /// @@ -3485,7 +3526,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (!ResolveGiveInFlight(now)) return; } - if (!_giveRedo.HasValue && _pendingGives.Count == 0) + var redo = _giveRedo; + if (!redo.HasValue && _pendingGives.Count == 0) { FinishGiveRun(now); return; @@ -3495,9 +3537,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase uint itemId, targetId; int amount; - if (_giveRedo.HasValue) + if (redo.HasValue) { - (itemId, targetId, amount) = _giveRedo.Value; + (itemId, targetId, amount) = redo.Value; _giveRedo = null; } else @@ -3507,7 +3549,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _giveRunActive = true; _giveRunStartAt = now; _giveRunLastAnswerAt = now; - _giveRunItems = _giveRunStacksDone = 0; + _giveRunItems = 0; _giveRunSkips.Clear(); } SendGive(itemId, targetId, amount, 1, resent: false, now); @@ -3522,13 +3564,20 @@ public sealed partial class RynthAiPlugin : RynthPluginBase long sinceSend = now - _giveInFlightAt; string tag = $"0x{_giveInFlightId:X8} '{_giveInFlightName}'"; - // 1. Progress: the item left the pack, or its stack shrank. - bool gone = true; - int stackNow = 0; - if (_objectCache?[unchecked((int)_giveInFlightId)] is WorldObject wo && InPlayerInventory(wo.Container)) + // 1. Progress: the item left the pack, or its stack shrank. A failed read is "no information": + // the stack count reads -1 (never a clamped 1, which looked like a shrink of 99), and an + // unreadable object (no cache entry, Container 0) must read the same on two ticks in a row. + var wo = _objectCache?[unchecked((int)_giveInFlightId)]; + bool readable = wo != null && wo.Container != 0; + bool carried = readable && InPlayerInventory(wo!.Container); + int stackNow = wo != null ? wo.Values(LongValueKey.StackCount, -1) : -1; + bool gone; + if (readable && !carried) { gone = true; _giveGoneStreak = 0; } + else if (readable) { gone = false; _giveGoneStreak = 0; } + else { - gone = false; - stackNow = Math.Max(1, wo.Values(LongValueKey.StackCount, 1)); + _giveGoneStreak++; + gone = _giveSawAcceptLine || _giveGoneStreak >= 2; } if (gone) { @@ -3537,7 +3586,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase CompleteGiveStack(given, now); return true; } - if (stackNow < _giveInFlightStack) + if (carried && stackNow >= 0 && stackNow < _giveInFlightStack) { int delta = _giveInFlightStack - stackNow; int remaining = _giveInFlightRemaining - delta; @@ -3547,32 +3596,47 @@ public sealed partial class RynthAiPlugin : RynthPluginBase uint shrunkId = _giveInFlightId; _giveInFlightId = 0; _giveBusyRetryAt = 0; + _giveBusySince = 0; if (remaining > 0) _giveRedo = (shrunkId, _giveInFlightTarget, remaining); - else - _giveRunStacksDone++; return true; } // 2. A chat verdict. - var chat = _giveChat; - _giveChat = GiveChat.None; - if (chat == GiveChat.ItemNotFound && _giveInFlightResent) + var chat = (GiveChat)Interlocked.Exchange(ref _giveChatVerdict, 0); + if (chat == GiveChat.ItemNotFound) { - int given = Math.Max(1, _giveInFlightRemaining); - Host.Log($"[RynthAi] Give answer: item-not-found after a re-send, counted as given {tag} +{given} item(s) after {sinceSend} ms"); - CompleteGiveStack(given, now); + // "Item not found" after a re-send means the earlier send landed, but only if the pack agrees: + // gone (or unreadable) counts as given; still carried with the same stack is a plain skip. + if (_giveInFlightResent && !carried) + { + int given = Math.Max(1, _giveInFlightRemaining); + Host.Log($"[RynthAi] Give answer: item-not-found after a re-send, item gone, counted as given {tag} +{given} item(s) after {sinceSend} ms"); + CompleteGiveStack(given, now); + return true; + } + Host.Log($"[RynthAi] Give answer: permanent {tag} '{_giveChatLine}' after {sinceSend} ms"); + SkipGiveStack("item not found", tag, now); return true; } - if (chat == GiveChat.ItemNotFound || chat == GiveChat.Permanent) + if (chat == GiveChat.Permanent) { Host.Log($"[RynthAi] Give answer: permanent {tag} '{_giveChatLine}' after {sinceSend} ms"); - SkipGiveStack(chat == GiveChat.ItemNotFound ? "item not found" : "refused", tag, now); + SkipGiveStack("refused", tag, now); return true; } if (chat == GiveChat.Busy) { - Host.Log($"[RynthAi] Give answer: busy {tag} '{_giveChatLine}' after {sinceSend} ms; re-sending in {GiveBusyRetryMs} ms"); + _giveBusyCount++; + if (_giveBusySince == 0) { _giveBusySince = now; _giveBusyNoticeAt = now; } + if (_giveBusyCount == 1 || _giveBusyCount % 10 == 0) + Host.Log($"[RynthAi] Give answer: busy #{_giveBusyCount} {tag} '{_giveChatLine}' after {sinceSend} ms; re-sending in {GiveBusyRetryMs} ms"); + if (now - _giveBusyNoticeAt >= GiveBusyNoticeMs) + { + _giveBusyNoticeAt = now; + string? who = _objectCache?[unchecked((int)_giveInFlightTarget)]?.Name; + ChatLine($"[RynthAi] Give: {(string.IsNullOrEmpty(who) ? "the target" : who)} is busy - still retrying (/ra givea stop to cancel)."); + } _giveBusyRetryAt = now + GiveBusyRetryMs; } if (_giveBusyRetryAt != 0) @@ -3600,10 +3664,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private void CompleteGiveStack(int items, long now) { _giveRunItems += items; - _giveRunStacksDone++; _giveRunLastAnswerAt = now; _giveInFlightId = 0; _giveBusyRetryAt = 0; + _giveBusySince = 0; } private void SkipGiveStack(string why, string tag, long now) @@ -3613,28 +3677,33 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _giveRunLastAnswerAt = now; _giveInFlightId = 0; _giveBusyRetryAt = 0; + _giveBusySince = 0; } /// Sends one give and records it as the in-flight one (amount = items still to hand over). private void SendGive(uint itemId, uint targetId, int amount, int tries, bool resent, long now) { WorldObject? wo = _objectCache?[unchecked((int)itemId)]; - int whole = wo != null ? Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) : Math.Max(1, amount); + // A failed or absent stack read is -1: record max(1, amount) as the stack, and send an explicit + // amount when it is more than one (never the whole object on a failed read). + int read = wo != null ? wo.Values(LongValueKey.StackCount, -1) : -1; + int whole = read >= 0 ? Math.Max(1, read) : Math.Max(1, amount); string name = wo?.Name ?? string.Empty; _giveInFlightId = itemId; _giveInFlightTarget = targetId; - _giveInFlightAmount = amount; - _giveInFlightRemaining = amount <= 0 || amount > whole ? whole : amount; + _giveInFlightRemaining = read < 0 ? Math.Max(1, amount) : (amount <= 0 || amount > whole ? whole : amount); _giveInFlightStack = whole; _giveInFlightTries = tries; _giveInFlightResent = resent; _giveInFlightName = name; _giveInFlightAt = now; _giveLastSendAt = now; - _giveChat = GiveChat.None; + Interlocked.Exchange(ref _giveChatVerdict, 0); _giveSawAcceptLine = false; - GiveItem(itemId, targetId, amount, whole); - Host.Log($"[RynthAi] Give send: 0x{itemId:X8} '{name}' stack={whole} amount={amount} try={tries}{(resent ? " (re-send)" : string.Empty)}"); + _giveGoneStreak = 0; + if (!resent) { _giveBusyCount = 0; _giveBusySince = 0; _giveUnclassified = 0; } + GiveItem(itemId, targetId, amount, read >= 0 ? whole : (amount > 1 ? amount + 1 : amount)); + Host.Log($"[RynthAi] Give send: 0x{itemId:X8} '{name}' stack={(read >= 0 ? whole.ToString() : "?")} amount={amount} try={tries}{(resent ? " (re-send)" : string.Empty)}"); } private void FinishGiveRun(long now) @@ -3647,7 +3716,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase string line = $"[RynthAi] Give queue complete: {_giveRunItems} item(s) given, {_giveRunSkips.Count} stack(s) skipped{why}, {elapsed / 1000.0:0.0}s total, {avg} per give."; Host.Log(line); ChatLine(line); - _giveRunItems = _giveRunStacksDone = 0; + _giveRunItems = 0; _giveRunSkips.Clear(); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs index 09a3f5b..57edf2e 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs @@ -34,7 +34,14 @@ internal static class GiveTests r.Add("give: a permanent refusal skips the stack at once and moves on", PermanentSkips); r.Add("give: item not found after a re-send counts as given", ItemNotFoundAfterResendCounts); r.Add("give: the summary counts items, not stacks", SummaryCountsItems); - r.Add("give: no answer at all re-sends once, then skips", NoAnswerSkips); } + r.Add("give: no answer at all re-sends once, then skips", NoAnswerSkips); + r.Add("give: an unreadable stack count is no information, not a shrink", UnreadableStackIsNotAShrink); + r.Add("give: an item unreadable for one tick is not gone; for two it is", OneTickUnreadableIsNotGone); + r.Add("give: speech lines never answer a give; item not found with the stack unchanged is a skip", SpeechIgnoredAndNotFoundNeedsGone); + r.Add("give: busy notice after 10 s, busy logging throttled, unclassified lines logged (max 5)", BusyNoticeAndLogThrottle); + r.Add("give: a counted give from one stack goes through the queue (NPC one per give, player split once)", CountedSingleStack); + r.Add("give: cancel in the middle of a busy wait stops everything", CancelMidBusy); + r.Add("give: a saved interval of 150 migrates to 0, other values stay", IntervalMigration); } private sealed class World { @@ -94,7 +101,7 @@ internal static class GiveTests /// Advances the clock, then runs one tick of the give queue. public void Tick(long advanceMs = 0) { Now += advanceMs; Call("DrainGiveQueue"); } - public void Chat(string text) => Call("NoteGiveChat", text); + public void Chat(string text, int chatType = 0) => Call("NoteGiveChat", text, chatType); /// Adds a carried stack the cache knows about. public void AddStack(uint id, string name, int count) @@ -262,6 +269,7 @@ internal static class GiveTests w.Tick(); w.Tick(3001); // no answer: sent once more Check.Eq(FakeHost.Gives.Count, 2, "re-sent after the confirm time"); + FakeHost.Containers[Mote1] = Npc; // the first send did land: the item is gone from the pack w.Chat("Item not found!"); w.Tick(); Check.Eq(FakeHost.Gives.Count, 2, "no third send"); @@ -291,5 +299,147 @@ internal static class GiveTests Check.True(w.ChatHas("didn't take"), "and says so"); Check.True(w.ChatHas("1 stack(s) skipped"), "the summary counts it as skipped"); } -} + private static void UnreadableStackIsNotAShrink() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; // the server has not answered yet + w.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + w.Call("EnqueueGive", Carapace, Npc, 5); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "sent"); + FakeHost.Ints.Remove((Carapace, 12)); // the engine read fails for a tick + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "a failed read is not a shrink of 4: no second give while the first is in flight"); + FakeHost.Ints[(Carapace, 12)] = 5; + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "read again, unchanged: still waiting"); + Check.False(w.ChatHas("item(s) given"), "nothing credited"); + FakeHost.Ints[(Carapace, 12)] = 4; // now a real shrink + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "a real shrink gives again"); + } + + private static void OneTickUnreadableIsNotGone() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + FakeHost.Containers[Mote1] = 0; // one unreadable tick + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "Container 0 for one tick is not gone"); + FakeHost.Containers[Mote1] = Player; + w.Tick(); + FakeHost.Containers[Mote1] = 0; + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "the streak restarted after a good read"); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "unreadable on two ticks in a row: gone, the next stack goes"); + } + + private static void SpeechIgnoredAndNotFoundNeedsGone() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + w.Chat("Bob<\\Tell> says, \"Town Crier doesn't want that\"", 17); + w.Chat("Bob says, \"Town Crier doesn't want that\"", 0); // shape alone is enough + w.Chat("Bob tells you, \"not accepting gifts\"", 3); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "other players' words are no answer: still in flight, nothing skipped"); + Check.False(w.ChatHas("skipped"), "no summary yet"); + w.Tick(3001); // re-sent + w.Chat("Item not found!"); + w.Tick(); // the item is still carried, stack unchanged: a skip, not a delivery + Check.Eq(FakeHost.Gives.Count, 3, "item not found with the item still in the pack skips it; the next stack goes"); + FakeHost.Containers[Mote2] = Npc; + w.Tick(); + Check.True(w.ChatHas("1 item(s) given, 1 stack(s) skipped"), "one skipped as item not found, one given"); + } + + private static void BusyNoticeAndLogThrottle() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Tick(); + for (int i = 0; i < 6; i++) w.Chat("Something odd " + i); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Give] unclassified chat:")), 5, "at most 5 unclassified lines logged per give"); + int busyCycles = 0; + long start = w.Now; + while (w.Now - start < 9000) + { + w.Chat("You're too busy!"); + w.Tick(0); + w.Tick(300); + busyCycles++; + } + Check.False(w.ChatHas("still retrying"), "no notice before 10 s of busy waiting"); + while (w.Now - start < 10700) + { + w.Chat("You're too busy!"); + w.Tick(0); + w.Tick(300); + busyCycles++; + } + Check.Eq(FakeHost.Chat.Count(c => c.Contains("Town Crier is busy - still retrying (/ra givea stop to cancel).")), 1, "one notice at about 10 s"); + int busyLogs = FakeHost.Logs.Count(l => l.Contains("Give answer: busy")); + Check.True(busyCycles >= 30 && busyLogs <= busyCycles / 10 + 1, $"busy logging throttled: {busyLogs} lines for {busyCycles} busy answers"); + Check.True(busyLogs >= 1, "the first busy is logged"); + } + + private static void CountedSingleStack() + { + var w = new World(); + w.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + w.NpcTakesOnePerGive(); + w.Run("/ub give 3 Olthoi Slayer Carapace to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 3, "3 of 5 to a one-per-give NPC: three gives"); + Check.Eq(FakeHost.Ints[(Carapace, 12)], 2, "two left in the pack"); + Check.Eq(FakeHost.Containers[Carapace], Player, "the stack stays"); + + var w2 = new World(); + const uint Friend = 0x50000F02; + FakeHost.Names[Friend] = "Friend"; + FakeHost.Positions[Friend] = (0x1048002Au, 101f, 101f, 0f); + FakeHost.ItemTypes[Friend] = 0x10; + w2.Cache.OnCreateObject(Friend); + w2.Cache.Tick(); + w2.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + FakeHost.GiveHandler = (item, target, amount) => + { + FakeHost.Ints[(item, 12)] -= amount == 0 ? FakeHost.Ints[(item, 12)] : amount; // a player takes what is asked + }; + w2.Run("/ub give 3 Olthoi Slayer Carapace to Friend"); + Check.Eq(FakeHost.Gives.Count, 1, "to a player: one give"); + Check.Eq(FakeHost.Gives[0].Amount, 3, "carrying the count (the server splits)"); + Check.Eq(FakeHost.Ints[(Carapace, 12)], 2, "two left"); + } + + private static void CancelMidBusy() + { + var w = new World(); + FakeHost.GiveHandler = (_, _, _) => { }; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + w.Chat("You're too busy!"); + w.Tick(100); // busy seen, re-send armed + w.Call("CancelGiveQueue"); + for (int i = 0; i < 20; i++) w.Tick(500); + Check.Eq(FakeHost.Gives.Count, 1, "nothing is sent after the cancel: no re-send, no next stack"); + Check.True(w.ChatHas("Give queue cancelled"), "cancel reported"); + } + + private static void IntervalMigration() + { + Check.Eq(LegacyUiSettings.MigrateGiveQueueIntervalMs(150), 0, "the old default becomes 0"); + Check.Eq(LegacyUiSettings.MigrateGiveQueueIntervalMs(400), 400, "a chosen value stays"); + Check.Eq(LegacyUiSettings.MigrateGiveQueueIntervalMs(0), 0, "0 stays"); + Check.Eq(new LegacyUiSettings().GiveQueueIntervalMs, 0, "the default is 0"); + } +}