aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 93b79520c60771c914aedf087de07478c17b7eb6
parent 37decc5d6fabe3175b4c40219bbbf3022b0be4ef
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 17:13:42 +0000

Restore worn icons after refused container deposits

Diffstat:
MTODO.md | 17+++++++++++++++++
Mdocs/backpacks.md | 34++++++++++++++++++++++++++++++++++
Mserver/backpacks.go | 8++++++++
Mserver/backpacks_test.go | 7++++++-
Aserver/browser_worn_container_deposit_test.go | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/worn_container_deposit_test.go | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_worn_container_deposit.mjs | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 410 insertions(+), 1 deletion(-)

diff --git a/TODO.md b/TODO.md @@ -246,6 +246,14 @@ recorded in [inventory behavior](docs/inventory.md). ## Stacks and backpacks +- [ ] [P1] Recover and implement direct worn-to-container transfers. Original + native input emits page101:6 and page102:21 deposits into an open backpack; + the server currently refuses them with source cancellation. Recover original + admission, delay and reply ordering for backpack and bank destinations before + combining unwear effects and placement. Check exact identities/effects, + occupied/full destinations, pending equipment, failed commits and native + page/cold recovery, without silently requiring an intermediate carried slot. + - [ ] [P2] Merge one stackable item type. Check: compatible stacks combine up to the applicable limit without changing the total item count. - [x] Split a stack. Check: splitting a known quantity produces two persistent @@ -4400,6 +4408,15 @@ and server restarts. Turn every reproduced bug into a focused regression test. wear, recovers/retries the loaded pistol and retains all four exact instances. This controlled checkpoint leaves the broader disappearance audit open; see [stale carried deposits](docs/backpacks.md#stale-carried-deposit-sources). +- [x] [P0] Restore worn sources after unsupported direct container deposits. + Real weapon/armor drops into an open backpack sent a move, hid the source and + received no reply. Validated cancellation146 restores the usable icon without + ownership writes or repeated wear effects. Handler cases cover weapon, HUD, + deck, armor and implant sources, both destinations, repeats, invalid rows and + unchanged pending equipment. A 27-second WASM check picks both corrected icons + again, removes/deposits normally and retains all three IDs and exact armor + effects through page/cold recovery. Direct transfer acceptance remains P1; + see [worn deposit refusals](docs/backpacks.md#direct-worn-deposit-refusals). - [x] [P0] Preserve selected-quality stack contracts after a refused split. Reproduction: a real QL2 Ctrl-split during a controlled pending equip rebuilt its native endpoints as 25811/25811 instead of 25812/25811. Resolve the shared diff --git a/docs/backpacks.md b/docs/backpacks.md @@ -377,6 +377,40 @@ and ledger report is `local/stale-container-deposit/verification.json`. The pending-deposit baseline fails in 21.21 seconds; the corrected scenario passes in 18.30. Its evidence and independent report are in `local/pending-stale-deposit/`. +## Direct worn deposit refusals + +Real native dragging from RHAND101:6 or chest102:21 into an open bag emits +InventoryMove with that worn source and target51017. The container handler +previously ignored these pages, leaving an empty equipment icon while the +physical item remained server-owned and worn. The cursor was already empty. + +Direct transfers remain unsupported. A validated owned worn source now gets +CharacterAction146 with its actual page/slot. This restores the icon without +unwearing the item, changing its effects, transferring ownership or writing +storage. A pending move's own source/destination is protected; unrelated +equipment continues with the same identity and deadline. Bank destinations +use the same source refusal after their existing availability gate. + +An initial same-slot InventoryMove reply reached the client but left RHAND +blank. Receiving a reply therefore did not prove correction. The accepted +fixture requires a second real pickup of each restored source, ordinary +unequip into inventory and a successful carried deposit into the same bag. +It verifies all eight AC values before refusal and after actual armor removal, +page replay of both exact stored items, and cold ownership of all three IDs. +It uses controlled gear and explicitly advances admitted equipment deadlines; +this is not earned-progression or original-server acceptance-policy evidence. + +Public-handler checks cover weapon, HUD, deck, armor and implant pages, both +bag/bank routes, repeats, invalid/empty rows, protected pending slots, unrelated +equipment completion, unchanged sessions and zero refusal writes. The real +WASM baseline fails in 22.10 seconds; the complete corrected scenario passes +in 27.03. Captures, the rejected first candidate and independent checks are +retained under `local/worn-container-deposit/`. The open direct-transfer TODO +keeps original admission, delay and reply ordering separate from this source +restoration fix. +The related Go run passes 15 roots/87 results normally and under race detection; +vet and driver syntax pass. Seven complete native traces have no errors/drops. + ## Verification `server/backpacks_test.go` exercises the actual world connection for opening and diff --git a/server/backpacks.go b/server/backpacks.go @@ -223,6 +223,14 @@ func (server *server) moveContainerItem_locked(client *worldClient, body []byte) } sourceSlot &= 65535 items = inventory.Containers[sourceBag] + } else if sourcePage == 101 && sourceSlot > 0 && sourceSlot < 16 || + sourcePage == 102 && sourceSlot >= 16 && sourceSlot < 32 || sourcePage == 103 && sourceSlot >= 33 && sourceSlot <= 45 { + // Direct worn deposits are unsupported; restore their validated native source. + if !slices.ContainsFunc(items, func(item ownedItem) bool { return item.Slot == sourceSlot }) || + client.equipment != nil && (sourceSlot == client.equipment.source || sourceSlot == client.equipment.destination) { + return nil + } + return client.send(characterActionPacket(client.id, [5]uint32{146, sourcePage, sourceSlot})) } else if sourcePage != 104 || sourceSlot < 64 || sourceSlot >= 94 { return nil } diff --git a/server/backpacks_test.go b/server/backpacks_test.go @@ -271,7 +271,12 @@ func TestBackpackConcurrentTransferAndFailedSave(t *testing.T) { t.Fatal(err) } } - if err == nil || !reflect.DeepEqual(world.characters[1].inventory, before) || len(conn.packets) != 1 || len(before.Containers[3]) != 1 || len(before.Items) != 4 { + expected := [][]byte{ + targetPacket(backpackMoveRequest(104, 68, 51017, 3, 0)), + targetPacket(characterActionPacket(1, [5]uint32{146, 104, 68})), + targetPacket(characterActionPacket(1, [5]uint32{112, 104, 68})), + } + if err == nil || !reflect.DeepEqual(world.characters[1].inventory, before) || !reflect.DeepEqual(conn.packets, expected) || len(before.Containers[3]) != 1 || len(before.Items) != 4 { t.Fatal("repeat transfer or failed save changed ownership", err) } } diff --git a/server/browser_worn_container_deposit_test.go b/server/browser_worn_container_deposit_test.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" +) + +func TestBrowserWornContainerDeposit(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for a worn source deposited into a backpack") + } + + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/worn-container-deposit", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.level = 2 + player.stats.Abilities.Sense, player.stats.Abilities.Agility = 8, 8 + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("worn-container-deposit"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 3, Items: []ownedItem{ + {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}, + {ID: 2, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}, + {ID: 3, Type: 51022, Template: 85481, Quality: 1, Slot: 21, Count: 1}}} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + var pending any + if client := world.clients[1]; client != nil && client.equipment != nil { + pending = map[string]any{"itemID": client.equipment.itemID, "source": client.equipment.source, + "destination": client.equipment.destination, "readyAt": client.equipment.readyAt} + } + var armor [8]int32 + for index := range armor { + armor[index] = player.equipmentBonus(90 + uint32(index)) + } + json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "pending": pending, "armor": armor}) + }) + mux.HandleFunc("POST /test-complete", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + finish := world.clients[1].equipment.readyAt + world.mutex.Unlock() + world.advanceEquipment(finish) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_worn_container_deposit.mjs"), host.URL, output) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + t.Logf("Browser artifacts: %s", output) + + if err != nil { + t.Fatal(err) + } + expected := playerInventory{LastID: 3, Items: []ownedItem{{ID: 2, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}}, + Containers: map[uint32][]ownedItem{2: { + {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 0, Count: 1}, + {ID: 3, Type: 51022, Template: 85481, Quality: 1, Slot: 1, Count: 1}}}} + cold := newTestInventoryServer(t) + if !reflect.DeepEqual(player.inventory, expected) || !reflect.DeepEqual(cold.characters[1].inventory, expected) || + world.nextItem != 3 || cold.nextItem != 3 { + t.Fatal("refused worn deposit and ordinary retry lost ownership") + } +} diff --git a/server/worn_container_deposit_test.go b/server/worn_container_deposit_test.go @@ -0,0 +1,157 @@ +package main + +import ( + "bytes" + "fmt" + "maps" + "reflect" + "slices" + "testing" +) + +func TestWornContainerDepositRestoresOwnedSource(t *testing.T) { + for _, destination := range []uint32{51017, 57005} { + for _, worn := range [][3]uint32{{101, 6, 209283}, {101, 3, 161699}, {101, 9, 36779}, {102, 21, 85481}, {103, 37, 101173}} { + for _, pending := range []bool{false, true} { + t.Run(fmt.Sprintf("destination%d/page%d/slot%d/pending%v", destination, worn[0], worn[1], pending), func(t *testing.T) { + world, output := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + if worn[1] == 9 { + if granted, err := world.grantItem_locked(player, 36783); err != nil || !granted { + t.Fatal(granted, err) + } + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[len(inventory.Items)-1].Slot = 7 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + } + if granted, err := world.grantItem_locked(player, worn[2]); err != nil || !granted { + t.Fatal(granted, err) + } + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[len(inventory.Items)-1].Slot = worn[1] + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]); err != nil { + t.Fatal(err) + } + var move equipmentMove + if pending { + template, target := uint32(209283), uint32(6) + if worn[1] == 6 { + template, target = 85481, 21 + } + if granted, err := world.grantItem_locked(player, template); err != nil || !granted { + t.Fatal(granted, err) + } + source := player.inventory.Items[len(player.inventory.Items)-1].Slot + if err := world.handleInventory(client, inventoryMovePacket(1, source, target)[20:]); err != nil || client.equipment == nil { + t.Fatal("unrelated fixture equipment did not begin", err) + } + move = *client.equipment + } + target := uint32(3) + if destination == 57005 { + target = 1 + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + inventory, handles, bank := player.inventory, maps.Clone(client.backpacks), *client.bank + auditCheckpointWrites(t, world) + output.packets = nil + + for range 2 { + if err := world.handleInventory(client, backpackMoveRequest(worn[0], worn[1], destination, target, 111)[20:]); err != nil { + t.Fatal(err) + } + } + after, err := readTestItemStore(world) + + packet := targetPacket(characterActionPacket(1, [5]uint32{146, worn[0], worn[1]})) + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || + !reflect.DeepEqual(player.inventory, inventory) || !reflect.DeepEqual(newTestInventoryServer(t).characters[1].inventory, inventory) || + !reflect.DeepEqual(client.backpacks, handles) || *client.bank != bank || + pending != (client.equipment != nil) || client.equipment != nil && *client.equipment != move || + !reflect.DeepEqual(output.packets, [][]byte{packet, packet}) { + t.Fatal("worn deposit omitted correction or changed ownership, sessions, pending move or writes", err, len(output.packets)) + } + if pending { + world.advanceEquipment(move.readyAt) + expected := inventory + expected.Items = slices.Clone(inventory.Items) + expected.Items[len(expected.Items)-1].Slot = move.destination + if client.equipment != nil || !reflect.DeepEqual(player.inventory, expected) || + !reflect.DeepEqual(newTestInventoryServer(t).characters[1].inventory, expected) { + t.Fatal("source correction changed the original equipment completion") + } + } + }) + } + } + } +} + +func TestWornContainerDepositPreservesInvalidAndPendingSources(t *testing.T) { + for _, destination := range []uint32{51017, 57005} { + for _, scenario := range []string{"wrong page", "empty worn row", "pending source", "pending destination"} { + t.Run(fmt.Sprintf("%d/%s", destination, scenario), func(t *testing.T) { + world, output := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + if granted, err := world.grantItem_locked(player, 209283); err != nil || !granted { + t.Fatal(granted, err) + } + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[5].Slot = 6 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + page, source, target := uint32(101), uint32(6), uint32(3) + if destination == 57005 { + target = 1 + } + switch scenario { + case "wrong page": + page = 102 + case "empty worn row": + source = 15 + case "pending source": + if err := world.handleInventory(client, itemMovePacket(1, 6, 69)[20:]); err != nil || client.equipment == nil { + t.Fatal("fixture removal did not begin", err) + } + case "pending destination": + if granted, err := world.grantItem_locked(player, 209283); err != nil || !granted { + t.Fatal(granted, err) + } + if err := world.handleInventory(client, inventoryMovePacket(1, 69, 6)[20:]); err != nil || client.equipment == nil { + t.Fatal("fixture replacement did not begin", err) + } + } + var pending equipmentMove + if client.equipment != nil { + pending = *client.equipment + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + output.packets = nil + + err = world.handleInventory(client, backpackMoveRequest(page, source, destination, target, 111)[20:]) + after, readErr := readTestItemStore(world) + + if err != nil || readErr != nil || !bytes.Equal(before, after) || len(output.packets) != 0 || + (pending.itemID != 0) != (client.equipment != nil) || + client.equipment != nil && *client.equipment != pending { + t.Fatal("invalid or admitted source was corrected or mutated", err, readErr) + } + }) + } + } +} diff --git a/tools/client/test_worn_container_deposit.mjs b/tools/client/test_worn_container_deposit.mjs @@ -0,0 +1,101 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output] = process.argv.slice(2); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [ + '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +let game; +const evidence = {}; +try { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'worn-container-deposit', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + await page.goto(url); + await game.ready(); + const server = async () => (await page.request.get(url + '/test-state')).json(); + const cell = (state, page, slot) => state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === page && cell.identity[1] === slot && !cell.dummy); + const click = async (cell, button = 'left') => { + assert(cell); + await game.click((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2, button); + }; + await game.key('i'); + await click(cell(game.state, 104, 48), 'right'); + await game.wait('empty backpack open', state => state.grids.some(grid => grid.totalCells === 21)); + await page.keyboard.press('Control+1'); + const protection = [5, 5, 1, 1, 5, 5, 1, 5]; + assert.deepEqual(game.local().effectiveArmor, protection); + for (const item of [ + {name: 'weapon', id: 1, page: 101, slot: 6, tab: 867, x: 867, y: 206}, + {name: 'armor', id: 3, page: 102, slot: 21, tab: 953, x: 927, y: 148}]) { + // Refuse the real direct deposit without changing ownership or worn effects. + await game.click(item.tab, 53); + const before = await server(), sequence = game.sequence; + await game.click(item.x, item.y); + await game.wait('worn source picked', state => state.dragged[0] === item.page && state.dragged[1] === item.slot); + await click(game.state.grids.find(grid => grid.totalCells === 21).cells.find(cell => cell.identity[0] === 0)); + await game.wait('real worn-to-backpack request', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '47537a24' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === item.page && Buffer.from(event.hex, 'hex').readUInt32BE(37) === 51017)); + await game.save(output + '/' + item.name + '-requested'); + await game.wait('worn deposit receives cancellation', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framereceived' && event.opcode === '5e477770')); + const replies = game.events.filter(event => event.sequence > sequence && event.direction === 'framereceived' && + event.opcode === '5e477770').map(event => Array.from({length: 5}, (_, index) => Buffer.from(event.hex, 'hex').readUInt32BE(29 + index * 4))); + assert.deepEqual(replies, [[146, item.page, item.slot, 0, 0]]); + evidence[item.name] = {before, refused: await server()}; + assert.deepEqual(evidence[item.name].refused, before); + assert.deepEqual(game.local().effectiveArmor, protection); + assert.deepEqual(game.state.dragged, [0, 0]); + await game.save(output + '/' + item.name + '-corrected'); + + // Pick that same icon again, remove normally, then deposit its carried proxy. + await game.click(item.x, item.y); + await game.wait('corrected worn icon can be picked again', state => state.dragged[0] === item.page && state.dragged[1] === item.slot); + const removal = game.sequence; + await click(game.state.grids.find(grid => grid.totalCells === 30).cells.find(cell => cell.identity[0] === 0)); + await game.wait('real ordinary equipment removal', () => game.events.some(event => event.sequence > removal && + event.direction === 'framesent' && event.opcode === '47537a24' && Buffer.from(event.hex, 'hex').readUInt32BE(37) === 50000)); + evidence[item.name].pending = await server(); + assert.equal(evidence[item.name].pending.pending.itemID, item.id); + assert((await page.request.post(url + '/test-complete')).ok()); + await game.wait('exact item becomes carried', state => game.local(state).inventory.some(owned => owned.id === item.id && owned.slot >= 48)); + await game.wait('ordinary removal animation ends', state => !game.local(state).actions.includes(3) && !game.local(state).actions.includes(6)); + const carried = game.local().inventory.find(owned => owned.id === item.id); + await click(cell(game.state, 104, carried.slot)); + await game.wait('retained carried source picked', state => state.dragged[0] === 104 && state.dragged[1] === carried.slot); + await click(game.state.grids.find(grid => grid.totalCells === 21).cells.find(cell => cell.identity[0] === 0)); + const packed = 1 << 16 | (item.id === 1 ? 0 : 1); + await game.wait('ordinary deposit succeeds', state => cell(state, 107, packed)); + evidence[item.name].after = await server(); + assert.equal(evidence[item.name].after.pending, null); + if (item.id === 3) protection.fill(0); + await game.wait('worn protection changes exactly once', state => game.local(state).effectiveArmor.every((value, index) => value === protection[index])); + assert.deepEqual(evidence[item.name].after.armor, protection); + await game.save(output + '/' + item.name + '-retried'); + } + evidence.after = await server(); + assert.deepEqual(evidence.after.inventory.Items.map(item => [item.ID, item.Slot]), [[2, 64]]); + assert.deepEqual(evidence.after.inventory.Containers[2].map(item => [item.ID, item.Slot]), [[1, 0], [3, 1]]); + await page.reload(); + await game.ready(); + if (!cell(game.state, 104, 48)) await game.key('i'); + await click(cell(game.state, 104, 48), 'right'); + await game.wait('both exact stored items replay', state => cell(state, 107, 65536) && cell(state, 107, 65537)); + assert.deepEqual(await server(), evidence.after); + assert.deepEqual(game.local().effectiveArmor, [0, 0, 0, 0, 0, 0, 0, 0]); + console.log('PASS: worn weapon/armor refusals restore usable icons; normal removal/deposit and page/cold recovery conserve all three instances'); + assert.deepEqual(game.errors, []); + assert.equal(game.dropped, 0); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n'); + if (game) await game.save(output + '/final'); + } finally { await browser.close(); } +}