aorecomp

Anarchy Online classic in the browser

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


commit 35e5477ed3a60d9ad462d4c6ae2b8d165ec30078
parent cd3e21da4bb8ff36025771966a0a06aa9d47d3be
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 22:27:01 +0000

Close stale backpack split windows after source transfers

Diffstat:
MTODO.md | 8++++++++
Mdocs/backpacks.md | 23++++++++++++++++++-----
Mserver/backpacks.go | 4+---
Aserver/browser_moved_closed_backpack_split_test.go | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/closed_backpack_split_test.go | 14+++++++++++---
Atools/client/test_moved_closed_backpack_split.mjs | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 216 insertions(+), 11 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -4565,6 +4565,14 @@ and server restarts. Turn every reproduced bug into a focused regression test. recovery of all three charges. Boundary/guard cases, related Go tests, race and vet pass. The broader disappearance audit stays open; see [closed-session splits](docs/backpacks.md#optimistic-splits-after-session-closure). +- [x] [P0] Close stale split windows after an earlier transfer removes their source. + A real native split still produces an extra row after the stack moves to + another owned bag and its old server session closes. Removing the current-row + requirement now permits closure by known owned bag and in-range slot. A short + WASM check verifies empty source reopening, normal withdrawal from the actual + destination and exact page/cold retention of all three charges without new + allocation. Ownership/bounds/deadline, race and vet checks pass; see + [closed-session splits](docs/backpacks.md#optimistic-splits-after-session-closure). - [x] [P0] Correct a late bank withdrawal after its session becomes unavailable during pending equipment. Public-handler cases reproduce no reply after closure or moving beyond the bank anchor. Check explicit native source diff --git a/docs/backpacks.md b/docs/backpacks.md @@ -310,10 +310,11 @@ instances. This is fixture evidence, not earned progression; see A cached native window can also send a Ctrl-split after its server handle closes. The original handler silently left an unowned child row and its selected source, while storage still held the original three-charge stack. The server now closes -that window only for a known carried bag, an in-range packed slot and an actual -owned stack. It leaves the handle closed and performs no ownership transaction -or allocation. Invalid/unowned sources and other closed-session actions retain -their existing handling. +that window for a known owned bag and an in-range packed slot. The old row can +be missing or contain a different item after an earlier transfer; that must not +suppress closure of the unavailable window. The handle stays closed, with no +ownership transaction or allocation. Unknown handles, unowned bags, out-of-range +slots and other closed-session actions retain their existing handling. The native client keeps a split source selected after closing its window. Ordinary placement uses the existing closed-source refusal; then real Use @@ -326,13 +327,25 @@ Public-handler checks cover both child-slot boundaries, repeated refusal, unchanged pending equipment/deadlines, zero writes/allocation, invalid sources and normal reopening/split retry. These are controlled session/item fixtures, not earned progression or recovered original-server rejection policy. Evidence -is retained under `local/closed-backpack-split/`. The final native check passes +is retained under `local/closed-backpack-split/`. The initial native check passes in 20.25 seconds with four clean stage traces. Related server coverage passes 111 roots / 976 results; focused race coverage passes three roots / 14 results. The 21 opt-in browser checks skipped in the related run are separate from the explicitly executed native case. Maintained-package vet and an independent packet/ownership audit pass. +An additional controlled missed-refresh check moves that same stack into a +second owned bag before closing the source session. The earlier row lookup +reproduces a silent real Ctrl-split with another unowned native row. Closure now +allows ordinary reopening of the empty source bag and normal withdrawal of the +exact retained stack from its actual bag. Both bags and all three laboratory +charges survive page/cold recovery without allocating an item. The moved-source +native check takes 19.45 seconds; the original closed-stack check also passes +in 20.20 seconds. Evidence is under `local/moved-closed-backpack-split/`. +Ten related roots / 40 results and two focused race roots / 13 results pass, +along with maintained-package vet. An independent packet/ownership audit checks +both native recoveries and all eight error/drop-free stage traces. + ## Stale withdrawal sources A known carried bag can have an empty slot behind a stale native window. The diff --git a/server/backpacks.go b/server/backpacks.go @@ -443,9 +443,7 @@ func (server *server) handleBackpackAction_locked(client *worldClient, body []by action := binary.BigEndian.Uint32(body[16:20]) if !handle.open { // An optimistic split needs its unavailable native window closed. - if action == 52 && position&65535 < 21 && slices.ContainsFunc(player.inventory.Containers[handle.id], func(item ownedItem) bool { - return item.Slot == position&65535 && item.isStackable() - }) { + if action == 52 && position&65535 < 21 { return client.send(backpackClosePacket(client.id, handle.id)) } return nil diff --git a/server/browser_moved_closed_backpack_split_test.go b/server/browser_moved_closed_backpack_split_test.go @@ -0,0 +1,94 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserMovedClosedBackpackSplit(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for closed backpack split") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/moved-closed-backpack-split", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("moved-closed-backpack-split"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 3, Items: []ownedItem{ + {ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}, + {ID: 3, Type: 51017, Template: 99228, Quality: 1, Slot: 65, Count: 1}}, + Containers: map[uint32][]ownedItem{1: { + {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 0, Count: 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() + json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "open": world.clients[1].backpacks[1].open}) + }) + // Commit an earlier transfer while retaining the old native source view. + mux.HandleFunc("POST /test-move-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.Containers = map[uint32][]ownedItem{3: slices.Clone(inventory.Containers[1])} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Error(err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + world.clients[1].backpacks[1] = backpackHandle{1, false} + }) + 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_moved_closed_backpack_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 := []ownedItem{{ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}, + {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 66, Count: 3}, + {ID: 3, Type: 51017, Template: 99228, Quality: 1, Slot: 65, Count: 1}} + for _, current := range []*character{player, cold.characters[1]} { + if len(current.inventory.Items) != 3 || len(current.inventory.Containers) != 0 || + current.inventory.Credits != 0 || current.inventory.LastID != 3 { + t.Fatal("stale split changed quantities, cash or allocation", current.inventory) + } + for _, item := range expected { + if !slices.Contains(current.inventory.Items, item) { + t.Fatal("stale split recovery lost an exact instance", current.inventory) + } + } + } + if world.nextItem != 3 || cold.nextItem != 3 { + t.Fatal("refused split allocated an identity or retry repeated allocation") + } +} diff --git a/server/closed_backpack_split_test.go b/server/closed_backpack_split_test.go @@ -85,7 +85,7 @@ func TestClosedBackpackSplitClosesWithoutWriting(t *testing.T) { } } -func TestClosedBackpackSplitIgnoresUnownedOrInvalidSources(t *testing.T) { +func TestClosedBackpackSplitValidatesSourceContainer(t *testing.T) { for _, scenario := range []string{"unknown handle", "unowned bag", "missing child", "outside bag", "individual source", "other action", "foreign actor"} { t.Run(scenario, func(t *testing.T) { world, output := newBackpackWorld(t) @@ -117,14 +117,22 @@ func TestClosedBackpackSplitIgnoresUnownedOrInvalidSources(t *testing.T) { if err != nil { t.Fatal(err) } + auditCheckpointWrites(t, world) output.packets = nil err = world.handleInventory(client, request) after, readErr := readTestItemStore(world) - if err != nil || readErr != nil || !bytes.Equal(before, after) || len(output.packets) != 0 || world.nextItem != 5 || + if err != nil || readErr != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || world.nextItem != 5 || client.backpacks[1].open || player.inventory.LastID != 5 { - t.Fatal("invalid closed split created correction traffic, ownership writes or allocation", err, readErr) + t.Fatal("closed split changed ownership, session or allocation", err, readErr) + } + if scenario == "missing child" || scenario == "individual source" { + if len(output.packets) != 1 || !bytes.Equal(output.packets[0], targetPacket(backpackClosePacket(1, 3))) { + t.Fatal("changed native source left its unavailable bag window open") + } + } else if len(output.packets) != 0 { + t.Fatal("unknown, unowned or out-of-range source created correction traffic") } }) } diff --git a/tools/client/test_moved_closed_backpack_split.mjs b/tools/client/test_moved_closed_backpack_split.mjs @@ -0,0 +1,84 @@ +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: 'moved-closed-backpack-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(); + const cell = position => game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 107 && cell.identity[1] === position && !cell.dummy); + const click = async source => { + assert(source, 'the exact native source must be usable'); + await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2); + }; + await game.key('KeyI'); + await game.click(681, 45, 'right'); + await game.wait('source bag opens', () => cell(65536)); + evidence.initial = await server(); + assert((await page.request.post(url + '/test-move-source')).ok()); + evidence.moved = await server(); + assert.equal(evidence.moved.open, false); + assert.equal(evidence.moved.inventory.Containers[1], undefined); + assert.equal(evidence.moved.inventory.Containers[3][0].ID, 2); + const sequence = game.sequence; + await page.keyboard.down('Control'); + try { await click(cell(65536)); } finally { await page.keyboard.up('Control'); } + await game.wait('real split from the stale source', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 52)); + await game.save(output + '/requested'); + await game.wait('closed empty source window retires', state => + !state.grids.some(grid => grid.cells.some(cell => cell.identity[0] === 107))); + assert(game.events.some(event => event.sequence > sequence && event.direction === 'framereceived' && event.opcode === '2049527c')); + if (game.state.dragged[0] !== 0) { + await game.click(789, 45); + await game.wait('stale selected source placement refuses', state => state.dragged[0] === 0); + } + evidence.refused = await server(); + assert.deepEqual(evidence.refused, evidence.moved); + await game.save(output + '/refused'); + + // Reopen the empty bag, then recover the exact retained stack from its real bag. + const reopen = game.sequence; + await game.click(681, 45, 'right'); + await game.wait('empty source bag reopens', () => game.events.some(event => event.sequence > reopen && + event.direction === 'framereceived' && event.opcode === '4e536976' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 1009)); + assert(!cell(65536) && !cell(65537)); + assert.equal((await server()).open, true); + await game.click(735, 45, 'right'); + await game.wait('actual retained stack opens in the other bag', () => cell(131072)); + await click(cell(131072)); + await game.wait('retained stack picked', state => state.dragged[0] === 107 && state.dragged[1] === 131072); + await game.click(789, 45); + await game.wait('retained three-charge stack withdrawn', state => game.local(state).inventory.some(item => + item.id === 2 && item.slot === 50 && item.count === 3)); + evidence.recovered = await server(); + assert.equal(evidence.recovered.inventory.Containers, null); + assert.equal(evidence.recovered.inventory.LastID, 3); + await game.save(output + '/recovered'); + await page.reload(); + await game.ready(); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.quality, item.count]).sort((a, b) => a[0] - b[0]), + [[1, 48, 1, 1], [2, 50, 2, 3], [3, 49, 1, 1]]); + assert.deepEqual((await server()).inventory, evidence.recovered.inventory); + assert.deepEqual(game.errors, []); + console.log('PASS: moved-source split closes stale window, reopens empty and retains the exact stack through normal withdrawal and 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(); } +}