aorecomp

Anarchy Online classic in the browser

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


commit 885ce33f56bbab2fbd4a775d4f58b276205944d6
parent 3f1df5db439012cb52c9d96020f57dfabee99298
Author: anon <anon@example.com>
Date:   Tue,  3 Nov 2026 16:51:30 +0000

Verify instantiated loaded weapons through player trade

Diffstat:
MTODO.md | 7+++++++
Mdocs/player-trading.md | 35+++++++++++++++++++++++++++++++++++
Aserver/browser_traded_weapon_test.go | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_traded_weapon.mjs | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 329 insertions(+), 0 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -3850,6 +3850,13 @@ and server restarts. Turn every reproduced bug into a focused regression test. cases, native completion/retry, page replay and exact cold ownership pass; this leaves the broader audit open. See [pending equipment](docs/inventory.md#another-move-while-equipment-is-pending). + A focused two-client native trade now follows an already instantiated QL50 + weapon through cancellation, mutual acceptance, immediate recipient + wear/remove/rewear and one shot, without a corrective reconnect. Its physical + ID, selected endpoints, loaded rounds and exactly-once Sense survive page + and fresh-server recovery; the giver retains its separate ammunition stack. + This path passes without a product fix; the broader disappearance report + remains open. See [loaded weapon trade](docs/player-trading.md#instantiated-loaded-weapons). - [x] [P0] Preserve selected-quality stack contracts after a refused split. Reproduction: a real QL2 Ctrl-split during a controlled pending equip rebuilt its native endpoints as 25811/25811 instead of 25812/25811. Resolve the shared diff --git a/docs/player-trading.md b/docs/player-trading.md @@ -178,3 +178,38 @@ exceeds one bounded trace, so the return-trade audit merges the saved stages by event sequence. Evidence and independent verifiers are under `local/earned-eight/`, including `sales-verified.json`, `prepared-verified.json` and `prepared-cold-verified.json`. + +## Instantiated loaded weapons + +`TestBrowserTradedWeapon` closes a specific native coverage gap in the P0 +disappearing-equipment audit. A controlled QL50 Cheap Kerans is worn and removed +before offering it, so both clients already know physical weapon ID1. Real +input cancels one offer, offers the same item again and completes both players' +consent. The recipient's anonymous template row immediately supports wear, +remove and rewear as that same physical ID, without a reconnect. One ordinary +shot consumes a loaded round and deals2 HP; both clients see the impact. + +The giver retains its separate100-bullet stack, no weapon and no Sense bonus. +The recipient retains the QL50 weapon with12 of its original13 loaded rounds, +the selected160476/160477 endpoints and exactly one+2 Sense bonus. Page replay +and a fresh server preserve those two physical item/location rows, unchanged +wallets and raw skills/abilities. The level200, abilities300 and trained skills +are controlled, cap-checked setup; this is not earned progression evidence. +The gift does not establish additional historical trade policies. + +The accepted run `local/traded-weapon/20261103-084609` passes in88.52s +(warm61.30, cold27.21), or96.128s including Go. Independent packet and SQLite +checks verify that ID1 changes parent from player1 to player2, one shot leaves12 +rounds and both snapshots retain exact ownership. All eight native traces have +no errors or dropped events. Camera placement and a guessed window height +caused the earlier fixture stops, before the handoff was exercised; no product +defect was reproduced. The broader disappearance audit remains open. + +A cold-only run from that accepted warm database opens the giver's100-bullet +inventory and the recipient's worn-weapon panel with the native12-round HUD. +Both captures were reviewed; no trading or combat was repeated. Evidence is +`local/traded-weapon-cold-inventory/20261103-084947` (20.10s, Go27.725s). +All ten combined traces are error-free without dropped events; the independent +report is `local/traded-weapon/verification.json`. The focused player-trade +suite passes20 groups and65 results in16.846s; vet, JavaScript syntax, gofmt +and whitespace checks pass. diff --git a/server/browser_traded_weapon_test.go b/server/browser_traded_weapon_test.go @@ -0,0 +1,142 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserTradedWeapon(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for the focused native traded-weapon check") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/traded-weapon", time.Now().Format("20060102-150405")) + t.Chdir(t.TempDir()) + for _, phase := range []string{"warm", "cold"} { + t.Run(phase, func(t *testing.T) { + world := newServerForTest(t) + var target *character + for _, actor := range world.characters { + if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (target == nil || actor.id < target.id) { + target = actor + } + } + if phase == "warm" { + for index := 0; index < 2; index++ { + player := world.newCharacter() + player.name, player.appearance = fmt.Sprint("Trader", index), 0x515 + player.position = [3]float32{60, 14.75, 53 - float32(index)*3} + player.rotation = [4]float32{0, 1, 0, 0} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("traded-weapon-", index)))) + player.level = 200 + player.stats.Abilities = characterAbilitiesStats{300, 300, 300, 300, 300, 300} + player.stats.Ranged.SubmachineGun, player.stats.Ranged.Burst = 400, 283 + for stat, raw := range map[uint32]uint16{114: 400, 148: 283} { + if uint32(raw) > player.trainingMaximum(stat) { + t.Fatal("controlled raw skill exceeds its native cap", stat) + } + } + for stat, expected := range map[uint32]int32{114: 474, 148: 357} { + if actual, _ := player.effectiveStat(stat); actual != expected { + t.Fatal("controlled effective skill differs", stat, actual) + } + } + player.health, player.nano = player.maximumHealth(), player.maximumNano() + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + } + // A loaded selected-quality weapon and separate ammunition isolate ownership. + for _, template := range []uint32{160477, 21605} { + if granted, err := world.grantItem_locked(world.characters[1], template); err != nil || !granted { + t.Fatal(granted, err) + } + } + world.characters[1].inventory.Items[0].Quality = 50 + world.characters[1].inventory.Items[0].Ammo = 13 + if err := world.saveInventory_locked(world.characters[1], world.characters[1].inventory); err != nil { + t.Fatal(err) + } + target.position, target.motion.home = [3]float32{61, 14.75, 48.5}, [3]float32{61, 14.75, 48.5} + world.combatRoll = func(limit uint32) uint32 { + if limit == 100 { + return 99 + } + return 0 + } + } + owner, watcher := world.characters[1], world.characters[2] + 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{"owner": owner.inventory, "recipient": watcher.inventory, + "target": target.id, "health": target.health, "fighting": owner.fighting, "ownerHealth": owner.health, "ownerSense": owner.effectiveAbility(20), "recipientSense": watcher.effectiveAbility(20)}) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + world.advanceEquipment(now) + world.advanceCombat(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + + if err := os.MkdirAll(filepath.Join(output, phase), 0755); err != nil { + t.Fatal(err) + } + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_traded_weapon.mjs"), host.URL, filepath.Join(output, phase)) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + cancel() + <-stopped + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("VACUUM INTO ?", filepath.Join(output, phase, "world.sqlite")); err != nil { + t.Fatal(err) + } + t.Logf("Browser artifacts: %s", output) + + if err != nil { + t.Fatal(err) + } + expected := []ownedItem{{ID: 1, Type: 51018, Template: 160477, Quality: 50, Slot: 6, Count: 1, Ammo: 12}} + if !slices.Equal(watcher.inventory.Items, expected) || + !slices.Equal(owner.inventory.Items, []ownedItem{{ID: 2, Type: 51005, Template: 21605, Quality: 1, Slot: 65, Count: 100}}) || + owner.inventory.Credits != 0 || watcher.inventory.Credits != 0 || world.nextItem != 2 || + owner.effectiveAbility(20) != 300 || watcher.effectiveAbility(20) != 302 { + t.Fatal("native weapon trade lost ownership, rounds or Sense", owner.inventory, watcher.inventory) + } + }) + if t.Failed() { + return + } + } +} diff --git a/tools/client/test_traded_weapon.mjs b/tools/client/test_traded_weapon.mjs @@ -0,0 +1,145 @@ +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', headless: false, + args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +const games = [], evidence = {}; +async function inventoryClick(game, slot, button = 'right') { + await game.wait('equipment action finishes', state => + !game.local(state).actions.includes(3) && !game.local(state).actions.includes(6)); + const cell = game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 104 && cell.identity[1] === slot && !cell.dummy); + assert(cell, 'ordinary inventory cell is visible'); + await game.click((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2, button); +} +try { + for (const index of [0, 1]) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'traded-weapon-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + } + const [owner, recipient] = games; + const state = async () => (await owner.page.request.get(url + '/test-state')).json(); + evidence.initial = await state(); + if (evidence.initial.owner.Items.length === 2) { + // Instantiate the loaded weapon in both native worlds before offering it. + await owner.key('KeyI'); + await owner.page.keyboard.press('Control+1'); + await inventoryClick(owner, 48); + await owner.wait('original owner wears the physical weapon', snapshot => + owner.local(snapshot).inventory.some(item => item.id === 1 && item.slot === 6)); + assert.equal((await state()).ownerSense, 302); + await owner.click(867, 206, 'right'); + await owner.wait('same physical weapon removed', snapshot => + owner.local(snapshot).inventory.some(item => item.id === 1 && item.slot === 48)); + assert.equal((await state()).ownerSense, 300); + await owner.page.keyboard.press('Control+1'); + if (!owner.state.camera.firstPerson) await owner.key('F8'); + + // Both native participants see cancellation, then consent to the same gift. + for (let attempt = 0; attempt < 2; ++attempt) { + await owner.click(...await owner.pick(50000, 2), 'right'); + await Promise.all(games.map(game => game.wait('player trade opens', snapshot => + snapshot.regions.some(([left, top, right, bottom]) => + left === 832 && top === 0 && right === 1024 && bottom === 247)))); + await inventoryClick(owner, 48, 'left'); + const sequence = owner.sequence; + await owner.click(864, 172); + await owner.wait('physical weapon offered', () => owner.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '36284f6e' && + Buffer.from(event.hex, 'hex').readUInt32BE(33) === 4)); + await recipient.wait('peer weapon offer visible', snapshot => snapshot.grids.some(grid => + grid.cells.some(cell => cell.identity[0] === 208 && !cell.dummy))); + evidence['offered' + attempt] = await state(); + assert.equal(evidence['offered' + attempt].owner.Items[0].Ammo, 13); + assert.deepEqual(evidence['offered' + attempt].recipient.Items, null); + await recipient.save(output + '/offer-' + attempt); + if (attempt === 0) { + await owner.click(945, 228); + await owner.wait('cancelled weapon restored with its identity', snapshot => + owner.local(snapshot).inventory.some(item => item.id === 1 && item.slot === 48)); + assert.equal((await state()).owner.Items[0].Ammo, 13); + } + } + await owner.click(874, 228); + await recipient.click(874, 228); + await recipient.wait('gift appears in recipient inventory', snapshot => + recipient.local(snapshot).inventory.some(item => item.slot === 48 && item.quality === 50)); + evidence.transferred = await state(); + assert.equal(evidence.transferred.owner.Items.length, 1); + assert.equal(evidence.transferred.recipient.Items[0].ID, 1); + assert.equal(evidence.transferred.recipient.Items[0].Ammo, 13); + await recipient.save(output + '/received'); + + // Use the received row immediately, without reconnecting to repair it. + if (!recipient.state.grids.some(grid => grid.cells.some(cell => cell.identity[0] === 104 && !cell.dummy))) + await recipient.key('KeyI'); + await recipient.page.keyboard.press('Control+1'); + await inventoryClick(recipient, 48); + await recipient.wait('recipient wears the same physical weapon', snapshot => + recipient.local(snapshot).inventory.some(item => item.id === 1 && item.slot === 6)); + assert.equal((await state()).recipientSense, 302); + await recipient.click(867, 206, 'right'); + await recipient.wait('recipient removes the same weapon', snapshot => + recipient.local(snapshot).inventory.some(item => item.id === 1 && item.slot === 48)); + assert.equal((await state()).recipientSense, 300); + await inventoryClick(recipient, 48); + await recipient.wait('recipient rewields the same weapon', snapshot => + recipient.local(snapshot).inventory.some(item => item.id === 1 && item.slot === 6)); + + const deadline = Date.now() + 10000; + while (recipient.state.selected[0] !== 50000 || recipient.state.selected[1] !== evidence.initial.target) { + assert(Date.now() < deadline, 'Tab did not select the controlled Leet'); + const selected = recipient.state.selected; + await recipient.key('Tab'); + await recipient.wait('target cycle advances', snapshot => + snapshot.selected[0] !== selected[0] || snapshot.selected[1] !== selected[1]); + } + const sequence = recipient.sequence; + await recipient.key('KeyQ'); + await recipient.wait('recipient fires retained ammunition', () => recipient.events.some(event => + event.sequence > sequence && event.direction === 'framereceived' && event.opcode === '46002f16' && event.actor[1] === 2)); + await recipient.key('KeyQ'); + await Promise.all(games.map(game => game.wait('both clients see the impact', snapshot => + snapshot.actors.some(actor => actor.id === evidence.initial.target && actor.stats[27] === 98)))); + evidence.hit = await state(); + assert.equal(evidence.hit.health, 98); + assert.equal(evidence.hit.recipient.Items[0].Ammo, 12); + assert.equal(evidence.hit.owner.Items[0].Count, 100); + await recipient.save(output + '/hit'); + for (const game of games) { await game.page.reload(); await game.ready(); } + } + assert.deepEqual(owner.local().inventory.map(item => [item.id, item.slot, item.quality, item.count]), [[2, 49, 1, 100]]); + assert.deepEqual(recipient.local().inventory.map(item => [item.id, item.slot, item.quality, ...item.templates]), + [[1, 6, 50, 160476, 160477]]); + evidence.final = await state(); + assert.equal(evidence.final.ownerSense, 300); + assert.equal(evidence.final.recipientSense, 302); + assert.equal(evidence.final.recipient.Items[0].Ammo, 12); + if (!owner.state.grids.some(grid => grid.cells.some(cell => cell.identity[0] === 104 && !cell.dummy))) { + await owner.key('KeyI'); + await owner.wait('retained ammunition inventory opens', snapshot => snapshot.grids.some(grid => + grid.cells.some(cell => cell.identity[0] === 104 && !cell.dummy))); + } + if (!recipient.state.regions.some(([left, top, right, bottom]) => + left === 832 && top === 0 && right === 1024 && bottom === 360)) + await recipient.page.keyboard.press('Control+1'); + await recipient.wait('retained weapon panel opens', snapshot => snapshot.regions.some(([left, top, right, bottom]) => + left === 832 && top === 0 && right === 1024 && bottom === 360)); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: instantiated loaded weapon survives cancelled/accepted trade, immediate recipient use and page/cold recovery'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2)); + await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); + } finally { await browser.close(); } +}