aorecomp

Anarchy Online classic in the browser

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


commit 1073efbe4f815105367411936e78507c716cca41
parent 0370ad1516d7220e853f0889d89d2ce31048d4db
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 01:07:25 +0000

Refresh backpack stacks after stale joins

Diffstat:
MTODO.md | 8++++++++
Mdocs/backpacks.md | 30++++++++++++++++++++++++++++++
Mserver/backpacks.go | 13+++++++++++++
Aserver/browser_stale_bag_stack_test.go | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/stale_bag_stack_test.go | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_stale_bag_stack.mjs | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 345 insertions(+), 0 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -4041,6 +4041,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 backpack stack joins. A controlled earlier merge leaves + a ghost and stale counts in the native bag; joins against the missing target + or consumed source received no reply. Source cancellation followed by current + contents now restores the open grid without writes or false join success. + Both short WASM checks verify a same-window retry, page replay and fifteen + retained charges; handler and cold database checks preserve exact identities + and session/equipment guards. The broader disappearance audit remains open. + See [stale backpack joins](docs/backpacks.md#stale-stack-joins). - [x] [P0] Restore ordinary stacks after stale joins. A missing target hides the still-owned source; an already-consumed source leaves the kept count stale. Controlled missed-refresh checkpoints reproduce both real requests without diff --git a/docs/backpacks.md b/docs/backpacks.md @@ -171,6 +171,36 @@ for the weapon, bag and contained item through page and cold recovery. Its controlled delayed completion is not earned progression. Captures are retained in `local/pending-backpack/`; the broader equipment audit remains open. +## Stale stack joins + +A backpack can still display an earlier stack after a committed merge consumes +that instance. Native action53 identifies both sides with page107 and packed +session-handle/slot positions. A join against the empty target, or from the +consumed source, previously received no response and retained the old grid and +counts. This differs from the hidden ordinary-inventory source: the bag's +icons remained usable and its cursor was empty. + +When exactly one side is missing, the handler requires the other to be an owned +stack in the same open, carried bag. Both slots must be 0..20. It sends +CharacterAction146 for the original packed source, followed by the authoritative +InventoryUpdate. A contents replay alone did not update the native grid after +the pending join. Cancellation plus replay removes the ghost and restores the +current counts without a successful action53 acknowledgement or database write. +Unknown handles, foreign pages, different bags, invalid slots and absent owned +stacks remain ignored; the existing pending-equipment guard remains in force. +This is verified refusal behavior using the original client protocol, rather +than evidence of the historical server's choice of reply packets. + +`TestStaleBackpackStackJoinRefreshesWithoutWrites` covers both directions, +repeated requests, ownership/session guards, zero writes, unchanged handles and +pending equipment, exact physical instances and cold loading. +`TestBrowserStaleBackpackStackJoin` uses controlled missed-refresh checkpoints, +not earned progression. Three QL2 laboratories initially hold 3/5/7 charges; +the checkpoint retains 8/7, both native refusal cases refresh that view, and a +same-window retry retains the fifteen-charge survivor. Page replay and a cold +database read preserve the bag and final instance. Captures are retained in +`local/stale-bag-stack/`; the broader disappearance audit remains open. + ## Stack join during pending equipment A controlled native check holds server completion after the local equipment diff --git a/server/backpacks.go b/server/backpacks.go @@ -379,6 +379,19 @@ func (server *server) handleBackpackAction_locked(client *worldClient, body []by } items := player.inventory.Containers[handle.id] index := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == position&65535 }) + if action == 53 && binary.BigEndian.Uint32(body[28:32]) == 107 { + // A missed merge refresh can leave either side in the open bag's old view. + otherPosition := binary.BigEndian.Uint32(body[32:36]) + if position&65535 < 21 && otherPosition&65535 < 21 && otherPosition>>16 == position>>16 { + other := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == otherPosition&65535 }) + if index < 0 && other >= 0 && items[other].isStackable() || other < 0 && index >= 0 && items[index].isStackable() { + if err := client.send(characterActionPacket(client.id, [5]uint32{146, 107, otherPosition})); err != nil { + return err + } + return server.syncStackPage_locked(client, 107, handle.id) + } + } + } if index < 0 { if action == 52 { return server.syncStackPage_locked(client, 107, handle.id) diff --git a/server/browser_stale_bag_stack_test.go b/server/browser_stale_bag_stack_test.go @@ -0,0 +1,95 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "maps" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserStaleBackpackStackJoin(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for stale backpack stack joins") + } + for _, missing := range []string{"target", "source"} { + t.Run(missing, func(t *testing.T) { + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/stale-bag-stack", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("stale-bag-stack"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 4, Items: []ownedItem{ + {ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}}, + Containers: map[uint32][]ownedItem{1: { + {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 0, Count: 3}, + {ID: 3, Type: 51005, Template: 25812, Quality: 2, Slot: 1, Count: 5}, + {ID: 4, Type: 51005, Template: 25812, Quality: 2, Slot: 2, Count: 7}}}} + 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) + }) + // Controlled checkpoint: an earlier merge committed without a native refresh. + 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.Containers = maps.Clone(inventory.Containers) + inventory.Containers[1] = slices.Clone(inventory.Containers[1][1:]) + inventory.Containers[1][0].Count = 8 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Error(err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + gesture := map[string]uint32{"removed": 2, "kept": 0} + if missing == "source" { + gesture = map[string]uint32{"removed": 0, "kept": 1} + } + json.NewEncoder(w).Encode(gesture) + }) + 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_bag_stack.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: 3, Type: 51005, Template: 25812, Quality: 2, Slot: 1, Count: 15}} + if !slices.Equal(player.inventory.Containers[1], expected) || !slices.Equal(cold.characters[1].inventory.Containers[1], expected) || + len(cold.characters[1].inventory.Items) != 1 || cold.characters[1].inventory.Items[0] != inventory.Items[0] || + world.nextItem != 4 || cold.nextItem != 4 { + t.Fatal("stale backpack join changed ownership, quantity or allocation") + } + }) + } +} diff --git a/server/stale_bag_stack_test.go b/server/stale_bag_stack_test.go @@ -0,0 +1,98 @@ +package main + +import ( + "bytes" + "encoding/binary" + "reflect" + "slices" + "testing" +) + +func TestStaleBackpackStackJoinRefreshesWithoutWrites(t *testing.T) { + for _, scenario := range []string{"missing target", "consumed source", "both missing", "foreign page", "other handle", "target outside bag", "source outside bag", "closed bag", "unowned bag", "individual survivor", "pending equipment"} { + t.Run(scenario, func(t *testing.T) { + world, output := newBackpackWorld(t) + player, client := world.characters[1], world.clients[1] + inventory := player.inventory + inventory.LastID = 6 + inventory.Items = slices.Clone(inventory.Items[2:]) + inventory.Containers = map[uint32][]ownedItem{3: { + {ID: 1, Type: 51005, Template: 25812, Quality: 2, Slot: 0, Count: 3}, + {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 1, Count: 5}, + {ID: 6, Type: 51005, Template: 25812, Quality: 2, Slot: 2, Count: 7}}} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 1)[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, characterActionPacket(1, [5]uint32{53, 107, 65537, 107, 65536})[20:]); err != nil { + t.Fatal(err) + } + request := characterActionPacket(1, [5]uint32{53, 107, 65536, 107, 65538})[20:] + switch scenario { + case "consumed source", "individual survivor": + request = characterActionPacket(1, [5]uint32{53, 107, 65537, 107, 65536})[20:] + if scenario == "individual survivor" { + player.inventory.Containers[3][0] = ownedItem{ID: 2, Type: 51018, Template: 209283, Quality: 1, Slot: 1, Count: 1} + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + } + case "both missing": + binary.BigEndian.PutUint32(request[32:36], 65539) + case "foreign page": + binary.BigEndian.PutUint32(request[28:32], 105) + case "other handle": + binary.BigEndian.PutUint32(request[32:36], 131074) + case "target outside bag": + binary.BigEndian.PutUint32(request[24:28], 65557) + case "source outside bag": + request = characterActionPacket(1, [5]uint32{53, 107, 65537, 107, 65557})[20:] + case "closed bag": + client.backpacks[1] = backpackHandle{3, false} + case "unowned bag": + client.backpacks[1] = backpackHandle{99, true} + case "pending equipment": + client.equipment = &equipmentMove{itemID: 5} + } + handle, pending := client.backpacks[1], 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, request); err != nil { + t.Fatal(err) + } + } + after, err := readTestItemStore(world) + cold := newTestInventoryServer(t) + + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || + !reflect.DeepEqual(player.inventory.Containers, cold.characters[1].inventory.Containers) || + world.nextItem != 6 || cold.nextItem != 6 || client.backpacks[1] != handle || client.equipment != pending { + t.Fatal("stale backpack join changed storage, allocation, handle or pending equipment", err) + } + if scenario != "missing target" && scenario != "consumed source" { + if len(output.packets) != 0 { + t.Fatal("invalid or unavailable stale join created correction traffic") + } + return + } + cancel := targetPacket(characterActionPacket(1, [5]uint32{146, 107, binary.BigEndian.Uint32(request[32:36])})) + refresh := targetPacket(backpackInventoryPacket(1, 3, 1, player.inventory.Containers[3])) + if !reflect.DeepEqual(output.packets, [][]byte{cancel, refresh, cancel, refresh}) { + t.Fatal("stale join omitted ordered cancellation and contents or falsely acknowledged success") + } + if !slices.Equal(player.inventory.Containers[3], []ownedItem{ + {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 1, Count: 8}, + {ID: 6, Type: 51005, Template: 25812, Quality: 2, Slot: 2, Count: 7}}) { + t.Fatal("refusal changed surviving identities or fifteen charges") + } + }) + } +} diff --git a/tools/client/test_stale_bag_stack.mjs b/tools/client/test_stale_bag_stack.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: 'stale-bag-stack', 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] === 107 && cell.identity[1] === (65536 | slot) && !cell.dummy); + const click = async slot => { + const source = cell(slot); + assert(source, `backpack slot ${slot} must be usable`); + await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2); + }; + const open = async () => { + await game.key('i'); + await game.wait('owned backpack visible', state => state.grids.flatMap(grid => grid.cells).some(cell => + cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy)); + const bag = game.state.grids.flatMap(grid => grid.cells).find(cell => cell.identity[0] === 104 && cell.identity[1] === 48); + await game.click((bag.bounds[0] + bag.bounds[2]) / 2, (bag.bounds[1] + bag.bounds[3]) / 2, 'right'); + await game.wait('backpack contents open', () => cell(1)); + }; + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + await open(); + assert(cell(0) && cell(2)); + evidence.initial = await server(); + const checkpoint = await page.request.post(url + '/test-stale-view'); + assert(checkpoint.ok()); + evidence.gesture = await checkpoint.json(); + evidence.stale = await server(); + await game.save(output + '/stale'); + + // Real input joins against a missed-refresh view of a committed merge. + const start = game.sequence; + await click(evidence.gesture.removed); + await click(evidence.gesture.kept); + await game.wait('actual stale backpack join', () => game.events.some(event => event.sequence > start && + event.direction === 'framesent' && event.opcode === '5e477770' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === 53)); + await game.save(output + '/requested'); + await game.wait('backpack authoritative contents restored', () => !cell(0) && cell(1) && cell(2) && + game.state.dragged[0] === 0 && game.events.some(event => event.sequence > start && + event.direction === 'framereceived' && event.opcode === '4e536976')); + const cancel = game.events.find(event => event.sequence > start && event.direction === 'framereceived' && + event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 146); + const refresh = game.events.find(event => event.sequence > start && event.direction === 'framereceived' && + event.opcode === '4e536976'); + assert(cancel && cancel.sequence < refresh.sequence); + const packet = Buffer.from(refresh.hex, 'hex'); + assert.deepEqual([0, 1].map(index => Array.from({length: 8}, (_, field) => packet.readUInt32BE(33 + index * 32 + field * 4))), [ + [1, 0x30008, 51005, 3, 25812, 25811, 2, 0], [2, 0x30007, 51005, 4, 25812, 25811, 2, 0]]); + evidence.refused = await server(); + assert.deepEqual(evidence.refused, evidence.stale); + await game.save(output + '/refused'); + + // A valid retry must use the refreshed sources in the same open window. + const retry = game.sequence; + await click(2); + await click(1); + await game.wait('valid backpack join acknowledged', () => !cell(2) && cell(1) && game.events.some(event => + event.sequence > retry && event.direction === 'framereceived' && event.opcode === '5e477770' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === 53)); + evidence.joined = await server(); + assert.deepEqual(evidence.joined.Containers[1].map(item => [item.ID, item.Slot, item.Quality, item.Count]), [[3, 1, 2, 15]]); + const acknowledgements = game.events.filter(event => event.sequence > start && event.direction === 'framereceived' && + event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 53); + assert.equal(acknowledgements.length, 1); + await game.save(output + '/joined'); + + await page.reload(); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + await open(); + assert(!cell(0) && !cell(2)); + evidence.replayed = await server(); + assert.deepEqual(evidence.replayed, evidence.joined); + assert.deepEqual(game.errors, []); + console.log('PASS: stale backpack join refresh, same-window retry and page recovery preserve fifteen charges'); +} 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(); } +}