Snapshot for release 2026.10.29.3 (internal f81a090)

This commit is contained in:
Tom Bohar 2026-10-29 15:22:43 -04:00
commit aa8bf65897
27 changed files with 1821 additions and 61 deletions

View file

@ -57,7 +57,7 @@ internal static unsafe class ActivityInterface
/// <summary>The bits from RynthAi's state (pure, so the host tests check the mapping).</summary> /// <summary>The bits from RynthAi's state (pure, so the host tests check the mapping).</summary>
internal static RynthAiActivity Compose(BotActivity activity, bool macroRunning, bool corpseInHand, bool salvageBusy, internal static RynthAiActivity Compose(BotActivity activity, bool macroRunning, bool corpseInHand, bool salvageBusy,
bool serverWait, bool crafting, bool autoCram) bool serverWait, bool crafting, bool autoCram, bool pacedWait = false)
{ {
RynthAiActivity f = RynthAiActivity.None; RynthAiActivity f = RynthAiActivity.None;
if (macroRunning) f |= RynthAiActivity.MacroRunning; if (macroRunning) f |= RynthAiActivity.MacroRunning;
@ -74,6 +74,7 @@ internal static unsafe class ActivityInterface
if (serverWait) f |= RynthAiActivity.ServerAction; if (serverWait) f |= RynthAiActivity.ServerAction;
if (crafting) f |= RynthAiActivity.Crafting; if (crafting) f |= RynthAiActivity.Crafting;
if (autoCram) f |= RynthAiActivity.AutoCram; if (autoCram) f |= RynthAiActivity.AutoCram;
if (pacedWait) f |= RynthAiActivity.PacedAction;
return f; return f;
} }
} }
@ -85,7 +86,8 @@ public sealed partial class RynthAiPlugin
{ {
var st = _dashboard?.Settings; var st = _dashboard?.Settings;
if (st == null || !_loginComplete) return null; if (st == null || !_loginComplete) return null;
bool serverWait = _busyCount > 0 || (ActionPacer.Enabled && ActionPacer.Current(Host) != null); bool pacedWait = ActionPacer.Enabled && ActionPacer.Current(Host) != null;
bool serverWait = _busyCount > 0 || pacedWait;
return ActivityInterface.Compose( return ActivityInterface.Compose(
st.IsMacroRunning ? _activity : BotActivity.Idle, st.IsMacroRunning ? _activity : BotActivity.Idle,
st.IsMacroRunning, st.IsMacroRunning,
@ -93,6 +95,7 @@ public sealed partial class RynthAiPlugin
salvageBusy: _salvageManager?.IsBusy == true, salvageBusy: _salvageManager?.IsBusy == true,
serverWait: serverWait, serverWait: serverWait,
crafting: _missileCraftingManager?.IsCrafting == true, crafting: _missileCraftingManager?.IsCrafting == true,
autoCram: st.EnableAutocram); autoCram: st.EnableAutocram,
pacedWait: pacedWait);
} }
} }

View file

@ -400,6 +400,38 @@ public partial class BuffManager : IDisposable
return Math.Min(reserve, cost + (max - cost) / 2); return Math.Min(reserve, cost + (max - cost) / 2);
} }
/// <summary>Logged once per stretch under Get Mana At: buffing goes on because nothing can refill
/// mana (CheckBuffs' mana floor).</summary>
private bool _manaFloorNoRefillLogged;
/// <summary>Heals the mana floor keeps mana for when nothing can refill it.</summary>
internal const int ManaFloorHeals = 2;
/// <summary>
/// The mana the Get Mana At floor keeps when nothing can refill it: ManaFloorHeals casts of the
/// Heal Self vitals would cast now (0 when none is known or Life Magic isn't usable).
/// </summary>
internal int ManaFloorHealReserve()
{
int heal = IsSkillUsable(AcSkillType.LifeMagic)
? _spellManager.GetDynamicSelfBuffId("Heal Self", AcSkillType.LifeMagic, LevelLacksComponents)
: 0;
int cost = heal != 0 ? SpellManaCost(heal) : 0;
return cost > 0 ? ManaFloorHeals * cost : 0;
}
/// <summary>True when no mana potion could be drunk at all (Use Potions off, or none listed or
/// in the pack); false while one exists but waits (drunk under 2.5 s ago, a cast holds it).</summary>
private bool NoManaPotionToDrink()
{
if (!_settings.UsePotions || _worldObjectCache == null) return true;
if (HasListedPotion("ManaPotion")) return false;
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false))
if (!IsKitName(wo.Name) && string.Equals(RynthCore.Plugin.RynthAi.LegacyUi.LegacyWeaponsUi.PotionType(wo), "ManaPotion", StringComparison.OrdinalIgnoreCase))
return false;
return true;
}
/// <summary>Combat fights with magic (CombatManager's chosen weapon is a wand; before it chose, /// <summary>Combat fights with magic (CombatManager's chosen weapon is a wand; before it chose,
/// the stance). A melee character's attacks don't spend mana, so the reserve doesn't hold them.</summary> /// the stance). A melee character's attacks don't spend mana, so the reserve doesn't hold them.</summary>
private bool FightsWithMagic() => _combatManager?.FightsWithMagic ?? CurrentCombatMode == CombatMode.Magic; private bool FightsWithMagic() => _combatManager?.FightsWithMagic ?? CurrentCombatMode == CombatMode.Magic;
@ -1717,30 +1749,71 @@ public partial class BuffManager : IDisposable
// Mana under Get Mana At left buffing waiting on natural regen - one buff every 1-2 // Mana under Get Mana At left buffing waiting on natural regen - one buff every 1-2
// minutes (tester, 10-01: 85 minutes of "buffing waits", Stamina to Mana never cast). // minutes (tester, 10-01: 85 minutes of "buffing waits", Stamina to Mana never cast).
// A low stamina is topped up first (kit, Revitalize, potion) so Stamina to Mana can run. // A low stamina is topped up first (kit, Revitalize, potion) so Stamina to Mana can run.
if (_vitals.StaminaPct > StaminaToManaFloorPct() && AttemptVitalCast("Stamina to Mana Self")) // Each source's reason, for the log line below: it used to show only the last one tried
// (the potion's), so a missing Stamina to Mana read as "none in the Items list or the pack".
string s2mWhy, stamWhy = "-", potWhy;
_vitalWhy = "";
if (_vitals.StaminaPct > StaminaToManaFloorPct())
{ {
_isRechargingMana = true; if (AttemptVitalCast("Stamina to Mana Self"))
return; {
_isRechargingMana = true;
return;
}
s2mWhy = Why(_vitalWhy);
} }
if (_vitals.StaminaPct <= 15 && (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self") else s2mWhy = $"stamina {_vitals.StaminaPct}% is under its line ({StaminaToManaFloorPct()}%)";
|| AttemptPotion("StaminaPotion", "Stamina"))) if (_vitals.StaminaPct <= 15)
{ {
_isRechargingStamina = true; _vitalWhy = "";
return; if (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self")
|| AttemptPotion("StaminaPotion", "Stamina"))
{
_isRechargingStamina = true;
return;
}
stamWhy = Why(_vitalWhy);
} }
_vitalWhy = "";
if (AttemptPotion("ManaPotion")) if (AttemptPotion("ManaPotion"))
{ {
_isRechargingMana = true; _isRechargingMana = true;
return; return;
} }
LastBuffSkipReason = $"mana {_vitals.ManaPct}% under Get Mana At {manaFloor}%"; potWhy = Why(_vitalWhy);
if ((RynthClock.Now - _lastManaFloorLogAt).TotalSeconds >= 30)
// Nothing can ever refill it (no Stamina to Mana known, no mana potion to drink): waiting
// only means natural regeneration, so buffing crawled one buff per regen climb. Worse, a
// rebuff raises max mana: the character logged in with full mana (209/207), the first
// buffs took max mana to 536, the same 209 read 39% under Get Mana At 40%, and every buff
// after waited (report R-20261029-103248-ce48, DreamWeave, 2026-10-29: "Buffing seems to
// be getting stuck"). The floor is there to keep mana for healing, so with no refill the
// buffs go on while mana keeps ManaFloorHealReserve after one (BuffWaitsForMana still
// holds any buff mana can't pay for). The same rule as the reserve: "With no Stamina to
// Mana at all nothing refills: the buff goes."
bool canRefill = TopStaminaToManaId() != 0 || !NoManaPotionToDrink();
int keep = ManaFloorHealReserve();
if (!canRefill && _vitals.CurrentMana >= keep + EstimatedManaCost(8))
{ {
_lastManaFloorLogAt = RynthClock.Now; if (!_manaFloorNoRefillLogged)
_host.Log($"[RynthAi] Vitals: buffing waits: mana {_vitals.ManaPct}% is under Get Mana At {manaFloor}%, stamina {_vitals.StaminaPct}%, and nothing refilled it (Stamina to Mana / stamina / potion: {Why(_vitalWhy)})"); {
_manaFloorNoRefillLogged = true;
_host.Log($"[RynthAi] Vitals: mana {_vitals.CurrentMana}/{_vitals.MaxMana} ({_vitals.ManaPct}%) is under Get Mana At {manaFloor}%, but nothing can refill it (Stamina to Mana: {s2mWhy}; mana potion: {potWhy}): buffing goes on, keeping {keep} mana for healing.");
}
}
else
{
LastBuffSkipReason = $"mana {_vitals.ManaPct}% under Get Mana At {manaFloor}%";
if ((RynthClock.Now - _lastManaFloorLogAt).TotalSeconds >= 30)
{
_lastManaFloorLogAt = RynthClock.Now;
_host.Log($"[RynthAi] Vitals: buffing waits: mana {_vitals.CurrentMana}/{_vitals.MaxMana} ({_vitals.ManaPct}%) is under Get Mana At {manaFloor}%, stamina {_vitals.StaminaPct}%, and nothing refilled it (Stamina to Mana: {s2mWhy}; stamina: {stamWhy}; mana potion: {potWhy})" +
(canRefill ? "" : $"; keeping {keep} mana for healing"));
}
return;
} }
return;
} }
else _manaFloorNoRefillLogged = false;
// Too-busy backoff gates BUFFING only, and sits after CheckVitals on // Too-busy backoff gates BUFFING only, and sits after CheckVitals on
// purpose: a refused heal is worth retrying hard, a refused buff is not. // purpose: a refused heal is worth retrying hard, a refused buff is not.

View file

