feat(vendor): Slice 6 buy arc — shop items are real objects, vendor selection is THE selection, and Buy works (0x005F)
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

Three ordered pieces in one landing (the shared controller/composition
files carry all three; the internal order was 6.1 -> 6.2 -> 6.3):

6.1 VendorShopItemMaterializer diff-merges the shop list into the live
ClientObjectTable on VendorState transitions (so client-local close and
session teardown retire the entries too) and never claims a guid it did
not add — ACE's UniqueItemsForSale can re-list a guid a player once
held (AP-163 files the collision-skip; no retail counterpart traced).
Right-click examine on shop items now routes through the ordinary
appraisal path — the 5.4 F7c blocker dissolves with the table entries.

6.2 SelectionChangeSource.Vendor: row clicks, auto-select, and examine
all flow through the canonical SelectionState; the status bar and the
existing byte-faithful StackSplitQuantityState slider light up
unmodified. VendorSplitPolicy is the single 0xDC41CB0 mask owner; the
slider VALUE seeds to 1 for exempt items while maxSplitSize keeps the
stack (the splitSize/maxSplitSize distinction, research §B.3).
Selection clears at retail's actual site — VendorItemsUI::RemoveFromShop
(pc:202848), not a CloseVendor-level clear that does not exist.

6.3 BuildBuy (0x005F): vendorGuid, count, (i32 amount, u32 guid) pairs,
and the trailing alternateCurrencyId the REAL client sends
(CM_Vendor::Event_Buy pc:689288) though ACE's reader ignores it.
TryBuy rides the EXISTING J5.2 one-request-at-a-time reservation and
completes on UseDone; the Buy button disables while a request is in
flight. The reconciliation round-trip (money property update, inventory
CreateObject, ApproachVendor refresh -> panel rebuild) is proven by a
synthetic-inbound test against existing machinery — no new owner.

Register: AP-161 narrowed (selection + examine residuals close;
staging/Sell remain; double-click-to-buy confirmed ABSENT from retail
with negative evidence cited — we match retail). AP-162 files the
conscious no-client-side-affordability-precheck deferral.

Clean-room complete solution: 11,368 passed / 4 skipped / 0 failed.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-08-07 20:28:26 +02:00
parent c884a938e0
commit 97cf873870
19 changed files with 1577 additions and 65 deletions

View file

@ -27,6 +27,7 @@ public sealed class ItemInteractionControllerTests
public readonly List<uint> Drops = new();
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();
public readonly List<string> Toasts = new();
public readonly List<string> SystemMessages = new();
public readonly List<CombatMode> CombatModeRequests = new();
@ -94,7 +95,9 @@ public sealed class ItemInteractionControllerTests
},
combatState: Combat,
sendChangeCombatMode: CombatModeRequests.Add,
requestUse: requestUse);
requestUse: requestUse,
sendBuy: (vendorGuid, itemGuid, amount, alternateCurrencyId) =>
Buys.Add((vendorGuid, itemGuid, amount, alternateCurrencyId)));
}
public ItemInteractionController Controller { get; }
@ -2145,4 +2148,123 @@ public sealed class ItemInteractionControllerTests
Assert.Equal(0, h.Controller.BusyCount);
Assert.Equal(InteractionModeKind.None, h.Controller.InteractionState.Current.Kind);
}
// ── Slice 6.3: TryBuy ───────────────────────────────────────────────
[Fact]
public void TryBuy_Succeeds_SendsBuyAndTakesTheSharedUseReservation()
{
var h = new Harness();
bool result = h.Controller.TryBuy(
vendorGuid: 0x40001000u,
itemGuid: 0x50002000u,
amount: 1,
alternateCurrencyId: 0u);
Assert.True(result);
Assert.Equal(
new[] { (0x40001000u, 0x50002000u, 1, 0u) },
h.Buys);
// BeginUseRequestReservation increments BusyCount synchronously,
// before/independent of any wire response -- this is what makes the
// Buy button disable immediately (research doc §A.4: "no second
// gate", the SAME BusyCount>0 check every other request rides).
Assert.Equal(1, h.Controller.BusyCount);
}
[Fact]
public void TryBuy_StackedQuantity_ForwardsTheExactAmount()
{
var h = new Harness();
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002001u, 25, 0u));
Assert.Equal(25, h.Buys.Single().Amount);
}
[Fact]
public void TryBuy_AlternateCurrencyVendor_ForwardsTheCurrencyWcid()
{
var h = new Harness();
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002000u, 1, 0x12345678u));
Assert.Equal(0x12345678u, h.Buys.Single().AlternateCurrencyId);
}
[Fact]
public void TryBuy_WhileAnotherRequestIsBusy_IsRejectedAndSendsNothing()
{
var h = new Harness();
h.Controller.IncrementBusyCount(); // simulates any other in-flight request
bool result = h.Controller.TryBuy(0x40001000u, 0x50002000u, 1, 0u);
Assert.False(result);
Assert.Empty(h.Buys);
Assert.Equal(1, h.Controller.BusyCount); // unchanged -- no second reservation taken
}
[Fact]
public void TryBuy_ASecondBuyWhileTheFirstIsInFlight_IsRejected()
{
var h = new Harness();
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002000u, 1, 0u));
bool second = h.Controller.TryBuy(0x40001000u, 0x50002001u, 1, 0u);
Assert.False(second);
Assert.Single(h.Buys);
Assert.Equal(1, h.Controller.BusyCount);
}
[Theory]
[InlineData(0u, 0x50002000u, 1)]
[InlineData(0x40001000u, 0u, 1)]
[InlineData(0x40001000u, 0x50002000u, 0)]
[InlineData(0x40001000u, 0x50002000u, -1)]
public void TryBuy_InvalidArguments_IsRejectedWithoutTakingAReservation(
uint vendorGuid, uint itemGuid, int amount)
{
var h = new Harness();
bool result = h.Controller.TryBuy(vendorGuid, itemGuid, amount, 0u);
Assert.False(result);
Assert.Empty(h.Buys);
Assert.Equal(0, h.Controller.BusyCount);
}
[Fact]
public void TryBuy_CompleteUse_ReleasesTheReservationAndReenablesFurtherRequests()
{
// Research doc §A.4: UseDone (0x01C7) is the completion signal for
// Buy, resolved through the SAME RuntimeInteractionTransactionState.
// CompleteUse the existing UseDone handler already calls -- no new
// completion plumbing needed on the receive side.
var h = new Harness();
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002000u, 1, 0u));
Assert.Equal(1, h.Controller.BusyCount);
h.Controller.CompleteUse(0);
Assert.Equal(0, h.Controller.BusyCount);
// The gate is free again -- a second Buy can now proceed.
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002001u, 1, 0u));
Assert.Equal(2, h.Buys.Count);
}
[Fact]
public void TryBuy_FailedUseDone_AlsoReleasesTheReservation()
{
// A.2's failure paths all still end in exactly one SendUseDoneEvent
// -- success or failure, the reservation resolves the same way.
var h = new Harness();
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002000u, 1, 0u));
h.Controller.CompleteUse(0x0009u); // an arbitrary nonzero WeenieError
Assert.Equal(0, h.Controller.BusyCount);
}
}

