aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 55b581355f9f633e3761df984405e9ed73caab59
parent 3bce13d226421753e7c68c5cf1db8ff45b987f6c
Author: anon <anon@example.com>
Date:   Tue,  3 Nov 2026 05:34:38 +0000

Publish player recovery through queued incoming hits

Diffstat:
MTODO.md | 8++++++++
Mdocs/combat-regeneration.md | 36++++++++++++++++++++++++++++--------
Aserver/browser_player_recovery_test.go | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/regeneration.go | 10++++++++--
Mserver/regeneration_test.go | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Atools/client/test_player_recovery.mjs | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 308 insertions(+), 13 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -1544,6 +1544,14 @@ replay/failure tests and WASM checks are recorded in [IP training](docs/ip-train packet confirms 106 after 2040 ms; no item charge changed. This separate prediction-phase case is retained in `local/earned-seven/post-kill-hp-phase-verified.json`; the broader audit stays open. +- [x] [P0] Prevent false-zero player HP after authoritative recovery during + incoming combat. Two native clients reproduce display0 versus server HP3 + after two real eight-point hits and a withheld three-point recovery. Actual + recovery now publishes with the received hit still pending; its impact + retains11, then the later hit leaves3. Body Development10 and cap-checked80 + retain exact HP through StopFight, both page reloads and cold loading, with + unchanged result queues and attacker deadlines. Independent prediction-phase + drift remains separate; see [player recovery](docs/combat-regeneration.md). - [x] [P0] Prevent inspection from debiting an already committed queued hit twice. Two native clients reproduce server/owner HP192 versus observer184 after T inspection and one eight-damage impact. Check remote inspection, unchanged diff --git a/docs/combat-regeneration.md b/docs/combat-regeneration.md @@ -193,14 +193,19 @@ placements changed, and both test clients were closed. There were no page or adapter errors. Captures and checked results are retained in `local/posture-research/verification.json`. -Absolute health is sent only when neither the player nor an enemy targeting -that player is attacking. StopFight flushes queued weapon outcomes before the -correction can be sent. This prevents an absolute snapshot from pre-applying -health damage that a later animation keyframe would subtract again. Quiet -observers also receive corrected health; current nano is private to its owner. -During combat, recovered regeneration advances authoritatively and the client -predicts it; native animation timing and prediction phase can still temporarily -differ from server state. The next quiet correction reconciles the display. +Actual health recovery publishes an absolute snapshot to the owner and ready +observers, including during incoming or outgoing combat. The maintained receiver +records received weapon results already included in that HP; their later +keyframes retain animation, feedback and ammunition without subtracting damage +again. Subsequent hits still apply normally. Withholding the recovery instead +can leave a living player displayed at zero HP after the next hit. + +Unchanged periodic health corrections still wait until neither the player nor +an enemy targeting that player is attacking. StopFight flushes queued weapon +outcomes before that quiet correction. Current nano remains private to its owner. +Publication does not reset recovery counters or attack clocks. Independent +client prediction phases can still differ temporarily; the next quiet snapshot +settles that drift. Original server publication cadence remains unestablished. Quiet health uses `HealthDamage` (`0x3710256c`) with four uint32 fields: absolute HP, zero signed change, zero damage type and zero death reason. @@ -263,6 +268,21 @@ special attacks and nanos. ## Verification +`TestBrowserPlayerCombatRecovery` checks the false-zero failure with two native +clients at each of raw Body Development10 and80, using a controlled level20 +Enforcer. The increased case uses Stamina41 and explicitly checks recovered +ability/level caps. Two real eight-point Leet results surround a three-point +recovery. The fixture advances one real scheduler check at counter58/56 instead +of waiting for the full interval. Previously both clients showed0 while server +HP was3. +The recovery snapshot now supplies11 with the first result still intact, its +impact retains11, and the later real hit leaves3. The NPC's target and attack/ +recharge deadlines do not change. StopFight, quiet correction, both page reloads +and cold database loading retain3. These are controlled incoming-combat checks, +not earned progression or complete target-switch/phase coverage. +Accepted captures: `local/player-combat-recovery/20261102-212600/10/` and +`local/player-combat-recovery/20261102-213014/80/`. + Tests cover default and edited abilities, standing/sitting/combat intervals, phase preservation when stopping attacks, minimum intervals, both resource maximums, incoming-only fights, owner/observer correction layouts, dead/loading/ diff --git a/server/browser_player_recovery_test.go b/server/browser_player_recovery_test.go @@ -0,0 +1,129 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserPlayerCombatRecovery(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for player recovery with queued incoming hits") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/player-combat-recovery", time.Now().Format("20060102-150405")) + for _, bodyDevelopment := range []uint16{10, 80} { + t.Run(fmt.Sprint(bodyDevelopment), func(t *testing.T) { + world := newTestServer(t) + var npc *character + for _, actor := range world.characters { + if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (npc == nil || actor.id < npc.id) { + npc = actor + } + } + if npc == nil { + t.Fatal("no admitted level-one Leet") + } + npc.playfield, npc.position, npc.rotation = 705, [3]float32{960, 16.5, 514}, [4]float32{0, 0, 0, 1} + npc.motion = nil + world.characters = map[uint32]*character{npc.id: npc} + for index := 0; index < 2; index++ { + player := world.newCharacter() + player.level, player.profession = 20, 9 + player.playfield, player.position = 705, [3]float32{960 + float32(index*2), 16.5, 511} + player.rotation = [4]float32{0, 0, 0, 1} + player.stats = testCharacterStats() + player.stats.Body.BodyDevelopment, player.health = bodyDevelopment, 16 + if bodyDevelopment == 80 { + player.stats.Abilities.Stamina = 41 + } + if uint32(bodyDevelopment) > player.trainingMaximum(152) || uint32(player.stats.Abilities.Stamina) > player.trainingMaximum(18) { + t.Fatal("recovery fixture exceeds the recovered training caps") + } + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("player-recovery-", index)))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + } + player := world.characters[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(map[string]any{"health": player.health, "maximum": player.maximumHealth(), + "bodyDevelopment": player.stats.Body.BodyDevelopment, "npc": npc.id, "target": npc.fighting, + "nextAttack": npc.nextAttack, "rechargeUntil": npc.rechargeUntil, "ownerTarget": player.fighting, + "counter": world.clients[1].regenerationSeconds}) + }) + // Establish incoming combat and its ordinary baseline before either hit. + mux.HandleFunc("POST /test-engage", func(w http.ResponseWriter, r *http.Request) { + world.updateMutex.Lock() + defer world.updateMutex.Unlock() + world.mutex.Lock() + updates := make(map[*worldClient][][]byte) + world.startAttack_locked(npc, player, time.Now(), updates) + world.queueHealthSnapshot_locked(updates, player) + world.mutex.Unlock() + world.sendCombatUpdates(updates) + }) + mux.HandleFunc("POST /test-swing", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + deadline := npc.nextAttack + world.mutex.Unlock() + world.advanceCombat(deadline) + }) + // Advance one real recovery check without waiting for its full interval. + mux.HandleFunc("POST /test-recover", func(w http.ResponseWriter, r *http.Request) { + now := time.Now() + world.mutex.Lock() + interval, _ := player.regenerationIntervals() + world.clients[1].regenerationAt = now.Add(-2 * time.Second) + world.clients[1].regenerationSeconds = interval*2 - 2 + world.mutex.Unlock() + world.advanceRegeneration(now) + }) + mux.HandleFunc("POST /test-stop", func(w http.ResponseWriter, r *http.Request) { + world.updateMutex.Lock() + defer world.updateMutex.Unlock() + world.mutex.Lock() + updates := make(map[*worldClient][][]byte) + world.stopAttack_locked(npc, updates) + world.queueQuietHealth_locked(updates, player) + world.mutex.Unlock() + world.sendCombatUpdates(updates) + }) + 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_player_recovery.mjs"), host.URL, + filepath.Join(output, fmt.Sprint(bodyDevelopment))) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + if err := command.Run(); err != nil { + t.Fatal(err) + } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + + if player.health != 3 || cold.characters[1].health != 3 || npc.fighting != 0 { + t.Fatal("player recovery did not retain exact health through stop/page/cold replay") + } + t.Logf("Browser artifacts: %s/%d", output, bodyDevelopment) + }) + } +} diff --git a/server/regeneration.go b/server/regeneration.go @@ -55,6 +55,7 @@ func (server *server) advanceRegeneration(now time.Time) { } // kkr.dll FUN_10074560 / FUN_1006ea50, with the native float reciprocal. + health := player.health stats := player.baseStats() healthInterval, nanoInterval := player.regenerationIntervals() nanoInterval &^= 1 @@ -77,7 +78,12 @@ func (server *server) advanceRegeneration(now time.Time) { player.nano = uint32(max(0, min(int32(player.maximumNano()), int32(player.nano)+gain))) } - server.queueQuietHealth_locked(updates, player) + // Actual recovery includes received hits even while their animations are pending. + if player.health != health { + server.queueHealthSnapshot_locked(updates, player) + } else { + server.queueQuietHealth_locked(updates, player) + } body := binary.BigEndian.AppendUint32(nil, 214) body = binary.BigEndian.AppendUint32(body, player.nano) updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, id, body)) @@ -88,7 +94,7 @@ func (server *server) advanceRegeneration(now time.Time) { } func (server *server) queueQuietHealth_locked(updates map[*worldClient][][]byte, actor *character) { - // Absolute HP must wait until weapon queues have been flushed by StopFight. + // Periodic snapshots wait for combat to end; actual recovery is reconciled separately. if server.characterInCombat_locked(actor) { return } diff --git a/server/regeneration_test.go b/server/regeneration_test.go @@ -3,6 +3,7 @@ package main import ( "bytes" "encoding/binary" + "fmt" "testing" "time" ) @@ -48,7 +49,7 @@ func TestRegenerationSittingHalvesHealthInterval(t *testing.T) { } } -func TestRegenerationCombatUsesLongerIntervalsWithoutAbsoluteHealth(t *testing.T) { +func TestRegenerationCombatPublishesOnlyActualHealthChanges(t *testing.T) { world, conn, start := newRegenerationWorld(t) if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil { t.Fatal(err) @@ -66,11 +67,63 @@ func TestRegenerationCombatUsesLongerIntervalsWithoutAbsoluteHealth(t *testing.T if world.characters[1].health != 23 || world.characters[1].nano != 6 { t.Fatalf("combat recovery: %+v", world.characters[1]) } + healthSnapshots := 0 for _, packet := range conn.packets { - if binary.BigEndian.Uint32(packet[16:20]) != 0x2b333d6e || binary.BigEndian.Uint32(packet[29:33]) != 214 { - t.Fatalf("combat recovery changed queued health: %x", packet) + if binary.BigEndian.Uint32(packet[16:20]) == 0x3710256c { + healthSnapshots++ + if !bytes.Equal(packet[29:45], []byte{0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) { + t.Fatal("combat recovery did not publish its exact zero-feedback health", packet) + } + } else if binary.BigEndian.Uint32(packet[16:20]) != 0x2b333d6e || binary.BigEndian.Uint32(packet[29:33]) != 214 { + t.Fatalf("combat recovery emitted an unexpected packet: %x", packet) } } + if healthSnapshots != 1 { + t.Fatal("actual combat recovery was withheld or unchanged health was published repeatedly", healthSnapshots) + } +} + +func TestRegenerationIncomingCombatPublishesRecoveryWithoutChangingAttack(t *testing.T) { + for _, bodyDevelopment := range []uint16{10, 80} { + t.Run(fmt.Sprint(bodyDevelopment), func(t *testing.T) { + world, conn, start := newRegenerationWorld(t) + player, npc := world.characters[1], world.characters[1000000] + player.level = 20 + player.stats.Body.BodyDevelopment = bodyDevelopment + counter := uint32(58) + if bodyDevelopment == 80 { + player.stats.Abilities.Stamina = 41 + counter = 56 + } + if uint32(bodyDevelopment) > player.trainingMaximum(152) || uint32(player.stats.Abilities.Stamina) > player.trainingMaximum(18) { + t.Fatal("recovery fixture exceeds the recovered training caps") + } + npc.regenerationAt = start.Add(time.Hour) + peer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + world.clients[2] = &worldClient{id: 2, conn: peer, target: true, ready: true, regenerationAt: start.Add(time.Hour)} + updates := make(map[*worldClient][][]byte) + world.startAttack_locked(npc, player, start, updates) + world.sendCombatUpdates(updates) + clocks := [2]time.Time{npc.nextAttack, npc.rechargeUntil} + world.clients[1].regenerationSeconds = counter - 2 + conn.packets, peer.packets = nil, nil + + world.advanceRegeneration(start.Add(2 * time.Second)) + world.advanceRegeneration(start.Add(2 * time.Second)) + + if player.health != 23 || world.clients[1].regenerationSeconds != counter || player.fighting != 0 || npc.fighting != 1 || + clocks != [2]time.Time{npc.nextAttack, npc.rechargeUntil} { + t.Fatal("recovery changed its amount, phase or incoming attacker") + } + if len(conn.packets) != 2 || len(peer.packets) != 1 || + binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x3710256c || + !bytes.Equal(conn.packets[0][29:45], []byte{0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) || + !bytes.Equal(conn.packets[0][16:], peer.packets[0][16:]) { + t.Fatal("incoming recovery did not publish one zero-feedback health snapshot to both clients") + } + }) + } } func TestRegenerationDoesNotCorrectHealthWhileOnlyTheEnemyAttacks(t *testing.T) { diff --git a/tools/client/test_player_recovery.mjs b/tools/client/test_player_recovery.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']}); +const games = [], evidence = {}; +const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id); +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: 'player-recovery-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + } + const [owner, observer] = games; + const server = async () => (await owner.page.request.get(url + '/test-state')).json(); + evidence.initial = await server(); + const npc = evidence.initial.npc; + const pending = game => actor(game, npc)?.weapons.some(weapon => weapon.pending.length); + const clients = () => games.map(game => ({health: actor(game, 1).stats[27], weapons: actor(game, npc).weapons})); + await Promise.all(games.map(game => game.wait('both players and Leet', () => actor(game, 1) && actor(game, 2) && actor(game, npc)))); + await owner.key('F1'); + const [x, y] = await observer.pick(50000, 1); + await observer.click(x, y); + assert((await owner.page.request.post(url + '/test-engage')).ok()); + await Promise.all(games.map(game => game.wait('incoming combat baseline', () => + actor(game, npc).combatTarget === 1 && actor(game, 1).stats[27] === 16))); + assert((await owner.page.request.post(url + '/test-swing')).ok()); + await Promise.all(games.map(game => game.wait('first real hit pending', () => pending(game)))); + evidence.pending = {server: await server(), clients: clients()}; + assert.equal(evidence.pending.server.health, 8); + assert(evidence.pending.clients.every(client => client.health === 16)); + + assert((await owner.page.request.post(url + '/test-recover')).ok()); + evidence.recovered = await server(); + assert.deepEqual(evidence.recovered, {...evidence.pending.server, health: 11, + counter: evidence.initial.bodyDevelopment === 80 ? 56 : 58}); + await Promise.all(games.map(game => game.wait('recovery snapshot or first impact', () => actor(game, 1).stats[27] === 11 || !pending(game)))); + evidence.included = clients(); + await Promise.all(games.map(game => game.wait('first impact consumed', () => !pending(game)))); + evidence.first = {server: await server(), clients: clients()}; + assert((await owner.page.request.post(url + '/test-swing')).ok()); + await Promise.all(games.map(game => game.wait('second hit pending', () => pending(game)))); + await Promise.all(games.map(game => game.wait('second impact consumed', () => !pending(game)))); + evidence.second = {server: await server(), clients: clients()}; + await Promise.all(games.map((game, index) => game.save(output + '/second-' + index))); + assert.equal(evidence.second.server.health, 3); + assert(evidence.second.clients.every(client => client.health === 3), 'Native player HP reached zero while authoritative health remained three'); + assert(evidence.first.clients.every(client => client.health === 11)); + assert.deepEqual(evidence.first.server, evidence.recovered); + assert(evidence.included.every(client => client.health === 11)); + evidence.included.forEach((client, index) => assert.deepEqual(client.weapons, evidence.pending.clients[index].weapons)); + + assert((await owner.page.request.post(url + '/test-stop')).ok()); + await Promise.all(games.map(game => game.wait('stopped attacker and retained health', () => + actor(game, npc).combatTarget === 0 && actor(game, 1).stats[27] === 3))); + evidence.stopped = await server(); + assert.equal(evidence.stopped.target, 0); + await Promise.all(games.map(async game => { await game.page.reload(); await game.ready(); })); + await Promise.all(games.map(game => game.wait('replayed owner health', () => actor(game, 1)?.stats[27] === 3))); + await owner.page.waitForFunction(() => touchRegion(500, 400)?.world === true); + evidence.replayed = {server: await server(), clients: clients()}; + assert.equal(evidence.replayed.server.health, 3); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: player recovery survives queued incoming impacts, both clients retain three HP through stop and page/cold replay'); +} 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(); } +}