@ -7245,6 +7245,13 @@ public partial class CombatManager : IDisposable
// table went to Slash (listed first), so a fire wand cast Blades (2026-09-30). // table went to Slash (listed first), so a fire wand cast Blades (2026-09-30).
if (target == null) return WeaponPlanner.FallbackOrder[0]; if (target == null) return WeaponPlanner.FallbackOrder[0];
var plan = PlanFor(target, rule); var plan = PlanFor(target, rule);
// The plan's wand isn't the one in hand (the swap was held: the target is nearly dead, a
// swap is resting, the off hand blocks it): the wand in hand casts its own element (owner's
// rule, 2026-09-30: "the wand should always cast its element"). The plan's element went
// out through the other wand: Acid Blasts from a Frost Sceptre while "not swapping Frost
// Sceptre for Acid Staff yet (target at 23% health)" (R-20261029-125901-e22d, Conquest).
if (HeldWandElement(plan, rule) is string held)
return held;
if (_autoElemDiagCount < 20) if (_autoElemDiagCount < 20)
{ {
_autoElemDiagCount++; _autoElemDiagCount++;
@ -7258,6 +7265,32 @@ public partial class CombatManager : IDisposable
/// This character can cast <paramref name="element"/> itself (FindBestShapedSpell falls /// This character can cast <paramref name="element"/> itself (FindBestShapedSpell falls
/// back to Fire for anything it can't, so a non-zero result alone doesn't say that). /// back to Fire for anything it can't, so a non-zero result alone doesn't say that).
/// </summary> /// </summary>
// Logged once per (plan wand, wand in hand, element): the cast follows the wand in hand.
private (int Plan, int Hand, string Elem) _heldWandElemLogged;
/// <summary>
/// The element of the wand in hand when it isn't the plan's weapon and the character can cast
/// that element (null = cast the plan's element). Only a wand: a melee or missile weapon in
/// hand doesn't choose the spell. A wand whose element isn't known yet, or isn't castable
/// (Nether without Void), leaves the plan's element.
/// </summary>
private string? HeldWandElement(WeaponPlan plan, MonsterRule? rule)
{
int hand = InHandWeaponId();
if (hand == 0 || plan.WeaponId == 0 || hand == plan.WeaponId) return null;
if (_worldFilter[hand] is not WorldObject wo || !IsWandObject(wo)) return null;
var c = ListedCandidates().FirstOrDefault(x => x.Id == hand);
string elem = c?.Element ?? WeaponElements.Normalize(ElementTracker.Read(hand, wo.Name).Element);
if (elem.Length == 0 || elem.Equals(plan.Element, StringComparison.OrdinalIgnoreCase) || !CanCastElement(elem, rule)) return null;
var key = (plan.WeaponId, hand, elem);
if (key != _heldWandElemLogged)
{
_heldWandElemLogged = key;
_host.Log($"[CombatCast] the plan's wand 0x{(uint)plan.WeaponId:X8} '{WeaponName(plan.WeaponId)}' ({plan.Element}) isn't in hand: casting {elem}, the element of 0x{(uint)hand:X8} '{wo.Name}' in hand");
}
return elem;
}
private bool CanCastElement(string element, MonsterRule? rule) private bool CanCastElement(string element, MonsterRule? rule)
{ {
if (CanCastOverride != null) return CanCastOverride(element); if (CanCastOverride != null) return CanCastOverride(element);

View file

@ -121,6 +121,24 @@ public sealed partial class RynthAiPlugin
private bool _currentLootItemPipelined; // sent while the last pickup's Return played (ACE queues it) private bool _currentLootItemPipelined; // sent while the last pickup's Return played (ACE queues it)
private int _currentLootItemErrSeqAtSend; // TryGetLastWeenieError seq at the send (0 = unknown) private int _currentLootItemErrSeqAtSend; // TryGetLastWeenieError seq at the send (0 = unknown)
private int _currentLootItemFreeRetries; // resends after a too-busy answer (not counted as attempts) private int _currentLootItemFreeRetries; // resends after a too-busy answer (not counted as attempts)
// 2026-10-29 (R-20261029-122319-321f): what the server said to the last send, and what the
// tries into the current destination came to (TickPendingCorpsePickup, JudgeLootDest).
private bool _currentLootItemAwaitingAnswer; // the last send has had no answer yet
private long _currentLootItemRefusedAt; // when a refusal of the last send was first seen (0 = none)
private uint _currentLootItemRefusalError;
private bool _currentLootItemRefusalBusy; // "too busy": before its pickup could run, not the pack's answer
private int _currentLootItemDestRefusals; // tries into _currentLootItemDest refused after the pickup ran
private int _currentLootItemDestTimeouts; // tries into it with no answer in PickupAnswerWaitMs
private bool _currentLootItemTimedOut; // a send of this item went unanswered: a later answer may be to it
private readonly List<int> _currentLootItemDestsTried = new();
private long _moveAwaitTickAt; // CorpseNowMs of the previous answer-wait call
// How long the server took to answer recent pickups (confirmations and refusals after the
// pickup ran): the answer wait is sized from the slowest of them.
private readonly long[] _pickupAnswerLatencies = new long[8];
private int _pickupAnswerLatencyCount, _pickupAnswerLatencyNext;
// Items given up (or dropped by a reset) with a move still possibly at the server: one that
// lands in a pack afterwards un-marks that pack (WatchLateLandings).
private readonly Dictionary<int, (long Until, long SentAt)> _lateLandings = new();
// The last answered pickup, until the character has finished its "Return" (stood up again). // The last answered pickup, until the character has finished its "Return" (stood up again).
// The corpse/chest is closed only after this (2026-10-07), and the next move may go out while // The corpse/chest is closed only after this (2026-10-07), and the next move may go out while
// it plays: ACE queues a move that arrives during the Return as its NextPickup. // it plays: ACE queues a move that arrives during the Return as its NextPickup.
@ -597,6 +615,7 @@ public sealed partial class RynthAiPlugin
return; return;
SyncCorpseContainerState(); SyncCorpseContainerState();
WatchLateLandings(CorpseNowMs);
TickDeferredClose(settings); TickDeferredClose(settings);
TakeLootThisRequest(settings); // /ra lootthis (RynthAiPlugin.VTankHotkeys.cs) TakeLootThisRequest(settings); // /ra lootthis (RynthAiPlugin.VTankHotkeys.cs)
@ -1729,6 +1748,7 @@ public sealed partial class RynthAiPlugin
_currentLootItemPipelined = pipelined; _currentLootItemPipelined = pipelined;
_currentLootItemStackable = stackable; _currentLootItemStackable = stackable;
_currentLootItemErrSeqAtSend = errSeqAtSend; _currentLootItemErrSeqAtSend = errSeqAtSend;
NoteLootMoveSent();
_currentLootItemFreeRetries = 0; _currentLootItemFreeRetries = 0;
_currentLootItemActionLabel = matchActionLabel; _currentLootItemActionLabel = matchActionLabel;
_currentLootItemName = matchItemName; _currentLootItemName = matchItemName;
@ -1865,6 +1885,157 @@ public sealed partial class RynthAiPlugin
catch { return false; } catch { return false; }
} }
// ── Waiting for the server's answer to a move (2026-10-29, R-20261029-122319-321f) ──
// Conquest, RynthAi 2026.10.29.1, "if max loot attempts are reached it locks up on looting
// other items": a pack move was retried every ~0.5 s once the character stood still, and
// after 3 tries (~1.6 s) the pack counted as full for 5 min. That server took 1.5-2.7 s to
// answer a pickup ("pickup confirmed for 0x8023F05A; merged into a stack in the pack (1657
// ms after the send)" came after attempt 3 had gone out), so moves were judged failed while
// the server was still on them. A resend while one is out does nothing useful either: the
// client drops it (its one pending inventory request, "You can only move or use one item at
// a time") or ACE turns it away as too busy. Good side packs were marked full one after
// another, each item burning two of them, until no pack was left. Now a send is followed by
// another only once it is answered (the item lands, or the server refuses it) or after
// PickupAnswerWaitMs with no answer, and only the server's refusals mark a pack full for
// longer than the item (PackRefusals).
/// <summary>The least time a move is given to be answered before it counts as unanswered.</summary>
internal const long PickupAnswerWaitMinMs = 4000;
/// <summary>The most: a slow server's measured answers raise the wait up to this.</summary>
internal const long PickupAnswerWaitMaxMs = 8000;
/// <summary>Added to the slowest recent answer.</summary>
internal const long PickupAnswerWaitMarginMs = 1500;
/// <summary>A pickup given up on is watched this long for a late landing.</summary>
internal const long LateLandingWatchMs = 15_000;
/// <summary>How long a send waits for its answer: the slowest of the last 8 answers plus a margin, 4-8 s.</summary>
internal long PickupAnswerWaitMs()
{
long slowest = 0;
for (int i = 0; i < _pickupAnswerLatencyCount; i++)
slowest = Math.Max(slowest, _pickupAnswerLatencies[i]);
return Math.Clamp(slowest + PickupAnswerWaitMarginMs, PickupAnswerWaitMinMs, PickupAnswerWaitMaxMs);
}
private void NotePickupAnswerLatency(long ms)
{
if (ms <= 0) return;
_pickupAnswerLatencies[_pickupAnswerLatencyNext] = ms;
_pickupAnswerLatencyNext = (_pickupAnswerLatencyNext + 1) % _pickupAnswerLatencies.Length;
if (_pickupAnswerLatencyCount < _pickupAnswerLatencies.Length) _pickupAnswerLatencyCount++;
}
/// <summary>A move of the current item went out: its answer is awaited afresh.</summary>
private void NoteLootMoveSent()
{
_currentLootItemAwaitingAnswer = true;
_currentLootItemRefusedAt = 0;
_currentLootItemRefusalError = 0;
_currentLootItemRefusalBusy = false;
}
/// <summary>
/// Notes the first refusal of the last send, every tick (so its time is known), and whether
/// it was "too busy" or the server's own answer after it ran the pickup. The "error 0x0" of
/// the report is a real refusal: the engine keeps only the last refusal message, ACE follows
/// a YoureTooBusy (0x1D) with InventoryServerSaveFailed for the item and no error code, and
/// a full pack answers with the same InventoryServerSaveFailed, no code ("Unable to put X
/// into container", Player.DoHandleActionPutItemInContainer). The old code took every one
/// for "too busy" and resent it free: 'Brier Wasp's Treasure Map' went into the full main
/// pack 6 times over 18 s. The time tells them apart: ACE turns a busy move away when it
/// arrives, and refuses for room only after the pickup motion (longer than PickupAnswerMinMs).
/// </summary>
private void PollCurrentPickupRefusal(long now)
{
if (_currentLootItemRefusedAt != 0 || !CurrentPickupRefused(out uint err))
return;
long after = now - _currentLootItemMoveRequestedAt;
_currentLootItemRefusedAt = now;
_currentLootItemRefusalError = err;
_currentLootItemRefusalBusy = err == WeenieErrorYoureTooBusy || after < PickupAnswerMinMs;
if (!_currentLootItemRefusalBusy && !_currentLootItemTimedOut)
NotePickupAnswerLatency(after);
}
/// <summary>
/// While a move waits for its answer the corpse's timeout clock does not run (as for the
/// cast-answer hold, PauseCorpseClockWhileHeld): three unanswered tries take longer than
/// the 12 s corpse timeout, which is meant for an idle corpse.
/// </summary>
private void PauseCorpseClockWhileMoveAwaits(long now)
{
long last = _moveAwaitTickAt;
_moveAwaitTickAt = now;
if (last == 0 || _targetCorpseId == 0 || _corpseTargetSince == 0 || _corpseHoldFrozenAge >= 0)
return;
long gap = now - last;
if (gap > 0 && gap <= PickupHoldMaxGapMs)
_corpseTargetSince += gap;
}
/// <summary>
/// What the tries into the current destination say about it: full (<paramref name="confirmed"/>:
/// the server refused at least two after running the pickup), doubtful (at least two failed,
/// some only for want of an answer: the item tries another pack, the mark is the item's
/// alone), or nothing (the server was only too busy: no pack is to blame).
/// </summary>
private bool JudgeLootDest(out bool confirmed)
{
confirmed = _currentLootItemDestRefusals >= 2;
return confirmed || _currentLootItemDestRefusals + _currentLootItemDestTimeouts >= 2;
}
private string LootPackName(int packId) =>
packId == unchecked((int)_playerId) ? "the main pack" : $"pack 0x{(uint)packId:X8}";
/// <summary>A pack other than the ones left out could take the item (the client's own counts).</summary>
private bool HasOtherLootDestination()
{
if (_objectCache == null || _playerId == 0) return false;
long now = CorpseNowMs;
return WorldObjectCache.FindLootDestination(_objectCache.GetDirectInventory(forceRefresh: false),
unchecked((int)_playerId), Host, id => _packRefusals.IsRefused(id, now)) != 0;
}
/// <summary>The current item is done without its landing seen: watch for one that comes late.</summary>
private void WatchLateLanding(long now)
{
if (_currentLootItemId == 0 || _currentLootItemDestsTried.Count == 0)
return;
_lateLandings[_currentLootItemId] = (now + LateLandingWatchMs, _currentLootItemMoveRequestedAt);
}
/// <summary>
/// An item given up on that lands in a pack after all: that pack had room, so it is no longer
/// treated as full (it may have been marked while the server was still on the item).
/// </summary>
private void WatchLateLandings(long now)
{
if (_lateLandings.Count == 0 || _objectCache == null)
return;
List<int>? done = null;
foreach (var kv in _lateLandings)
{
WorldObject? wo = _objectCache[kv.Key];
int container = wo?.Container ?? 0;
if (wo != null && InPlayerInventory(container))
{
bool wasMarked = _packRefusals.IsRefused(container, now);
_packRefusals.Accepted(container);
LootDiag($"[RynthAi] {LootTag}: 0x{(uint)kv.Key:X8} landed in {LootPackName(container)} {now - kv.Value.SentAt} ms after its last send, after it was given up" +
(wasMarked ? $"; {LootPackName(container)} has room after all and is no longer treated as full." : "."));
(done ??= new()).Add(kv.Key);
}
else if (now >= kv.Value.Until)
(done ??= new()).Add(kv.Key);
}
if (done != null)
foreach (int id in done) _lateLandings.Remove(id);
}
/// <summary>A stack when its move is sent: it may merge into a stack in the pack and be deleted.</summary> /// <summary>A stack when its move is sent: it may merge into a stack in the pack and be deleted.</summary>
private bool IsStackAtSend(int itemId) private bool IsStackAtSend(int itemId)
{ {
@ -2033,14 +2204,18 @@ public sealed partial class RynthAiPlugin
: mergedAway : mergedAway
? "merged into a stack in the pack" ? "merged into a stack in the pack"
: $"off the corpse, not seen in a pack (container=0x{(uint)currentContainer:X8})", : $"off the corpse, not seen in a pack (container=0x{(uint)currentContainer:X8})",
answered); answered,
inPack ? currentContainer : 0);
return; return;
} }
// The server turned the move away ("You're too busy": it arrived during the last // The server turned the move away. "Too busy" (it arrived during the last pickup's
// pickup's bend-down, not its Return). Resend it as soon as the character is still, // bend-down, not its Return): resend it as soon as the character is still, without
// without counting it as one of the item's 3 tries. // counting it as one of the item's 3 tries. Refused after the pickup ran (no room): one
bool refused = CurrentPickupRefused(out uint refusal); // of the tries, and the evidence a pack is full (PollCurrentPickupRefusal).
PollCurrentPickupRefusal(now);
bool refused = _currentLootItemRefusedAt != 0;
bool busyRefusal = refused && _currentLootItemRefusalBusy;
// Item still on corpse — wait before retrying the UseObject. The window counts from // Item still on corpse — wait before retrying the UseObject. The window counts from
// when the character is still: while a pickup animation plays the engine holds the // when the character is still: while a pickup animation plays the engine holds the
@ -2050,35 +2225,81 @@ public sealed partial class RynthAiPlugin
if (PickupAnimating(now)) if (PickupAnimating(now))
{ {
_currentLootItemStillSince = 0; _currentLootItemStillSince = 0;
if (_currentLootItemAwaitingAnswer) PauseCorpseClockWhileMoveAwaits(now);
return; return;
} }
if (_currentLootItemStillSince == 0) if (_currentLootItemStillSince == 0)
_currentLootItemStillSince = now; _currentLootItemStillSince = now;
bool freeRetry = refused && _currentLootItemFreeRetries < PickupFreeRetries; bool freeRetry = busyRefusal && _currentLootItemFreeRetries < PickupFreeRetries;
// No answer yet: no resend before PickupAnswerWaitMs (2026-10-29, R-20261029-122319-321f).
// The Loot Retry Timeout alone (0.5-1 s) is shorter than a slow server's answer (1.5-2.7 s
// on Conquest), and a resend while the move is out is dropped by the client or refused.
long answerWaitMs = PickupAnswerWaitMs();
long sinceSend = now - _currentLootItemMoveRequestedAt;
if (_currentLootItemAwaitingAnswer && !refused && sinceSend < answerWaitMs)
{
PauseCorpseClockWhileMoveAwaits(now);
return;
}
long verifyWindowMs = Math.Max(150, settings.LootRetryTimeoutMs); long verifyWindowMs = Math.Max(150, settings.LootRetryTimeoutMs);
long windowStart = Math.Max(_currentLootItemMoveRequestedAt, _currentLootItemStillSince); long windowStart = Math.Max(_currentLootItemMoveRequestedAt, _currentLootItemStillSince);
if (!freeRetry && now - windowStart < verifyWindowMs) if (!freeRetry && now - windowStart < verifyWindowMs)
return; return;
// The last send failed: what it came to, once per send (a free resend's "too busy" is
// not one of the tries). Refused after the pickup ran counts against the pack; no answer
// at all only half (JudgeLootDest).
string lastTry = "";
if (_currentLootItemAwaitingAnswer && !freeRetry)
{
_currentLootItemAwaitingAnswer = false;
long answerMs = refused ? _currentLootItemRefusedAt - _currentLootItemMoveRequestedAt : sinceSend;
if (!refused)
{
_currentLootItemDestTimeouts++;
_currentLootItemTimedOut = true;
lastTry = $"no answer in {answerMs} ms";
}
else if (!busyRefusal)
{
_currentLootItemDestRefusals++;
lastTry = $"refused {answerMs} ms after the send, after its pickup ran (error 0x{_currentLootItemRefusalError:X})";
}
else
lastTry = $"too busy, {answerMs} ms after the send";
}
if (!freeRetry && _currentLootItemMoveAttempts >= 3) if (!freeRetry && _currentLootItemMoveAttempts >= 3)
{ {
// None of the tries landed: the pack they went to is likely full (its contents // None of the tries landed. When the server refused them after running the pickup,
// unknown to the client). Leave that pack out for a while and give the item one // the pack they went to is full (its contents unknown to the client): leave it out
// more round into the next one; with no other pack, the item is left as before. // for a while and give the item one more round into the next one; with no other
if (_currentLootItemDest != 0) // pack, the corpse is left with the pack-full message. When they only went unanswered
// the pack is not known to be full: the item may try another pack, but the mark is
// dropped with the item, so the next item and corpse start fresh (R-20261029-122319-321f:
// those quick marks used up every pack). When the server was only too busy, no pack is
// to blame.
int dest = _currentLootItemDest;
if (dest != 0 && JudgeLootDest(out bool confirmed))
{ {
_packRefusals.Refuse(_currentLootItemDest, now); _packRefusals.Refuse(dest, now, confirmed);
if (!_currentLootItemPackRetried) if (!_currentLootItemPackRetried && (confirmed || HasOtherLootDestination()))
{ {
LootDiag($"[RynthAi] {LootTag}: {(_currentLootItemDest == _playerId ? "the main pack" : $"pack 0x{(uint)_currentLootItemDest:X8}")} took none of {_currentLootItemMoveAttempts} tries for 0x{(uint)_currentLootItemId:X8}; treating it as full for {RynthCore.Plugin.RynthAi.Loot.PackRefusals.HoldMs / 60_000} min and trying another pack."); LootDiag(confirmed
? $"[RynthAi] {LootTag}: {LootPackName(dest)} took none of {_currentLootItemMoveAttempts} tries for 0x{(uint)_currentLootItemId:X8} (the server refused {_currentLootItemDestRefusals} after the pickup ran); treating it as full for {RynthCore.Plugin.RynthAi.Loot.PackRefusals.HoldMs / 60_000} min and trying another pack."
: $"[RynthAi] {LootTag}: {LootPackName(dest)} took none of {_currentLootItemMoveAttempts} tries for 0x{(uint)_currentLootItemId:X8} ({_currentLootItemDestTimeouts} unanswered in {answerWaitMs} ms, {_currentLootItemDestRefusals} refused); trying another pack for this item only (not known to be full).");
_currentLootItemPackRetried = true; _currentLootItemPackRetried = true;
_currentLootItemMoveAttempts = 0; _currentLootItemMoveAttempts = 0;
_currentLootItemDestRefusals = 0;
_currentLootItemDestTimeouts = 0;
_currentLootItemStillSince = 0; _currentLootItemStillSince = 0;
_lastLootActionAt = now; _lastLootActionAt = now;
return; return;
} }
} }
LootDiag($"[RynthAi] {LootTag}: pickup failed for 0x{(uint)_currentLootItemId:X8}; container remained 0x{(uint)_openedContainerId:X8} after {_currentLootItemMoveAttempts} attempt(s)."); LootDiag($"[RynthAi] {LootTag}: pickup failed for 0x{(uint)_currentLootItemId:X8}; container remained 0x{(uint)_openedContainerId:X8} after {_currentLootItemMoveAttempts} attempt(s)" +
(lastTry.Length > 0 ? $" (last: {lastTry})." : "."));
_processedCorpseItems.Add(_currentLootItemId); _processedCorpseItems.Add(_currentLootItemId);
ResetCurrentLootItem(); ResetCurrentLootItem();
_lastLootActionAt = now; _lastLootActionAt = now;
@ -2093,6 +2314,8 @@ public sealed partial class RynthAiPlugin
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)_currentLootItemId)); RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)_currentLootItemId));
Host.SelectItem(unchecked((uint)_currentLootItemId)); Host.SelectItem(unchecked((uint)_currentLootItemId));
int errSeqAtSend = LastWeenieErrorSeq(); int errSeqAtSend = LastWeenieErrorSeq();
long refusedAfter = refused ? _currentLootItemRefusedAt - _currentLootItemMoveRequestedAt : 0;
uint refusal = _currentLootItemRefusalError;
LootPickupResult retry = SendLootPickup(_currentLootItemId, _currentLootItemName, _openedContainerId); LootPickupResult retry = SendLootPickup(_currentLootItemId, _currentLootItemName, _openedContainerId);
if (retry == LootPickupResult.NoRoom || retry == LootPickupResult.Refused) if (retry == LootPickupResult.NoRoom || retry == LootPickupResult.Refused)
return; // SendLootPickup finished the item / corpse return; // SendLootPickup finished the item / corpse
@ -2103,12 +2326,14 @@ public sealed partial class RynthAiPlugin
_currentLootItemMoveAttempts++; _currentLootItemMoveAttempts++;
_currentLootItemErrSeqAtSend = errSeqAtSend; _currentLootItemErrSeqAtSend = errSeqAtSend;
_currentLootItemMoveRequestedAt = now; _currentLootItemMoveRequestedAt = now;
if (retried) NoteLootMoveSent();
_currentLootItemStillSince = 0; _currentLootItemStillSince = 0;
_currentLootItemSawAnim = false; _currentLootItemSawAnim = false;
_lastLootActionAt = now; _lastLootActionAt = now;
LootDiag(freeRetry LootDiag(freeRetry
? $"[RynthAi] {LootTag}: the server refused 0x{(uint)_currentLootItemId:X8} (error 0x{refusal:X}); sending it again now the character is still." ? $"[RynthAi] {LootTag}: the server refused 0x{(uint)_currentLootItemId:X8} as too busy ({refusedAfter} ms after the send, before its pickup ran; error 0x{refusal:X}); sending it again now the character is still."
: $"[RynthAi] {LootTag}: retrying use for 0x{(uint)_currentLootItemId:X8} attempt {_currentLootItemMoveAttempts}."); : $"[RynthAi] {LootTag}: retrying use for 0x{(uint)_currentLootItemId:X8} attempt {_currentLootItemMoveAttempts}" +
(lastTry.Length > 0 ? $" (last: {lastTry})." : "."));
if (!retried && _currentLootItemMoveAttempts >= 3) if (!retried && _currentLootItemMoveAttempts >= 3)
{ {
@ -2149,7 +2374,18 @@ public sealed partial class RynthAiPlugin
? SendOwnCorpsePickup(itemId, out dest) ? SendOwnCorpsePickup(itemId, out dest)
: LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out dest, : LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out dest,
id => _packRefusals.IsRefused(id, CorpseNowMs)); id => _packRefusals.IsRefused(id, CorpseNowMs));
if (r == LootPickupResult.Moved) _currentLootItemDest = unchecked((int)dest); if (r == LootPickupResult.Moved)
{
int to = unchecked((int)dest);
if (to != _currentLootItemDest)
{
// Another pack: what the tries into the last one came to says nothing about it.
_currentLootItemDestRefusals = 0;
_currentLootItemDestTimeouts = 0;
}
_currentLootItemDest = to;
if (!_currentLootItemDestsTried.Contains(to)) _currentLootItemDestsTried.Add(to);
}
if (ownCorpse && r == LootPickupResult.NoRoom) if (ownCorpse && r == LootPickupResult.NoRoom)
{ {
PauseOwnCorpseNoRoom(corpseId, itemName); PauseOwnCorpseNoRoom(corpseId, itemName);
@ -2182,13 +2418,32 @@ public sealed partial class RynthAiPlugin
/// </summary> /// </summary>
private void ConfirmCurrentLootItemMoved(long now, string reason) => ConfirmCurrentLootItem(now, reason, answered: true); private void ConfirmCurrentLootItemMoved(long now, string reason) => ConfirmCurrentLootItem(now, reason, answered: true);
private void ConfirmCurrentLootItem(long now, string reason, bool answered) /// <param name="landedIn">The pack the item was seen in (0: merged away, or not seen).</param>
private void ConfirmCurrentLootItem(long now, string reason, bool answered, int landedIn = 0)
{ {
if (_currentLootItemId == 0) if (_currentLootItemId == 0)
return; return;
int itemId = _currentLootItemId; int itemId = _currentLootItemId;
if (answered && _currentLootItemDest != 0) _packRefusals.Accepted(_currentLootItemDest); if (answered)
{
// The pack it landed in has room, whatever it was marked (an earlier send may have
// landed after the item moved on to another pack: R-20261029-122319-321f). A stack
// that merged needed no slot, so it clears its destination only when no refusal
// from there said otherwise.
if (landedIn != 0)
{
if (_packRefusals.IsRefused(landedIn, now))
LootDiag($"[RynthAi] {LootTag}: 0x{(uint)itemId:X8} landed in {LootPackName(landedIn)}; it has room after all and is no longer treated as full.");
_packRefusals.Accepted(landedIn);
}
else if (_currentLootItemDest != 0 && _currentLootItemDestRefusals == 0)
_packRefusals.Accepted(_currentLootItemDest);
// Only an answer that is surely to the last send (a lag spike's answer to an earlier,
// timed-out send would stretch the wait for every item after it).
if (!_currentLootItemTimedOut) NotePickupAnswerLatency(now - _currentLootItemMoveRequestedAt);
}
if (answered) _currentLootItemDestsTried.Clear(); // landed: nothing to watch for (ResetCurrentLootItem)
_processedCorpseItems.Add(_currentLootItemId); _processedCorpseItems.Add(_currentLootItemId);
LootDiag($"[RynthAi] {LootTag}: pickup confirmed for 0x{(uint)_currentLootItemId:X8}; {reason}" + LootDiag($"[RynthAi] {LootTag}: pickup confirmed for 0x{(uint)_currentLootItemId:X8}; {reason}" +
$" ({now - _currentLootItemMoveRequestedAt} ms after the send{(_currentLootItemPipelined ? ", queued" : "")})."); $" ({now - _currentLootItemMoveRequestedAt} ms after the send{(_currentLootItemPipelined ? ", queued" : "")}).");
@ -3023,6 +3278,21 @@ public sealed partial class RynthAiPlugin
private void ResetCurrentLootItem() private void ResetCurrentLootItem()
{ {
// An item done without its landing seen (given up, or dropped by a close / reopen /
// stop) may still land: watch for it. Its unanswered-tries pack marks go with it, so
// the next item and corpse start fresh (R-20261029-122319-321f).
long now = CorpseNowMs;
WatchLateLanding(now);
_packRefusals.ClearUnconfirmed();
_currentLootItemAwaitingAnswer = false;
_currentLootItemRefusedAt = 0;
_currentLootItemRefusalError = 0;
_currentLootItemRefusalBusy = false;
_currentLootItemDestRefusals = 0;
_currentLootItemDestTimeouts = 0;
_currentLootItemTimedOut = false;
_currentLootItemDestsTried.Clear();
_moveAwaitTickAt = 0;
_currentLootItemId = 0; _currentLootItemId = 0;
_currentLootItemRequested = false; _currentLootItemRequested = false;
_currentLootItemRequestedAt = 0; _currentLootItemRequestedAt = 0;

View file

@ -9,31 +9,61 @@ namespace RynthCore.Plugin.RynthAi.Loot;
/// time, and every item on every corpse was skipped (Drakkon, 2026-10-15, 62 items in a row). /// time, and every item on every corpse was skipped (Drakkon, 2026-10-15, 62 items in a row).
/// A pack that takes none of an item's tries counts as full for <see cref="HoldMs"/>; the /// A pack that takes none of an item's tries counts as full for <see cref="HoldMs"/>; the
/// destination search skips it, so the next pack is tried. Pure: the caller passes the time. /// destination search skips it, so the next pack is tried. Pure: the caller passes the time.
///
/// 2026-10-29 (R-20261029-122319-321f, Conquest): a mark is CONFIRMED only when the server
/// answered the tries with a refusal after it had run the pickup (ACE's "Unable to put X into
/// container" + InventoryServerSaveFailed). Tries that simply had no answer in time mark the
/// pack UNCONFIRMED: the item tries another pack, but the mark is the item's alone and is
/// dropped when the item is done (<see cref="ClearUnconfirmed"/>). Quick unanswered retries
/// on a slow server had marked one good pack after another full for 5 min, until looting
/// "locked up" with nothing left to put loot into.
/// </summary> /// </summary>
internal sealed class PackRefusals internal sealed class PackRefusals
{ {
/// <summary>How long a refusing pack is left out (time to free some room, or open it).</summary> /// <summary>How long a refusing pack is left out (time to free some room, or open it).</summary>
public const long HoldMs = 5 * 60_000; public const long HoldMs = 5 * 60_000;
private readonly Dictionary<int, long> _until = new(); private readonly Dictionary<int, (long Until, bool Confirmed)> _until = new();
/// <summary>The server took none of the tries into <paramref name="packId"/>.</summary> /// <summary>
public void Refuse(int packId, long nowMs) /// The server took none of the tries into <paramref name="packId"/>. <paramref name="confirmed"/>:
/// it said so (refusals after the pickup ran); false: the tries went unanswered. A confirmed
/// mark is never weakened by a later unconfirmed one.
/// </summary>
public void Refuse(int packId, long nowMs, bool confirmed = true)
{ {
if (packId != 0) _until[packId] = nowMs + HoldMs; if (packId == 0) return;
if (_until.TryGetValue(packId, out var old) && old.Confirmed && !confirmed && nowMs < old.Until)
return;
_until[packId] = (nowMs + HoldMs, confirmed);
} }
/// <summary>True while <paramref name="packId"/> is left out.</summary> /// <summary>True while <paramref name="packId"/> is left out.</summary>
public bool IsRefused(int packId, long nowMs) public bool IsRefused(int packId, long nowMs)
{ {
if (!_until.TryGetValue(packId, out long until)) return false; if (!_until.TryGetValue(packId, out var mark)) return false;
if (nowMs < until) return true; if (nowMs < mark.Until) return true;
_until.Remove(packId); _until.Remove(packId);
return false; return false;
} }
/// <summary>True while <paramref name="packId"/> is left out on the server's own refusals.</summary>
public bool IsConfirmed(int packId, long nowMs) =>
IsRefused(packId, nowMs) && _until.TryGetValue(packId, out var mark) && mark.Confirmed;
/// <summary>An item landed in <paramref name="packId"/>: it has room after all.</summary> /// <summary>An item landed in <paramref name="packId"/>: it has room after all.</summary>
public void Accepted(int packId) => _until.Remove(packId); public void Accepted(int packId) => _until.Remove(packId);
/// <summary>Drops the marks no refusal backed (the item that made them is done).</summary>
public void ClearUnconfirmed()
{
if (_until.Count == 0) return;
List<int>? drop = null;
foreach (var kv in _until)
if (!kv.Value.Confirmed) (drop ??= new()).Add(kv.Key);
if (drop != null)
foreach (int id in drop) _until.Remove(id);
}
public void Clear() => _until.Clear(); public void Clear() => _until.Clear();
} }

View file

@ -18,7 +18,9 @@ public static unsafe class PluginExports
// "RynthAi.Activity" v1 for RynthSort (what the bot is doing, so pack moves stay out of its way), // "RynthAi.Activity" v1 for RynthSort (what the bot is doing, so pack moves stay out of its way),
// "RynthAi.Combat" v1 for RynthLua (a script choosing attack and heal spells, Shared/RynthAiCombatApi.cs), // "RynthAi.Combat" v1 for RynthLua (a script choosing attack and heal spells, Shared/RynthAiCombatApi.cs),
// "RynthAi.Hub" v1 for RynthILT (the Mini Remote hosting its ILT tabs, /myquests, spell names, loot // "RynthAi.Hub" v1 for RynthILT (the Mini Remote hosting its ILT tabs, /myquests, spell names, loot
// matching, the .usd importer, session stats; Shared/RynthAiHubApi.cs, HubInterface.cs). // matching, the .usd importer, session stats; Shared/RynthAiHubApi.cs, HubInterface.cs),
// "RynthAi.Yield" v1 for RynthDefective (the player's key press goes before RynthAi's next action;
// Shared/RynthAiYieldApi.cs, YieldInterface.cs).
// Fixed signature: void* (const char* iface, uint version). // Fixed signature: void* (const char* iface, uint version).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version)
@ -30,6 +32,7 @@ public static unsafe class PluginExports
if (table == IntPtr.Zero) table = StatusInterface.Query(iface, version); if (table == IntPtr.Zero) table = StatusInterface.Query(iface, version);
if (table == IntPtr.Zero) table = ActivityInterface.Query(iface, version); if (table == IntPtr.Zero) table = ActivityInterface.Query(iface, version);
if (table == IntPtr.Zero) table = HubInterface.Query(iface, version); if (table == IntPtr.Zero) table = HubInterface.Query(iface, version);
if (table == IntPtr.Zero) table = YieldInterface.Query(iface, version);
return table != IntPtr.Zero ? table : CombatHookInterface.Query(iface, version); return table != IntPtr.Zero ? table : CombatHookInterface.Query(iface, version);
} }
catch catch
@ -53,6 +56,8 @@ public static unsafe class PluginExports
catch (Exception ex) { LogShutdownError(plugin, "StatusInterface.Release", ex); } catch (Exception ex) { LogShutdownError(plugin, "StatusInterface.Release", ex); }
try { ActivityInterface.Release(); } try { ActivityInterface.Release(); }
catch (Exception ex) { LogShutdownError(plugin, "ActivityInterface.Release", ex); } catch (Exception ex) { LogShutdownError(plugin, "ActivityInterface.Release", ex); }
try { YieldInterface.Release(); }
catch (Exception ex) { LogShutdownError(plugin, "YieldInterface.Release", ex); }
try { HubInterface.Release(); } // Version 0; the table stays (RynthILT's render thread may hold it) try { HubInterface.Release(); } // Version 0; the table stays (RynthILT's render thread may hold it)
catch (Exception ex) { LogShutdownError(plugin, "HubInterface.Release", ex); } catch (Exception ex) { LogShutdownError(plugin, "HubInterface.Release", ex); }
try { CombatHookInterface.Shutdown(); } // the hook goes native at once (RynthLua re-claims after a reload) try { CombatHookInterface.Shutdown(); } // the hook goes native at once (RynthLua re-claims after a reload)

View file

@ -247,6 +247,7 @@ public sealed partial class RynthAiPlugin
_currentLootItemPipelined = pipelined; _currentLootItemPipelined = pipelined;
_currentLootItemStackable = stackable; _currentLootItemStackable = stackable;
_currentLootItemErrSeqAtSend = errSeqAtSend; _currentLootItemErrSeqAtSend = errSeqAtSend;
NoteLootMoveSent();
_currentLootItemActionLabel = "Recover"; _currentLootItemActionLabel = "Recover";
_currentLootItemName = name; _currentLootItemName = name;
_currentLootItemIsSalvage = false; // never salvage your own things _currentLootItemIsSalvage = false; // never salvage your own things

View file

@ -39,6 +39,7 @@
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" /> <Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- RynthSort reads what the bot is doing through RynthAi.Activity (read only). --> <!-- RynthSort reads what the bot is doing through RynthAi.Activity (read only). -->
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" /> <Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<Compile Include="..\Shared\RynthAiYieldApi.cs" Link="Shared\RynthAiYieldApi.cs" />
<!-- RynthLua's scripts choose attack and heal spells through RynthAi.Combat. --> <!-- RynthLua's scripts choose attack and heal spells through RynthAi.Combat. -->
<Compile Include="..\Shared\RynthAiCombatApi.cs" Link="Shared\RynthAiCombatApi.cs" /> <Compile Include="..\Shared\RynthAiCombatApi.cs" Link="Shared\RynthAiCombatApi.cs" />
<!-- RynthNav's navmesh path queries (stuck-recovery detours outdoors). --> <!-- RynthNav's navmesh path queries (stuck-recovery detours outdoors). -->

View file

@ -0,0 +1,73 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// RynthAi's side of the "RynthAi.Yield" interface (Shared/RynthAiYieldApi.cs, 2026-10-29): a plugin
/// acting for the player (RynthDefective's Shortcuts bar) takes the player's turn, and RynthAi starts
/// nothing new until it has gone (ActionPacer.HoldForPlayer). Runs on the plugin pump thread (the
/// caller's OnTick), on the current plugin instance.
/// </summary>
internal static unsafe class YieldInterface
{
private static RynthAiYieldApiV1* _table;
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthAiYieldApiV1.InterfaceName || version == 0 || version > RynthAiYieldApiV1.InterfaceVersion) return IntPtr.Zero;
if (_table == null)
{
var t = (RynthAiYieldApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiYieldApiV1));
t->Version = RynthAiYieldApiV1.InterfaceVersion;
t->StructSize = (uint)sizeof(RynthAiYieldApiV1);
t->HoldForPlayer = &HoldForPlayer;
t->ReleaseHold = &ReleaseHold;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Frees the table (plugin shutdown). Callers resolve it every tick.</summary>
public static void Release()
{
var t = _table;
_table = null;
if (t != null) NativeMemory.Free(t);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int HoldForPlayer(uint ms)
{
try { return PluginExports.Runtime.Plugin?.HoldForPlayer(ms) == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ReleaseHold()
{
try
{
PluginExports.Runtime.Plugin?.ReleasePlayerHold();
return 1;
}
catch
{
return 0;
}
}
}
public sealed partial class RynthAiPlugin
{
/// <summary>The player's turn for another plugin (RynthAi.Yield); false before login or with pacing off.</summary>
internal bool HoldForPlayer(uint ms)
{
if (!_loginComplete) return false;
return ActionPacer.HoldForPlayer(Host, Math.Min(ms, RynthAiYieldApiV1.MaxHoldMs));
}
internal void ReleasePlayerHold() => ActionPacer.ReleasePlayerHold(Host);
}

View file

@ -37,6 +37,7 @@
<ItemGroup> <ItemGroup>
<!-- What RynthAi is doing (read only), so a weapon swap stays out of its way. --> <!-- What RynthAi is doing (read only), so a weapon swap stays out of its way. -->
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" /> <Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<Compile Include="..\Shared\RynthAiYieldApi.cs" Link="Shared\RynthAiYieldApi.cs" />
<!-- An older RynthAi without RynthAi.Activity: its RynthAi.Status macro bit instead. --> <!-- An older RynthAi without RynthAi.Activity: its RynthAi.Status macro bit instead. -->
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" /> <Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. --> <!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->

View file

@ -27,6 +27,16 @@
// After that the use is sent: if the server really is busy it answers // After that the use is sent: if the server really is busy it answers
// "You're too busy" (UseDone 0x1D) and the use controller tries once more. // "You're too busy" (UseDone 0x1D) and the use controller tries once more.
// //
// With RynthAi holding for the press (RynthAi.Yield, 2026-10-29), RynthAi says
// exactly what it has in flight (its pacer's one outstanding action), so the
// rule is simpler and doesn't wait seconds for the count to sit still:
// * RynthAi's own unanswered action holds, for at most BotTrustMs;
// * the count holds only right after our own use (OwnTrustMs);
// * anything else in the count is a leftover (a death, a login, a corpse
// open's +1) or a click in the game's own windows: the use goes.
// After a death or a login RynthAi's stream of rebuffs kept the count moving,
// so it never read "steady" and a press waited until it gave up.
//
// RynthDefective never resets the client's count itself (ForceResetBusyCount): // RynthDefective never resets the client's count itself (ForceResetBusyCount):
// the count is the engine's (its reconciler and watchdogs own it), RynthAi // the count is the engine's (its reconciler and watchdogs own it), RynthAi
// stopped resetting it on 2026-10-06 because a reset zeroes actions the server // stopped resetting it on 2026-10-06 because a reset zeroes actions the server
@ -54,9 +64,15 @@ internal enum BusyStale { None = 0, Count = 1, Animation = 2, Bot = 4 }
/// <param name="AnimatingMs">How long it has animated without a break.</param> /// <param name="AnimatingMs">How long it has animated without a break.</param>
/// <param name="BotWaiting">RynthAi is waiting on the server (null = RynthAi isn't there).</param> /// <param name="BotWaiting">RynthAi is waiting on the server (null = RynthAi isn't there).</param>
/// <param name="BotSteadyMs">How long that bit has read its current value.</param> /// <param name="BotSteadyMs">How long that bit has read its current value.</param>
/// <param name="BotPaced">
/// RynthAi holds for the press and reports its own unanswered action (RynthAi.Yield); null = it
/// doesn't (absent, from before, its pacing off): the rules above apply.
/// </param>
/// <param name="BotPacedMs">How long RynthAi's own action has been unanswered (0 when none).</param>
internal readonly record struct BusyFacts( internal readonly record struct BusyFacts(
int Count, long CountSteadyMs, int Leftover, long SinceOwnSendMs, int Count, long CountSteadyMs, int Leftover, long SinceOwnSendMs,
bool Animating, long AnimatingMs, bool? BotWaiting, long BotSteadyMs); bool Animating, long AnimatingMs, bool? BotWaiting, long BotSteadyMs,
bool? BotPaced = null, long BotPacedMs = 0);
internal static class BusyRule internal static class BusyRule
{ {
@ -78,6 +94,23 @@ internal static class BusyRule
if (f.AnimatingMs < AnimationMaxMs) return BusyHold.Animation; if (f.AnimatingMs < AnimationMaxMs) return BusyHold.Animation;
stale |= BusyStale.Animation; stale |= BusyStale.Animation;
} }
if (f.BotPaced is bool paced)
{
// RynthAi holds for the press and says what it has in flight: that, and our own last use,
// are all that hold it. The rest of the count is a leftover or a click in the game's own
// windows; a really busy server answers "You're too busy" (one more try).
if (paced)
{
if (f.BotPacedMs < BotTrustMs) return BusyHold.Bot;
stale |= BusyStale.Bot;
}
if (f.Count > 0)
{
if (f.Count > f.Leftover && f.SinceOwnSendMs < OwnTrustMs) return BusyHold.Busy;
stale |= BusyStale.Count;
}
return BusyHold.None;
}
if (f.Count > 0) if (f.Count > 0)
{ {
bool fresh = f.CountSteadyMs < CountTrustMs || f.SinceOwnSendMs < OwnTrustMs; bool fresh = f.CountSteadyMs < CountTrustMs || f.SinceOwnSendMs < OwnTrustMs;
@ -110,14 +143,22 @@ internal sealed class BusyGate
private long _animatingSinceMs; private long _animatingSinceMs;
private bool? _bot; private bool? _bot;
private long _botSinceMs; private long _botSinceMs;
private bool _paced;
private long _pacedSinceMs;
private long _ownSendMs = long.MinValue / 4; private long _ownSendMs = long.MinValue / 4;
private BusyStale _logged; private BusyStale _logged;
/// <summary>The count judged a leftover (0 = none).</summary> /// <summary>The count judged a leftover (0 = none).</summary>
public int Leftover => _leftover; public int Leftover => _leftover;
public void Observe(int count, bool animating, bool? botWaiting, long now) public void Observe(int count, bool animating, bool? botWaiting, long now) => Observe(count, animating, botWaiting, null, now);
/// <param name="botPaced">RynthAi's own action is unanswered (null = it can't say).</param>
public void Observe(int count, bool animating, bool? botWaiting, bool? botPaced, long now)
{ {
bool paced = botPaced == true;
if (paced && !_paced) _pacedSinceMs = now;
_paced = paced;
if (count < 0) count = 0; if (count < 0) count = 0;
if (!_started) if (!_started)
{ {
@ -153,17 +194,24 @@ internal sealed class BusyGate
/// <summary>Our own use or cast went out now.</summary> /// <summary>Our own use or cast went out now.</summary>
public void NoteOwnSend(long now) => _ownSendMs = now; public void NoteOwnSend(long now) => _ownSendMs = now;
public BusyFacts Facts(long now) => new( public BusyFacts Facts(long now) => Facts(now, false);
/// <param name="pacedKnown">RynthAi holds for the press (its PacedAction bit is meaningful).</param>
public BusyFacts Facts(long now, bool pacedKnown) => new(
_count, now - _countSinceMs, _leftover, now - _ownSendMs, _count, now - _countSinceMs, _leftover, now - _ownSendMs,
_animating, _animating ? now - _animatingSinceMs : 0, _bot, now - _botSinceMs); _animating, _animating ? now - _animatingSinceMs : 0, _bot, now - _botSinceMs,
pacedKnown ? _paced : null, pacedKnown && _paced ? now - _pacedSinceMs : 0);
/// <summary> /// <summary>
/// What holds a use back now. A count found to be a leftover becomes the new leftover; /// What holds a use back now. A count found to be a leftover becomes the new leftover;
/// <paramref name="newlyIgnored"/> names the leftovers not reported before (log them once). /// <paramref name="newlyIgnored"/> names the leftovers not reported before (log them once).
/// </summary> /// </summary>
public BusyHold Judge(long now, out BusyStale newlyIgnored) public BusyHold Judge(long now, out BusyStale newlyIgnored) => Judge(now, false, out newlyIgnored);
/// <param name="pacedKnown">RynthAi holds for the press (RynthAi.Yield): its own action is what it says.</param>
public BusyHold Judge(long now, bool pacedKnown, out BusyStale newlyIgnored)
{ {
BusyHold hold = BusyRule.Decide(Facts(now), out BusyStale stale); BusyHold hold = BusyRule.Decide(Facts(now, pacedKnown), out BusyStale stale);
if ((stale & BusyStale.Count) != 0 && _count > _leftover) if ((stale & BusyStale.Count) != 0 && _count > _leftover)
{ {
_leftover = _count; _leftover = _count;
@ -175,15 +223,21 @@ internal sealed class BusyGate
} }
/// <summary>The words for the log line when a leftover is first ignored.</summary> /// <summary>The words for the log line when a leftover is first ignored.</summary>
public string Describe(BusyStale what, long now) public string Describe(BusyStale what, long now) => Describe(what, now, false);
public string Describe(BusyStale what, long now, bool pacedKnown)
{ {
BusyFacts f = Facts(now); BusyFacts f = Facts(now, pacedKnown);
var parts = new System.Collections.Generic.List<string>(3); var parts = new System.Collections.Generic.List<string>(3);
if ((what & BusyStale.Count) != 0) if ((what & BusyStale.Count) != 0)
parts.Add($"the client's busy count has read {f.Count} for {f.CountSteadyMs / 1000.0:0.0} s with nothing of ours in flight"); parts.Add(f.BotPaced != null
? $"the client's busy count reads {f.Count} with nothing of ours or RynthAi's in flight"
: $"the client's busy count has read {f.Count} for {f.CountSteadyMs / 1000.0:0.0} s with nothing of ours in flight");
if ((what & BusyStale.Animation) != 0) if ((what & BusyStale.Animation) != 0)
parts.Add($"the character has read 'animating' for {f.AnimatingMs / 1000.0:0.0} s"); parts.Add($"the character has read 'animating' for {f.AnimatingMs / 1000.0:0.0} s");
if ((what & BusyStale.Bot) != 0) if ((what & BusyStale.Bot) != 0 && f.BotPaced != null)
parts.Add($"RynthAi's own action has had no answer for {f.BotPacedMs / 1000.0:0.0} s");
else if ((what & BusyStale.Bot) != 0)
parts.Add($"RynthAi has read 'waiting on the server' for {f.BotSteadyMs / 1000.0:0.0} s" parts.Add($"RynthAi has read 'waiting on the server' for {f.BotSteadyMs / 1000.0:0.0} s"
+ ((what & BusyStale.Count) != 0 || (_logged & BusyStale.Count) != 0 ? " (its copy of the same count)" : "")); + ((what & BusyStale.Count) != 0 || (_logged & BusyStale.Count) != 0 ? " (its copy of the same count)" : ""));
return "[RynthDefective] " + string.Join("; ", parts) return "[RynthDefective] " + string.Join("; ", parts)
@ -194,6 +248,7 @@ internal sealed class BusyGate
{ {
_started = false; _started = false;
_leftover = 0; _leftover = 0;
_paced = false;
_logged = BusyStale.None; _logged = BusyStale.None;
_ownSendMs = long.MinValue / 4; _ownSendMs = long.MinValue / 4;
} }

View file

@ -40,6 +40,9 @@ internal sealed unsafe class HostDefWorld : IDefWorld
public bool? BotWaitingOnServer => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.ServerAction) != 0 : null; public bool? BotWaitingOnServer => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.ServerAction) != 0 : null;
public bool? BotMacroRunning => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.MacroRunning) != 0 : null; public bool? BotMacroRunning => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.MacroRunning) != 0 : null;
public bool? BotPaced => BotYield.Available(_host) && BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.PacedAction) != 0 : null;
public bool HoldBot(uint ms) => BotYield.Hold(_host, ms);
public void ReleaseBot() => BotYield.Release(_host);
public int RefusalSeq => _host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0; public int RefusalSeq => _host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
@ -149,6 +152,47 @@ internal sealed unsafe class HostDefWorld : IDefWorld
} }
} }
/// <summary>
/// RynthAi's "RynthAi.Yield" interface (2026-10-29): the player's key press takes RynthAi's turn, so
/// RynthAi starts nothing new until the press has gone. Resolved again every call (a RynthAi reload
/// frees the table). Absent on a RynthAi from before it: nothing is held then.
/// </summary>
internal static unsafe class BotYield
{
private static RynthAiYieldApiV1* Table(RynthCoreHost host)
{
if (!host.HasGetPluginInterface) return null;
try
{
var t = (RynthAiYieldApiV1*)host.GetPluginInterface("RynthAi", RynthAiYieldApiV1.InterfaceName, RynthAiYieldApiV1.InterfaceVersion);
return t != null && t->Version >= 1 && t->StructSize >= (uint)sizeof(RynthAiYieldApiV1) ? t : null;
}
catch
{
return null; // a RynthAi mid-reload
}
}
public static bool Available(RynthCoreHost host) => Table(host) != null;
/// <summary>Asks for the player's turn for <paramref name="ms"/>; true when RynthAi holds (its pacing is on).</summary>
public static bool Hold(RynthCoreHost host, uint ms)
{
var t = Table(host);
if (t == null || t->HoldForPlayer == null) return false;
try { return t->HoldForPlayer(ms) != 0; }
catch { return false; }
}
public static void Release(RynthCoreHost host)
{
var t = Table(host);
if (t == null || t->ReleaseHold == null) return;
try { t->ReleaseHold(); }
catch { }
}
}
/// <summary> /// <summary>
/// RynthAi's activity bits: its "RynthAi.Activity" interface; on an older RynthAi without it, the /// RynthAi's activity bits: its "RynthAi.Activity" interface; on an older RynthAi without it, the
/// macro bit from "RynthAi.Status"; null when RynthAi isn't loaded or not ready. Resolved again every /// macro bit from "RynthAi.Status"; null when RynthAi isn't loaded or not ready. Resolved again every

View file

@ -27,6 +27,18 @@ internal interface IDefWorld
bool? BotWaitingOnServer { get; } bool? BotWaitingOnServer { get; }
/// <summary>RynthAi's macro is running (null = RynthAi isn't there).</summary> /// <summary>RynthAi's macro is running (null = RynthAi isn't there).</summary>
bool? BotMacroRunning { get; } bool? BotMacroRunning { get; }
/// <summary>
/// A use, cast or stance change RynthAi sent has no answer yet (its pacer's; not the busy count).
/// Null = can't tell: RynthAi isn't there or is from before RynthAi.Yield.
/// </summary>
bool? BotPaced { get; }
/// <summary>
/// The player's turn: RynthAi starts nothing new for <paramref name="ms"/> (RynthAi.Yield). True when
/// it holds; false when it can't (not there, from before, its pacing off): BotPaced means nothing then.
/// </summary>
bool HoldBot(uint ms);
/// <summary>Ends the player's turn.</summary>
void ReleaseBot();
/// <summary>Count of the server's UseDone events; 0 when the engine can't report them.</summary> /// <summary>Count of the server's UseDone events; 0 when the engine can't report them.</summary>
int UseDoneSeq { get; } int UseDoneSeq { get; }
/// <summary>The error of the server's first UseDone after <paramref name="seqAtSend"/> (0x1D: "You're too busy"); 0 = none or unknown.</summary> /// <summary>The error of the server's first UseDone after <paramref name="seqAtSend"/> (0x1D: "You're too busy"); 0 = none or unknown.</summary>
@ -136,6 +148,18 @@ internal static class Stance
/// holds nothing (<see cref="BusyGate"/>, logged once); if the server really is busy it answers /// holds nothing (<see cref="BusyGate"/>, logged once); if the server really is busy it answers
/// "You're too busy" and the use is tried once more after <see cref="RetryAfterMs"/>. Weapon swaps /// "You're too busy" and the use is tried once more after <see cref="RetryAfterMs"/>. Weapon swaps
/// also wait out a running RynthAi macro unless the player allowed them (it would swap straight back). /// also wait out a running RynthAi macro unless the player allowed them (it would swap straight back).
///
/// The player's turn (2026-10-29): while a request waits, and for the first <see cref="FlightHoldMs"/>
/// of its flight, RynthAi is asked to start nothing new (RynthAi.Yield, renewed every tick, let go
/// when done). After a death or a login RynthAi rebuffs and re-wields, and a press used to wait
/// behind that stream until it gave up. While RynthAi holds, it also says exactly what it has in
/// flight, so only that and our own last use hold a press: the busy count beyond them is a leftover.
///
/// After a portal (2026-10-29): the engine takes no game action until 5 s after portal space ends
/// (its world-transition gate: AC is still loading the new place), so a press then was refused and
/// reported as "the client didn't take the request". Within <see cref="PortalRetryWindowMs"/> of
/// coming out of portal space a refused use or cast waits instead and is tried again every
/// <see cref="RefusedRetryMs"/>; it goes the moment the engine takes it.
/// </summary> /// </summary>
internal sealed class UseController internal sealed class UseController
{ {
@ -156,6 +180,14 @@ internal sealed class UseController
public const long RetryAfterMs = 1000; public const long RetryAfterMs = 1000;
/// <summary>ACE's YoureTooBusy, as a UseDone error.</summary> /// <summary>ACE's YoureTooBusy, as a UseDone error.</summary>
public const uint TooBusyError = 0x1D; public const uint TooBusyError = 0x1D;
/// <summary>Each ask for the player's turn lasts this long (asked again every tick while it is wanted).</summary>
public const uint BotHoldAskMs = 1500;
/// <summary>RynthAi is held this long into our use's flight (a stance change of its own would cancel the use on the server).</summary>
public const long FlightHoldMs = 3000;
/// <summary>A use or cast the client refuses this soon after portal space ends waits and is tried again (the engine's gate holds 5 s).</summary>
public const long PortalRetryWindowMs = 6000;
/// <summary>How often a refused use or cast is tried again after a portal.</summary>
public const long RefusedRetryMs = 250;
private enum Stage { Sent, WaitWield, Stance, Magic } private enum Stage { Sent, WaitWield, Stance, Magic }
@ -175,6 +207,9 @@ internal sealed class UseController
// A cast: the spell, its target, and the Magic stance it waits for. // A cast: the spell, its target, and the Magic stance it waits for.
public uint SpellId, Target; public uint SpellId, Target;
public bool ModeAsked; public bool ModeAsked;
/// <summary>A cast the client refused after a portal is tried again from this time.</summary>
public long CastRetryAtMs;
public bool CastWaitSaid;
public long MagicSeenMs; public long MagicSeenMs;
} }
@ -184,6 +219,20 @@ internal sealed class UseController
private long _retryNotBeforeMs = long.MinValue / 4; private long _retryNotBeforeMs = long.MinValue / 4;
private string _lastWait = string.Empty; private string _lastWait = string.Empty;
private readonly BusyGate _busy = new(); private readonly BusyGate _busy = new();
/// <summary>RynthAi holds for us (the last ask was taken): its PacedAction bit is what it has in flight.</summary>
private bool _botHeld;
// When the character last came out of portal space (or logged in): a refused send soon after waits.
// Starts "in the world" so a plugin load in the world doesn't count as an arrival.
private bool _wasInWorld = true;
private long _worldBackMs = long.MinValue / 4;
private long _refusedRetryAtMs = long.MinValue / 4;
private UseRequest? _refusedSaid;
/// <summary>The engine refused sends this soon after the character came out of portal space: they are tried again.</summary>
private bool JustArrived(long now) => now - _worldBackMs < PortalRetryWindowMs;
/// <summary>RynthAi holds its next action for the press now (tests).</summary>
internal bool BotHeld => _botHeld;
/// <summary>The busy readings' clocks (tests look at the leftover).</summary> /// <summary>The busy readings' clocks (tests look at the leftover).</summary>
internal BusyGate Busy => _busy; internal BusyGate Busy => _busy;
@ -227,6 +276,7 @@ internal sealed class UseController
_flight = null; _flight = null;
_lastWait = string.Empty; _lastWait = string.Empty;
_retryNotBeforeMs = long.MinValue / 4; _retryNotBeforeMs = long.MinValue / 4;
_refusedRetryAtMs = long.MinValue / 4;
} }
/// <summary> /// <summary>
@ -243,8 +293,41 @@ internal sealed class UseController
public void Tick(IDefWorld w) public void Tick(IDefWorld w)
{ {
long now = w.NowMs; long now = w.NowMs;
_busy.Observe(w.BusyCount, w.Animating, w.BotWaitingOnServer, now); _busy.Observe(w.BusyCount, w.Animating, w.BotWaitingOnServer, w.BotPaced, now);
if (!w.InWorld) try
{
TickInner(w, now);
}
finally
{
KeepBotHeld(w, now, ask: false); // let RynthAi go the tick the press is done
}
}
/// <summary>
/// The player's turn: asked for while a request waits or its flight is young (ask), let go when
/// neither. RynthAi's hold ends by itself within <see cref="BotHoldAskMs"/> if we stop asking.
/// </summary>
private void KeepBotHeld(IDefWorld w, long now, bool ask)
{
bool want = _pending != null || (_flight != null && now - _flight.SentMs < FlightHoldMs);
if (want)
{
if (ask) _botHeld = w.HoldBot(BotHoldAskMs);
}
else if (_botHeld)
{
w.ReleaseBot();
_botHeld = false;
}
}
private void TickInner(IDefWorld w, long now)
{
bool inWorld = w.InWorld;
if (inWorld && !_wasInWorld) _worldBackMs = now;
_wasInWorld = inWorld;
if (!inWorld)
{ {
// Portal space (a death's too): what was waiting is dropped, and said so (a key pressed in the // Portal space (a death's too): what was waiting is dropped, and said so (a key pressed in the
// portal did nothing). A use in flight is the server's now; nothing to say about it. // portal did nothing). A use in flight is the server's now; nothing to say about it.
@ -252,6 +335,7 @@ internal sealed class UseController
if (_pending != null || _flight != null) Reset(); if (_pending != null || _flight != null) Reset();
return; return;
} }
KeepBotHeld(w, now, ask: true);
if (_flight != null && !AdvanceFlight(w, now)) return; // still in flight: nothing new goes out if (_flight != null && !AdvanceFlight(w, now)) return; // still in flight: nothing new goes out
if (_pending == null) return; if (_pending == null) return;
@ -275,6 +359,7 @@ internal sealed class UseController
{ {
if (now - _lastDoneMs < MinGapMs) return "the last action just finished"; if (now - _lastDoneMs < MinGapMs) return "the last action just finished";
if (now < _retryNotBeforeMs) return "the server said the character was busy"; if (now < _retryNotBeforeMs) return "the server said the character was busy";
if (now < _refusedRetryAtMs) return "the game is still loading after the portal";
return Hold(now) switch return Hold(now) switch
{ {
BusyHold.Busy => "the character is busy", BusyHold.Busy => "the character is busy",
@ -287,8 +372,8 @@ internal sealed class UseController
/// <summary>The busy gate's verdict now; a leftover it ignores for the first time is logged.</summary> /// <summary>The busy gate's verdict now; a leftover it ignores for the first time is logged.</summary>
private BusyHold Hold(long now) private BusyHold Hold(long now)
{ {
BusyHold hold = _busy.Judge(now, out BusyStale ignored); BusyHold hold = _busy.Judge(now, _botHeld, out BusyStale ignored);
if (ignored != BusyStale.None) Log?.Invoke(_busy.Describe(ignored, now)); if (ignored != BusyStale.None) Log?.Invoke(_busy.Describe(ignored, now, _botHeld));
return hold; return hold;
} }
@ -354,6 +439,7 @@ internal sealed class UseController
bool sent = target != 0 ? w.UseObjectOn(item.Id, target) : w.UseObject(item.Id); bool sent = target != 0 ? w.UseObjectOn(item.Id, target) : w.UseObject(item.Id);
if (!sent) if (!sent)
{ {
if (WaitOutRefusal(req, name, now)) return;
Warn?.Invoke($"{name}: the client didn't take the request (nothing was sent)."); Warn?.Invoke($"{name}: the client didn't take the request (nothing was sent).");
return; return;
} }
@ -378,6 +464,25 @@ internal sealed class UseController
Say?.Invoke(action == UseAction.Equip ? $"Wielding {name}..." : $"Using {name}..."); Say?.Invoke(action == UseAction.Equip ? $"Wielding {name}..." : $"Using {name}...");
} }
/// <summary>
/// The client refused to send <paramref name="req"/>: just after a portal the engine takes no game
/// action yet, so the request waits and is tried again (its wait limit still counts from the press).
/// Said once per request. False when it isn't just after a portal: a refusal is reported as before.
/// </summary>
private bool WaitOutRefusal(UseRequest req, string name, long now)
{
if (!JustArrived(now) || _pending != null) return false; // a newer press waits already: the newest wish wins
_pending = req;
_refusedRetryAtMs = now + RefusedRetryMs;
if (!ReferenceEquals(_refusedSaid, req))
{
_refusedSaid = req;
Log?.Invoke($"[RynthDefective] {req.Source}: the client doesn't take {name} yet ({now - _worldBackMs} ms after the portal); trying again");
Say?.Invoke($"{name}: waiting for the game to finish the portal...");
}
return true;
}
/// <summary> /// <summary>
/// The server answered "You're too busy" (UseDone 0x1D) to <paramref name="f"/>'s use: it is tried /// The server answered "You're too busy" (UseDone 0x1D) to <paramref name="f"/>'s use: it is tried
/// once more after <see cref="RetryAfterMs"/>, unless a newer request is waiting (the newest wish /// once more after <see cref="RetryAfterMs"/>, unless a newer request is waiting (the newest wish
@ -475,10 +580,23 @@ internal sealed class UseController
private bool Cast(IDefWorld w, Flight f, long now) private bool Cast(IDefWorld w, Flight f, long now)
{ {
if (now < f.CastRetryAtMs) return false;
f.UseDoneAtSend = w.UseDoneSeq; f.UseDoneAtSend = w.UseDoneSeq;
f.RefusalAtSend = w.RefusalSeq; f.RefusalAtSend = w.RefusalSeq;
if (!w.CastSpell(f.Target, f.SpellId)) if (!w.CastSpell(f.Target, f.SpellId))
{ {
// Just after a portal the engine takes no game action yet: the cast is tried again.
if (JustArrived(now) && now - f.Request.AtMs < WaitLimitMs)
{
f.CastRetryAtMs = now + RefusedRetryMs;
if (!f.CastWaitSaid)
{
f.CastWaitSaid = true;
Log?.Invoke($"[RynthDefective] {f.Request.Source}: the client doesn't take the cast of {f.What} yet ({now - _worldBackMs} ms after the portal); trying again");
Say?.Invoke($"{f.Name}: waiting for the game to finish the portal...");
}
return false;
}
Warn?.Invoke($"{f.Name}: the client didn't take the cast (nothing was sent)."); Warn?.Invoke($"{f.Name}: the client didn't take the cast (nothing was sent).");
Finish(now); Finish(now);
return true; return true;

View file

@ -50,6 +50,12 @@
// the character animates, and nothing while a use's turn is unanswered, keeps every // the character animates, and nothing while a use's turn is unanswered, keeps every
// server motion out of every server turn. // server motion out of every server turn.
// //
// The player's turn (2026-10-29, RynthAi.Yield): another plugin acting for the player (the
// Shortcuts bar's key press) holds every start (MayStart, GestureHolds, ChangeCombatModeFor) for
// a moment, so the player's action goes next instead of waiting behind RynthAi's own. What is
// already out still finishes. Each ask lasts at most PlayerHoldMaxMs; the asker asks again
// every tick while its action waits or is in flight.
//
// Opt-in (Enabled, RynthAi sets it at Init); off = every call goes through as before. // Opt-in (Enabled, RynthAi sets it at Init); off = every call goes through as before.
// Linked into RynthAi only. UseAudit reports its sends through UseAudit.AfterSend. // Linked into RynthAi only. UseAudit reports its sends through UseAudit.AfterSend.
// ============================================================================ // ============================================================================
@ -139,6 +145,8 @@ internal static class ActionPacer
public const long AttackAfterModeReadMs = 300; public const long AttackAfterModeReadMs = 300;
/// <summary>An engine without UseDone: an action counts as answered after this (no real pacing).</summary> /// <summary>An engine without UseDone: an action counts as answered after this (no real pacing).</summary>
public const long NoUseDoneFallbackMs = 600; public const long NoUseDoneFallbackMs = 600;
/// <summary>The longest one ask for the player's turn holds RynthAi (RynthAiYieldApiV1.MaxHoldMs).</summary>
public const long PlayerHoldMaxMs = 3000;
private static readonly object Gate = new(); private static readonly object Gate = new();
private static PacedAction? _cur; private static PacedAction? _cur;
@ -155,6 +163,10 @@ internal static class ActionPacer
private static readonly Dictionary<string, int> _holdsByWho = new(); private static readonly Dictionary<string, int> _holdsByWho = new();
private static string _lastTimeout = ""; private static string _lastTimeout = "";
// The player's turn (RynthAi.Yield): starts are held until _playerHoldUntil (0 = no hold).
private static long _playerHoldUntil, _playerHoldSince, _playerHolds, _playerHeldStarts;
private static readonly HashSet<string> _playerHoldLogged = new();
public static long Started => _started; public static long Started => _started;
public static long Answered => _answered; public static long Answered => _answered;
public static long TimedOut => _timedOut; public static long TimedOut => _timedOut;
@ -166,6 +178,9 @@ internal static class ActionPacer
public static long HealsAhead => _healsAhead; public static long HealsAhead => _healsAhead;
public static long GestureHoldCount => _gestureHolds; public static long GestureHoldCount => _gestureHolds;
public static long GestureLimits => _gestureLimits; public static long GestureLimits => _gestureLimits;
/// <summary>Times another plugin took the player's turn, and the starts it held.</summary>
public static long PlayerHolds => _playerHolds;
public static long PlayerHeldStarts => _playerHeldStarts;
/// <summary>Back to a fresh load (Init, logout, tests). Enabled is left as it is.</summary> /// <summary>Back to a fresh load (Init, logout, tests). Enabled is left as it is.</summary>
public static void Reset() public static void Reset()
@ -184,6 +199,8 @@ internal static class ActionPacer
_maxWaitMs = 0; _maxWaitMs = 0;
_maxWaitWhat = ""; _maxWaitWhat = "";
_holdsByWho.Clear(); _holdsByWho.Clear();
_playerHoldUntil = _playerHoldSince = _playerHolds = _playerHeldStarts = 0;
_playerHoldLogged.Clear();
_lastTimeout = ""; _lastTimeout = "";
ClearBusyLocked(); ClearBusyLocked();
_stuckBreaks = 0; _stuckBreaks = 0;
@ -362,6 +379,72 @@ internal static class ActionPacer
return action != null; return action != null;
} }
// ── The player's turn ───────────────────────────────────────────────────
/// <summary>
/// Another plugin acting for the player (RynthAi.Yield): no start for <paramref name="ms"/> from now
/// (at most <see cref="PlayerHoldMaxMs"/>), the newest ask setting the end. False when pacing is off:
/// RynthAi then knows nothing about what it has in flight, so the asker goes by its old rules.
/// </summary>
public static bool HoldForPlayer(RynthCoreHost host, long ms)
{
if (!Enabled) return false;
long now = NowMs();
bool began;
lock (Gate)
{
began = _playerHoldUntil == 0 || now >= _playerHoldUntil;
if (began)
{
_playerHoldSince = now;
_playerHolds++;
_playerHoldLogged.Clear();
}
_playerHoldUntil = now + Math.Clamp(ms, 1, PlayerHoldMaxMs);
}
if (began) Log(host, "[Pace] the player's turn: a key press from another plugin goes first; RynthAi starts nothing new until it has gone");
return true;
}
/// <summary>Ends the player's turn now (the asker's action was answered, or dropped).</summary>
public static void ReleasePlayerHold(RynthCoreHost host)
{
long held;
lock (Gate)
{
if (_playerHoldUntil == 0) return;
held = NowMs() - _playerHoldSince;
_playerHoldUntil = 0;
_playerHoldLogged.Clear();
}
Log(host, $"[Pace] the player's turn is over after {held} ms; RynthAi goes on");
}
/// <summary>True (with why) while another plugin has the player's turn. One log line per hold and subsystem.</summary>
private static bool PlayerHoldsStart(RynthCoreHost host, string who, out string why)
{
why = "";
if (!Enabled) return false;
long now = NowMs();
bool log;
lock (Gate)
{
if (_playerHoldUntil == 0) return false;
if (now >= _playerHoldUntil)
{
// The asker stopped asking (unloaded, stuck): the hold ends by itself.
_playerHoldUntil = 0;
_playerHoldLogged.Clear();
return false;
}
_playerHeldStarts++;
log = _playerHoldLogged.Add(who);
}
why = "the player's key press goes first";
if (log) Log(host, $"[Pace] {who} waits: {why}");
return true;
}
// ── Gates ─────────────────────────────────────────────────────────────── // ── Gates ───────────────────────────────────────────────────────────────
/// <summary> /// <summary>
@ -382,6 +465,7 @@ internal static class ActionPacer
bool animationGate = true, bool settleGate = true, bool attackRepeat = false) bool animationGate = true, bool settleGate = true, bool attackRepeat = false)
{ {
if (!Enabled) { why = ""; return true; } if (!Enabled) { why = ""; return true; }
if (PlayerHoldsStart(host, who, out why)) return false;
if (ServerBusyHolds(host, who, attackRepeat, out why, out bool tryAfterBusy, heal)) return false; if (ServerBusyHolds(host, who, attackRepeat, out why, out bool tryAfterBusy, heal)) return false;
// An emergency heal does not wait for the movement settle (150-600 ms): at Emergency Heal At // An emergency heal does not wait for the movement settle (150-600 ms): at Emergency Heal At
// the heal comes first; it still obeys the in-flight rules below (OutstandingAllows, GestureHolds). // the heal comes first; it still obeys the in-flight rules below (OutstandingAllows, GestureHolds).
@ -472,6 +556,7 @@ internal static class ActionPacer
{ {
why = ""; why = "";
if (!Enabled) return false; if (!Enabled) return false;
if (PlayerHoldsStart(host, who, out why)) return true; // the item managers' moves wait too
bool busy; bool busy;
try { busy = host.HasGetCastBusyState && host.GetCastBusyState() != 0; } catch { busy = false; } try { busy = host.HasGetCastBusyState && host.GetCastBusyState() != 0; } catch { busy = false; }
long now = NowMs(); long now = NowMs();
@ -1165,6 +1250,7 @@ internal static class ActionPacer
{ {
lines.Add($" Sent {_started}, answered {_answered}, no answer in time {_timedOut}{(_lastTimeout.Length > 0 ? $" (last: {_lastTimeout})" : "")}"); lines.Add($" Sent {_started}, answered {_answered}, no answer in time {_timedOut}{(_lastTimeout.Length > 0 ? $" (last: {_lastTimeout})" : "")}");
lines.Add($" Starts held {_heldStarts}, moves held {_heldMoves}, heals let ahead {_healsAhead}, sent over an unanswered one {_sentOverOutstanding}"); lines.Add($" Starts held {_heldStarts}, moves held {_heldMoves}, heals let ahead {_healsAhead}, sent over an unanswered one {_sentOverOutstanding}");
lines.Add($" The player's turn (key presses from other plugins): {_playerHolds}, starts held for them {_playerHeldStarts}");
lines.Add($" Mode changes refused while waiting {_modeRefused}, skipped (already in that mode) {_modeSkipped}"); lines.Add($" Mode changes refused while waiting {_modeRefused}, skipped (already in that mode) {_modeSkipped}");
lines.Add($" Held while the character was animating {_gestureHolds}, animation time limits {_gestureLimits}"); lines.Add($" Held while the character was animating {_gestureHolds}, animation time limits {_gestureLimits}");
lines.Add($" Held after a 'too busy' answer {_refusalHolds}, held casts turned to {_heldTurns}, stuck casts broken {_stuckBreaks} ({_forcedBreaks} by the HP failsafe; limit {StuckCastMs} ms)"); lines.Add($" Held after a 'too busy' answer {_refusalHolds}, held casts turned to {_heldTurns}, stuck casts broken {_stuckBreaks} ({_forcedBreaks} by the HP failsafe; limit {StuckCastMs} ms)");
@ -1244,6 +1330,7 @@ internal static class ActionPacer
lock (Gate) _modeSkipped++; lock (Gate) _modeSkipped++;
return false; return false;
} }
if (PlayerHoldsStart(host, "mode:" + who, out _)) return false;
PacedAction? a = Current(host); PacedAction? a = Current(host);
if (a != null) if (a != null)
{ {

View file

@ -60,4 +60,11 @@ public enum RynthAiActivity : uint
Crafting = 1u << 7, Crafting = 1u << 7,
/// <summary>The AutoCram setting is on: RynthAi itself moves loose items out of the main pack.</summary> /// <summary>The AutoCram setting is on: RynthAi itself moves loose items out of the main pack.</summary>
AutoCram = 1u << 8, AutoCram = 1u << 8,
/// <summary>
/// A use, cast or stance change RynthAi sent has no answer from the server yet: its pacer's one
/// outstanding action (Shared/ActionPacer.cs). Unlike <see cref="ServerAction"/>, not the client's
/// busy count, which can stay up with nothing in flight (a death, a login, a corpse open).
/// Reported by a RynthAi that has RynthAi.Yield (2026-10-29), with its pacing on.
/// </summary>
PacedAction = 1u << 9,
} }

View file

@ -0,0 +1,47 @@
// ============================================================================
// RynthSuite - Plugins/Shared/RynthAiYieldApi.cs
// The "RynthAi.Yield" interface (2026-10-29): a plugin acting for the player
// (RynthDefective's Shortcuts bar: a key press, a click) asks RynthAi to start
// nothing new for a moment, so the player's action goes next instead of
// waiting behind RynthAi's stream of uses and casts. After a death or a login
// RynthAi rebuffs and re-wields, every action of its moves the client's busy
// count, and the bar's press waited until it gave up ("not used, the
// character is busy"). What RynthAi already sent still finishes; nothing is
// cancelled, and its moving and turning are not held.
//
// Its own interface: RynthAi.Activity stays read only.
//
// Rules: as RynthAi.Script (Shared/RynthAiScriptApi.cs): append-only, pump
// thread only (OnTick and the events it drains), resolve the table again
// every tick (a RynthAi reload frees it).
// ============================================================================
using System.Runtime.InteropServices;
namespace RynthCore.Plugin.Shared;
[StructLayout(LayoutKind.Sequential)]
public unsafe struct RynthAiYieldApiV1
{
public const string InterfaceName = "RynthAi.Yield";
public const uint InterfaceVersion = 1;
/// <summary>
/// The longest one ask holds RynthAi, in ms. The asker asks again every tick while the player's
/// action waits or is in flight, so one that stops asking (unloaded, stuck) frees RynthAi within this.
/// </summary>
public const uint MaxHoldMs = 3000;
public uint Version; // InterfaceVersion of the table RynthAi filled
public uint StructSize; // sizeof(RynthAiYieldApiV1) as RynthAi built it
/// <summary>
/// RynthAi starts no use, cast, stance change, attack or item move for <c>ms</c> from now (at most
/// <see cref="MaxHoldMs"/>); the newest ask sets the end. 1 = held. 0 = RynthAi can't: not logged in,
/// or its action pacing is off (then it doesn't know what it has in flight either).
/// </summary>
public delegate* unmanaged[Cdecl]<uint, int> HoldForPlayer;
/// <summary>Ends the hold now (the player's action went and was answered, or was dropped). 1 = ok.</summary>
public delegate* unmanaged[Cdecl]<int> ReleaseHold;
}

View file

@ -85,6 +85,7 @@ internal static class Program
FloodPerfTests.Register(runner); FloodPerfTests.Register(runner);
LootSalvageTests.Register(runner); LootSalvageTests.Register(runner);
LootCorpseTests.Register(runner); LootCorpseTests.Register(runner);
LootRetryTimingTests.Register(runner);
ChestLootTests.Register(runner); ChestLootTests.Register(runner);
OwnCorpseTests.Register(runner); OwnCorpseTests.Register(runner);
UseRefusalTests.Register(runner); UseRefusalTests.Register(runner);

View file

@ -46,6 +46,7 @@ internal static class ActionPacingTests
public static void Register(Runner r) public static void Register(Runner r)
{ {
r.Add("pacing: a use is the server action until its UseDone; a refusal answers it too; a wield answers by wielding", UseAnswers); r.Add("pacing: a use is the server action until its UseDone; a refusal answers it too; a wield answers by wielding", UseAnswers);
r.Add("pacing: the player's turn (RynthAi.Yield) holds every start, mode change and move, ends by itself, and lets what is out finish", PlayersTurn);
r.Add("pacing: the stall onset replayed - the idle peace swap waits for the corpse use's answer, then goes; no swap to the mode you're in", OnsetModeChangeHeld); r.Add("pacing: the stall onset replayed - the idle peace swap waits for the corpse use's answer, then goes; no swap to the mode you're in", OnsetModeChangeHeld);
r.Add("pacing: moves and turns wait while the server answers; a stop with nothing of ours moving waits too, is never dropped; a real stop and the cast nudge go through", MovesHeld); r.Add("pacing: moves and turns wait while the server answers; a stop with nothing of ours moving waits too, is never dropped; a real stop and the cast nudge go through", MovesHeld);
r.Add("pacing (stop burst, flight 63260): a held stop goes out once the server answers, before the next start", HeldStopSentAfterAnswer); r.Add("pacing (stop burst, flight 63260): a held stop goes out once the server answers, before the next start", HeldStopSentAfterAnswer);
@ -151,6 +152,65 @@ internal static class ActionPacingTests
// ── The pacer ─────────────────────────────────────────────────────────────── // ── The pacer ───────────────────────────────────────────────────────────────
private static void PlayersTurn()
{
PaceOff();
var off = World();
Check.False(ActionPacer.HoldForPlayer(off, 1500), "pacing off: RynthAi can't hold (it doesn't know what it has in flight)");
Check.True(ActionPacer.MayStart(off, "Combat", HealNeed.None, out _), "and nothing is held");
Paced(() =>
{
var host = World();
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "free before the ask");
Check.True(ActionPacer.HoldForPlayer(host, 1500), "the ask is taken");
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string why), "a buff cast waits");
Check.True(why.Contains("key press"), "and says why: " + why);
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.Emergency, out _), "an emergency heal waits too (the press is the player's choice)");
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "an attack repeat waits");
Check.True(ActionPacer.GestureHolds(host, "Loot", HealNeed.None, out _), "the item managers' moves wait");
FakeHost.CombatModeRequests.Clear();
Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand"), "a stance change is held");
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "and not sent");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("the player's turn: a key press")), 1, "the hold logged once");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Pace] Buff waits: the player's key press goes first")), 1, "each subsystem's wait logged once");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Pace] mode:Buff waits: the player's key press")), 1, "the held stance change its own line");
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "asked again: still held");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Pace] Buff waits: the player's key press")), 1, "not logged again");
// Renewed: the newest ask sets the end.
_t += 1000;
Check.True(ActionPacer.HoldForPlayer(host, 1500), "asked again a second later");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("the player's turn: a key press")), 1, "a renewal is the same hold");
_t += 1400;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "2.4 s in, 1.4 s after the renewal: held");
_t += 200;
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "the asker stopped asking: the hold ends by itself");
Check.Eq(ActionPacer.PlayerHolds, 1L, "one hold counted");
// Capped at PlayerHoldMaxMs whatever is asked.
Check.True(ActionPacer.HoldForPlayer(host, 60_000), "a long ask");
_t += ActionPacer.PlayerHoldMaxMs - 1;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "held up to the cap");
_t += 2;
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "free past it");
// Released early: free at once, logged.
Check.True(ActionPacer.HoldForPlayer(host, 1500), "a third hold");
ActionPacer.ReleasePlayerHold(host);
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "released: free at once");
Check.True(Logged("the player's turn is over"), "the release logged");
int lines = FakeHost.Logs.Count;
ActionPacer.ReleasePlayerHold(host);
Check.Eq(FakeHost.Logs.Count, lines, "a second release says nothing");
// What is already out finishes: a hold doesn't touch the outstanding action.
Check.True(host.UseFor(Corpse, "Loot", "open the claimed corpse"), "a corpse open goes out");
Check.True(ActionPacer.HoldForPlayer(host, 1500), "then the press takes the turn");
Check.True(ActionPacer.Current(host) != null, "the corpse open is still RynthAi's outstanding action");
});
}
private static void UseAnswers() => Paced(() => private static void UseAnswers() => Paced(() =>
{ {
var host = World(); var host = World();

View file

@ -15,6 +15,8 @@ internal static class ActivityInterfaceTests
r.Add("activity: each arbiter decision maps to its own bit", ArbiterBits); r.Add("activity: each arbiter decision maps to its own bit", ArbiterBits);
r.Add("activity: corpse, salvage queue, server wait, crafting and AutoCram add their bits", ExtraBits); r.Add("activity: corpse, salvage queue, server wait, crafting and AutoCram add their bits", ExtraBits);
r.Add("activity: the table answers only its own name and versions", QueryTable); r.Add("activity: the table answers only its own name and versions", QueryTable);
r.Add("activity: RynthAi's own unanswered action has its own bit (PacedAction), apart from the busy count", PacedBit);
r.Add("yield: the RynthAi.Yield table answers only its own name and versions; nothing held before login", YieldTable);
} }
private static void ArbiterBits() private static void ArbiterBits()
@ -70,4 +72,37 @@ internal static class ActivityInterfaceTests
ActivityInterface.Release(); ActivityInterface.Release();
} }
} }
private static void PacedBit()
{
RynthAiActivity f = ActivityInterface.Compose(BotActivity.Buffing, true, false, false, serverWait: true, false, false, pacedWait: true);
Check.Eq(f, RynthAiActivity.MacroRunning | RynthAiActivity.Buffing | RynthAiActivity.ServerAction | RynthAiActivity.PacedAction,
"a cast of RynthAi's out: waiting on the server, and its own action");
f = ActivityInterface.Compose(BotActivity.Idle, false, false, false, serverWait: true, false, false);
Check.Eq(f, RynthAiActivity.ServerAction, "only the busy count up (a leftover): no PacedAction");
Check.Eq((uint)RynthAiActivity.PacedAction, 1u << 9, "the next free bit, after AutoCram");
}
private static unsafe void YieldTable()
{
try
{
Check.True(YieldInterface.Query(RynthAiActivityApiV1.InterfaceName, 1) == IntPtr.Zero, "another interface's name");
Check.True(YieldInterface.Query(RynthAiYieldApiV1.InterfaceName, 0) == IntPtr.Zero, "version 0");
Check.True(YieldInterface.Query(RynthAiYieldApiV1.InterfaceName, 2) == IntPtr.Zero, "a newer version than RynthAi has");
IntPtr p = YieldInterface.Query(RynthAiYieldApiV1.InterfaceName, 1);
Check.True(p != IntPtr.Zero, "v1 answers");
var t = (RynthAiYieldApiV1*)p;
Check.Eq(t->Version, 1u, "table version");
Check.Eq(t->StructSize, (uint)sizeof(RynthAiYieldApiV1), "table size");
Check.True(t->HoldForPlayer != null && t->ReleaseHold != null, "functions filled in");
Check.True(YieldInterface.Query(RynthAiYieldApiV1.InterfaceName, 1) == p, "the same table on every call");
Check.Eq(t->HoldForPlayer(1500), 0, "no logged-in plugin: nothing held");
Check.Eq(t->ReleaseHold(), 1, "a release with nothing held is fine");
}
finally
{
YieldInterface.Release();
}
}
} }

