commit feef14a3434821c06bad6c510d0bcd037db46317
parent 55b581355f9f633e3761df984405e9ed73caab59
Author: anon <anon@example.com>
Date: Tue, 3 Nov 2026 05:49:35 +0000
Test sparse inventory layout through shop transitions
Diffstat:
4 files changed, 264 insertions(+), 0 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -3562,6 +3562,13 @@ with payloads and known client/server provenance.
remaining main-inventory entries. Isolate the transition, an inspection race,
and any intentional native compaction before changing persistence behavior.
Evidence: `local/todo-progression-play/runtime-level20/`.
+ A controlled sparse-layout regression now retains exact saved/visible cells
+ through reload, city/shop zoning, a two-part sale and laboratory purchase;
+ cold recovery accounts for all three retained instances. Native Remove does
+ not compact survivors, and the 108-byte size reduction matches nine removed
+ entries. The empty inspection remains unreproduced; next isolate the earlier
+ seeded/login context rather than repeat this passing transition. See
+ [layout through shop transitions](docs/inventory.md#layout-through-shop-transitions).
- [x] Resolve the browser snapshot's incorrect local identity for normally
created characters. The first repeatable starter run reported local ID1
while directory actor2 had seven issued items and exchanged CharacterReady.
diff --git a/docs/inventory.md b/docs/inventory.md
@@ -246,6 +246,28 @@ cell 8 after page reload and a server restart. Its server ID, QL, logical slot
and item count stayed unchanged. A second visitor moved its own pistol without
changing the first visitor's cell. Idle frames did not rewrite the saved file.
+### Layout through shop transitions
+
+`TestBrowserInventoryLayoutTransitions` starts with four controlled items,
+moves the weapon to visual cell 8, reloads that layout, and uses control
+checkpoints to zone to an Omni shop and back. Native mouse input sells two
+parts and purchases one laboratory. This is a controlled regression, not
+earned progression. The retained weapon stays at cell 8, the earlier laboratory
+at cell 3, and the new purchase takes cell 0. Each checkpoint compares the
+serialized main-inventory map with the visible grid. Page replay and cold
+database recovery retain the three expected physical instances and quantities.
+
+Original CCR Save stores an 8-byte header, 16 bytes per group and 12 bytes per
+entry. Remove erases only the selected identity; CheckGrid preserves occupied
+indices. Load does not delete the file. Consequently the historical 516 -> 408
+byte change is exactly consistent with nine net removed entries, but does not
+explain the intermediate empty OPFS inspection or compact positions. Those
+remain unresolved; this fixture does not reproduce them. Complete original
+static evidence and the bounded investigation are retained in
+`local/icon-layout-research/`, with browser captures in
+`local/icon-layout-transitions/`. No production persistence change is justified
+by this check.
+
## Verification
`server/inventory_test.go` exercises native initialization and a captured native
diff --git a/server/browser_icon_persistence_test.go b/server/browser_icon_persistence_test.go
@@ -0,0 +1,99 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "testing"
+ "time"
+)
+
+func TestBrowserInventoryLayoutTransitions(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for the inventory layout transition check")
+ }
+
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/icon-layout-transitions", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.appearance = 0x515
+ player.level, player.stats, player.health = 10, testCharacterStats(), 50
+ player.playfield, player.position = 705, [3]float32{960, 16.5, 511}
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("icon-persistence")))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ for _, template := range []uint32{121564, 42640, 42640, 25812} {
+ if granted, err := world.grantItem_locked(player, template); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ }
+ inventory := player.inventory
+ inventory.Credits = 5000
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ // Controlled stock isolates the inventory transition, not booth membership.
+ stock := gamedata.ShopStock[99383]
+ t.Cleanup(func() { gamedata.ShopStock[99383] = stock })
+ gamedata.ShopStock[99383] = []gamedata.ShopItem{{Template: 25812, Quality: 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(world.characters[player.id].inventory)
+ })
+ // Use the normal control transition to reach each checkpoint without travel.
+ mux.HandleFunc("POST /test-zone", func(w http.ResponseWriter, r *http.Request) {
+ world.updateMutex.Lock()
+ defer world.updateMutex.Unlock()
+ world.mutex.Lock()
+ destination := world.characters[player.id].userData()
+ world.mutex.Unlock()
+ if r.URL.Query().Get("shop") == "1" {
+ destination.Playfield, destination.Position = 1183, [3]float32{188, 5.11, 139.5}
+ destination.Rotation = [4]float32{0, 0.70710677, 0, 0.70710677}
+ } else {
+ destination.Playfield, destination.Position = 705, [3]float32{960, 16.5, 511}
+ destination.Rotation = [4]float32{0, 0, 0, 1}
+ }
+ if err := world.updateUser_locked(destination); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+ })
+ host := httptest.NewServer(mux)
+ t.Cleanup(host.Close)
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_icon_persistence.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)
+ expected := []ownedItem{
+ inventory.Items[0], inventory.Items[3],
+ {ID: 5, Type: 51005, Template: 25812, Quality: 1, Slot: 65, Count: 50},
+ }
+ if !slices.Equal(world.characters[player.id].inventory.Items, expected) ||
+ !slices.Equal(cold.characters[player.id].inventory.Items, expected) {
+ t.Fatal("sale, purchase or recovery changed retained item instances")
+ }
+}
diff --git a/tools/client/test_icon_persistence.mjs b/tools/client/test_icon_persistence.mjs
@@ -0,0 +1,136 @@
+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 evidence = {};
+let game;
+try {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'icon-persistence', url}]);
+ const page = await context.newPage();
+ game = await GameTest.attach(page);
+ await page.goto(url);
+ await game.ready();
+ const grid = state => state.grids.find(grid => grid.cells.some(cell => cell.identity[0] === 104));
+ const cell = slot => grid(game.state).cells.find(cell => cell.identity[0] === 104 && cell.identity[1] === slot && !cell.dummy);
+ const clickCell = async target => game.click((target.bounds[0] + target.bounds[2]) / 2, (target.bounds[1] + target.bounds[3]) / 2);
+ const server = async () => (await page.request.get(url + '/test-state')).json();
+ const record = async name => {
+ evidence[name] = {grid: grid(game.state), inventory: game.local().inventory, server: await server(),
+ files: await page.evaluate(async () => {
+ const files = [];
+ async function visit(directory, path) {
+ for await (const [name, handle] of directory.entries()) {
+ if (handle.kind === 'directory') await visit(handle, path + '/' + name);
+ else if (name === 'IconPositions.bin') files.push({path: path + '/' + name,
+ bytes: Array.from(new Uint8Array(await (await handle.getFile()).arrayBuffer()))});
+ }
+ }
+ await visit(await navigator.storage.getDirectory(), '');
+ return files;
+ })};
+ await game.save(output + '/' + name);
+ console.log(name, JSON.stringify({cells: evidence[name].grid?.cells.filter(cell => !cell.dummy).map(cell => [cell.index, cell.identity]),
+ files: evidence[name].files.map(file => [file.path, file.bytes.length])}));
+ const file = evidence[name].files.find(file => file.path.endsWith('/1/IconPositions.bin'));
+ assert(file, 'The character icon file disappeared');
+ const bytes = Buffer.from(file.bytes);
+ assert.equal(bytes.readUInt32BE(0), bytes.length);
+ let offset = 8, positions;
+ for (let group = 0; group < bytes.readUInt32BE(4); ++group) {
+ const owner = [bytes.readUInt32BE(offset), bytes.readUInt32BE(offset + 4), bytes.readUInt32BE(offset + 8)];
+ const count = bytes.readUInt32BE(offset + 12);
+ offset += 16;
+ const rows = [];
+ for (let entry = 0; entry < count; ++entry, offset += 12) {
+ rows.push([bytes.readUInt32BE(offset), bytes.readUInt32BE(offset + 4), bytes.readUInt32BE(offset + 8)]);
+ }
+ if (owner[0] === 50000 && owner[1] === 1 && owner[2] === 1) positions = rows;
+ }
+ assert.equal(offset, bytes.length);
+ assert.deepEqual(positions, evidence[name].grid.cells.filter(cell => !cell.dummy).map(cell => [cell.index, ...cell.identity]));
+ };
+ const inventoryOpen = async () => {
+ await page.waitForFunction(() => touchRegion(500, 400)?.world === true);
+ await game.snapshot();
+ if (!grid(game.state)) await game.key('i');
+ await game.wait('inventory grid visible', state => grid(state));
+ };
+ const zone = async shop => {
+ const response = await page.request.post(url + '/test-zone?shop=' + (shop ? '1' : '0'));
+ assert.equal(response.status(), 200);
+ await game.wait('controlled zone ready', state => game.local(state)?.playfield === (shop ? 1183 : 705));
+ await inventoryOpen();
+ };
+
+ // Make a reset observable without earning or replaying progression.
+ await inventoryOpen();
+ evidence.initial = await server();
+ const source = cell(48);
+ const target = grid(game.state).cells.find(cell => cell.index === 8);
+ assert(source && target);
+ await clickCell(source);
+ await game.wait('weapon picked', state => state.dragged[0] === 104 && state.dragged[1] === 48);
+ await clickCell(target);
+ await game.wait('sparse weapon placement', state => state.dragged[0] === 0 &&
+ grid(state)?.cells.some(cell => cell.index === 8 && cell.identity[1] === 48 && !cell.dummy));
+ await record('moved');
+ assert.deepEqual(await server(), evidence.initial);
+ await page.reload();
+ await game.ready();
+ await inventoryOpen();
+ await record('initial-reload');
+ assert.equal(cell(48).index, 8, 'Initial reload reset the retained visual cell');
+ await zone(true);
+ await record('shop-zone');
+ assert.equal(cell(48).index, 8, 'Zoning reset the retained visual cell');
+
+ // Sell two exact instances and buy one item through real browser input.
+ if (!game.state.camera.firstPerson) await game.key('F8');
+ await game.click(...await game.pick(51035, 3221226655), 'right');
+ const shopOpen = state => state.regions.some(([left, top, right, bottom]) => left === 832 && top === 0 && right === 1024 && bottom === 494);
+ await game.wait('shop open', shopOpen);
+ for (const slot of [49, 50]) {
+ await clickCell(cell(slot));
+ await game.wait('sale icon picked', state => state.dragged[0] === 104 && state.dragged[1] === slot);
+ const sequence = game.sequence;
+ await game.click(864, 416);
+ await game.wait('sale offer sent', () => game.events.some(event => event.sequence > sequence && event.direction === 'framesent' && event.opcode === '36284f6e'));
+ }
+ await game.click(874, 475);
+ await game.wait('parts sold', state => game.local(state).inventory.length === 2);
+ await game.wait('accepted sale window closes', state => !shopOpen(state));
+ await record('sold');
+ await game.click(...await game.pick(51035, 3221226655), 'right');
+ await game.wait('shop reopened', shopOpen);
+ await game.click(864, 85);
+ await game.click(874, 475);
+ await game.wait('laboratory purchased', state => game.local(state).inventory.length === 3);
+ await game.wait('accepted purchase window closes', state => !shopOpen(state));
+ await record('purchased');
+ assert.equal(cell(48).index, 8, 'Trade reset the retained visual cell');
+ await zone(false);
+ await record('city-zone');
+ assert.equal(cell(48).index, 8, 'Return zoning reset the retained visual cell');
+ const retained = await server();
+ await page.reload();
+ await game.ready();
+ await inventoryOpen();
+ await record('reloaded');
+ assert.equal(cell(48).index, 8, 'Reload reset the retained visual cell');
+ assert.deepEqual(await server(), retained);
+ assert.equal(game.errors.length, 0);
+ console.log('PASS: sparse layout, retained identities, sale/purchase and zoning/reload persistence');
+} 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(); }
+}