commit 12415697ade471ce9912f4f4334ebf165ef9f206
parent 9cee024c0f32a42c2cadb6fd0c0b4423cddc0de0
Author: anon <anon@example.com>
Date: Sun, 25 Oct 2026 08:33:09 +0000
Restore native inventory placement when sale offers return
Diffstat:
6 files changed, 359 insertions(+), 3 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -648,6 +648,12 @@ introduction and starting-item gameplay remain open below.
replies and reconnect/restart. Keep every owned item and credit accounted
for on both successful and rejected paths. Include effective skill changes
while a basket is open and removal of the sale funding a selected purchase.
+- [x] Restore removed/cancelled sale offers into native first-free inventory
+ slots, rather than their original positions. Preserve stable TradeInv slots,
+ ownership and quantities; commit placement before acknowledgement and retain
+ the draft after SQLite failure for retry. Cover noncontiguous source slots,
+ reverse offer order and removal while another offered root reserves a slot.
+ See [shop restoration](docs/shops.md).
- [ ] Refresh one vendor's stock. Check: the intended stock policy updates the
list without changing an already purchased item's identity or properties.
@@ -948,6 +954,13 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah
## Player trading and tradeskills
+- [x] Recover the original player-trade message topology, first-free placement,
+ one-shot acceptance and filled-backpack restrictions. The protocol ledger
+ and explicit remaining limits are in [player trading](docs/player-trading.md).
+- [ ] Recover and verify peer template-stack delivery before enabling trades.
+ Native Add7 creates a count-one row; correcting ordinary inventory only after
+ completion does not fix the quantity shown before consent. Test partial/full
+ charged stacks, actual IDs, QL, ammunition and both native basket views.
- [ ] Open a two-player trade. Check: both native windows refer to the correct
participants and offered items remain unavailable for conflicting transfers.
- [ ] Complete an item-for-item trade. Check: both confirmations transfer items
@@ -1272,6 +1285,13 @@ current SQLite storage when applying these findings.
## Thorough gameplay regression testing
+- [ ] Reproduce stale shop interaction state after a live control-panel
+ inventory edit. In the restoration smoke run, a nearby original terminal
+ reported "Too far away" after the edit, while a fresh page could use it.
+ Check position/range and native trade state through edit, reconnect and
+ reopening the window; establish the cause before changing the protocol.
+ Evidence: `local/player-trade-smoke/check-vendor-pick-state.json` and
+ `fixed-fresh-vendor.png`. This is separate from the freeze below.
- [ ] Reproduce and fix a WASM freeze during live control-panel player edits
that reload the playfield. Check: capture the full stack for the observed
`ErrorEvent: unwind`, verify that native frames and world traffic resume,
diff --git a/docs/player-trading.md b/docs/player-trading.md
@@ -0,0 +1,101 @@
+# Original player trading contract
+
+Two-player trading is not implemented yet. The original 14.9.1 client has enough
+recovered protocol to open, cancel and confirm trades, but remote stack quantity
+delivery remains unresolved. Do not mark a transfer complete using a peer row
+that silently changes a stack to one charge.
+
+Research is retained in `local/player-trade-research/native/README.md` and its
+exported KKR/DDR/EER evidence. The shipped help file
+`cd_image/text/help/The Trade Window.txt` independently describes both players
+pressing ACCEPT, free gifts, entering cash with Enter, and the green opponent
+acceptance indicator. Its SHA-256 is
+`315fbe0b3b1f7ef4be7cf01e688779f4ddd38c20fd2cb920782730c33445723e`.
+The source ledger is `local/player-trade-research/sources/source-ledger.json`.
+
+## Wire contract
+
+TradeIIR key `0x36284f6e` has six network-order DWORDs:
+`1, action, A.type, A.id, B.type, B.id`. The outer N3 subject is separate.
+Let P be the offering player and Q the other player; zero means `(0,0)`.
+
+| Action | Subject; A; B | Meaning |
+| --- | --- | --- |
+| 0 | P; player Q; zero | Start; recursively initializes both player trade helpers |
+| 1 | Q; zero; zero | Notify Q that its opponent accepted |
+| 2 | P; `(0,showMessage)`; zero | Abort; recursively restores both players' offers |
+| 3 | P; zero; zero | Complete P's outgoing items and cash; does not recurse |
+| 4 | P; player P; `(104,sourceSlot)` | Move an ordinary owned row into TradeInv |
+| 5 | P; player P; `(108,tradeSlot)` | Return one owned offer to ordinary inventory |
+| 6 | P; `(0,signedCash)`; zero | Set P's offered cash |
+| 7 | Q; player P; actual item identity | Add P's actual item to Q's peer display |
+| 8 | Q; player P; actual item identity | Remove that peer row by actual identity |
+
+Start can be sent unchanged to both clients. It needs neither vending catalog
+initialization nor a shop GUI tag. After an atomic transfer, both Complete
+directions must reach both clients, followed by any absolute cash corrections.
+An own-subject Accept echo would light the wrong opponent indicator.
+
+KKR Start/Abort/Complete handlers are 0x10077370, 0x100774a0 and 0x10077700;
+the dispatcher is 0x100780b0. Ordinary native slots 48..77 correspond to
+server slots 64..93. Each player has thirty TradeInv slots, allocated first-free
+from zero. Removing an offer leaves other trade slots stable.
+
+## Restoration and consent
+
+KKR Remove helper 0x10060090 returns the selected row to the first free ordinary
+slot. Abort scans TradeInv in ascending order and restores each row first-free.
+For example, offering saved slots 64 and 70 with slot 65 empty then cancelling
+returns them to 64 and 65. The shop implementation uses this same restoration
+rule and commits the layout before acknowledging cancellation or removal.
+
+Offers remain durably owned until completion. When returning one row, remove
+all offered roots from the prospective ordinary layout, restore the selected
+row first-free, then reserve space for still-offered roots. Otherwise the
+returned row can collide with another offer's saved source slot. Draft source
+snapshots must follow these reservations. Preserve IDs, counts, QL, ammunition
+and container contents; cancellation changes placement, not ownership.
+
+DDR Accept handler 0x10048870 sends Cash6 before Accept1 even if cash is
+unchanged. It sets a one-shot flag reset by TradeStart. Incoming Accept invokes
+the local callback; DDR 0x10048e70 lights the opponent's green lamp.
+No Unaccept action or second confirmation stage was recovered. Actions 7/8
+are peer item operations. A later 2009 forum report of a confirmation dialog
+does not establish that behavior in 14.9.1.
+
+Proposed server policy: freeze both baskets and cash after either acceptance;
+allow unchanged Cash6, but require cancellation before actual changes. Merely
+clearing server acceptance cannot make this UI send another Accept. The
+protocol has no basket revision or session nonce.
+
+## Restrictions and remaining quantity work
+
+The original start producer 0x1001f840 requires a different SimpleChar target
+within five units. No faction restriction was recovered. Offering equipped
+items, foreign items, NoDrop roots or items directly inside a container is
+rejected by the client. Ordinary filled backpacks are supported, but common
+validator 0x10060510 rejects any NoDrop or Unique child through 0x1008bdd0.
+Original server-error strings also describe recipient capacity and Unique
+duplicates; they do not establish exact server counting rules.
+
+Peer Add7 reaches 0x10061b40 then row constructor 0x1002d870, which explicitly
+creates flags 0x22 and count one. QL and templates come from actual item
+stats 701/702/703. Neither Energy26 nor MultipleCount412 populates the row
+quantity. Peer page 208's stat412 reads the row itself in 0x1005de70.
+Complete preserves that row's count; its 0x1002dd90 call sets a dirty flag,
+not quantity. Consequently a full item dynel plus Add7 is insufficient for
+the correct displayed count of a charged template stack.
+
+InventoryUpdate's SimpleChar branch 0x10062ec0 accepts overflow page 110,
+not TradeInv. FullCharacter can seed remote ordinary rows, but also reapplies
+other character state; seeding followed by Add4 remains an untested delivery
+reconstruction. Completing both directions then rebuilding ordinary stacks
+could correct final inventory counts, but would leave inaccurate quantities
+in the basket before consent. Recover or verify a complete path before enabling
+stack trading.
+
+Server implementation still needs atomic two-player item/cash persistence,
+capacity and Unique checks against prospective inventories, filled-bag
+ownership, conflicting-action exclusion, current-session/range/death checks,
+and cancellation on disconnect, replacement or zoning. Tests must cover both
+native views and durable ownership through failure, replay and cold restart.
diff --git a/docs/shops.md b/docs/shops.md
@@ -290,7 +290,23 @@ TradeUpdated notification. Remove action 5 uses B=(108,trade slot); page 111
belongs to machine stock. Basket slots remain stable when another is removed.
Player Abort action 2 restores native offered items and clears the machine's
-record. The native Accept button first sends SetCash action 6 with zero cash,
+record. Remove returns its selected row into the first free ordinary slot;
+Abort does the same for each remaining TradeInv slot in ascending order.
+Neither operation remembers original inventory positions. The server commits
+this layout before acknowledging Remove/Abort. Other offered roots retain
+durable ownership in reserved slots, with their draft snapshots updated to
+match; those reservations do not occupy the client's ordinary inventory.
+Failed restoration leaves the draft available for retry. Native evidence is
+in [player trading](player-trading.md); regression tests include noncontiguous
+source slots, reverse offer order and a failed SQLite placement write.
+
+The actual GPU WASM test reproduced the old slot-65/slot-70 discrepancy
+with a 25-charge kit. After the fix, removal, re-addition and selling only that
+kit preserved the other offered item's identity; native rows and SQLite agreed
+after cancellation and cold restart. Captures and assertions are retained in
+`local/player-trade-smoke/verification.txt` and `tmp_verify.py`.
+
+The native Accept button first sends SetCash action 6 with zero cash,
then Accept action 1. The server echoes that zero reset without changing
credits; a nonzero cash offer is rejected. Complete action 3 invokes the
vending finalizer 0x100a99d0. That
diff --git a/server/shops.go b/server/shops.go
@@ -2,8 +2,10 @@ package main
import (
"ao/server/gamedata"
+ "cmp"
"encoding/binary"
"fmt"
+ "maps"
"math"
"slices"
"time"
@@ -134,10 +136,76 @@ func (server *server) handleShopUse(client *worldClient, body []byte) error {
}
func (server *server) abortShop_locked(client *worldClient) error {
+ if client.shop != nil {
+ slots := make([]uint32, 0, len(client.shop.items))
+ for slot := range client.shop.items {
+ slots = append(slots, slot)
+ }
+ slices.Sort(slots)
+ if err := server.restoreTradeItems_locked(client, client.shop.items, slots); err != nil {
+ return err
+ }
+ }
client.shop = nil
return client.send(shopTradePacket([2]uint32{50000, client.id}, 2, [2]uint32{}, [2]uint32{}))
}
+func (server *server) restoreTradeItems_locked(client *worldClient, offers map[uint32]ownedItem, returned []uint32) error {
+ if len(offers) == 0 {
+ return nil
+ }
+ player := server.characters[client.id]
+ inventory := player.inventory
+ inventory.Items = slices.Clone(inventory.Items)
+ remaining := maps.Clone(offers)
+ for _, slot := range returned {
+ delete(remaining, slot)
+ }
+
+ // Offered roots remain durably owned, but are absent from the native ordinary
+ // inventory. Restore selected rows first, in the same first-free order as KKR.
+ var held []ownedItem
+ inventory.Items = slices.DeleteFunc(inventory.Items, func(item ownedItem) bool {
+ for _, offer := range offers {
+ if item.ID == offer.ID {
+ held = append(held, item)
+ return true
+ }
+ }
+ return false
+ })
+ order := slices.Clone(returned)
+ for slot := range remaining {
+ order = append(order, slot)
+ }
+ slices.Sort(order[len(returned):])
+ for _, slot := range order {
+ index := slices.IndexFunc(held, func(item ownedItem) bool { return item.ID == offers[slot].ID })
+ if index < 0 {
+ continue
+ }
+ item := held[index]
+ item.Slot = 64
+ for slices.ContainsFunc(inventory.Items, func(other ownedItem) bool { return other.Slot == item.Slot }) {
+ item.Slot++
+ }
+ inventory.Items = append(inventory.Items, item)
+ if _, exists := remaining[slot]; exists {
+ remaining[slot] = item
+ }
+ }
+ slices.SortFunc(inventory.Items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) })
+ // Publish draft reservations only after their durable placement commits.
+ if !slices.Equal(inventory.Items, player.inventory.Items) {
+ if err := server.saveInventory_locked(player, inventory); err != nil {
+ return err
+ }
+ }
+ clear(offers)
+ maps.Copy(offers, remaining)
+ return nil
+}
+
func (item ownedItem) shopPrice() uint32 {
low, high := item.templateIDs()
first, second := gamedata.ItemTemplates[low], gamedata.ItemTemplates[high]
@@ -282,7 +350,9 @@ func (server *server) handleShopTrade(client *worldClient, body []byte) error {
if _, exists := client.shop.items[second[1]]; first != [2]uint32{50000, client.id} || second[0] != 108 || !exists {
return server.abortShop_locked(client)
}
- delete(client.shop.items, second[1])
+ if err := server.restoreTradeItems_locked(client, client.shop.items, []uint32{second[1]}); err != nil {
+ return err
+ }
return client.send(shopTradePacket([2]uint32{50000, client.id}, action, first, second))
case 1, 6:
if first != [2]uint32{} || second != [2]uint32{} {
diff --git a/server/shops_test.go b/server/shops_test.go
@@ -285,7 +285,7 @@ func TestShopRemovingAnOfferKeepsTheOtherTradeSlotsStable(t *testing.T) {
if restored.Credits != 125 || !reflect.DeepEqual(restored.Items, []ownedItem{
{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1},
- {ID: 3, Type: 51005, Template: 43552, Quality: 1, Slot: 66, Count: 1},
+ {ID: 3, Type: 51005, Template: 43552, Quality: 1, Slot: 65, Count: 1},
}) {
t.Fatal("removing offers shifted the remaining trade slot or sold the wrong item")
}
@@ -494,6 +494,10 @@ func TestShopRejectsChangedOffersAndCreditOverflow(t *testing.T) {
player.appearance = 0x315
}
before := player.inventory
+ before.Items = append([]ownedItem(nil), before.Items...)
+ if scenario == "moved" {
+ before.Items[0].Slot = 64
+ }
err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
diff --git a/server/trade_restoration_test.go b/server/trade_restoration_test.go
@@ -0,0 +1,145 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "reflect"
+ "slices"
+ "testing"
+)
+
+func TestShopRestoresOffersIntoNativeFirstFreeSlots(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ offer []uint32
+ remove bool
+ want []ownedItem
+ }{
+ {"cancel noncontiguous", []uint32{64, 70}, false, []ownedItem{
+ {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1},
+ {ID: 2, Type: 51018, Template: 209283, Quality: 1, Slot: 65, Count: 1},
+ }},
+ {"cancel trade order", []uint32{70, 64}, false, []ownedItem{
+ {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 65, Count: 1},
+ {ID: 2, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1},
+ }},
+ {"remove then cancel", []uint32{64, 70}, true, []ownedItem{
+ {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 65, Count: 1},
+ {ID: 2, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1},
+ }},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ world, conn := newShopWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ if granted, err := world.grantItem_locked(player, 209283); err != nil || !granted {
+ t.Fatalf("grant: %v %v", granted, err)
+ }
+ player.inventory.Items[1].Slot = 70
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ for _, slot := range scenario.offer {
+ if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, slot})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if scenario.remove {
+ if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{50000, 1}, [2]uint32{108, 1})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if client.shop.items[0].Slot != 65 || player.inventory.Items[1].Slot != 64 {
+ t.Fatal("returned item collided with another offer's reservation")
+ }
+ }
+ conn.packets = nil
+ if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t).characters[1].inventory
+
+ if client.shop != nil || !reflect.DeepEqual(player.inventory.Items, scenario.want) || !reflect.DeepEqual(restored.Items, scenario.want) || restored.Credits != 100 {
+ t.Fatalf("restored memory=%+v disk=%+v", player.inventory, restored)
+ }
+ if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][33:37]) != 2 {
+ t.Fatal("native cancel acknowledgement missing")
+ }
+ })
+ }
+}
+
+func TestShopFullInventoryCanRemoveReofferAndSellChargedItems(t *testing.T) {
+ world, _ := newShopWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ for range 29 {
+ if granted, err := world.grantItem_locked(player, 85366); err != nil || !granted {
+ t.Fatalf("grant charged kit: %v %v", granted, err)
+ }
+ }
+ for _, slot := range []uint32{64, 93} {
+ if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, slot})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{50000, 1}, [2]uint32{108, 1})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if client.shop.items[0].Slot != 93 || player.inventory.Items[29].Slot != 64 {
+ t.Fatal("full inventory did not reserve the remaining offer away from the restored kit")
+ }
+ if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t).characters[1].inventory
+
+ if client.shop != nil || restored.Credits != 706 || len(restored.Items) != 28 || !reflect.DeepEqual(restored, player.inventory) ||
+ slices.ContainsFunc(restored.Items, func(item ownedItem) bool {
+ return item.ID == 1 || item.ID == 30 || item.Count != 25 || item.Slot < 65 || item.Slot > 92
+ }) {
+ t.Fatalf("full inventory reoffer sold the wrong items or changed surviving charges: %+v", restored)
+ }
+}
+
+func TestShopRestorationFailureRetainsDraftAndCanRetry(t *testing.T) {
+ world, conn := newShopWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ player.inventory.Items[0].Slot = 70
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 70})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER fail_restore BEFORE INSERT ON item_locations BEGIN SELECT RAISE(ABORT, 'restore failure'); END"); err != nil {
+ t.Fatal(err)
+ }
+ conn.packets = nil
+ request := shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]
+
+ failed := world.handleShopTrade(client, request)
+ after, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if failed == nil || !bytes.Equal(before, after) || player.inventory.Items[0].Slot != 70 || client.shop == nil || client.shop.items[0].Slot != 70 || len(conn.packets) != 0 {
+ t.Fatal("failed restoration published a layout or cleared its retryable draft")
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_restore"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleShopTrade(client, request); err != nil {
+ t.Fatal(err)
+ }
+ if client.shop != nil || newTestInventoryServer(t).characters[1].inventory.Items[0].Slot != 64 {
+ t.Fatal("restoration retry did not commit")
+ }
+}