Files
OpenFrontIO/tests/matchmaking/e2e.mjs
T
3a5fba2e12 Add 2v2 ranked matchmaking (#4596)
## Description:

Implements 2v2 ranked matchmaking end-to-end against the matchmaking
API's 2v2 queues (API PR #419): core team pinning, the server's second
checkin loop and game creation, and the client UI.

## Core — deterministic team pinning

The matcher's assignment specifies exactly who plays with whom (`teams:
[[a,d],[b,c]]`), but team assignment previously only did clan/friend
balancing and could scramble the ELO-balanced split.

- `PlayerSchema`/`PlayerInfo` gain an optional **`teamIndex`** — a
server-stamped index into the game's team list, part of `GameStartInfo`
so it's identical on every client (same category as `clanTag`/`friends`,
which already feed deterministic team assignment).
- `assignTeams` honors pins **unconditionally** — before clan/friend
grouping and past `maxTeamSize` (the matcher's balancing is
authoritative) — and seeds the counts that balancing of any unpinned
players sees. Pinned players still participate in the friend graph, so
an unpinned friend is pulled toward a pinned player's team.
- publicIds never enter core: the game server resolves publicId →
teamIndex per client at game start.

## Server

- **One checkin long-poll per mode.** Both loops send `mode` explicitly
(the API deployed ahead of the client, so no omit-for-back-compat
needed).
- **`get2v2Config()`**: Team mode, `playerTeams: 2`, `maxPlayers: 4`,
always-compact map, donations enabled (matching public team games),
`rankedType: "2v2"` (the API's 2v2 ingestion has shipped; `RankedType`
gains `TwoVTwo`).
- **The assignment payload is now used** (it was previously discarded):
`players` → `allowedPublicIds` so only the matched accounts can take the
slots (also hardens 1v1), and `teams` → `teamIndex` stamps at game
start. A malformed assignment logs a warning and falls back to creating
the game without pins rather than stranding matched players.
- The 3-clients-per-IP cap on public games applies to matchmade games
too (an allowlist doesn't stop one person multi-tabbing multiple
accounts). It is now skipped in dev, where local testing (multi-tab, the
4-player e2e) is inherently same-IP — matching the existing dev/prod
gating of Turnstile and the duplicate-account kick.

## Client

- Ranked modal's 2v2 card is enabled; it passes the mode through
`open-matchmaking` (dispatchers without a detail — homepage button,
requeue URL — still mean 1v1).
- Matchmaking modal joins with `&mode=1v1`/`&mode=2v2`, shows a 2v2
title (`matchmaking_modal.title_2v2` in en.json), and shows the real 2v2
ELO from the new `leaderboard.twoVtwo` field in `/users/@me` (the ranked
modal's 2v2 card does too).
- WinModal shows requeue for any ranked game and carries the mode back
into the right queue (`/?requeue=2v2`).
- 2v2 ranked stats surface in the player stats tree (labeled via
`player_stats_tree.ranked_2v2`).

## Harnesses (`tests/matchmaking/`)

- Contained: the fake server captures the `mode` query param; asserts
each queue sends its mode explicitly. **10/10.**
- E2E: `MM_MODE=2v2` runs four real browser players through the real
local worker's 2v2 queue and rides the flow into the started game.
Asserts same gameId for all four, the 2v2 config, allowlist admission,
and a **deterministic 2 vs 2 in-game split read from each client's
GameView** (the software-WebGL gate is spoofed in test pages only).
**8/8.** 1v1 e2e still **6/6.**

## Verification

- `npm test`: 2,053 tests pass, including 7 new (6 `assignTeams` pinning
unit tests + a full-game pinned-split test through `setup()`).
- `npx tsc --noEmit`, ESLint clean.
- Live e2e against a local `wrangler dev` API worker: 1v1 (6/6) and 2v2
(8/8) as above.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


## Please complete the following:

- [x] I have added screenshots for all UI updates
- [x] I process any text displayed to the user through translateText()
and I've added it to the en.json file
- [x] I have added relevant tests to the test directory

(UI changes — the ranked modal's 1v1/2v2 cards — were verified with
before/after screenshots in the live app during development.)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 15:22:52 -07:00

285 lines
8.7 KiB
JavaScript

// End-to-end matchmaking integration test. Requires the REAL stack:
// - the API worker running on localhost:8787 (wrangler dev in the API repo)
// - the dev app running on localhost:9000 (`npm run dev` — its game server
// long-polls the worker's /matchmaking/checkin out of the box in dev)
//
// Drives real browser players through the real matchmaking modal: all join
// the queue on the worker, the matcher groups them, the local game server
// receives the checkin assignment and creates the game, and every client
// gets into it (which also proves the allowedPublicIds allowlist accepts
// the matched players).
//
// Run: npm run test:matchmaking:e2e (1v1: two players)
// MM_MODE=2v2 npm run test:matchmaking:e2e (2v2: four players,
// also verifies the in-game team split is 2 vs 2 and identical on
// every client)
import {
gotoHome,
launch,
} from "../../.claude/skills/run-openfront/driver.mjs";
import { isUp, makeChecker, waitFor } from "./util.mjs";
const MODE = process.env.MM_MODE === "2v2" ? "2v2" : "1v1";
const PLAYER_COUNT = MODE === "2v2" ? 4 : 2;
if (!(await isUp("http://localhost:9000"))) {
console.error(
"Dev app is not running on :9000 — start it with `npm run dev`.",
);
process.exit(1);
}
if (!(await isUp("http://localhost:8787"))) {
console.error(
"API worker is not running on :8787 — start it with `wrangler dev` in the API repo.",
);
process.exit(1);
}
// Throttle rAF like the driver does for in-game work: software WebGL frames
// are expensive and an unthrottled loop starves the sim/timers.
const rafThrottle = (interval) => {
let last = 0;
window.requestAnimationFrame = (cb) => {
const now = performance.now();
const wait = Math.max(0, interval - (now - last));
return setTimeout(() => {
last = performance.now();
cb(last);
}, wait);
};
window.cancelAnimationFrame = (id) => clearTimeout(id);
};
// The app refuses software WebGL (initGL.ts gates on the renderer string and
// failIfMajorPerformanceCaveat), but headless browsers only have SwiftShader.
// We're verifying matchmaking/teams, not rendering, so let the context
// through in the test pages.
const glSpoof = () => {
const origGetContext = HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.getContext = function (type, attrs) {
if (type === "webgl2" && attrs) {
const rest = { ...attrs };
delete rest.failIfMajorPerformanceCaveat;
return origGetContext.call(this, type, rest);
}
return origGetContext.call(this, type, attrs);
};
const origGetParameter = WebGL2RenderingContext.prototype.getParameter;
WebGL2RenderingContext.prototype.getParameter = function (p) {
if (p === 0x9246 /* UNMASKED_RENDERER_WEBGL */) {
return "Harness Spoofed GPU";
}
return origGetParameter.call(this, p);
};
};
const { browser } = await launch();
const pages = [];
for (let i = 0; i < PLAYER_COUNT; i++) {
// One context per player: separate localStorage = distinct players.
const context = await browser.newContext({
viewport: { width: 1400, height: 1000 },
});
await context.addInitScript(rafThrottle, 2000);
await context.addInitScript(glSpoof);
pages.push(await context.newPage());
}
const consoles = pages.map(() => []);
pages.forEach((p, i) => p.on("console", (msg) => consoles[i].push(msg.text())));
const dumpConsoles = () => {
pages.forEach((_, i) => {
console.error(`\n--- player ${i + 1} console (last 25 lines) ---`);
for (const line of consoles[i].slice(-25)) console.error(line);
});
console.error(
"\nHints: close code 1008 means the worker rejected the play token; " +
"no assignment at all usually means the worker isn't accepting the " +
"game server's checkin (x-api-key) or the matcher isn't running.",
);
};
// The dev game server runs NUM_WORKERS=2; the worker path is derived from
// the gameId, so just probe both.
const fetchGameInfo = async (gameId) => {
for (const worker of ["w0", "w1"]) {
const res = await fetch(
`http://localhost:9000/${worker}/api/game/${gameId}`,
);
if (res.ok) return res.json();
}
return null;
};
const c = makeChecker();
try {
for (const p of pages) {
await gotoHome(p);
await p.evaluate((mode) => {
window.__joinLobby = null;
document.addEventListener(
"join-lobby",
(e) => (window.__joinLobby = e.detail ?? {}),
);
const el = document.querySelector("matchmaking-modal");
el.mode = mode;
el.connect();
}, MODE);
}
console.log(`${PLAYER_COUNT} players queued (${MODE})...`);
const gameIdOf = (p) =>
p.evaluate(() => document.querySelector("matchmaking-modal").gameID);
let gameIds;
try {
gameIds = await waitFor(
async () => {
const ids = await Promise.all(pages.map(gameIdOf));
return ids.every(Boolean) ? ids : null;
},
{
timeoutMs: 90000,
intervalMs: 1000,
label: "every player to receive a match-assignment",
},
);
} catch (err) {
dumpConsoles();
throw err;
}
const gameId = gameIds[0];
c.check(
`all ${PLAYER_COUNT} players received an assignment (${gameId})`,
true,
);
c.check(
"all players got the same gameId",
gameIds.every((id) => id === gameId),
);
// The modal polls the game server until the assigned game exists, then
// dispatches join-lobby — this proves the checkin/creation side worked.
try {
await waitFor(
async () => {
const details = await Promise.all(
pages.map((p) => p.evaluate(() => window.__joinLobby)),
);
return details.every((d) => d?.gameID === gameId);
},
{
timeoutMs: 45000,
intervalMs: 1000,
label: "every player to dispatch join-lobby for the created game",
},
);
c.check("game created on the game server", true);
} catch (err) {
dumpConsoles();
throw err;
}
// The game must carry the mode's config and admit exactly the matched
// players (allowedPublicIds).
const info = await fetchGameInfo(gameId);
if (MODE === "2v2") {
c.check(
"2v2 game config: Team mode, 2 teams, 4 max players, ranked 2v2",
info?.gameConfig?.gameMode === "Team" &&
info?.gameConfig?.playerTeams === 2 &&
info?.gameConfig?.maxPlayers === 4 &&
info?.gameConfig?.rankedType === "2v2",
);
} else {
c.check(
"1v1 game config: FFA, 2 max players",
info?.gameConfig?.gameMode === "Free For All" &&
info?.gameConfig?.maxPlayers === 2,
);
}
c.check(
`assignment allowlist has ${PLAYER_COUNT} publicIds`,
info?.gameConfig?.allowedPublicIds?.length === PLAYER_COUNT,
);
try {
await waitFor(
async () => {
const now = await fetchGameInfo(gameId);
return (now?.clients?.length ?? 0) === PLAYER_COUNT;
},
{
timeoutMs: 60000,
intervalMs: 1000,
label: "all matched players to pass the allowlist and join the game",
},
);
c.check("all matched players admitted past the allowlist", true);
} catch (err) {
console.error(
"game info at failure:",
JSON.stringify(await fetchGameInfo(gameId)),
);
for (const p of pages) {
console.error("page:", p.url());
}
dumpConsoles();
throw err;
}
if (MODE === "2v2") {
// Ride the real flow into the game and read the ground-truth team split
// from each client's GameView (see run-openfront skill notes).
const splitOf = (p) =>
p.evaluate(() => {
const g = document.querySelector("build-menu")?.game;
if (!g) return null;
try {
const humans = g.players().filter((pl) => pl.type() === "HUMAN");
if (humans.length < 4) return null;
return humans.map((pl) => `${pl.clientID()}:${pl.team()}`).sort();
} catch {
return null;
}
});
let splits;
try {
splits = await waitFor(
async () => {
const all = await Promise.all(pages.map(splitOf));
return all.every(Boolean) ? all : null;
},
{
timeoutMs: 120000,
intervalMs: 2000,
label: "every client to reach the started game with 4 humans",
},
);
} catch (err) {
dumpConsoles();
throw err;
}
const teamCounts = {};
for (const entry of splits[0]) {
const team = entry.split(":")[1];
teamCounts[team] = (teamCounts[team] ?? 0) + 1;
}
c.check(
`in-game team split is 2 vs 2 (${JSON.stringify(teamCounts)})`,
Object.values(teamCounts).sort().join(",") === "2,2",
);
c.check(
"team split is identical on every client (deterministic)",
splits.every((s) => JSON.stringify(s) === JSON.stringify(splits[0])),
);
}
} finally {
await browser.close();
}
c.finish();