commit 4f1980ccd112eed3a771553b566cacd1b691fa7e
parent c9c4cf5abc0d653059e544ce7ddca142cf55ac64
Author: anon <anon@example.com>
Date: Tue, 3 Nov 2026 23:41:22 +0000
Reset empty native shop selection totals
Diffstat:
7 files changed, 313 insertions(+), 1 deletion(-)
diff --git a/TODO.md b/TODO.md
@@ -2067,12 +2067,20 @@ introduction and starting-item gameplay remain open below.
and server restart retain the result. See [mixed baskets](docs/shop-multi-sale.md).
- [ ] [P1] Resolve native shop quotes after live Computer Literacy changes.
Check: displayed BUY, affordability and final debit agree across skill rises
- and drops, partial removal, an empty selection and re-addition. Reproduced:
+ and drops, partial removal and re-addition. Original reproduction:
adding a 230-credit Lock Pick at skill 39, then receiving +10, leaves BUY 230;
removal leaves 2 with no selected items, and current Accept charges 228.
Recover the historical pricing/lifecycle policy before freezing or rebuilding
drafts; ordinary TradeUpdated and Remove/Add do not repair the cache.
See [live quote findings](docs/shop-multi-sale.md).
+- [x] Reset empty native shop selection totals after a live skill change.
+ Reproduction: select a 230-credit Lock Pick, raise effective Computer Literacy
+ 39 -> 49, then remove the purchase and funding sale; empty BUY 2 blocks Accept
+ with zero credits. Completion: empty BUY/SELL are zero and real Accept succeeds
+ without changing the axe, cash or item-ID allocation. Native/paged/WASM entry
+ tests cover both residue signs and preserve nonempty arithmetic; a 15-second
+ WASM fixture, page replay and cold database load pass. The nonempty live-quote
+ policy above remains unresolved. See [empty selections](docs/shop-multi-sale.md#empty-selections).
- [x] Restore removed/cancelled sale offers into native first-free inventory
slots, rather than their original positions. Preserve stable TradeInv slots,
ownership and quantities; commit placement before acknowledgement and retain
diff --git a/client/Makefile.linux b/client/Makefile.linux
@@ -176,6 +176,8 @@ test: build/linux/window build/linux/graphics build/linux/atoi build/linux/stric
./build/linux/bitmap-clear-paged
./build/linux/bulk-fill
./build/linux/bulk-fill-paged
+ ./build/linux/shop-empty-total
+ ./build/linux/shop-empty-total-paged
./build/linux/reference-persistence
./build/linux/weapon-range
./build/linux/ip-training
@@ -726,3 +728,9 @@ build/linux/bulk-fill build/linux/bulk-fill-paged: tests/bulk_fill.c game/bbr.dl
$(CC) $(CPPFLAGS) $(CFLAGS) $(if $(filter %-paged,$@),-U__linux__) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@
test: build/linux/bulk-fill build/linux/bulk-fill-paged
+
+build/linux/shop-empty-total build/linux/shop-empty-total-paged: tests/shop_empty_total.c game/kkr.dll/lifted-0012.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h
+ @mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(if $(filter %-paged,$@),-U__linux__) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@
+
+test: build/linux/shop-empty-total build/linux/shop-empty-total-paged
diff --git a/client/game/kkr.dll/lifted-0012.c b/client/game/kkr.dll/lifted-0012.c
@@ -8373,6 +8373,8 @@ L_3601E34D:
ecx = ecx - 1; /* 0x3601E36B: dec ecx */
_flag_k = FK_DEC;
MEM32(eax + 0x8) = ecx; /* 0x3601E36C: mov dword ptr [eax + 8], ecx */
+ /* An empty selection carries no purchase cost. */
+ if (ecx == 0) MEM32(esi + 0x14) = 0;
ecx = esi; /* 0x3601E36F: mov ecx, esi */
RECOMP_ICALL(0x3601E450u); /* 0x3601E371: call 0x3601e450 */ /* not lifted */
RECOMP_FLAGS_IN();
diff --git a/client/tests/shop_empty_total.c b/client/tests/shop_empty_total.c
@@ -0,0 +1,95 @@
+#include "recomp_types.h"
+#include <assert.h>
+
+void sub_3601E2E0(void);
+enum { transaction = 0x50000000, list = 0x50000100, sentinel = 0x50000200,
+ first = 0x50000300, second = 0x50000340, source = 0x50000400 };
+static unsigned releases, notifications;
+static uint32_t expected_quote;
+
+static void release_row(void)
+{
+ assert(MEM32(g_esp + 4) == first);
+ ++releases;
+ g_esp += 4;
+}
+
+static void selection_changed(void)
+{
+ assert(g_ecx == transaction);
+ assert(MEM32(transaction + 0x14) == expected_quote);
+ ++notifications;
+ g_esp += 4;
+}
+
+recomp_func_t recomp_lookup_manual(uint32_t address) { return NULL; }
+recomp_func_t recomp_lookup_import(uint32_t address) { abort(); }
+recomp_func_t recomp_lookup(uint32_t address)
+{
+ switch (address) {
+ case 0x3615fcc4: return release_row;
+ case 0x3601e450: return selection_changed;
+ default: fprintf(stderr, "Unexpected shop selection dependency: %08x\n", address); abort();
+ }
+}
+
+int main(void)
+{
+ assert(guest_map("shop selection and stack", 0x50000000, 0x10000));
+ const struct {
+ uint32_t total, price;
+ unsigned quantity, rows;
+ uint32_t expected_total;
+ unsigned expected_rows, expected_quantity, found;
+ } cases[] = {
+ {230, 228, 1, 1, 0, 0, 0, 1},
+ {228, 230, 1, 1, 0, 0, 0, 1},
+ {460, 228, 2, 1, 232, 1, 1, 1},
+ {460, 228, 1, 2, 232, 1, 0, 1},
+ {230, 228, 1, 1, 230, 1, 1, 0},
+ {0, 228, 0, 0, 0, 0, 0, 0},
+ };
+ for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) {
+ memset((void *)ADDR(transaction), 0, 0x10000);
+ releases = notifications = 0;
+ expected_quote = cases[i].expected_total;
+ MEM32(transaction + 0x10) = list;
+ MEM32(transaction + 0x14) = cases[i].total;
+ MEM32(list + 4) = sentinel;
+ MEM32(list + 8) = cases[i].rows;
+ MEM32(sentinel) = cases[i].rows ? first : sentinel;
+ MEM32(sentinel + 4) = cases[i].rows == 2 ? second : cases[i].rows ? first : sentinel;
+ MEM32(first) = cases[i].rows == 2 ? second : sentinel;
+ MEM32(first + 4) = sentinel;
+ MEM32(first + 8) = 111;
+ MEM32(first + 12) = 1;
+ MEM16(first + 0x18) = cases[i].quantity;
+ MEM32(second) = sentinel;
+ MEM32(second + 4) = first;
+ MEM32(second + 8) = 111;
+ MEM32(second + 12) = 2;
+ MEM16(second + 0x18) = 1;
+ MEM32(source) = 111;
+ MEM32(source + 4) = cases[i].found ? 1 : 9;
+ g_ecx = transaction;
+ g_esp = 0x5000ff00;
+ g_ebp = 123; g_ebx = 234; g_esi = 345; g_edi = 456;
+ g_fp_top = 8;
+ MEM32(g_esp + 4) = source;
+ MEM32(g_esp + 8) = cases[i].price;
+
+ sub_3601E2E0();
+
+ assert(MEM32(transaction + 0x14) == cases[i].expected_total);
+ assert(MEM32(list + 8) == cases[i].expected_rows);
+ assert((g_eax & 255) == cases[i].found);
+ assert(notifications == cases[i].found);
+ assert(releases == (cases[i].found && cases[i].quantity == 1));
+ if (cases[i].expected_quantity) assert(MEM16(first + 0x18) == cases[i].expected_quantity);
+ if (!cases[i].expected_rows) assert(MEM32(sentinel) == sentinel && MEM32(sentinel + 4) == sentinel);
+ if (cases[i].rows == 2) assert(MEM32(sentinel) == second && MEM32(second + 4) == sentinel);
+ assert(g_esp == 0x5000ff0c && g_ebp == 123);
+ assert(g_ebx == 234 && g_esi == 345 && g_edi == 456 && g_fp_top == 8);
+ }
+ puts("shop empty total: positive/negative residue, quantities, other rows, misses and ABI passed");
+}
diff --git a/docs/shop-multi-sale.md b/docs/shop-multi-sale.md
@@ -108,3 +108,33 @@ It therefore does not justify freezing this server's drafts or rewriting the
client's quote cache. The original opening-stat snapshot or corresponding
server exchange remains the specific evidence gap. Further broad searches did
not recover a period example; keep the live-quote issue open.
+
+### Empty selections
+
+An empty selection has no purchase cost regardless of the unresolved pricing
+policy. The client now resets the cached aggregate when removing its final row,
+before notifying the GUI. Nonempty quantities and other rows retain their
+existing arithmetic. This is a two-line correction in
+`client/game/kkr.dll/lifted-0012.c::sub_3601E2E0`; the original unlink/decrement
+path at `1001e36c` left the stale aggregate intact.
+
+`client/tests/shop_empty_total.c` invokes that native entry with positive and
+negative residual quotes, a remaining quantity, another selected row, an unknown
+identity and an already empty selection. It checks the total before notification,
+list links, releases, return value and guest stack/register preservation under
+native, paged-memory and WASM execution. `TestBrowserShopEmptyTotal` supplies a
+controlled zero-credit character and one axe; no earned progression is claimed.
+The native shop selects a Lock Pick, receives a raw Computer Literacy change
+38 -> 48 (effective 39 -> 49), removes the purchase and funding axe, then accepts
+the empty basket. The completion check is BUY 0, an actual Accept request and
+unchanged cash, physical item properties and allocation after page/cold recovery.
+This does not settle repricing while any purchase remains selected.
+
+The pre-fix browser run at `local/shop-empty-total/20261103-153518` shows BUY 2,
+SELL -2, no selected server rows and no Accept request. The rebuilt client run at
+`local/shop-empty-total/20261103-154001` completes in 15.24 seconds: BUY/SELL 0,
+one actual Accept and one Complete, the unchanged axe and zero credits after
+native page replay and a cold database load. All retained traces are free of
+client exceptions. Six focused Go checks (including that browser fixture),
+native/paged entry tests and a standalone WASM entry test pass. Evidence and
+bundle hashes are checked by `local/shop-empty-total/tmp_verify.py`.
diff --git a/server/browser_shop_empty_total_test.go b/server/browser_shop_empty_total_test.go
@@ -0,0 +1,92 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/binary"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserShopEmptyTotal(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for empty shop totals")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/shop-empty-total", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.level = 20
+ player.playfield, player.position, player.appearance = 1183, [3]float32{188, 5.751, 135.5}, 0x515
+ player.rotation = [4]float32{0, .70710677, 0, .70710677}
+ player.stats.Abilities.Intelligence = 4
+ player.stats.TradeRepair.ComputerLiteracy = 38
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("shop-empty-total")))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ inventory := playerInventory{LastID: 1, Items: []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, 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()
+ sales, purchases, open := 0, uint16(0), false
+ if client := world.clients[1]; client != nil && client.shop != nil {
+ open = true
+ sales, purchases = len(client.shop.items), client.shop.purchases[0]
+ }
+ json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "sales": sales, "purchases": purchases, "open": open, "lastID": world.nextItem})
+ })
+ mux.HandleFunc("POST /test-skill", func(w http.ResponseWriter, r *http.Request) {
+ world.updateMutex.Lock()
+ defer world.updateMutex.Unlock()
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ player.stats.TradeRepair.ComputerLiteracy = 48
+ if err := world.saveUser_locked(player); err != nil {
+ t.Error(err)
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ stats := player.baseStats()
+ payload := binary.BigEndian.AppendUint32(nil, 75)
+ for _, field := range stats.trainingStats() {
+ payload = binary.BigEndian.AppendUint32(payload, field.stat)
+ payload = binary.BigEndian.AppendUint32(payload, uint32(*field.value))
+ }
+ world.clients[1].send(n3Packet(0x3e205660, 50000, 1, payload))
+ })
+ 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_shop_empty_total.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).characters[1].inventory
+ if !reflect.DeepEqual(cold.Items, inventory.Items) || !reflect.DeepEqual(player.inventory.Items, inventory.Items) ||
+ cold.Credits != 0 || player.inventory.Credits != 0 || world.nextItem != 1 {
+ t.Fatal("empty acceptance changed inventory, cash or item allocation", cold)
+ }
+}
diff --git a/tools/client/test_shop_empty_total.mjs b/tools/client/test_shop_empty_total.mjs
@@ -0,0 +1,77 @@
+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: 'shop-empty-total', url}]);
+ const page = await context.newPage();
+ game = await GameTest.attach(page);
+ const server = async () => (await page.request.get(url + '/test-state')).json();
+ const cell = (state, page, slot) => state.grids.flatMap(grid => grid.cells).find(cell =>
+ cell.identity[0] === page && cell.identity[1] === slot && !cell.dummy);
+ const clickCell = async source => game.click(
+ (source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2);
+ const waitServer = async (description, predicate) => {
+ const deadline = Date.now() + 5000;
+ while (!predicate(await server())) {
+ assert(Date.now() < deadline, description);
+ await game.snapshot();
+ }
+ };
+ await page.goto(url);
+ await game.ready();
+ await page.waitForFunction(() => touchRegion(500, 400)?.world === true);
+ await game.snapshot();
+ evidence.before = await server();
+ assert.equal(game.local().stats[161], 38);
+ await game.key('KeyI');
+ if (!game.state.camera.firstPerson) await game.key('F8');
+ await game.click(...await game.pick(51035, 3221488799), 'right');
+ await game.wait('tools catalog opens', state => cell(state, 111, 0));
+ await clickCell(cell(game.state, 104, 48));
+ await game.wait('axe picked', state => state.dragged[0] === 104 && state.dragged[1] === 48);
+ await game.click(860, 412);
+ await waitServer('axe offered to fund selection', state => state.sales === 1);
+ await clickCell(cell(game.state, 111, 0));
+ await waitServer('Lock Pick selected', state => state.purchases === 1);
+ await game.save(output + '/selected');
+ assert((await page.request.post(url + '/test-skill')).ok());
+ await game.wait('controlled live Computer Literacy update', state => game.local(state).stats[161] === 48);
+ await game.save(output + '/skill-changed');
+ await game.click(860, 328);
+ await waitServer('last purchase removed', state => state.purchases === 0);
+ await game.click(860, 412);
+ await waitServer('funding axe removed', state => state.sales === 0);
+ await game.wait('funding axe restored to inventory', state => game.local(state).inventory.some(item => item.id === 1));
+ evidence.empty = await server();
+ await game.save(output + '/empty');
+ const sequence = game.sequence;
+ await game.click(873, 475);
+ await game.wait('empty zero-credit basket sends Accept', () => game.events.some(event =>
+ event.sequence > sequence && event.direction === 'framesent' && event.opcode === '36284f6e' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(33) === 1));
+ await waitServer('empty basket accepted', state => !state.open);
+ evidence.after = await server();
+ assert.deepEqual(evidence.after.inventory, evidence.before.inventory);
+ assert.equal(evidence.after.lastID, 1);
+ await page.reload();
+ await game.ready();
+ assert.deepEqual((await server()).inventory, evidence.before.inventory);
+ assert.deepEqual(game.errors, []);
+ console.log('PASS: last purchase removal accepts an empty zero-credit basket and retains the axe after reload');
+} 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(); }
+}