aorecomp

Anarchy Online classic in the browser

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


commit 5d6b0a8be22676c917e990280587ad40568d6957
parent ec0ee20a3ecbd8e862d0015596ed66c7415c8504
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 01:58:41 +0000

Refresh stale ordinary stacks after refused shop offers

Diffstat:
MTODO.md | 9+++++++++
Mdocs/shops.md | 29+++++++++++++++++++++++++++++
Aserver/browser_shop_refusal_test.go | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/shop_stale_offer_test.go | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/shops.go | 6+++++-
Atools/client/test_shop_refusal.mjs | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 272 insertions(+), 1 deletion(-)

diff --git a/TODO.md b/TODO.md @@ -4050,6 +4050,15 @@ 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 ordinary stacks after a stale shop offer. Reproduction: + an earlier controlled merge consumes the offered source without refreshing + the native inventory. Shop cancellation leaves its ghost and old survivor + count visible. Cancellation now precedes an authoritative stack refresh, + without ownership writes or false sale success. A short WASM check removes + the ghost, restores eight/seven charges, retries and cancels a real offer on + the same page, and retains both IDs through page/cold recovery. This isolates + the broader disappearance audit above. See + [stale shop offers](docs/shops.md#stale-owned-sale-sources). - [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 diff --git a/docs/shops.md b/docs/shops.md @@ -463,6 +463,35 @@ SQLite writes leave both RAM and disk unchanged. A lost completion reply or repeated/concurrent Accept cannot award the sale twice. Reconnect discards an unaccepted draft and reloads authoritative inventory and credits. +## Stale owned sale sources + +A controlled missed-refresh fixture isolates a stale shop offer: three QL2 +Treatment Laboratories show 3/5/7 charges, while an earlier committed merge +has consumed the first and retained eight charges in the second. Real native +pickup and SELL placement request the now-empty ordinary slot. The original +cancellation closes the shop but restores the three-charge ghost and leaves +the survivor showing five. + +For an authenticated sale Add with a valid, missing ordinary slot, cancellation +now precedes the shared ordinary-stack refresh. This removes stale rows and +rebuilds the selected template endpoints, QL and current counts while preserving +live individual rows. It does not acknowledge a sale or write ownership/cash. +Other invalid offer guards retain their existing cancellation policy. + +`TestShopStaleOfferRefreshesStacksWithoutWrites` checks repeated requests, +cancellation order, the selected QL2 endpoints, unchanged cold ownership and +allocation, no checkpoint writes, and preservation of an unrelated live weapon. +`TestBrowserShopSaleRefusal` reproduces the actual native request, verifies +usable eight/seven-charge rows, reopens the shop on the same page to offer and +cancel the survivor, then checks exact page replay and cold ownership. This is +a controlled state fixture, not earned-progression evidence. + +The failing native capture is +`local/shop-sale-refusal/20261103-175253/`; the corrected 16-second check is +`local/shop-sale-refusal/20261103-175424/`. The screenshots show the baseline +3/5/7 ghost state and corrected 8/7 state. The broader disappearance audit +remains open. + ## Verification `server/gamedata/shops_test.go` checks all 795 authored identities, templates, diff --git a/server/browser_shop_refusal_test.go b/server/browser_shop_refusal_test.go @@ -0,0 +1,85 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "reflect" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserShopSaleRefusal(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for shop sale refusal") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/shop-sale-refusal", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.playfield, player.position, player.appearance = 1183, [3]float32{188, 5.751, 135.5}, 0x515 + player.rotation = [4]float32{0, .70710677, 0, .70710677} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("shop-sale-refusal"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 3, Items: []ownedItem{ + {ID: 1, Type: 51005, Template: 25812, Quality: 2, Slot: 64, Count: 3}, + {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 65, Count: 5}, + {ID: 3, Type: 51005, Template: 25812, Quality: 2, Slot: 66, 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() + open := world.clients[1] != nil && world.clients[1].shop != nil + json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "open": open}) + }) + // Isolate an earlier committed merge without refreshing the native view. + 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[1:]) + inventory.Items[0].Count = 8 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Error(err) + http.Error(w, err.Error(), http.StatusInternalServerError) + } + }) + 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_shop_refusal.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).characters[1].inventory + expected := []ownedItem{{ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 64, Count: 8}, + {ID: 3, Type: 51005, Template: 25812, Quality: 2, Slot: 66, Count: 7}} + if !reflect.DeepEqual(cold.Items, expected) || !reflect.DeepEqual(player.inventory.Items, expected) || + cold.Credits != 0 || player.inventory.Credits != 0 || world.nextItem != 3 { + t.Fatal("sale refusal changed ownership or cash", cold) + } +} diff --git a/server/shop_stale_offer_test.go b/server/shop_stale_offer_test.go @@ -0,0 +1,61 @@ +package main + +import ( + "bytes" + "encoding/binary" + "reflect" + "testing" +) + +func TestShopStaleOfferRefreshesStacksWithoutWrites(t *testing.T) { + world, output := newShopWorld(t) + player, client := world.characters[1], world.clients[1] + inventory := player.inventory + inventory.LastID = 3 + inventory.Items = []ownedItem{ + {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 67, Count: 1}, + {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 65, Count: 8}, + {ID: 3, Type: 51005, Template: 25812, Quality: 2, Slot: 66, Count: 7}} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + auditCheckpointWrites(t, world) + output.packets = nil + request := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:] + + for range 2 { + if err := world.handleTrade(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 || client.shop != nil || + !reflect.DeepEqual(player.inventory, inventory) || !reflect.DeepEqual(cold.characters[1].inventory, inventory) || + world.nextItem != 3 || cold.nextItem != 3 { + t.Fatal("stale offer changed inventory, cash or allocation", err) + } + if len(output.packets) < 2 || binary.BigEndian.Uint32(output.packets[0][16:20]) != 0x36284f6e || + binary.BigEndian.Uint32(output.packets[0][33:37]) != 2 { + t.Fatal("stale offer omitted cancellation before the refresh") + } + var additions [][4]uint32 + for _, packet := range output.packets[1:] { + if binary.BigEndian.Uint32(packet[16:20]) == 0x052e2f0c { + additions = append(additions, [4]uint32{binary.BigEndian.Uint32(packet[29:33]), binary.BigEndian.Uint32(packet[33:37]), + binary.BigEndian.Uint32(packet[37:41]), binary.BigEndian.Uint32(packet[41:45])}) + } + if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && + binary.BigEndian.Uint32(packet[29:33]) == 112 && binary.BigEndian.Uint32(packet[37:41]) == 51 { + t.Fatal("refresh retired the unrelated live weapon") + } + } + if !reflect.DeepEqual(additions, [][4]uint32{{25812, 25811, 2, 8}, {25812, 25811, 2, 7}}) { + t.Fatal("stale offer omitted authoritative selected-quality stacks", additions) + } +} diff --git a/server/shops.go b/server/shops.go @@ -298,7 +298,11 @@ func (server *server) handleTrade(client *worldClient, body []byte) error { } index := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { return item.Slot == second[1] }) if index < 0 { - return server.abortShop_locked(client) + if err := server.abortShop_locked(client); err != nil { + return err + } + // Cancellation restores the drag, but not stale stack rows or counts. + return server.syncStacks_locked(client) } item := player.inventory.Items[index] definition := item.templateDefinition() diff --git a/tools/client/test_shop_refusal.mjs b/tools/client/test_shop_refusal.mjs @@ -0,0 +1,83 @@ +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: 'shop-sale-refusal', 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 clickCell = async source => game.click( + (source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2); + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + evidence.before = await server(); + await game.key('KeyI'); + if (!game.state.camera.firstPerson) await game.key('F8'); + await game.click(...await game.pick(51035, 3221488799), 'right'); + await game.wait('Tools shop opens', state => state.grids.some(grid => + grid.cells.some(cell => cell.identity[0] === 111 && !cell.dummy))); + assert((await page.request.post(url + '/test-stale-view')).ok()); + evidence.merged = await server(); + await game.save(output + '/stale'); + await clickCell(cell(48)); + await game.wait('stale source picked', state => state.dragged[0] === 104 && state.dragged[1] === 48); + const sequence = game.sequence; + await game.click(860, 412); + await game.wait('native stale sale request', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '36284f6e' && + Buffer.from(event.hex, 'hex').readUInt32BE(33) === 4)); + await game.wait('stale offer aborts shop', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framereceived' && event.opcode === '36284f6e' && + Buffer.from(event.hex, 'hex').readUInt32BE(33) === 2)); + await game.wait('current source counts restored without a ghost', state => !cell(48) && cell(49) && cell(50) && + game.local(state).inventory.find(item => item.slot === 49)?.count === 8); + evidence.refused = await server(); + assert.deepEqual(evidence.refused.inventory, evidence.merged.inventory); + await game.save(output + '/refused'); + + // Retry through ordinary native input on the same page, then cancel the sale. + await game.click(...await game.pick(51035, 3221488799), 'right'); + await game.wait('shop reopens', state => state.grids.some(grid => + grid.cells.some(cell => cell.identity[0] === 111 && !cell.dummy))); + await clickCell(cell(49)); + await game.wait('surviving stack picked', state => state.dragged[0] === 104 && state.dragged[1] === 49); + await game.click(860, 412); + await game.wait('current stack offered', state => state.grids.some(grid => + grid.cells.some(cell => cell.identity[0] === 108 && !cell.dummy))); + await game.save(output + '/retry'); + await game.click(945, 475); + await game.wait('cancelled offer remains usable in its restored slot', state => cell(48) && cell(50) && + game.local(state).inventory.some(item => item.slot === 48 && item.count === 8)); + evidence.after = await server(); + assert.deepEqual(evidence.after.inventory.Items.map(item => [item.ID, item.Slot, item.Count]), [[2, 64, 8], [3, 66, 7]]); + assert.equal(evidence.after.inventory.Credits, 0); + await page.reload(); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.quality, item.count, ...item.templates]), + [[2, 48, 2, 8, 25812, 25811], [3, 50, 2, 7, 25812, 25811]]); + assert.deepEqual(await server(), evidence.after); + assert.deepEqual(game.errors, []); + console.log('PASS: stale shop source removed, current counts restored, native retry and page/cold ownership retain 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(); } +}