aorecomp

Anarchy Online classic in the browser

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


commit f12bd68da24528deff8d7c7cc8d380f2a15a1c9a
parent d8130436516050db736bfdce730b60e2e7ba5df3
Author: anon <anon@example.com>
Date:   Tue,  3 Nov 2026 09:46:56 +0000

Restore item sources after full backpack transfer refusals

Diffstat:
MTODO.md | 10++++++++++
Mdocs/backpacks.md | 20++++++++++++++++++++
Aserver/backpack_capacity_test.go | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/backpacks.go | 12+++++++++---
Mserver/backpacks_test.go | 17+++++++++++++----
Aserver/browser_backpack_capacity_test.go | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_full_backpack.mjs | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 315 insertions(+), 7 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -3760,6 +3760,16 @@ and server restarts. Turn every reproduced bug into a focused regression test. admitted-source duplicate remains pending. Public-handler and WASM retry, page replay and cold recovery retain the same axe, bag and contained part. See [pending backpack deposit](docs/backpacks.md#deposit-during-pending-equipment). +- [x] [P0] Restore the carried source after a full-backpack deposit refusal. + Reproduction: open a bag with space, fill its final slot in a controlled server + fixture without refreshing the native view, then deposit a carried item. + The original handler leaves its source hidden without a reply. The existing + source correction now restores that icon without changing ownership. Handler + and short WASM checks verify same-window retry, page replay and all 23 cold-owned + identities. Related Go checks pass 42 roots/122 results, focused race checks + pass 4/14 and vet is clean. This isolates the broader disappearance audit. See + [full destination refusal](docs/backpacks.md#full-destination-refusal) and + `local/full-backpack/verification-summary.json`. - [x] [P0] Correct a late bank withdrawal after its session becomes unavailable during pending equipment. Public-handler cases reproduce no reply after closure or moving beyond the bank anchor. Check explicit native source diff --git a/docs/backpacks.md b/docs/backpacks.md @@ -192,6 +192,26 @@ page replay and cold recovery retain the axe, bag and contained part. This is controlled late-completion evidence. Captures and packet checks are retained in `local/pending-backpack-deposit/`. +## Full destination refusal + +A native view can still show a free bag slot after the server has filled it. +Refusing that deposit without a response leaves the carried source marked dummy +and hidden, although its durable ownership has not changed. Capacity refusals +now restore a validated carried source with the existing two-swap correction. +Packed backpack sources receive CharacterAction 146 with their original page +and packed slot when their destination is full. Existing bank corrections are +unchanged. This uses the recovered native correction contract; it does not +establish which refusal packets the original server sent. + +`TestBackpackFullDepositRestoresSourceForRetry` checks unchanged item-store bytes, +the open handle, explicit correction, normal withdrawal to free a slot, retry +and cold identity retention. `TestBrowserBackpackFullDeposit` keeps one native +slot visibly empty while a controlled fixture fills it, then deposits through +real mouse input. Source restoration, same-window retry, page replay and native +scrolling to the retained final slot pass. A fresh database reader checks all +23 identities. Fixture placement changes are controlled evidence, not earned +progression. Captures are in `local/full-backpack/`. + ## Verification `server/backpacks_test.go` exercises the actual world connection for opening and diff --git a/server/backpack_capacity_test.go b/server/backpack_capacity_test.go @@ -0,0 +1,62 @@ +package main + +import ( + "bytes" + "cmp" + "reflect" + "slices" + "testing" +) + +func TestBackpackFullDepositRestoresSourceForRetry(t *testing.T) { + world, conn := newBackpackWorld(t) + player, client := world.characters[1], world.clients[1] + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 1)[20:]); err != nil { + t.Fatal(err) + } + inventory := player.inventory + inventory.Containers = map[uint32][]ownedItem{3: {}} + for slot := uint32(0); slot < 21; slot++ { + inventory.Containers[3] = append(inventory.Containers[3], ownedItem{ + ID: 6 + slot, Type: 51018, Template: 121567, Quality: 1, Slot: slot, Count: 1}) + } + inventory.LastID = 26 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + conn.packets = nil + request := backpackMoveRequest(104, 68, 51017, 3, 111)[20:] + + if err := world.handleInventory(client, request); err != nil { + t.Fatal(err) + } + after, err := readTestItemStore(world) + + expectedPackets := equipmentCorrectionPackets(1, 68) + for index := range expectedPackets { + expectedPackets[index] = targetPacket(expectedPackets[index]) + } + if err != nil || !bytes.Equal(before, after) || !reflect.DeepEqual(conn.packets, expectedPackets) || + !reflect.DeepEqual(client.backpacks, map[uint32]backpackHandle{1: {3, true}}) { + t.Fatalf("full bag refusal changed ownership or failed to restore its source: packets %x, error %v", conn.packets, err) + } + if err := world.handleInventory(client, backpackMoveRequest(107, 1<<16|20, 50000, 1, 69)[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, request); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t).characters[1].inventory + contents := slices.Clone(cold.Containers[3]) + slices.SortFunc(contents, func(a, b ownedItem) int { return cmp.Compare(a.Slot, b.Slot) }) + if !slices.Equal(player.inventory.Items, cold.Items) || !slices.Equal(player.inventory.Containers[3], contents) || + cold.LastID != 26 || len(cold.Items) != 5 || len(contents) != 21 || + !slices.Contains(cold.Items, ownedItem{ID: 26, Type: 51018, Template: 121567, Quality: 1, Slot: 69, Count: 1}) || + contents[20] != (ownedItem{ID: 5, Type: 51018, Template: 121567, Quality: 1, Slot: 20, Count: 1}) { + t.Fatal("same-window full-bag retry lost or duplicated an instance") + } +} diff --git a/server/backpacks.go b/server/backpacks.go @@ -287,10 +287,16 @@ func (server *server) moveContainerItem_locked(client *worldClient, body []byte) } } if slot < first || slot >= end || slices.ContainsFunc(targetItems, func(item ownedItem) bool { return item.Slot == slot }) { - if bank { - return client.send(characterActionPacket(client.id, [5]uint32{146, sourcePage, binary.BigEndian.Uint32(body[20:24])})) + // Restore a validated source when the destination has no available slot. + if sourcePage == 104 && !bank { + for _, packet := range equipmentCorrectionPackets(client.id, sourceSlot) { + if err := client.send(packet); err != nil { + return err + } + } + return nil } - return nil + return client.send(characterActionPacket(client.id, [5]uint32{146, sourcePage, binary.BigEndian.Uint32(body[20:24])})) } // Commit ownership, quantity and both container locations atomically. diff --git a/server/backpacks_test.go b/server/backpacks_test.go @@ -192,12 +192,15 @@ func TestBackpackRejectsInvalidOwnershipAndPlacement(t *testing.T) { if err != nil { t.Fatal(err) } - packets := len(conn.packets) + expectedPackets := slices.Clone(conn.packets) + if scenario == "occupied main" { + expectedPackets = append(expectedPackets, targetPacket(characterActionPacket(1, [5]uint32{146, 107, 1 << 16}))) + } err = world.handleInventory(client, request) after, readErr := readTestItemStore(world) - if err != nil || readErr != nil || !bytes.Equal(before, after) || len(conn.packets) != packets { + if err != nil || readErr != nil || !bytes.Equal(before, after) || !reflect.DeepEqual(conn.packets, expectedPackets) { t.Fatal("invalid placement changed persisted ownership or sent success", err, readErr) } }) @@ -205,7 +208,7 @@ func TestBackpackRejectsInvalidOwnershipAndPlacement(t *testing.T) { } func TestBackpackCapacityTwentyOneAndFullMainInventory(t *testing.T) { - world, _ := newBackpackWorld(t) + world, conn := newBackpackWorld(t) client, player := world.clients[1], world.characters[1] world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 1)[20:]) for range 21 { @@ -226,12 +229,18 @@ func TestBackpackCapacityTwentyOneAndFullMainInventory(t *testing.T) { t.Fatal(granted, err) } } - world.handleInventory(client, backpackMoveRequest(107, 1<<16|20, 50000, 1, 111)[20:]) + conn.packets = nil + if err := world.handleInventory(client, backpackMoveRequest(107, 1<<16|20, 50000, 1, 111)[20:]); err != nil { + t.Fatal(err) + } restarted := newTestInventoryServer(t).characters[1] if err != nil || !fullBag || len(restarted.inventory.Items) != 30 || len(restarted.inventory.Containers[3]) != 21 || restarted.inventory.Containers[3][20].Slot != 20 { t.Fatalf("capacity rejection lost an item: %+v %v", restarted.inventory, err) } + if !reflect.DeepEqual(conn.packets, [][]byte{targetPacket(characterActionPacket(1, [5]uint32{146, 107, 1<<16 | 20}))}) { + t.Fatalf("full inventory refusal did not restore its packed backpack source: %x", conn.packets) + } } func TestBackpackConcurrentTransferAndFailedSave(t *testing.T) { diff --git a/server/browser_backpack_capacity_test.go b/server/browser_backpack_capacity_test.go @@ -0,0 +1,101 @@ +package main + +import ( + "cmp" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "maps" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "reflect" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserBackpackFullDeposit(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for full-backpack deposit refusal") + } + + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/full-backpack", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.stats = testCharacterStats() + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("full-backpack"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 23, Items: []ownedItem{ + {ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}, + {ID: 2, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}}, + Bank: []ownedItem{{ID: 23, Type: 51005, Template: 42640, Quality: 1, Count: 1}}, + Containers: map[uint32][]ownedItem{1: {}}} + for slot := uint32(0); slot < 20; slot++ { + inventory.Containers[1] = append(inventory.Containers[1], ownedItem{ + ID: 3 + slot, Type: 51005, Template: 42640, Quality: 1, Slot: slot, 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() + json.NewEncoder(w).Encode(player.inventory) + }) + // Keep the native free-slot view stale while changing only fixture placement. + mux.HandleFunc("POST /test-capacity", func(w http.ResponseWriter, r *http.Request) { + world.updateMutex.Lock() + defer world.updateMutex.Unlock() + world.mutex.Lock() + defer world.mutex.Unlock() + inventory := player.inventory + inventory.Containers = maps.Clone(inventory.Containers) + if len(inventory.Bank) != 0 { + item := inventory.Bank[0] + item.Slot = 20 + inventory.Containers[1] = append(slices.Clone(inventory.Containers[1]), item) + inventory.Bank = nil + } else { + item := inventory.Containers[1][20] + item.Slot = 0 + inventory.Bank = []ownedItem{item} + inventory.Containers[1] = slices.Clone(inventory.Containers[1][:20]) + } + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Error(err) + w.WriteHeader(http.StatusInternalServerError) + } + }) + 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_full_backpack.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) + } + cold := newTestInventoryServer(t).characters[1].inventory + slices.SortFunc(cold.Containers[1], func(a, b ownedItem) int { return cmp.Compare(a.Slot, b.Slot) }) + if !reflect.DeepEqual(player.inventory, cold) || len(cold.Items) != 1 || cold.Items[0].ID != 1 || + len(cold.Containers[1]) != 21 || cold.Containers[1][20] != (ownedItem{ID: 2, Type: 51005, Template: 42640, Quality: 1, Slot: 20, Count: 1}) || + !slices.Equal(cold.Bank, []ownedItem{{ID: 23, Type: 51005, Template: 42640, Quality: 1, Count: 1}}) { + t.Fatal("full-backpack retry or cold recovery lost an instance") + } +} diff --git a/tools/client/test_full_backpack.mjs b/tools/client/test_full_backpack.mjs @@ -0,0 +1,100 @@ +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: 'full-backpack', 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 carried = state => state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 104 && cell.identity[1] === 49 && !cell.dummy); + const open = async () => { + const cell = game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy); + assert(cell, 'carried backpack is usable'); + await game.click((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2, 'right'); + }; + await game.key('i'); + await open(); + const bagGrid = state => state.grids.find(grid => grid.totalCells === 21 && + grid.cells.some(cell => cell.identity[0] === 107 && !cell.dummy)); + const scrollToEnd = async () => { + while (!bagGrid(game.state).cells.some(cell => cell.index === 20)) { + const grid = bagGrid(game.state); + const cell = grid.cells[0]; + const point = await game.point((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2); + await page.mouse.move(point.x, point.y); + await page.mouse.wheel(0, 120); + await game.wait('bag scroll row advances', state => bagGrid(state)?.firstRow > grid.firstRow); + } + }; + await game.wait('backpack opens', bagGrid); + await scrollToEnd(); + assert((await page.request.post(url + '/test-capacity')).ok()); + evidence.full = await server(); + assert.equal(evidence.full.Containers[1].length, 21); + const deposit = async () => { + const sequence = game.sequence; + const cell = carried(game.state); + assert(cell, 'carried source is usable'); + await game.click((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2); + await game.wait('carried source picked', state => state.dragged[0] === 104 && state.dragged[1] === 49); + const target = bagGrid(game.state).cells.find(cell => cell.index === 20); + await game.click((target.bounds[0] + target.bounds[2]) / 2, (target.bounds[1] + target.bounds[3]) / 2); + await game.wait('actual backpack deposit', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '47537a24' && + Buffer.from(event.hex, 'hex').readUInt32BE(37) === 51017)); + return sequence; + }; + const sequence = await deposit(); + await game.wait('refused full-bag source restored', state => carried(state) && game.events.some(event => + event.sequence > sequence && event.direction === 'framereceived' && event.opcode === '47537a24')); + evidence.refused = await server(); + assert.deepEqual(evidence.refused, evidence.full); + assert.deepEqual(game.state.dragged, [0, 0]); + await game.save(output + '/refused'); + + // Free only the fixture slot, then retry through the same native window. + assert((await page.request.post(url + '/test-capacity')).ok()); + await deposit(); + await game.wait('same-window retry succeeds', state => !game.local(state).inventory.some(item => item.id === 2) && bagGrid(state)); + evidence.after = await server(); + assert.equal(evidence.after.Items.length, 1); + assert.equal(evidence.after.Items[0].ID, 1); + assert.equal(evidence.after.Containers[1][20].ID, 2); + assert.equal(evidence.after.Bank[0].ID, 23); + assert.deepEqual([...evidence.after.Items, ...evidence.after.Containers[1], ...evidence.after.Bank] + .map(item => item.ID).sort((a, b) => a - b), Array.from({length: 23}, (_, index) => index + 1)); + await game.save(output + '/retried'); + await page.reload(); + await game.ready(); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot]), [[1, 48]]); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + if (!game.state.grids.some(grid => grid.cells.some(cell => cell.identity[0] === 104 && !cell.dummy))) await game.key('i'); + await open(); + await game.wait('backpack retained after page replay', bagGrid); + await scrollToEnd(); + assert(bagGrid(game.state).cells.some(cell => cell.identity[0] === 107 && + cell.identity[1] === (1 << 16 | 20) && !cell.dummy)); + assert.equal(game.errors.length, 0); + console.log('PASS: full-backpack deposit restores its source and permits same-window retry/page/cold recovery'); +} 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(); } +}