commit c747b4d8d1859b4753ab2d69c49a6658126f4dd3
parent a1e470df75fa98c69172bb4753be38ec28c60904
Author: anon <anon@example.com>
Date: Wed, 4 Nov 2026 12:39:15 +0000
Complete stale contained Use and clear its cached source
Diffstat:
7 files changed, 286 insertions(+), 3 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -3291,6 +3291,16 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah
page101/slot15 receives failure2 with its original sequence and source;
replay/invalid references do not change items, equipment or bonuses, and
supported backpack Use still works afterward.
+- [x] [P1] Complete stale contained-item Use without retaining a ghost source.
+ An earlier controlled bag-to-bag transfer leaves the old Briefcase visible;
+ its real page107 Use request consumed the sequence but received no completion.
+ Failure2 with the exact sequence/source now precedes clearing only that empty
+ cached row. An empty contents snapshot alone leaves the native icon present.
+ Public-handler checks preserve open/closed handles, other contents, ownership,
+ allocation and duplicate/invalid-source guards. A 15-second WASM check clears
+ the ghost, uses the same Briefcase from its real bag on the same page, and
+ retains both bags/item through page replay and cold Go loading. This is a
+ controlled checkpoint; see [stale contained Use](docs/remote-bank.md#stale-contained-use).
- [x] Support NCU Hacker Interface equipment at QL1..200. Use original
endpoints158416/158417 and shared interpolation for all six nano skills and
the Fixer/level wear requirement. Keep source Interface161699 separate.
diff --git a/docs/remote-bank.md b/docs/remote-bank.md
@@ -86,6 +86,42 @@ Use3 combat restriction, so those events stay distinct. General combat equipment
changes still use the existing combat-swap policy. Specials and OnHit effects
remain explicit TODOs.
+## Stale contained Use
+
+A known carried backpack can retain an old native child after an earlier
+transfer commits without its contents refresh. The server previously consumed
+the new Use sequence but returned without completing it when that child slot
+was empty. A valid page107 position now receives failure2 with its exact command
+sequence and packed source. CharacterAction112 then clears only that empty
+cached child row, removing its stale icon while retaining other items. An empty
+BackpackIIR snapshot alone leaves the native child cached. Closed handles stay
+closed. Unknown handles, out-of-range child slots and
+non-carried bags retain their ownership guards.
+
+`TestStaleContainedUseCompletesAndClearsOnlyEmptyOwnedSources` covers both
+child boundaries, duplicate sequences, open/closed handles, unknown handles and
+the first invalid slot. It checks exact ordered replies, unchanged sessions,
+zero checkpoint writes, byte-identical item storage and cold ownership. A later
+valid Use opens the bank through the retained Briefcase. The existing unavailable
+source regression also requires clearing only the empty slot while retaining the
+real child in another slot, without reporting successful bank Use.
+
+`TestBrowserStaleContainedUse` isolates an earlier bag-to-bag transfer with a
+controlled level100 Bureaucrat and sufficient Psychology. A real native
+right-click reproduces the unanswered command. Completion and row clearing
+then remove the old icon; the same page opens the real destination and uses that
+exact Briefcase to open the bank. Page replay and a fresh Go database reader
+retain both bags and the Briefcase without new allocation or consumption.
+Captures are retained under `local/stale-contained-use/`. This is controlled
+protocol/ownership evidence, separate from earned acquisition and original-server
+lost-publication policy.
+The initial missing-completion run fails in19.18seconds; a contents-only
+correction still leaves the ghost. Explicit row clearing passes in14.71seconds.
+The final focused Go and race selections each pass11roots/54results, with vet
+and driver syntax checks passing. Exact reply/clear ordering, the empty native
+row, later accepted Use and unchanged ledger are independently checked in
+`local/stale-contained-use/verification.json`.
+
## Verification
Automated tests exercise exact Psychology/title boundaries, ability trickle,
diff --git a/server/backpacks.go b/server/backpacks.go
@@ -84,7 +84,7 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error
// Known carried contents remain usable after their bag window closes.
slot := binary.BigEndian.Uint32(body[44:48])
bag := client.backpacks[slot>>16].id
- if bag == 0 || !slices.ContainsFunc(player.inventory.Items, func(item ownedItem) bool { return item.ID == bag && item.isPortableContainer() }) {
+ if bag == 0 || slot&65535 >= 21 || !slices.ContainsFunc(player.inventory.Items, func(item ownedItem) bool { return item.ID == bag && item.isPortableContainer() }) {
return nil
}
for _, item := range player.inventory.Containers[bag] {
@@ -92,7 +92,13 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error
return server.useRemoteBank_locked(client, item, body)
}
}
- return nil
+ // Complete the old command before clearing only its empty cached child row.
+ reply := append([]byte(nil), body[16:]...)
+ binary.BigEndian.PutUint32(reply, 2)
+ if err := client.send(n3Packet(0x52526858, 50000, client.id, reply)); err != nil {
+ return err
+ }
+ return client.send(characterActionPacket(client.id, [5]uint32{112, 107, slot}))
}
if page == 104 || page == 101 {
index := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool {
diff --git a/server/browser_stale_contained_use_test.go b/server/browser_stale_contained_use_test.go
@@ -0,0 +1,81 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserStaleContainedUse(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for stale contained Use")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/stale-contained-use", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.level, player.profession = 100, 8
+ player.stats.TradeRepair.Psychology = 500
+ player.playfield, player.position = 1183, [3]float32{193.79826, 5.01, 136.83983}
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("stale-contained-use")))
+ 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: 2, Type: 51017, Template: 99228, Quality: 1, Slot: 65, Count: 1}},
+ Containers: map[uint32][]ownedItem{1: {{ID: 3, Type: 51018, Template: 205736, Quality: 100, Count: 1}}}}
+ 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(player.inventory)
+ })
+ // Retain the old native child while committing an earlier bag-to-bag transfer.
+ 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 = map[uint32][]ownedItem{2: inventory.Containers[1]}
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Error(err)
+ http.Error(w, err.Error(), 500)
+ }
+ })
+ 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_contained_use.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)
+ }
+ inventory.Containers = map[uint32][]ownedItem{2: inventory.Containers[1]}
+ if world.nextItem != 3 || !reflect.DeepEqual(player.inventory, inventory) ||
+ !reflect.DeepEqual(newTestInventoryServer(t).characters[1].inventory, inventory) {
+ t.Fatal("stale Use/retry changed the Briefcase or either backpack")
+ }
+}
diff --git a/server/remote_bank_test.go b/server/remote_bank_test.go
@@ -200,7 +200,14 @@ func TestRemoteBankRejectsUnavailableCarriedSources(t *testing.T) {
if err != nil || !bytes.Equal(before, after) || client.bank != nil {
t.Fatal("unavailable or non-carried source opened remote storage", err)
}
- for _, packet := range conn.packets {
+ if scenario == "missing child" && (len(conn.packets) != 2 ||
+ !bytes.Equal(conn.packets[1], targetPacket(characterActionPacket(1, [5]uint32{112, 107, 1<<16 | 20})))) {
+ t.Fatal("missing-child refusal did not clear only its empty source")
+ }
+ for index, packet := range conn.packets {
+ if scenario == "missing child" && index == 1 {
+ continue
+ }
if binary.BigEndian.Uint32(packet[16:20]) != 0x52526858 || binary.BigEndian.Uint32(packet[29:33]) != 2 {
t.Fatalf("unavailable source sent success: %x", conn.packets)
}
diff --git a/server/stale_contained_use_test.go b/server/stale_contained_use_test.go
@@ -0,0 +1,70 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "maps"
+ "reflect"
+ "testing"
+)
+
+func TestStaleContainedUseCompletesAndClearsOnlyEmptyOwnedSources(t *testing.T) {
+ for _, source := range []uint32{1 << 16, 1<<16 | 20, 1<<16 | 21, 2 << 16} {
+ for _, closed := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%d/closed%v", source, closed), func(t *testing.T) {
+ world, output := newRemoteBankWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleInventory(client, backpackMoveRequest(104, 69, 51017, 3, 111)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleInventory(client, backpackMoveRequest(107, 1<<16, 50000, 1, 69)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if closed {
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ request := backpackUseRequest(1, source, 10)[20:]
+ binary.BigEndian.PutUint32(request[40:44], 107)
+ handles := maps.Clone(client.backpacks)
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ auditCheckpointWrites(t, world)
+ output.packets = nil
+
+ for range 2 {
+ if err := world.handleOwnedItemUse(client, request); err != nil {
+ t.Fatal(err)
+ }
+ }
+ after, err := readTestItemStore(world)
+
+ if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 ||
+ !reflect.DeepEqual(handles, client.backpacks) || client.bank != nil || world.nextItem != 6 ||
+ !reflect.DeepEqual(player.inventory, newTestInventoryServer(t).characters[1].inventory) {
+ t.Fatal("stale contained Use changed durable ownership, allocation or sessions", err)
+ }
+ var expected [][]byte
+ if source>>16 == 1 && source&65535 < 21 {
+ reply := bytes.Clone(request[16:])
+ binary.BigEndian.PutUint32(reply, 2)
+ expected = append(expected, targetPacket(n3Packet(0x52526858, 50000, 1, reply)))
+ expected = append(expected, targetPacket(characterActionPacket(1, [5]uint32{112, 107, source})))
+ }
+ if !reflect.DeepEqual(output.packets, expected) {
+ t.Fatalf("stale contained Use omitted its exact completion/empty row clearing: got %d replies, want %d", len(output.packets), len(expected))
+ }
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 69, 11)[20:]); err != nil || client.bank == nil {
+ t.Fatal("later valid Use of the retained Briefcase failed", err)
+ }
+ })
+ }
+ }
+}
diff --git a/tools/client/test_stale_contained_use.mjs b/tools/client/test_stale_contained_use.mjs
@@ -0,0 +1,73 @@
+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: 'stale-contained-use', 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 = (page, slot) => game.state.grids.flatMap(grid => grid.cells).find(cell =>
+ cell.identity[0] === page && cell.identity[1] === slot && !cell.dummy);
+ const use = async (page, slot) => {
+ const source = cell(page, slot);
+ assert(source, 'native Use source is visible');
+ await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2, 'right');
+ };
+ const command = async slot => {
+ const sequence = game.sequence;
+ await use(107, slot);
+ await game.wait('actual contained Use request', () => game.events.some(event => event.sequence > sequence &&
+ event.direction === 'framesent' && event.opcode === '52526858' && Buffer.from(event.hex, 'hex').readUInt32BE(53) === 107));
+ const request = game.events.find(event => event.sequence > sequence && event.direction === 'framesent' && event.opcode === '52526858');
+ return {sequence, reference: Buffer.from(request.hex, 'hex').readUInt32BE(33)};
+ };
+ await game.key('KeyI');
+ await use(104, 48);
+ await game.wait('Briefcase source visible in first bag', () => cell(107, 65536));
+ assert((await page.request.post(url + '/test-stale-view')).ok());
+ evidence.before = await server();
+ const first = await command(65536);
+ evidence.first = first;
+ await game.save(output + '/requested');
+ await game.wait('stale Use receives exact failure completion', () => game.events.some(event => event.sequence > first.sequence &&
+ event.direction === 'framereceived' && event.opcode === '52526858' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(29) === 2 && Buffer.from(event.hex, 'hex').readUInt32BE(33) === first.reference));
+ await game.wait('empty cached child row clears', () => !cell(107, 65536));
+ assert.deepEqual(await server(), evidence.before);
+ await game.save(output + '/refused');
+ await use(104, 48);
+ await game.wait('first bag closes', state => !state.grids.some(grid => grid.totalCells === 21));
+ await use(104, 49);
+ await game.wait('real Briefcase destination opens', () => cell(107, 131072));
+ const second = await command(131072);
+ evidence.second = second;
+ await game.wait('same-page retained Briefcase opens bank', () => game.events.some(event => event.sequence > second.sequence &&
+ event.direction === 'framereceived' && event.opcode === '343c287f'));
+ assert.deepEqual(await server(), evidence.before);
+ await game.save(output + '/retried');
+ await page.reload();
+ await game.ready();
+ assert.deepEqual(await server(), evidence.before);
+ assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot]), [[1, 48], [2, 49]]);
+ assert.deepEqual(game.errors, []);
+ assert.equal(game.dropped, 0);
+ console.log('PASS: stale contained Use completes exactly, clears its empty cached row and permits same-page remote-bank Use');
+} 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(); }
+}