commit 11918d2eeb84fe7be698c1011fc4340ef4e994d1
parent 8557a0846bf64691a3ff36e998f2ae8386b82011
Author: anon <anon@example.com>
Date: Wed, 4 Nov 2026 13:32:04 +0000
Upload tokens and maps from carried backpacks
Diffstat:
10 files changed, 513 insertions(+), 11 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -2665,6 +2665,14 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
replies and SQL failure/ignored-update/commit rollback/retry. GPU WASM
verifies all six real icons; see [token redemption](docs/token-upload.md).
Acquisition and conditional completion XP remain separate P0 work below.
+- [x] [P1] Upload supported tokens and maps from carried backpacks. Check: exact
+ packed child consumption commits with faction counters/map banks, preserving
+ authored refusals, companions, empty bags and closed known handles. Public
+ regressions verify first-success durability, private replies, replay and
+ storage-failure rollback/retry. A short WASM fixture reproduces both failures
+ and verifies native token/map updates, source removal, remaining-item use and
+ page/cold recovery. This does not establish token acquisition. See
+ [contained uploads](docs/contained-uploads.md).
- [x] [P1] Verify original token-board wear using persistent faction counters.
All30 original boards now have public wear/remove/re-wear and cold-ownership
checks for every companion, strict token/title gates, faction differences and
diff --git a/docs/contained-uploads.md b/docs/contained-uploads.md
@@ -0,0 +1,49 @@
+# Token and map uploads from carried backpacks
+
+The shared Use dispatcher admits complete token and map contracts from page107,
+alongside its existing ordinary-inventory path. The upper16 source bits resolve
+the session's known Chest handle; the lower16 select its exact child. The bag
+must still be carried. A known handle remains usable after its window closes.
+Shared ownership, pending equipment and trade guards still apply.
+
+Both upload handlers preserve their original authored requirements and metadata
+rules. The token path still evaluates current level and faction at redemption;
+the map path still applies the documented map-bank reconstruction policy.
+They clone the affected child slice and contents map, consume one exact child,
+and commit metadata with that removal before acknowledging success. Companions
+and empty bags remain owned. Completion and DeleteItem retain the request's
+actual packed source; native stat updates remain private.
+
+Original KKR quantity callback1005e790 explicitly resolves the Chest handle,
+debits its child's Eat quantity and refreshes the Chest. Its source-bound REA
+record and the original DLL hash are retained with
+[contained nano learning](nano-learning.md#learning-from-carried-backpacks).
+The token and map authoritative effects already follow the native gates and
+resource descriptors documented in [tokens](token-upload.md) and
+[maps](map-uploads.md). This extends that recovered source contract; it does
+not establish original mission-token eligibility or new map arithmetic.
+
+Public-handler tests place items through ordinary backpack deposits, then use
+nonzero child slots with distinct physical bag IDs and session handles. All six
+token variants and representative Hit, SetFlag and reader-upgrade maps verify
+first-success durability, private updates, exact removal, open/closed handles,
+companions, empty bags, replay and cold ownership. Metadata, child-removal,
+ignored-write and COMMIT failures preserve independent live contents and
+durable state before a one-time retry. Wrong faction, counter overflow, known
+map upgrades and strict skill equality remain refusals.
+
+A controlled WASM baseline sends both real page107 commands and receives
+failure2 for each. The fixed14.52-second run redeems a level50 Omni token for3,
+uploads Arrow for MapOptions16, removes only those two rows and withdraws the
+remaining Monster Part through the same window. Native stats, feedback,
+screenshots, page replay and a cold reader retain the exact results with no
+page errors or dropped events. Supplies, faction, level and skills are fixture
+state, not earned progression or evidence of mission-token acquisition.
+Artifacts are under `local/backpack-uploads/`.
+
+The ordinary/source-focused Go run passes17 roots/201 results, including all55
+map entries and original token-level boundaries. The focused race run passes9
+roots/92 results across contained uploads, duplicate/lost replies and neighboring
+medical, crystal, Briefcase and stale-source paths. Maintained-package vet and
+Node syntax checks pass. The independent native audit verifies both packed
+requests/completions, four absolute stat updates and exactly two child removals.
diff --git a/docs/map-uploads.md b/docs/map-uploads.md
@@ -5,6 +5,8 @@ The server stores MapOptions (470), MapAreaPart1 (471) and MapAreaPart2 (472)
alongside the inventory. Uploading a supported map commits the updated banks
and removal of its one owned instance in the same SQLite transaction. A failed
transaction publishes neither change. FullCharacter restores all three banks.
+Supported uploads also consume exact carried-backpack children through that
+transaction; see [contained uploads](contained-uploads.md).
## Original contracts
diff --git a/docs/token-upload.md b/docs/token-upload.md
@@ -30,9 +30,10 @@ values are rejected; this transport/storage bound does not establish an original
server token cap. A failed or ignored write, deletion or commit retains both
counter and item for retry. Duplicate requests and lost replies cannot redeem
an instance twice. A full main inventory can redeem a token normally, freeing
-only its own slot. Bank and backpack use remain outside the admitted main-slot
-path. Significant inventory writes preserve both counters; routine poses still
-use periodic checkpoints.
+only its own slot. Carried-backpack sources now use the same contracts and
+transaction; see [contained uploads](contained-uploads.md). Bank sources remain
+outside the admitted path. Significant inventory writes preserve both counters;
+routine poses still use periodic checkpoints.
## Native evidence and delivery
diff --git a/server/backpack_uploads_test.go b/server/backpack_uploads_test.go
@@ -0,0 +1,244 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "database/sql"
+ "encoding/binary"
+ "fmt"
+ "maps"
+ "reflect"
+ "slices"
+ "testing"
+ "time"
+)
+
+type backpackUploadCommitConn struct {
+ combatTestConn
+ db *sql.DB
+ observed bool
+ tokens [2]uint32
+ flags [3]uint32
+ items int
+ err error
+}
+
+func (conn *backpackUploadCommitConn) Write(packet []byte) (int, error) {
+ if !conn.observed && binary.BigEndian.Uint32(packet[16:20]) == 0x52526858 && binary.BigEndian.Uint32(packet[29:33]) == 1 {
+ conn.observed = true
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ conn.err = conn.db.QueryRowContext(ctx, `SELECT clan_tokens, omni_tokens, map_options, map_area_1, map_area_2,
+ (SELECT count(*) FROM items WHERE id=1) FROM players WHERE id=1`).Scan(
+ &conn.tokens[0], &conn.tokens[1], &conn.flags[0], &conn.flags[1], &conn.flags[2], &conn.items)
+ }
+ return conn.combatTestConn.Write(packet)
+}
+
+func newBackpackUploadWorld(t *testing.T, template uint32, side uint16, companion bool) (*server, *combatTestConn, []byte) {
+ t.Helper()
+ world, output := newTokenUploadWorld(t, template, 50, side)
+ player, client := world.characters[1], world.clients[1]
+ player.stats.Navigation.MapNavigation = 700
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(player, 99228); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ if companion {
+ if granted, err := world.grantItem_locked(player, 42640); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ }
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 65, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleInventory(client, backpackMoveRequest(104, 64, 51017, 2, 111)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ player.inventory.Containers[2][0].Slot = 20
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ if companion {
+ if err := world.handleInventory(client, backpackMoveRequest(104, 66, 51017, 2, 111)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ request := backpackUseRequest(1, 1<<16|20, 10)[20:]
+ binary.BigEndian.PutUint32(request[40:44], 107)
+ output.packets = nil
+ return world, output, request
+}
+
+func TestBackpackUploadsCommitExactChildAndMetadataBeforeSuccess(t *testing.T) {
+ for _, fixture := range []struct {
+ template uint32
+ side uint16
+ tokens [2]uint32
+ flags [3]uint32
+ }{
+ {96349, 2, [2]uint32{10, 23}, [3]uint32{}}, {96350, 1, [2]uint32{12, 20}, [3]uint32{}},
+ {152932, 2, [2]uint32{10, 45}, [3]uint32{}}, {152933, 1, [2]uint32{35, 20}, [3]uint32{}},
+ {158421, 2, [2]uint32{10, 21}, [3]uint32{}}, {158422, 1, [2]uint32{11, 20}, [3]uint32{}},
+ {116694, 0, [2]uint32{10, 20}, [3]uint32{16, 0, 0}},
+ {116646, 0, [2]uint32{10, 20}, [3]uint32{0, 4, 0x40000000}},
+ {116696, 1, [2]uint32{10, 20}, [3]uint32{0, 0x1180000e, 0xc1000000}},
+ } {
+ for _, closed := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%d/closed%v", fixture.template, closed), func(t *testing.T) {
+ world, _, request := newBackpackUploadWorld(t, fixture.template, fixture.side, !closed)
+ player, client := world.characters[1], world.clients[1]
+ if closed {
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 65, 2)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ output := &backpackUploadCommitConn{db: world.db}
+ client.conn = output
+ observer := &combatTestConn{}
+ world.characters[2] = &character{id: 2, health: 100, playfield: player.playfield}
+ world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true}
+
+ err := world.handleOwnedItemUse(client, request)
+ world.handleOwnedItemUse(client, request)
+ cold := newTestInventoryServer(t)
+
+ if err != nil || !output.observed || output.err != nil || output.items != 0 || output.tokens != fixture.tokens || output.flags != fixture.flags ||
+ player.inventory.ClanTokens != fixture.tokens[0] || player.inventory.OmniTokens != fixture.tokens[1] || player.inventory.MapFlags != fixture.flags ||
+ !reflect.DeepEqual(player.inventory, cold.characters[1].inventory) || len(observer.packets) != 0 || client.backpacks[1] != (backpackHandle{2, !closed}) {
+ t.Fatal("contained upload did not commit exact private metadata/consumption before success", err, output.err)
+ }
+ if closed {
+ if player.inventory.Containers != nil || len(cold.items) != 1 || world.nextItem != 2 {
+ t.Fatal("last-child upload lost its empty bag or retained a consumed identity")
+ }
+ } else if !slices.Equal(player.inventory.Containers[2], []ownedItem{{ID: 3, Type: 51005, Template: 42640, Quality: 1, Count: 1}}) || len(cold.items) != 2 || world.nextItem != 3 {
+ t.Fatal("upload changed the retained companion or container")
+ }
+ ack := output.packets[0]
+ if binary.BigEndian.Uint32(ack[29:33]) != 1 || binary.BigEndian.Uint32(ack[33:37]) != 10 ||
+ binary.BigEndian.Uint32(ack[53:57]) != 107 || binary.BigEndian.Uint32(ack[57:61]) != 1<<16|20 {
+ t.Fatal("upload completion lost its reference or packed source")
+ }
+ removals := 0
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 112 {
+ removals++
+ if binary.BigEndian.Uint32(packet[33:37]) != 107 || binary.BigEndian.Uint32(packet[37:41]) != 1<<16|20 {
+ t.Fatal("upload cleared another source")
+ }
+ }
+ }
+ if removals != 1 {
+ t.Fatal("duplicate upload consumed or reported another instance")
+ }
+ })
+ }
+ }
+}
+
+func TestBackpackUploadsRollbackContentsAndMetadataThenRetry(t *testing.T) {
+ for _, template := range []uint32{96350, 116646} {
+ for _, companion := range []bool{false, true} {
+ for _, phase := range []string{"metadata", "child", "ignored metadata", "commit"} {
+ t.Run(fmt.Sprintf("%d/companion%v/%s", template, companion, phase), func(t *testing.T) {
+ world, output, request := newBackpackUploadWorld(t, template, 1, companion)
+ player := world.characters[1]
+ original := player.inventory
+ original.Items = slices.Clone(original.Items)
+ original.Containers = maps.Clone(original.Containers)
+ original.Containers[2] = slices.Clone(original.Containers[2])
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ statement := "CREATE TRIGGER reject_bag_upload BEFORE UPDATE ON players BEGIN SELECT RAISE(ABORT, 'metadata'); END"
+ switch phase {
+ case "child":
+ statement = "CREATE TRIGGER reject_bag_upload BEFORE DELETE ON item_locations WHEN OLD.item_id=1 BEGIN SELECT RAISE(ABORT, 'child'); END"
+ case "ignored metadata":
+ statement = "CREATE TRIGGER reject_bag_upload BEFORE UPDATE ON players BEGIN SELECT RAISE(IGNORE); END"
+ case "commit":
+ statement = "CREATE TABLE pending_bag_upload (id INTEGER REFERENCES items(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_bag_upload AFTER UPDATE ON players BEGIN INSERT INTO pending_bag_upload VALUES(999999); END"
+ }
+ if _, err := world.db.Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+
+ failed := world.handleOwnedItemUse(world.clients[1], request)
+ after, err := readTestItemStore(world)
+ if failed == nil || err != nil || !bytes.Equal(before, after) || !reflect.DeepEqual(player.inventory, original) || len(output.packets) != 0 {
+ t.Fatal("failed contained upload changed live/durable metadata, source slice/map or output", failed, err)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER reject_bag_upload"); err != nil {
+ t.Fatal(err)
+ }
+ binary.BigEndian.PutUint32(request[20:24], 11)
+ err = world.handleOwnedItemUse(world.clients[1], request)
+ cold := newTestInventoryServer(t)
+
+ if err != nil || !reflect.DeepEqual(player.inventory, cold.characters[1].inventory) || player.inventory.OmniTokens != 20 {
+ t.Fatal("contained upload retry lost its committed metadata or retained the source", err)
+ }
+ if _, exists := world.items[1]; exists {
+ t.Fatal("contained upload retry retained the consumed item")
+ }
+ if template == 96350 {
+ if player.inventory.ClanTokens != 12 || player.inventory.MapFlags != [3]uint32{} {
+ t.Fatal("token retry lost the exact faction increment")
+ }
+ } else if player.inventory.ClanTokens != 10 || player.inventory.MapFlags != [3]uint32{0, 4, 0x40000000} {
+ t.Fatal("map retry lost its exact banks or changed token counters")
+ }
+ if companion {
+ if len(cold.items) != 2 || len(player.inventory.Containers[2]) != 1 || player.inventory.Containers[2][0].ID != 3 {
+ t.Fatal("retry removed the companion")
+ }
+ } else if len(cold.items) != 1 || player.inventory.Containers != nil {
+ t.Fatal("retry did not retain an empty carried bag")
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestBackpackUploadsKeepAuthoredRefusals(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ template uint32
+ }{{"wrong faction", 96350}, {"overflow", 152932}, {"known upgrade", 116694}, {"skill equality", 116694}} {
+ t.Run(scenario.name, func(t *testing.T) {
+ world, output, request := newBackpackUploadWorld(t, scenario.template, 2, true)
+ player := world.characters[1]
+ switch scenario.name {
+ case "overflow":
+ player.inventory.OmniTokens = 2147483647
+ case "known upgrade":
+ player.inventory.MapFlags[0] = 16
+ case "skill equality":
+ player.stats.Navigation.MapNavigation = 22
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ err = world.handleOwnedItemUse(world.clients[1], request)
+ after, readErr := readTestItemStore(world)
+
+ if err != nil || readErr != nil || !bytes.Equal(before, after) || len(player.inventory.Containers[2]) != 2 ||
+ len(output.packets) != 1 || binary.BigEndian.Uint32(output.packets[0][29:33]) != 2 {
+ t.Fatal("contained upload bypassed a supported refusal or changed ownership", err, readErr)
+ }
+ })
+ }
+}
diff --git a/server/backpacks.go b/server/backpacks.go
@@ -89,6 +89,12 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error
}
for index, item := range player.inventory.Containers[bag] {
if item.Slot == slot&65535 {
+ if stat, supported := item.tokenUpload(); supported {
+ return server.uploadToken_locked(client, index, body, stat)
+ }
+ if flags, supported := item.mapUpload(); supported {
+ return server.uploadMap_locked(client, index, body, flags)
+ }
if kit, supported := item.resourceKit(); supported {
return server.useResourceKit_locked(client, index, body, kit)
}
diff --git a/server/browser_backpack_uploads_test.go b/server/browser_backpack_uploads_test.go
@@ -0,0 +1,73 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserBackpackUploads(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for carried-backpack token/map uploads")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/backpack-uploads", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.level, player.appearance = 50, player.appearance&^(3<<9)|2<<9
+ player.stats.Navigation.MapNavigation = 30
+ player.playfield, player.position = 1183, [3]float32{193.79826, 5.01, 136.83983}
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("backpack-uploads")))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ // Controlled supplies and level isolate Use; no mission token acquisition is claimed.
+ inventory := playerInventory{LastID: 4, Items: []ownedItem{{ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}}, Containers: map[uint32][]ownedItem{}}
+ for index, template := range []uint32{96349, 116694, 42640} {
+ definition := gamedata.ItemTemplates[template]
+ inventory.Containers[1] = append(inventory.Containers[1], ownedItem{ID: uint32(index + 2), Type: definition.HeaderWords[0],
+ Template: template, Quality: *definition.Quality, Slot: uint32(index), 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)
+ })
+ 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_backpack_uploads.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)
+ if !reflect.DeepEqual(player.inventory, cold.characters[1].inventory) || player.inventory.OmniTokens != 3 || player.inventory.ClanTokens != 0 ||
+ player.inventory.MapFlags != [3]uint32{16, 0, 0} || len(player.inventory.Containers) != 0 || len(player.inventory.Items) != 2 ||
+ player.inventory.Items[0].ID != 1 || player.inventory.Items[1].ID != 4 || len(cold.items) != 2 || world.nextItem != 4 {
+ t.Fatal("contained uploads did not retain exact metadata, consumed children and companion through cold recovery")
+ }
+}
diff --git a/server/map_upload.go b/server/map_upload.go
@@ -3,6 +3,7 @@ package main
import (
"ao/server/gamedata"
"encoding/binary"
+ "maps"
"slices"
)
@@ -57,8 +58,14 @@ func (item ownedItem) mapUpload() ([3]uint32, bool) {
func (server *server) uploadMap_locked(client *worldClient, index int, body []byte, flags [3]uint32) error {
player := server.characters[client.id]
- item := player.inventory.Items[index]
- accepted := item.Slot >= 64 && player.templateUseRequirementsMet(gamedata.ItemTemplates[item.Template])
+ page, source := binary.BigEndian.Uint32(body[40:44]), binary.BigEndian.Uint32(body[44:48])
+ items, bag := player.inventory.Items, uint32(0)
+ if page == 107 {
+ bag = client.backpacks[source>>16].id
+ items = player.inventory.Containers[bag]
+ }
+ item := items[index]
+ accepted := (bag != 0 || item.Slot >= 64) && player.templateUseRequirementsMet(gamedata.ItemTemplates[item.Template])
if accepted {
// Knowledge and consumption share the inventory transaction. OR preserves
// existing regions, including authored maps which allow re-upload.
@@ -66,7 +73,20 @@ func (server *server) uploadMap_locked(client *worldClient, index int, body []by
for index, mask := range flags {
inventory.MapFlags[index] |= mask
}
- inventory.Items = slices.Delete(slices.Clone(inventory.Items), index, index+1)
+ remaining := slices.Delete(slices.Clone(items), index, index+1)
+ if bag == 0 {
+ inventory.Items = remaining
+ } else {
+ inventory.Containers = maps.Clone(inventory.Containers)
+ if len(remaining) == 0 {
+ delete(inventory.Containers, bag)
+ } else {
+ inventory.Containers[bag] = remaining
+ }
+ if len(inventory.Containers) == 0 {
+ inventory.Containers = nil
+ }
+ }
if err := server.saveInventory_locked(player, inventory); err != nil {
return err
}
@@ -90,7 +110,7 @@ func (server *server) uploadMap_locked(client *worldClient, index int, body []by
}
}
var removal []byte
- for _, value := range []uint32{112, 104, item.Slot, item.Template, item.Template} {
+ for _, value := range []uint32{112, page, source, item.Template, item.Template} {
removal = binary.BigEndian.AppendUint32(removal, value)
}
return client.send(n3Packet(0x5e477770, 50000, client.id, removal))
diff --git a/server/token_upload.go b/server/token_upload.go
@@ -4,6 +4,7 @@ import (
"ao/server/gamedata"
"encoding/binary"
"fmt"
+ "maps"
"slices"
)
@@ -67,9 +68,15 @@ func (item ownedItem) tokenUpload() (uint32, bool) {
func (server *server) uploadToken_locked(client *worldClient, index int, body []byte, stat uint32) error {
player := server.characters[client.id]
- item := player.inventory.Items[index]
+ page, source := binary.BigEndian.Uint32(body[40:44]), binary.BigEndian.Uint32(body[44:48])
+ items, bag := player.inventory.Items, uint32(0)
+ if page == 107 {
+ bag = client.backpacks[source>>16].id
+ items = player.inventory.Containers[bag]
+ }
+ item := items[index]
definition := gamedata.ItemTemplates[item.Template]
- accepted := item.Slot >= 64 && player.templateUseRequirementsMet(definition)
+ accepted := (bag != 0 || item.Slot >= 64) && player.templateUseRequirementsMet(definition)
value, _ := player.effectiveStat(stat)
if accepted {
// Evaluate each authored increment at redemption time, not mission acceptance.
@@ -100,7 +107,20 @@ func (server *server) uploadToken_locked(client *worldClient, index int, body []
} else {
inventory.OmniTokens = uint32(value)
}
- inventory.Items = slices.Delete(slices.Clone(inventory.Items), index, index+1)
+ remaining := slices.Delete(slices.Clone(items), index, index+1)
+ if bag == 0 {
+ inventory.Items = remaining
+ } else {
+ inventory.Containers = maps.Clone(inventory.Containers)
+ if len(remaining) == 0 {
+ delete(inventory.Containers, bag)
+ } else {
+ inventory.Containers[bag] = remaining
+ }
+ if len(inventory.Containers) == 0 {
+ inventory.Containers = nil
+ }
+ }
if err := server.saveInventory_locked(player, inventory); err != nil {
return err
}
@@ -120,7 +140,7 @@ func (server *server) uploadToken_locked(client *worldClient, index int, body []
if err := client.send(n3Packet(0x2b333d6e, 50000, client.id, update)); err != nil {
return err
}
- if err := client.send(characterActionPacket(client.id, [5]uint32{112, 104, item.Slot, item.Template, item.Template})); err != nil {
+ if err := client.send(characterActionPacket(client.id, [5]uint32{112, page, source, item.Template, item.Template})); err != nil {
return err
}
text := fmt.Sprintf("Side tokens collected: %d.", value)
diff --git a/tools/client/test_backpack_uploads.mjs b/tools/client/test_backpack_uploads.mjs
@@ -0,0 +1,79 @@
+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: 'backpack-uploads', 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 click = async (source, button = 'left') => {
+ assert(source, 'exact source cell is usable');
+ await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2, button);
+ };
+ const upload = async slot => {
+ const sequence = game.sequence;
+ await click(cell(107, 65536 | slot), 'right');
+ await game.wait('actual contained upload Use', () => 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');
+ const reference = Buffer.from(request.hex, 'hex').readUInt32BE(33);
+ await game.wait('exact upload completion', () => game.events.some(event => event.sequence > sequence &&
+ event.direction === 'framereceived' && event.opcode === '52526858' && Buffer.from(event.hex, 'hex').readUInt32BE(33) === reference));
+ const reply = game.events.find(event => event.sequence > sequence && event.direction === 'framereceived' &&
+ event.opcode === '52526858' && Buffer.from(event.hex, 'hex').readUInt32BE(33) === reference);
+ return {reference, result: Buffer.from(reply.hex, 'hex').readUInt32BE(29)};
+ };
+ await game.key('KeyI');
+ await click(cell(104, 48), 'right');
+ await game.wait('token, map and companion visible', () => cell(107, 65536) && cell(107, 65537) && cell(107, 65538));
+ evidence.before = await server();
+ evidence.token = await upload(0);
+ evidence.map = await upload(1);
+ await game.save(output + '/upload-results');
+ assert.equal(evidence.token.result, 1);
+ assert.equal(evidence.map.result, 1);
+ await game.wait('both exact uploaded rows disappear', () => !cell(107, 65536) && !cell(107, 65537) && cell(107, 65538));
+ await game.wait('native token count and map option update', () => game.local().stats[75] === 3 && game.local().stats[470] === 16);
+ evidence.uploaded = await server();
+ assert.equal(evidence.uploaded.OmniTokens, 3);
+ assert.equal(evidence.uploaded.ClanTokens, 0);
+ assert.deepEqual(evidence.uploaded.MapFlags, [16, 0, 0]);
+ assert.deepEqual(evidence.uploaded.Containers[1].map(item => item.ID), [4]);
+
+ // The remaining item stays usable without closing or refreshing the bag.
+ await click(cell(107, 65538));
+ await game.wait('companion picked', state => state.dragged[0] === 107 && state.dragged[1] === 65538);
+ await click(game.state.grids.find(grid => grid.totalCells === 30).cells.find(cell => cell.identity[0] === 0));
+ await game.wait('exact companion withdraws', state => game.local(state).inventory.some(item => item.id === 4 && item.slot === 49));
+ evidence.after = await server();
+ await game.save(output + '/verified');
+ await page.reload();
+ await game.ready();
+ assert.deepEqual(await server(), evidence.after);
+ assert.equal(game.local().stats[75], 3);
+ assert.equal(game.local().stats[470], 16);
+ assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot]), [[1, 48], [4, 49]]);
+ assert.deepEqual(game.errors, []);
+ assert.equal(game.dropped, 0);
+ console.log('PASS: contained token/map uploads consume exact children with persistent metadata; companion and page/cold ownership remain exact');
+} 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(); }
+}