View file

@ -78,6 +78,7 @@ internal static class BuffTests
r.Add("buff timers: tier-8 weapon auras last 90 minutes", TierEightAuras); // was a known failure; fixed by 9a317a8 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.Add("buff chat: another player's speech can't record a buff timer", SpeechIsNotACast); // was a known failure; fixed by 0e384d2
r.Add("buff school: Armor Tinkering Expertise is a Creature Enchantment spell", ArmorTinkeringSchool); // was a known failure r.Add("buff school: Armor Tinkering Expertise is a Creature Enchantment spell", ArmorTinkeringSchool); // was a known failure
r.Add("mana floor: under Get Mana At with nothing to refill mana, buffs go on while a heal's mana is kept (R-20261029-103248-ce48)", ManaFloorNoRefill);
r.Add("buff upgrade: in a force run, the priority buffs go first, then the families cast before the skill rose are recast a level higher", UpgradeInRun); r.Add("buff upgrade: in a force run, the priority buffs go first, then the families cast before the skill rose are recast a level higher", UpgradeInRun);
r.Add("buff upgrade: the next pass recasts every buff a level higher once the skill allows it; equal level or a lower skill casts nothing", UpgradeNextPass); r.Add("buff upgrade: the next pass recasts every buff a level higher once the skill allows it; equal level or a lower skill casts nothing", UpgradeNextPass);
r.Add("buff upgrade: a higher level learned from a scroll is cast at once (the spellbook is read again)", UpgradeAfterScroll); r.Add("buff upgrade: a higher level learned from a scroll is cast at once (the spellbook is read again)", UpgradeAfterScroll);
@ -1219,6 +1220,85 @@ internal static class BuffTests
Check.True(line.Contains("level 6 -> 7 (Incantation of Strength Self)"), "the line says 6 -> 7, the level counted: " + line); Check.True(line.Contains("level 6 -> 7 (Incantation of Strength Self)"), "the line says 6 -> 7, the level counted: " + line);
} }
// A report (DreamWeave, 2026-10-29: "Buffing seems to be getting stuck"): logged in at
// 209/207 mana, the first buffs took max mana to 536, the same 209 read 39% under Get Mana At
// 40%, and with no Stamina to Mana known and no mana potion every buff after waited on regen.
private static BuffRig FloorRig(bool knowStaminaToMana, uint mana, uint stamina = 383)
{
FakeHost.Reset();
foreach (var row in SpellTable.Rows)
if (knowStaminaToMana || !row.Name.StartsWith("Stamina to Mana", StringComparison.Ordinal))
FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeCreature)] = (300, 2);
FakeHost.Skills[(Player, STypeLife)] = (300, 2);
FakeHost.Skills[(Player, STypeItem)] = (300, 2);
FakeHost.WeaponCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
var rig = new BuffRig();
rig.B.SetWorldObjectCache(FakeHost.MakeCache(rig.Host, Player, Array.Empty<uint>()));
BuffManager.ManaCostOverride = id => LevelOf(id) * 10;
rig.S.IsMacroRunning = true;
rig.S.SpellCastIntervalMs = 0;
rig.S.GetManaAt = 40; rig.S.TopOffMana = 40;
rig.S.HealAt = 0; rig.S.TopOffHP = 0; rig.S.EmergencyHealAt = 0; rig.S.StaminaToHealthAt = 0;
rig.S.RestamAt = 0; rig.S.TopOffStam = 0; rig.S.UsePotions = false;
rig.V.MaxHealth = 400; rig.V.CurrentHealth = 400;
rig.V.MaxStamina = 383; rig.V.CurrentStamina = stamina;
rig.V.MaxMana = 536; rig.V.CurrentMana = mana;
var at = FakeClock(rig);
at(0);
rig.B.MarkLiveBuffsReadyForTests();
rig.Live(("Strength Self I", 3000));
rig.B.ForceFullRebuff();
return rig;
}
private static int FloorBeats(BuffRig rig, int n)
{
int before = FakeHost.Casts.Count;
for (int i = 0; i < n; i++)
{
rig.B.OnHeartbeat();
if (FakeHost.Casts.Count > before)
{
int id = FakeHost.Casts.Last().SpellId;
rig.B.OnChatWindowText($"You cast {NameOf(id)} on {(BuffManager.IsItemEnchantment(NameOf(id)) ? "Rune Robe" : "yourself")}", 7);
SetFld(rig.B, "_lastCastAttempt", DateTime.Now.AddSeconds(-10));
SetFld(rig.B, "_lastSelfBuffPollAt", DateTime.MinValue);
}
}
return FakeHost.Casts.Count - before;
}
private static void ManaFloorNoRefill()
{
// The report: 209/536 (39%), Get Mana At 40%, no Stamina to Mana, no potion. Buffs go.
var r = FloorRig(knowStaminaToMana: false, mana: 209);
int keep = r.B.ManaFloorHealReserve();
Check.True(keep > 0, $"a heal's mana is kept ({keep})");
int sent = FloorBeats(r, 6);
Check.True(sent > 0, $"buffs are cast under the floor (sent {sent}, last skip: {r.B.LastBuffSkipReason})");
Check.True(FakeHost.Casts.All(c => !NameOf(c.SpellId).StartsWith("Stamina to Mana", StringComparison.Ordinal)), "no Stamina to Mana (none is known)");
Check.True(FakeHost.Logs.Count(l => l.Contains("nothing can refill it") && l.Contains("buffing goes on")) == 1, "logged once");
// Down near the heal reserve: buffing waits, and the line names every source's reason.
var low = FloorRig(knowStaminaToMana: false, mana: (uint)(keep + 10));
Check.Eq(FloorBeats(low, 6), 0, "under a heal's mana plus a buff: buffing waits");
string line = FakeHost.Logs.LastOrDefault(l => l.Contains("buffing waits: mana")) ?? "";
Check.True(line.Contains("Stamina to Mana: no known") && line.Contains("mana potion: Use Potions is off") && line.Contains("for healing"),
"the line gives each reason: " + line);
// Stamina to Mana known, stamina under its line: the floor still refills first, as before
// (Revitalize for stamina, then Stamina to Mana); no buff goes while it can refill.
var s2m = FloorRig(knowStaminaToMana: true, mana: 209, stamina: 20);
FloorBeats(s2m, 6);
var sentNames = FakeHost.Casts.Select(c => NameOf(c.SpellId)).ToList();
Check.True(sentNames.Count > 0 && sentNames.All(n => n.StartsWith("Revitalize", StringComparison.Ordinal) || n.StartsWith("Stamina to Mana", StringComparison.Ordinal)
|| n.Contains("Revitalize") || n.Contains("Stamina to Mana")),
"Stamina to Mana known: only refills go, no buff: " + string.Join(", ", sentNames));
Check.Eq(FakeHost.Logs.Count(l => l.Contains("buffing goes on")), 0, "the no-refill path isn't taken");
}
private static T Fld<T>(BuffManager b, string name) => (T)typeof(BuffManager).GetField(name, BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(b)!; private static T Fld<T>(BuffManager b, string name) => (T)typeof(BuffManager).GetField(name, BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(b)!;
private static void SetFld(BuffManager b, string name, object v) => typeof(BuffManager).GetField(name, BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(b, v); private static void SetFld(BuffManager b, string name, object v) => typeof(BuffManager).GetField(name, BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(b, v);

View file

@ -757,6 +757,7 @@ internal static class LootCorpseTests
FakeHost.CastBusy = 0; FakeHost.CastBusy = 0;
TickFor(bot, retryWindowMs / 2); TickFor(bot, retryWindowMs / 2);
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the retry window counts from when the character is still"); Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the retry window counts from when the character is still");
// (Also past the 4 s answer wait from the send by now: R-20261029-122319-321f.)
TickFor(bot, retryWindowMs); TickFor(bot, retryWindowMs);
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 2, "then one retry"); Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 2, "then one retry");
} }
@ -765,6 +766,8 @@ internal static class LootCorpseTests
// contents unknown to the client), 3 tries each, and every item on every corpse was skipped. // contents unknown to the client), 3 tries each, and every item on every corpse was skipped.
// A pack that takes none of an item's tries now counts as full for a while: the item gets one // A pack that takes none of an item's tries now counts as full for a while: the item gets one
// more round into another pack, and with none left looting stops with the pack-full message. // more round into another pack, and with none left looting stops with the pack-full message.
// 2026-10-29 (R-20261029-122319-321f): only the server's refusals mark a pack full, so the
// refusals are given here (unanswered tries: LootRetryTimingTests).
private static void RefusingPackIsLeftOut() private static void RefusingPackIsLeftOut()
{ {
var refusals = new RynthCore.Plugin.RynthAi.Loot.PackRefusals(); var refusals = new RynthCore.Plugin.RynthAi.Loot.PackRefusals();
@ -776,6 +779,7 @@ internal static class LootCorpseTests
Check.False(refusals.IsRefused(8, 1), "an item landing there ends the hold"); Check.False(refusals.IsRefused(8, 1), "an item landing there ends the hold");
BaseWorld(corpsePositioned: true); BaseWorld(corpsePositioned: true);
FakeHost.WeenieErrorCalls = true; // the server's refusals (2026-10-29: only they mark a pack full)
var host = FakeHost.Create(Player); var host = FakeHost.Create(Player);
var bot = new Bot(host); var bot = new Bot(host);
bot.Cache.OnCreateObject(Corpse); bot.Cache.OnCreateObject(Corpse);
@ -785,10 +789,25 @@ internal static class LootCorpseTests
bot.Cache.Tick(); bot.Cache.Tick();
bot.P.OnViewObjectContents(Corpse); bot.P.OnViewObjectContents(Corpse);
// The main pack (the only destination here) never takes the gem: it stays on the corpse. // The main pack (the only destination here) never takes the gem: it stays on the corpse,
int retryWindowMs = bot.S.LootRetryTimeoutMs; // and the server refuses each move once its pickup has run (~0.8 s: "Unable to put X into
TickFor(bot, retryWindowMs * 4 + 600); // container" + InventoryServerSaveFailed with no error code).
Check.True(FakeHost.ExternalMoves.Count(m => m.Id == Gem) >= 3, "three tries into the main pack"); int seen = 0;
var refuseAt = new List<long>();
long end = Environment.TickCount64 + 6000;
while (Environment.TickCount64 < end && !FakeHost.Logs.Any(l => l.Contains("no pack has a free slot")))
{
for (; seen < FakeHost.ExternalMoves.Count; seen++)
if (FakeHost.ExternalMoves[seen].Id == Gem) refuseAt.Add(Environment.TickCount64 + 800);
while (refuseAt.Count > 0 && Environment.TickCount64 >= refuseAt[0])
{
refuseAt.RemoveAt(0);
FakeHost.WeenieError(0, 0x00A0, Gem);
}
bot.Tick(BotActivity.Looting);
Thread.Sleep(10);
}
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 3, "three tries into the main pack, each after the last one's refusal");
Check.True(FakeHost.ExternalMoves.Where(m => m.Id == Gem).All(m => m.Target == Player), "all into the main pack"); Check.True(FakeHost.ExternalMoves.Where(m => m.Id == Gem).All(m => m.Target == Player), "all into the main pack");
Check.True(FakeHost.Logs.Any(l => l.Contains("took none of 3 tries") && l.Contains("trying another pack")), "the refusing pack is left out, said once"); Check.True(FakeHost.Logs.Any(l => l.Contains("took none of 3 tries") && l.Contains("trying another pack")), "the refusing pack is left out, said once");
Check.True(FakeHost.Logs.Any(l => l.Contains("no pack has a free slot")), "no other pack: the corpse is left"); Check.True(FakeHost.Logs.Any(l => l.Contains("no pack has a free slot")), "no other pack: the corpse is left");
@ -827,9 +846,10 @@ internal static class LootCorpseTests
for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == Gem); i++) { t += 50; bot.Tick(BotActivity.Looting); Thread.Sleep(10); } for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == Gem); i++) { t += 50; bot.Tick(BotActivity.Looting); Thread.Sleep(10); }
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the pickup goes on the cast's UseDone"); Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the pickup goes on the cast's UseDone");
// The item stays on the corpse (refused); the next cast is unanswered when a retry is due. // The item stays on the corpse (no answer); the next cast is unanswered when a retry is
// due (after the answer wait, 2026-10-29: R-20261029-122319-321f).
ActionPacer.Begin(host, PacedKind.Cast, 0, "Bloodstone Bolt I", "Combat", FakeHost.UseDoneSeq); ActionPacer.Begin(host, PacedKind.Cast, 0, "Bloodstone Bolt I", "Combat", FakeHost.UseDoneSeq);
TickFor(bot, 1_500); TickFor(bot, (int)RynthAiPlugin.PickupAnswerWaitMinMs + bot.S.LootRetryTimeoutMs + 500);
Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "no retry while a cast is unanswered"); Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "no retry while a cast is unanswered");
FakeHost.UseDone(0); FakeHost.UseDone(0);
TickFor(bot, 300); TickFor(bot, 300);

