commit f46122a951111b0eeed9d6456c91524220d7e56c
parent 6f02cb8969e4808b4b5599ecdc86fcf8564f9d71
Author: anon <anon@example.com>
Date: Fri, 30 Oct 2026 07:51:47 +0000
Add general browser game testing harness
Diffstat:
17 files changed, 927 insertions(+), 5 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
@@ -8,6 +8,13 @@ Ensure cleanup also runs after failed tests, for example with `finally` blocks.
Clean up only instances started for your tests. Keep user-owned instances and
sessions explicitly requested for manual testing available until asked to stop.
+# Game testing
+
+Use the browser harness in `tools/client/game_test.mjs` for repeatable client
+testing; see `DEVELOPERS.md` under "Browser game testing". Prefer observed
+state transitions over fixed sleeps and ad hoc WASM memory probes. Keep real
+browser input coverage and check significant outcomes against server state.
+
# No server backward compatibility
Backward compatibility with earlier development versions of this server is
diff --git a/DEVELOPERS.md b/DEVELOPERS.md
@@ -431,12 +431,123 @@ comparison wrappers live in `tools/client/test_portable_*.py`; they use the loca
LLVM-MinGW compiler and WSL. Normal Linux tests do not require those wrappers.
See [tools/README.md](tools/README.md) for the smoke-test fixtures and tools.
-For client smoke tests, wait at least 30 seconds for world loading, open/close
+For client smoke tests, confirm world loading has completed, open/close
inventory (`I`) and map (`P`), move and turn, and inspect the rendered results.
+Use the browser harness below to wait for actual gameplay readiness.
On Windows, `F12` saves the game's own screenshot. The Linux harness captures
the completed game framebuffer through GDB, before desktop clipping. Static screenshots cannot exclude brief
rendering glitches. Keep test servers isolated from the user's saved characters.
+### Browser game testing
+
+`tools/client/game_test.mjs` provides a reusable Playwright driver for the
+maintained WASM client. It uses real browser mouse/keyboard input and read-only
+C snapshots taken after complete game frames. It does not grant items, edit
+stats, teleport characters, bypass native commands or inject protocol packets.
+Use it for remaining gameplay work instead of copying local memory-scanning
+scripts or adding sleeps after each action.
+
+Run its isolated browser regression with Node.js, Playwright and Chromium
+available (`node` on PATH, `playwright` installed locally or on NODE_PATH,
+`/usr/bin/chromium` installed):
+
+```sh
+AO_GAME_TEST=1 go test ./server -run '^TestBrowserGameHarness$' -count=1 -timeout=10m -v
+```
+
+This starts an HTTP server on a random loopback port and uses a disposable
+database and browser context. It exercises actor readiness, movement, targeting,
+posture, native world picking, UI input, resizing and reload reconstruction.
+The setup creates the scenario before connecting; all actions under test use
+normal browser input and the actual game/server protocol. The test closes its
+browser, streams and HTTP server even after failures. Reports and screenshots
+remain in `local/game-tests/<run>/`. On the Linux desktop, use the same working
+DISPLAY/XAUTHORITY environment as the other GPU browser checks.
+
+For a new scenario, attach before navigation so protocol capture includes the
+initial stream handshake:
+
+```js
+import {GameTest} from './game_test.mjs';
+
+const game = await GameTest.attach(page);
+try {
+ await page.goto(url);
+ await game.ready();
+ await game.key('F1');
+ await game.key('x');
+ await game.wait('sitting', state => game.local(state).stats[430] === 2);
+ await game.hold('w', 'cross the doorway', state =>
+ game.local(state).position[2] > doorwayZ);
+} finally {
+ try { await game.save(outputDirectory); }
+ finally { await browser.close(); }
+}
+```
+
+The driver provides:
+
+- `snapshot()` requests a fresh frame snapshot. `state` is the latest copy;
+ `local(state)` finds that snapshot's local character.
+- `wait(label, predicate, timeout)` repeatedly requests snapshots until the
+ condition holds, or fails with its label. The normal timeout is ten seconds;
+ `ready()` allows three minutes for initial loading and requires the current
+ connection's CharacterReady acknowledgement as well as the native actor and
+ inventory. Actor construction alone precedes usable game input. Predicates can
+ also inspect `game.events` for protocol or input evidence.
+- `key(key)` and `click(x, y, button)` wait for SDL consumption of press/release.
+ This confirms delivery, not gameplay success: follow them with an outcome
+ predicate. `hold(key, label, predicate, timeout)` releases the key in `finally`.
+- `point(x, y)` converts native render coordinates to browser coordinates;
+ `click` performs that conversion itself. This handles CSS scaling of the canvas.
+- `pick(type, id)` probes near the entity's projected position and returns native
+ coordinates only after the real game picker reports that identity. It moves
+ the browser pointer; it does not select or activate the entity. Position the
+ character/camera normally first, then click the returned point. Occlusion and
+ offscreen targets should fail visibly rather than bypass picking.
+- `save(directory)` writes `trace.json` and `screen.png`. Keep it inside a
+ `finally` with browser cleanup, as in the example.
+
+For burst input, focus-loss and timing regressions, drive Playwright's mouse
+and keyboard directly while keeping `GameTest` attached for observation. The
+helpers deliberately synchronize ordinary actions. Inspect saved screenshots
+for rendering and UI correctness as well as asserting underlying game state.
+
+Snapshots include frame number, render size, browser focus/visibility,
+selected/hovered identities, camera angles, visible native UI regions, and loaded
+characters, world items, machines
+and corpses. Actor fields include global position, rotation, playfield, deletion
+and combat state. Characters expose the 1024 raw stat values by native stat ID; these
+are the dictionary values, not a reconstruction of all effective modifiers.
+The local character includes inventory/equipment proxies with native slots,
+instance identities, QL, template endpoints and counts. Inventory slots 48..77
+correspond to server slots 64..93. Snapshots are copied on the game thread and
+published synchronously before C frees their buffers. Missing actors during
+zoning or removal are not proof of death or success.
+
+Tracing activates with the first snapshot request. It records browser delivery,
+SDL consumption, protocol packets in both directions, and observed stat,
+inventory and position changes. Packet capture reassembles fragmentation and
+deduplicates transport replay across reconnects. A received packet is evidence
+of receipt, not that native activation or server acceptance succeeded. Check the
+resulting client state and, for significant transactions, independent server
+state or persistence. The report retains 2048 events and 32 snapshots; `dropped`
+reports overwritten events. Save intermediate reports for long scenarios.
+
+Extend the C snapshot at `client/runtime/browser_testing.c` when a new scenario
+needs another native field. Keep object traversal on the game-owning thread;
+do not resume pointer scanning from page JavaScript. The production page does
+not request snapshots or collect test traces during normal play. Rebuild and
+publish the matching bundle with `make wasm -j8` after runtime changes.
+
+Focused harness checks, without starting the full game:
+
+```sh
+make -C client -f Makefile.wasm build/wasm/browser-testing.js
+node client/build/wasm/browser-testing.js
+node --test client/tests/*.mjs
+```
+
### Bronto Burger reference view
The approved Bronto Burger view in Omni-1 Entertainment faces northeast:
diff --git a/client/Makefile.wasm b/client/Makefile.wasm
@@ -5,6 +5,7 @@ CFLAGS := -Oz -flto=thin -fno-strict-aliasing -pthread -sSUPPORT_LONGJMP=wasm
PORT_FLAGS := -sUSE_SDL=2 -sUSE_FREETYPE=1 -sUSE_ZLIB=1
RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_imports.c runtime/linux_gdi.c runtime/linux_audio.c runtime/linux_music.c runtime/browser_audio.c runtime/linux_window.c runtime/linux_graphics.c runtime/gl_renderer.c runtime/linux_platform.c runtime/linux_diagnostics.c runtime/linux_sync.c runtime/linux_file.c runtime/linux_tls.c runtime/linux_thread.c runtime/linux_snapshot.c runtime/browser_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_exception.c runtime/guest_rtti.c runtime/guest_format.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c runtime/linux_path.c runtime/browser_host.c runtime/browser_loop.c runtime/browser_resolution.c runtime/browser_profile.c
GAME_SOURCES := $(wildcard game/*/*.c) game/dispatch.c
+RUNTIME_SOURCES += runtime/browser_testing.c
DATA_SOURCES := $(wildcard data/*.c)
VENDOR_SOURCES := $(wildcard vendor/msvcp60/source/*.c) $(wildcard vendor/ace/source/*.c)
OBJECTS := $(patsubst %.c,build/wasm/objects/%.o,$(GAME_SOURCES) $(DATA_SOURCES) $(VENDOR_SOURCES) $(RUNTIME_SOURCES))
@@ -12,6 +13,10 @@ OBJECTS := $(patsubst %.c,build/wasm/objects/%.o,$(GAME_SOURCES) $(DATA_SOURCES)
.DEFAULT_GOAL := all
include Makefile.portable
+build/wasm/browser-testing.js: tests/browser_testing.c runtime/browser_testing.c runtime/guest_memory.c runtime/recomp_state.c
+ @mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) $^ -o $@
+
# Compiler flag changes must rebuild objects as well as relink the client.
$(OBJECTS): Makefile.wasm
diff --git a/client/runtime/browser_host.js b/client/runtime/browser_host.js
@@ -1,4 +1,33 @@
addToLibrary({
+ $AOTest: {enabled: false, frame: 0},
+ ao_test_publish__deps: ['$AOTest', 'ao_test_publish_main'],
+ ao_test_publish: (json) => {
+ AOTest.enabled = true;
+ _ao_test_publish_main(json);
+ },
+ ao_test_publish_main__deps: ['$AOTest', '$UTF8ToString'],
+ ao_test_publish_main__proxy: 'sync',
+ ao_test_publish_main: (json) => {
+ AOTest.enabled = true;
+ Module.onTestSnapshot?.(JSON.parse(UTF8ToString(json)));
+ },
+ ao_test_input__deps: ['$AOTest', 'ao_test_event'],
+ ao_test_input: (stage, type, a, b, c, d) => {
+ if (AOTest.enabled) _ao_test_event(stage, type, a, b, c, d, AOTest.frame,
+ performance.timeOrigin + performance.now());
+ },
+ ao_test_event__proxy: 'async',
+ ao_test_event: (stage, type, a, b, c, d, frame, time) => {
+ const event = {kind: 'input', stage: stage ? 'consumed' : 'queued',
+ type, frame: stage ? frame : null, time};
+ if (type === 768 || type === 769)
+ Object.assign(event, {key: a, down: !!b, repeat: !!c, modifiers: d});
+ else if (type === 1025 || type === 1026)
+ Object.assign(event, {button: a, down: !!b, x: c, y: d});
+ else if (type === 32769) event.character = a;
+ else Object.assign(event, {x: a, y: b});
+ Module.onTestEvent?.(event);
+ },
emscripten_request_animation_frame_loop__deps: ['$callUserCallback', '$getWasmTableEntry'],
emscripten_request_animation_frame_loop: (callback, userData) => {
// Guest shutdown can exit from a frame; let Emscripten handle its exit sentinel.
@@ -93,8 +122,9 @@ addToLibrary({
Module.onTouchRegions?.({regions, screenWidth, screenHeight});
},
$AOFrameWait: 0,
- ao_frame_begin__deps: ['$AOProfile', '$AOFrameWait'],
+ ao_frame_begin__deps: ['$AOProfile', '$AOFrameWait', '$AOTest'],
ao_frame_begin: (timestamp) => {
+ ++AOTest.frame;
AOProfile.end('raf wait', AOFrameWait, AOProfile.detailed ? {
frame_time_us: (performance.timeOrigin + timestamp) * 1000
} : undefined);
diff --git a/client/runtime/browser_loop.c b/client/runtime/browser_loop.c
@@ -9,6 +9,7 @@ static uint32_t client_object, loop_stack, loop_frame;
void ao_frame_complete(void);
void ao_frame_begin(double timestamp);
void ao_game_closed(void);
+void browser_test_frame(void);
int browser_graphics_ready(void);
void sub_28002DA0(void);
void sub_28001000(void);
@@ -33,6 +34,7 @@ static bool browser_frame(double timestamp, void *argument)
return false;
}
assert(g_esp == loop_stack);
+ browser_test_frame();
ao_frame_complete();
return true;
}
diff --git a/client/runtime/browser_testing.c b/client/runtime/browser_testing.c
@@ -0,0 +1,143 @@
+#define _GNU_SOURCE
+#include "recomp_types.h"
+#include "linux_graphics.h"
+#include <stdatomic.h>
+#include <emscripten.h>
+
+static _Atomic unsigned requested;
+static unsigned frame;
+void ao_test_publish(const char *json);
+
+/* Requests cross threads; guest objects are read only after a complete game frame. */
+EMSCRIPTEN_KEEPALIVE void browser_test_request(void)
+{
+ atomic_store(&requested, 1);
+}
+
+static void vector(FILE *output, uint32_t address, unsigned count)
+{
+ fputc('[', output);
+ for (unsigned i = 0; i < count; ++i) {
+ float value;
+ memcpy(&value, (void *)ADDR(address + i * 4), 4);
+ if (i) fputc(',', output);
+ if (isfinite(value)) fprintf(output, "%.9g", value);
+ else fputs("null", output);
+ }
+ fputc(']', output);
+}
+
+static void inventory(FILE *output, uint32_t actor)
+{
+ uint32_t attributes = MEM32(actor + 0x150);
+ fputc('[', output);
+ if (attributes) {
+ /* KKR inventory proxies: flags/count, identity, QL and template endpoints. */
+ uint32_t slots = MEM32(MEM32(MEM32(attributes + 12) + 4) + 4);
+ unsigned count = 0;
+ for (unsigned slot = 0; slot < 78; ++slot) {
+ uint32_t item = MEM32(slots + slot * 4);
+ if (!item) continue;
+ if (count++) fputc(',', output);
+ fprintf(output, "{\"slot\":%u,\"type\":%u,\"id\":%u,\"quality\":%u,"
+ "\"templates\":[%u,%u],\"count\":%u}", slot, MEM32(item + 8),
+ MEM32(item + 12), MEM32(item + 16), MEM32(item + 20),
+ MEM32(item + 24), MEM32(item + 4) >> 16);
+ }
+ }
+ fputc(']', output);
+}
+
+static void actor(FILE *output, uint32_t object, uint32_t type, uint32_t id, int local)
+{
+ uint32_t vehicle = MEM32(object + 0x60);
+ fprintf(output, "{\"type\":%u,\"id\":%u,\"position\":", type, id);
+ /* Vehicle global coordinates differ from local coordinates inside scene sections. */
+ vector(output, vehicle + (MEM32(vehicle + 0x28) ? 0xe8 : 0x54), 3);
+ float position[3], screen[3];
+ memcpy(position, (void *)ADDR(vehicle + (MEM32(vehicle + 0x28) ? 0xe8 : 0x54)), sizeof(position));
+ fputs(",\"screenPosition\":", output);
+ if (linux_graphics_project(position, screen))
+ fprintf(output, "[%.9g,%.9g,%.9g]", screen[0], screen[1], screen[2]);
+ else fputs("null", output);
+ fputs(",\"rotation\":", output);
+ vector(output, vehicle + 0x7c, 4);
+ fprintf(output, ",\"playfield\":%u,\"deleting\":%s", MEM32(object + 0x78),
+ MEM8(object + 0x94) ? "true" : "false");
+ if (type == 50000) {
+ /* KKR's stat dictionary has 1024 raw entries; modifiers are separate. */
+ uint32_t stats = MEM32(MEM32(object + 0xe8) + 4);
+ uint32_t combat = MEM32(object + 0x16c);
+ fprintf(output, ",\"fighting\":%u,\"combatTarget\":%u,\"stats\":[",
+ combat ? MEM32(combat + 0x50) : 0, combat ? MEM32(combat + 0x5c) : 0);
+ for (unsigned i = 0; i < 1024; ++i) {
+ if (i) fputc(',', output);
+ fprintf(output, "%d", (int32_t)MEM32(stats + i * 4));
+ }
+ fputc(']', output);
+ if (local) {
+ fputs(",\"inventory\":", output);
+ inventory(output, object);
+ }
+ }
+ fputc('}', output);
+}
+
+static void directory(FILE *output, uint32_t node, uint32_t nil, uint32_t local, unsigned *count)
+{
+ if (node == nil) return;
+ directory(output, MEM32(node), nil, local, count);
+ uint32_t type = MEM32(node + 12), id = MEM32(node + 16), object = MEM32(node + 20);
+ if ((type == 50000 || type == 51005 || type == 51035 || type == 51050) && MEM32(object + 0x60)) {
+ if ((*count)++) fputc(',', output);
+ actor(output, object, type, id, object == local);
+ }
+ directory(output, MEM32(node + 8), nil, local, count);
+}
+
+void browser_test_frame(void)
+{
+ ++frame;
+ if (!atomic_exchange(&requested, 0)) return;
+
+ char *json;
+ size_t length;
+ FILE *output = open_memstream(&json, &length);
+ if (!output) abort();
+ uint32_t engine = MEM32(0x2d01752c), local = engine ? MEM32(engine + 0x88) : 0;
+ /* KKR sub_36072000 owns selection in the local actor's command helper. */
+ uint32_t commands = local ? MEM32(local + 0x168) : 0;
+ fprintf(output, "{\"frame\":%u,\"screen\":[%u,%u],\"localId\":%u,\"hover\":[%u,%u],\"selected\":[%u,%u],",
+ frame, MEM32(0x27048be8), MEM32(0x27048bec), local ? MEM32(local + 0x10) : 0,
+ engine ? MEM32(engine + 0xd8) : 0, engine ? MEM32(engine + 0xdc) : 0,
+ commands ? MEM32(commands + 0x70) : 0, commands ? MEM32(commands + 0x74) : 0);
+
+ uint32_t scene = MEM32(0x3806ec04), camera = scene ? MEM32(scene + 0x80) : 0;
+ fputs("\"camera\":", output);
+ if (camera) {
+ fprintf(output, "{\"firstPerson\":%s,\"angles\":", MEM32(camera + 0x19c) ? "false" : "true");
+ vector(output, camera + 0xc4, 2);
+ fputc('}', output);
+ } else fputs("null", output);
+
+ fputs(",\"actors\":[", output);
+ uint32_t actors = MEM32(0x3806c110);
+ unsigned count = 0;
+ if (actors) directory(output, MEM32(MEM32(actors + 4) + 4), MEM32(actors + 8), local, &count);
+ fputs("],\"regions\":[", output);
+ /* CCR sub_27010890 walks this list in native hit-test order. */
+ uint32_t module = MEM32(0x27048b7c);
+ uint32_t head = module && MEM8(module + 4) ? MEM32(MEM32(module) + 4) : 0;
+ count = 0;
+ for (uint32_t node = head ? MEM32(head) : 0; node && node != head; node = MEM32(node)) {
+ uint32_t region = MEM32(node + 8);
+ if (!MEM8(region + 8)) continue;
+ if (count++) fputc(',', output);
+ fprintf(output, "[%d,%d,%d,%d]", (int32_t)MEM32(region + 0x2c),
+ (int32_t)MEM32(region + 0x30), (int32_t)MEM32(region + 0x34), (int32_t)MEM32(region + 0x38));
+ }
+ fputs("]}", output);
+ if (fclose(output)) abort();
+ ao_test_publish(json);
+ free(json);
+}
diff --git a/client/runtime/linux_graphics.c b/client/runtime/linux_graphics.c
@@ -1933,6 +1933,20 @@ static void transform_vector(const float input[4], const float matrix[16], float
input[2] * matrix[8 + j] + input[3] * matrix[12 + j];
}
+int linux_graphics_project(const float position[3], float screen[3])
+{
+ if (!devices) return 0;
+ float camera[4], clip[4];
+ transform_vector((float[]){position[0], position[1], position[2], 1},
+ (const float *)devices->transforms[1], camera);
+ transform_vector(camera, (const float *)devices->transforms[2], clip);
+ if (clip[3] <= 0 || !isfinite(clip[3])) return 0;
+ screen[0] = devices->viewport[0] + (1 + clip[0] / clip[3]) * devices->viewport[2] / 2;
+ screen[1] = devices->viewport[1] + (1 - clip[1] / clip[3]) * devices->viewport[3] / 2;
+ screen[2] = clip[2] / clip[3];
+ return 1;
+}
+
static int projective_normal_matrix(const float matrix[16], float normal[9])
{
/* Invert the complete world/view matrix before taking its normal portion. */
diff --git a/client/runtime/linux_graphics.h b/client/runtime/linux_graphics.h
@@ -11,5 +11,6 @@ struct SDL_Window *linux_graphics_window(void);
struct SDL_DisplayMode;
int linux_graphics_display_mode(struct SDL_DisplayMode *mode);
int linux_graphics_resize(unsigned width, unsigned height, uint32_t drawing_surface);
+int linux_graphics_project(const float position[3], float screen[3]);
#endif
diff --git a/client/runtime/linux_window.c b/client/runtime/linux_window.c
@@ -6,6 +6,7 @@
#include <pthread.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
+void ao_test_input(int stage, int type, int a, int b, int c, int d);
#endif
/* Guest classes and handles contain no native pointers. SDL owns decoration. */
@@ -969,6 +970,7 @@ EMSCRIPTEN_KEEPALIVE void browser_input_key(int key, int down, int repeat, int m
event.key.keysym.mod = modifiers;
event.key.state = down ? SDL_PRESSED : SDL_RELEASED;
event.key.repeat = repeat;
+ ao_test_input(0, event.type, key, down, repeat, modifiers);
if (SDL_PushEvent(&event) != 1) abort();
}
@@ -977,6 +979,7 @@ EMSCRIPTEN_KEEPALIVE void browser_input_character(unsigned character)
/* Keep composed characters separate from message-loop wakeups. */
SDL_Event event = {.type = SDL_USEREVENT + 1};
event.user.code = character;
+ ao_test_input(0, event.type, character, 0, 0, 0);
if (SDL_PushEvent(&event) != 1) abort();
}
@@ -985,6 +988,7 @@ EMSCRIPTEN_KEEPALIVE void browser_input_motion(int x, int y)
SDL_Event event = {.type = SDL_MOUSEMOTION};
event.motion.which = SDL_TOUCH_MOUSEID;
event.motion.x = x; event.motion.y = y;
+ ao_test_input(0, event.type, x, y, 0, 0);
if (SDL_PushEvent(&event) != 1) abort();
}
@@ -995,6 +999,7 @@ EMSCRIPTEN_KEEPALIVE void browser_input_button(unsigned button, int down, int x,
event.button.button = button;
event.button.state = down ? SDL_PRESSED : SDL_RELEASED;
event.button.x = x; event.button.y = y;
+ ao_test_input(0, event.type, button, down, x, y);
if (SDL_PushEvent(&event) != 1) abort();
}
@@ -1012,6 +1017,16 @@ static void process_event(const SDL_Event *event)
{
if (!client.handle) return;
#ifdef __EMSCRIPTEN__
+ if (event->type == SDL_KEYDOWN || event->type == SDL_KEYUP)
+ ao_test_input(1, event->type, event->key.keysym.sym, event->key.state,
+ event->key.repeat, event->key.keysym.mod);
+ else if (event->type == SDL_MOUSEBUTTONDOWN || event->type == SDL_MOUSEBUTTONUP)
+ ao_test_input(1, event->type, event->button.button, event->button.state,
+ event->button.x, event->button.y);
+ else if (event->type == SDL_MOUSEMOTION)
+ ao_test_input(1, event->type, event->motion.x, event->motion.y, 0, 0);
+ else if (event->type == SDL_USEREVENT + 1)
+ ao_test_input(1, event->type, event->user.code, 0, 0, 0);
/* HTML input supplies composed text; physical keys use TranslateMessage. */
if (event->type == SDL_USEREVENT + 1) {
queue_message(client.handle, 0x102, event->user.code, 1, 0, 0);
diff --git a/client/tests/browser_loop.c b/client/tests/browser_loop.c
@@ -22,6 +22,7 @@ void ao_frame_begin(double timestamp)
previous = timestamp;
}
void ao_frame_complete(void) { ++completed; }
+void browser_test_frame(void) { assert(frames == completed + 1); }
void ao_game_closed(void) { ++closed; }
void sub_28002DA0(void)
diff --git a/client/tests/browser_profile.mjs b/client/tests/browser_profile.mjs
@@ -205,6 +205,7 @@ async function frameCallbackTimestampPreservesPacing() {
vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context);
context.AOProfile = library.$AOProfile;
vm.runInContext(fs.readFileSync(new URL('../runtime/browser_host.js', import.meta.url), 'utf8'), context);
+ context.AOTest = library.$AOTest;
assert.equal(library.ao_frame_complete(), undefined);
now = 180;
diff --git a/client/tests/browser_testing.c b/client/tests/browser_testing.c
@@ -0,0 +1,92 @@
+#include "recomp_types.h"
+#include <assert.h>
+
+void browser_test_request(void);
+void browser_test_frame(void);
+static unsigned publications;
+static char *snapshot;
+
+void ao_test_publish(const char *json)
+{
+ free(snapshot);
+ snapshot = strdup(json);
+ ++publications;
+}
+
+int linux_graphics_project(const float position[3], float screen[3])
+{
+ memcpy(screen, position, 12);
+ return 1;
+}
+
+static void snapshot_copies_native_state_without_changing_guest_registers(void)
+{
+ guest_map("test engine", 0x2d010000, 0x10000);
+ guest_map("test UI", 0x27040000, 0x10000);
+ guest_map("test directory", 0x38060000, 0x10000);
+ guest_map("test objects", 0x50000000, 0x10000);
+ MEM32(0x2d01752c) = 0x50000000;
+ MEM32(0x50000088) = 0x50001000;
+ MEM32(0x500000d8) = 51050;
+ MEM32(0x500000dc) = 99;
+ MEM32(0x27048be8) = 1024;
+ MEM32(0x27048bec) = 768;
+ MEM32(0x3806c110) = 0x50000200;
+ MEM32(0x50000204) = 0x50000300;
+ MEM32(0x50000208) = 0x50000400;
+ MEM32(0x50000304) = 0x50000500;
+ memcpy((void *)ADDR(0x50000500), (uint32_t[]){0x50000400, 0, 0x50000400, 50000, 7, 0x50001000}, 24);
+ MEM32(0x50001010) = 7;
+ MEM32(0x50001060) = 0x50002000;
+ MEM32(0x50001078) = 705;
+ MEM32(0x500010e8) = 0x50003000;
+ MEM32(0x50003004) = 0x50004000;
+ MEM32(0x50001150) = 0x50006000;
+ MEM32(0x50001168) = 0x50008000;
+ MEM32(0x50008070) = 50000;
+ MEM32(0x50008074) = 9;
+ MEM32(0x5000600c) = 0x50006100;
+ MEM32(0x50006104) = 0x50006200;
+ MEM32(0x50006204) = 0x50006300;
+ MEM32(0x50006300 + 48 * 4) = 0x50007000;
+ memcpy((void *)ADDR(0x50007000), (uint32_t[]){0, 3 << 16, 51005, 25, 1, 25812, 25812, 0}, 32);
+ memcpy((void *)ADDR(0x50002054), (float[]){10, 20, 30}, 12);
+ g_eax = 123;
+ g_esp = 456;
+
+ browser_test_frame();
+ assert(publications == 0);
+ browser_test_request();
+ browser_test_frame();
+
+ assert(publications == 1);
+ assert(strstr(snapshot, "\"frame\":2"));
+ assert(strstr(snapshot, "\"localId\":7"));
+ assert(strstr(snapshot, "\"position\":[10,20,30]"));
+ assert(strstr(snapshot, "\"hover\":[51050,99]"));
+ assert(strstr(snapshot, "\"selected\":[50000,9]"));
+ assert(strstr(snapshot, "\"slot\":48,\"type\":51005,\"id\":25,\"quality\":1,\"templates\":[25812,25812],\"count\":3"));
+ assert(g_eax == 123 && g_esp == 456);
+}
+
+static void snapshots_observe_directory_clear_and_new_frames(void)
+{
+ MEM32(0x50000304) = 0x50000400;
+ MEM32(0x50000088) = 0;
+
+ browser_test_request();
+ browser_test_frame();
+
+ assert(publications == 2);
+ assert(strstr(snapshot, "\"frame\":3"));
+ assert(strstr(snapshot, "\"localId\":0"));
+ assert(strstr(snapshot, "\"actors\":[]"));
+}
+
+int main(void)
+{
+ snapshot_copies_native_state_without_changing_guest_registers();
+ snapshots_observe_directory_clear_and_new_frames();
+ free(snapshot);
+ puts("PASS: frame snapshots, native inventory, directory clearing and guest state preservation");
+}
diff --git a/client/tests/game_test.mjs b/client/tests/game_test.mjs
@@ -0,0 +1,103 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import fs from 'node:fs';
+import vm from 'node:vm';
+import {GameTest, PacketStream} from '../../tools/client/game_test.mjs';
+
+function frame(offset, bytes) {
+ const result = Buffer.alloc(8 + bytes.length);
+ result.writeBigUInt64BE(BigInt(offset));
+ bytes.copy(result, 8);
+ return result;
+}
+
+test('packets survive fragmented headers, padding and replayed stream bytes', () => {
+ const stream = new PacketStream();
+ const first = Buffer.alloc(24);
+ first.writeUInt16BE(21, 6);
+ first.writeUInt32BE(0x52526858, 16);
+ first[20] = 1;
+ const second = Buffer.alloc(20);
+ second.writeUInt16BE(20, 6);
+ second.writeUInt32BE(0x2252445f, 16);
+
+ const partial = stream.receive(frame(0, first.subarray(0, 5)));
+ const completed = stream.receive(frame(0, Buffer.concat([first, second.subarray(0, 10)])));
+ const replayed = stream.receive(frame(0, first));
+ const next = stream.receive(frame(24, second));
+
+ assert.deepEqual(partial, []);
+ assert.deepEqual(completed, [first.subarray(0, 21)]);
+ assert.deepEqual(replayed, []);
+ assert.deepEqual(next, [second]);
+ assert.equal(stream.pending.length, 0);
+});
+
+test('stream gaps fail instead of silently losing protocol evidence', () => {
+ const stream = new PacketStream();
+
+ const receive = () => stream.receive(frame(1, Buffer.alloc(20)));
+
+ assert.throws(receive, /Gap in browser stream/);
+});
+
+test('input tracing stays inactive until the first requested snapshot', () => {
+ let library;
+ const inputs = [], snapshots = [];
+ const context = vm.createContext({addToLibrary: value => { library = value; },
+ Module: {onTestEvent: event => inputs.push(event), onTestSnapshot: value => snapshots.push(value)},
+ UTF8ToString: value => value, performance: {timeOrigin: 1000, now: () => 20}});
+ vm.runInContext(fs.readFileSync(new URL('../runtime/browser_host.js', import.meta.url), 'utf8'), context);
+ context.AOTest = library.$AOTest;
+ context._ao_test_event = library.ao_test_event;
+ context._ao_test_publish_main = library.ao_test_publish_main;
+
+ library.ao_test_input(1, 768, 119, 1, 0, 0);
+ const inactive = inputs.length;
+ library.ao_test_publish('{"frame":7}');
+ context.AOTest.frame = 8;
+ library.ao_test_input(1, 768, 119, 1, 0, 0);
+
+ assert.equal(inactive, 0);
+ assert.equal(snapshots[0].frame, 7);
+ assert.equal(inputs.length, 1);
+ assert.equal(inputs[0].stage, 'consumed');
+ assert.equal(inputs[0].frame, 8);
+ assert.equal(inputs[0].time, 1020);
+ assert.equal(inputs[0].key, 119);
+ assert.equal(inputs[0].down, true);
+});
+
+test('readiness waits past actor construction and ignores a previous connection acknowledgement', async () => {
+ const game = new GameTest();
+ game.navigation = 2;
+ game.worldStream = 'current';
+ game.page = {waitForFunction: async () => {}};
+ let samples = 0;
+ game.snapshot = async () => {
+ ++samples;
+ if (samples === 2) game.record({kind: 'packet', direction: 'framereceived', opcode: '570c2039', navigation: 2, stream: 'previous', actor: [50000, 7]});
+ if (samples === 3) game.record({kind: 'packet', direction: 'framereceived', opcode: '570c2039', navigation: 2, stream: 'current', actor: [50000, 8]});
+ if (samples === 4) game.record({kind: 'packet', direction: 'framereceived', opcode: '570c2039', navigation: 2, stream: 'current', actor: [50000, 7]});
+ return {frame: samples, localId: 7, screen: [1024, 768],
+ actors: [{type: 50000, id: 7, inventory: []}]};
+ };
+
+ const state = await game.ready();
+
+ assert.equal(samples, 4);
+ assert.equal(state.frame, 4);
+});
+
+test('a stalled game releases held keys and reports the unmet condition', async () => {
+ const game = new GameTest();
+ const keys = [];
+ game.page = {bringToFront: async () => {}, locator: () => ({focus: async () => {}}),
+ keyboard: {down: async key => keys.push(['down', key]), up: async key => keys.push(['up', key])}};
+ game.snapshot = async () => { throw Object.assign(new Error('frame stalled'), {name: 'TimeoutError'}); };
+
+ const action = game.hold('KeyW', 'crossing the doorway', () => false);
+
+ await assert.rejects(action, /Timed out waiting for crossing the doorway/);
+ assert.deepEqual(keys, [['down', 'KeyW'], ['up', 'KeyW']]);
+});
diff --git a/server/browser_game_test.go b/server/browser_game_test.go
@@ -0,0 +1,79 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserGameHarness(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 to run the real WASM client in Chromium")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local", "game-tests", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ world.characters = make(map[uint32]*character)
+ world.mobileNPCs = nil
+ player := world.newCharacter()
+ player.playfield = 705
+ player.position = [3]float32{960, 16.5, 510}
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("game-harness")))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(player, 121567); !granted || err != nil {
+ t.Fatal(granted, err)
+ }
+ world.characters[1000000] = &character{id: 1000000, name: "Harness Leet", npc: true,
+ playfield: 705, position: [3]float32{960, 16.5, 498}, rotation: [4]float32{0, 0, 0, 1},
+ appearance: 229, monsterData: 17655, level: 1, health: 100}
+ 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, "sitting": player.sitting,
+ "items": player.inventory.Items, "position": player.position})
+ })
+ host := httptest.NewServer(mux)
+ defer host.Close()
+ defer func() {
+ world.mutex.Lock()
+ var streams []*browserStream
+ for _, stream := range world.browserStreams {
+ streams = append(streams, stream)
+ }
+ world.mutex.Unlock()
+ for _, stream := range streams {
+ stream.close()
+ }
+ }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute)
+ defer cancel()
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_game.mjs"), host.URL, output)
+ command.Dir = root
+ command.Stdout, command.Stderr = 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 player.sitting || player.position[2] < 510.5 || len(player.inventory.Items) != 1 {
+ t.Fatalf("browser controls did not produce their authoritative outcomes: sitting=%t position=%v inventory=%+v", player.sitting, player.position, player.inventory)
+ }
+}
diff --git a/tools/client/game_test.mjs b/tools/client/game_test.mjs
@@ -0,0 +1,254 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+
+// Reassemble protocol packets, independently of WebSocket fragmentation and replay.
+export class PacketStream {
+ offset = 0;
+ pending = Buffer.alloc(0);
+
+ receive(payload) {
+ if (!Buffer.isBuffer(payload)) return [];
+ assert(payload.length >= 8, 'Missing stream offset');
+ const offset = Number(payload.readBigUInt64BE());
+ assert(offset <= this.offset, 'Gap in browser stream');
+ const skip = this.offset - offset;
+ const bytes = payload.subarray(8 + skip);
+ this.offset += bytes.length;
+ this.pending = Buffer.concat([this.pending, bytes]);
+ const packets = [];
+ while (this.pending.length >= 8) {
+ const length = this.pending.readUInt16BE(6);
+ assert(length >= 20, 'Invalid game packet length');
+ const aligned = (length + 3) & ~3;
+ if (this.pending.length < aligned) break;
+ packets.push(this.pending.subarray(0, length));
+ this.pending = this.pending.subarray(aligned);
+ }
+ return packets;
+ }
+}
+
+export class GameTest {
+ events = [];
+ snapshots = [];
+ sequence = 0;
+ dropped = 0;
+ state = null;
+ streams = new Map();
+ navigation = 0;
+ worldStream = null;
+ readyActors = new Set();
+
+ static async attach(page) {
+ const game = new GameTest();
+ game.page = page;
+ await page.exposeFunction('aoTestEvent', event => game.record(event));
+ await page.addInitScript(() => {
+ // Capture browser delivery separately from the game's SDL consumption.
+ for (const type of ['keydown', 'keyup', 'mousedown', 'mouseup'])
+ window.addEventListener(type, event => window.aoTestEvent({kind: 'browser-input',
+ type, code: event.code, button: event.button, x: event.clientX, y: event.clientY,
+ time: performance.timeOrigin + performance.now()}), true);
+ });
+ page.on('framenavigated', frame => {
+ if (frame === page.mainFrame()) {
+ ++game.navigation;
+ game.worldStream = null;
+ game.readyActors.clear();
+ game.record({kind: 'navigation', url: frame.url()});
+ }
+ });
+ page.on('pageerror', error => game.record({kind: 'error', message: String(error)}));
+ page.on('console', message => {
+ if (message.type() === 'error' || message.type() === 'warning')
+ game.record({kind: 'console', level: message.type(), message: message.text()});
+ });
+ page.on('websocket', socket => {
+ if (!socket.url().endsWith('/browser-world')) return;
+ const navigation = game.navigation;
+ let streams, stream;
+ for (const direction of ['framesent', 'framereceived']) socket.on(direction, ({payload}) => {
+ try {
+ if (typeof payload === 'string') {
+ const handshake = JSON.parse(payload);
+ if (direction === 'framesent' && handshake.stream) {
+ stream = handshake.stream;
+ if (game.worldStream !== stream) game.readyActors.clear();
+ game.worldStream = stream;
+ streams = game.streams.get(handshake.stream);
+ if (!streams) {
+ streams = {framesent: new PacketStream(), framereceived: new PacketStream()};
+ game.streams.set(handshake.stream, streams);
+ }
+ }
+ return;
+ }
+ assert(streams, 'Game bytes arrived before stream handshake');
+ for (const packet of streams[direction].receive(payload)) {
+ const kind = packet.readUInt32BE(16).toString(16).padStart(8, '0');
+ const actor = packet.readUInt16BE(2) === 10 && packet.length >= 28 ?
+ [packet.readUInt32BE(20), packet.readUInt32BE(24)] : null;
+ game.record({kind: 'packet', direction, navigation, stream, actor, opcode: kind, hex: packet.toString('hex')});
+ }
+ } catch (error) {
+ game.record({kind: 'error', message: String(error)});
+ }
+ });
+ });
+ return game;
+ }
+
+ record(event) {
+ // Transport reconnects retain readiness; a new game stream must acknowledge again.
+ if (event.kind === 'packet' && event.direction === 'framereceived' && event.opcode === '570c2039' &&
+ event.navigation === this.navigation && event.stream === this.worldStream && event.actor?.[0] === 50000)
+ this.readyActors.add(event.actor[1]);
+ this.events.push({time: Date.now(), navigation: this.navigation, ...event, sequence: ++this.sequence});
+ if (this.events.length > 2048) { this.events.shift(); ++this.dropped; }
+ }
+
+ async snapshot(timeout = 10000) {
+ const frame = await this.page.evaluate(() => {
+ if (!Module.onTestSnapshot) {
+ Module.onTestSnapshot = snapshot => {
+ window.aoTestSnapshot = {...snapshot, browser: {focused: document.hasFocus(),
+ visibility: document.visibilityState, activeElement: document.activeElement?.id}};
+ };
+ Module.onTestEvent = event => window.aoTestEvent(event);
+ }
+ const frame = window.aoTestSnapshot?.frame ?? -1;
+ Module._browser_test_request();
+ return frame;
+ });
+ await this.page.waitForFunction(frame => window.aoTestSnapshot?.frame > frame, frame,
+ {timeout});
+ const previous = this.state;
+ this.state = await this.page.evaluate(() => window.aoTestSnapshot);
+ this.state.navigation = this.navigation;
+ const before = previous && this.local(previous), after = this.local();
+ if (before && after) {
+ const stats = after.stats.map((value, id) => [id, before.stats[id], value])
+ .filter(([, before, after]) => before !== after);
+ if (stats.length) this.record({kind: 'stats', frame: this.state.frame, changes: stats});
+ if (JSON.stringify(before.inventory) !== JSON.stringify(after.inventory))
+ this.record({kind: 'inventory', frame: this.state.frame, items: after.inventory});
+ if (JSON.stringify(before.position) !== JSON.stringify(after.position))
+ this.record({kind: 'position', frame: this.state.frame, position: after.position});
+ }
+ this.snapshots.push(this.state);
+ if (this.snapshots.length > 32) this.snapshots.shift();
+ return this.state;
+ }
+
+ async wait(label, predicate, timeout = 10000) {
+ const deadline = Date.now() + timeout;
+ do {
+ let state;
+ try { state = await this.snapshot(Math.max(1, deadline - Date.now())); }
+ catch (error) {
+ if (error.name !== 'TimeoutError') throw error;
+ break;
+ }
+ const error = this.events.find(event => event.kind === 'error');
+ assert(!error, error?.message);
+ if (predicate(state)) return state;
+ } while (Date.now() < deadline);
+ throw new Error(`Timed out waiting for ${label}; client frame ${this.state?.frame ?? 'none'}`);
+ }
+
+ async ready() {
+ await this.page.waitForFunction(() => typeof Module !== 'undefined' &&
+ typeof Module._browser_test_request === 'function', null, {timeout: 180000});
+ return this.wait('local actor and inventory', state => {
+ const actor = state.actors.find(actor => actor.type === 50000 && actor.id === state.localId);
+ return actor && !actor.deleting && actor.inventory && state.screen[0] > 0 &&
+ this.worldStream !== null && this.readyActors.has(state.localId);
+ }, 180000);
+ }
+
+ local(state = this.state) {
+ return state.actors.find(actor => actor.type === 50000 && actor.id === state.localId);
+ }
+
+ // Separate down/up by consumed game frames, without guessing a click duration.
+ async key(key) {
+ this.record({kind: 'action', action: 'key', key});
+ await this.page.bringToFront();
+ await this.page.locator('#canvas').focus();
+ let sequence = this.sequence;
+ await this.page.keyboard.down(key);
+ try {
+ await this.wait('key down consumed', () => this.events.some(event =>
+ event.sequence > sequence && event.kind === 'input' && event.stage === 'consumed' && event.type === 768));
+ } finally {
+ sequence = this.sequence;
+ await this.page.keyboard.up(key);
+ }
+ await this.wait('key up consumed', () => this.events.some(event =>
+ event.sequence > sequence && event.kind === 'input' && event.stage === 'consumed' && event.type === 769));
+ }
+
+ async hold(key, label, predicate, timeout = 10000) {
+ this.record({kind: 'action', action: 'hold', key, label});
+ await this.page.bringToFront();
+ await this.page.locator('#canvas').focus();
+ await this.page.keyboard.down(key);
+ let sequence;
+ try { await this.wait(label, predicate, timeout); }
+ finally {
+ sequence = this.sequence;
+ await this.page.keyboard.up(key);
+ }
+ return this.wait('held key released', () => this.events.some(event =>
+ event.sequence > sequence && event.kind === 'input' && event.stage === 'consumed' && event.type === 769));
+ }
+
+ async point(x, y) {
+ const bounds = await this.page.locator('#canvas').boundingBox();
+ assert(bounds, 'Canvas has no bounds');
+ return {x: bounds.x + Math.round(x) * bounds.width / this.state.screen[0],
+ y: bounds.y + Math.round(y) * bounds.height / this.state.screen[1]};
+ }
+
+ async click(x, y, button = 'left') {
+ const point = await this.point(x, y);
+ this.record({kind: 'action', action: 'click', x, y, button});
+ await this.page.mouse.move(point.x, point.y);
+ await this.snapshot();
+ let sequence = this.sequence;
+ await this.page.mouse.down({button});
+ try {
+ await this.wait('mouse down consumed', () => this.events.some(event =>
+ event.sequence > sequence && event.kind === 'input' && event.stage === 'consumed' && event.type === 1025));
+ } finally {
+ sequence = this.sequence;
+ await this.page.mouse.up({button});
+ }
+ await this.wait('mouse up consumed', () => this.events.some(event =>
+ event.sequence > sequence && event.kind === 'input' && event.stage === 'consumed' && event.type === 1026));
+ }
+
+ async pick(type, id) {
+ this.record({kind: 'action', action: 'pick', type, id});
+ const state = await this.snapshot();
+ const actor = state.actors.find(actor => actor.type === type && actor.id === id);
+ assert(actor?.screenPosition, `Entity ${type}:${id} is not projected`);
+ const [x, y, depth] = actor.screenPosition;
+ assert(depth >= 0 && depth <= 1, `Entity ${type}:${id} is outside the camera depth range`);
+ // Distant models can be only a few pixels wide around their projected origin.
+ for (const dy of [0, -8, -20, -40, 8, 20]) for (const dx of [0, -1, 1, -8, 8, -20, 20]) {
+ const point = await this.point(x + dx, y + dy);
+ await this.page.mouse.move(point.x, point.y);
+ const sample = await this.snapshot();
+ if (sample.hover[0] === type && sample.hover[1] === id) return [x + dx, y + dy];
+ }
+ throw new Error(`Native picker did not hit ${type}:${id} near its screen position`);
+ }
+
+ async save(directory) {
+ await fs.mkdir(directory, {recursive: true});
+ await fs.writeFile(`${directory}/trace.json`, JSON.stringify({url: this.page.url(),
+ dropped: this.dropped, events: this.events, snapshots: this.snapshots}, null, 2) + '\n');
+ await this.page.screenshot({path: `${directory}/screen.png`});
+ }
+}
diff --git a/tools/client/publish_wasm.py b/tools/client/publish_wasm.py
@@ -40,10 +40,10 @@ page = page.replace('__WASM_DECODED_BYTES__', str((source / 'game.wasm').stat().
(staging / 'index.html').write_text(page)
# Record the exact inputs and published bytes, including uncommitted source edits.
-inputs = subprocess.check_output(
- ['git', 'ls-files', 'client', 'tools/client/build_wasm_dependencies.py',
+inputs = sorted(subprocess.check_output(
+ ['git', 'ls-files', '--cached', '--others', '--exclude-standard', 'client', 'tools/client/build_wasm_dependencies.py',
'tools/client/resolve_guest_calls.py', 'tools/client/share_guest_bodies.py'], cwd=root
-).decode().splitlines()
+).decode().splitlines())
digest = hashlib.sha256()
for name in inputs:
digest.update(name.encode() + b'\0')
diff --git a/tools/client/test_game.mjs b/tools/client/test_game.mjs
@@ -0,0 +1,64 @@
+import assert from 'node:assert/strict';
+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);
+assert(url && output, 'Run through TestBrowserGameHarness');
+const browser = await chromium.launch({executablePath: '/usr/bin/chromium',
+ args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage']});
+let game;
+try {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'game-harness', url}]);
+ const page = await context.newPage();
+ game = await GameTest.attach(page);
+
+ await page.goto(url);
+ await game.ready();
+ assert.equal(game.state.localId, 1);
+ assert.equal(game.local().inventory[0].templates[0], 121567);
+ const inventory = game.local().inventory;
+ console.log('PASS: coherent actor, stats and inventory readiness');
+
+ const z = game.local().position[2];
+ await game.hold('KeyS', 'backward movement', state => game.local(state).position[2] < z - 0.5);
+ await game.hold('KeyW', 'forward movement', state => game.local(state).position[2] > z + 0.5);
+ await game.key('F1');
+ await game.wait('self selection', state => state.selected[0] === 50000 && state.selected[1] === 1);
+ await game.key('x');
+ await game.wait('sitting posture', state => game.local(state).stats[430] === 2);
+ const posture = await (await context.request.get(url + '/test-state')).json();
+ assert.equal(posture.sitting, true);
+ await game.key('x');
+ await game.wait('standing posture', state => game.local(state).stats[430] !== 2);
+ await assert.rejects(game.hold('w', 'intentional timeout', () => false, 1), /intentional timeout/);
+ await game.snapshot();
+ console.log('PASS: real movement, targeting and posture controls');
+
+ if (!game.state.camera.firstPerson) await game.key('F8');
+ await game.hold('KeyD', 'turn toward the open street', state => Math.abs(game.local(state).rotation[3]) < 0.05);
+ const [x, y] = await game.pick(50000, 1000000);
+ await game.click(x, y);
+ await game.wait('native world selection', state => state.selected[0] === 50000 && state.selected[1] === 1000000);
+ console.log('PASS: projected coordinates, native picking and mouse input');
+
+ await game.key('i');
+ await game.save(output + '/inventory');
+ await game.key('i');
+ await page.setViewportSize({width: 800, height: 600});
+ await game.wait('native resolution change', state => state.screen[0] === 800 && state.screen[1] === 600);
+ const position = game.local().position;
+ await page.reload();
+ await game.ready();
+
+ assert.deepEqual(game.local().inventory, inventory);
+ assert(Math.abs(game.local().position[2] - position[2]) < 0.2);
+ assert(game.events.some(event => event.kind === 'packet' && event.direction === 'framesent'));
+ assert(game.events.some(event => event.kind === 'packet' && event.direction === 'framereceived'));
+ assert(game.events.some(event => event.kind === 'input' && event.stage === 'consumed'));
+ console.log('PASS: viewport changes, reload reconstruction and bidirectional tracing');
+} finally {
+ try { if (game) await game.save(output); }
+ finally { await browser.close(); }
+}