aorecomp

Anarchy Online classic in the browser

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


commit 8c5379c9a1829a0ad7095602f0671403a609d796
parent 7986a18e2d57f51dd502363df138aba88c8ded85
Author: anon <anon@example.com>
Date:   Thu,  5 Nov 2026 00:39:24 +0000

Restore individual items after stale ordinary split requests

Diffstat:
MTODO.md | 11+++++++++++
Mdocs/inventory-stacks.md | 32+++++++++++++++++++++++++++++---
Aserver/browser_replaced_stack_split_test.go | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/inventory.go | 8++++++++
Aserver/replaced_stack_split_test.go | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/stacks.go | 30+++++++++++++++++++++---------
Atools/client/test_replaced_stack_split.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 334 insertions(+), 12 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -4556,6 +4556,17 @@ and server restarts. Turn every reproduced bug into a focused regression test. checks pass 44 roots/124 results, focused race checks pass 5/19, and ten native traces are clean. See [session and destination refusals](docs/backpacks.md#session-and-destination-policy-refusals) and `local/backpack-refusals/verification-summary.json`. +- [x] [P0] Correct an ordinary split after its old stack source is replaced by an + individual item. Reproduction: retain the native laboratory row after a + controlled bank exchange puts a loaded pistol in that slot, then Ctrl-click; + the nonstackable-source no-op leaves the old source and a phantom charge row. + Correction now rebuilds that source and the stack rows with normal item + delivery, retaining exact identity/QL/endpoints/ammunition without storage + writes or allocation. Weapon, filled-bag and ordinary-template cases cover both + boundaries, repeats and a separate pending equip/deadline. Short native Use + equips the corrected pistol before reconnect; page/cold ownership retains it + and the banked three-charge laboratory. The broader item-loss audit stays open. + See [replaced ordinary sources](docs/inventory-stacks.md#replaced-ordinary-sources). - [x] [P0] Correct an ordinary stale split whose retained count equals the actual source count. Reproduction: the native laboratory still shows three charges after controlled earlier consumption leaves one; real Ctrl-click requests diff --git a/docs/inventory-stacks.md b/docs/inventory-stacks.md @@ -135,6 +135,30 @@ controlled setup, not earned progression or a claim about period timing. Baseline/native captures and an independent trace audit are retained under `local/depleted-stack-split/`. +### Replaced ordinary sources + +If a nonstackable item replaces a stale ordinary stack source, silently refusing +its native split leaves the old row and an unowned clone. Preserving every +individual-item slot during stack correction cannot repair that replaced row. +An ordinary split now detects this case before pending-equipment refusal and +rebuilds the affected source along with supported stacks. Unrelated individual +items and equipment remain intact. Native weapon/container delivery retires only +the affected live identity before recreating its correct subclass; known open +backpack handles close before that container is recreated. First-free delivery +and logical-slot restoration use the same correction path. + +`TestReplacedStackSplitCorrectsWithoutWriting` covers loaded weapons, filled +backpacks and ordinary nonstackable items at slots 64/93, repeated requests and +a separate admitted equip. Ownership, quantities, loaded rounds, allocation and +the pending move/deadline remain unchanged, with no checkpoint writes. +`TestBrowserReplacedStackSplit` reproduces the original stale laboratory/phantom +after a controlled bank exchange. Real Ctrl-click restores pistol ID2, QL2, +endpoints 123742/123743 and three loaded rounds. Same-page native Use equips it; +page replay and a separate database load retain it and laboratory ID1's three +banked charges. The admitted equipment deadline is advanced explicitly, keeping +this a short transfer/correction check rather than earned-progression evidence. +Captures and the independent trace audit are in `local/replaced-stack-split/`. + ### Reviewed family anchors Same-QL stacks identified by opposite endpoints of one reviewed family now join @@ -171,12 +195,14 @@ remove a provisional clone safely. That behavior is supported by `ev_331fd15acd45f210966ad41148a5960706f3a66f90d7daa3d710e0e9e5d29ba1`. The server instead rebuilds only the supported ordinary stacks: -1. Preserve all occupied individual-item slots and all equipment. +1. Preserve occupied individual-item slots except a replaced split source, and + preserve all equipment. 2. Delete the other ordinary slots using native action 112, removing any provisional supported-stack clones. Neither supported template has deletion event functions. -3. Add each authoritative stack in slot order using AddTemplate `0x052e2f0c`, - body `{low, high, QL, count}`. It chooses the first free ordinary slot. +3. Deliver authoritative stacks and any replaced source in slot order. Stacks + use AddTemplate `0x052e2f0c`, body `{low, high, QL, count}`; individual sources + use normal item delivery. Both choose the first free ordinary slot. 4. Move it to its saved slot with the existing own-player ContainerAddItem response when needed. diff --git a/server/browser_replaced_stack_split_test.go b/server/browser_replaced_stack_split_test.go @@ -0,0 +1,96 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserReplacedStackSplit(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for a replaced ordinary split source") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/replaced-stack-split", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.stats = testCharacterStats() + player.stats.Abilities = characterAbilitiesStats{80, 80, 80, 80, 80, 80} + player.stats.Ranged.Pistol = 100 + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("replaced-stack-split"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 2, + Items: []ownedItem{{ID: 1, Type: 51005, Template: 25812, Quality: 2, Slot: 64, Count: 3}}, + Bank: []ownedItem{{ID: 2, Type: 51018, Template: 123742, Quality: 2, Slot: 0, Count: 1, Ammo: 3}}} + 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() + pending := world.clients[1].equipment != nil + json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "pending": pending}) + }) + // Isolate an earlier committed transfer while the original source remains native. + mux.HandleFunc("POST /test-replace-source", 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, inventory.Bank = slices.Clone(inventory.Bank), slices.Clone(inventory.Items) + inventory.Items[0].Slot, inventory.Bank[0].Slot = 64, 0 + 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_replaced_stack_split.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 := playerInventory{LastID: 2, + Items: []ownedItem{{ID: 2, Type: 51018, Template: 123742, Quality: 2, Slot: 6, Count: 1, Ammo: 3}}, + Bank: []ownedItem{{ID: 1, Type: 51005, Template: 25812, Quality: 2, Slot: 0, Count: 3}}} + for _, current := range []*character{player, cold.characters[1]} { + if !slices.Equal(current.inventory.Items, expected.Items) || !slices.Equal(current.inventory.Bank, expected.Bank) || + current.inventory.LastID != 2 || current.inventory.Credits != 0 { + t.Fatal("replaced split changed exact ownership, charges or loaded rounds", current.inventory) + } + } + if world.nextItem != 2 || cold.nextItem != 2 { + t.Fatal("replaced source correction allocated an item") + } +} diff --git a/server/inventory.go b/server/inventory.go @@ -242,6 +242,14 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { return err } } + if key == 0x5e477770 && binary.BigEndian.Uint32(body[16:20]) == 52 && binary.BigEndian.Uint32(body[20:24]) == 104 { + source := binary.BigEndian.Uint32(body[24:28]) + index := slices.IndexFunc(character.inventory.Items, func(item ownedItem) bool { return item.Slot == source }) + if source >= 64 && source < 94 && index >= 0 && !character.inventory.Items[index].isStackable() { + // A stale template split can name a slot now occupied by an individual item. + return server.syncStackSource_locked(client, source) + } + } if key == 0x3a243f41 { // Ground storage is unsupported; restore only a validated owned source. page, slot := binary.BigEndian.Uint32(body[16:20]), binary.BigEndian.Uint32(body[20:24]) diff --git a/server/replaced_stack_split_test.go b/server/replaced_stack_split_test.go @@ -0,0 +1,98 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "reflect" + "slices" + "testing" +) + +func TestReplacedStackSplitCorrectsWithoutWriting(t *testing.T) { + for _, replacement := range []ownedItem{ + {ID: 2, Type: 51018, Template: 123742, Quality: 2, Count: 1, Ammo: 3}, + {ID: 2, Type: 51017, Template: 99228, Quality: 1, Count: 1}, + {ID: 2, Type: 51005, Template: 42640, Quality: 1, Count: 1}, + } { + for _, slot := range []uint32{64, 93} { + for _, pending := range []bool{false, true} { + t.Run(fmt.Sprintf("%d/slot%d/pending%v", replacement.Template, slot, pending), func(t *testing.T) { + world, output := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + replacement.Slot = slot + inventory := playerInventory{LastID: 6, Items: []ownedItem{ + {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 65, Count: 1}, replacement, + {ID: 3, Type: 51005, Template: 25812, Quality: 2, Slot: 66, Count: 3}, + {ID: 4, Type: 51005, Template: 42640, Quality: 1, Slot: 67, Count: 1}}, + Bank: []ownedItem{{ID: 5, Type: 51005, Template: 25812, Quality: 2, Slot: 0, Count: 3}}} + if replacement.isPortableContainer() { + inventory.Containers = map[uint32][]ownedItem{2: {{ID: 6, Type: 51005, Template: 21609, Quality: 1, Slot: 0, Count: 100}}} + } + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if replacement.isPortableContainer() { + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, slot, 1)[20:]); err != nil { + t.Fatal(err) + } + } + if pending { + if err := world.handleInventory(client, inventoryMovePacket(1, 65, 6)[20:]); err != nil || client.equipment == nil { + t.Fatal("fixture did not admit the separate axe move", err) + } + } + var move *equipmentMove + if client.equipment != nil { + copy := *client.equipment + move = &copy + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + auditCheckpointWrites(t, world) + + for range 2 { + output.packets = nil + if err := world.handleInventory(client, stackActionPacket(1, 52, slot, 1)[20:]); err != nil { + t.Fatal(err) + } + + var cleared []uint32 + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 112 { + cleared = append(cleared, binary.BigEndian.Uint32(packet[37:41])+16) + if binary.BigEndian.Uint32(packet[37:41])+16 == 65 || binary.BigEndian.Uint32(packet[37:41])+16 == 67 { + t.Fatal("correction deleted an unrelated individual source") + } + } + } + if len(cleared) != 28 || !slices.Contains(cleared, slot) || + !slices.ContainsFunc(output.packets, func(packet []byte) bool { + return bytes.Equal(packet, targetPacket(inventoryAdditionPacket(player, replacement))) + }) || + !reflect.DeepEqual(client.equipment, move) { + t.Fatal("correction omitted the replacement or changed the pending move/deadline") + } + if replacement.isPortableContainer() && client.backpacks[1] != (backpackHandle{2, false}) { + t.Fatal("replacement container retained its invalidated native window") + } + for _, value := range output.packets { + if bytes.Equal(value, targetPacket(n3Packet(0x36510078, 51018, 1, nil))) { + t.Fatal("correction retired the unrelated axe") + } + } + } + after, err := readTestItemStore(world) + cold := newTestInventoryServer(t) + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || + !reflect.DeepEqual(player.inventory, inventory) || !reflect.DeepEqual(cold.characters[1].inventory, inventory) || + world.nextItem != 6 || cold.nextItem != 6 { + t.Fatal("replacement correction changed ownership, charges, ammunition or allocation", err) + } + }) + } + } + } +} diff --git a/server/stacks.go b/server/stacks.go @@ -142,12 +142,16 @@ func (server *server) syncStackPage_locked(client *worldClient, page, bag uint32 } func (server *server) syncStacks_locked(client *worldClient) error { + return server.syncStackSource_locked(client, 0) +} + +func (server *server) syncStackSource_locked(client *worldClient, source uint32) error { // Preserve live individual items and equipped modifiers while rebuilding - // supported stacks and removing any optimistic split clones. + // supported stacks and a replaced source, removing optimistic split clones. player := server.characters[client.id] var occupied [30]bool for _, item := range player.inventory.Items { - if item.Slot >= 64 && !item.isStackable() { + if item.Slot >= 64 && !item.isStackable() && item.Slot != source { occupied[item.Slot-64] = true } } @@ -164,19 +168,27 @@ func (server *server) syncStacks_locked(client *worldClient) error { } } - // AddTemplate chooses first-free; move each restored stack to its saved slot. + // Item delivery chooses first-free; move each restored item to its saved slot. items := slices.Clone(player.inventory.Items) slices.SortFunc(items, func(first, second ownedItem) int { return int(first.Slot) - int(second.Slot) }) for _, item := range items { - if !item.isStackable() { + if item.Slot < 64 || !item.isStackable() && item.Slot != source { continue } - var body []byte - low, high := item.templateIDs() - for _, value := range []uint32{low, high, item.Quality, uint32(item.Count)} { - body = binary.BigEndian.AppendUint32(body, value) + if item.Slot == source && (item.Type == 51018 || item.isPortableContainer()) { + for index, handle := range client.backpacks { + if handle.id == item.ID && handle.open { + client.backpacks[index] = backpackHandle{item.ID, false} + if err := client.send(backpackClosePacket(client.id, item.ID)); err != nil { + return err + } + } + } + if err := client.send(n3Packet(0x36510078, item.Type, item.ID, nil)); err != nil { + return err + } } - if err := client.send(n3Packet(0x052e2f0c, 50000, client.id, body)); err != nil { + if err := client.send(inventoryAdditionPacket(player, item)); err != nil { return err } slot := uint32(64) diff --git a/tools/client/test_replaced_stack_split.mjs b/tools/client/test_replaced_stack_split.mjs @@ -0,0 +1,71 @@ +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: 'replaced-stack-split', 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(); + await game.key('KeyI'); + evidence.initial = await server(); + assert((await page.request.post(url + '/test-replace-source')).ok()); + evidence.replaced = await server(); + assert.equal(evidence.replaced.inventory.Items[0].ID, 2); + const sequence = game.sequence; + await page.keyboard.down('Control'); + try { await game.click(681, 45); } finally { await page.keyboard.up('Control'); } + await game.wait('actual stale-source split request', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 52)); + evidence.requested = await server(); + await game.save(output + '/requested'); + await game.wait('only the authoritative replacement remains carried', snapshot => game.local(snapshot).inventory.length === 1 && + game.local(snapshot).inventory.some(item => item.id === 2 && item.type === 51018 && item.slot === 48 && item.count === 1)); + assert.deepEqual(await server(), evidence.replaced); + if (game.state.dragged[0] !== 0) { + await game.click(735, 45); + await game.wait('replacement can be placed normally', snapshot => snapshot.dragged[0] === 0); + } + await game.wait('replacement icon is usable', snapshot => snapshot.grids.some(grid => grid.cells.some(cell => + cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy))); + assert.deepEqual(game.local().inventory[0].templates, [123742, 123743]); + await game.save(output + '/corrected'); + + // Use the corrected gun before reconnecting, then complete its admitted delay. + const source = game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy); + await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2, 'right'); + await game.waitFor('same replacement admitted for wear', async () => (await server()).pending); + assert((await page.request.post(url + '/test-complete')).ok()); + await game.wait('same gun equipped without reload', snapshot => game.local(snapshot).inventory.some(item => + item.id === 2 && item.slot === 6) && game.local(snapshot).weapons.some(weapon => weapon.slot === 6 && weapon.loadedAmmo === 3)); + evidence.worn = await server(); + assert.equal(evidence.worn.inventory.Items[0].Ammo, 3); + assert.deepEqual(evidence.worn.inventory.Bank, evidence.replaced.inventory.Bank); + await game.save(output + '/worn'); + await page.reload(); + await game.ready(); + await game.wait('loaded rounds replay', snapshot => game.local(snapshot).weapons.some(weapon => weapon.slot === 6 && weapon.loadedAmmo === 3)); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.quality, item.count]), [[2, 6, 2, 1]]); + assert.deepEqual(game.local().inventory[0].templates, [123742, 123743]); + assert.deepEqual(await server(), evidence.worn); + assert.deepEqual(game.errors, []); + console.log('PASS: stale nonstackable-source split removes phantom charges, restores the loaded replacement and permits same-page wear with page/cold ownership'); +} 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(); } +}