View file

@ -0,0 +1,473 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// R-20261029-122319-321f (Conquest, RynthAi 2026.10.29.1): "If max loot attempts are reached it
// locks up on looting other items". A pack move was retried every ~0.5 s once the character stood
// still, and after 3 tries (~1.6 s) the pack counted as full for 5 min. That server answered a
// pickup 1.5-2.7 s after the send (one confirmation landed after attempt 3 had gone out), and a
// resend while a move is out is dropped by the client (one pending inventory request) or turned
// away by ACE as too busy. Side packs were marked full one after another until looting stopped.
// Also: a full main pack's refusals (InventoryServerSaveFailed, "error 0x0") were all taken for
// "too busy" and resent for free, 6 sends over 18 s.
// The server is simulated (SlowAce): a 1.7 s pickup motion, room per pack, refusals for room only
// after the motion, "too busy" on arrival, the queued move behind a Return, and the client's own
// one-request slot (a move sent while the last is unanswered never leaves the client).
// The loot clock (CorpseOpenController.CorpseClock) is moved by hand.
internal static class LootRetryTimingTests
{
private const uint Player = 0x50000D31;
private const uint Corpse = 0x80263100;
private const uint SidePack = 0x80263001;
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800;
private const uint LongDescKey = 16, ItemsCapacityKey = 6;
private const string Me = "Brannoc Vell";
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private const long TickMs = 25;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
public static void Register(Runner r)
{
r.Add("loot retry (R-20261029-122319-321f): with 1.7 s answers no move is resent while one is out, no pack is marked full, every item lands", SlowServerNoFalseFull);
r.Add("loot retry (R-20261029-122319-321f): a full main pack's refusals after the pickup count as tries (no free resends) and mark it full; the items go to the side pack", FullMainPackRefusals);
r.Add("loot retry (R-20261029-122319-321f): unanswered moves are retried only after the answer wait; their pack marks end with the item, the next item starts fresh", UnansweredMovesDontPoison);
r.Add("loot retry (R-20261029-122319-321f): an item that lands late, after its pack was given up on, un-marks that pack", LateLandingUnmarks);
r.Add("loot retry (R-20261029-122319-321f): a refusal on arrival is 'too busy' (free resend), one after the pickup is the pack's answer", RefusalTiming);
r.Add("loot retry (R-20261029-122319-321f): the answer wait grows with the server's measured answers, within 4-8 s", AnswerWaitAdapts);
r.Add("loot retry (R-20261029-122319-321f): PackRefusals keeps confirmed marks and drops the unconfirmed ones with the item", PackRefusalMarks);
}
// ── Clock and world ───────────────────────────────────────────────────────
private static long _now;
private static void Clocked(Action body)
{
var old = RynthAiPlugin.CorpseClock;
_now = 70_000_000;
RynthAiPlugin.CorpseClock = () => _now;
try { body(); }
finally { RynthAiPlugin.CorpseClock = old; }
}
private static void World(bool sidePack, params uint[] gems)
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId
FakeHost.ServerGates = true; // GetCastBusyState (the pickup motions)
FakeHost.WeenieErrorCalls = true; // GetLastWeenieError (the refusals)
FakeHost.Names[Player] = Me;
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
FakeHost.Names[Corpse] = "Corpse of Brier Wasp";
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
FakeHost.NotAttackable.Add(Corpse);
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
if (sidePack)
{
FakeHost.Names[SidePack] = "Backpack";
FakeHost.ItemTypes[SidePack] = ItemTypeContainer;
FakeHost.Ints[(SidePack, ItemsCapacityKey)] = 24;
FakeHost.Containers[SidePack] = Player;
}
foreach (uint g in gems)
{
FakeHost.Names[g] = $"Gem {g & 0xFF}";
FakeHost.ItemTypes[g] = ItemTypeGem;
FakeHost.Containers[g] = Corpse;
FakeHost.Appraised.Add(g);
}
}
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new()
{
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
};
public readonly WorldObjectCache Cache;
public SlowAce? Sim;
public Bot(RynthCoreHost host)
{
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
Cache = new WorldObjectCache(host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
string profile = Path.Combine(Program.TempRoot, "loot-retry-timing.json");
var p = new LootProfile { Name = "gems" };
var rule = new LootRule { Name = "Gems", Action = LootAction.Keep };
rule.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
p.Rules.Add(rule);
p.Save(profile);
S.CurrentLootPath = profile;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
/// <summary>One plugin tick: the clock moves on, the simulated server catches up, the looter runs.</summary>
public void Tick()
{
_now += TickMs;
Sim?.Step(_now);
Set("_activity", BotActivity.Looting);
Call("TickCorpseOpening");
}
public void TickUntil(Func<bool> done, long maxMs)
{
long end = _now + maxMs;
while (_now < end && !done()) Tick();
}
public int MovesOf(uint id) => FakeHost.ExternalMoves.Count(m => m.Id == id);
public RynthCore.Plugin.RynthAi.Loot.PackRefusals Refusals => Get<RynthCore.Plugin.RynthAi.Loot.PackRefusals>("_packRefusals");
public bool Completed => Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)Corpse));
}
/// <summary>
/// ACE's pickup (Player_Inventory.cs): the move arrives, the pickup motion plays (PickupMs), then
/// the item goes into the pack or, with no room there, "Unable to put X into container" +
/// InventoryServerSaveFailed(item, no error code); then the Return. A move arriving during the
/// Return is queued (NextPickup), one during the motion is "You're too busy". The client keeps
/// one pending inventory request: a move sent while one is unanswered never leaves the client.
/// <see cref="Lag"/>: extra delay before the server takes up an item's first move (a lag spike);
/// <see cref="NeverAnswer"/>: items whose moves the server never answers. The engine empties a
/// pending request that has had no answer for 10 s (ClientActionGates.PendingTimeoutMs).
/// </summary>
private sealed class SlowAce
{
public long Rtt = 200, PickupMs = 1700, ReturnMs = 740;
public readonly Dictionary<uint, int> Room = new(); // the server's free slots per pack (absent: plenty)
public readonly Dictionary<uint, long> Lag = new();
public readonly HashSet<uint> NeverAnswer = new();
public long ClientPendingTimeoutMs = 10_000;
public int TooBusy, LocalRefused, Queued, RoomRefusals;
public readonly List<(uint Id, uint Pack, long At)> Landed = new();
private enum St { Idle, Pickup, Return }
private St _st;
private (uint Id, uint Pack) _next;
private int _seenMoves;
private uint _clientPending;
private long _clientPendingAt;
private readonly List<(long At, int Seq, Action Act)> _events = new();
private int _seq;
private void At(long at, Action act) => _events.Add((at, _seq++, act));
public void Step(long now)
{
while (_seenMoves < FakeHost.ExternalMoves.Count)
{
var m = FakeHost.ExternalMoves[_seenMoves++];
if (_clientPending != 0 && now - _clientPendingAt >= ClientPendingTimeoutMs) _clientPending = 0; // the engine lets it go
if (_clientPending != 0) { LocalRefused++; continue; } // "You can only move or use one item at a time"
_clientPending = m.Id;
_clientPendingAt = now;
if (NeverAnswer.Contains(m.Id)) continue;
long arrive = now - TickMs + Rtt / 2;
if (Lag.Remove(m.Id, out long lag)) arrive += lag;
At(arrive, () => Receive(m.Id, m.Target, arrive));
}
while (true)
{
var due = _events.Where(e => e.At <= now).OrderBy(e => e.At).ThenBy(e => e.Seq).ToList();
if (due.Count == 0) break;
var e = due[0];
_events.Remove(e);
e.Act();
}
}
private void Answered(uint id) { if (_clientPending == id) _clientPending = 0; }
private void Receive(uint id, uint pack, long ts)
{
if (_st == St.Idle) { StartPickup(id, pack, ts); return; }
if (_st == St.Return && _next.Id == 0) { _next = (id, pack); Queued++; return; }
TooBusy++;
At(ts + Rtt / 2, () =>
{
FakeHost.WeenieError(0x1D); // YoureTooBusy
FakeHost.WeenieError(0, 0x00A0, id); // InventoryServerSaveFailed(item)
Answered(id);
});
}
private void StartPickup(uint id, uint pack, long ts)
{
_st = St.Pickup;
At(ts + Rtt / 2, () => FakeHost.CastBusy = 1);
At(ts + PickupMs, () => Finish(id, pack, ts + PickupMs));
}
private void Finish(uint id, uint pack, long ts)
{
_st = St.Return;
if (Room.TryGetValue(pack, out int free) && free <= 0)
{
RoomRefusals++;
At(ts + Rtt / 2, () =>
{
FakeHost.WeenieError(0, 0x00A0, id); // "Unable to put X into container" + save failed, no code
Answered(id);
});
}
else
{
if (Room.ContainsKey(pack)) Room[pack] = free - 1;
At(ts + Rtt / 2, () =>
{
FakeHost.Containers[id] = pack;
Landed.Add((id, pack, ts + Rtt / 2));
Answered(id);
});
}
At(ts + ReturnMs, () => ReturnDone(ts + ReturnMs));
}
private void ReturnDone(long ts)
{
if (_next.Id != 0)
{
var n = _next;
_next = default;
StartPickup(n.Id, n.Pack, ts);
return;
}
_st = St.Idle;
At(ts + Rtt / 2, () => FakeHost.CastBusy = 0);
}
}
/// <summary>Claims and opens the corpse (the server's ViewContents), with the side pack known to the cache.</summary>
private static Bot Open(SlowAce sim, bool sidePack, params uint[] gems)
{
var host = FakeHost.Create(Player);
var bot = new Bot(host) { Sim = sim };
var ids = new List<uint> { Corpse };
if (sidePack) ids.Add(SidePack);
ids.AddRange(gems);
foreach (uint id in ids) bot.Cache.OnCreateObject(id);
for (int i = 0; i < 50; i++) bot.Cache.Tick();
if (sidePack)
Check.True(bot.Cache.GetDirectInventory(forceRefresh: true).Any(o => o.Id == unchecked((int)SidePack) && o.ObjectClass == AcObjectClass.Container),
"the side pack is in the inventory as a container");
bot.Tick();
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
FakeHost.UseDone(0);
FakeHost.GroundContainer = Corpse;
bot.P.OnViewObjectContents(Corpse);
return bot;
}
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
/// <summary>Ticks until <paramref name="done"/>, noting the clock at each new move.</summary>
private static List<(uint Id, long At)> Run(Bot bot, Func<bool> done, long maxMs)
{
var sends = new List<(uint, long)>();
int seen = FakeHost.ExternalMoves.Count;
long end = _now + maxMs;
while (_now < end && !done())
{
bot.Tick();
while (seen < FakeHost.ExternalMoves.Count) sends.Add((FakeHost.ExternalMoves[seen++].Id, _now));
}
return sends;
}
// ── 1. A slow server, room everywhere ─────────────────────────────────────
private static void SlowServerNoFalseFull() => Clocked(() =>
{
const uint G1 = 0x80263101, G2 = 0x80263102, G3 = 0x80263103, G4 = 0x80263104;
World(sidePack: true, G1, G2, G3, G4);
var sim = new SlowAce();
var bot = Open(sim, sidePack: true, G1, G2, G3, G4);
Run(bot, () => bot.Completed, 60_000);
foreach (uint g in new[] { G1, G2, G3, G4 })
{
Check.Eq(bot.MovesOf(g), 1, $"0x{g:X8} is sent once: its answer (~1.8 s, or behind the last Return) is waited for");
Check.True(sim.Landed.Any(l => l.Id == g), $"0x{g:X8} lands");
}
Check.Eq(sim.LocalRefused, 0, "no move sent while another was unanswered (the client would drop it)");
Check.Eq(sim.TooBusy, 0, "no 'too busy' from the server");
Check.False(Logged("took none of"), "no pack judged full");
Check.False(Logged("pickup failed"), "nothing given up on");
Check.False(Logged("retrying use"), "no retries at all");
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), "the main pack is not marked");
Check.True(bot.Completed, "the corpse is finished");
});
// ── 2. The main pack is full (the client counts room) ─────────────────────
private static void FullMainPackRefusals() => Clocked(() =>
{
const uint Map = 0x80263111, G2 = 0x80263112;
World(sidePack: true, Map, G2);
var sim = new SlowAce();
sim.Room[Player] = 0; // the server's main pack is full; the client's count says room
var bot = Open(sim, sidePack: true, Map, G2);
Run(bot, () => bot.Completed, 60_000);
var mapMoves = FakeHost.ExternalMoves.Where(m => m.Id == Map).ToList();
Check.Eq(mapMoves.Count(m => m.Target == Player), 3, "three tries into the main pack (each refused after the pickup ran), no free resends");
Check.False(Logged("as too busy"), "a refusal after the pickup is not taken for 'too busy'");
Check.True(Logged("the main pack took none of 3 tries") && Logged("the server refused 3 after the pickup ran") && Logged("treating it as full"),
"the main pack is judged full on the server's refusals");
Check.True(mapMoves.Last().Target == SidePack && sim.Landed.Any(l => l.Id == Map && l.Pack == SidePack), "then the map goes into the side pack and lands");
Check.True(FakeHost.ExternalMoves.Where(m => m.Id == G2).All(m => m.Target == SidePack), "the next item goes straight to the side pack");
Check.True(sim.Landed.Any(l => l.Id == G2), "and lands");
Check.True(bot.Refusals.IsConfirmed(unchecked((int)Player), _now), "the main pack stays marked (confirmed by the server)");
Check.False(bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "the side pack is not marked");
Check.Eq(sim.LocalRefused, 0, "no move sent while another was unanswered");
});
// ── 3. Moves the server never answers ─────────────────────────────────────
private static void UnansweredMovesDontPoison() => Clocked(() =>
{
const uint Lost = 0x80263121, Next = 0x80263122;
World(sidePack: true, Lost, Next);
var sim = new SlowAce();
sim.NeverAnswer.Add(Lost); // the server never answers the lost item's moves
var bot = Open(sim, sidePack: true, Lost, Next);
var sends = Run(bot, () => bot.Completed, 90_000).Where(s => s.Id == Lost).ToList();
var lostMoves = FakeHost.ExternalMoves.Where(m => m.Id == Lost).ToList();
Check.Eq(lostMoves.Count, 6, "three tries into the main pack, three into the side pack");
var gaps = sends.Zip(sends.Skip(1), (a, b) => b.At - a.At).ToList();
Check.True(gaps.Count > 0 && gaps.All(g => g >= RynthAiPlugin.PickupAnswerWaitMinMs - TickMs),
$"each retry only after the answer wait ({string.Join(", ", gaps)} ms)");
Check.True(Logged("trying another pack for this item only"), "the main pack is left out for this item only");
Check.False(Logged("treating it as full"), "no pack is judged full on unanswered tries");
Check.True(Logged("pickup failed for 0x80263121"), "the item is given up after the second round");
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), "the main pack's mark ended with the item");
Check.False(bot.Refusals.IsRefused(unchecked((int)SidePack), _now), "so did the side pack's");
Check.True(FakeHost.ExternalMoves.Where(m => m.Id == Next).All(m => m.Target == Player), "the next item goes into the main pack again");
Check.True(sim.Landed.Any(l => l.Id == Next && l.Pack == Player), "and lands there");
Check.False(Logged("pickup failed for 0x80263122"), "the next item is not given up on");
Check.False(Logged("no pack has a free slot"), "looting does not stop for want of a pack");
});
// ── 4. A late landing ─────────────────────────────────────────────────────
private static void LateLandingUnmarks() => Clocked(() =>
{
const uint Slow = 0x80263131, Next = 0x80263132;
World(sidePack: true, Slow, Next);
var sim = new SlowAce();
sim.Lag[Slow] = 12_500; // a lag spike: the server takes up the first move 12.5 s late
var bot = Open(sim, sidePack: true, Slow, Next);
Run(bot, () => bot.Completed, 90_000);
Check.True(sim.Landed.Any(l => l.Id == Slow && l.Pack == Player), "the first move lands in the main pack, late");
Check.True(Logged("trying another pack for this item only"), "after three unanswered tries the main pack was left out for the item");
Check.True(Logged("0x80263131 landed in the main pack; it has room after all and is no longer treated as full"), "the late landing un-marks the main pack");
Check.False(bot.Refusals.IsRefused(unchecked((int)Player), _now), "the main pack is not marked");
Check.True(sim.Landed.Any(l => l.Id == Next), "the next item lands too");
Check.False(Logged("pickup failed for 0x80263132"), "the next item is not given up on");
Check.False(Logged("no pack has a free slot"), "looting does not stop");
Check.Eq((long)bot.Call("PickupAnswerWaitMs")!, RynthAiPlugin.PickupAnswerWaitMinMs,
"the lag spike's late answer (to an earlier, timed-out send) does not stretch the answer wait");
});
// ── 5. Busy or room ───────────────────────────────────────────────────────
private static void RefusalTiming() => Clocked(() =>
{
const uint G1 = 0x80263141;
World(sidePack: false, G1);
var bot = Open(new SlowAce(), sidePack: false, G1);
bot.Sim = null; // the answers are given by hand here
bot.TickUntil(() => bot.MovesOf(G1) > 0, 2000);
Check.Eq(bot.MovesOf(G1), 1, "the move is sent");
// Refused on arrival (ACE: YoureTooBusy, then InventoryServerSaveFailed with no code; the
// engine keeps the last one, error 0x0): a free resend once still.
bot.Tick();
FakeHost.WeenieError(0x1D);
FakeHost.WeenieError(0, 0x00A0, G1);
bot.TickUntil(() => bot.MovesOf(G1) > 1, 1000);
Check.Eq(bot.MovesOf(G1), 2, "resent at once");
Check.True(Logged("the server refused 0x80263141 as too busy"), "logged as too busy");
Check.Eq(bot.Get<int>("_currentLootItemMoveAttempts"), 1, "not one of the 3 tries");
// Refused after its pickup ran (no room; the same error 0x0): one of the tries.
FakeHost.CastBusy = 1;
bot.TickUntil(() => false, 1800);
FakeHost.WeenieError(0, 0x00A0, G1);
bot.Tick();
FakeHost.CastBusy = 0;
bot.TickUntil(() => bot.MovesOf(G1) > 2, 3000);
Check.Eq(bot.MovesOf(G1), 3, "sent again after the retry window");
Check.Eq(bot.Get<int>("_currentLootItemMoveAttempts"), 2, "counted as a try");
Check.True(Logged("retrying use for 0x80263141 attempt 2 (last: refused"), "logged as refused after its pickup ran");
Check.Eq(bot.Get<int>("_currentLootItemDestRefusals"), 1, "and it counts against the main pack (the busy one does not)");
});
// ── 6. The wait itself ────────────────────────────────────────────────────
private static void AnswerWaitAdapts() => Clocked(() =>
{
World(sidePack: false);
var bot = new Bot(FakeHost.Create(Player));
long Wait() => (long)bot.Call("PickupAnswerWaitMs")!;
Check.Eq(Wait(), RynthAiPlugin.PickupAnswerWaitMinMs, "4 s with nothing measured");
foreach (long ms in new long[] { 1500, 1657, 2735 }) bot.Call("NotePickupAnswerLatency", ms);
Check.Eq(Wait(), 2735 + RynthAiPlugin.PickupAnswerWaitMarginMs, "the slowest answer (2.7 s, Conquest's queued pickups) plus 1.5 s");
bot.Call("NotePickupAnswerLatency", 20_000L);
Check.Eq(Wait(), RynthAiPlugin.PickupAnswerWaitMaxMs, "at most 8 s");
for (int i = 0; i < 8; i++) bot.Call("NotePickupAnswerLatency", 800L);
Check.Eq(Wait(), RynthAiPlugin.PickupAnswerWaitMinMs, "the last 8 answers only, never under 4 s");
});
private static void PackRefusalMarks()
{
var r = new RynthCore.Plugin.RynthAi.Loot.PackRefusals();
r.Refuse(1, 0, confirmed: true);
r.Refuse(2, 0, confirmed: false);
Check.True(r.IsRefused(1, 10) && r.IsConfirmed(1, 10), "a confirmed mark");
Check.True(r.IsRefused(2, 10) && !r.IsConfirmed(2, 10), "an unconfirmed mark is left out too");
r.Refuse(1, 5, confirmed: false);
Check.True(r.IsConfirmed(1, 10), "a confirmed mark is not weakened by an unconfirmed one");
r.ClearUnconfirmed();
Check.True(r.IsRefused(1, 10), "the confirmed mark stays");
Check.False(r.IsRefused(2, 10), "the unconfirmed one goes with its item");
r.Accepted(1);
Check.False(r.IsRefused(1, 10), "an item landing there ends a confirmed mark");
}
}

