aorecomp

Anarchy Online classic in the browser

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


commit 31f04acc6b4f094d531c431cf1518572daede855
parent d005e352d9c20c41773e51822434e1e899f456ad
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 14:32:47 +0000

Clear unrelated stale carried sources during pending equipment

Diffstat:
MTODO.md | 8++++++++
Mdocs/inventory.md | 29+++++++++++++++++++++++++++--
Aserver/browser_pending_stale_equipment_test.go | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/inventory.go | 3++-
Aserver/pending_stale_equipment_test.go | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/stale_inventory_move_test.go | 6+++++-
Atools/client/test_pending_stale_equipment.mjs | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 296 insertions(+), 4 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -4233,6 +4233,14 @@ and server restarts. Turn every reproduced bug into a focused regression test. instances. First/last carried rows and invalid/pending requests have handler checks. The broader disappearance audit remains open. See [stale carried sources](docs/inventory.md#stale-carried-move-sources). +- [x] [P0] Clear an unrelated stale carried source during pending equipment. + A controlled native checkpoint moves a second weapon to another carried slot + without refreshing its old icon. Wearing that old icon while the first equip + is held previously left the second source hidden. Ordered cancellation and + clearing now affect only its empty row, preserving the admitted move and + deadline. Native completion, page replay, recovered replacement and cold + loading retain both physical weapons; the broader audit remains open. See + [pending equipment](docs/inventory.md#another-move-while-equipment-is-pending). - [x] [P0] Clear a stale empty right-hand source after native removal. A controlled earlier transfer leaves the worn axe visible; removal sends101:6 to111 but previously received no reply. Cancellation, the existing unequip notification diff --git a/docs/inventory.md b/docs/inventory.md @@ -196,12 +196,13 @@ Repeated requests for the now-empty slot do nothing. A controlled earlier bank transfer can leave an old carried weapon icon in the native view. Right-click wear still sends a real ContainerAddItem request, but the server previously ignored the empty source, leaving that unusable ghost. -For a current living session with no pending equipment, an ordinary source and +For a current living session, an unrelated ordinary source and an owner-directed valid equipment/carried destination, the server now cancels the source with action146 before clearing just its empty row with action112. This is a private GUI correction: no ownership is deleted, no successful move is reported and no live weapon destruction is sent. The banked physical instance -remains intact. Invalid, foreign and pending-equipment requests keep their guards. +remains intact. Invalid and foreign requests keep their guards; a pending move's +own source and destination remain protected. `TestStaleOrdinaryMoveClearsOnlyEmptySourceWithoutWrites` checks first/last carried rows, repeated cancellation/clear ordering, exact cold ownership, allocation and @@ -716,6 +717,30 @@ inventory captures were reviewed. AO_GAME_TEST=1 go test ./server -run '^TestBrowserSecondEquipmentMove$' -count=1 -timeout=4m -v ``` +An unrelated stale carried row needs the same cancellation while equipment is +pending. A controlled committed move of the second axe from saved slot65 to66 +leaves the old native slot49 visible. Wearing that old icon after the first +axe's local animation ends sends a real request; the old pending guard silently +ignored it. Action146 followed by112 now clears only that empty carried row, +without changing the first axe's identity, placement or completion deadline. +The pending move's own source and destination stay protected. This is GUI +correction of a missed refresh, not deletion of the retained weapon. + +`TestStaleCarriedSourceDuringEquipment` covers wear/removal, two empty source +positions, equipment/carried destinations, repeated requests, zero writes and +exact completion/cold ownership. `TestBrowserStaleSourceDuringEquipment` uses +real native mouse input, checks the ordered replies and unchanged pending state, +completes the first equip, then reloads and equips the exact second weapon from +its committed location. Both fixture identities survive cold loading. The +controlled items, missed refresh and held server completion isolate this issue; +they do not establish earned progression or historical concurrent-equip policy. +Baseline and fixed captures are under `local/pending-stale-equipment/`. +The accepted run `20261104-062815` completes in20.77s. Independent trace checks +confirm all three native requests, the stale row's actual removal and both +retained identities. Focused normal checks pass11 roots/42 results; related +race checks pass29 roots/117 results in175.956s. Maintained-package vet and +JavaScript syntax checks pass; details are in that folder's `verification.json`. + ### Owned-item Use during pending equipment An authenticated owned-item Use arriving during an admitted equipment move now diff --git a/server/browser_pending_stale_equipment_test.go b/server/browser_pending_stale_equipment_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserStaleSourceDuringEquipment(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for a stale source during pending equipment") + } + + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/pending-stale-equipment", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.stats = testCharacterStats() + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("pending-stale-equipment"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + for range 2 { + if granted, err := world.grantItem_locked(player, 209283); err != nil || !granted { + t.Fatal(granted, 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} + } + json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "pending": pending}) + }) + // A committed move with no refresh leaves the second carried icon stale. + 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 + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[1].Slot = 66 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Error(err) + http.Error(w, err.Error(), http.StatusInternalServerError) + } + }) + 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_pending_stale_equipment.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) + expected := []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 66, Count: 1}, + {ID: 2, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}} + if !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || + world.nextItem != 2 || cold.nextItem != 2 { + t.Fatal("stale-source correction lost an equipment instance") + } +} diff --git a/server/inventory.go b/server/inventory.go @@ -360,7 +360,8 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { } } destination := binary.BigEndian.Uint32(body[32:36]) - if index < 0 && client.equipment == nil && key == 0x47537a24 && sourceType == 104 && sourceSlot >= 64 && sourceSlot < 94 && + if index < 0 && (client.equipment == nil || sourceSlot != client.equipment.source && sourceSlot != client.equipment.destination) && + key == 0x47537a24 && sourceType == 104 && sourceSlot >= 64 && sourceSlot < 94 && binary.BigEndian.Uint32(body[24:28]) == 50000 && binary.BigEndian.Uint32(body[28:32]) == client.id && (destination > 0 && destination < 46 && destination != 32 || destination >= 64 && destination < 94) { // Cancel the stale drag before clearing only its now-empty carried row. diff --git a/server/pending_stale_equipment_test.go b/server/pending_stale_equipment_test.go @@ -0,0 +1,75 @@ +package main + +import ( + "bytes" + "fmt" + "slices" + "testing" +) + +func TestStaleCarriedSourceDuringEquipment(t *testing.T) { + for _, removing := range []bool{false, true} { + for _, source := range []uint32{65, 93} { + for _, destination := range []uint32{6, 66} { + t.Run(fmt.Sprintf("removing%v/source%d/destination%d", removing, source, destination), func(t *testing.T) { + world, output := newEquipmentWorld(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[1].Slot = 67 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment == nil { + t.Fatal("fixture equip did not start", err) + } + if removing { + world.advanceEquipment(client.equipment.readyAt) + if err := world.handleInventory(client, itemMovePacket(1, 6, 64)[20:]); err != nil || client.equipment == nil { + t.Fatal("fixture removal did not start", err) + } + } + pending := *client.equipment + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + output.packets = nil + auditCheckpointWrites(t, world) + + for range 2 { + if err := world.handleInventory(client, inventoryMovePacket(1, source, destination)[20:]); err != nil { + t.Fatal(err) + } + } + after, err := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || + client.equipment == nil || *client.equipment != pending || world.nextItem != 2 || len(output.packets) != 4 { + t.Fatal("stale correction changed storage, allocation or the admitted equipment move", err) + } + for index, action := range []uint32{146, 112, 146, 112} { + if !bytes.Equal(output.packets[index], targetPacket(characterActionPacket(1, [5]uint32{action, 104, source}))) { + t.Fatal("stale correction did not cancel then clear only its empty carried row") + } + } + world.advanceEquipment(pending.readyAt) + cold := newTestInventoryServer(t) + expectedSlot := uint32(6) + if removing { + expectedSlot = 64 + } + expected := []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: expectedSlot, Count: 1}, + {ID: 2, Type: 51018, Template: 209283, Quality: 1, Slot: 67, Count: 1}} + if client.equipment != nil || !slices.Equal(player.inventory.Items, expected) || + !slices.Equal(cold.characters[1].inventory.Items, expected) || cold.nextItem != 2 { + t.Fatal("original equipment completion lost either retained weapon") + } + }) + } + } + } +} diff --git a/server/stale_inventory_move_test.go b/server/stale_inventory_move_test.go @@ -84,7 +84,11 @@ func TestStaleOrdinaryMoveIgnoresInvalidOrPendingRequests(t *testing.T) { if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment == nil { t.Fatal("equipment fixture did not begin", err) } - request = inventoryMovePacket(1, 65, 66)[20:] + world.advanceEquipment(client.equipment.readyAt) + if err := world.handleInventory(client, itemMovePacket(1, 6, 64)[20:]); err != nil || client.equipment == nil { + t.Fatal("equipment removal fixture did not begin", err) + } + request = inventoryMovePacket(1, 64, 66)[20:] } pending := client.equipment before, err := readTestItemStore(world) diff --git a/tools/client/test_pending_stale_equipment.mjs b/tools/client/test_pending_stale_equipment.mjs @@ -0,0 +1,87 @@ +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: 'pending-stale-equipment', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + const server = async () => (await page.request.get(url + '/test-state')).json(); + const cell = slot => game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 104 && cell.identity[1] === slot && !cell.dummy); + const equip = async slot => { + const source = cell(slot); + assert(source, 'equipment source must be usable'); + const sequence = game.sequence; + await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2); + await game.click(867, 206); + await game.wait('actual equipment request', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '47537a24' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === 104 && Buffer.from(event.hex, 'hex').readUInt32BE(33) === slot)); + return sequence; + }; + const idle = () => game.wait('native equip animation ends', state => + !game.local(state).actions.includes(3) && !game.local(state).actions.includes(6)); + await page.goto(url); + await game.ready(); + await game.key('i'); + await page.keyboard.press('Control+1'); + await game.wait('both fixture weapons visible', () => cell(48) && cell(49)); + assert((await page.request.post(url + '/test-stale-view')).ok()); + await equip(48); + evidence.pending = await server(); + assert(evidence.pending.pending); + await idle(); + + // The second native request addresses the old, now-empty carried row. + const sequence = await equip(49); + evidence.refused = await server(); + assert.deepEqual(evidence.refused, evidence.pending); + await game.save(output + '/requested'); + await game.wait('stale source cancelled and cleared during pending equipment', () => + !cell(49) && game.events.filter(event => event.sequence > sequence && + event.direction === 'framereceived' && event.opcode === '5e477770').length >= 2); + assert.deepEqual(game.events.filter(event => event.sequence > sequence && event.direction === 'framereceived' && + event.opcode === '5e477770').map(event => { + const packet = Buffer.from(event.hex, 'hex'); + return [packet.readUInt32BE(29), packet.readUInt32BE(33), packet.readUInt32BE(37)]; + }), [[146, 104, 49], [112, 104, 49]]); + assert.deepEqual(game.state.dragged, [0, 0]); + await game.save(output + '/corrected'); + assert((await page.request.post(url + '/test-complete')).ok()); + await game.wait('original pending weapon completes', state => game.local(state).inventory.some(item => item.id === 1 && item.slot === 6)); + evidence.completed = await server(); + assert.equal(evidence.completed.pending, null); + + // Page recovery exposes the committed location; that exact weapon must equip. + await page.reload(); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + if (!cell(50)) await game.key('i'); + await page.keyboard.press('Control+1'); + await game.wait('both exact retained weapons replay', () => cell(50) && game.local().inventory.some(item => item.id === 1 && item.slot === 6)); + await equip(50); + assert((await page.request.post(url + '/test-complete')).ok()); + await game.wait('recovered weapon replaces original', state => game.local(state).inventory.some(item => item.id === 2 && item.slot === 6)); + evidence.after = await server(); + assert.deepEqual(evidence.after.inventory.Items.map(item => [item.ID, item.Slot, item.Count]), [[1, 66, 1], [2, 6, 1]]); + await game.save(output + '/retained'); + assert.deepEqual(game.errors, []); + console.log('PASS: pending equip survives stale-source correction and both weapons remain usable after 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(); } +}