aorecomp

Anarchy Online classic in the browser

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


commit d005e352d9c20c41773e51822434e1e899f456ad
parent 42f63e7313e5bfbc2432a5057de3ca30473ec510
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 14:04:01 +0000

Stop owned pet combat on retreat and wait

Diffstat:
MTODO.md | 11+++++++++--
Mdocs/pet-follow.md | 6++++--
Mdocs/pet-owner-protocol.md | 5++++-
Adocs/pet-retreat.md | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_pet_retreat_test.go | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/pet_follow.go | 9+++++++--
Aserver/pet_retreat_test.go | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_pet_retreat.mjs | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 410 insertions(+), 7 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -3208,8 +3208,15 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah Blocked on the original PT50 combat-profile binding above: retained fist records120634/120637 establish candidate weapon data, not that this summoned pet equips them. Keep the attack schedule tied to recovered profile evidence. -- [ ] [P1] Stop a pet's attack. Check: the stop command clears combat and queued - actions according to the recovered behavior. + Default and follow/behind/wait retaliation policies also need period evidence; + sources differ on whether a waiting pet responds to a fresh attack. +- [x] [P1] Stop a pet's attack. Original behind2 and wait4 now clear outgoing + combat, the future swing and retained encounter threat before publishing the + owner-follow or halt controller. The opponent's independent attack, recharge, + ownership and summon cost remain intact. Public-handler and two-client WASM + checks verify no hit at the held deadline, behind return and stationary wait. + This is controlled scheduler evidence, not a PT50 weapon/profile binding or + a resolved fresh-attack retaliation policy. See [pet retreat](docs/pet-retreat.md). - [ ] [P1] Handle pet death. Check: death removes the applicable ownership state and stale commands cannot act on a replacement pet. Original death/termination animation and corpse presentation still need diff --git a/docs/pet-follow.md b/docs/pet-follow.md @@ -35,9 +35,11 @@ Pose corrections use extended action20 (`0x94`), which preserves the target. ## Server behavior and limits -Only the captured all-pets follow and wait requests are admitted. Actor identity +The captured all-pets follow, behind, wait and terminate requests are admitted. +Behind/wait combat cancellation is described in [pet retreat](pet-retreat.md), +and termination has its separate retirement checks. Actor identity and the current ready client must match; named selectors, arguments and other -commands are refused. The server selects entities from its ownership map rather than +unsupported commands are refused. The server selects entities from its ownership map rather than trusting pet IDs supplied by a client. Dead, expired or other-playfield pets cannot start following. diff --git a/docs/pet-owner-protocol.md b/docs/pet-owner-protocol.md @@ -1,7 +1,8 @@ # Original pet owner-list protocol This document covers the original transport prerequisite. The server now admits -one [owned summon](pet-summoning.md) and all-pets [follow/wait](pet-follow.md); +one [owned summon](pet-summoning.md), all-pets [follow/wait](pet-follow.md) and +[combat retreat](pet-retreat.md); broader commands and lifecycle fidelity remain separate work. ## Original client evidence @@ -25,6 +26,8 @@ The same native input captures `/pet follow` as `1, 0, 1009, 0, 0`; the owned server implementation is documented in [pet follow](pet-follow.md). It captures `/pet wait` as `4, 0, 1009, 0, 0`, now admitted by the same owned command handler. +Original `/pet behind` captures `2, 0, 1009, 0, 0`; its admitted combat stop and +owner-follow transition are documented in [pet retreat](pet-retreat.md). Original `/pet terminate` captures `10, 0, 1009, 0, 0`; the owned [dismissal implementation](pet-dismissal.md) retires only that owner's set. diff --git a/docs/pet-retreat.md b/docs/pet-retreat.md @@ -0,0 +1,61 @@ +# Stopping owned pet combat + +Original `/pet behind` emits PetCommand6b333303 with body words +`2, 0, 1009, 0, 0`. `/pet wait` emits `4, 0, 1009, 0, 0`. Both use the implicit +authenticated owner's pet set. Named selectors and other argument forms remain +outside this admission. The actual 14.9.1 requests are retained under +`local/pet-retreat/` and the earlier wait captures in [pet movement](pet-follow.md). + +Funcom's classic *Your Guide to Anarchy Online*, printed page70, describes +behind as "Retreat from combat" and wait as staying without attacking. +The [publisher-authored manual, mirrored here](https://manuals.plus/m/1f4dd17ae346cdbd3c4bb8391f9a059768560b95cd148ed039c288b9bd69cb97.pdf) +is corroborated for the command names by the shipped14.9.1 +`cd_image/text/help/Pet Commands.txt`. The mirror's upload date is not used as +the manual's publication date. + +## Current encounter transition + +The current ready session may command only its owned living, unexpired pets in +the same playfield. Behind and wait clear that pet's encounter threat and use +the existing StopFight path to clear its outgoing target, future swing and +scheduler entry. Threat clearing prevents the next combat tick from immediately +reselecting the stopped opponent. Damage credit and already committed outcomes +are not rewritten, and the existing recharge deadline remains unchanged. +The opponent's independent attack is not cancelled. + +StopFight precedes the movement controller. Behind installs the existing NPC +owner-follow controller. Wait clears follow/pursuit, applies Halt19 and publishes +an empty FollowTarget identity. No ownership, resource, expiry or allocation +change occurs, and these transient commands do not write SQLite. + +This stops the current encounter and its queued future swing. It does not +establish all subsequent aggression/retaliation modes. A separate +[early-style player guide](https://www.az-net.at/wp-content/uploads/2014/05/gameguide.pdf) +says a waiting pet may react to a fresh attack, unlike a literal reading of the +classic manual's no-attack wording. Its future14.2 reference does not prove the +14.9.1 behavior. Default and command-specific retaliation remain evidence gaps +with the open pet-combat work; no speculative persistent passive flag was added. + +## Verification + +Public-handler tests cover idle/attacking pets, pre-existing threat, a future +recharge, authenticated and forged/unavailable requests, no checkpoint writes, +native stop-before-controller ordering and an opponent whose independent target +and clock remain unchanged. Advancing past the old swing verifies no resumed +pet attack or hit. + +Two controlled owners complete the normal summon action before browser entry. +A test-only endpoint starts a held production-scheduler attack; no weapon hit +is calculated, so this does not establish the unresolved PT50 weapon/profile +binding. Real native behind and wait commands stop both visible copies before +their held deadlines. Behind follows ordinary owner movement; wait stays at its +commanded pose while the owner moves away. Both deadline checks preserve target +health, the other pet, ownership and the original25-point post-summon balances. +The final native check takes21.17seconds with no page errors or dropped events. +The source, traces, screenshots and precise verification scope are retained in +`local/pet-retreat/`. + +The broader pet/threat suite passes28 roots/90 results normally and under race +detection. Maintained-package vet and Node syntax checks pass. An independent +audit verifies both client streams, the two stop-before-controller transitions, +no weapon results, equal final pet poses and preserved native owner counts. diff --git a/server/browser_pet_retreat_test.go b/server/browser_pet_retreat_test.go @@ -0,0 +1,89 @@ +package main + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserPetRetreat(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for native pet retreat") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/pet-retreat", time.Now().Format("20060102-150405")) + world := newBrowserOwnedPetWorld(t) + pet, target := world.characters[1000001], world.characters[2] + var attackDeadline time.Time + 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{"fighting": pet.fighting, "nextAttack": pet.nextAttack, "follow": pet.followTarget, + "petPosition": pet.position, "ownerPosition": world.characters[1].position, "targetHealth": target.health, + "ownerNano": world.characters[1].nano, "peerNano": target.nano, "peerPet": world.characters[1000002].position}) + }) + // Controlled pending attack, not evidence of the original PT50 weapon binding. + mux.HandleFunc("POST /test-attack", 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(pet, target, time.Now(), updates) + attackDeadline = pet.nextAttack + world.mutex.Unlock() + world.sendCombatUpdates(updates) + w.WriteHeader(http.StatusNoContent) + }) + mux.HandleFunc("POST /test-deadline", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + deadline := attackDeadline + world.mutex.Unlock() + world.advanceCombat(deadline.Add(time.Nanosecond)) + w.WriteHeader(http.StatusNoContent) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + world.advancePlayerMovement(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_pet_retreat.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) + } + world.mutex.Lock() + defer world.mutex.Unlock() + if pet.fighting != 0 || !pet.nextAttack.IsZero() || pet.followTarget != 0 || world.fighting[pet.id] != nil || + world.characters[1].nano != 25 || target.nano != 25 || len(world.characters[1].pets) != 1 || len(target.pets) != 1 || world.nextNPC != 1000003 { + t.Fatal("retreat changed ownership/cost or retained a future attack") + } +} diff --git a/server/pet_follow.go b/server/pet_follow.go @@ -12,10 +12,10 @@ func (server *server) handlePetCommand(client *worldClient, body []byte) error { if len(body) < 36 { return fmt.Errorf("invalid pet command length") } - // Original unfiltered commands: follow=1, wait=4, terminate=10, no named selector. + // Original unfiltered commands: follow=1, behind=2, wait=4, terminate=10. command := binary.BigEndian.Uint32(body[16:20]) if len(body) != 36 || !client.target || binary.BigEndian.Uint32(body[4:8]) != 50000 || - binary.BigEndian.Uint32(body[8:12]) != client.id || command != 1 && command != 4 && command != 10 || + binary.BigEndian.Uint32(body[8:12]) != client.id || command != 1 && command != 2 && command != 4 && command != 10 || binary.BigEndian.Uint32(body[20:24]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 1009 || binary.BigEndian.Uint32(body[28:32]) != 0 || binary.BigEndian.Uint32(body[32:36]) != 0 { return nil @@ -40,6 +40,11 @@ func (server *server) handlePetCommand(client *worldClient, body []byte) error { if pet.health == 0 || pet.playfield != owner.playfield || !now.Before(pet.pet.expiresAt) { continue } + if command == 2 || command == 4 { + // Explicit retreat/wait must not reselect the stopped encounter next tick. + pet.threat = nil + server.stopAttack_locked(pet, updates) + } if command == 4 { pet.followTarget = 0 pet.pet.paused = false diff --git a/server/pet_retreat_test.go b/server/pet_retreat_test.go @@ -0,0 +1,131 @@ +package main + +import ( + "encoding/binary" + "fmt" + "reflect" + "testing" + "time" +) + +func TestPetRetreatAndWaitCancelOnlyOwnedOutgoingCombat(t *testing.T) { + for _, command := range []uint32{2, 4} { + for _, fighting := range []bool{false, true} { + t.Run(fmt.Sprintf("%d/fighting%v", command, fighting), func(t *testing.T) { + world, output := newPetSummonWorld(t) + owner, client := world.characters[1], world.clients[1] + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]); err != nil { + t.Fatal(err) + } + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + pet := owner.pets[1000001] + target := &character{id: 2, playfield: owner.playfield, position: pet.position, health: 100, stats: testCharacterStats()} + peerOutput := &combatTestConn{} + world.characters[2] = target + world.clients[2] = &worldClient{id: 2, conn: peerOutput, ready: true, target: true, npcs: map[uint32]bool{pet.id: true}} + updates := make(map[*worldClient][][]byte) + now := time.Now() + pet.rechargeUntil = now.Add(time.Second) + pet.threat = map[uint32]int64{2: 10} + if fighting { + world.startAttack_locked(pet, target, now, updates) + } + // Retreat clears outgoing combat; the opponent's independent attack remains. + world.startAttack_locked(target, pet, now, updates) + target.nextAttack = now.Add(time.Hour) + opponentDeadline := target.nextAttack + ownership, recharge, health := *pet.pet, pet.rechargeUntil, owner.health + request := petFollowRequest(1)[20:] + binary.BigEndian.PutUint32(request[16:], command) + output.packets, peerOutput.packets = nil, nil + auditCheckpointWrites(t, world) + + err := world.handlePetCommand(client, request) + world.advanceCombat(now.Add(10 * time.Second)) + + if err != nil || pet.fighting != 0 || !pet.nextAttack.IsZero() || len(pet.threat) != 0 || world.fighting[pet.id] != nil || + target.fighting != pet.id || !target.nextAttack.Equal(opponentDeadline) || world.fighting[target.id] != target || + !pet.rechargeUntil.Equal(recharge) || target.health != 100 || owner.health != health || owner.nano != 25 || + *pet.pet != ownership || owner.pets[pet.id] != pet || len(checkpointWrites(t, world)) != 0 { + t.Fatal("retreat retained/reselected outgoing combat or changed the opponent, resources, ownership or writes", err) + } + if command == 2 { + if pet.followTarget != 1 || pet.motion == nil { + t.Fatal("behind did not install its owner-follow controller") + } + } else if pet.followTarget != 0 || pet.motion != nil { + t.Fatal("wait retained follow or pursuit") + } + for _, packets := range [][][]byte{output.packets, peerOutput.packets} { + stop, follow := -1, -1 + for index, packet := range packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x4a41203e { + if binary.BigEndian.Uint32(packet[24:28]) != pet.id || stop != -1 { + t.Fatal("retreat stopped another actor or repeated StopFight") + } + stop = index + } + if binary.BigEndian.Uint32(packet[16:20]) == 0x260f3671 { + follow = index + } + } + if follow == -1 || fighting && (stop == -1 || stop >= follow) || !fighting && stop != -1 { + t.Fatal("native stop did not precede the new controller, or an idle command invented combat") + } + } + }) + } + } +} + +func TestPetRetreatRejectsUnavailableAndForgedCommands(t *testing.T) { + for _, scenario := range []string{"foreign actor", "stale client", "not ready", "loading", "owner dead", "pet dead", "expired", "other zone", "argument", "selector", "boolean", "name"} { + t.Run(scenario, func(t *testing.T) { + world, output := newPetSummonWorld(t) + owner, client := world.characters[1], world.clients[1] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]) + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + pet := owner.pets[1000001] + pet.fighting, pet.nextAttack = 1000000, time.Now().Add(time.Second) + pet.threat = map[uint32]int64{1: 10} + world.fighting[pet.id] = pet + request := petFollowRequest(1)[20:] + binary.BigEndian.PutUint32(request[16:], 2) + switch scenario { + case "foreign actor": + binary.BigEndian.PutUint32(request[8:], 2) + case "stale client": + world.clients[1] = &worldClient{id: 1} + case "not ready": + client.ready = false + case "loading": + client.loading = true + case "owner dead": + owner.health = 0 + case "pet dead": + pet.health = 0 + case "expired": + pet.pet.expiresAt = time.Now().Add(-time.Second) + case "other zone": + pet.playfield++ + case "argument": + binary.BigEndian.PutUint32(request[20:], 1000001) + case "selector": + binary.BigEndian.PutUint32(request[24:], 1010) + case "boolean": + binary.BigEndian.PutUint32(request[28:], 1) + case "name": + binary.BigEndian.PutUint32(request[32:], 1) + request = append(request, 'x') + } + before := *pet + output.packets = nil + + err := world.handlePetCommand(client, request) + + if err != nil || !reflect.DeepEqual(*pet, before) || world.fighting[pet.id] != pet || len(output.packets) != 0 { + t.Fatal("invalid retreat changed the pet's current attack or controller", err) + } + }) + } +} diff --git a/tools/client/test_pet_retreat.mjs b/tools/client/test_pet_retreat.mjs @@ -0,0 +1,105 @@ +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: 'pet-cast-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + } + const [owner] = games; + const server = async () => (await owner.page.request.get(url + '/test-state')).json(); + await Promise.all(games.map(game => game.wait('both owned pets visible', () => actor(game, 1000001) && actor(game, 1000002)))); + evidence.before = await server(); + assert((await owner.page.request.post(url + '/test-attack')).ok()); + await Promise.all(games.map(game => game.wait('real attack installed on owned pet', () => actor(game, 1000001).combatTarget === 2))); + evidence.attacking = await server(); + assert.equal(evidence.attacking.fighting, 2); + + const sequence = owner.sequence; + await owner.key('Enter'); + await owner.page.keyboard.type('/pet behind'); + await owner.key('Enter'); + await owner.wait('actual behind command', () => owner.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '6b333303')); + const sent = owner.events.find(event => event.sequence > sequence && event.direction === 'framesent' && event.opcode === '6b333303'); + evidence.command = [29, 33, 37, 41, 45].map(offset => Buffer.from(sent.hex, 'hex').readUInt32BE(offset)); + assert.deepEqual(evidence.command, [2, 0, 1009, 0, 0]); + evidence.afterCommand = await server(); + await Promise.all(games.map(game => game.wait('owned pet stops fighting and follows its owner', () => + actor(game, 1000001).combatTarget === 0 && game.events.some(event => event.direction === 'framereceived' && + event.opcode === '260f3671' && Buffer.from(event.hex, 'hex').readUInt32BE(24) === 1000001 && + Buffer.from(event.hex, 'hex').readUInt32BE(33) === 1)))); + evidence.retreated = await server(); + assert.equal(evidence.retreated.fighting, 0); + assert.equal(evidence.retreated.nextAttack, '0001-01-01T00:00:00Z'); + assert.equal(evidence.retreated.follow, 1); + assert.deepEqual(evidence.retreated.peerPet, evidence.before.peerPet); + assert((await owner.page.request.post(url + '/test-deadline')).ok()); + evidence.afterDeadline = await server(); + assert.equal(evidence.afterDeadline.targetHealth, evidence.before.targetHealth); + assert.equal(evidence.afterDeadline.fighting, 0); + assert(!owner.events.some(event => event.sequence > sequence && event.direction === 'framereceived' && + ['46002f16', '5c654b28'].includes(event.opcode))); + + // Ordinary movement proves the retreat controller remains usable. + const start = owner.local().position; + await owner.hold('KeyW', 'owner moves away from the attack checkpoint', state => owner.local(state).position[2] > start[2] + 4); + await owner.wait('retreated pet follows', () => Math.hypot(...actor(owner, 1000001).position.map((value, axis) => + value - owner.local().position[axis])) < 2.2); + evidence.final = await server(); + assert.equal(evidence.final.targetHealth, evidence.before.targetHealth); + assert.equal(evidence.final.ownerNano, 25); + assert.equal(evidence.final.peerNano, 25); + assert.deepEqual(evidence.final.peerPet, evidence.before.peerPet); + + // Wait also cancels a pending swing and then holds while its owner moves. + assert((await owner.page.request.post(url + '/test-attack')).ok()); + await Promise.all(games.map(game => game.wait('second held attack installed', () => actor(game, 1000001).combatTarget === 2))); + const waitSequence = owner.sequence; + await owner.key('Enter'); + await owner.page.keyboard.type('/pet wait'); + await owner.key('Enter'); + await owner.wait('actual wait command', () => owner.events.some(event => event.sequence > waitSequence && + event.direction === 'framesent' && event.opcode === '6b333303')); + const waitRequest = owner.events.find(event => event.sequence > waitSequence && event.direction === 'framesent' && event.opcode === '6b333303'); + evidence.waitCommand = [29, 33, 37, 41, 45].map(offset => Buffer.from(waitRequest.hex, 'hex').readUInt32BE(offset)); + assert.deepEqual(evidence.waitCommand, [4, 0, 1009, 0, 0]); + await Promise.all(games.map(game => game.wait('wait stops the owned fight', () => actor(game, 1000001).combatTarget === 0))); + evidence.waited = await server(); + assert.equal(evidence.waited.fighting, 0); + assert.equal(evidence.waited.follow, 0); + assert((await owner.page.request.post(url + '/test-deadline')).ok()); + const departure = owner.local().position; + await owner.hold('KeyW', 'owner leaves the waiting pet', state => owner.local(state).position[2] > departure[2] + 2); + evidence.waitFinal = await server(); + assert.deepEqual(evidence.waitFinal.petPosition, evidence.waited.petPosition); + assert.equal(evidence.waitFinal.targetHealth, evidence.before.targetHealth); + assert.deepEqual(evidence.waitFinal.peerPet, evidence.before.peerPet); + assert(!owner.events.some(event => event.sequence > waitSequence && event.direction === 'framereceived' && + ['46002f16', '5c654b28'].includes(event.opcode))); + for (const game of games) { + assert.deepEqual(game.errors, []); + assert.equal(game.dropped, 0); + } + console.log('PASS: native behind/wait cancel held attacks; behind follows and wait holds, with peer/ownership/cost preserved'); +} 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(); } +}