fix(vendor): Slice 6 review corrections — ownership-checked retire, live slider display, drag-proof shop rows, hardened buy reservation
Some checks are pending
Headless portability / portable-headless (ubuntu-latest) (push) Waiting to run
Headless portability / portable-headless (windows-latest) (push) Waiting to run
Headless portability / linux-graphical (push) Waiting to run
Headless portability / linux-vulkan (push) Waiting to run

All nine findings from the buy-arc review, at root:

F1 the materializer's retire pass re-checks ownership (guid->vendorId
map; remove only while the live object's ContainerId still equals the
recording vendor) — buying a player-sold UNIQUE no longer deletes the
item you just purchased; the discriminating reparent-then-refresh test
pins it. F2 the cost/name display subscribes to the live split state
and shares ONE quantity computation with Buy (retail re-renders per
slider tick: RecvNotice_StackSliderChanged 0x004C4500) — the sentence
and the charge can no longer disagree. F3 shop rows never mint drag
payloads (UiItemSlot.AllowDragSource gates both IsDragSource AND
GetDragPayload — the second gate was caught by this pass's own test).
F4 sendBuy reports whether anything was sent; a null-session buy
cancels the reservation instead of leaking BusyCount forever.
F5 the retire loop snapshots, isolates per-guid observer failures, and
clears its tracking in finally and Dispose — teardown convergence can
no longer wedge. F6 auto-select is retail's unconditional
first-filtered-item shape (pc:201180-201184; the survival-check was
our invention and the comment claiming otherwise is corrected).
F7 non-stack buys clamp to quantity 1 locally (BuySingleItem
pc:201669). F8 the Add button is hard-disabled until staging exists.
F9 AP-161/162/163 rewritten to the post-fix reality.

Clean-room complete solution: 11,378 passed / 4 skipped / 0 failed.
The #350 render-ledger overflow observed this session is under
separate investigation and is NOT addressed here.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-08-07 23:12:50 +02:00
parent 97cf873870
commit 3c9fc57adb
11 changed files with 670 additions and 116 deletions

File diff suppressed because one or more lines are too long

View file

@ -365,12 +365,17 @@ internal sealed class RetailInteractionRetainedUiCompositionFactory
// Slice 6.3: ItemInteractionController.TryBuy owns the
// reservation dance itself (see its doc comment); this is a
// plain wire send, not a second requestUse-shaped delegate.
// F4 (Slice 6 review): report whether the send actually
// happened — a null CurrentSession or a not-in-world session
// must return false so TryBuy releases the reservation instead
// of marking it dispatched for a request nothing ever sent.
sendBuy: (vendorGuid, itemGuid, amount, alternateCurrencyId) =>
session.CurrentSession?.SendBuy(
vendorGuid,
itemGuid,
amount,
alternateCurrencyId));
{
if (session.CurrentSession is not { } activeSession || !session.IsInWorld)
return false;
activeSession.SendBuy(vendorGuid, itemGuid, amount, alternateCurrencyId);
return true;
});
}
public MagicRuntime CreateMagicRuntime(
@ -671,8 +676,8 @@ internal sealed class RetailInteractionRetainedUiCompositionFactory
// guid" — Slice 6.1 guarantees a materialized shop
// item's ContainerId IS the vendor's guid, so this reads
// straight off the same ClientObjectTable/VendorState
// pair VendorUiController.VendorSplitSize's display-only
// copy also reads, through the SAME VendorSplitPolicy
// pair VendorUiController.ResolveBuyQuantity (F2, Slice 6
// review) also reads, through the SAME VendorSplitPolicy
// mask helper (no second mask copy).
guid =>
d.Inventory.Vendor.VendorId != 0u

View file

@ -61,8 +61,12 @@ public sealed class ItemInteractionController : IDisposable
private readonly Action<string>? _systemMessage;
private readonly AutoWieldController _autoWield;
private readonly Action<uint, ItemUseRequestReservation>? _requestUse;
// Slice 6.3: vendorGuid, itemGuid, amount, alternateCurrencyId.
private readonly Action<uint, uint, int, uint>? _sendBuy;
// Slice 6.3: vendorGuid, itemGuid, amount, alternateCurrencyId -> true
// when the wire send actually happened. F4 (Slice 6 review): a plain
// Action can't tell TryBuy apart from a silent no-op (no session / not
// in world) — the bool return is what lets TryBuy release the
// reservation instead of leaking BusyCount forever.
private readonly Func<uint, uint, int, uint, bool>? _sendBuy;
private readonly RuntimeInteractionTransactionState _runtimeTransactions;
private readonly InventoryTransactionState _transactions;
@ -104,7 +108,7 @@ public sealed class ItemInteractionController : IDisposable
CombatState? combatState = null,
Action<CombatMode>? sendChangeCombatMode = null,
Action<uint, ItemUseRequestReservation>? requestUse = null,
Action<uint, uint, int, uint>? sendBuy = null)
Func<uint, uint, int, uint, bool>? sendBuy = null)
{
_objects = objects ?? throw new ArgumentNullException(nameof(objects));
_playerGuid = playerGuid ?? throw new ArgumentNullException(nameof(playerGuid));
@ -242,6 +246,20 @@ public sealed class ItemInteractionController : IDisposable
/// exactly what <see cref="EnsureInventoryRequestReady"/>'s
/// <c>BusyCount == 0</c> check already guards for every other request.
/// </summary>
/// <remarks>
/// F4 (Slice 6 review): <see cref="_sendBuy"/> reports whether the wire
/// send actually happened (false when there is no live session or the
/// session is not in world). Mirrors
/// <c>RuntimeInteractionTransactionState.TryDispatchUse</c>'s shape —
/// every rejecting path calls <see cref="ItemUseRequestReservation.CancelBeforeDispatch"/>
/// before returning, never <see cref="ItemUseRequestReservation.MarkDispatched"/>.
/// The OLD void-returning delegate could not distinguish "sent" from a
/// session-null no-op, so a buy attempted while disconnected/mid-teardown
/// permanently marked the reservation dispatched — <c>BusyCount</c> then
/// never balances, because no <c>UseDone</c> will ever arrive for a
/// request that was never actually sent, leaking "You can only move or
/// use one item at a time" forever.
/// </remarks>
public bool TryBuy(uint vendorGuid, uint itemGuid, int amount, uint alternateCurrencyId)
{
if (vendorGuid == 0u || itemGuid == 0u || amount <= 0 || _sendBuy is null)
@ -250,15 +268,23 @@ public sealed class ItemInteractionController : IDisposable
return false;
ItemUseRequestReservation reservation = BeginUseRequestReservation();
bool dispatched;
try
{
_sendBuy(vendorGuid, itemGuid, amount, alternateCurrencyId);
dispatched = _sendBuy(vendorGuid, itemGuid, amount, alternateCurrencyId);
}
catch
{
reservation.CancelBeforeDispatch();
throw;
}
if (!dispatched)
{
reservation.CancelBeforeDispatch();
return false;
}
reservation.MarkDispatched();
return true;
}

View file

@ -261,9 +261,11 @@ public sealed class SelectedObjectController : IRetainedPanelController
/// equals <c>VendorState.VendorId</c>) AND its type intersects
/// <see cref="VendorSplitPolicy.SplitExemptMask"/>. When true, a stack
/// seeds to quantity 1 instead of the full authored stack size — see
/// <see cref="ApplySelection"/>. <c>VendorUiController.VendorSplitSize</c>
/// answers the SAME question for vendor's own display text via the SAME
/// <see cref="VendorSplitPolicy"/> helper, so the mask exists in exactly
/// <see cref="ApplySelection"/>. F2 (Slice 6 review):
/// <c>VendorUiController.ResolveBuyQuantity</c> answers the equivalent
/// LIVE question for vendor's own display text and Buy dispatch (the
/// CURRENT slider value, not the seed) via the SAME
/// <see cref="VendorSplitPolicy"/> mask, so the mask exists in exactly
/// one place (composed at <c>InteractionRetainedUiComposition</c>).
/// </param>
public static SelectedObjectController Bind(

View file

@ -273,9 +273,14 @@ public sealed class VendorUiController : IRetainedPanelController
_itemList.FillVisibleEmptySlots = true;
if (emptySlotSprite != 0u)
_itemList.CellEmptySprite = emptySlotSprite;
// F3 (Slice 6 review): vendor rows are never drag sources — see
// UiItemSlot.AllowDragSource. Set here too (empty cells are already
// non-sources via ItemId==0) so the invariant holds by construction
// rather than incidentally.
_itemList.EmptySlotFactory = () => new UiItemSlot
{
SpriteResolve = _itemList.SpriteResolve,
AllowDragSource = false,
};
// Slice 6.1: mirrors ExternalContainerController's own
// right-click-examine wiring (UiItemSlot.OnEvent's RightClick case).
@ -352,6 +357,11 @@ public sealed class VendorUiController : IRetainedPanelController
// increments BusyCount synchronously, before the wire send), and
// re-enable on the matching UseDone/cancel, without polling.
_itemInteraction.StateChanged += OnInteractionStateChanged;
// F2 (Slice 6 review): retail re-runs UpdateItemsUI on every slider
// change (gmVendorUI::RecvNotice_StackSliderChanged, pc:203262-203278)
// — the displayed name/price must track the LIVE split, not just the
// value at selection time.
_splitQuantity.Changed += OnSplitQuantityChanged;
}
/// <param name="objects">
@ -579,18 +589,38 @@ public sealed class VendorUiController : IRetainedPanelController
/// selected) shows zero rows, matching retail.
/// </summary>
/// <remarks>
/// F4/F7a (Slice 5.4 review): the tail of the SAME retail function
/// (<c>pc:201180-201190</c>) — after every rebuild (fresh open OR an
/// explicit category switch, both funnel through this method) the
/// FIRST item that passed the filter becomes the display selection when
/// the previous one didn't survive it, and the list unconditionally
/// scrolls back to its start (<c>ScrollToShow(m_shopList, 0)</c>).
/// Slice 6.2: retail routes the selection through the global
/// F4/F7a (Slice 5.4 review) + F6 (Slice 6 review): the tail of the SAME
/// retail function (<c>pc:201180-201190</c>) — after every rebuild the
/// list unconditionally scrolls back to its start
/// (<c>ScrollToShow(m_shopList, 0)</c>) and, on the retail caller's
/// "notify" paths, the FIRST item that passed the filter becomes the
/// selection UNCONDITIONALLY — there is no survival test
/// (<c>pc:201180-201184</c>: <c>if (arg3 != 0) SetSelectedObject(i_1, 0)</c>,
/// where <c>i_1</c> is simply the first matching item, 0/none if the
/// filter matched nothing). F6 confirmed all THREE of our call sites are
/// retail's notify=1 case, not notify=0: a fresh vendor open AND a
/// same-vendor post-buy/sell refresh both run
/// <c>VendorItemsUI::OpenVendor</c> UNCONDITIONALLY (<c>pc:203852</c>,
/// not gated on the sameVendor flag), which clamps the dropdown index
/// and calls <c>UIElement_Menu::SetSelectedItem(..., 1)</c>
/// (<c>pc:200783-201022</c>) — that trailing <c>1</c> is retail's
/// selection-changed notify flag, and setting the menu's selection
/// synchronously cascades into <c>UpdateItemsList(0, 1)</c> via
/// <c>gmVendorUI::ListenToElementMessage</c>'s <c>idMessage==7</c> case
/// (<c>pc:204302-204303</c>) — the SAME idMessage==7/notify=1 path a
/// manual category switch (<see cref="SelectCategory"/>) already takes.
/// Retail's ONLY notify=0 (no-reselect) call site is a bare tab-page-open
/// with no category/vendor change (<c>idMessage==0x2c</c>,
/// <c>m_OpenPageToken==0x100000bc</c>, <c>pc:204283-204285</c>) — this
/// controller has no equivalent call site (<see cref="ShowTab"/> never
/// calls this method), so every path that reaches
/// <see cref="RebuildItemList"/> is retail's notify=1 case. Slice 6.2:
/// retail routes the selection through the global
/// <c>ACCWeenieObject::selectedID</c>/<c>SetSelectedObject</c>
/// (<c>pc:201184</c>, confirmed to be the SAME primitive as the fallback
/// select here) — this now calls <see cref="SelectionState.Select"/>
/// instead of the retired private field, so the toolbar status bar and
/// slider light up for the auto-selected item too.
/// (<c>pc:201184</c>) — this calls <see cref="SelectionState.Select"/>/
/// <see cref="SelectionState.Clear"/> instead of the retired private
/// field, so the toolbar status bar and slider light up for the
/// auto-selected item too.
/// </remarks>
private void RebuildItemList()
{
@ -600,8 +630,14 @@ public sealed class VendorUiController : IRetainedPanelController
uint maskValue = (uint)activeMask;
IReadOnlyList<VendorShopItem> items = _vendor.Items;
// Best-effort initial paint only — the OLD selection, captured
// before this rebuild. The unconditional Select/Clear call below is
// what actually decides the post-rebuild selection (F6); this just
// avoids a one-frame flash of "nothing highlighted" in the common
// case where the old and new selections turn out to be the same
// guid (SelectionState.Select is a no-op then and won't re-fire
// Changed to correct it).
uint? selectedGuid = _selection.SelectedObjectId;
bool selectionStillPresent = false;
VendorShopItem? firstItem = null;
using (_itemList.DeferLayout())
@ -614,7 +650,6 @@ public sealed class VendorUiController : IRetainedPanelController
if (((item.ItemType ?? 0u) & maskValue) == 0u) continue;
firstItem ??= item;
if (item.ItemGuid == selectedGuid) selectionStillPresent = true;
// F5 (Slice 5.4 review): forward the icon underlay/
// overlay/effects PublicWeenieDescParser already
@ -630,6 +665,11 @@ public sealed class VendorUiController : IRetainedPanelController
{
SpriteResolve = _itemList.SpriteResolve,
SlotIndex = _itemList.GetNumUIItems(),
// F3 (Slice 6 review): a shop row must never become a
// drag source — see UiItemSlot.AllowDragSource's doc
// comment for why this must be gated at the source,
// not left to every destination handler to reject.
AllowDragSource = false,
};
cell.SetItem(item.ItemGuid, icon);
cell.Selected = item.ItemGuid == selectedGuid;
@ -640,13 +680,14 @@ public sealed class VendorUiController : IRetainedPanelController
}
}
if (!selectionStillPresent)
{
if (firstItem is { } first)
_selection.Select(first.ItemGuid, SelectionChangeSource.Vendor);
else
_selection.Clear(SelectionChangeSource.Vendor);
}
// F6: unconditional — no survival test. Every rebuild call site
// (Opened/Refreshed via RebuildCategories, and a manual category
// switch via SelectCategory) is retail's notify=1 case; see the
// remarks above for the decomp trace.
if (firstItem is { } first)
_selection.Select(first.ItemGuid, SelectionChangeSource.Vendor);
else
_selection.Clear(SelectionChangeSource.Vendor);
// F7a: unconditional scroll-to-start on every rebuild (retail only
// guards on the list being non-empty; resetting an already-empty
@ -666,12 +707,22 @@ public sealed class VendorUiController : IRetainedPanelController
/// directly and let this method react).
/// </summary>
/// <remarks>
/// F2/F3 (Slice 5.4 review): the priced/named QUANTITY is retail's
/// <c>ItemHolder::GetObjectSplitSize</c> (<c>0x00586F00</c>,
/// <c>pc:401465-401477</c>) AS SEEDED for a vendor-shop item by
/// <c>gmToolbarUI::HandleSelectionChanged</c>'s vendor branch — see
/// <see cref="VendorSplitSize"/> for the exact mask citation. Name:
/// <c>ACCWeenieObject::GetObjectName</c> (<c>0x0058E6E0</c>,
/// F2/F3 (Slice 5.4 review), rewired for F2 (Slice 6 review): the
/// priced/named QUANTITY is retail's <c>ItemHolder::GetObjectSplitSize</c>
/// (<c>0x00586F00</c>, <c>pc:401465-401477</c>) read LIVE — retail
/// re-runs this SAME display update on every slider change
/// (<c>gmVendorUI::RecvNotice_StackSliderChanged</c>,
/// <c>pc:203262-203278</c>, <c>0x004C4500</c>, wired via
/// <see cref="OnSplitQuantityChanged"/> below), reading the singular/
/// plural gate, the count, and the price off the CURRENT split value
/// (<c>pc:202602</c>/<c>202621</c>/<c>202644</c>), not a value frozen at
/// selection time. <see cref="ResolveBuyQuantity"/> is the SAME
/// computation <see cref="BuySelectedItem"/> uses to decide what it
/// actually sends, so the displayed price always equals what a Buy press
/// would charge. <c>VendorSplitPolicy.SeedQuantity</c> stays only in
/// <see cref="SelectedObjectController"/>'s real seeding path (the
/// toolbar slider's INITIAL value); this display no longer reads it.
/// Name: <c>ACCWeenieObject::GetObjectName</c> (<c>0x0058E6E0</c>,
/// <c>pc:409056-409132</c>) — NAME_SINGULAR for quantity &lt;= 1,
/// NAME_PLURAL for quantity &gt; 1; when no plural is authored
/// (<c>m_len==1</c>, an empty <c>PString</c>) retail falls back to the
@ -694,7 +745,7 @@ public sealed class VendorUiController : IRetainedPanelController
cell.Selected = cell.ItemId == item.ItemGuid;
}
int quantity = VendorSplitSize(item);
int quantity = (int)ResolveBuyQuantity(item);
string baseName = quantity <= 1
? item.Name ?? string.Empty
@ -739,6 +790,24 @@ public sealed class VendorUiController : IRetainedPanelController
private void OnSelectionTransition(SelectionTransition transition)
{
_ = transition;
RefreshSelectionDisplay();
}
/// <summary>
/// F2 (Slice 6 review): retail's <c>gmVendorUI::RecvNotice_StackSliderChanged</c>
/// (<c>pc:203262-203278</c>, <c>0x004C4500</c>) — a registered listener
/// on the SAME global slider-changed notice
/// <see cref="SelectedObjectController"/> broadcasts, gated (in retail)
/// on the panel being visible and the globally-selected item being one
/// of the vendor's own. <see cref="RefreshSelectionDisplay"/> already
/// applies that same gate (it no-ops to <see cref="ClearSelectionDisplay"/>
/// when the current selection isn't a vendor item), so no separate
/// visibility check is needed here.
/// </summary>
private void OnSplitQuantityChanged() => RefreshSelectionDisplay();
private void RefreshSelectionDisplay()
{
uint? selected = _selection.SelectedObjectId;
if (selected is { } guid)
{
@ -776,21 +845,26 @@ public sealed class VendorUiController : IRetainedPanelController
}
/// <summary>
/// The quantity retail prices/names a vendor-shop selection at —
/// <c>gmToolbarUI::HandleSelectionChanged</c>'s vendor-owned branch
/// (<c>pc:198779-198790</c>). Every row <see cref="VendorUiController"/>
/// shows IS vendor-owned (its container is unconditionally the open
/// vendor), so the "does this item belong to the open vendor" gate that
/// precedes the mask check in retail's function is always true here and
/// is not reproduced separately. Slice 6.2: delegates to
/// <see cref="VendorSplitPolicy"/> — the single source of truth for the
/// <c>0xDC41CB0</c> mask, also used by <c>SelectedObjectController</c>'s
/// REAL seeding path (<c>InteractionRetainedUiComposition</c>'s
/// <c>isVendorSplitExempt</c> delegate) so the mask exists in exactly
/// one place.
/// F2/F7 (Slice 6 review): the SINGLE quantity computation both the
/// display (<see cref="ApplyItemDisplay"/>) and the actual purchase
/// (<see cref="BuySelectedItem"/>) use — retail's
/// <c>gmVendorUI::BuySingleItem</c> (<c>pc:201661</c>,
/// <c>0x004C2820</c>): quantity 1 when the item's own authored stack
/// size is <c>&lt;= 1</c> (<c>pc:201674-201681</c>) — there is no split
/// UI for a non-stack item, so a leftover slider value from a
/// PREVIOUSLY-selected DIFFERENT stackable item must never leak into
/// this one — otherwise the CURRENT slider value via
/// <c>ItemHolder::GetObjectSplitSize</c> (<c>0x00586F00</c>).
/// </summary>
private static int VendorSplitSize(VendorShopItem item) =>
VendorSplitPolicy.SeedQuantity((ItemType)(item.ItemType ?? 0u), item.DescStackSize);
private uint ResolveBuyQuantity(VendorShopItem item)
{
uint stackSize = (uint)Math.Max(item.DescStackSize ?? 1, 1);
if (stackSize <= 1u)
return 1u;
uint selected = _selection.SelectedObjectId ?? item.ItemGuid;
return _splitQuantity.GetObjectSplitSize(item.ItemGuid, selected, stackSize);
}
/// <summary>
/// Cost sentence — <c>VendorItemsUI::UpdateItemsUI</c>'s tail
@ -852,10 +926,20 @@ public sealed class VendorUiController : IRetainedPanelController
SetActionButtonsEnabled(false);
}
/// <summary>
/// F8 (Slice 6 review): "Add to List" (staging into the "Buying" tab,
/// contract decision 6) has NO wired <c>OnClick</c> at all — before this
/// fix it enabled on selection exactly like Buy, so it read as a working
/// affordance that silently did nothing on click, which is worse than a
/// disabled button (a disabled Add correctly signals "not available
/// yet"; an enabled dead Add signals a bug). Permanently disabled until
/// the "Buying" tab's staging list is actually implemented — see the
/// register, AP-161.
/// </summary>
private void SetActionButtonsEnabled(bool enabled)
{
_buyEnabledBySelection = enabled;
if (_addButton is not null) _addButton.Enabled = enabled;
if (_addButton is not null) _addButton.Enabled = false;
RecomputeBuyButtonEnabled();
}
@ -864,8 +948,9 @@ public sealed class VendorUiController : IRetainedPanelController
/// something selected" (<see cref="_buyEnabledBySelection"/>, set by
/// <see cref="SetActionButtonsEnabled"/>) and "is the shared inventory/
/// use gate free right now" (<see cref="ItemInteractionController.CanMakeInventoryRequest"/>).
/// The Add button (staging, contract decision 6 — unwired this pass)
/// stays selection-only. Called on every selection change AND on every
/// The Add button (staging, contract decision 6 — unwired this pass) is
/// PERMANENTLY disabled instead (F8, Slice 6 review) — see
/// <see cref="SetActionButtonsEnabled"/>. Called on every selection change AND on every
/// <see cref="ItemInteractionController.StateChanged"/> tick, so the
/// button disables the instant <see cref="ItemInteractionController.TryBuy"/>
/// takes its reservation and re-enables on the matching completion —
@ -881,13 +966,16 @@ public sealed class VendorUiController : IRetainedPanelController
/// <summary>
/// Slice 6.3: retail <c>gmVendorUI::BuySingleItem</c> (<c>pc:201661</c>).
/// Reads the CURRENT globally-selected shop item and the CURRENT split
/// quantity, then dispatches a single-item purchase through the shared
/// use/inventory reservation. Client-side affordability/capacity
/// pre-checks are deliberately NOT ported (research doc's open question
/// 1: the server is authoritative either way and pre-checks are latency/
/// UX polish, not correctness — deferred as a fast follow-up if the
/// round-trip lag on a refused purchase is noticeable live).
/// Reads the CURRENT globally-selected shop item and dispatches a
/// single-item purchase through the shared use/inventory reservation,
/// using <see cref="ResolveBuyQuantity"/> — the SAME quantity
/// computation <see cref="ApplyItemDisplay"/> prices/names the selection
/// at (F2), so the amount actually sent always matches what was shown.
/// Client-side affordability/capacity pre-checks are deliberately NOT
/// ported (research doc's open question 1: the server is authoritative
/// either way and pre-checks are latency/UX polish, not correctness —
/// deferred as a fast follow-up if the round-trip lag on a refused
/// purchase is noticeable live).
/// </summary>
private void BuySelectedItem()
{
@ -906,8 +994,7 @@ public sealed class VendorUiController : IRetainedPanelController
if (selected is not { } shopItem)
return;
uint stackSize = (uint)Math.Max(shopItem.DescStackSize ?? 1, 1);
uint quantity = _splitQuantity.GetObjectSplitSize(shopItem.ItemGuid, guid, stackSize);
uint quantity = ResolveBuyQuantity(shopItem);
_itemInteraction.TryBuy(
_vendor.VendorId,
shopItem.ItemGuid,
@ -947,6 +1034,7 @@ public sealed class VendorUiController : IRetainedPanelController
_selection.Changed -= OnSelectionTransition;
_objects.ObjectRemoved -= OnObjectRemoved;
_itemInteraction.StateChanged -= OnInteractionStateChanged;
_splitQuantity.Changed -= OnSplitQuantityChanged;
RetailTabBinding.SetClick(_itemsTab, null);
RetailTabBinding.SetClick(_buyingTab, null);
RetailTabBinding.SetClick(_sellingTab, null);

View file

@ -140,7 +140,7 @@ public class UiItemSlot : UiElement
/// <inheritdoc/>
public override object? GetDragPayload()
=> ItemId != 0 && !_primaryPressConsumed
=> AllowDragSource && ItemId != 0 && !_primaryPressConsumed
? new ItemDragPayload(ItemId, SourceKind, SlotIndex, this, Shortcut)
: null;
@ -158,7 +158,8 @@ public class UiItemSlot : UiElement
internal override void SetDragSourceActive(bool active, object? payload)
{
// ItemList_BeginDrag ghosts physical lists, but explicitly excludes shortcut lists
// (along with vendor/salvage lists, which acdream does not model as ItemDragSource).
// (along with vendor/salvage lists — see AllowDragSource above, F3: those never
// reach here at all, since IsDragSource is false for them).
// Keep the source's full cell icon in place and reveal the authored grey mesh over it.
SetWaitingState(active && SourceKind != ItemDragSource.ShortcutBar);
}
@ -171,13 +172,35 @@ public class UiItemSlot : UiElement
internal void SetWaitingState(bool waiting)
=> _waiting = waiting && ItemId != 0;
/// <summary>
/// F3 (Slice 6 review): opt-out for lists whose rows must NEVER initiate
/// a drag, regardless of occupancy — retail's <c>ItemList_BeginDrag</c>
/// explicitly excludes vendor/salvage lists from drag-drop (see the
/// <see cref="SetDragSourceActive"/> comment above). Before shop items
/// had real <see cref="ClientObjectTable"/> identity (Slice 6.1) a
/// dragged shop guid failed every destination's existence guard as a
/// harmless no-op; once it resolved, the SAME drag would pass a pack
/// drop's <c>PutItemInContainer</c>, persist a dangling shortcut-bar
/// entry, or fire <c>PlaceIn3D</c> — reparenting a vendor's stock
/// without ever going through Buy. Gating the SOURCE here (rather than
/// asking every destination handler to reject a vendor-tagged payload)
/// means the drag never starts at all, so no future drop handler can
/// regress this by forgetting a check. Defaults true — every existing
/// physical list (inventory, paperdoll, container, shortcut bar) is
/// unaffected; <see cref="VendorUiController"/> is the only caller that
/// sets it false.
/// </summary>
public bool AllowDragSource { get; set; } = true;
/// <summary>An OCCUPIED slot is a drag source — a press-and-move picks up the item
/// rather than moving the toolbar window. An EMPTY slot is NOT a drag source, so a
/// press-and-move there falls through to the IA-12 whole-window-drag, keeping the bar
/// movable by its empty cells / chrome. Drives <see cref="UiRoot"/>'s mousedown
/// window-vs-item disambiguation (retail moves the window via a dragbar, never cells;
/// our whole-window-drag approximation reconciles by gating on occupancy).</summary>
public override bool IsDragSource => ItemId != 0;
/// our whole-window-drag approximation reconciles by gating on occupancy).
/// <see cref="AllowDragSource"/> is an additional, independent gate (F3) — false for
/// vendor rows regardless of ItemId.</summary>
public override bool IsDragSource => ItemId != 0 && AllowDragSource;
/// <summary>Walk up to the containing <see cref="UiItemList"/> (the drop handler owner).</summary>
protected UiItemList? FindList()

View file

@ -86,12 +86,40 @@ namespace AcDream.Runtime.Gameplay;
/// already was, which is safe by construction and never corrupts a real
/// object's ownership.
/// </para>
///
/// <para>
/// <b>Ownership re-check on retire (review finding F1).</b> Buying a
/// UNIQUE vendor item does not merely drop it from the next
/// <c>ApproachVendor</c> snapshot — ACE first re-containers the SAME guid
/// into the BUYER's own pack via <c>CreateObject</c>
/// (<c>Player_Commerce.cs:86-108</c>, A.2 of the Slice 6 research doc) and
/// only THEN sends the full-replace refresh that no longer lists it. If
/// the retire pass below removed every guid merely absent from the new
/// snapshot, it would delete the just-purchased item straight back out of
/// the buyer's own inventory the instant the post-buy refresh landed. Each
/// owned guid therefore remembers the vendor id it was registered under,
/// and the retire pass only calls <see cref="ClientObjectTable.Remove"/>
/// when the LIVE object's current <c>ContainerId</c> still equals that
/// recorded vendor id — i.e. nothing else has re-containered it since.
/// When it no longer matches (a purchase moved it to the buyer, or some
/// other owner claimed it), the tracking entry is dropped silently and the
/// object itself is left completely untouched, mirroring the collision
/// policy above.
/// </para>
/// </summary>
public sealed class VendorShopItemMaterializer : IDisposable
{
private readonly VendorState _vendor;
private readonly ClientObjectTable _objects;
private readonly HashSet<uint> _ownedGuids = new();
/// <summary>
/// Guids this materializer currently owns in <see cref="ClientObjectTable"/>,
/// mapped to the vendor id they were registered under. F1: the retire
/// pass re-checks the live object's <c>ContainerId</c> against this
/// recorded value before deleting anything — see the class doc's
/// "Ownership re-check on retire" section.
/// </summary>
private readonly Dictionary<uint, uint> _ownedGuids = new();
private bool _disposed;
public VendorShopItemMaterializer(VendorState vendor, ClientObjectTable objects)
@ -110,7 +138,7 @@ public sealed class VendorShopItemMaterializer : IDisposable
public int OwnedCount => _ownedGuids.Count;
/// <summary>True if <paramref name="guid"/> is a shop item this materializer put in the table.</summary>
public bool Owns(uint guid) => _ownedGuids.Contains(guid);
public bool Owns(uint guid) => _ownedGuids.ContainsKey(guid);
private void OnVendorTransition(VendorTransition transition)
{
@ -119,40 +147,78 @@ public sealed class VendorShopItemMaterializer : IDisposable
foreach (VendorShopItem item in currentItems)
stillListed.Add(item.ItemGuid);
// Retire every guid we own that fell out of the new snapshot (sold
// out, session closed/reset, or a different vendor superseded this
// one — in every one of those cases stillListed is missing it).
// Runs BEFORE the materialize loop below: "on REPLACE, the old
// vendor's items go before the new ones land."
foreach (uint guid in _ownedGuids)
var nextOwned = new Dictionary<uint, uint>(currentItems.Count);
try
{
if (!stillListed.Contains(guid))
_objects.Remove(guid);
}
var nextOwned = new HashSet<uint>(currentItems.Count);
foreach (VendorShopItem item in currentItems)
{
bool ownedAlready = _ownedGuids.Contains(item.ItemGuid);
if (!ownedAlready && _objects.Get(item.ItemGuid) is not null)
// Retire every guid we own that fell out of the new snapshot (sold
// out, session closed/reset, or a different vendor superseded this
// one — in every one of those cases stillListed is missing it).
// Runs BEFORE the materialize loop below: "on REPLACE, the old
// vendor's items go before the new ones land."
//
// Iterate a SNAPSHOT (F5): ClientObjectTable.Remove synchronously
// fires ObjectRemoved to every subscriber with no per-listener
// isolation (unlike VendorState's own Changed dispatch). A
// throwing external observer must not abort this loop midway and
// strand the remaining guids un-retired.
foreach (KeyValuePair<uint, uint> owned in new List<KeyValuePair<uint, uint>>(_ownedGuids))
{
// Collision guard — see class doc. Never take ownership of a
// guid this materializer did not itself add.
Console.Error.WriteLine(
"[VendorShopItemMaterializer] skipped guid=0x"
+ item.ItemGuid.ToString("X8")
+ " — already present in ClientObjectTable and not "
+ "owned by this vendor session.");
continue;
if (stillListed.Contains(owned.Key))
continue;
// F1 — re-check ownership before removing. A purchase can
// have already re-containered this guid into the buyer's
// pack (see class doc); only retire it if it is STILL the
// vendor's, i.e. the live object's ContainerId still equals
// the vendor id we registered it under. If it moved, drop
// the tracking entry silently and leave the (now
// someone-else's) object completely untouched.
ClientObject? live = _objects.Get(owned.Key);
if (live is null || live.ContainerId != owned.Value)
continue;
try
{
_objects.Remove(owned.Key);
}
catch (Exception error)
{
System.Diagnostics.Trace.TraceError(
"[VendorShopItemMaterializer] ObjectRemoved observer "
+ "threw retiring guid=0x{0}: {1}",
owned.Key.ToString("X8"),
error);
}
}
_objects.Ingest(ToWeenieData(item, transition.VendorId));
nextOwned.Add(item.ItemGuid);
}
foreach (VendorShopItem item in currentItems)
{
bool ownedAlready = _ownedGuids.ContainsKey(item.ItemGuid);
if (!ownedAlready && _objects.Get(item.ItemGuid) is not null)
{
// Collision guard — see class doc. Never take ownership of a
// guid this materializer did not itself add.
Console.Error.WriteLine(
"[VendorShopItemMaterializer] skipped guid=0x"
+ item.ItemGuid.ToString("X8")
+ " — already present in ClientObjectTable and not "
+ "owned by this vendor session.");
continue;
}
_ownedGuids.Clear();
foreach (uint guid in nextOwned)
_ownedGuids.Add(guid);
_objects.Ingest(ToWeenieData(item, transition.VendorId));
nextOwned[item.ItemGuid] = transition.VendorId;
}
}
finally
{
// F5: guaranteed to run even if the retire/materialize passes
// above throw somewhere this method doesn't already catch, so
// _ownedGuids never straddles two inconsistent generations.
_ownedGuids.Clear();
foreach (KeyValuePair<uint, uint> entry in nextOwned)
_ownedGuids[entry.Key] = entry.Value;
}
}
/// <summary>
@ -198,5 +264,12 @@ public sealed class VendorShopItemMaterializer : IDisposable
if (_disposed) return;
_disposed = true;
_vendor.Changed -= OnVendorTransition;
// F5 safety net: RuntimeInventoryState.Dispose() always runs
// Vendor.Reset() first (which drives OnVendorTransition's own retire
// pass down to zero), but a caller that disposes this class directly
// without a prior Reset()/Close() must not leave stale tracking
// entries behind — OwnedCount feeds
// RuntimeInventoryOwnershipSnapshot.IsConverged.
_ownedGuids.Clear();
}
}

