towerdef/e2e/scenarios/11-coop-chaos.js
Claude 28502984ec Co-op robustness, audio/a11y, new towers and enemies, Uplink rebalance
Co-op (QA'd with two to three real browsers, TCP-proxy chaos scenarios):
- partner's tower changes are never dropped after a render stall or snapshot burst
- half-open connections show "reconnecting" in ~6 s instead of 45-65 s
- upgrade and next-wave are idempotent (stale commands refused), restart message,
  promoted host gets Play again, failed joins never kill a live game, listener leaks

Audio / keyboard / a11y:
- one Audio element per track, fade/stinger supersede tokens, play() retry on the
  next gesture, 5 s fallback to the synth, mute works everywhere, dialogs with
  role/aria-modal/focus handling, accessible names for sound/speed/pause

New content:
- enemies: Daemon (healer), Proxy (regenerating shield), Botnet (flyer swarm);
  waves weave them in from wave 9 (waves 1-8 unchanged)
- towers: Sandbox (stun pulse), Load Balancer (fire-rate aura); hotkeys 1-9
- glyphs/shapes, stun/heal effects, gallery e2e that pixel-checks every kind

Orbital Uplink rebalanced after playtesting (was affordable by wave ~6 and buyable
in bulk from boss rewards): 1500 credits, upgrades 1200/2000/3200, and every Uplink
already owned makes the next one 25% dearer to buy AND to upgrade (each tower
remembers its multiplier, carried in the tower list as a 9th field). Shared
TD.priceFor/upgradePrice so the UI shows exactly what the sim charges.

Also: tablet/foldable viewports in the layout matrix (tolerant colour check),
docs (README tower/enemy tables, PROTOCOL shield/stun/pm encodings, NEXT roadmap).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
2026-10-10 21:18:43 +00:00

282 lines
21 KiB
JavaScript

'use strict';
/*
* Co-op under stress: two real browsers against real servers (one per scenario, started here on random ports), plus a small
* order-preserving TCP proxy that can freeze a connection (half-open: bytes swallowed, nothing closed) or delay what the server sends.
*
* stall a page that stops rendering for 1.5 s does not lose the partner's towers (coop-1, code-1)
* freeze a half-open connection shows "reconnecting" within seconds and rejoins on a new socket (coop-2)
* endhost the host leaves while the end screen is up: the promoted guest gets Play again (coop-3, code-11)
* lobby a failed join from the menu keeps the live game; a double click makes one room; Back cancels a pending join (coop-4, code-4, code-3)
* stale Upgrade / Next wave pressed from a stale view are refused, silently (coop-5)
* restart after a server restart: the message says so; stale resume / reload rejoin tell the user (coop-6, code-24)
*/
const net = require('net');
const { createServer } = require('../../server');
const FILTER = require('../../public/js/sim.js').TOWERS.filter;
const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function until(fn, ms, what) { const t0 = Date.now(); for (;;) { try { const v = await fn(); if (v) return v; } catch (e) { /* retry */ } if (Date.now() - t0 > ms) throw new Error('TIMEOUT: ' + what); await sleep(40); } }
const newServer = (opts) => createServer(Object.assign({ port: 0, host: '127.0.0.1', log: () => {}, pingMs: 0 }, opts));
const urlOf = (port) => 'http://127.0.0.1:' + port + '/';
// TCP proxy in front of the server. delay: ms added to what the server sends (order kept). freeze(): every connection that exists now
// swallows all bytes in both directions and closes nothing, which is what a dead Wi-Fi / NAT path looks like to both ends.
function startProxy(targetPort) {
const st = { delay: 0, accepted: 0, pairs: new Set() };
const server = net.createServer((c) => {
st.accepted++;
const u = net.connect(targetPort, '127.0.0.1');
const pair = { c, u, frozen: false };
st.pairs.add(pair);
const pipe = (from, to, toClient) => {
const q = []; let pumping = false;
const pump = () => {
pumping = false;
while (q.length && q[0].at <= Date.now()) { const it = q.shift(); if (!pair.frozen && !to.destroyed) to.write(it.d); }
if (q.length) { pumping = true; setTimeout(pump, Math.max(1, q[0].at - Date.now())); }
};
from.on('data', (d) => {
if (pair.frozen) return;
q.push({ at: Date.now() + (toClient ? st.delay : 0), d });
if (!pumping) pump();
});
from.on('close', () => { st.pairs.delete(pair); if (!pair.frozen) to.destroy(); });
from.on('error', () => {});
};
pipe(c, u, false); pipe(u, c, true);
});
const ready = new Promise((res) => server.listen(0, '127.0.0.1', res));
st.ready = ready.then(() => { st.port = server.address().port; return st; });
st.freeze = () => { for (const p of st.pairs) p.frozen = true; };
st.close = () => { for (const p of st.pairs) { p.c.destroy(); p.u.destroy(); } server.close(); };
return st;
}
function maker(browser, errors) {
return async (name, opts, seed) => {
const ctx = await browser.newContext(opts || { viewport: { width: 1100, height: 700 } });
if (seed !== false) await ctx.addInitScript(() => { try { localStorage.setItem('nw.helped', 'true'); } catch (e) { /* ignore */ } }); // the first-run help is tested in 04-coop
const page = await ctx.newPage();
page.on('pageerror', (e) => errors.push('[' + name + '] pageerror: ' + e.message));
page.on('console', (m) => { if (m.type() === 'error' && !/WebSocket|ERR_|Failed to load/.test(m.text())) errors.push('[' + name + '] console.error: ' + m.text()); });
return { ctx, page, name };
};
}
const joined = (P) => P.page.evaluate(() => NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined');
async function hostRoom(P, url, name) {
await P.page.goto(url); await sleep(250);
await P.page.click('#btnCoop'); await P.page.fill('#inName', name || 'Alice'); await P.page.click('#btnCreate');
await until(() => joined(P), 6000, 'host joined');
return P.page.evaluate(() => NW.app.ctrl.room);
}
async function guestJoin(P, url, room, name) {
await P.page.goto(url + '?room=' + room); await sleep(250);
await P.page.fill('#inName', name || 'Bob'); await P.page.click('#btnJoin');
await until(() => joined(P), 6000, 'guest joined');
}
const send = (P, cmd) => P.page.evaluate((c) => NW.app.ctrl.send(c), cmd);
const cellPt = async (P, cx, cy) => { const box = await P.page.locator('#board').boundingBox(); const r = await P.page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); return { x: box.x + r.x, y: box.y + r.y }; };
const vis = (P, sel) => P.page.evaluate((s) => { const e = document.querySelector(s); return !!e && !e.hidden && e.getClientRects().length > 0; }, sel);
// ------------------------------------------------------------------------------------------------ coop-1
async function stall(mk) {
console.log('--- stall: B stops rendering for 1.5 s while A builds');
const srv = await newServer(), url = urlOf(srv.port);
const A = await mk('A'), B = await mk('B');
try {
const room = await hostRoom(A, url); await guestJoin(B, url, room);
const R = srv.rooms.get(room);
await B.page.evaluate(() => { window.__held = []; window.__raf = window.requestAnimationFrame.bind(window); window.requestAnimationFrame = (cb) => { window.__held.push(cb); return 0; }; });
await sleep(300);
for (const [x, y] of [[14, 3], [14, 4]]) { await send(A, { c: 'place', type: 'wall', x, y }); await sleep(60); }
await sleep(1500); // ~30 snapshots arrive while nothing is displayed; the buffer holds 10
await B.page.evaluate(() => { window.requestAnimationFrame = window.__raf; for (const cb of window.__held.splice(0)) cb(performance.now()); });
// no further tower change from here on: the old code stayed wrong until somebody built or sold something again
await until(() => B.page.evaluate(() => NW.app.ctrl.view.towers.length), 3000, 'B shows the walls');
await sleep(1200);
const b = await B.page.evaluate(() => ({ towers: NW.app.ctrl.view.towers.length, rev: NW.app.ctrl.rev, route: NW.app.ctrl.board.routeLen, gold: NW.app.ctrl.view.gold }));
assert(R.sim.towers.length === 2 && b.towers === 2, 'B shows both walls the partner built while it was stalled (server ' + R.sim.towers.length + ', B ' + b.towers + ')');
assert(b.rev === R.sim.rev, 'B\'s tower revision equals the server\'s (' + b.rev + ')');
assert(Math.abs(b.route - R.sim.board.routeLen) < 1e-6, 'B\'s mirrored board has the same route length as the server');
assert(b.gold === R.sim.gold, 'credits agree');
} finally { await A.ctx.close(); await B.ctx.close(); await srv.close(); }
}
// ------------------------------------------------------------------------------------------------ coop-2
async function freeze(mk) {
console.log('--- freeze: B\'s connection goes half-open');
const srv = await newServer(), px = startProxy(srv.port); await px.ready;
const A = await mk('A'), B = await mk('B');
try {
const room = await hostRoom(A, urlOf(srv.port)); await guestJoin(B, urlOf(px.port), room);
const R = srv.rooms.get(room);
await send(A, { c: 'place', type: 'wall', x: 14, y: 3 });
await until(() => B.page.evaluate(() => NW.app.ctrl.view.towers.length === 1), 3000, 'B sees the first wall');
await B.page.evaluate(() => { window.__ws1 = NW.app.ctrl.ws; });
const acc0 = px.accepted;
px.freeze(); const t0 = Date.now();
await send(A, { c: 'place', type: 'wall', x: 14, y: 4 }); // built while B is cut off
await until(() => B.page.evaluate(() => NW.app.ctrl.status === 'reconnecting' && !document.getElementById('reconnect').hidden), 9000, 'B shows the reconnecting overlay');
const tShown = Date.now() - t0;
assert(tShown < 8500, 'the overlay is up ' + (tShown / 1000).toFixed(1) + ' s after the path died (it used to take 45 to 65 s)');
await until(() => B.page.evaluate(() => NW.app.ctrl.status === 'joined' && NW.app.ctrl.ws !== window.__ws1 && document.getElementById('reconnect').hidden), 9000, 'B is back on a fresh socket');
const tBack = Date.now() - t0;
assert(tBack < 10000 && px.accepted > acc0, 'B rejoined on a new connection after ' + (tBack / 1000).toFixed(1) + ' s without waiting for the dead one to close');
await until(() => B.page.evaluate(() => NW.app.ctrl.view.towers.length === 2), 3000, 'B has the wall built while it was cut off');
assert(R.sim.towers.length === 2 && R.players.every((p) => p && p.conn), 'both players are online again in the same room and seats');
} finally { await A.ctx.close(); await B.ctx.close(); px.close(); await srv.close(); }
}
// ------------------------------------------------------------------------------------------------ coop-3
async function endhost(mk) {
console.log('--- endhost: the host leaves while the end screen is up');
const srv = await newServer(), url = urlOf(srv.port);
const A = await mk('A'), B = await mk('B', { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true });
try {
const room = await hostRoom(A, url); await guestJoin(B, url, room);
const R = srv.rooms.get(room);
R.sim.lives = 0; // the next tick is a breach
await until(() => Promise.all([A, B].map((P) => vis(P, '#end'))).then((v) => v[0] && v[1]), 5000, 'both see the end screen');
assert((await vis(A, '#btnAgain')) && !(await vis(A, '#endWait')), 'host: Play again is offered');
assert(!(await vis(B, '#btnAgain')) && (await vis(B, '#endWait')), 'guest: waits for the host');
await A.page.click('#btnEndMenu'); // the host goes to the menu: leaves the room
await until(() => B.page.evaluate(() => NW.app.ctrl.players.length === 1 && NW.app.ctrl.you.host), 4000, 'guest promoted');
await until(() => vis(B, '#btnAgain'), 2000, 'the promoted guest gets Play again');
assert(!(await vis(B, '#endWait')), 'and the "waiting for the host" text is gone');
await B.page.tap('#btnAgain');
await until(() => B.page.evaluate(() => NW.app.ctrl.view.state === 'playing' && document.getElementById('end').hidden), 3000, 'B starts a new game');
assert(R.sim.state === 'playing', 'the server runs a new game');
} finally { await A.ctx.close(); await B.ctx.close(); await srv.close(); }
}
// ------------------------------------------------------------------------------------------------ coop-4, code-4, code-3
async function lobby(mk) {
console.log('--- lobby: failed join, double click, cancelled join');
const srv = await newServer(), px = startProxy(srv.port); await px.ready;
const url = urlOf(srv.port);
const A = await mk('A'), B = await mk('B'), C = await mk('C'), D = await mk('D');
try {
// coop-4: a failed join from the in-game menu leaves the live game alone
const room = await hostRoom(A, url); await guestJoin(B, url, room);
const R = srv.rooms.get(room);
await A.page.click('#btnMenu'); await A.page.click('#btnCoop');
await A.page.fill('#inCode', 'ZZZZ'); await A.page.click('#btnJoin');
await until(() => A.page.evaluate(() => /does not exist/.test(document.getElementById('lobbyMsg').textContent)), 4000, 'the lobby says the room does not exist');
const a1 = await A.page.evaluate(() => ({ st: NW.app.ctrl.status, room: NW.app.ctrl.room, inGame: NW.app.inGame, ss: sessionStorage.getItem('nw.room'), ls: !!localStorage.getItem('nw.session'), joinOff: document.getElementById('btnJoin').disabled }));
assert(a1.st === 'joined' && a1.room === room && a1.inGame, 'A is still in the live game after the failed join');
assert(a1.ss === room && a1.ls, 'and its saved room is untouched');
assert(!a1.joinOff, 'Join is usable again');
await A.page.click('#btnLobbyBack');
await send(A, { c: 'place', type: 'wall', x: 14, y: 3 });
await until(() => B.page.evaluate(() => NW.app.ctrl.view.towers.length === 1), 3000, 'A can still build and B sees it');
assert(R.players.filter((p) => p && p.conn).length === 2, 'the partner never saw A leave');
// code-4: a double click on Create room makes one room
const rooms0 = srv.rooms.size;
await C.page.goto(url); await sleep(250);
await C.page.click('#btnCoop'); await C.page.fill('#inName', 'Dbl');
await C.page.dblclick('#btnCreate');
await until(() => joined(C), 5000, 'C joined');
await sleep(600);
assert(srv.rooms.size === rooms0 + 1, 'one room was created, not two (' + srv.rooms.size + ' rooms)');
// code-3: Back and Play solo while a join is still connecting: the late answer must not take the solo game over
await D.page.goto(urlOf(px.port)); await sleep(300);
px.delay = 1200;
await D.page.click('#btnCoop'); await D.page.fill('#inName', 'Late'); await D.page.click('#btnCreate');
await sleep(300);
assert(await D.page.evaluate(() => document.getElementById('btnCreate').disabled), 'Create is disabled while connecting');
await D.page.click('#btnLobbyBack');
await D.page.click('#btnSolo');
for (const [x, y] of [[12, 3], [12, 4], [12, 5]]) await send(D, { c: 'place', type: 'wall', x, y });
await sleep(4000); // the server's answer (and its 1.2 s delay, twice) is long over
const d = await D.page.evaluate(() => ({ kind: NW.app.ctrl.kind, towers: NW.app.ctrl.view.towers.length, inGame: NW.app.inGame }));
assert(d.kind === 'local' && d.towers === 3 && d.inGame, 'the solo game was not replaced by the late co-op join');
assert(srv.rooms.size === rooms0 + 1, 'and the room the cancelled join had created is gone again');
px.delay = 0;
} finally { for (const P of [A, B, C, D]) await P.ctx.close(); px.close(); await srv.close(); }
}
// ------------------------------------------------------------------------------------------------ coop-5
async function stale(mk) {
console.log('--- stale: Upgrade / Next wave from a view that is behind');
const srv = await newServer(), px = startProxy(srv.port); await px.ready;
const A = await mk('A'), B = await mk('B');
try {
const room = await hostRoom(A, urlOf(srv.port)); await guestJoin(B, urlOf(px.port), room);
const R = srv.rooms.get(room);
R.sim.gold = 1000;
await send(A, { c: 'place', type: 'filter', x: 10, y: 8 });
const pt = await cellPt(B, 10, 8);
await until(() => B.page.evaluate(() => NW.app.ctrl.view.towers.length === 1 && NW.app.ctrl.view.gold === 975), 3000, 'B sees the turret');
await B.page.mouse.click(pt.x, pt.y); // B selects it
await until(() => B.page.evaluate(() => !!document.querySelector('#info [data-act="up"]:not([disabled])')), 2000, 'B has an enabled Upgrade button');
await B.page.evaluate(() => { window.__rej = []; NW.app.ctrl.on('reject', (r) => window.__rej.push(r.reason)); });
px.delay = 1800; // from now B\'s picture of the game is 1.8 s behind
await send(A, { c: 'upgrade', id: 1 }); // the partner upgrades it first...
await until(() => R.sim.towers[0].level === 2, 2000, 'the server upgraded it');
await B.page.click('#info [data-act="up"]'); // ...B still sees level 1 and presses Upgrade too
await send(A, { c: 'wave' });
await until(() => R.sim.wave === 1, 2000, 'wave 1 started');
await B.page.click('#btnWave'); // same with Next wave: B still sees wave 0
await until(() => B.page.evaluate(() => window.__rej.length >= 2), 6000, 'B got both rejections');
assert((await B.page.evaluate(() => window.__rej.join(','))) === 'stale,stale', 'both were refused as stale');
assert(R.sim.towers[0].level === 2 && R.sim.towers[0].spent === FILTER.levels[0].cost + FILTER.levels[1].cost, 'the turret was upgraded once and paid for once (level ' + R.sim.towers[0].level + ', spent ' + R.sim.towers[0].spent + ')');
assert(R.sim.wave === 1, 'one wave started, not two');
assert((await B.page.evaluate(() => document.querySelectorAll('#toasts .toast.bad').length)) === 0, 'and B was not shown an error for it');
px.delay = 0;
} finally { await A.ctx.close(); await B.ctx.close(); px.close(); await srv.close(); }
}
// ------------------------------------------------------------------------------------------------ coop-6, code-24
async function restart(mk) {
console.log('--- restart: the server restarts, stale saved rooms');
let srv = await newServer(); const port = srv.port, url = urlOf(port);
const A = await mk('A'), B = await mk('B'), C = await mk('C'), D = await mk('D');
try {
const room = await hostRoom(A, url); await guestJoin(B, url, room);
await srv.close();
await until(() => A.page.evaluate(() => NW.app.ctrl.status === 'reconnecting' && !document.getElementById('reconnect').hidden), 4000, 'A shows the reconnecting overlay');
await sleep(1200);
srv = await newServer({ port }); // back up, with no rooms
for (const P of [A, B]) await until(() => P.page.evaluate(() => NW.app.ctrl.kind === 'local' && /server restarted/.test(document.getElementById('lobbyMsg').textContent)), 14000, P.name + ' is told the server restarted');
const msg = await A.page.evaluate(() => document.getElementById('lobbyMsg').textContent);
assert(msg === 'The server restarted, your game was lost.', 'the message: ' + msg);
assert(await A.page.evaluate(() => localStorage.getItem('nw.session') === null && sessionStorage.getItem('nw.room') === null), 'the dead room is forgotten (no Resume for it)');
// code-24: a reload that tries to slip back into a room that is gone says so
await C.ctx.addInitScript(() => { try { if (!sessionStorage.getItem('seeded')) { sessionStorage.setItem('seeded', '1'); sessionStorage.setItem('nw.room', 'ZZZZ'); localStorage.setItem('nw.session', JSON.stringify({ pid: 'abcdefgh12345678', room: 'ZZZZ', name: 'Cee', ts: Date.now() })); } } catch (e) { /* ignore */ } });
await C.page.goto(url);
await until(() => C.page.evaluate(() => [...document.querySelectorAll('#toasts .toast')].some((t) => /gone/.test(t.textContent))), 5000, 'C is told the game is gone');
const c = await C.page.evaluate(() => ({ resume: document.getElementById('btnResume').hidden, ls: localStorage.getItem('nw.session'), ss: sessionStorage.getItem('nw.room'), kind: NW.app.ctrl.kind }));
assert(c.resume && c.ls === null && c.ss === null && c.kind === 'local', 'and the stale Resume button / saved room are gone');
// code-24: "Resume co-op game" for a room that is gone
await D.ctx.addInitScript(() => { try { if (!localStorage.getItem('seeded')) { localStorage.setItem('seeded', '1'); localStorage.setItem('nw.session', JSON.stringify({ pid: 'abcdefgh87654321', room: 'YYYY', name: 'Dee', ts: Date.now() })); } } catch (e) { /* ignore */ } });
await D.page.goto(url); await sleep(300);
assert(await vis(D, '#btnResume'), 'D is offered Resume');
await D.page.click('#btnResume');
await until(() => D.page.evaluate(() => [...document.querySelectorAll('#toasts .toast')].some((t) => /gone/.test(t.textContent))), 5000, 'D is told the game is gone');
assert(!(await vis(D, '#btnResume')), 'the stale Resume button is removed');
// coop-6: running out of retries does not throw the saved room away (the seat is held for a minute): Resume stays
const room2 = await hostRoom(C, url, 'Cee');
await C.page.evaluate(() => NW.app.ctrl._die('lost', 'Lost connection to the server.'));
await until(() => C.page.evaluate(() => NW.app.ctrl.kind === 'local' && /Lost connection/.test(document.getElementById('lobbyMsg').textContent)), 3000, 'C is told the connection was lost');
assert(await C.page.evaluate(([r]) => sessionStorage.getItem('nw.room') === r && !!localStorage.getItem('nw.session'), [room2]), 'the saved room is kept after "lost connection"');
await C.page.click('#btnLobbyBack');
assert(await vis(C, '#btnResume'), 'and Resume is offered on the menu');
} finally { for (const P of [A, B, C, D]) await P.ctx.close(); await srv.close(); }
}
module.exports = async function ({ browser }) {
const errors = [];
const mk = maker(browser, errors);
const only = process.env.COOP_CHAOS || '';
const all = { stall, freeze, endhost, lobby, stale, restart };
for (const [name, fn] of Object.entries(all)) { if (!only || only.split(',').includes(name)) await fn(mk); }
if (errors.length) throw new Error('console errors:\n' + errors.join('\n'));
console.log('no console errors');
};