View file

@ -54,6 +54,9 @@ internal static class SelfTestMetaTests
var cache = FakeHost.MakeCache(host, Player, new[] { buffBot }, new Dictionary<uint, float> { [buffBot] = 1f }); var cache = FakeHost.MakeCache(host, Player, new[] { buffBot }, new Dictionary<uint, float> { [buffBot] = 1f });
var r = new Run(host, cache, "T2 Fight"); var r = new Run(host, cache, "T2 Fight");
r.M.SetCombatTargetCount(() => targets); r.M.SetCombatTargetCount(() => targets);
// What the Default state sets before the run reaches the fight. It came from an earlier test's
// pvars file, which reached the disk only when its real-time save throttle allowed (a flake).
r.M.Expressions.Evaluate("setpvar[rt_fight,`PENDING`]");
return r; return r;
} }

View file

@ -54,6 +54,7 @@ internal static class WeaponTests
r.Add("slayer: read through the host (int 166, float 138, monster int 2), cached by wcid", SlayerFromHost); r.Add("slayer: read through the host (int 166, float 138, monster int 2), cached by wcid", SlayerFromHost);
r.Add("refusal: a refused stance change in combat's equip pass sets no backoff and starts no stuck clock", StanceRefusedKeepsBackoff); r.Add("refusal: a refused stance change in combat's equip pass sets no backoff and starts no stuck clock", StanceRefusedKeepsBackoff);
r.Add("weapon choice: an unlisted wand is never picked (Damage tab, learned, pack, name)", UnlistedNeverPicked); r.Add("weapon choice: an unlisted wand is never picked (Damage tab, learned, pack, name)", UnlistedNeverPicked);
r.Add("cast element: with the plan's wand not in hand (a held swap), the wand in hand casts its own element (R-20261029-125901-e22d)", HeldWandCastsItsElement);
r.Add("weapon choice: the Monsters rule's weapon is used (R-20261022-193411-fb72), below this monster's Damage tab pick; the Default row's like the Damage tab default", MonsterRuleWeapon); r.Add("weapon choice: the Monsters rule's weapon is used (R-20261022-193411-fb72), below this monster's Damage tab pick; the Default row's like the Damage tab default", MonsterRuleWeapon);
r.Add("Items list: a listed item no longer carried is reported missing (pack, hand, unknown)", MissingFromPack); r.Add("Items list: a listed item no longer carried is reported missing (pack, hand, unknown)", MissingFromPack);
r.Add("weapon choice: a listed weapon someone else now has (sold) is skipped, even as this monster's Damage tab pick", SoldWeaponSkipped); r.Add("weapon choice: a listed weapon someone else now has (sold) is skipped, even as this monster's Damage tab pick", SoldWeaponSkipped);
@ -888,6 +889,36 @@ internal static class WeaponTests
/// Lightning wand; the rule says the fire wand. Each step uses a new rule object, so PlanFor's /// Lightning wand; the rule says the fire wand. Each step uses a new rule object, so PlanFor's
/// cache (keyed on the rule by reference) doesn't hand back the previous answer. /// cache (keyed on the rule by reference) doesn't hand back the previous answer.
/// </summary> /// </summary>
// Conquest, 2026-10-29: "not swapping 0x80181B46 'Frost Sceptre' for 0x8024231C 'Acid Staff' yet
// (target at 23% health)", then Incantation of Acid Blast cast through the Frost Sceptre.
private static void HeldWandCastsItsElement()
{
var rig = new Rig(1535, "Ethereal Wisp");
rig.S.ItemRules.Add(new() { Id = unchecked((int)FireWand), Name = "Fire Wand", Element = "Fire", ElementSource = "icon" });
var rule = new MonsterRule { Name = "Ethereal" }; // damage type Auto
var pref = typeof(CombatManager).GetMethod("GetPreferredElement", BindingFlags.Instance | BindingFlags.NonPublic)!;
string Elem() => (string)pref.Invoke(rig.C, new object?[] { rig.Target, rule })!;
var plan = rig.C.PlanFor(rig.Target, rule);
Check.Eq(unchecked((uint)plan.WeaponId), ListedWand, "the plan: the Lightning wand (the weakness)");
rig.C.InHandOverride = () => unchecked((int)ListedWand);
Check.Eq(Elem(), "Lightning", "the plan's wand in hand: its element");
rig.C.InHandOverride = () => unchecked((int)FireWand); // the swap was held: the fire wand stays
Check.Eq(Elem(), "Fire", "the fire wand in hand casts Fire, not the plan's Lightning");
Check.True(FakeHost.Logs.Count(l => l.Contains("isn't in hand: casting Fire")) == 1, "logged once");
Elem();
Check.True(FakeHost.Logs.Count(l => l.Contains("isn't in hand: casting Fire")) == 1, "still once");
rig.C.CanCastOverride = e => e != "Nether" && e != "Fire"; // a wand whose element can't be cast
Check.Eq(Elem(), "Lightning", "an element the character can't cast: the plan's element");
rig.C.InHandOverride = () => 0; // nothing readable in hand
rig.C.CanCastOverride = e => e != "Nether";
Check.Eq(Elem(), "Lightning", "nothing in hand: the plan's element");
}
private static void MonsterRuleWeapon() private static void MonsterRuleWeapon()
{ {
var rig = new Rig(1535, "Ethereal Wisp"); var rig = new Rig(1535, "Ethereal Wisp");

View file

@ -70,6 +70,9 @@ namespace RynthDefective.Tests
Run("busy rule: a leftover count, our own use, animation, a count that just changed", BusyRuleDecisions); Run("busy rule: a leftover count, our own use, animation, a count that just changed", BusyRuleDecisions);
Run("use: a busy count left by a death or a login doesn't hold the bar", UseStaleBusy); Run("use: a busy count left by a death or a login doesn't hold the bar", UseStaleBusy);
Run("use: 'You're too busy' from the server: one more try", UseTooBusyRetry); Run("use: 'You're too busy' from the server: one more try", UseTooBusyRetry);
Run("busy rule with RynthAi holding: its own action and our last use hold, the rest of the count doesn't", BusyRulePaced);
Run("use: the player's turn - after a death the press goes next, RynthAi holds and is let go", UsePlayersTurn);
Run("use: just after a portal the client takes nothing for a few seconds - the press waits and goes when it can", UseAfterPortal);
Run("spells: the table's names and flags, the name search", SpellTableAndSearch); Run("spells: the table's names and flags, the name search", SpellTableAndSearch);
Run("spells: whom a cast goes to", SpellCastTarget); Run("spells: whom a cast goes to", SpellCastTarget);
Run("spells: a slot casts, Magic mode first, refusals", SpellUse); Run("spells: a slot casts, Magic mode first, refusals", SpellUse);
@ -219,6 +222,28 @@ namespace RynthDefective.Tests
public bool Animating { get; set; } public bool Animating { get; set; }
public bool? BotWaitingOnServer { get; set; } public bool? BotWaitingOnServer { get; set; }
public bool? BotMacroRunning { get; set; } public bool? BotMacroRunning { get; set; }
/// <summary>RynthAi has RynthAi.Yield with its pacing on (off: a RynthAi from before, as the older tests assume).</summary>
public bool YieldOn;
/// <summary>RynthAi's own action is unanswered (read only while YieldOn).</summary>
public bool BotOwnAction;
public bool? BotPaced => YieldOn ? BotOwnAction : null;
/// <summary>The asks for the player's turn, the releases, and whether RynthAi holds now.</summary>
public int HoldAsks, Releases;
public bool BotHeldNow;
public long HeldUntil;
public bool HoldBot(uint ms)
{
if (!YieldOn) return false;
HoldAsks++;
BotHeldNow = true;
HeldUntil = NowMs + ms;
return true;
}
public void ReleaseBot()
{
Releases++;
BotHeldNow = false;
}
public int UseDoneSeq { get; set; } = 1; public int UseDoneSeq { get; set; } = 1;
public int CombatMode { get; set; } = Stance.NonCombat; public int CombatMode { get; set; } = Stance.NonCombat;
public int RefusalSeq { get; set; } public int RefusalSeq { get; set; }

View file

@ -35,6 +35,7 @@
<ItemGroup> <ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthDefective\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthDefective\obj\**;..\..\Plugins\RynthCore.Plugin.RynthDefective\bin\**" Link="RynthDefective\%(RecursiveDir)%(Filename)%(Extension)" /> <Compile Include="..\..\Plugins\RynthCore.Plugin.RynthDefective\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthDefective\obj\**;..\..\Plugins\RynthCore.Plugin.RynthDefective\bin\**" Link="RynthDefective\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\Plugins\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" /> <Compile Include="..\..\Plugins\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiYieldApi.cs" Link="Shared\RynthAiYieldApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" /> <Compile Include="..\..\Plugins\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" /> <Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" /> <Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />

View file

@ -174,6 +174,189 @@ namespace RynthDefective.Tests
Eq(BusyRule.Decide(Facts(bot: false, botMs: 50), out _), BusyHold.None, "RynthAi idle"); Eq(BusyRule.Decide(Facts(bot: false, botMs: 50), out _), BusyHold.None, "RynthAi idle");
} }
// RynthAi holds for the press (RynthAi.Yield, 2026-10-29) and says what it has in flight.
private static BusyFacts Paced(int count = 0, long steady = 0, int leftover = 0, long own = long.MaxValue / 4,
bool anim = false, long animMs = 0, bool? botWait = null, bool paced = false, long pacedMs = 0) =>
new(count, steady, leftover, own, anim, animMs, botWait, 0, paced, pacedMs);
private static void BusyRulePaced()
{
Eq(BusyRule.Decide(Paced(), out BusyStale st), BusyHold.None, "idle: send");
Eq(BusyRule.Decide(Paced(count: 2, steady: 100), out st), BusyHold.None,
"a count that just moved, with nothing of ours or RynthAi's in flight (a death's, a corpse open's): send");
Eq(st, BusyStale.Count, "ignored as a leftover");
Eq(BusyRule.Decide(Paced(count: 1, steady: 100, own: 500), out _), BusyHold.Busy, "right after our own use: wait");
Eq(BusyRule.Decide(Paced(count: 1, steady: 100, own: BusyRule.OwnTrustMs), out _), BusyHold.None, "our own use long enough ago: send");
Eq(BusyRule.Decide(Paced(count: 3, steady: 100, leftover: 3, own: 500), out _), BusyHold.None, "our use's count back at the leftover: send");
Eq(BusyRule.Decide(Paced(paced: true, pacedMs: 300), out _), BusyHold.Bot, "RynthAi's own action unanswered: wait for its answer");
Eq(BusyRule.Decide(Paced(paced: true, pacedMs: BusyRule.BotTrustMs), out st), BusyHold.None, "at most BotTrustMs");
Eq(st, BusyStale.Bot, "then ignored");
Eq(BusyRule.Decide(Paced(count: 1, steady: 50, botWait: true), out _), BusyHold.None,
"RynthAi's 'waiting on the server' bit (its copy of the busy count) holds nothing while it holds for us");
Eq(BusyRule.Decide(Paced(anim: true, animMs: 300), out _), BusyHold.Animation, "a gesture still holds");
Eq(BusyRule.Decide(Facts(count: 1, steady: 100), out _), BusyHold.Busy, "without the hold (a RynthAi from before): the old rule, a fresh count holds");
}
private static void UsePlayersTurn()
{
ItemRef kit = ItemRef.From(Kit(0x10));
// After a death: the death left 2 in the count, and RynthAi's rebuffs keep moving it.
Harness h = With(Kit(0x10));
h.World.YieldOn = true;
h.World.BusyCount = 2;
h.Tick();
h.World.BusyCount = 3; h.Tick(400); // a cast of RynthAi's, answered
h.World.BusyCount = 2; h.Tick(400);
Eq(h.World.HoldAsks, 0, "nothing asked while nothing waits");
h.Slot(kit);
h.Tick(50);
Eq(string.Join("|", h.World.Sent), "useon 10 me", "the press goes at once: nothing of ours or RynthAi's is in flight");
Check(h.World.HoldAsks == 1 && h.World.BotHeldNow && h.Use.BotHeld, "RynthAi was asked to hold, and holds through the kit's flight");
Eq(h.Warned.Count, 0, "no warning");
Eq(h.Logged.Count(l => l.Contains("nothing of ours or RynthAi's in flight")), 1, "the leftover is logged once");
h.Tick(100);
Check(h.World.HoldAsks == 2 && h.World.BotHeldNow, "asked again every tick of the flight");
h.World.Answer();
h.Tick(100);
Check(!h.Use.InFlight && !h.World.BotHeldNow && h.World.Releases == 1 && !h.Use.BotHeld, "answered: RynthAi is let go that tick");
h.Tick(100);
Eq(h.World.Releases, 1, "and only once");
// RynthAi's own cast is still out: the press waits for its answer, and goes before anything new of RynthAi's.
h = With(Kit(0x10));
h.World.YieldOn = true;
h.World.BotOwnAction = true;
h.World.BusyCount = 1;
h.Tick();
h.Slot(kit);
h.Ticks(3, 500);
Eq(h.World.Sent.Count, 0, "RynthAi's cast has no answer yet: the press waits");
Check(h.World.BotHeldNow && h.World.HoldAsks == 3, "while RynthAi holds its next one (asked every tick)");
h.World.BotOwnAction = false;
h.World.BusyCount = 0;
h.Tick(100);
Eq(h.World.Sent.Count, 1, "answered: the press goes next");
// A RynthAi action that never gets an answer holds the press at most BotTrustMs.
h = With(Kit(0x10));
h.World.YieldOn = true;
h.World.BotOwnAction = true;
h.Tick();
h.Slot(kit);
h.Ticks(5, 1000);
Eq(h.World.Sent.Count, 0, "5 s: still waiting for RynthAi's answer");
h.Tick(600);
Check(h.World.Sent.Count == 1 && h.Warned.Count == 0, "past 5.5 s the press goes anyway, no warning");
Check(h.Logged.Any(l => l.Contains("RynthAi's own action has had no answer")), "and the log says why");
// Our use gets no answer: RynthAi is let go after FlightHoldMs though the use is still out.
h = With(Kit(0x10));
h.World.YieldOn = true;
h.Tick();
h.Slot(kit);
h.Tick(50);
h.World.BusyCount = 1; // the client holds our kit busy (so it isn't let go as quiet)
h.Tick(2000);
Check(h.Use.InFlight && h.World.BotHeldNow, "2 s into the flight: RynthAi still holds");
h.Tick(1100);
Check(h.Use.InFlight && !h.World.BotHeldNow && h.World.Releases == 1, "past 3 s: RynthAi goes on while our use waits for its answer");
// Portal space drops the press and lets RynthAi go.
h = With(Kit(0x10));
h.World.YieldOn = true;
h.World.BotOwnAction = true;
h.Tick();
h.Slot(kit);
h.Tick(100);
Check(h.World.BotHeldNow, "held while the press waits");
h.World.InWorld = false;
h.Tick(100);
Check(!h.Use.HasPending && !h.World.BotHeldNow && h.World.Releases == 1, "portal space: dropped, RynthAi let go");
// A RynthAi from before RynthAi.Yield: nothing to ask, nothing to let go, the old rule.
h = With(Kit(0x10));
h.World.BusyCount = 1;
h.Tick();
h.Slot(kit);
h.Tick(100);
Check(h.World.Sent.Count == 0 && h.World.HoldAsks == 0 && h.World.Releases == 0 && !h.Use.BotHeld,
"no hold taken; a count that may be real still holds the press");
}
// A report (10-29): after portalling in, four presses of a weapon slot in three seconds each said
// "the client didn't take the request (nothing was sent)": the engine takes no game action until
// 5 s after portal space ends. The press now waits for it.
private static Harness OutOfPortal(params CarriedItem[] items)
{
Harness h = With(items);
h.World.InWorld = false; // portal space
h.Tick(100);
h.World.InWorld = true; // out of it: the engine's gate holds game actions a while yet
h.World.RefuseSends = true;
h.Tick(100);
return h;
}
private static void UseAfterPortal()
{
ItemRef kit = ItemRef.From(Kit(0x10));
Harness h = OutOfPortal(Kit(0x10));
h.Slot(kit);
h.Tick(50);
Check(h.World.Sent.Count == 0 && h.Warned.Count == 0 && h.Use.HasPending, "refused just after the portal: it waits, no warning");
Eq(h.Said.Count(s => s.Contains("waiting for the game to finish the portal")), 1, "says what it waits for");
h.Ticks(8, 250);
Check(h.Warned.Count == 0 && h.Use.HasPending, "2 s more of refusals: still waiting");
Eq(h.Said.Count(s => s.Contains("waiting for the game")), 1, "said once");
Eq(h.Logged.Count(l => l.Contains("doesn't take") && l.Contains("after the portal")), 1, "logged once");
h.World.RefuseSends = false; // the engine's gate opens
h.Tick(250);
Eq(string.Join("|", h.World.Sent), "useon 10 me", "it goes the moment the client takes it");
Check(h.Use.InFlight && h.Warned.Count == 0, "in flight, never a warning");
// A second press of the same slot while it waits doesn't queue twice.
h = OutOfPortal(Kit(0x10));
h.Slot(kit);
h.Tick(50);
Check(!h.Slot(kit), "the same press again: already waiting");
// The client never takes it: once the portal is 6 s behind, the refusal is said as before.
h = OutOfPortal(Kit(0x10));
h.Slot(kit);
h.Ticks(24, 250);
Check(!h.Use.HasPending && h.Warned.Count == 1 && h.Warned[0].Contains("didn't take the request"),
"6 s after the portal it gives up and says so: " + string.Join("|", h.Warned));
// Long after a portal a refusal is said at once, as before.
h = OutOfPortal(Kit(0x10));
h.Tick(UseController.PortalRetryWindowMs);
h.Slot(kit);
h.Tick(50);
Check(h.Warned.Count == 1 && h.Warned[0].Contains("didn't take the request") && !h.Use.HasPending, "well after the portal: said at once");
// A plugin loaded in the world saw no arrival: said at once.
h = With(Kit(0x10));
h.World.RefuseSends = true;
h.Tick();
h.Slot(kit);
h.Tick(50);
Check(h.Warned.Count == 1 && !h.Use.HasPending, "no portal seen: said at once");
// A spell slot: the cast waits the same way, after Magic mode.
h = OutOfPortal();
h.World.Known = new HashSet<uint> { 6 };
h.World.CombatMode = Stance.Magic;
Check(h.Use.Request(UseRequest.Cast(6, "Heal Self I", "slot", h.World.NowMs)), "a cast queued");
h.Tick(50);
h.Ticks(4, 250);
Check(h.Use.InFlight && h.World.Sent.Count == 0 && h.Warned.Count == 0, "the cast is refused and waits");
Eq(h.Said.Count(s => s.Contains("waiting for the game to finish the portal")), 1, "said once");
h.World.RefuseSends = false;
h.Tick(250);
Eq(string.Join("|", h.World.Sent), "cast 6 me", "cast the moment the client takes it");
}
private static void UseStaleBusy() private static void UseStaleBusy()
{ {
ItemRef kit = ItemRef.From(Kit(0x10)); ItemRef kit = ItemRef.From(Kit(0x10));