View file

@ -94,6 +94,9 @@ public class SelectedObjectControllerTests
public readonly Dictionary<uint, bool> HasHealthMap = new();
public readonly Dictionary<uint, float> ManaMap = new();
public readonly Dictionary<uint, uint> StackMap = new();
// Slice 6.2: vendor-owned split-exempt predicate — see
// SelectedObjectController.Bind's isVendorSplitExempt parameter.
public readonly Dictionary<uint, bool> VendorSplitExemptMap = new();
public void FireSelection(uint? g)
{
@ -135,7 +138,8 @@ public class SelectedObjectControllerTests
unsubscribeObjectUpdated: h =>
{
if (ObjectUpdatedHandler == h) ObjectUpdatedHandler = null;
});
},
isVendorSplitExempt: g => VendorSplitExemptMap.TryGetValue(g, out var v) && v);
}
// ── B1: Bind initialisation ──────────────────────────────────────────────

View file

@ -4,6 +4,8 @@ using AcDream.App.UI;
using AcDream.App.UI.Layout;
using AcDream.Core.Items;
using AcDream.Core.Properties;
using AcDream.Core.Selection;
using AcDream.Runtime.Gameplay;
namespace AcDream.App.Tests.UI.Layout;
@ -41,13 +43,26 @@ public sealed class VendorUiControllerTests
Visible = false,
});
var objects = new ClientObjectTable();
using var itemInteraction = new ItemInteractionController(
objects,
new RuntimeInteractionTransactionState(new InventoryTransactionState(objects)),
new InteractionState(),
playerGuid: static () => 0u,
sendUse: null,
sendUseWithTarget: null,
sendWield: null,
sendDrop: null);
VendorUiController? controller = VendorUiController.Bind(
layout,
new VendorState(),
window,
static (_, _, _, _, _) => 0u,
new ClientObjectTable(),
objects,
static () => 0u,
itemInteraction,
new SelectionState(),
new StackSplitQuantityState(),
datFont: null,
debugFont: null,
static _ => (0u, 0, 0));
@ -60,9 +75,11 @@ public sealed class VendorUiControllerTests
// F2/F3: a deterministic non-zero player coin total so the cost-text
// "(you have ...)" tail is assertable.
public const int DefaultPlayerCoinValue = 1500;
private const uint PlayerGuid = 0x50000001u;
public const uint PlayerGuid = 0x50000001u;
public readonly VendorState State = new();
public readonly SelectionState Selection = new();
public readonly StackSplitQuantityState SplitQuantity = new();
public readonly UiRoot Screen = new() { Width = 800f, Height = 600f };
public readonly ClientObjectTable Objects = new();
public readonly UiItemList ItemList = new();
@ -81,6 +98,9 @@ public sealed class VendorUiControllerTests
public readonly UiButton AddButton;
public readonly RetailWindowHandle Window;
public readonly VendorUiController Controller;
public readonly List<uint> Examines = new();
public readonly List<(uint VendorGuid, uint ItemGuid, int Amount, uint AlternateCurrencyId)> Buys = new();
public readonly ItemInteractionController ItemInteraction;
public Harness()
{
@ -145,6 +165,19 @@ public sealed class VendorUiControllerTests
Resizable = false,
});
ItemInteraction = new ItemInteractionController(
Objects,
new RuntimeInteractionTransactionState(new InventoryTransactionState(Objects)),
new InteractionState(),
playerGuid: static () => PlayerGuid,
sendUse: null,
sendUseWithTarget: null,
sendWield: null,
sendDrop: null,
sendExamine: Examines.Add,
sendBuy: (vendorGuid, itemGuid, amount, alternateCurrencyId) =>
Buys.Add((vendorGuid, itemGuid, amount, alternateCurrencyId)));
Controller = VendorUiController.Bind(
layout,
State,
@ -155,6 +188,9 @@ public sealed class VendorUiControllerTests
static (_, iconId, underlay, overlay, effects) => iconId + underlay + overlay + effects,
Objects,
static () => PlayerGuid,
ItemInteraction,
Selection,
SplitQuantity,
datFont: null,
debugFont: null,
static _ => (0u, 0, 0))!;
@ -611,4 +647,204 @@ public sealed class VendorUiControllerTests
Assert.False(h.SellingPage.Visible);
Assert.Equal(1, h.ItemList.GetNumUIItems());
}
[Fact]
public void RightClickShopRow_SelectsAndRoutesThroughItemInteractionExamine()
{
// Slice 6.1: mirrors ExternalContainerControllerTests'
// RightClickLoot_selectsAndExaminesWithoutPickingUp — the shop list
// wires ExamineItemRequested the same way the container lists do,
// now that shop items are materialized into ClientObjectTable
// (AP-161 finding #2's examine gap closes here).
var h = new Harness();
h.State.Apply(VendorGuid, Profile(), new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
new VendorShopItem(FoodItemGuid, -1, 1u, "Bread", (uint)ItemType.Food, 100u, 5),
});
// Food, not the auto-selected Armor default, so the assertion below
// proves the right click itself drove the selection.
UiItemSlot? foodCell = null;
object? foodPayload = h.TypeMenu.Items.First(i => i.Label == "Food").Payload;
h.TypeMenu.OnSelect!.Invoke(foodPayload);
foodCell = h.ItemList.GetItem(0);
Assert.Equal(FoodItemGuid, foodCell!.ItemId);
foodCell.OnEvent(new UiEvent(0u, foodCell, UiEventType.RightClick));
Assert.Equal(new[] { FoodItemGuid }, h.Examines);
Assert.Equal("Bread", GetText(h.ItemNameText));
Assert.True(foodCell.Selected);
}
// ── Slice 6.3: Buy button ────────────────────────────────────────────
[Fact]
public void BuyButton_Press_NonStackedItem_BuysQuantityOne()
{
var h = new Harness();
h.State.Apply(VendorGuid, Profile(), new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
// F4 auto-selected the sole item; its own stack size (default/absent)
// is <=1, so StackSplitQuantityState was never seeded above 1 either
// (this harness doesn't mount SelectedObjectController, so the split
// state starts at its class default Value=1/Maximum=1 — exactly what
// production would also show for a non-stacked item).
h.BuyButton.OnClick!.Invoke();
Assert.Equal(
new[] { (VendorGuid, ArmorItemGuid, 1, 0u) },
h.Buys);
}
[Fact]
public void BuyButton_Press_StackedItem_UsesTheLiveSplitSliderQuantity()
{
// Slice 6.3: BuySingleItem (pc:201674-201681) reads the CURRENT
// slider value, not the full stack. This harness doesn't mount
// SelectedObjectController (the toolbar owns that seeding in
// production), so the test seeds SplitQuantity directly to stand in
// for "the player selected this item, then dragged the slider to
// 25" before pressing Buy.
var h = new Harness();
h.State.Apply(VendorGuid, Profile(), new[]
{
new VendorShopItem(
StackedItemGuid, -1, 3u, "Arrows", (uint)ItemType.MissileWeapon, 300u, 1000,
DescStackSize: 100),
});
h.SplitQuantity.Reset(100u, initialValue: 25u);
h.BuyButton.OnClick!.Invoke();
Assert.Equal(25, h.Buys.Single().Amount);
}
[Fact]
public void BuyButton_Press_AlternateCurrencyVendor_ForwardsTheVendorsTradeWcid()
{
var h = new Harness();
h.State.Apply(
VendorGuid,
Profile(altCurrency: 0x12345678u, altName: "Trade Notes", altAmount: 500u),
new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
h.BuyButton.OnClick!.Invoke();
Assert.Equal(0x12345678u, h.Buys.Single().AlternateCurrencyId);
}
[Fact]
public void BuyButton_DisablesTheInstantAPurchaseIsInFlight_AndReenablesOnCompletion()
{
var h = new Harness();
h.State.Apply(VendorGuid, Profile(), new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
Assert.True(h.BuyButton.Enabled);
h.BuyButton.OnClick!.Invoke();
// TryBuy's reservation increments BusyCount synchronously, before
// any wire response — the button must reflect that immediately,
// with no per-frame polling (ItemInteractionController.StateChanged
// drives RecomputeBuyButtonEnabled).
Assert.False(h.BuyButton.Enabled);
h.ItemInteraction.CompleteUse(0);
Assert.True(h.BuyButton.Enabled);
}
[Fact]
public void BuyButton_NoSelection_PressDoesNothing()
{
var h = new Harness();
h.BuyButton.OnClick!.Invoke();
Assert.Empty(h.Buys);
}
[Fact]
public void ReconciliationRoundTrip_MoneyCreateObjectAndApproachVendorRefresh_FlowThroughExistingMachinery()
{
// Slice 6.3: verifies the loop end-to-end with synthetic inbound
// messages, adding no new owner (research doc §C.4/§A.2 point 4):
// (1) a money property update applies to the SAME ClientObjectTable
// the vendor panel reads live for its cost text,
// (2) the purchase lands in the player's inventory via the ordinary
// CreateObject merge-upsert (ClientObjectTable.Ingest),
// (3) the vendor's post-buy ApproachVendor refresh
// (VendorStateTransitionKind.Refreshed) rebuilds the panel —
// here the bought-out item leaves the vendor's stock entirely
// (the common single-item-purchase case), so the rebuild is
// externally observable: the item leaves the list and the
// selection/buttons clear.
var h = new Harness();
const uint PurchasedItemGuid = 0x60000900u;
h.State.Apply(VendorGuid, Profile(sellRate: 1.0f), new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
Assert.Equal(1, h.ItemList.GetNumUIItems());
Assert.True(h.BuyButton.Enabled);
h.BuyButton.OnClick!.Invoke();
Assert.Single(h.Buys);
Assert.False(h.BuyButton.Enabled);
// (1) Money: PrivateUpdatePropertyInt(CoinValue) — the exact path
// ObjectTableWiring's PlayerIntPropertyUpdated handler calls.
int newCoinValue = Harness.DefaultPlayerCoinValue - 500;
h.Objects.UpdateIntProperty(Harness.PlayerGuid, (uint)PropertyInt.CoinValue, newCoinValue);
// (2) CreateObject: the purchased item lands in the player's own
// inventory — the ordinary Ingest merge-upsert every CreateObject
// uses (ObjectTableWiring.ApplyEntitySpawn), landing here with the
// player as its container.
h.Objects.Ingest(new WeenieData(
Guid: PurchasedItemGuid,
Name: "Chainmail",
Type: ItemType.Armor,
WeenieClassId: 2u,
IconId: 200u,
IconOverlayId: 0u,
IconUnderlayId: 0u,
Effects: 0u,
Value: 500,
StackSize: null,
StackSizeMax: null,
Burden: null,
ContainerId: Harness.PlayerGuid,
WielderId: 0u,
ValidLocations: null,
CurrentWieldedLocation: null,
Priority: null,
ItemsCapacity: null,
ContainersCapacity: null,
Structure: null,
MaxStructure: null,
Workmanship: null));
// (3) ApproachVendor refresh: sold out of the ONLY armor stack, so
// the SAME vendor's next snapshot no longer lists it.
h.State.Apply(VendorGuid, Profile(sellRate: 1.0f), System.Array.Empty<VendorShopItem>());
// (4) UseDone completes the reservation.
h.ItemInteraction.CompleteUse(0);
Assert.Equal(newCoinValue, h.Objects.Get(Harness.PlayerGuid)?.Properties.GetInt((uint)PropertyInt.CoinValue));
Assert.Equal(Harness.PlayerGuid, h.Objects.Get(PurchasedItemGuid)?.ContainerId);
Assert.Equal(0, h.ItemList.GetNumUIItems());
Assert.Equal(string.Empty, GetText(h.ItemNameText));
Assert.False(h.BuyButton.Enabled);
}
}