View file

@ -28,6 +28,11 @@ public sealed class ItemInteractionControllerTests
public readonly List<(uint Item, uint Amount)> SplitDrops = new();
public readonly List<(uint Target, uint Item, uint Amount)> Gives = new();
public readonly List<(uint VendorGuid, uint ItemGuid, int Amount, uint AlternateCurrencyId)> Buys = new();
// F4 (Slice 6 review): simulates the composition-root sendBuy
// delegate's "no live session / not in world" no-op case —
// TryBuy must see this as false and release the reservation
// rather than mark it dispatched for a request nothing sent.
public bool SendBuySucceeds = true;
public readonly List<string> Toasts = new();
public readonly List<string> SystemMessages = new();
public readonly List<CombatMode> CombatModeRequests = new();
@ -97,7 +102,12 @@ public sealed class ItemInteractionControllerTests
sendChangeCombatMode: CombatModeRequests.Add,
requestUse: requestUse,
sendBuy: (vendorGuid, itemGuid, amount, alternateCurrencyId) =>
Buys.Add((vendorGuid, itemGuid, amount, alternateCurrencyId)));
{
if (!SendBuySucceeds)
return false;
Buys.Add((vendorGuid, itemGuid, amount, alternateCurrencyId));
return true;
});
}
public ItemInteractionController Controller { get; }
@ -2267,4 +2277,35 @@ public sealed class ItemInteractionControllerTests
Assert.Equal(0, h.Controller.BusyCount);
}
[Fact]
public void TryBuy_NoSessionToSendOn_ReleasesTheReservation_AndASubsequentBuyWorks()
{
// F4 (Slice 6 review): the composition-root sendBuy delegate
// returns false when there is no live session (or it's not in
// world) -- BEFORE this fix, sendBuy was a plain Action, so TryBuy
// could not tell "sent" apart from a silent no-op and always
// called MarkDispatched(). Since nothing was actually sent, no
// UseDone would ever arrive to balance it, leaking BusyCount and
// permanently wedging every future Use/Buy behind "You can only
// move or use one item at a time."
var h = new Harness();
h.SendBuySucceeds = false;
bool result = h.Controller.TryBuy(0x40001000u, 0x50002000u, 1, 0u);
Assert.False(result);
Assert.Empty(h.Buys);
// The reservation was cancelled, not dispatched -- the gate is
// free again immediately, with no UseDone needed to release it.
Assert.Equal(0, h.Controller.BusyCount);
// A subsequent buy, once a session IS available, proceeds normally.
h.SendBuySucceeds = true;
bool second = h.Controller.TryBuy(0x40001000u, 0x50002001u, 1, 0u);
Assert.True(second);
Assert.Single(h.Buys);
Assert.Equal(1, h.Controller.BusyCount);
}
}

