commit 2c5c5e785b77f1b0478a36cea3ffa7b108b953ca
parent ae585b666bfacbf43f27b544eb0697ad13710985
Author: anon <anon@example.com>
Date: Tue, 3 Nov 2026 22:58:10 +0000
fix: cancel and refresh stale backpack withdrawals
Diffstat:
6 files changed, 338 insertions(+), 1 deletion(-)
diff --git a/TODO.md b/TODO.md
@@ -4021,6 +4021,15 @@ and server restarts. Turn every reproduced bug into a focused regression test.
withdrawal. These checks now pass, preserving the bank anchor and all three
physical identities across page/cold recovery, with no ownership writes for
repeated stale requests. See [stale withdrawals](docs/bank-storage.md#stale-withdrawal-sources).
+- [x] [P0] Cancel and refresh stale carried-backpack withdrawals. Reproduction:
+ an earlier controlled bag-to-bag transfer leaves a loaded QL2 pistol visible
+ in its old native window; pickup/place sends a real request with no reply and
+ hides the source. Completion: cancel the packed source, remove its ghost from
+ current contents, and withdraw the remaining QL2 charged item through the same
+ window. Preserve handle state, pending equipment, four IDs, three charges and
+ three loaded rounds through page and fresh-server WASM recovery. These checks
+ pass, with no ownership writes for repeated refusals. See
+ [stale backpack sources](docs/backpacks.md#stale-withdrawal-sources).
- [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/backpacks.md b/docs/backpacks.md
@@ -272,6 +272,39 @@ returns the same part. Page replay and a fresh database reader retain all three
instances. This is fixture evidence, not earned progression; see
`local/backpack-refusals/` and its referenced native captures.
+## Stale withdrawal sources
+
+A known carried bag can have an empty slot behind a stale native window. The
+former transfer guard silently ignored that pickup/place request and left its
+source hidden. Empty slots within the original 21-slot capacity now receive
+CharacterAction146 with their unchanged packed page107 position. An open handle
+then receives current BackpackIIR contents, removing the ghost while keeping
+the remaining item usable. Closed handles stay closed and receive only the
+cancellation. Unknown handles and out-of-range slots receive no contents.
+
+`TestBackpackStaleWithdrawalCancelsAndRefreshesWithoutWrites` uses ordinary
+opening, deposit and withdrawal through public handlers before repeating the
+empty-source request. It checks empty/partially filled bags, a closed handle,
+pending equipment, unknown handles and the capacity boundary. SQL write counts,
+durable ownership, handles and the admitted equipment deadline remain unchanged;
+cold loading retains the exact items.
+
+`TestBrowserStaleBackpackWithdrawal` isolates an earlier bag-to-bag transfer in
+a controlled fixture, without refreshing the source's native view. Real native
+pickup/place reproduces the missing reply. After correction, the same window
+withdraws its remaining QL2 three-charge laboratory. Page replay and a fresh
+server/WASM phase retain both bags, that laboratory and the QL2 pistol in the
+other bag, including its three loaded rounds. This is controlled ownership and
+UI evidence, not earned progression or a historical lost-reply policy.
+The native phases pass in 16.53/8.56 seconds under
+`local/stale-backpack/20261103-145502/`, with five clean traces. The independent
+verifier checks the actual packed request, cancellation-before-contents order,
+selected endpoints, native quantities and exact warm/page/cold ownership.
+Related Go checks pass68roots/265results, focused race checks pass4/12, and vet
+and driver syntax checks pass. The report is
+`local/stale-backpack/verification.json`. The broader disappearance audit stays
+open; no client or published-bundle change is needed for this server refusal.
+
## Verification
`server/backpacks_test.go` exercises the actual world connection for opening and
diff --git a/server/backpacks.go b/server/backpacks.go
@@ -207,13 +207,22 @@ func (server *server) moveContainerItem_locked(client *worldClient, body []byte)
}
index := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == sourceSlot })
if index < 0 {
- // A stale bank window still hides its picked source until cancellation.
+ // Stale container windows hide their picked source until cancellation.
if sourcePage == 105 && sourceSlot < bankCapacity {
if err := client.send(characterActionPacket(client.id, [5]uint32{146, sourcePage, sourceSlot})); err != nil {
return err
}
return client.send(bankInventoryPacket(player))
}
+ if sourceBag != 0 && sourceSlot < 21 {
+ position := binary.BigEndian.Uint32(body[20:24])
+ if err := client.send(characterActionPacket(client.id, [5]uint32{146, 107, position})); err != nil {
+ return err
+ }
+ if client.backpacks[position>>16].open {
+ return client.send(backpackInventoryPacket(client.id, sourceBag, position>>16, items))
+ }
+ }
return nil
}
item := items[index]
diff --git a/server/browser_stale_backpack_test.go b/server/browser_stale_backpack_test.go
@@ -0,0 +1,105 @@
+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 TestBrowserStaleBackpackWithdrawal(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for stale backpack withdrawal")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/stale-backpack", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("stale-backpack")))
+ 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},
+ {ID: 4, Type: 51017, Template: 99228, Quality: 1, Slot: 65, Count: 1}},
+ Containers: map[uint32][]ownedItem{1: {
+ {ID: 2, Type: 51018, Template: 123742, Quality: 2, Slot: 0, Count: 1, Ammo: 3},
+ {ID: 3, Type: 51005, Template: 25812, Quality: 2, Slot: 1, Count: 3}}}}
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.db.Close(); err != nil {
+ t.Fatal(err)
+ }
+ for _, phase := range []string{"withdrawal", "cold"} {
+ t.Run(phase, func(t *testing.T) {
+ world := newServerForTest(t)
+ player := world.characters[1]
+ 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)
+ })
+ // Commit an earlier bag-to-bag transfer without refreshing the source 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.Containers = maps.Clone(inventory.Containers)
+ inventory.Containers[4] = []ownedItem{inventory.Containers[1][0]}
+ inventory.Containers[1] = slices.Clone(inventory.Containers[1][1:])
+ 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_stale_backpack.mjs"), host.URL, filepath.Join(output, phase), phase)
+ 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)
+ }
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ expected := []ownedItem{{ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1},
+ {ID: 4, Type: 51017, Template: 99228, Quality: 1, Slot: 65, Count: 1},
+ {ID: 3, Type: 51005, Template: 25812, Quality: 2, Slot: 66, Count: 3}}
+ contents := []ownedItem{{ID: 2, Type: 51018, Template: 123742, Quality: 2, Slot: 0, Count: 1, Ammo: 3}}
+ if len(player.inventory.Items) != 3 || len(player.inventory.Containers) != 1 ||
+ !slices.Equal(player.inventory.Containers[4], contents) || world.nextItem != 4 {
+ t.Fatal("stale backpack request changed identity, charges or loaded rounds")
+ }
+ for _, item := range expected {
+ if !slices.Contains(player.inventory.Items, item) {
+ t.Fatal("stale backpack recovery lost an exact owned instance", item)
+ }
+ }
+ })
+ if t.Failed() {
+ return
+ }
+ }
+}
diff --git a/server/stale_backpack_test.go b/server/stale_backpack_test.go
@@ -0,0 +1,92 @@
+package main
+
+import (
+ "bytes"
+ "cmp"
+ "maps"
+ "reflect"
+ "slices"
+ "testing"
+)
+
+func TestBackpackStaleWithdrawalCancelsAndRefreshesWithoutWrites(t *testing.T) {
+ for _, scenario := range []string{"empty", "remaining item", "closed", "pending equipment", "unknown handle", "outside"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, conn := newBackpackWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleInventory(client, backpackMoveRequest(104, 68, 51017, 3, 111)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if scenario == "remaining item" {
+ if err := world.handleInventory(client, backpackMoveRequest(104, 65, 51017, 3, 111)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ request := backpackMoveRequest(107, 1<<16, 50000, 1, 111)[20:]
+ if err := world.handleInventory(client, request); err != nil {
+ t.Fatal(err)
+ }
+ switch scenario {
+ case "closed":
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ case "pending equipment":
+ if err := world.handleInventory(client, inventoryMovePacket(1, 68, 6)[20:]); err != nil || client.equipment == nil {
+ t.Fatal("withdrawn weapon did not begin equipment", err)
+ }
+ case "unknown handle":
+ request = backpackMoveRequest(107, 2<<16, 50000, 1, 111)[20:]
+ case "outside":
+ request = backpackMoveRequest(107, 1<<16|21, 50000, 1, 111)[20:]
+ }
+ handles := maps.Clone(client.backpacks)
+ var pending equipmentMove
+ if client.equipment != nil {
+ pending = *client.equipment
+ }
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ auditCheckpointWrites(t, world)
+ conn.packets = nil
+
+ for range 2 {
+ if err := world.handleInventory(client, request); err != nil {
+ t.Fatal(err)
+ }
+ }
+ after, err := readTestItemStore(world)
+ cold := newTestInventoryServer(t)
+ expected := player.inventory
+ expected.Items = slices.Clone(expected.Items)
+ slices.SortFunc(expected.Items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) })
+ restored := cold.characters[1].inventory
+ restored.Items = slices.Clone(restored.Items)
+ slices.SortFunc(restored.Items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) })
+
+ if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 ||
+ !reflect.DeepEqual(handles, client.backpacks) ||
+ (scenario == "pending equipment") != (client.equipment != nil) || client.equipment != nil && *client.equipment != pending {
+ t.Fatal("stale withdrawal changed ownership, writes, handles or the admitted move", err)
+ }
+ if !reflect.DeepEqual(expected, restored) {
+ t.Fatalf("cold ownership differs: live=%+v cold=%+v", expected, restored)
+ }
+ var replies [][]byte
+ if scenario != "unknown handle" && scenario != "outside" {
+ replies = append(replies, targetPacket(characterActionPacket(1, [5]uint32{146, 107, 1 << 16})))
+ if scenario != "closed" {
+ replies = append(replies, targetPacket(backpackInventoryPacket(1, 3, 1, player.inventory.Containers[3])))
+ }
+ }
+ if !reflect.DeepEqual(conn.packets, append(slices.Clone(replies), replies...)) {
+ t.Fatalf("stale withdrawal needs ordered cancellation and current open contents: got %d replies", len(conn.packets))
+ }
+ })
+ }
+}
diff --git a/tools/client/test_stale_backpack.mjs b/tools/client/test_stale_backpack.mjs
@@ -0,0 +1,89 @@
+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, phase] = 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-backpack', url}]);
+ const page = await context.newPage();
+ game = await GameTest.attach(page);
+ const server = async () => (await page.request.get(url + '/test-state')).json();
+ const source = (state, slot) => state.grids.flatMap(grid => grid.cells).find(cell =>
+ cell.identity[0] === 107 && cell.identity[1] === (65536 | slot) && !cell.dummy);
+ const carried = (state, slot) => state.grids.flatMap(grid => grid.cells).find(cell =>
+ cell.identity[0] === 104 && cell.identity[1] === slot && !cell.dummy);
+ const clickCell = async cell => game.click((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2);
+ const inventory = async () => {
+ if (!game.state.grids.some(grid => grid.totalCells === 30)) await game.key('KeyI');
+ };
+ await page.goto(url);
+ await game.ready();
+ await page.waitForFunction(() => touchRegion(500, 400)?.world === true);
+ await game.snapshot();
+ await inventory();
+ if (phase === 'withdrawal') {
+ const bag = carried(game.state, 48);
+ await game.click((bag.bounds[0] + bag.bounds[2]) / 2, (bag.bounds[1] + bag.bounds[3]) / 2, 'right');
+ await game.wait('both backpack sources open', state => source(state, 0) && source(state, 1));
+ assert((await page.request.post(url + '/test-stale-view')).ok());
+ evidence.transferred = await server();
+ assert.deepEqual(evidence.transferred.Containers[1].map(item => [item.ID, item.Slot]), [[3, 1]]);
+ assert.equal(evidence.transferred.Containers[4][0].ID, 2);
+ await game.save(output + '/stale');
+ const withdraw = async slot => {
+ const sequence = game.sequence;
+ await clickCell(source(game.state, slot));
+ await game.wait('backpack source picked', state => state.dragged[0] === 107 && state.dragged[1] === (65536 | slot));
+ await clickCell(game.state.grids.find(grid => grid.totalCells === 30).cells.find(cell => cell.identity[0] === 0));
+ await game.wait('actual backpack withdrawal', () => game.events.some(event => event.sequence > sequence &&
+ event.direction === 'framesent' && event.opcode === '47537a24' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(29) === 107 && Buffer.from(event.hex, 'hex').readUInt32BE(33) === (65536 | slot)));
+ return sequence;
+ };
+ const sequence = await withdraw(0);
+ await game.wait('stale backpack request cancelled', () => game.events.some(event => event.sequence > sequence &&
+ event.direction === 'framereceived' && event.opcode === '5e477770' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(29) === 146));
+ await game.wait('backpack refresh removes ghost and retains remaining source', state => !source(state, 0) && source(state, 1));
+ assert.deepEqual(game.state.dragged, [0, 0]);
+ evidence.refused = await server();
+ assert.deepEqual(evidence.refused, evidence.transferred);
+ await game.save(output + '/refused');
+ await withdraw(1);
+ await game.wait('remaining source transfers in same window', state => game.local(state).inventory.some(item =>
+ item.id === 3 && item.slot === 50 && item.quality === 2 && item.count === 3));
+ evidence.after = await server();
+ assert.deepEqual(evidence.after.Items.map(item => [item.ID, item.Slot]), [[1, 64], [4, 65], [3, 66]]);
+ assert.equal(evidence.after.Containers[1], undefined);
+ await game.save(output + '/collected');
+ await page.reload();
+ await game.ready();
+ await page.waitForFunction(() => touchRegion(500, 400)?.world === true);
+ await game.snapshot();
+ assert.deepEqual(await server(), evidence.after);
+ await inventory();
+ }
+ assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.templates, item.quality, item.count]), [
+ [1, 48, [99228, 99228], 1, 1], [4, 49, [99228, 99228], 1, 1], [3, 50, [25812, 25811], 2, 3]]);
+ const bag = carried(game.state, 49);
+ await game.click((bag.bounds[0] + bag.bounds[2]) / 2, (bag.bounds[1] + bag.bounds[3]) / 2, 'right');
+ await game.wait('earlier transferred weapon visible in its retained backpack', state => source(state, 0));
+ evidence.final = await server();
+ assert.deepEqual(evidence.final.Containers[4], [{ID: 2, Type: 51018, Template: 123742, Quality: 2, Slot: 0, Count: 1, Ammo: 3}]);
+ assert.deepEqual(game.errors, []);
+ console.log('PASS: stale backpack withdrawal cancelled; same-window retry/page/cold conserve four IDs, three charges and three loaded rounds');
+} 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(); }
+}