Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions phaser-asteroids/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ gameplay; this folder is self-contained and does not touch it.

## Run it

For necessary gameplay/feature checks, `npm run test:feature -- combat ranked-input` builds once
and runs only those suites. After changing test scripts alone, `npm run test:feature -- --no-build combat`
can reuse that build. Rebuild after source or asset changes. See [focused testing and timings](docs/test-performance.md).
Minor cosmetic UI edits use the existing Vite server and only relevant focused checks; two minutes is the ceiling.

For physical Android ranked testing against local Worker/D1, use the opt-in [LAN startup and S25 checklist](../docs/android-lan-testing.md).

Requires Node.js 20.19+ or 22.12+ (Vite 8's requirement; developed on Node 22.14).
Expand Down
77 changes: 77 additions & 0 deletions phaser-asteroids/docs/test-performance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Focused developer testing

Minor UI edits: make the smallest change, inspect through the existing Vite server, and run a focused
TypeScript check only when useful. Two minutes is a ceiling, not a target. No production builds or
browser/unit sweeps for cosmetic changes. GitHub Actions retains its normal checks when shipping is requested.

For gameplay mechanics, choose the existing tests that exercise the affected behavior:

```sh
npm test -- tests/combat.test.ts # substitute the relevant existing Vitest file
npm run test:feature -- combat # existing combat browser suite, fresh production build
npm run test:feature -- combat ranked-input # both suites, one build
npm run test:feature -- --no-build combat # reuse dist after test-script-only changes
```

`--no-build` is explicit: rebuild after changing source, public assets, environment variables or build
configuration. The default always runs the existing `npm run build`, including TypeScript and the Node
replay build. Existing named test commands, release/deployment checks and security gates are unchanged.
The feature command accepts explicit suite names only; no default broad sweep, retries or ignored failures.
It stops at the first failed suite. Each child command has a ten-minute limit; exceeding it is a failure.
Longer legacy suites can still use their existing commands. Run from `phaser-asteroids/`.

Available names: `smoke`, `keyboard`, `combat`, `coop`, `gamepad`, `touch`, `music`, `menu`,
`mobile-entry`, `pages`, `replay`, `ranked`, `ranked-ui`, `ranked-input`, `worker`.
For a mobile-entry feature, select `mobile-entry`; this already covers PLAY, PRACTICE, touch readiness,
error paths and desktop entry. It is unnecessary for a cosmetic label edit.

Scoring, replay verification, authentication, persistence and security changes require explicit risk
identification and appropriate focused/integration checks. Production replay checks continue to use real
runs and verification. This change does not replace or recertify the release process.

## Measured comparison (2026-10-23)

Windows, Node, installed Chromium 155, headless SwiftShader. Same source/build and existing assertion
sets; sequential suites without competing test processes. One before/after pair, not a statistical benchmark.
Times include process startup/cleanup and exclude builds unless stated.

| Test | Before | After | Checks |
| --- | ---: | ---: | ---: |
| Combat browser | 58.711 s | 47.906 s | 39/39 both |
| Ranked input, real Worker/D1 | 50.221 s | 28.274 s | 22/22 both |

Initial build stages: TypeScript 0.649 s, frontend 3.604 s, Node replay 0.324 s (4.577 s total,
excluding npm wrapper overhead). Each additional selected suite previously repeated these stages through
its build-first alias. The new batch runs that unchanged build command once.

Combat's measured browser-check body was 56.604 s before and 46.935 s after. Preview and Chromium
startup together were 0.489 s before. Ranked input bootstrap was D1 migration 9.837 s, Worker 1.929 s,
preview 0.344 s and Chromium 0.229 s. After, those were 2.561 s, 1.432 s, 0.331 s and 0.171 s.
The faster D1 migration reflects warm caches/host variation, not a migration optimization. Do not attribute
the entire ranked-input reduction to the code changes or extrapolate these results to unmeasured suites.

Raw phase timings and PASS output are retained locally under ignored `scripts/.smoke-output/narrow-*`.
Set `TEST_TIMINGS=1` for optional phase diagnostics on standalone combat/ranked suites; the batch prints
timings by default. No full suite was run for this work.

A final `npm run test:feature -- combat ranked-input` invocation verified the new command itself:
one build (1.628 s), combat 49.420 s (39/39), ranked input 25.045 s (22/22). This second after sample
confirms the direction of the change, while also showing ordinary host/cache variation. Work stopped
within the announced 20-minute budget; no retries or further browser runs were needed.

## Kept changes and limits

- Wait for real collision consumption, UFO destruction, armor damage, pause/resume and restarted simulation
readiness in combat instead of arbitrary padding. All 39 assertions remain, including exactly-once events.
- Observe the real menu input lock and animation-frame consumption for focused ranked-input taps and title
readiness. The production lock, clock and input behavior are never altered.
- Preserve natural UFO spawn timing, projectile/laser observation windows, held-input durations, shield grace,
combo/banner expiry, retry delay, pause stability and the eight-second performance sample.
- Terminate the owned Wrangler/preview process tree on Windows to avoid orphaned workerd instances.
- Keep per-suite Chromium and empty D1 databases. Subsecond browser startup does not justify pooling;
different Worker settings/state make sharing more complex. No existing Vite server is stopped or replaced.

Remaining costs: actual simulation/performance observation windows, page/asset initialization in isolated
browser contexts, screenshots and real D1 migrations. Assertions and isolation remain more valuable than
removing these costs. No full-release speedup is claimed. The broader unfinished experiment remains stashed;
its release runner, fingerprinting, worker-count tuning and unrelated fixture fixes were not restored.
1 change: 1 addition & 0 deletions phaser-asteroids/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"preview:lan": "vite preview --host",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:feature": "node scripts/test-feature.mjs",
"test:replay:browser": "npm run build && node scripts/replay-browser.mjs",
"benchmark:replay": "npm run build && node scripts/benchmark-replay.mjs",
"test:browser": "npm run build && node scripts/smoke.mjs",
Expand Down
32 changes: 17 additions & 15 deletions phaser-asteroids/scripts/combat.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import http from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright-core';
import { timed } from './lib/testTiming.mjs';

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const outDir = path.join(root, 'scripts', '.smoke-output');
Expand Down Expand Up @@ -67,14 +68,14 @@ process.on('exit', stopServer);
let browser;
let browserVersion = '?';
try {
await waitForServer();
browser = await chromium.launch({
await timed('preview startup', waitForServer);
browser = await timed('Chromium startup', () => chromium.launch({
executablePath: findChrome(),
headless: true,
args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'],
});
}));
browserVersion = browser.version();
await run(browser);
await timed('combat browser checks', () => run(browser));
} finally {
await browser?.close();
stopServer();
Expand Down Expand Up @@ -110,6 +111,7 @@ async function run(browser) {
keys: g.sound.sounds.map((s) => s.key) }; })()`);
const keyTap = async (key, ms = 60) => (await page.keyboard.down(key), await sleep(ms), await page.keyboard.up(key));
const evalSim = (body) => page.evaluate(`(() => { const s = ${S}.sim; ${body} })()`);
const waitSim = (condition) => page.waitForFunction(`(() => { const s = ${S}.sim; return ${condition}; })()`, null, { timeout: 5000 });
/** Stops asteroids and the UFO schedule and clears the field, so a scenario starts from a known state. */
const quiet = () =>
evalSim(`s.spawner.spawnTimer = -1e9; s.ufoSpawner.enabled = false; s.asteroids.length = 0; s.shots.length = 0;
Expand Down Expand Up @@ -140,7 +142,7 @@ async function run(browser) {
await page.waitForFunction(() => window.__game?.scene.isActive('StartScene'), null, { timeout: 20000 });
await page.keyboard.press('Space');
await page.waitForFunction(() => window.__game.scene.isActive('GameScene'), null, { timeout: 5000 });
await sleep(500);
await waitSim('s.time > 0');
const baseline = await page.evaluate(`({ blur: window.__game.events.listenerCount('blur'), hidden: window.__game.events.listenerCount('hidden') })`);
const baselineChildren = await page.evaluate(`${S}.children.list.length`);
// Counts the simulation events the scene hands to the audio, so 'exactly once' can be checked without racing the ship.
Expand Down Expand Up @@ -176,7 +178,7 @@ async function run(browser) {
await addUfo('large', 300, 200, true);
await addUfo('small', 950, 250, true);
await evalSim(`s.ufos.forEach((u) => { u.shootTimer = 0.3; });`);
await sleep(700);
await waitSim('s.ufoShots.length >= 1');
st = await sim();
check('a large and a small UFO are in play and have fired', st.ufos.length === 2 && st.ufoShots >= 1, JSON.stringify({ ufos: st.ufos.length, shots: st.ufoShots }));
await shot('ufos');
Expand All @@ -189,7 +191,7 @@ async function run(browser) {
await place(640, 360, 0);
const a0 = await audio();
await addUfoShot(640, 360);
await sleep(250);
await waitSim('s.ufoShots.length === 0');
st = await sim();
let a1 = await audio();
check('a UFO shot costs a life, sends the ship to the respawn point and plays one sound', st.lives === 2 && Math.abs(st.x - 320) < 20 && st.respawning && st.ufoShots === 0 && a1.played === a0.played + 1, JSON.stringify({ lives: st.lives, x: st.x, played: a1.played - a0.played }));
Expand All @@ -199,13 +201,13 @@ async function run(browser) {
await evalSim(`s.player.shieldActive = true;`);
const a2 = await audio();
await addUfoShot(640, 360);
await sleep(250);
await waitSim('s.ufoShots.length === 0');
st = await sim();
a1 = await audio();
check('a shield absorbs a UFO shot: no life lost, shield gone, no death sound', st.lives === 3 && !st.shield && a1.played === a2.played, JSON.stringify({ lives: st.lives, shield: st.shield, played: a1.played - a2.played }));
await evalSim(`s.player.isRespawning = true; s.player.respawnTimer = 5;`);
await addUfoShot(640, 360);
await sleep(250);
await waitSim('s.ufoShots.length === 0');
st = await sim();
check('a respawning (invulnerable) ship takes no damage from a UFO shot', st.lives === 3 && st.ufoShots === 0);
await evalSim(`s.player.isRespawning = false; s.player.respawnTimer = 0;`);
Expand All @@ -216,7 +218,7 @@ async function run(browser) {
await addUfo('small', 700, 360);
await resetEv();
await page.keyboard.down('Space');
await sleep(1500);
await waitSim('s.ufos.length === 0');
await page.keyboard.up('Space');
await sleep(200);
st = await sim();
Expand Down Expand Up @@ -250,7 +252,7 @@ async function run(browser) {
await quiet();
await place(640, 360, 0);
await addUfo('large', 660, 360);
await sleep(250);
await waitSim('s.player.lives === 2');
st = await sim();
check('touching a UFO without boosting costs a life; the UFO flies on', st.lives === 2 && st.ufos.length === 1);

Expand Down Expand Up @@ -350,7 +352,7 @@ async function run(browser) {
await place(60, 360, 270);
await addRock(400, 360, 20, 'armored');
await keyTap('Space', 40);
await sleep(1100);
await waitSim('s.asteroids[0]?.hitPoints === 1');
st = await sim();
check('the first hit on an armored rock is not a kill (no combo, no score)', st.combo === 0 && st.score === 0 && st.asteroids === 1, JSON.stringify({ combo: st.combo, score: st.score, rocks: st.asteroids }));

Expand All @@ -361,13 +363,13 @@ async function run(browser) {
await evalSim(`s.ufos[0].shootTimer = 0.2;`);
await sleep(900);
await keyTap('KeyP');
await sleep(200);
await page.waitForFunction(`${S}.paused`, null, { timeout: 5000 });
const pausedA = await sim();
await sleep(1200);
const pausedB = await sim();
check('pausing freezes UFOs, UFO shots and the clock', pausedA.paused && JSON.stringify(pausedA.ufos) === JSON.stringify(pausedB.ufos) && pausedA.ufoShots === pausedB.ufoShots && pausedA.time === pausedB.time, JSON.stringify({ a: pausedA.ufos[0], b: pausedB.ufos[0] }));
await keyTap('KeyP');
await sleep(500);
await waitSim(`!${S}.paused && s.time > ${pausedB.time} + 0.3`);
const resumed = await sim();
check('resuming moves them again', !resumed.paused && resumed.time > pausedB.time + 0.3 && JSON.stringify(resumed.ufos) !== JSON.stringify(pausedB.ufos));

Expand Down Expand Up @@ -434,7 +436,7 @@ async function run(browser) {
check(`game over #${round + 1} with UFOs on screen: banner and combo HUD are gone`, st.banner === null && !(await texts()).some((t) => /COMBO|KILLS/.test(t)), JSON.stringify(await texts()));
await page.waitForFunction(`${S}.sim.retryDelay === 0`, null, { timeout: 5000 });
await keyTap('KeyR');
await sleep(500);
await waitSim("s.phase === 'playing' && s.time > 0");
st = await sim();
const au = await audio();
check(`restart #${round + 1}: no UFOs, enemy shots, combo or banner left over; one music instance`, st.phase === 'playing' && st.ufos.length === 0 && st.ufoShots === 0 && st.combo === 0 && st.banner === null && st.lives === 3 && st.score === 0 && au.musicInstances === 1, JSON.stringify({ ufos: st.ufos.length, shots: st.ufoShots, combo: st.combo, music: au.musicInstances }));
Expand Down
17 changes: 17 additions & 0 deletions phaser-asteroids/scripts/lib/menuWaits.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Observe the real input lock; never advance the scene clock or unlock the menu.
export function waitTitleReady(page) {
return page.waitForFunction(() => {
const game = window.__game;
if (!game) return false;
if (game.scene.isActive('GameScene')) return true;
if (!game.scene.isActive('StartScene')) return false;
const controller = game.scene.getScene('StartScene').menu?.controller;
return controller?.snapshot().items.length > 0 && controller.clock() >= controller.lockUntil;
}, null, { timeout: 15000 });
}

export async function settleTitleInput(page) {
// Phaser consumes pointer/gamepad input on a frame, after the CDP command returns.
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))));
await waitTitleReady(page);
}
17 changes: 11 additions & 6 deletions phaser-asteroids/scripts/lib/rankedStack.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import os from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { chromium } from 'playwright-core';
import { timed } from './testTiming.mjs';
import { waitTitleReady } from './menuWaits.mjs';
import { stopTestProcess } from './stopTestProcess.mjs';

export const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
export const serverDir = path.join(root, 'server');
Expand Down Expand Up @@ -76,7 +79,9 @@ export class WorkerStack {
}

migrate() {
const start = performance.now();
const r = spawnSync(process.execPath, [wranglerBin, 'd1', 'migrations', 'apply', 'asteroids-leaderboard', '--local', '--persist-to', this.persist], { cwd: serverDir, env, encoding: 'utf8' });
if (process.env.TEST_TIMINGS) console.log(`TIME D1 migration: ${((performance.now() - start) / 1000).toFixed(3)}s`);
return { ok: r.status === 0, output: (r.stdout + r.stderr).slice(-400) };
}

Expand All @@ -86,11 +91,11 @@ export class WorkerStack {
this.proc = spawn(process.execPath, args, { cwd: serverDir, env, stdio: ['ignore', 'pipe', 'pipe'] });
this.proc.stdout.on('data', (d) => (this.log += d));
this.proc.stderr.on('data', (d) => (this.log += d));
await waitFor(`${this.API}/api/v1/health`);
await timed('Worker startup', () => waitFor(`${this.API}/api/v1/health`));
}

stop() {
this.proc?.kill();
stopTestProcess(this.proc);
this.proc = null;
}

Expand Down Expand Up @@ -127,14 +132,14 @@ export class WorkerStack {
export async function startGameAndBrowser(gamePort) {
const GAME = `http://127.0.0.1:${gamePort}/`;
const preview = spawn(process.execPath, [path.join(root, 'node_modules', 'vite', 'bin', 'vite.js'), 'preview', '--port', String(gamePort), '--strictPort', '--host', '127.0.0.1'], { cwd: root, stdio: 'ignore' });
await waitFor(GAME);
const browser = await chromium.launch({ executablePath: findChrome(), headless: true, args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] });
await timed('preview startup', () => waitFor(GAME));
const browser = await timed('Chromium startup', () => chromium.launch({ executablePath: findChrome(), headless: true, args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }));
return {
GAME,
browser,
async close() {
await browser.close().catch(() => undefined);
preview.kill();
stopTestProcess(preview);
},
};
}
Expand All @@ -153,7 +158,7 @@ export async function openTitle(context, GAME, { api, query = '' } = {}) {
if (api) q.set('api', api);
await page.goto(`${GAME}?${q}`);
await page.waitForFunction(() => window.__game?.scene.isActive('StartScene'), null, { timeout: 20000 });
await sleep(500);
await waitTitleReady(page);
return page;
}

Expand Down
11 changes: 11 additions & 0 deletions phaser-asteroids/scripts/lib/stopTestProcess.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { spawnSync } from 'node:child_process';

// Only call for a process spawned by this suite. Wrangler owns a workerd child.
export function stopTestProcess(child) {
if (!child?.pid || child.exitCode !== null || child.signalCode !== null) return;
if (process.platform === 'win32') {
const result = spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 10000 });
if (result.error) throw result.error;
if (result.status !== 0) throw new Error(`Could not stop test process tree ${child.pid}`);
} else child.kill();
}
8 changes: 8 additions & 0 deletions phaser-asteroids/scripts/lib/testTiming.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Optional wall-clock diagnostics; no changes to test execution or assertions.
export async function timed(name, action) {
const start = performance.now();
try { return await action(); }
finally {
if (process.env.TEST_TIMINGS) console.log(`TIME ${name}: ${((performance.now() - start) / 1000).toFixed(3)}s`);
}
}
3 changes: 2 additions & 1 deletion phaser-asteroids/scripts/ranked-input.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Focused release-blocker checks. Real local Worker/D1 + production browser build; no legacy browser sweep.
import { clickItem, itemPoint, makeChecker, menuItems, openTitle, requireBuild, sceneTexts, sleep, startGameAndBrowser, WorkerStack } from './lib/rankedStack.mjs';
import { settleTitleInput } from './lib/menuWaits.mjs';

const PORT = 4416;
const worker = new WorkerStack({ port: 8796, gamePort: PORT, vars: { RANKED_TIME_LIMIT_SECONDS: '5' } });
Expand Down Expand Up @@ -28,7 +29,7 @@ try {
const tap = async (page, id) => {
const p = await itemPoint(page, id);
await page.touchscreen.tap(p.x, p.y);
await sleep(350);
await settleTitleInput(page);
};
const playing = (page) => page.waitForFunction(() => window.__game.scene.isActive('GameScene') && window.__ASTEROIDS_REPLAY__?.isVerified, null, { timeout: 15000 });
const storedOff = (page) => page.evaluate(() => localStorage.getItem('asteroids.inputMode') === 'desktop' && localStorage.getItem('asteroids.touchMovement') === 'pointToFly');
Expand Down
Loading
Loading