View file

@ -176,7 +176,10 @@ public sealed class VendorUiControllerTests
sendDrop: null,
sendExamine: Examines.Add,
sendBuy: (vendorGuid, itemGuid, amount, alternateCurrencyId) =>
Buys.Add((vendorGuid, itemGuid, amount, alternateCurrencyId)));
{
Buys.Add((vendorGuid, itemGuid, amount, alternateCurrencyId));
return true;
});
Controller = VendorUiController.Bind(
layout,
@ -293,6 +296,15 @@ public sealed class VendorUiControllerTests
});
h.ItemList.GetItem(0)!.Clicked?.Invoke();
// F2 (Slice 6 review): the display now reads the LIVE split state
// instead of recomputing a static seed. Production seeds this via
// SelectedObjectController (mounted on the toolbar, subscribed to
// SelectionState.Changed BEFORE VendorUiController — RetailUiRuntime
// MountToolbar() runs before MountVendor()); this harness doesn't
// mount that controller, so the test seeds SplitQuantity directly to
// stand in for it, matching the SAME not-exempt full-stack seed
// SelectedObjectController.ApplySelection would have computed.
h.SplitQuantity.Reset(100u, initialValue: 100u);
// No authored PluralName -> ACCWeenieObject::GetObjectName falls back
// to the singular name UNCHANGED (not an invented "Arrows" + "s").
@ -319,6 +331,10 @@ public sealed class VendorUiControllerTests
});
h.ItemList.GetItem(0)!.Clicked?.Invoke();
// F2: exempt seed is 1 regardless of the 50-unit authored stack —
// see the split-exempt comment on the sibling test above for why
// this harness seeds SplitQuantity explicitly.
h.SplitQuantity.Reset(50u, initialValue: 1u);
Assert.Equal("Bread", GetText(h.ItemNameText));
Assert.Equal(
@ -338,10 +354,56 @@ public sealed class VendorUiControllerTests
});
h.ItemList.GetItem(0)!.Clicked?.Invoke();
// F2: Key is not split-exempt -> full authored stack (10).
h.SplitQuantity.Reset(10u, initialValue: 10u);
Assert.Equal("10 Iron Keys", GetText(h.ItemNameText));
}
[Fact]
public void SliderChange_AfterSelection_UpdatesNameAndPriceToLiveQuantity_MatchingWhatBuyWouldCharge()
{
// F2 (Slice 6 review): retail re-runs UpdateItemsUI on every slider
// change (gmVendorUI::RecvNotice_StackSliderChanged,
// pc:203262-203278) -- the OLD implementation froze the display's
// quantity at a static per-selection seed while BuySelectedItem
// separately read the LIVE split, so a slider drag after selecting
// never updated the sentence/price and could show a DIFFERENT price
// than what Buy would actually charge. Both now go through the SAME
// ResolveBuyQuantity, proven here by asserting the displayed price
// equals the amount the subsequent Buy press actually sends.
var h = new Harness();
h.State.Apply(VendorGuid, Profile(sellRate: 2.0f), new[]
{
// perUnit = 1000/100 = 10 (MissileWeapon, not split-exempt).
new VendorShopItem(
StackedItemGuid, -1, 3u, "Arrows", (uint)ItemType.MissileWeapon, 300u, 1000,
DescStackSize: 100),
});
// F6 auto-selects the sole item; the harness's un-mounted-toolbar
// split state starts at its class default (Value=1/Maximum=1) —
// singular display, matching a fresh, not-yet-slider-touched
// selection.
Assert.Equal("Arrows", GetText(h.ItemNameText));
Assert.Equal(
$"costs {20:N0} (you have {Harness.DefaultPlayerCoinValue:N0})",
GetText(h.ItemCostText));
// Player drags the slider to 40 AFTER selecting -- no re-click, no
// re-selection, purely a StackSplitQuantityState.Changed event.
h.SplitQuantity.Reset(100u, initialValue: 40u);
// SellPrice = ceil(2.0*10*40 - 0.1) = 800.
Assert.Equal("40 Arrows", GetText(h.ItemNameText));
Assert.Equal(
$"cost {800:N0} (you have {Harness.DefaultPlayerCoinValue:N0})",
GetText(h.ItemCostText));
h.BuyButton.OnClick!.Invoke();
Assert.Equal(40, h.Buys.Single().Amount);
}
[Fact]
public void SelectingItem_WithAlternateCurrency_ShowsFullRetailCostSentence()
{
@ -370,10 +432,34 @@ public sealed class VendorUiControllerTests
}
[Fact]
public void NoSelection_DisablesBuyAndAddButtons_SelectionEnablesThem()
public void NoSelection_DisablesBuyButton_SelectionEnablesIt()
{
var h = new Harness();
Assert.False(h.BuyButton.Enabled);
h.State.Apply(VendorGuid, Profile(), new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
// F4 auto-selects the sole item on open, so Buy is already enabled
// — SetState(1), pc:202784-202789.
Assert.True(h.BuyButton.Enabled);
// Closing clears the selection -> SetState(0xd), pc:202572-202577.
h.State.Close();
Assert.False(h.BuyButton.Enabled);
}
[Fact]
public void AddButton_IsPermanentlyDisabled_RegardlessOfSelection()
{
// F8 (Slice 6 review): "Add to List" has no wired OnClick at all
// (staging into the "Buying" tab is deferred, contract decision 6)
// — an enabled button that silently does nothing on click is a
// dead-affordance bug, worse than a disabled one. It must never
// enable, with or without a selection.
var h = new Harness();
Assert.False(h.AddButton.Enabled);
h.State.Apply(VendorGuid, Profile(), new[]
@ -381,14 +467,10 @@ public sealed class VendorUiControllerTests
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
// F4 auto-selects the sole item on open, so the buttons are already
// enabled — SetState(1), pc:202784-202789.
Assert.True(h.BuyButton.Enabled);
Assert.True(h.AddButton.Enabled);
// F4/F6 auto-selects the sole item on open -- Add stays disabled.
Assert.False(h.AddButton.Enabled);
// Closing clears the selection -> SetState(0xd), pc:202572-202577.
h.State.Close();
Assert.False(h.BuyButton.Enabled);
Assert.False(h.AddButton.Enabled);
}
@ -473,6 +555,29 @@ public sealed class VendorUiControllerTests
Assert.NotNull(h.ItemList.EmptySlotFactory);
}
[Fact]
public void ShopRow_NeverMintsADragPayload()
{
// F3 (Slice 6 review): with shop items materialized into
// ClientObjectTable (Slice 6.1), a draggable vendor cell would pass
// every destination handler's existence guard -- a pack drop would
// send a real PutItemInContainer for vendor stock, the shortcut bar
// would persist a dangling guid, and PlaceIn3D would fire. Retail
// excludes vendor/salvage lists from ItemList_BeginDrag entirely; a
// populated shop row must never become a drag source at all.
var h = new Harness();
h.State.Apply(VendorGuid, Profile(), new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
UiItemSlot cell = h.ItemList.GetItem(0)!;
Assert.NotEqual(0u, cell.ItemId); // occupied -- would otherwise be a drag source by default
Assert.False(cell.IsDragSource);
Assert.Null(cell.GetDragPayload());
}
[Fact]
public void Opened_WithDifferentVendor_ResetsToFirstPresentCategory_NotThePreviousVendors()
{
@ -529,6 +634,43 @@ public sealed class VendorUiControllerTests
Assert.Equal("Food", h.TypeMenu.Items.Single(i => Equals(i.Payload, h.TypeMenu.Selected)).Label);
}
[Fact]
public void Refreshed_SameVendor_ReselectsFirstItemUnconditionally_NotThePreviouslySelectedSurvivor()
{
// F6 (Slice 6 review): retail's VendorItemsUI::UpdateItemsList
// selects UNCONDITIONALLY on every rebuild call site this
// controller reaches (pc:201180-201184, confirmed via
// VendorItemsUI::OpenVendor's unconditional clamp +
// SetSelectedItem(...,1) at pc:201022, which every vendor
// open/refresh runs regardless of the sameVendor flag) -- there is
// NO survival test. A same-vendor refresh that re-lists the SAME
// two items in the SAME order must reset to the FIRST one even
// though the player's prior selection (the second item) is still
// present in the new snapshot -- this is the case that would have
// diverged under the OLD "preserve if it survives" logic.
const uint SecondArmorGuid = 0x60000110u;
var h = new Harness();
var items = new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
new VendorShopItem(SecondArmorGuid, -1, 4u, "Buckler", (uint)ItemType.Armor, 900u, 40),
};
h.State.Apply(VendorGuid, Profile(), items);
Assert.Equal(ArmorItemGuid, h.ItemList.GetItem(0)!.ItemId); // auto-selected first
// Player explicitly picks the SECOND item.
h.ItemList.GetItem(1)!.Clicked?.Invoke();
Assert.True(h.ItemList.GetItem(1)!.Selected);
// SAME vendor, SAME two items, SAME order -> Refreshed transition.
h.State.Apply(VendorGuid, Profile(), items);
// Retail resets to the FIRST item, not the still-present second one.
Assert.True(h.ItemList.GetItem(0)!.Selected);
Assert.False(h.ItemList.GetItem(1)!.Selected);
Assert.Equal("Chainmail", GetText(h.ItemNameText));
}
[Fact]
public void CategoryMenu_OpensAndSelectsThroughRealHitPath_UsingAuthoredPopupGeometry()
{
@ -723,6 +865,36 @@ public sealed class VendorUiControllerTests
Assert.Equal(25, h.Buys.Single().Amount);
}
[Fact]
public void BuyButton_Press_NonStackedItem_IgnoresAStaleSliderFromAPreviouslySelectedStackableItem()
{
// F7 (Slice 6 review): retail's BuySingleItem (pc:201674-201681)
// gates on the SELECTED item's OWN stack size FIRST -- quantity 1
// whenever it is <=1, regardless of whatever
// GenItemHolder::splitSize still holds from a PREVIOUSLY selected,
// DIFFERENT, stackable item. Without this guard,
// ResolveBuyQuantity's GetObjectSplitSize(item.ItemGuid, selected,
// stackSize) call trivially returns the live Value for ANY selected
// item (item.ItemGuid always equals the selection guid at this call
// site) -- leaking a stale quantity into a non-stack purchase.
var h = new Harness();
h.State.Apply(VendorGuid, Profile(), new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
// Simulate a stale slider left over from a PREVIOUSLY selected,
// different, stackable item -- this harness doesn't mount
// SelectedObjectController, which in production would already have
// reset the slider on selecting the (non-stack) armor; seeding it
// directly here proves the clamp doesn't depend on that reset
// having run.
h.SplitQuantity.Reset(50u, initialValue: 30u);
h.BuyButton.OnClick!.Invoke();
Assert.Equal(1, h.Buys.Single().Amount);
}
[Fact]
public void BuyButton_Press_AlternateCurrencyVendor_ForwardsTheVendorsTradeWcid()
{

View file

@ -66,6 +66,33 @@ public class UiItemSlotTests
Assert.Null(slot.GetDragPayload());
}
// ── F3 (Slice 6 review): AllowDragSource ────────────────────────────────
[Fact]
public void AllowDragSource_DefaultsTrue_OccupiedSlotIsADragSource()
{
var s = new UiItemSlot();
s.SetItem(0x5001u, 0x99u);
Assert.True(s.IsDragSource);
Assert.NotNull(s.GetDragPayload());
}
[Fact]
public void AllowDragSource_False_OccupiedSlotIsNeverADragSource()
{
// A vendor row (or any future list retail excludes from
// ItemList_BeginDrag, e.g. salvage) sets this false. IsDragSource is
// the sole gate UiRoot reads at MouseDown to decide whether a
// press-and-move even becomes a drag CANDIDATE -- GetDragPayload()
// is never reached at all when this is false, so no destination
// drop handler needs to reject anything.
var s = new UiItemSlot { AllowDragSource = false };
s.SetItem(0x5001u, 0x99u);
Assert.False(s.IsDragSource);
}
// ── Shortcut number tests ────────────────────────────────────────────────
// Port of UIElement_UIItem::SetShortcutNum (acclient_2013_pseudo_c.txt:229465).

View file

@ -119,8 +119,15 @@ public sealed class VendorShopItemMaterializerTests
[Fact]
public void Refreshed_ItemNoLongerListed_IsRemoved()
{
// A unique item sold out (bought up / delisted) between one
// ApproachVendor and the next same-vendor refresh.
// An item drops out of the vendor's own list WITHOUT ever being
// re-containered elsewhere (e.g. admin-removed stock, a delisted
// line item) -- its live ContainerId is still the vendor's own
// guid, so the retire pass's F1 ownership re-check finds a match
// and removes it. This is deliberately NOT "I bought it" -- see
// Refreshed_ItemPurchased_ReparentedIntoBuyerPack_Survives for that
// case, where the SAME "missing from the new snapshot" trigger must
// NOT delete the item because a real purchase already moved it into
// the buyer's own pack before this refresh arrived.
var vendor = new VendorState();
var objects = new ClientObjectTable();
using var materializer = new VendorShopItemMaterializer(vendor, objects);
@ -133,6 +140,62 @@ public sealed class VendorShopItemMaterializerTests
Assert.Equal(1, materializer.OwnedCount);
}
[Fact]
public void Refreshed_ItemPurchased_ReparentedIntoBuyerPack_Survives()
{
// F1: buying a UNIQUE vendor item does not merely drop it from the
// next ApproachVendor snapshot -- ACE first re-containers the SAME
// guid into the BUYER's own pack via CreateObject
// (Player_Commerce.cs:86-108) and only THEN sends the full-replace
// refresh that no longer lists it. The retire pass must re-check
// live ownership (ContainerId) before deleting, or it strips the
// just-purchased item straight back out of the buyer's inventory.
var vendor = new VendorState();
var objects = new ClientObjectTable();
using var materializer = new VendorShopItemMaterializer(vendor, objects);
vendor.Apply(VendorGuid, default, new[] { Item(ItemA, "Unique Sword"), Item(ItemB) });
Assert.Equal(VendorGuid, objects.Get(ItemA)!.ContainerId);
const uint BuyerGuid = 0x50009000u;
// Simulate the purchase's CreateObject: ACE re-containers the SAME
// guid into the buyer's pack BEFORE the post-buy ApproachVendor
// refresh arrives.
objects.Ingest(new WeenieData(
Guid: ItemA,
Name: null,
Type: null,
WeenieClassId: 0,
IconId: 0,
IconOverlayId: 0,
IconUnderlayId: 0,
Effects: 0,
Value: null,
StackSize: null,
StackSizeMax: null,
Burden: null,
ContainerId: BuyerGuid,
WielderId: null,
ValidLocations: null,
CurrentWieldedLocation: null,
Priority: null,
ItemsCapacity: null,
ContainersCapacity: null,
Structure: null,
MaxStructure: null,
Workmanship: null));
Assert.Equal(BuyerGuid, objects.Get(ItemA)!.ContainerId);
// Post-buy ApproachVendor refresh: the purchased item is gone from
// the shop's own list.
vendor.Apply(VendorGuid, default, new[] { Item(ItemB) });
ClientObject? survivor = objects.Get(ItemA);
Assert.NotNull(survivor);
Assert.Equal(BuyerGuid, survivor!.ContainerId);
Assert.False(materializer.Owns(ItemA));
Assert.Equal(1, materializer.OwnedCount);
}
[Fact]
public void CollidingGuid_AlreadyOwnedBySomethingElse_IsNeverClobbered()
{
@ -188,4 +251,38 @@ public sealed class VendorShopItemMaterializerTests
vendor.Close();
Assert.NotNull(objects.Get(ItemA));
}
[Fact]
public void Retire_ThrowingObjectRemovedObserver_StillRetiresRemainingGuidsAndConverges()
{
// F5: ClientObjectTable.Remove fires ObjectRemoved with NO
// per-listener isolation (unlike VendorState's own Changed
// dispatch). One throwing observer must not abort the retire loop
// partway through and strand _ownedGuids -- every owned guid still
// retires, and OwnedCount still converges to zero.
var vendor = new VendorState();
var objects = new ClientObjectTable();
using var materializer = new VendorShopItemMaterializer(vendor, objects);
vendor.Apply(VendorGuid, default, new[] { Item(ItemA), Item(ItemB) });
Assert.Equal(2, materializer.OwnedCount);
// A throwing ObjectRemoved observer fires on EVERY Remove() call
// (both ItemA's and ItemB's) -- multicast delegate invocation has
// no per-listener isolation, so each Remove() call itself throws.
objects.ObjectRemoved += _ => throw new InvalidOperationException("boom");
vendor.Close();
// Both guids are gone from the table -- the throwing first observer
// did not stop the second guid's Remove() call from happening.
Assert.Null(objects.Get(ItemA));
Assert.Null(objects.Get(ItemB));
Assert.Equal(0, materializer.OwnedCount);
Assert.False(materializer.Owns(ItemA));
Assert.False(materializer.Owns(ItemB));
// Dispose still converges cleanly afterward.
materializer.Dispose();
Assert.Equal(0, materializer.OwnedCount);
}
}