aorecomp

Anarchy Online classic in the browser

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


commit 073d32874d0250c985c7b5597ce49e38f1754ebf
parent a1d08ce15f8e7da95a4f01cf246f754af3bb5336
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 16:22:51 +0000

Correct stale worn sources during pending equipment

Diffstat:
MTODO.md | 9+++++++++
Mdocs/inventory.md | 39+++++++++++++++++++++++++++++++++++++++
Aserver/browser_pending_stale_worn_test.go | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/inventory.go | 3++-
Aserver/pending_stale_worn_test.go | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/stale_armor_move_test.go | 17+++++++++++++----
Mserver/stale_implant_move_test.go | 17+++++++++++++----
Mserver/stale_non_hand_move_test.go | 17+++++++++++++----
Atools/client/test_pending_stale_worn.mjs | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9 files changed, 369 insertions(+), 13 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -4271,6 +4271,15 @@ and server restarts. Turn every reproduced bug into a focused regression test. usable after page replay and retained by cold loading. Focused wear/removal, boundary-slot and protected-source checks pass; the broader audit remains open. See [pending equipment](docs/inventory.md#another-move-while-equipment-is-pending). +- [x] [P0] Clear unrelated stale worn armor during pending equipment. A controlled + committed vest removal leaves its native row and AC effects visible while an + axe equip is held. Native removal previously received no reply. Cancellation, + the exact cached inverse once and empty-row clearing now remove all eight + effects without changing the pending identity/deadline or writing ownership. + Shared HUD/deck/armor/implant handler checks cover wear/removal and protected + pending destinations. Native axe completion, vest replay/re-wear and cold + loading retain both instances; the broader disappearance audit stays open. See + [pending worn effects](docs/inventory.md#stale-worn-effects-during-pending-equipment). - [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 @@ -768,6 +768,45 @@ checks pass. Independent packet/state checks and source hashes are recorded in AO_GAME_TEST=1 go test ./server -run '^TestBrowserStaleDropDuringEquipment$' -count=1 -timeout=3m -v ``` +### Stale worn effects during pending equipment + +A missed refresh of a completed vest removal leaves native Clothes row21 and +its AC effects visible. With an unrelated axe equip pending, the server formerly +ignored the native102:21 removal request. The controlled QL1 vest retained +native AC `5,5,1,1,5,5,1,5` while the committed server values were all zero. + +The shared worn-source guard now permits correction outside the pending move's +own source and destination. Existing cancellation146, the cached exact unwear +contract and clearing112 remove only the stale row and its effects. The cached +inverse is consumed once, followed by the existing derived-resource refresh. +It does not move or delete the retained item, change the pending deadline or +write inventory. Invalid sources/actors/targets stay rejected. Weapon-hand +correction remains its separate path. + +`TestStaleWornSourceDuringUnrelatedEquipment` checks HUD, deck, armor and implant +sources during axe wear/removal, repeated requests, exact inverses, zero writes, +unchanged pending state and completion/cold ownership. The existing invalid-input +checks also protect an actual pending destination of each item class. +`TestBrowserStaleWornSourceDuringEquipment` uses a controlled level2 character, +Sense8/Agility8, one QL1 vest and one axe. Real Clothes input clears all eight +effects, the original axe equip completes, and page replay exposes the vest's +actual carried slot for successful re-wear. Cold loading retains both IDs. +The held deadline and omitted refresh isolate the defect, without earned +progression or a new historical concurrent-equip policy. + +Baseline `local/pending-stale-worn/20261104-081416` fails in23.13s; fixed +`20261104-081820` passes in20.35s. Corrected and recovered native appearance +captures were visually reviewed; all four accepted traces have no errors or +dropped events. Focused Go checks pass13 roots/145 results in21.194s; race +checks pass14 roots/146 results in110.416s. Maintained-package vet, JavaScript +syntax and whitespace checks pass. +Independent packet/state checks and source hashes are retained in that folder's +`verification.json`. + +```sh +AO_GAME_TEST=1 go test ./server -run '^TestBrowserStaleWornSourceDuringEquipment$' -count=1 -timeout=3m -v +``` + ### 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_worn_test.go b/server/browser_pending_stale_worn_test.go @@ -0,0 +1,103 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserStaleWornSourceDuringEquipment(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for a stale worn source during pending equipment") + } + + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/pending-stale-worn", 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("pending-stale-worn"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + for _, template := range []uint32{209283, 85481} { + if granted, err := world.grantItem_locked(player, template); err != nil || !granted { + t.Fatal(granted, err) + } + } + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[1].Slot = 21 + 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}) + }) + // A committed removal with no refresh leaves the worn vest and its effects 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 = 65 + 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_worn.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: 6, Count: 1}, + {ID: 2, Type: 51022, Template: 85481, Quality: 1, Slot: 21, 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 @@ -384,7 +384,8 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { } return server.sendEquipmentResources_locked(client) } - if index < 0 && client.equipment == nil && key == 0x47537a24 && + if index < 0 && (client.equipment == nil || sourceSlot != client.equipment.source && sourceSlot != client.equipment.destination) && + key == 0x47537a24 && (sourceType == 101 && sourceSlot > 0 && sourceSlot < 16 && sourceSlot != 6 && sourceSlot != 8 || sourceType == 102 && sourceSlot >= 16 && sourceSlot < 32 || sourceType == 103 && sourceSlot >= 33 && sourceSlot <= 45) && binary.BigEndian.Uint32(body[24:28]) == 50000 && binary.BigEndian.Uint32(body[28:32]) == client.id && diff --git a/server/pending_stale_worn_test.go b/server/pending_stale_worn_test.go @@ -0,0 +1,82 @@ +package main + +import ( + "bytes" + "fmt" + "reflect" + "slices" + "testing" +) + +func TestStaleWornSourceDuringUnrelatedEquipment(t *testing.T) { + for _, scenario := range []struct { + name string + page, source uint32 + setup func(*testing.T) (*server, *combatTestConn) + }{ + {"HUD", 101, 3, func(t *testing.T) (*server, *combatTestConn) { return newStaleNonHandMoveWorld(t, 3) }}, + {"deck", 101, 9, func(t *testing.T) (*server, *combatTestConn) { return newStaleNonHandMoveWorld(t, 9) }}, + {"armor", 102, 18, newStaleArmorMoveWorld}, + {"implant", 103, 37, newStaleImplantMoveWorld}, + } { + for _, removing := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/removing%v", scenario.name, removing), func(t *testing.T) { + world, output := scenario.setup(t) + player, client := world.characters[1], world.clients[1] + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment == nil { + t.Fatal("fixture axe equip did not begin", 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 axe removal did not begin", err) + } + } + inventory, pending := player.inventory, *client.equipment + removal := slices.Clone(client.wornRemoval[scenario.source]) + if removal == nil { + t.Fatal("fixture did not retain its published removal contract") + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + output.packets = nil + auditCheckpointWrites(t, world) + + for range 2 { + if err := world.handleInventory(client, itemMovePacket(1, scenario.source, 111)[20:]); err != nil { + t.Fatal(err) + } + } + after, err := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || + !reflect.DeepEqual(player.inventory, inventory) || client.equipment == nil || *client.equipment != pending || + client.wornRemoval[scenario.source] != nil || len(output.packets) != 10 { + t.Fatal("stale worn correction omitted replies or changed storage, pending equip or its removal cache", err, len(output.packets)) + } + for index, action := range map[int]uint32{0: 146, 2: 112, 8: 146, 9: 112} { + if !bytes.Equal(output.packets[index], targetPacket(characterActionPacket(1, [5]uint32{action, scenario.page, scenario.source}))) { + t.Fatal("stale worn correction addressed another row") + } + } + if !bytes.Equal(output.packets[1], targetPacket(removal)) { + t.Fatal("stale worn correction did not use its exact cached inverse") + } + world.advanceEquipment(pending.readyAt) + expected := inventory + expected.Items = slices.Clone(inventory.Items) + expected.Items[0].Slot = 6 + if removing { + expected.Items[0].Slot = 64 + } + cold := newTestInventoryServer(t) + if client.equipment != nil || !reflect.DeepEqual(player.inventory, expected) || + !reflect.DeepEqual(cold.characters[1].inventory, expected) || cold.nextItem != world.nextItem { + t.Fatal("original equipment completion changed retained ownership after stale correction") + } + }) + } + } +} diff --git a/server/stale_armor_move_test.go b/server/stale_armor_move_test.go @@ -106,7 +106,7 @@ func TestStaleArmorMoveUnwearsOnlyItsPublishedTemplateOnce(t *testing.T) { } func TestStaleArmorMovePreservesInvalidAndPendingRequests(t *testing.T) { - for _, scenario := range []string{"foreign actor", "foreign target", "target type", "wrong page", "source before", "source after", "invalid destination", "pending equipment"} { + for _, scenario := range []string{"foreign actor", "foreign target", "target type", "wrong page", "source before", "source after", "invalid destination", "pending destination"} { t.Run(scenario, func(t *testing.T) { world, output := newStaleArmorMoveWorld(t) client := world.clients[1] @@ -126,9 +126,18 @@ func TestStaleArmorMovePreservesInvalidAndPendingRequests(t *testing.T) { binary.BigEndian.PutUint32(request[20:], 32) case "invalid destination": binary.BigEndian.PutUint32(request[32:], 94) - case "pending equipment": - if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment == nil { - t.Fatal("fixture weapon did not start wear", err) + case "pending destination": + player := world.characters[1] + inventory := player.inventory + item := inventory.Bank[0] + item.Slot = 65 + inventory.Items = append(slices.Clone(inventory.Items), item) + inventory.Bank = nil + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, inventoryMovePacket(1, 65, 18)[20:]); err != nil || client.equipment == nil { + t.Fatal("fixture helmet did not start wear into the protected row", err) } } pending := client.equipment diff --git a/server/stale_implant_move_test.go b/server/stale_implant_move_test.go @@ -104,7 +104,7 @@ func TestStaleImplantMoveClearsOnlyTheRequestedEmptyRow(t *testing.T) { } func TestStaleImplantMovePreservesInvalidAndPendingRequests(t *testing.T) { - for _, scenario := range []string{"foreign actor", "foreign target", "target type", "wrong page", "source before", "source after", "invalid destination", "pending equipment"} { + for _, scenario := range []string{"foreign actor", "foreign target", "target type", "wrong page", "source before", "source after", "invalid destination", "pending destination"} { t.Run(scenario, func(t *testing.T) { world, output := newStaleImplantMoveWorld(t) client := world.clients[1] @@ -124,9 +124,18 @@ func TestStaleImplantMovePreservesInvalidAndPendingRequests(t *testing.T) { binary.BigEndian.PutUint32(request[20:], 46) case "invalid destination": binary.BigEndian.PutUint32(request[32:], 94) - case "pending equipment": - if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment == nil { - t.Fatal("fixture weapon did not start wear", err) + case "pending destination": + player := world.characters[1] + inventory := player.inventory + item := inventory.Bank[0] + item.Slot = 65 + inventory.Items = append(slices.Clone(inventory.Items), item) + inventory.Bank = nil + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, inventoryMovePacket(1, 65, 37)[20:]); err != nil || client.equipment == nil { + t.Fatal("fixture implant did not start wear into the protected row", err) } } pending := client.equipment diff --git a/server/stale_non_hand_move_test.go b/server/stale_non_hand_move_test.go @@ -121,7 +121,7 @@ func TestStaleNonHandMoveClearsOnlyTheRequestedEmptyRow(t *testing.T) { } func TestStaleNonHandMovePreservesInvalidAndPendingRequests(t *testing.T) { - for _, scenario := range []string{"foreign actor", "foreign target", "target type", "wrong page", "source before", "source after", "left hand", "invalid destination", "pending equipment"} { + for _, scenario := range []string{"foreign actor", "foreign target", "target type", "wrong page", "source before", "source after", "left hand", "invalid destination", "pending destination"} { t.Run(scenario, func(t *testing.T) { world, output := newStaleNonHandMoveWorld(t, 3) client := world.clients[1] @@ -143,9 +143,18 @@ func TestStaleNonHandMovePreservesInvalidAndPendingRequests(t *testing.T) { binary.BigEndian.PutUint32(request[20:], 8) case "invalid destination": binary.BigEndian.PutUint32(request[32:], 94) - case "pending equipment": - if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment == nil { - t.Fatal("fixture weapon did not start wear", err) + case "pending destination": + player := world.characters[1] + inventory := player.inventory + item := inventory.Bank[0] + item.Slot = 65 + inventory.Items = append(slices.Clone(inventory.Items), item) + inventory.Bank = nil + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, inventoryMovePacket(1, 65, 3)[20:]); err != nil || client.equipment == nil { + t.Fatal("fixture HUD item did not start wear into the protected row", err) } } pending := client.equipment diff --git a/tools/client/test_pending_stale_worn.mjs b/tools/client/test_pending_stale_worn.mjs @@ -0,0 +1,95 @@ +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-worn', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + const server = async () => (await page.request.get(url + '/test-state')).json(); + const armor = [5, 5, 1, 1, 5, 5, 1, 5]; + await page.goto(url); + await game.ready(); + assert.deepEqual(game.local().effectiveArmor, armor); + await game.key('i'); + await page.keyboard.press('Control+1'); + assert((await page.request.post(url + '/test-stale-view')).ok()); + + // Start the axe equip while the native vest still carries stale armor effects. + const carried = game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy); + assert(carried); + const first = game.sequence; + await game.click((carried.bounds[0] + carried.bounds[2]) / 2, (carried.bounds[1] + carried.bounds[3]) / 2); + await game.click(867, 206); + await game.wait('actual axe equip request', () => game.events.some(event => event.sequence > first && + event.direction === 'framesent' && event.opcode === '47537a24')); + evidence.pending = await server(); + assert(evidence.pending.pending); + assert.deepEqual(evidence.pending.armor, [0, 0, 0, 0, 0, 0, 0, 0]); + assert.deepEqual(game.local().effectiveArmor, armor); + await game.wait('native axe animation ends', state => !game.local(state).actions.includes(3) && !game.local(state).actions.includes(6)); + + // Remove the stale worn row using actual Clothes input while server equip is held. + await game.click(953, 53); + const sequence = game.sequence; + await game.click(927, 148, 'right'); + await game.wait('actual stale vest removal request', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '47537a24' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === 102 && Buffer.from(event.hex, 'hex').readUInt32BE(33) === 21)); + evidence.refused = await server(); + assert.deepEqual(evidence.refused, evidence.pending); + await game.save(output + '/requested'); + await game.wait('stale vest and all eight effects removed', state => + !game.local(state).inventory.some(item => item.slot === 21) && game.local(state).effectiveArmor.every(value => value === 0)); + const replies = game.events.filter(event => event.sequence > sequence && event.direction === 'framereceived' && + ['5e477770', '35505644'].includes(event.opcode)).map(event => [event.opcode, + ...Array.from({length: event.opcode === '35505644' ? 9 : 5}, (_, index) => Buffer.from(event.hex, 'hex').readUInt32BE(29 + index * 4))]); + assert.deepEqual(replies, [['5e477770', 146, 102, 21, 0, 0], + ['35505644', 85481, 85481, 1, 1, 7, 102, 21, 0, 0], ['5e477770', 112, 102, 21, 0, 0]]); + await game.save(output + '/corrected'); + assert((await page.request.post(url + '/test-complete')).ok()); + await game.wait('original axe equip completes', state => game.local(state).inventory.some(item => item.id === 1 && item.slot === 6)); + evidence.completed = await server(); + assert.equal(evidence.completed.pending, null); + + // Replay exposes the retained vest's actual carried slot; wear that exact instance. + await page.reload(); + await game.ready(); + if (!game.state.grids.some(grid => grid.cells.some(cell => cell.identity[0] === 104 && cell.identity[1] === 49))) await game.key('i'); + await page.keyboard.press('Control+1'); + await game.click(953, 53); + await game.wait('retained vest carried row available', state => state.grids.some(grid => grid.cells.some(cell => + cell.identity[0] === 104 && cell.identity[1] === 49 && !cell.dummy))); + const vest = game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 104 && cell.identity[1] === 49 && !cell.dummy); + const recovered = game.sequence; + await game.click((vest.bounds[0] + vest.bounds[2]) / 2, (vest.bounds[1] + vest.bounds[3]) / 2, 'right'); + await game.wait('actual recovered vest wear request', () => game.events.some(event => event.sequence > recovered && + event.direction === 'framesent' && event.opcode === '47537a24')); + assert((await page.request.post(url + '/test-complete')).ok()); + await game.wait('retained vest and effects restored exactly once', state => game.local(state).inventory.some(item => item.id === 2 && item.slot === 21) && + JSON.stringify(game.local(state).effectiveArmor) === JSON.stringify(armor)); + evidence.after = await server(); + assert.deepEqual(evidence.after.inventory.Items.map(item => [item.ID, item.Slot, item.Count]), [[1, 6, 1], [2, 21, 1]]); + assert.deepEqual(evidence.after.armor, armor); + assert.deepEqual(game.errors, []); + assert.equal(game.dropped, 0); + await game.save(output + '/retained'); + console.log('PASS: stale worn correction removes all eight effects without changing pending equip or either item'); +} 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(); } +}