From 4afd6c41a933fcb43e0c897623f1d5874cc07fab Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Mon, 12 Oct 2026 18:44:39 -0700 Subject: [PATCH] Give queue: shrink-aware landing, no dead time, busy re-sends An NPC with a Give emote takes one item per give, so a whole-stack give left the stack in the pack and the queue waited 3 s, re-sent, then skipped. - A give is answered when the item leaves the pack or its stack shrinks; a shrunk stack goes again in the same tick (one give in flight at a time). - Post-landing interval removed; GiveQueueIntervalMs (default 0, range 0-2000) is only a minimum gap between sends. - Busy-class chat re-sends after 300 ms with no cap; permanent refusals skip at once; Item not found after a re-send counts as given. - No-answer re-send/skip (3 s, 2 tries) kept. - Per-send/answer/skip Host.Log lines and an end-of-run summary. - Tests in GiveTests.cs (fake clock + FakeHost.GiveHandler). Co-Authored-By: Claude Opus 5.5 (1M context) --- .../LegacyUi/LegacyAdvancedSettingsUi.cs | 4 +- .../LegacyUi/LegacyUiSettings.cs | 2 +- .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 291 ++++++++++++++---- .../Fakes/FakeHost.cs | 5 +- .../Tests/GiveTests.cs | 159 +++++++++- 5 files changed, 404 insertions(+), 57 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 7ec3561..d00dd58 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -433,9 +433,9 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Spacing(); ImGui.Text("Give Queue"); ImGui.SetNextItemWidth(150); - ImGui.SliderInt("Give Interval (ms)", ref _settings.GiveQueueIntervalMs, 50, 2000); + ImGui.SliderInt("Give Interval (ms)", ref _settings.GiveQueueIntervalMs, 0, 2000); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Minimum delay between each item sent by /ra givea commands.\nLower = faster but may drop items if the server can't keep up."); + ImGui.SetTooltip("Minimum gap between two gives sent by /ra givea commands.\n0 = send the next give the moment the server answers the last (fastest).\nThe queue always waits for the server's answer first."); break; case "Recharge": diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index c50f09b..adb527a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -397,7 +397,7 @@ public sealed class LegacyUiSettings /// public List MonsterNameBlacklist { get; set; } = new(); - public int GiveQueueIntervalMs = 150; + public int GiveQueueIntervalMs = 0; /// /// Item augmentation count used for T11 wield gates in loot rules ("T11: Can Wield"). diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index afd4360..f941781 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -140,6 +140,31 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private long _giveInFlightAt; private const long GiveConfirmMs = 3000; private const int GiveMaxTries = 2; + // Items still to hand over from the in-flight give (a whole stack = its size; each shrink lowers it). + private int _giveInFlightRemaining; + // True once the in-flight give has been sent more than once (a busy re-send or a no-answer re-send): + // an "Item not found!" then means an earlier send already landed. + private bool _giveInFlightResent; + private string _giveInFlightName = string.Empty; + private long _giveLastSendAt = long.MinValue; + // 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 + // 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 string _giveChatLine = string.Empty; + private bool _giveSawAcceptLine; + // A stack that shrank but is still carried goes again before anything else in the queue. + private (uint itemId, uint targetId, int remaining)? _giveRedo; + // Run summary (reset when the queue empties). + private bool _giveRunActive; + private long _giveRunStartAt, _giveRunLastAnswerAt; + private int _giveRunItems, _giveRunStacksDone; + private readonly List _giveRunSkips = new(); + // Test seam: a fake millisecond clock. + private Func? _giveClock; + private long GiveNow() => _giveClock?.Invoke() ?? Environment.TickCount64; private RynthCore.Loot.LootProfile? _nativeLootProfile; private string _nativeLootProfilePath = string.Empty; private DateTime _nativeLootProfileTime = DateTime.MinValue; @@ -450,6 +475,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _playerId = 0; _loginComplete = false; _pendingGives.Clear(); + ResetGiveState(); // A /ub delay armed before logout must not fire into the next character's session. _delayedCommands.Clear(); ClearPropertyDump(); @@ -1011,7 +1037,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { ["TargetFPSFocused"] = (10, 240), ["TargetFPSBackground"] = (5, 60), ["BlacklistAttempts"] = (1, 20), ["BlacklistTimeoutSec"] = (5, 120), ["BlacklistCastSettleMs"] = (500, 5000), - ["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000), + ["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (0, 2000), ["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60), ["MissileArcClearance"] = (0, 3), ["HealAt"] = (0, 100), ["EmergencyHealAt"] = (0, 100), ["StaminaToHealthAt"] = (0, 100), ["StaminaToHealthMinStamina"] = (0, 100), ["RestamAt"] = (0, 100), ["RestamTo"] = (0, 100), ["GetManaAt"] = (0, 100), @@ -2301,6 +2327,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); _buffManager?.OnChatWindowText(text, chatType); _manaStoneManager?.OnChatWindowText(text); _salvageManager?.OnChatWindowText(text); @@ -3393,75 +3420,235 @@ public sealed partial class RynthAiPlugin : RynthPluginBase internal void CancelGiveQueue() { - int count = _pendingGives.Count; + int count = _pendingGives.Count + (_giveRedo.HasValue ? 1 : 0); _pendingGives.Clear(); - _giveInFlightId = 0; + ResetGiveState(); ChatLine(count > 0 ? $"[RynthAi] Give queue cancelled ({count} item(s) remaining)." : "[RynthAi] Give queue is already empty."); } + /// Drops the in-flight give, the redo slot and the run summary (cancel, logout). + private void ResetGiveState() + { + _giveInFlightId = 0; + _giveRedo = null; + _giveBusyRetryAt = 0; + _giveChat = GiveChat.None; + _giveRunActive = false; + _giveRunItems = _giveRunStacksDone = 0; + _giveRunSkips.Clear(); + } + /// - /// One give at a time, each after the server has taken the last: the item has left the - /// inventory (or its stack shrank, for part of a stack). The queue used to send a give - /// every 150 ms; the server takes one give at a time and answers the rest "too busy", - /// so /ub give handed over one item and dropped the rest (2026-10-08). A give with no - /// answer in GiveConfirmMs is sent once more, then skipped. + /// Classifies a chat line as an answer to the in-flight give. Lowercase substrings: the client + /// renders WeenieError text from its own string table, so only the server's custom strings + /// ("Item not found!", "Target not found!", "Give amount not valid!") are exact. + /// + private static GiveChat ClassifyGiveChat(string text) + { + string t = text.ToLowerInvariant(); + // Busy class first: " is too busy to accept gifts" must not read as "not accepting gifts". + if (t.Contains("too busy") || t.Contains("is busy right now")) return GiveChat.Busy; + if (t.Contains("item not found")) return GiveChat.ItemNotFound; + if (t.Contains("give amount not valid") || t.Contains("target not found") + || t.Contains("doesn't want") || t.Contains("does not want") + || t.Contains("not accepting gifts") || t.Contains("cowers from you")) + return GiveChat.Permanent; + return GiveChat.None; + } + + /// OnChatWindowText: only records the verdict; every send happens in DrainGiveQueue. + private void NoteGiveChat(string text) + { + if (_giveInFlightId == 0) 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; } + } + + /// + /// One give at a time, answered before the next goes out (ACE cancels a move chain when a second + /// give arrives, and answers extras "too busy"). An answer is the item leaving the pack or its + /// stack shrinking: an NPC with a Give emote takes ONE item per give, so a shrunk stack goes + /// again at once, in the same tick. Busy refusals re-send after GiveBusyRetryMs with no cap; + /// permanent refusals skip the stack. No answer at all in GiveConfirmMs re-sends, up to + /// GiveMaxTries, then skips. GiveQueueIntervalMs is only a minimum gap between two sends. /// private void DrainGiveQueue() { - long now = Environment.TickCount64; + long now = GiveNow(); if (_giveInFlightId != 0) { - if (GiveLanded()) - { - _giveInFlightId = 0; - _lastGiveAt = DateTime.UtcNow; - if (_pendingGives.Count == 0) - ChatLine("[RynthAi] Give queue complete."); - } - else if (now - _giveInFlightAt < GiveConfirmMs) - return; - else if (_giveInFlightTries < GiveMaxTries) - { - GiveItem(_giveInFlightId, _giveInFlightTarget, _giveInFlightAmount, _giveInFlightStack); - _giveInFlightTries++; - _giveInFlightAt = now; - return; - } - else - { - ChatLine($"[RynthAi] Give: the server didn't take 0x{_giveInFlightId:X8} - skipping it."); - _giveInFlightId = 0; - if (_pendingGives.Count == 0) return; - } + if (!ResolveGiveInFlight(now)) return; } - if (_pendingGives.Count == 0) return; - int intervalMs = _dashboard?.Settings.GiveQueueIntervalMs ?? 150; - if ((DateTime.UtcNow - _lastGiveAt).TotalMilliseconds < intervalMs) return; + if (!_giveRedo.HasValue && _pendingGives.Count == 0) + { + FinishGiveRun(now); + return; + } + int intervalMs = Math.Max(0, _dashboard?.Settings.GiveQueueIntervalMs ?? 0); + if (intervalMs > 0 && _giveLastSendAt != long.MinValue && now - _giveLastSendAt < intervalMs) return; - var (itemId, targetId, stackSize) = _pendingGives.Dequeue(); - // The queued amount is what to hand over; GiveItem gives the whole object when it is - // the whole stack (amount 0) and uses AC's real give action, which an NPC accepts. - int whole = _objectCache?[unchecked((int)itemId)] is WorldObject wo ? Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) : stackSize; - GiveItem(itemId, targetId, stackSize, whole); - _lastGiveAt = DateTime.UtcNow; - _giveInFlightId = itemId; - _giveInFlightTarget = targetId; - _giveInFlightAmount = stackSize; - _giveInFlightStack = whole; - _giveInFlightTries = 1; - _giveInFlightAt = now; + uint itemId, targetId; + int amount; + if (_giveRedo.HasValue) + { + (itemId, targetId, amount) = _giveRedo.Value; + _giveRedo = null; + } + else + (itemId, targetId, amount) = _pendingGives.Dequeue(); + if (!_giveRunActive) + { + _giveRunActive = true; + _giveRunStartAt = now; + _giveRunLastAnswerAt = now; + _giveRunItems = _giveRunStacksDone = 0; + _giveRunSkips.Clear(); + } + SendGive(itemId, targetId, amount, 1, resent: false, now); } - /// The in-flight give went through: the item left the inventory, or part of its stack did. - private bool GiveLanded() + /// + /// Settles the in-flight give. Returns true when it is done (landed or skipped) and the tick may + /// send the next give now; false when the tick must stop (still waiting, or a re-send just went out). + /// + private bool ResolveGiveInFlight(long now) { - if (_objectCache?[unchecked((int)_giveInFlightId)] is not WorldObject wo) return true; - if (!InPlayerInventory(wo.Container)) return true; - return _giveInFlightAmount < _giveInFlightStack - && Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) < _giveInFlightStack; + 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)) + { + gone = false; + stackNow = Math.Max(1, wo.Values(LongValueKey.StackCount, 1)); + } + if (gone) + { + int given = Math.Max(1, Math.Min(_giveInFlightRemaining, _giveInFlightStack)); + Host.Log($"[RynthAi] Give answer: gone {tag} +{given} item(s) after {sinceSend} ms (accept line seen: {_giveSawAcceptLine})"); + CompleteGiveStack(given, now); + return true; + } + if (stackNow < _giveInFlightStack) + { + int delta = _giveInFlightStack - stackNow; + int remaining = _giveInFlightRemaining - delta; + Host.Log($"[RynthAi] Give answer: shrink {tag} {_giveInFlightStack}->{stackNow} after {sinceSend} ms (accept line seen: {_giveSawAcceptLine})"); + _giveRunItems += delta; + _giveRunLastAnswerAt = now; + uint shrunkId = _giveInFlightId; + _giveInFlightId = 0; + _giveBusyRetryAt = 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) + { + 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); + return true; + } + if (chat == GiveChat.ItemNotFound || chat == GiveChat.Permanent) + { + Host.Log($"[RynthAi] Give answer: permanent {tag} '{_giveChatLine}' after {sinceSend} ms"); + SkipGiveStack(chat == GiveChat.ItemNotFound ? "item not found" : "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"); + _giveBusyRetryAt = now + GiveBusyRetryMs; + } + if (_giveBusyRetryAt != 0) + { + if (now < _giveBusyRetryAt) return false; + _giveBusyRetryAt = 0; + SendGive(_giveInFlightId, _giveInFlightTarget, _giveInFlightRemaining, _giveInFlightTries, resent: true, now); + return false; + } + + // 3. No answer at all. + if (sinceSend < GiveConfirmMs) return false; + if (_giveInFlightTries < GiveMaxTries) + { + Host.Log($"[RynthAi] Give answer: no-answer {tag} after {sinceSend} ms; re-sending"); + SendGive(_giveInFlightId, _giveInFlightTarget, _giveInFlightRemaining, _giveInFlightTries + 1, resent: true, now); + return false; + } + Host.Log($"[RynthAi] Give answer: no-answer {tag} after {sinceSend} ms; giving up"); + ChatLine($"[RynthAi] Give: the server didn't take 0x{_giveInFlightId:X8} - skipping it."); + SkipGiveStack("no answer", tag, now); + return true; + } + + private void CompleteGiveStack(int items, long now) + { + _giveRunItems += items; + _giveRunStacksDone++; + _giveRunLastAnswerAt = now; + _giveInFlightId = 0; + _giveBusyRetryAt = 0; + } + + private void SkipGiveStack(string why, string tag, long now) + { + _giveRunSkips.Add($"{tag}: {why}"); + Host.Log($"[RynthAi] Give skip: {tag} ({why})"); + _giveRunLastAnswerAt = now; + _giveInFlightId = 0; + _giveBusyRetryAt = 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); + string name = wo?.Name ?? string.Empty; + _giveInFlightId = itemId; + _giveInFlightTarget = targetId; + _giveInFlightAmount = amount; + _giveInFlightRemaining = amount <= 0 || amount > whole ? whole : amount; + _giveInFlightStack = whole; + _giveInFlightTries = tries; + _giveInFlightResent = resent; + _giveInFlightName = name; + _giveInFlightAt = now; + _giveLastSendAt = now; + _giveChat = GiveChat.None; + _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)}"); + } + + private void FinishGiveRun(long now) + { + if (!_giveRunActive) return; + _giveRunActive = false; + long elapsed = Math.Max(0, _giveRunLastAnswerAt - _giveRunStartAt); + string avg = _giveRunItems > 0 ? $"{elapsed / _giveRunItems} ms" : "n/a"; + string why = _giveRunSkips.Count == 0 ? string.Empty : $" ({string.Join("; ", _giveRunSkips)})"; + 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; + _giveRunSkips.Clear(); } /// diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index 3dc7d1a..43c3785 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -105,6 +105,8 @@ internal static unsafe class FakeHost /// When true (the default) a give lands at once, as the server does when it isn't busy: /// the item goes to the target. False = the server hasn't taken it (still carried). public static bool GiveLands = true; + /// Optional: runs for every give instead of the default landing (a test's own server: NPC takes one per give, busy, ...). + public static Action? GiveHandler; /// Opt-in: wires StopCompletely (off by default so no other test sees it). public static bool StopCalls; /// StopCompletely calls (opt-in with ). @@ -262,7 +264,7 @@ internal static unsafe class FakeHost Vitals = default; BaseVitals = default; WorldName = ""; AccountName = ""; HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0; Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); AfterCastSpell = null; - AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; + AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null; Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1; RequestIdAccepts = true; RefusedIdRequests = 0; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; @@ -774,6 +776,7 @@ internal static unsafe class FakeHost private static int GiveObjectTo(uint item, uint target, int amount) { Gives.Add((item, target, amount)); + if (GiveHandler != null) { GiveHandler(item, target, amount); return 1; } if (GiveLands && amount == 0) Containers[item] = target; return 1; } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs index 8c117b5..09a3f5b 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs @@ -28,12 +28,20 @@ internal static class GiveTests r.Add("give: /mt give hands over only the first match", MtGivesFirst); r.Add("give: /ub givep matches part of the name", UbGivePartial); r.Add("give: the next give waits until the server took the last (it answers extra gives 'too busy')", WaitsForServer); - } + r.Add("give: a whole stack to an NPC that takes one per give keeps giving until it is gone, one give per tick", NpcStackOneAtATime); + r.Add("give: the answer and the next give share one tick (the interval is only a minimum gap between sends)", NextGiveSameTick); + r.Add("give: busy refusals re-send with no cap", BusyResendsUncapped); + r.Add("give: a permanent refusal skips the stack at once and moves on", PermanentSkips); + r.Add("give: item not found after a re-send counts as given", ItemNotFoundAfterResendCounts); + r.Add("give: the summary counts items, not stacks", SummaryCountsItems); + r.Add("give: no answer at all re-sends once, then skips", NoAnswerSkips); } private sealed class World { public readonly RynthAiPlugin P = new(); public readonly LegacyUiSettings S = new() { GiveQueueIntervalMs = 0 }; + /// The queue's fake millisecond clock. + public long Now; public readonly WorldObjectCache Cache; public World() @@ -67,6 +75,7 @@ internal static class GiveTests Set("_playerId", Player); Set("_initialized", true); Set("_loginComplete", true); + Set("_giveClock", (Func)(() => Now)); foreach (uint id in new[] { Npc, Mote1, Mote2, Mote3, WornMote, Other }) Cache.OnCreateObject(id); Cache.Tick(); } @@ -82,6 +91,36 @@ internal static class GiveTests for (int i = 0; i < 20; i++) Call("DrainGiveQueue"); } + /// 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); + + /// Adds a carried stack the cache knows about. + public void AddStack(uint id, string name, int count) + { + FakeHost.Names[id] = name; + FakeHost.Containers[id] = Player; + FakeHost.ItemTypes[id] = 0x80; + FakeHost.Ints[(id, 12)] = count; // StackCount + Cache.OnCreateObject(id); + Cache.Tick(); + } + + /// An NPC with a Give emote: each give takes ONE item from the stack (ACE: acceptAll ? amount : 1). + public void NpcTakesOnePerGive() + { + FakeHost.GiveHandler = (item, target, amount) => + { + if (!FakeHost.Ints.TryGetValue((item, 12), out int n)) { FakeHost.Containers[item] = target; return; } // a single item goes whole + if (n <= 0) return; + FakeHost.Ints[(item, 12)] = n - 1; + if (n - 1 <= 0) FakeHost.Containers[item] = target; + }; + } + + public bool ChatHas(string part) => FakeHost.Chat.Any(c => c.Contains(part, StringComparison.Ordinal)); + public uint[] GivenItems => FakeHost.Gives.Select(g => g.Item).ToArray(); } @@ -135,4 +174,122 @@ internal static class GiveTests Check.Eq(FakeHost.Gives.Count, 3, "then the other two, each after the last landed"); Check.Eq(FakeHost.Gives.Select(g => g.Item).Distinct().Count(), 3, "no item sent twice"); } + + private const uint Carapace = 0x80281301; + + // 2026-10-12: Olthoi Carapace stack of 100 to a Collector NPC: the server takes ONE per give, the + // stack stays in the pack, and the queue used to wait 3 s, re-send once and skip. + private static void NpcStackOneAtATime() + { + var w = new World(); + w.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + w.NpcTakesOnePerGive(); + w.Call("EnqueueGive", Carapace, Npc, 5); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "the first give goes out"); + for (int expected = 2; expected <= 5; expected++) + { + w.Tick(); // the stack shrank: the same item goes again, in this very tick + Check.Eq(FakeHost.Gives.Count, expected, $"give #{expected} sent on the tick that saw the shrink"); + } + Check.True(FakeHost.Gives.All(g => g.Item == Carapace && g.Target == Npc), "always the same stack, to the NPC"); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 5, "the stack is gone: nothing more is sent"); + Check.False(w.ChatHas("didn't take"), "never reported as not taken"); + } + + private static void NextGiveSameTick() + { + var w = new World(); + w.S.GiveQueueIntervalMs = 150; // a saved old default: only a minimum gap between SENDS + w.Run("/ub give Mana Mote to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 1, "one give out, the server not yet heard from at t=0"); + // The first landed at once in the fake. Less than the gap since the send: the next must wait. + w.Tick(100); + Check.Eq(FakeHost.Gives.Count, 1, "inside the minimum gap the next send waits"); + // A round trip longer than the gap: answer observed and the next give leaves in the same tick. + w.Tick(60); + Check.Eq(FakeHost.Gives.Count, 2, "answer seen and the next give sent on one tick"); + w.Tick(200); + Check.Eq(FakeHost.Gives.Count, 3, "and again for the third"); + } + + private static void BusyResendsUncapped() + { + var w = new World(); + FakeHost.GiveLands = false; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Tick(); + for (int busy = 1; busy <= 6; busy++) + { + int before = FakeHost.Gives.Count; + w.Chat("You're too busy!"); + w.Tick(100); + Check.Eq(FakeHost.Gives.Count, before, $"busy #{busy}: not re-sent before the short delay"); + w.Tick(300); + Check.Eq(FakeHost.Gives.Count, before + 1, $"busy #{busy}: re-sent after it"); + } + Check.False(w.ChatHas("didn't take"), "no cap: never skipped"); + FakeHost.GiveLands = true; + FakeHost.Containers[Mote1] = Npc; // finally taken + w.Tick(100); + Check.True(w.ChatHas("1 item(s) given"), "then it lands and counts"); + Check.Eq(FakeHost.Gives.Count, 7, "seven sends: the first plus six re-sends"); + } + + private static void PermanentSkips() + { + var w = new World(); + FakeHost.GiveLands = false; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Call("EnqueueGive", Mote2, Npc, 1); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 1, "first stack out"); + w.Chat("Town Crier is not accepting gifts right now."); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "refused for good: the next stack is sent on that same tick"); + Check.Eq(FakeHost.Gives[1].Item, Mote2, "the second stack, not a retry of the first"); + FakeHost.Containers[Mote2] = Npc; + w.Tick(); + Check.True(w.ChatHas("1 item(s) given, 1 stack(s) skipped"), "summary: one given, one skipped with its reason"); + } + + private static void ItemNotFoundAfterResendCounts() + { + var w = new World(); + FakeHost.GiveLands = false; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Tick(); + w.Tick(3001); // no answer: sent once more + Check.Eq(FakeHost.Gives.Count, 2, "re-sent after the confirm time"); + w.Chat("Item not found!"); + w.Tick(); + Check.Eq(FakeHost.Gives.Count, 2, "no third send"); + Check.True(w.ChatHas("1 item(s) given, 0 stack(s) skipped"), "the earlier send landed: counted as given, not skipped"); + } + + private static void SummaryCountsItems() + { + var w = new World(); + w.AddStack(Carapace, "Olthoi Slayer Carapace", 5); + w.NpcTakesOnePerGive(); + w.Call("EnqueueGive", Carapace, Npc, 5); + w.Call("EnqueueGive", Mote1, Npc, 1); + for (int i = 0; i < 12; i++) w.Tick(50); + Check.True(w.ChatHas("Give queue complete: 6 item(s) given, 0 stack(s) skipped"), "5 carapaces + 1 mote = 6 items from 2 stacks"); + } + + private static void NoAnswerSkips() + { + var w = new World(); + FakeHost.GiveLands = false; + w.Call("EnqueueGive", Mote1, Npc, 1); + w.Tick(); + w.Tick(3001); + w.Tick(3001); + Check.Eq(FakeHost.Gives.Count, 2, "two tries, then it gives up"); + Check.True(w.ChatHas("didn't take"), "and says so"); + Check.True(w.ChatHas("1 stack(s) skipped"), "the summary counts it as skipped"); + } } +