commit 8557a0846bf64691a3ff36e998f2ae8386b82011
parent e647f1504c23bc7526be278dd16b169542cd97b2
Author: anon <anon@example.com>
Date: Wed, 4 Nov 2026 13:18:47 +0000
Use medical kits from carried backpacks
Diffstat:
7 files changed, 556 insertions(+), 10 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -4704,6 +4704,14 @@ and server restarts. Turn every reproduced bug into a focused regression test.
targets, first-packet durability, last charges, resource caps, movement cadence,
ignored/failed writes, failed COMMIT, retry and output failure/restart replay.
See `server/consumable_outcome_test.go`; the broader consumable audit remains.
+- [x] [P1] Use admitted medical kits from carried backpacks. Check: exact packed
+ child debit and last-charge removal commit with the correct patient's resources
+ and actor lock; retain authored gates, companions and empty bags. Public-handler
+ regressions cover six families, self/other, open/closed handles, storage failures
+ and retry. A short two-client WASM fixture verifies First Aid, teammate treatment,
+ same-window companion use and page/cold recovery. This is controlled fixture
+ evidence; the broader consumable audit remains open. See
+ [contained medical use](docs/medical-consumables.md#use-from-carried-backpacks).
- [ ] [P1] Audit nano learning and casting. Cover unmet requirements, duplicates,
missing resources, interruption/cancellation, invalid or changing targets,
recharge boundaries and interaction with queued weapon results.
diff --git a/docs/medical-consumables.md b/docs/medical-consumables.md
@@ -83,8 +83,52 @@ actors must be out of combat and the patient must sit. The patient's131 lock
is distinct from Treatment124 and the user's FirstAid123.
Emergency laboratories add53051; Purge kits add53177 and
different lock semantics. These functions must be implemented as complete
-contracts before those items are admitted. General use from inside backpacks
-and other quality families remain open.
+contracts before those items are admitted. Other quality families remain open.
+
+## Use from carried backpacks
+
+Admitted medical kits use the same patient requirements, resource effects and
+actor-owned locks from a carried backpack. Page107 resolves the session Chest
+handle and exact child slot; a known handle remains usable after its window
+closes. Source ownership, pending equipment and trade guards remain in the
+shared Use dispatcher.
+
+The handler clones the source slice and affected container map before debiting
+one charge. The charge, patient resources and proper actor's lock commit in one
+transaction. Last-charge consumption removes only that child, including the
+last child of an otherwise empty carried bag. GenericCmd completion,
+UseTemplateAction and DeleteItem retain the actual page107/packed position.
+
+Original KKR quantity callback1005e790 resolves page107 through its Chest and
+debits that child's quantity. UseTemplateAction1005e980 executes action3 on the
+supplied actor through the template. These source-independent effect and
+contained-debit paths are retained in the source-bound REA evidence linked in
+[carried nano learning](nano-learning.md#learning-from-carried-backpacks), using
+the same original DLL hash above. They establish the native source contract;
+they are not an original-server packet recording or a new balance rule.
+
+Public-handler regressions cover six medical families, self/teammate patients,
+partial/last charges, nonzero child slots and open/closed handles. They check
+resources and charge durability at the first success packet, exact source
+replies, authored requirement refusals, empty-bag handling and cold ownership.
+Injected charge, lock, health, nano and COMMIT failures preserve independent
+live contents and durable state with no output, followed by a one-time retry.
+
+A controlled two-client WASM fixture reproduces the former failure2 response to
+a real contained First Aid right-click. The fixed path heals the owner and
+consumes one of two charges; a last-charge startup laboratory then restores
+exactly 15 health and 15 nano to a seated teammate. Both clients observe the
+patient's health, only the correct actors receive their locks, the laboratory
+row disappears, and the companion withdraws through the same bag window.
+Page replay and cold loading preserve resources, charges, identities and lock
+deadlines. This uses fixture supplies and team state, not earned progression.
+Artifacts are under `local/backpack-medical/`.
+
+The focused Go run passes24 roots/189 results; the expanded race run passes34
+roots/246 results, including ordinary medical use, contained crystals,
+Briefcases and stale-child clearing. Vet on the maintained packages and Node
+syntax checks pass. The final native fixture completes in24.51 seconds with
+no page errors or dropped trace events.
## Verification
diff --git a/server/backpack_medical_test.go b/server/backpack_medical_test.go
@@ -0,0 +1,251 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "maps"
+ "reflect"
+ "slices"
+ "testing"
+ "time"
+)
+
+func newBackpackMedicalWorld(t *testing.T, template uint32, other bool, count uint16, closed bool) (*server, *character, *combatTestConn, []byte) {
+ t.Helper()
+ world, target, output := newConsumableOutcomeWorld(t, template, other)
+ player, client := world.characters[1], world.clients[1]
+ player.stats.NanoAiding.FirstAid, player.stats.NanoAiding.Treatment, player.stats.NanoAiding.TimeAndSpace = 10, 10, 10
+ target.health, target.nano, target.sitting = 1, 1, true
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.saveUser_locked(target); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec("UPDATE characters SET health=1, nano=1 WHERE id=?", target.id); err != nil {
+ t.Fatal(err)
+ }
+ target.savedVitals = target.vitals()
+ player.inventory.Items[0].Count = count
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ for _, template := range []uint32{99228, 42640} {
+ if granted, err := world.grantItem_locked(player, template); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ }
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 65, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ for _, slot := range []uint32{64, 66} {
+ if err := world.handleInventory(client, backpackMoveRequest(104, slot, 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 closed {
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 65, 2)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ request := backpackUseRequest(1, 1<<16|20, 10)[20:]
+ binary.BigEndian.PutUint32(request[40:44], 107)
+ output.packets = nil
+ if other {
+ world.clients[target.id].conn.(*combatTestConn).packets = nil
+ }
+ return world, target, output, request
+}
+
+func TestBackpackMedicalCommitsExactSourceAndPatient(t *testing.T) {
+ for _, kit := range []struct {
+ template, healthLow, healthHigh, nanoLow, nanoHigh, lock uint32
+ }{
+ {23314, 10, 12, 0, 0, 123}, {85366, 0, 0, 10, 12, 123},
+ {116629, 5, 7, 5, 7, 123}, {25812, 30, 30, 0, 0, 124},
+ {25820, 0, 0, 30, 30, 131}, {116628, 15, 15, 15, 15, 124},
+ } {
+ for _, other := range []bool{false, true} {
+ for _, count := range []uint16{1, 3} {
+ t.Run(fmt.Sprintf("%d/other%v/count%d", kit.template, other, count), func(t *testing.T) {
+ world, target, _, request := newBackpackMedicalWorld(t, kit.template, other, count, count == 3)
+ player, client := world.characters[1], world.clients[1]
+ output := &consumableCommitConn{db: world.db, target: target.id}
+ client.conn = output
+
+ err := world.handleOwnedItemUse(client, request)
+ cold := newTestInventoryServer(t)
+
+ if err != nil || !output.observed || output.err != nil || output.count != count-1 ||
+ output.health != target.health || output.nano != target.nano ||
+ target.health < 1+kit.healthLow || target.health > 1+kit.healthHigh || target.nano < 1+kit.nanoLow || target.nano > 1+kit.nanoHigh ||
+ !reflect.DeepEqual(player.inventory, cold.characters[1].inventory) || target.vitals() != cold.characters[target.id].vitals() ||
+ target.savedVitals != target.vitals() || client.backpacks[1] != (backpackHandle{2, count != 3}) {
+ t.Fatal("contained medical source/resources were not durable before success", err, output.err)
+ }
+ contents := player.inventory.Containers[2]
+ if count == 1 {
+ if len(contents) != 1 || contents[0].ID != 3 || len(cold.items) != 2 {
+ t.Fatal("last charge removed the wrong child or its companion")
+ }
+ } else if len(contents) != 2 || contents[0].ID != 1 || contents[0].Slot != 20 || contents[0].Count != 2 || contents[1].ID != 3 || len(cold.items) != 3 {
+ t.Fatal("partial charge changed its location, bag or companion")
+ }
+ lockRecipient := target
+ if kit.lock == 123 {
+ lockRecipient = player
+ }
+ if lockRecipient.skillLocks[kit.lock].IsZero() || !cold.characters[lockRecipient.id].skillLocks[kit.lock].Equal(lockRecipient.skillLocks[kit.lock]) ||
+ other && (player != lockRecipient && len(player.skillLocks) != 0 || target != lockRecipient && len(target.skillLocks) != 0) {
+ t.Fatal("contained source changed the authored lock recipient")
+ }
+ 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("completion lost its exact reference or packed source")
+ }
+ var actions, removals int
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x35505644 {
+ actions++
+ if binary.BigEndian.Uint32(packet[49:53]) != 107 || binary.BigEndian.Uint32(packet[53:57]) != 1<<16|20 || binary.BigEndian.Uint32(packet[61:65]) != target.id {
+ t.Fatal("medical graphics used the wrong source or patient")
+ }
+ }
+ 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("last-charge removal cleared another source")
+ }
+ }
+ }
+ if actions != 1 || count == 1 && removals != 1 || count != 1 && removals != 0 {
+ t.Fatal("contained use repeated its effect or removed a partial charge")
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestBackpackMedicalLastChildLeavesAnEmptyCarriedBag(t *testing.T) {
+ world, target, output, request := newBackpackMedicalWorld(t, 116628, false, 1, false)
+ player, client := world.characters[1], world.clients[1]
+ if err := world.handleInventory(client, backpackMoveRequest(107, 1<<16|1, 50000, 1, 64)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+
+ err := world.handleOwnedItemUse(client, request)
+ cold := newTestInventoryServer(t)
+
+ if err != nil || target.health != 16 || target.nano != 16 || player.inventory.Containers != nil ||
+ cold.characters[1].inventory.Containers != nil || !reflect.DeepEqual(player.inventory, cold.characters[1].inventory) ||
+ len(cold.items) != 2 || len(player.inventory.Items) != 2 || client.backpacks[1] != (backpackHandle{2, true}) {
+ t.Fatal("last medical child removed its bag, withdrawn companion or empty-container state", err)
+ }
+}
+
+func TestBackpackMedicalFailedCommitPreservesChildrenAndRetries(t *testing.T) {
+ for _, count := range []uint16{1, 3} {
+ for _, phase := range []string{"charge", "lock", "health", "nano", "commit"} {
+ t.Run(fmt.Sprintf("%d/%s", count, phase), func(t *testing.T) {
+ world, target, output, request := newBackpackMedicalWorld(t, 116628, true, count, false)
+ 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_kit BEFORE UPDATE ON items WHEN NEW.id=1 BEGIN SELECT RAISE(ABORT, 'charge'); END"
+ switch phase {
+ case "charge":
+ if count == 1 {
+ statement = "CREATE TRIGGER reject_bag_kit BEFORE DELETE ON item_locations WHEN OLD.item_id=1 BEGIN SELECT RAISE(ABORT, 'last charge'); END"
+ }
+ case "lock":
+ statement = "CREATE TRIGGER reject_bag_kit BEFORE INSERT ON skill_locks BEGIN SELECT RAISE(ABORT, 'lock'); END"
+ case "health":
+ statement = "CREATE TRIGGER reject_bag_kit BEFORE UPDATE OF health ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(ABORT, 'health'); END"
+ case "nano":
+ statement = "CREATE TRIGGER reject_bag_kit BEFORE UPDATE OF nano ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(ABORT, 'nano'); END"
+ case "commit":
+ statement = "CREATE TABLE pending_bag_kit (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_bag_kit AFTER UPDATE OF health ON characters WHEN NEW.id=2 BEGIN INSERT INTO pending_bag_kit 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)
+ rolledBack := newTestInventoryServer(t)
+ if failed == nil || err != nil || !bytes.Equal(before, after) || !reflect.DeepEqual(player.inventory, original) ||
+ target.health != 1 || target.nano != 1 || rolledBack.characters[2].health != 1 || rolledBack.characters[2].nano != 1 ||
+ len(player.skillLocks) != 0 || len(target.skillLocks) != 0 || len(rolledBack.characters[2].skillLocks) != 0 ||
+ len(output.packets) != 0 || len(world.clients[2].conn.(*combatTestConn).packets) != 0 {
+ t.Fatal("failed contained medical commit mutated live/durable source, resources, locks or output", failed, err)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER reject_bag_kit"); 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 || target.health != 16 || target.nano != 16 || cold.characters[2].health != 16 || cold.characters[2].nano != 16 ||
+ cold.characters[2].skillLocks[124].IsZero() || !reflect.DeepEqual(player.inventory, cold.characters[1].inventory) ||
+ player.inventory.Containers[2][len(player.inventory.Containers[2])-1].ID != 3 {
+ t.Fatal("contained medical retry lost the exact child, companion or atomic patient outcome", err)
+ }
+ if count == 1 {
+ if len(cold.items) != 2 || len(player.inventory.Containers[2]) != 1 {
+ t.Fatal("retry retained its last charge")
+ }
+ } else if len(cold.items) != 3 || player.inventory.Containers[2][0].Count != 2 {
+ t.Fatal("retry consumed more than one charge")
+ }
+ })
+ }
+ }
+}
+
+func TestBackpackMedicalRetainsPatientRequirements(t *testing.T) {
+ for _, scenario := range []string{"standing", "skill equality", "locked", "far", "no target"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, target, output, request := newBackpackMedicalWorld(t, 116628, true, 3, false)
+ player, client := world.characters[1], world.clients[1]
+ switch scenario {
+ case "standing":
+ target.sitting = false
+ case "skill equality":
+ player.stats.NanoAiding.Treatment = 3
+ case "locked":
+ target.setSkillLock_locked(124, time.Now().Add(time.Minute))
+ case "far":
+ target.position[0] = player.position[0] + 20
+ case "no target":
+ client.selectedTarget = [2]uint32{}
+ }
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ err = world.handleOwnedItemUse(client, request)
+ after, readErr := readTestItemStore(world)
+
+ if err != nil || readErr != nil || !bytes.Equal(before, after) || target.health != 1 || target.nano != 1 ||
+ player.inventory.Containers[2][0].Count != 3 || len(output.packets) != 1 || binary.BigEndian.Uint32(output.packets[0][29:33]) != 2 {
+ t.Fatal("contained source bypassed an authored medical gate", err, readErr)
+ }
+ })
+ }
+}
diff --git a/server/backpacks.go b/server/backpacks.go
@@ -89,6 +89,9 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error
}
for index, item := range player.inventory.Containers[bag] {
if item.Slot == slot&65535 {
+ if kit, supported := item.resourceKit(); supported {
+ return server.useResourceKit_locked(client, index, body, kit)
+ }
if item.Template == 43330 || nanoCrystalProgram(item.Template) != 0 {
return server.learnNano_locked(client, index, body)
}
diff --git a/server/browser_backpack_medical_test.go b/server/browser_backpack_medical_test.go
@@ -0,0 +1,111 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserBackpackMedical(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for carried-backpack medical use")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/backpack-medical", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ players := []*character{}
+ for index := range 2 {
+ player := world.newCharacter()
+ player.name, player.level = fmt.Sprint("Bag medical ", index), 10
+ player.playfield, player.position = 1183, [3]float32{193.79826, 5.01, 136.83983 + float32(index*2)}
+ player.stats.Body.BodyDevelopment = 55
+ player.stats.NanoAiding.FirstAid, player.stats.NanoAiding.Treatment = 10, 10
+ player.health, player.nano = 20, 1
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("backpack-medical-", index))))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ world.clients[player.id] = &worldClient{id: player.id, conn: &combatTestConn{}, target: true, ready: true}
+ players = append(players, player)
+ }
+ // Controlled team and supplies, not earned progression; no regeneration runs.
+ formTestTeam(t, world, 1, 2)
+ delete(world.clients, 1)
+ delete(world.clients, 2)
+ inventory := playerInventory{LastID: 4, Items: []ownedItem{{ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}},
+ Containers: map[uint32][]ownedItem{1: {
+ {ID: 2, Type: 51005, Template: 23314, Quality: 1, Slot: 0, Count: 2},
+ {ID: 3, Type: 51005, Template: 116628, Quality: 1, Slot: 1, Count: 1},
+ {ID: 4, Type: 51005, Template: 42640, Quality: 1, Slot: 2, Count: 1}}}}
+ if err := world.saveInventory_locked(players[0], 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()
+ state := []map[string]any{}
+ for _, player := range players {
+ state = append(state, map[string]any{"health": player.health, "nano": player.nano, "sitting": player.sitting,
+ "locks": player.skillLocks, "inventory": player.inventory})
+ }
+ json.NewEncoder(w).Encode(state)
+ })
+ 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_medical.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)
+ for _, player := range players {
+ restored := cold.characters[player.id]
+ if player.id == 1 && !reflect.DeepEqual(player.inventory, restored.inventory) || player.health != restored.health || player.nano != restored.nano {
+ t.Fatalf("player%d medical resources or source ownership changed across cold recovery: live=%+v cold=%+v", player.id, player.inventory, restored.inventory)
+ }
+ for skill, deadline := range player.skillLocks {
+ var saved time.Time
+ if err := world.db.QueryRow("SELECT locked_until FROM skill_locks WHERE player_id=? AND skill=?", player.id, skill).Scan(&saved); err != nil {
+ t.Fatal(err)
+ }
+ if !saved.Equal(deadline) {
+ t.Fatal("contained medical lock deadline changed across cold recovery")
+ }
+ // A short patient lock may expire during two page reloads and cold loading.
+ if restored.skillLocks[skill].IsZero() {
+ if time.Now().Before(deadline) {
+ t.Fatal("active contained medical lock was not restored")
+ }
+ } else if !restored.skillLocks[skill].Equal(deadline) {
+ t.Fatal("restored contained medical lock has another deadline")
+ }
+ }
+ }
+ if len(cold.items) != 3 || world.nextItem != 4 || len(cold.characters[2].inventory.Items) != 0 || len(players[0].inventory.Containers[1]) != 1 ||
+ players[0].inventory.Containers[1][0].ID != 2 || players[0].inventory.Containers[1][0].Count != 1 ||
+ players[0].health < 30 || players[0].health > 32 || players[1].health != 35 || players[1].nano != 16 ||
+ players[0].skillLocks[123].IsZero() || !players[0].skillLocks[124].IsZero() ||
+ players[1].skillLocks[124].IsZero() || !players[1].skillLocks[123].IsZero() {
+ t.Fatal("contained first aid/treatment lost an exact charge, companion, resource or lock recipient")
+ }
+}
diff --git a/server/resource_kit.go b/server/resource_kit.go
@@ -3,6 +3,7 @@ package main
import (
"ao/server/gamedata"
"encoding/binary"
+ "maps"
"math/rand/v2"
"slices"
"time"
@@ -156,14 +157,20 @@ func (server *server) itemUseRequirementsMet_locked(player, target *character, i
func (server *server) useResourceKit_locked(client *worldClient, index int, body []byte, kit resourceKit) 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]
target := server.characters[client.selectedTarget[1]]
lockRecipient := target
if kit.lockSkill == 123 {
lockRecipient = player
}
now := time.Now()
- accepted := item.Slot >= 64 && item.Slot < 94 && client.selectedTarget[0] == 50000 &&
+ accepted := (bag != 0 || item.Slot >= 64 && item.Slot < 94) && client.selectedTarget[0] == 50000 &&
target != nil && !target.npc && target.health > 0 && target.playfield == player.playfield &&
server.clients[target.id] != nil && server.clients[target.id].ready && !server.clients[target.id].loading
if accepted {
@@ -178,10 +185,23 @@ func (server *server) useResourceKit_locked(client *worldClient, index int, body
if accepted {
// Commit both resources, charge and the correct actor's cooldown together.
inventory := player.inventory
- inventory.Items = slices.Clone(inventory.Items)
- inventory.Items[index].Count--
- if inventory.Items[index].Count == 0 {
- inventory.Items = slices.Delete(inventory.Items, index, index+1)
+ remaining := slices.Clone(items)
+ remaining[index].Count--
+ if remaining[index].Count == 0 {
+ remaining = slices.Delete(remaining, 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
+ }
}
deadline := now.Add(time.Duration(lockRecipient.skillLockSeconds(kit.lockSeconds)) * time.Second)
vitals := target.vitals()
@@ -210,7 +230,7 @@ func (server *server) useResourceKit_locked(client *worldClient, index int, body
// The ACK debits one native charge; TemplateAction runs the authored graphics.
var action []byte
low, high := item.templateIDs()
- for _, value := range []uint32{low, high, item.Quality, 1, 3, 104, item.Slot, 50000, target.id} {
+ for _, value := range []uint32{low, high, item.Quality, 1, 3, page, source, 50000, target.id} {
action = binary.BigEndian.AppendUint32(action, value)
}
updates := make(map[*worldClient][][]byte)
@@ -225,7 +245,7 @@ func (server *server) useResourceKit_locked(client *worldClient, index int, body
}
if item.Count == 1 {
var removal []byte
- for _, value := range []uint32{112, 104, item.Slot, low, high} {
+ for _, value := range []uint32{112, page, source, low, high} {
removal = binary.BigEndian.AppendUint32(removal, value)
}
updates[client] = append(updates[client], n3Packet(0x5e477770, 50000, client.id, removal))
diff --git a/tools/client/test_backpack_medical.mjs b/tools/client/test_backpack_medical.mjs
@@ -0,0 +1,109 @@
+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']});
+const games = [], evidence = {};
+try {
+ for (let index = 0; index < 2; index++) {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'backpack-medical-' + index, url}]);
+ const page = await context.newPage();
+ const game = await GameTest.attach(page);
+ games.push(game);
+ await page.goto(url);
+ await game.ready();
+ }
+ const [owner, patient] = games;
+ const server = async () => (await owner.page.request.get(url + '/test-state')).json();
+ const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id);
+ const cell = (page, slot) => owner.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 owner.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2, button);
+ };
+ const use = async slot => {
+ const sequence = owner.sequence;
+ await click(cell(107, 65536 | slot), 'right');
+ await owner.wait('actual contained medical Use', () => owner.events.some(event => event.sequence > sequence &&
+ event.direction === 'framesent' && event.opcode === '52526858' && Buffer.from(event.hex, 'hex').readUInt32BE(53) === 107));
+ const request = owner.events.find(event => event.sequence > sequence && event.direction === 'framesent' && event.opcode === '52526858');
+ const reference = Buffer.from(request.hex, 'hex').readUInt32BE(33);
+ await owner.wait('exact medical completion', () => owner.events.some(event => event.sequence > sequence &&
+ event.direction === 'framereceived' && event.opcode === '52526858' && Buffer.from(event.hex, 'hex').readUInt32BE(33) === reference));
+ const reply = owner.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 Promise.all(games.map(game => game.wait('both patients present', () => actor(game, 1) && actor(game, 2))));
+ await owner.key('F1');
+ await owner.key('KeyI');
+ await click(cell(104, 48), 'right');
+ await owner.wait('all three contained items visible', () => cell(107, 65536) && cell(107, 65537) && cell(107, 65538));
+ evidence.before = await server();
+ evidence.firstAid = await use(0);
+ await owner.save(output + '/first-aid-result');
+ assert.equal(evidence.firstAid.result, 1);
+ evidence.healed = await server();
+ assert(evidence.healed[0].health >= 30 && evidence.healed[0].health <= 32);
+ assert.equal(evidence.healed[0].inventory.Containers[1][0].Count, 1);
+ assert.deepEqual(evidence.healed[1], evidence.before[1]);
+ await Promise.all(games.map(game => game.wait('both see the healed owner', () => actor(game, 1).stats[27] === evidence.healed[0].health)));
+
+ // The teammate sits through real input, then receives the last laboratory charge.
+ await patient.key('KeyX');
+ await patient.wait('native patient seated', state => patient.local(state).stats[430] === 2);
+ assert((await server())[1].sitting, 'patient seated on server');
+ await owner.click(...await owner.pick(50000, 2));
+ await owner.wait('teammate selected', state => state.selected[0] === 50000 && state.selected[1] === 2);
+ evidence.treatment = await use(1);
+ assert.equal(evidence.treatment.result, 1);
+ await owner.wait('last laboratory charge disappears', () => !cell(107, 65537) && cell(107, 65536) && cell(107, 65538));
+ evidence.treated = await server();
+ assert.equal(evidence.treated[1].health, 35);
+ assert.equal(evidence.treated[1].nano, 16);
+ assert.equal(evidence.treated[0].health, evidence.healed[0].health);
+ assert.equal(evidence.treated[0].nano, 1);
+ assert.deepEqual(evidence.treated[0].locks, evidence.healed[0].locks);
+ assert(evidence.treated[1].locks[124]);
+ assert(!evidence.treated[1].locks[123]);
+ await Promise.all(games.map(game => game.wait('both see treated health', () => actor(game, 2).stats[27] === 35)));
+ await patient.wait('patient receives its nano', () => patient.local().stats[214] === 16);
+
+ // The unchanged companion can still be withdrawn through the same bag window.
+ await click(cell(107, 65538));
+ await owner.wait('companion picked', state => state.dragged[0] === 107 && state.dragged[1] === 65538);
+ await click(owner.state.grids.find(grid => grid.totalCells === 30).cells.find(cell => cell.identity[0] === 0));
+ await owner.wait('exact companion withdraws', state => owner.local(state).inventory.some(item => item.id === 4 && item.slot === 49));
+ evidence.after = await server();
+ await Promise.all(games.map((game, index) => game.save(output + '/verified-' + index)));
+ for (const game of games) {
+ await game.page.reload();
+ await game.ready();
+ }
+ evidence.replayed = await server();
+ for (let index = 0; index < 2; index++) {
+ assert.equal(evidence.replayed[index].health, evidence.after[index].health);
+ assert.equal(evidence.replayed[index].nano, evidence.after[index].nano);
+ assert.deepEqual(evidence.replayed[index].locks, evidence.after[index].locks);
+ assert.deepEqual(evidence.replayed[index].inventory, evidence.after[index].inventory);
+ }
+ assert.deepEqual(owner.local().inventory.map(item => [item.id, item.slot]), [[1, 48], [4, 49]]);
+ for (const game of games) {
+ assert.deepEqual(game.errors, []);
+ assert.equal(game.dropped, 0);
+ }
+ console.log('PASS: contained first aid and teammate treatment consume exact charges, preserve actors and companion, and survive page/cold recovery');
+} finally {
+ try {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n');
+ await Promise.all(games.map((game, index) => game.save(output + '/final-' + index)));
+ } finally { await browser.close(); }
+}