aorecomp

Anarchy Online classic in the browser

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


commit 54adf801e78d0fe72a7068532f5f90e94556844f
parent 844245d1a9d227e126b07b247355d2fd99cd9e73
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 03:36:34 +0000

Restore stale reclaim sources without shifting remaining slots

Diffstat:
MTODO.md | 8++++++++
Mdocs/reclaim.md | 22++++++++++++++++++++++
Aserver/browser_stale_reclaim_test.go | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/reclaim.go | 23+++++++++++++++++++----
Mserver/reclaim_test.go | 2+-
Aserver/stale_reclaim_test.go | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_stale_reclaim.mjs | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 301 insertions(+), 5 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -4057,6 +4057,14 @@ and server restarts. Turn every reproduced bug into a focused regression test. both directions during wear/removal without writes or deadline changes. No product defect reproduced on this path; see [backpack joins](docs/backpacks.md#stack-join-during-pending-equipment). +- [x] [P0] Refresh stale reclaim withdrawals. Reproduction: a controlled earlier + collection/bank transfer leaves an old native source visible; clicking its + already-collected snapshot slot receives no reply and hides the icon. Source + cancellation followed by current contents now removes the ghost and preserves + the remaining slot for same-window pickup. A short WASM check and public-handler + regressions retain both exact instances through page/cold recovery, with no + writes or allocation for repeated stale refusals. The broader disappearance + audit remains open. See [stale reclaim](docs/reclaim.md#stale-collected-sources). - [x] [P0] Prevent banked backpack updates from replacing native character rows. Reproduction: opening a bank with bag2 in bank slot6 replaces worn weapon1's native slot6 identity, while its old templates and durable ownership remain. diff --git a/docs/reclaim.md b/docs/reclaim.md @@ -150,6 +150,28 @@ changing playfield, the server clears its snapshot mapping, cancels the pending page106 move with146 and closes the native window with110. Ownership remains unchanged. Returning to a booth can open a fresh mapping of the same items. +### Stale collected sources + +A pickup for an already-collected snapshot slot previously received no reply, +leaving its native source hidden. The server now sends source cancellation146 +before current ReclaimIIR contents. The encoder omits cleared entries while +retaining every remaining entry's original window slot. The stale refusal does +not write ownership, allocate an item or report another successful transfer. +Requests outside the authenticated open snapshot remain ignored. + +`TestReclaimStaleWithdrawalCancelsAndRefreshesWithoutWrites` covers both a cleared +slot and a still-mapped missing identity, with empty and nonempty remaining +contents. Repeated requests preserve byte-identical storage, zero checkpoint +writes, exact cold ownership and the remaining slot/flags/identity. +`TestBrowserStaleReclaimWithdrawal` uses a controlled earlier collection into +bank storage without refreshing the native reclaim view. Its real stale pickup +is cancelled, the ghost disappears, and the original slot1 remains usable for +same-window collection. Native page replay and cold loading retain banked1 and +carried2 without duplication or cash changes. The fixture controls location, +available reclaim and the missed refresh; it is not earned-death evidence. +Captures are in `local/stale-reclaim/`, including the failing baseline and the +21-second passing check `20261103-193314/`. + ## Verification `TestBrowserReclaimDuringPlayerTrade` opens reclaim and then receives a normal diff --git a/server/browser_stale_reclaim_test.go b/server/browser_stale_reclaim_test.go @@ -0,0 +1,89 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserStaleReclaimWithdrawal(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for stale reclaim withdrawal") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/stale-reclaim", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.level, player.appearance = 10, 0x515 + player.playfield, player.position = 705, [3]float32{598, 16.9, 329} + player.rotation = [4]float32{0, .70710677, 0, .70710677} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("stale-reclaim"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 2, Reclaim: []reclaimItem{ + {ownedItem{ID: 1, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}, time.Now().Add(-time.Hour).UTC()}, + {ownedItem{ID: 2, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}, time.Now().Add(-time.Hour).UTC()}}} + 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) + }) + // Isolate an earlier collected/banked item without refreshing the reclaim view. + mux.HandleFunc("POST /test-stale-view", func(w http.ResponseWriter, r *http.Request) { + world.updateMutex.Lock() + defer world.updateMutex.Unlock() + world.mutex.Lock() + defer world.mutex.Unlock() + inventory := player.inventory + item := inventory.Reclaim[0].Item + item.Slot = 0 + inventory.Bank = []ownedItem{item} + inventory.Reclaim = slices.Clone(inventory.Reclaim[1:]) + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Error(err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + world.clients[1].reclaimItems[0] = 0 + }) + 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_stale_reclaim.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 := []ownedItem{{ID: 2, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}} + banked := []ownedItem{{ID: 1, Type: 51005, Template: 42640, Quality: 1, Slot: 0, Count: 1}} + cold := newTestInventoryServer(t) + if !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || + !slices.Equal(player.inventory.Bank, banked) || !slices.Equal(cold.characters[1].inventory.Bank, banked) || + len(player.inventory.Reclaim) != 0 || len(cold.characters[1].inventory.Reclaim) != 0 || + player.inventory.Credits != 0 || cold.characters[1].inventory.Credits != 0 || world.nextItem != 2 || cold.nextItem != 2 { + t.Fatal("stale reclaim request lost or duplicated an exact instance", player.inventory, cold.characters[1].inventory) + } +} diff --git a/server/reclaim.go b/server/reclaim.go @@ -40,15 +40,21 @@ func (server *server) nearReclaim_locked(client *worldClient) bool { } func reclaimInventoryPacket(player *character, slots []uint32) []byte { - body := binary.BigEndian.AppendUint32(nil, uint32(len(slots)+1)*1009) + body := binary.BigEndian.AppendUint32(nil, 1009) + count := uint32(1) for slot, id := range slots { + if id == 0 { + continue + } index := slices.IndexFunc(player.inventory.Reclaim, func(entry reclaimItem) bool { return entry.Item.ID == id }) item := player.inventory.Reclaim[index].Item low, high := item.templateIDs() for _, value := range []uint32{uint32(slot), 0x00030000 | uint32(item.Count), item.Type, item.ID, low, high, item.Quality, 0} { body = binary.BigEndian.AppendUint32(body, value) } + count++ } + binary.BigEndian.PutUint32(body, count*1009) body = binary.BigEndian.AppendUint32(body, player.id) return n3Packet(0x52213420, 50000, player.id, body) } @@ -101,8 +107,7 @@ func (server *server) takeReclaim(client *worldClient, body []byte) error { if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || binary.BigEndian.Uint32(body[24:28]) != 50000 || binary.BigEndian.Uint32(body[28:32]) != client.id || - binary.BigEndian.Uint32(body[32:36]) != 111 || source >= uint32(len(client.reclaimItems)) || - client.reclaimItems[source] == 0 { + binary.BigEndian.Uint32(body[32:36]) != 111 || source >= uint32(len(client.reclaimItems)) { server.mutex.Unlock() return nil } @@ -115,7 +120,17 @@ func (server *server) takeReclaim(client *worldClient, body []byte) error { return client.send(characterActionPacket(client.id, [5]uint32{110})) } index := slices.IndexFunc(player.inventory.Reclaim, func(entry reclaimItem) bool { return entry.Item.ID == client.reclaimItems[source] }) - if index < 0 || time.Now().Before(player.inventory.Reclaim[index].AvailableAt) { + if index < 0 { + // Retain the other snapshot slots while removing an already-collected source. + client.reclaimItems[source] = 0 + packet := reclaimInventoryPacket(player, client.reclaimItems) + server.mutex.Unlock() + if err := client.send(characterActionPacket(client.id, [5]uint32{146, 106, source})); err != nil { + return err + } + return client.send(packet) + } + if time.Now().Before(player.inventory.Reclaim[index].AvailableAt) { server.mutex.Unlock() return nil } diff --git a/server/reclaim_test.go b/server/reclaim_test.go @@ -143,7 +143,7 @@ func TestReclaimPendingThenPrivatePickupPersistsOnce(t *testing.T) { t.Fatalf("incorrect native pickup: %x", moved) } expected := ownedItem{ID: 3, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1} - if len(player.inventory.Items) != 3 || player.inventory.Items[2] != expected || len(player.inventory.Reclaim) != 0 || len(conn.packets) != count || + if len(player.inventory.Items) != 3 || player.inventory.Items[2] != expected || len(player.inventory.Reclaim) != 0 || len(conn.packets) != count+2 || !reflect.DeepEqual(player.inventory.Items, restarted.characters[1].inventory.Items) || len(restarted.characters[1].inventory.Reclaim) != 0 || restarted.characters[1].inventory.LastID != player.inventory.LastID { t.Fatal("pickup lost or duplicated an item") diff --git a/server/stale_reclaim_test.go b/server/stale_reclaim_test.go @@ -0,0 +1,94 @@ +package main + +import ( + "bytes" + "encoding/binary" + "reflect" + "slices" + "testing" + "time" +) + +func TestReclaimStaleWithdrawalCancelsAndRefreshesWithoutWrites(t *testing.T) { + for _, remaining := range []bool{false, true} { + for _, mapped := range []bool{false, true} { + name := "empty" + if remaining { + name = "remaining item" + } + if mapped { + name += "/stale identity" + } else { + name += "/collected slot" + } + t.Run(name, func(t *testing.T) { + world, conn := newReclaimWorld(t) + player, client := world.characters[1], world.clients[1] + inventory := player.inventory + inventory.LastID = 5 + inventory.Reclaim = []reclaimItem{ + {ownedItem{ID: 4, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}, time.Now().Add(-time.Hour).UTC()}} + if remaining { + inventory.Reclaim = append(inventory.Reclaim, reclaimItem{ + ownedItem{ID: 5, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}, time.Now().Add(-time.Hour).UTC()}) + } + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if err := world.handleReclaim(client, reclaimRequest(109)); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, reclaimTakeRequest(0)); err != nil { + t.Fatal(err) + } + if mapped { + client.reclaimItems[0] = 4 + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + expected := player.inventory + auditCheckpointWrites(t, world) + conn.packets = nil + + for range 2 { + if err := world.handleInventory(client, reclaimTakeRequest(0)); err != nil { + t.Fatal(err) + } + } + after, err := readTestItemStore(world) + cold := newTestInventoryServer(t) + + mapping := []uint32{0} + if remaining { + mapping = append(mapping, 5) + } + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || + !reflect.DeepEqual(expected, player.inventory) || !reflect.DeepEqual(expected, cold.characters[1].inventory) || + !slices.Equal(client.reclaimItems, mapping) || world.nextItem != 5 || cold.nextItem != 5 { + t.Fatal("stale reclaim changed ownership, allocation or the remaining window slot", err) + } + if len(conn.packets) != 4 { + t.Fatalf("two stale withdrawals need cancellation and current contents each: got %d packets", len(conn.packets)) + } + for index := 0; index < len(conn.packets); index += 2 { + cancel, contents := conn.packets[index], conn.packets[index+1] + if binary.BigEndian.Uint32(cancel[16:20]) != 0x5e477770 || + !bytes.Equal(cancel[29:49], []byte{0, 0, 0, 146, 0, 0, 0, 106, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) || + binary.BigEndian.Uint32(contents[16:20]) != 0x52213420 { + t.Fatal("stale reclaim did not cancel before refreshing its own window") + } + if remaining { + if binary.BigEndian.Uint32(contents[29:33]) != 2018 || binary.BigEndian.Uint32(contents[33:37]) != 1 || + binary.BigEndian.Uint32(contents[37:41]) != 0x00030001 || binary.BigEndian.Uint32(contents[45:49]) != 5 { + t.Fatalf("remaining reclaim row changed slots, flags or identity: %x", contents) + } + } else if binary.BigEndian.Uint32(contents[29:33]) != 1009 || binary.BigEndian.Uint16(contents[6:8]) != 37 { + t.Fatalf("empty reclaim retained a ghost: %x", contents) + } + } + }) + } + } +} diff --git a/tools/client/test_stale_reclaim.mjs b/tools/client/test_stale_reclaim.mjs @@ -0,0 +1,68 @@ +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: 'stale-reclaim', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + const server = async () => (await page.request.get(url + '/test-state')).json(); + const source = (state, slot) => state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 106 && cell.identity[1] === slot && !cell.dummy); + const click = async cell => game.click((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2); + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + await game.key('KeyI'); + await game.click(...await game.pick(51059, 3221881537), 'right'); + await game.wait('both reclaim sources open', state => source(state, 0) && source(state, 1)); + assert((await page.request.post(url + '/test-stale-view')).ok()); + evidence.transferred = await server(); + assert.equal(evidence.transferred.Items, null); + assert.deepEqual(evidence.transferred.Bank.map(item => [item.ID, item.Slot]), [[1, 0]]); + assert.deepEqual(evidence.transferred.Reclaim.map(entry => entry.Item.ID), [2]); + await game.save(output + '/stale'); + const sequence = game.sequence; + await click(source(game.state, 0)); + await game.wait('actual stale reclaim withdrawal', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '47537a24' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === 106 && Buffer.from(event.hex, 'hex').readUInt32BE(33) === 0)); + await game.wait('stale reclaim request cancelled', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framereceived' && event.opcode === '5e477770' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === 146)); + await game.wait('reclaim refresh removes ghost and preserves remaining slot', state => !source(state, 0) && source(state, 1)); + assert.deepEqual(game.state.dragged, [0, 0]); + assert.deepEqual(await server(), evidence.transferred); + await game.save(output + '/refused'); + await click(source(game.state, 1)); + await game.wait('remaining item collected in same window', state => game.local(state).inventory.some(item => item.id === 2 && item.slot === 48)); + evidence.after = await server(); + assert.deepEqual(evidence.after.Items.map(item => [item.ID, item.Slot]), [[2, 64]]); + assert.deepEqual(evidence.after.Bank, evidence.transferred.Bank); + assert.equal(evidence.after.Reclaim, null); + await game.save(output + '/collected'); + await page.reload(); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.count]), [[2, 48, 1]]); + assert.deepEqual(await server(), evidence.after); + assert.deepEqual(game.errors, []); + console.log('PASS: stale reclaim pickup cancelled, stable remaining slot collected and both exact instances retained through 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(); } +}