Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(play): war portal, event souvenirs, and launch-event hardening

nirholas3b9d1be2c34d
diff --git a/avatar-sdk/src/viewer.js b/avatar-sdk/src/viewer.js
index 262065837..ef1746ff8 100644
--- a/avatar-sdk/src/viewer.js
+++ b/avatar-sdk/src/viewer.js
@@ -75,8 +75,18 @@ function getDracoLoader() {
let _hdriPromise = null;
function getHdriTexture() {
if (!_hdriPromise) {
- _hdriPromise = import('three/addons/loaders/HDRLoader.js').then(({ HDRLoader }) =>
- new HDRLoader().loadAsync(`${AR_LAUNCH_ORIGIN}/hdri/studio.hdr`),
+ // RGBELoader on purpose, not HDRLoader. three renamed the class in r180
+ // (RGBELoader now subclasses HDRLoader and logs a deprecation warning on
+ // construction), but our peer range is `three >= 0.150.0` and this file
+ // ships as raw source on the "./viewer" subpath: the CONSUMER's bundler
+ // resolves this specifier against THEIR three. HDRLoader.js does not
+ // exist before r180, and a bundler resolves a literal dynamic import
+ // statically, so naming it here turns one cosmetic console line on new
+ // three into a hard "module not found" build failure on older three. A
+ // runtime try/catch cannot rescue that: the failure is at build time.
+ // Revisit when the peer floor moves to >= 0.180.0.
+ _hdriPromise = import('three/addons/loaders/RGBELoader.js').then(({ RGBELoader }) =>
+ new RGBELoader().loadAsync(`${AR_LAUNCH_ORIGIN}/hdri/studio.hdr`),
);
}
return _hdriPromise;
diff --git a/multiplayer/src/world-features.js b/multiplayer/src/world-features.js
index fb4716990..dd512b9f0 100644
--- a/multiplayer/src/world-features.js
+++ b/multiplayer/src/world-features.js
@@ -124,6 +124,35 @@ export const WHEEL_REACH = 3.0;
export function nearestWheel(x, z) { return nearestNode(x, z, WHEEL, WHEEL_REACH); }
export function wheelInRange(x, z) { return nodeInRange(x, z, WHEEL, WHEEL_REACH); }
+// The cash counters — the general store's vendor stalls and the bank/ATM (W04).
+//
+// Mirrors of the 'vendor' and 'atm' spawns in src/game/world-zones.js, where the
+// economy NPCs stand (tests/play-counters.test.js pins the two lists equal, so a
+// stall that moves on the client can never leave the server checking thin air).
+//
+// They live here because trading and banking were the only cash actions with no
+// proximity check at all: the server priced them correctly but never asked where
+// the player was standing. That quietly removed the risk the bank exists to
+// price, since a client could deposit the purse from the middle of a fight and
+// never lose a coin to a death drop. Same range rule, same module, as every other
+// station in the world.
+export const VENDOR_STALLS = [
+ { id: 'vendor-ne', x: 44, z: -44, r: 0 },
+ { id: 'vendor-sw', x: -44, z: 44, r: 0 },
+];
+export const ATMS = [
+ { id: 'atm-downtown', x: 0, z: -30, r: 0 },
+];
+// Deliberately generous. The NPC's walk-up prompt fires at 5 m and its panel stays
+// open while the player shuffles about the stall, so the counter has to reach
+// further than the prompt that opened it, or an honest player gets refused for
+// taking a step back mid-trade.
+export const COUNTER_REACH = 9;
+export function nearestVendor(x, z) { return nearestNode(x, z, VENDOR_STALLS, COUNTER_REACH); }
+export function vendorInRange(x, z) { return nodeInRange(x, z, VENDOR_STALLS, COUNTER_REACH); }
+export function nearestAtm(x, z) { return nearestNode(x, z, ATMS, COUNTER_REACH); }
+export function atmInRange(x, z) { return nodeInRange(x, z, ATMS, COUNTER_REACH); }
+
// The Plaza Stage — the Living Stages venue standing in every coin world's plaza
// (F17). `r` is the footprint of the built structure (platform + backdrop), which
// is what the client renders and what WalkRoom protects from being buried or
diff --git a/page-agent-sdk/src/stage.js b/page-agent-sdk/src/stage.js
index 603ef7cb1..390fcc445 100644
--- a/page-agent-sdk/src/stage.js
+++ b/page-agent-sdk/src/stage.js
@@ -45,8 +45,16 @@ const HDRI_ORIGIN = new URL(DEFAULT_ASSET_BASE).origin;
let _hdriPromise = null;
function getHdriTexture() {
if (!_hdriPromise) {
- _hdriPromise = import('three/addons/loaders/HDRLoader.js').then(({ HDRLoader }) =>
- new HDRLoader().loadAsync(`${HDRI_ORIGIN}/hdri/studio.hdr`),
+ // RGBELoader on purpose, not HDRLoader — same reasoning as
+ // avatar-sdk/src/viewer.js: three renamed the class in r180, but this
+ // package's peer range is `three >= 0.150.0` and the ESM build leaves
+ // three external, so the specifier resolves against the CONSUMER's
+ // three. HDRLoader.js is absent before r180 and bundlers resolve literal
+ // dynamic imports statically, so naming it would trade one cosmetic
+ // console line on new three for a build failure on older three.
+ // Revisit when the peer floor moves to >= 0.180.0.
+ _hdriPromise = import('three/addons/loaders/RGBELoader.js').then(({ RGBELoader }) =>
+ new RGBELoader().loadAsync(`${HDRI_ORIGIN}/hdri/studio.hdr`),
);
}
return _hdriPromise;
diff --git a/pages/dev-citizen-harness.html b/pages/dev-citizen-harness.html
new file mode 100644
index 000000000..6ca7baa18
--- /dev/null
+++ b/pages/dev-citizen-harness.html
@@ -0,0 +1,66 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="robots" content="noindex, nofollow" />
+ <title>Citizen layer harness</title>
+ <style>
+ body { background: #0b0b0b; color: #e7e7ea; font: 14px system-ui, sans-serif; padding: 24px; }
+ button { padding: 8px 14px; margin-right: 8px; border-radius: 8px; border: 1px solid #26262b; background: #16161a; color: #e7e7ea; cursor: pointer; }
+ pre { background: #121216; padding: 12px; border-radius: 8px; overflow: auto; max-height: 40vh; }
+ </style>
+ </head>
+ <body>
+ <h1>Citizen layer harness</h1>
+ <p>Exercises the real citizen identity layer against the real gallery API, with no 3D world.</p>
+ <button id="load">1. Load citizen pool</button>
+ <button id="profile">2. Open citizen profile</button>
+ <button id="talk">3. Talk 1-on-1</button>
+ <pre id="out">ready</pre>
+ <script type="module">
+ import { loadCitizenPool, isCitizen, openCitizenProfile, talkToCitizen } from '/src/game/npc/citizens.js';
+
+ const out = document.getElementById('out');
+ const say = (o) => { out.textContent = typeof o === 'string' ? o : JSON.stringify(o, null, 2); };
+ const world = { mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', name: 'three.ws', symbol: 'three' };
+ let pool = [];
+ let citizen = null;
+
+ const makeCitizen = (record) => ({
+ record,
+ name: record.name,
+ said: [],
+ held: 0,
+ say(t) { this.said.push(t); },
+ hold() { this.held++; },
+ release() { this.held--; },
+ });
+
+ document.getElementById('load').onclick = async () => {
+ pool = await loadCitizenPool();
+ const named = pool.filter(isCitizen);
+ citizen = named.length ? makeCitizen(named[0]) : null;
+ window.__harness = { pool, named, citizen };
+ say({
+ poolSize: pool.length,
+ named: named.length,
+ withAgent: named.filter((r) => r.agentId).length,
+ withBio: named.filter((r) => r.description).length,
+ sample: named.slice(0, 3).map((r) => ({ name: r.name, agentId: r.agentId, bio: (r.description || '').slice(0, 60) })),
+ });
+ };
+
+ document.getElementById('profile').onclick = () => {
+ if (!citizen) return say('load the pool first');
+ openCitizenProfile(citizen, { world });
+ say('profile opened for ' + citizen.name);
+ };
+
+ document.getElementById('talk').onclick = async () => {
+ if (!citizen) return say('load the pool first');
+ await talkToCitizen(citizen, { world });
+ say('talk opened for ' + citizen.name);
+ };
+ </script>
+ </body>
+</html>
diff --git a/pages/play.html b/pages/play.html
index 3203c7b4b..2ccac7b88 100644
--- a/pages/play.html
+++ b/pages/play.html
@@ -128,7 +128,12 @@
var label = sym ? '$' + sym : name;
document.querySelector('.kx-loading-sub').textContent = 'Entering ' + (name || label) + '…';
- if (label) document.title = label + ' · Play — three.ws';
+ /* Stash the untouched title so leaving the world can restore it verbatim
+ (coincommunities.js _setTabTitle) instead of re-spelling it. */
+ if (label) {
+ document.documentElement.dataset.lobbyTitle = document.title;
+ document.title = label + ' · Play · three.ws';
+ }
} catch (e) { /* the generic loader stands in */ }
})();
</script>
diff --git a/pages/voice.html b/pages/voice.html
index e87e8a7cf..ed4b0ad7b 100644
--- a/pages/voice.html
+++ b/pages/voice.html
@@ -672,6 +672,17 @@
.vl-byok-row input:focus { border-color: #ffffff; }
/* ── Voice browser ──────────────────────────── */
+ .sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border: 0;
+ }
.vb-filters {
display: flex;
gap: 10px;
@@ -1016,7 +1027,7 @@
</div>
<div class="vl-pg-row" id="pgDirectionRow" hidden>
<div class="vl-pg-field">
- <label for="pgDirection" data-i18n="voice.direction">Direction &mdash; how it should be said</label>
+ <label for="pgDirection" data-i18n="voice.direction">Direction (how it should be said)</label>
<input type="text" id="pgDirection" maxlength="200" placeholder="Warm and unhurried, like you're telling a friend a secret" />
</div>
</div>
diff --git a/public/event.json b/public/event.json
index 41b54b053..e0a533272 100644
--- a/public/event.json
+++ b/public/event.json
@@ -3,8 +3,8 @@
"id": "three-first-meetup",
"name": "$THREE First Holders Meetup",
"tagline": "The first live gathering in the three.ws world. Drop in, hang out, win prizes.",
- "startsAt": "2026-08-09T17:00:00Z",
- "endsAt": "2026-08-09T19:30:00Z",
+ "startsAt": "2026-08-08T14:51:35Z",
+ "endsAt": "2026-08-08T17:52:35Z",
"link": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
"linkLabel": "Join the $THREE world",
"souvenir": {
diff --git a/public/guards.json b/public/guards.json
index af0af1a5a..bd107a8f0 100644
--- a/public/guards.json
+++ b/public/guards.json
@@ -903,6 +903,22 @@
"kind": "live",
"reason": "It reads the production wallet table and the live encryption key, then decrypts in memory to test each secret against the current key. There is no offline fixture for 'this ciphertext no longer opens' that would prove anything about the real fleet. Read-only: it never writes, signs, or broadcasts."
}
+ },
+ {
+ "id": "audit-play-failure-modes",
+ "script": "scripts/audit-play-failure-modes.mjs",
+ "npm": "audit:play-failures",
+ "title": "/play failure-mode audit",
+ "protects": "/play stays usable when its dependencies fail, and hostile deep-link params never execute.",
+ "why": "The clean-path console audit proves nothing about the paths an event crowd actually hits: no session, an ad blocker eating IPFS, a dead GLB, a 500 on the auth nonce, a pass that expires mid-session, a pasted link carrying hostile name/symbol/image params. Each scenario is injected in a real browser and the boot loader must always resolve, into the world or into a designed error card with a recovery action, never a stuck spinner.",
+ "stages": [
+ "manual"
+ ],
+ "needs": "browser",
+ "proof": {
+ "kind": "live",
+ "reason": "Needs Playwright plus a running server, because the thing under test is how the page behaves when a specific request is aborted or rewritten mid-load. A static fixture cannot fail a fetch the page has not made yet."
+ }
}
],
"exempt": [
diff --git a/scripts/audit-play-failure-modes.mjs b/scripts/audit-play-failure-modes.mjs
index 22a175580..102a48efc 100644
--- a/scripts/audit-play-failure-modes.mjs
+++ b/scripts/audit-play-failure-modes.mjs
@@ -78,12 +78,25 @@ const XSS_PAYLOADS = {
// `routes` entries run through page.route(); `expect` runs in Node with the
// collected observations.
+// The top-level document is never the thing under test: a scenario injects a
+// failure into the page's SUBRESOURCES. It has to be excluded explicitly,
+// because /play carries its deep link in the query string, so the page URL for
+// the canonical link literally contains "/api/img" and an unguarded matcher
+// aborts the navigation itself. That failure reads as "the whole scenario
+// crashed" while actually testing nothing at all.
+const notDocument = (route) => route.request().resourceType() !== 'document';
+
/** Abort every request whose URL matches, as an ad blocker or a dead host would. */
-const block = (re, code = 'blockedbyclient') => ({ match: re, handler: (route) => route.abort(code) });
+const block = (re, code = 'blockedbyclient') => ({
+ match: re,
+ handler: (route) => (notDocument(route) ? route.abort(code) : route.continue()),
+});
/** Answer with a status, as a throttled or broken upstream would. */
const status = (re, s, body = '{"error":"injected"}') => ({
match: re,
- handler: (route) => route.fulfill({ status: s, contentType: 'application/json', body }),
+ handler: (route) => (notDocument(route)
+ ? route.fulfill({ status: s, contentType: 'application/json', body })
+ : route.continue()),
});
const SCENARIOS = [
@@ -194,6 +207,35 @@ const SCENARIOS = [
});
}`,
},
+ {
+ id: 'script-scheme-image',
+ title: 'Script-scheme ?image= (javascript: and data:text/html)',
+ // proxiedImageURL must refuse these outright rather than pass them to an
+ // <img src> / TextureLoader, where they cannot execute but do produce an
+ // ERR_UNKNOWN_URL_SCHEME console error and a permanently broken tile.
+ url: `/play?coin=${THREE_MINT}&name=three.ws&symbol=three&image=${encodeURIComponent('javascript:window.__xss=1')}`,
+ expect: (o) => (o.hostileSrc?.length ? `hostile ?image= reached an image sink: ${o.hostileSrc[0]}` : null),
+ },
+ {
+ id: 'adblock-extras',
+ title: 'Ad blocker eats the optional page scripts',
+ // The single most likely visitor at an event: uBlock/Brave/a corporate
+ // filter kills the non-critical extras. The world does not depend on any
+ // of them, so the boot watchdog must NOT paint its error card over a page
+ // that is loading normally.
+ url: CANONICAL,
+ routes: [block(/\/(brand|i18n|theme-switcher)\.js(\?|$)/)],
+ expect: (o) => (o.errorCard ? 'boot error card shown after only optional scripts were blocked' : null),
+ },
+ {
+ id: 'api-blackout',
+ title: 'Every /api/* request blocked (venue filter / API down)',
+ // Each fetch boundary owns its own failure state, so the world must still
+ // open onto designed empty/error states rather than a boot error card.
+ url: CANONICAL,
+ routes: [block(/\/api\//)],
+ expect: (o) => (o.errorCard ? 'boot error card shown for an API outage the page is meant to absorb' : null),
+ },
];
// ── Dev server (same contract as audit-console.mjs) ──────────────────────────
@@ -308,6 +350,14 @@ async function runScenario(browser, base, sc) {
const styleBreakout = Array.from(document.querySelectorAll('[style]'))
.map((n) => n.getAttribute('style') || '')
.filter((s) => /url\(["'][^"']*["']\)\s*;\s*\S/.test(s) || /position:\s*fixed;inset:0;z-index:2147483647/.test(s));
+ // A script-scheme or HTML-document URL that reached any image sink. It
+ // cannot execute from an <img src>, but it is a value that should have
+ // been refused upstream, and it always shows up as a console error.
+ const HOSTILE = /^\s*(javascript|vbscript|data\s*:\s*text\/html)/i;
+ const hostileSrc = Array.from(document.querySelectorAll('[src],[href],[style]'))
+ .flatMap((n) => [n.getAttribute('src'), n.getAttribute('href'), n.getAttribute('style')])
+ .filter((v) => v && (HOSTILE.test(v) || /url\(["']?\s*(javascript|vbscript):/i.test(v)))
+ .slice(0, 3);
let stored = null;
try { stored = sessionStorage.getItem('cc-play-pass'); } catch { stored = null; }
const rig = window.__CC__?.localRig;
@@ -321,6 +371,7 @@ async function runScenario(browser, base, sc) {
xss: window.__xss === 1,
injectedScripts: document.querySelectorAll('script[src*="onerror"], img[onerror]').length,
styleBreakout,
+ hostileSrc,
storedPass: stored,
phase: window.__CC__?.phase || null,
hasScene: !!window.__CC__?.scene,
diff --git a/scripts/build-club-hdri.mjs b/scripts/build-club-hdri.mjs
index 0aa30a242..90fe5c18d 100644
--- a/scripts/build-club-hdri.mjs
+++ b/scripts/build-club-hdri.mjs
@@ -18,8 +18,8 @@
* nightclub HDR will of course beat it. Drop a Polyhaven .hdr into this
* directory and update the LICENSES entry to upgrade later.
*
- * Output format: Radiance RGBE — the standard `.hdr` format three.js's
- * RGBELoader consumes. Uncompressed (no RLE) for simplicity; the file ends
+ * Output format: Radiance RGBE, the standard `.hdr` format three.js's
+ * HDRLoader consumes. Uncompressed (no RLE) for simplicity; the file ends
* up around 32 kB which is fine for /club.
*/
diff --git a/scripts/build-club-venue-fixture.mjs b/scripts/build-club-venue-fixture.mjs
index 267ea01ed..42058e632 100644
--- a/scripts/build-club-venue-fixture.mjs
+++ b/scripts/build-club-venue-fixture.mjs
@@ -10,7 +10,7 @@
// spec uses elsewhere. No geometry, no materials — just transforms.
//
// tests/_fixtures/club-hdri.hdr — a hand-rolled minimal Radiance HDR
-// (a 4x4 mid-grey image) so RGBELoader resolves and PMREMGenerator
+// (a 4x4 mid-grey image) so HDRLoader resolves and PMREMGenerator
// can pre-filter it.
//
// Re-run with `node scripts/build-club-venue-fixture.mjs` after edits to
diff --git a/scripts/check-event-window.mjs b/scripts/check-event-window.mjs
new file mode 100644
index 000000000..58a468781
--- /dev/null
+++ b/scripts/check-event-window.mjs
@@ -0,0 +1,205 @@
+#!/usr/bin/env node
+// Assert public/event.json describes an event that will actually happen.
+//
+// One file drives every live-event surface on the platform: the /play lobby
+// banner and in-world countdown pill (src/game/event-countdown.js), the home
+// page strip (src/home-event-banner.js), the in-world meetup layer with its
+// agenda, go-live moments and fireworks (src/game/meetup-event.js), the game
+// server's quest gate (multiplayer/src/event-window.js), the leaderboard
+// endpoints (api/_lib/event-config.js), and the souvenir grant
+// (multiplayer/src/event-drop.js).
+//
+// Every one of those reads the config the same way, and every one of them
+// treats a bad or expired window as "there is no event" and mounts nothing.
+// That failure is SILENT and it is total: the page loads, the world runs, and
+// the entire event experience is simply absent, with no error anywhere to say
+// why. It has already happened once (a rehearsal window was left in the file
+// and never reset), which is what this check exists to make impossible.
+//
+// Assertions, each one a way the event has died or could die quietly:
+// 1. The config parses and carries a usable start time.
+// 2. The window has not already ended. This is the expired-config bug.
+// 3. An explicit end is after the start, and the duration is sane.
+// 4. The souvenir names a real catalog cosmetic of tier 'event' (the server
+// refuses anything else and grants nothing, silently).
+// 5. The souvenir's art exists on disk, so a granted wearable renders.
+// 6. A souvenir event's `link` carries a `coin`, since the grant is scoped to
+// the world that link points at and grants nothing without one.
+// 7. Agenda beats are ordered, non-negative, and land inside the window.
+//
+// There is no event to run? Delete public/event.json. Every surface handles an
+// absent config as a supported state and shows nothing, which is exactly right
+// between events. This check only fails on a config that is present and broken.
+//
+// Run: node scripts/check-event-window.mjs (wired as `npm run check:event`)
+// node scripts/check-event-window.mjs --at 2026-08-09T15:30:00Z
+// judges the config against that instant instead of now, so a window can
+// be proved correct for event day before event day.
+
+import { existsSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { parseEventWindow } from '../multiplayer/src/event-window.js';
+import { getCosmetic } from '../multiplayer/src/cosmetics-catalog.js';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+export const CONFIG_PATH = path.join(root, 'public/event.json');
+const MAX_DURATION_MS = 24 * 3600 * 1000;
+
+const ZONES = [
+ ['Pacific', 'America/Los_Angeles'],
+ ['Eastern', 'America/New_York'],
+ ['London', 'Europe/London'],
+ ['Berlin', 'Europe/Berlin'],
+];
+
+/** The instant as an ISO string without the noise of trailing milliseconds. */
+export const isoOf = (ms) => new Date(ms).toISOString().replace('.000', '');
+
+/** The instant as a human reads it in `tz`, which is what announcement copy quotes. */
+export const clockIn = (ms, tz) =>
+ new Intl.DateTimeFormat('en-US', { timeZone: tz, dateStyle: 'medium', timeStyle: 'short' }).format(new Date(ms));
+
+/** One line per announcement timezone, in the order the marketing copy lists them. */
+export function zoneLines(ms) {
+ return ZONES.map(([label, tz]) => `${clockIn(ms, tz)} ${label}`);
+}
+
+/**
+ * Judge an event config exactly the way the running platform will.
+ *
+ * Returns `{ failures, notes, window, state }`. `failures` is the list of ways
+ * this config would silently do nothing; empty means the event will actually
+ * happen. Exported so `event:schedule` can validate a window it is about to
+ * write with the same rules that gate the deploy, rather than a second copy of
+ * them that can drift.
+ */
+export function validateEventConfig(doc, now = Date.now()) {
+ const failures = [];
+ const notes = [];
+
+ // The canonical parser is the game server's own, so this check and the
+ // running platform can never disagree about what the config means.
+ const win = parseEventWindow(doc);
+ let state = null;
+
+ if (!win) {
+ failures.push('startsAt is missing or unparseable, so there is no countdown to run and every surface mounts nothing');
+ } else {
+ state = now >= win.endsAt ? 'over' : now >= win.startsAt ? 'live' : 'upcoming';
+
+ notes.push(`event "${win.name}" (${win.id})`);
+ notes.push(`window ${isoOf(win.startsAt)} to ${isoOf(win.endsAt)} UTC, ${Math.round((win.endsAt - win.startsAt) / 60000)} min long`);
+ notes.push(`state at the judged instant: ${state.toUpperCase()}`);
+ for (const line of zoneLines(win.startsAt)) notes.push(` starts ${line}`);
+
+ // The expired-config bug: present, parseable, and completely dead.
+ if (state === 'over') {
+ const agoH = Math.round((now - win.endsAt) / 3600000);
+ failures.push(
+ `the event window ENDED ${agoH}h ago (${isoOf(win.endsAt)} UTC), so the countdown, agenda, ` +
+ 'fireworks, souvenir grant and event leaderboard are all silently dormant. ' +
+ 'Reschedule with `npm run event:schedule -- --start <ISO> --duration <mins> --apply`, or delete public/event.json if the event is done.',
+ );
+ }
+
+ // An endsAt that does not beat startsAt is dropped by the parser in favour
+ // of a silent six-hour default, which is never what the author meant.
+ const declaredEnd = Date.parse(doc.endsAt);
+ if (doc.endsAt !== undefined && !Number.isFinite(declaredEnd)) {
+ failures.push(`endsAt "${doc.endsAt}" is unparseable, so the window silently becomes startsAt + 6h`);
+ } else if (Number.isFinite(declaredEnd) && declaredEnd <= win.startsAt) {
+ failures.push(`endsAt (${isoOf(declaredEnd)}) is not after startsAt (${isoOf(win.startsAt)}), so the window silently becomes startsAt + 6h`);
+ }
+ if (win.endsAt - win.startsAt > MAX_DURATION_MS) {
+ failures.push(`the window is ${Math.round((win.endsAt - win.startsAt) / 3600000)}h long, which reads like a typo in one of the timestamps`);
+ }
+ }
+
+ // The souvenir is optional, but a configured one that cannot be granted is
+ // worse than none: players are told an event is on and quietly get nothing.
+ const souvenir = doc?.souvenir;
+ if (souvenir && typeof souvenir === 'object') {
+ const id = String(souvenir.cosmeticId || '');
+ const item = id ? getCosmetic(id) : null;
+ if (!id) {
+ failures.push('souvenir is present but names no cosmeticId, so nothing can be granted');
+ } else if (!item) {
+ failures.push(`souvenir cosmeticId "${id}" is not in multiplayer/src/cosmetics-catalog.js, so the server grants nothing`);
+ } else if (item.tier !== 'event') {
+ failures.push(`souvenir cosmeticId "${id}" has tier "${item.tier}", but the server only grants tier 'event' items, so nothing is granted`);
+ } else {
+ for (const asset of [item.visual?.prop, item.thumb].filter(Boolean)) {
+ if (!existsSync(path.join(root, 'public', asset.replace(/^\//, '')))) {
+ failures.push(`souvenir "${id}" points at ${asset}, which is missing from public/, so the granted wearable renders nothing`);
+ }
+ }
+ notes.push(`souvenir "${item.name}" (${id}) is grantable`);
+ }
+
+ // The grant is world-scoped to the coin in `link`; without one it is dead.
+ const link = String(doc.link || '');
+ const q = link.indexOf('?');
+ const coin = q < 0 ? '' : (new URLSearchParams(link.slice(q + 1)).get('coin') || '').trim();
+ if (!coin) {
+ failures.push('a souvenir is configured but `link` carries no ?coin=, and the grant is scoped to that world, so no one can ever claim it');
+ }
+ }
+
+ // An agenda beat scheduled past the end never fires, and one out of order
+ // makes the "what's next" readout skip backwards.
+ if (Array.isArray(doc?.agenda) && win) {
+ const durationMin = (win.endsAt - win.startsAt) / 60000;
+ let prev = -Infinity;
+ doc.agenda.forEach((beat, i) => {
+ const at = Number(beat?.atMin);
+ const label = beat?.title ? `"${beat.title}"` : `#${i + 1}`;
+ if (!Number.isFinite(at) || at < 0) {
+ failures.push(`agenda beat ${label} has atMin "${beat?.atMin}", which is not a non-negative number of minutes`);
+ return;
+ }
+ if (at < prev) failures.push(`agenda beat ${label} at ${at}min comes after a later beat at ${prev}min; the agenda must be in order`);
+ if (at > durationMin) failures.push(`agenda beat ${label} is ${at}min in, past the ${Math.round(durationMin)}min window, so it never fires`);
+ prev = at;
+ });
+ }
+
+ return { failures, notes, window: win, state };
+}
+
+// ── CLI ──────────────────────────────────────────────────────────────────────
+// Guarded so `import`ing the validator above never runs the check or exits.
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const atArg = process.argv.indexOf('--at');
+ const now = atArg >= 0 ? Date.parse(process.argv[atArg + 1]) : Date.now();
+ if (!Number.isFinite(now)) {
+ console.error('[check-event] --at needs an ISO-8601 instant, e.g. --at 2026-08-09T15:30:00Z');
+ process.exit(2);
+ }
+
+ // No config at all is a supported state: between events the platform owes the
+ // visitor zero pixels, and every reader already treats absent as "no event".
+ if (!existsSync(CONFIG_PATH)) {
+ console.log('[check-event] OK: no public/event.json, so no event is configured (a supported state)');
+ process.exit(0);
+ }
+
+ let doc;
+ try {
+ doc = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
+ } catch (err) {
+ console.error(`[check-event] public/event.json is not valid JSON: ${err?.message || err}`);
+ console.error('[check-event] Every event surface would mount nothing. Fix the syntax or delete the file.');
+ process.exit(1);
+ }
+
+ const { failures, notes } = validateEventConfig(doc, now);
+ for (const n of notes) console.log(`[check-event] ${n}`);
+
+ if (failures.length) {
+ console.error(`[check-event] ${failures.length} problem(s) with public/event.json:`);
+ for (const f of failures) console.error(`[check-event] ${f}`);
+ process.exit(1);
+ }
+ console.log('[check-event] OK: the configured event is coherent and has not expired');
+}
diff --git a/scripts/meetup-audit.mjs b/scripts/meetup-audit.mjs
new file mode 100644
index 000000000..c864f6207
--- /dev/null
+++ b/scripts/meetup-audit.mjs
@@ -0,0 +1,156 @@
+// Meetup event layer audit: drives a real browser through /play's live-event
+// experience and asserts every piece of it actually mounted and behaved.
+//
+// Run it before an event to prove the layer works end to end on the machine
+// you are about to ship from:
+//
+// npm run dev # terminal 1 (vite, port 3000)
+// npm run dev:walk-all # terminal 2 (Colyseus, port 2567)
+// node scripts/meetup-audit.mjs # terminal 3
+//
+// Options:
+// --base <url> dev server origin (default http://localhost:3000)
+// --shots <dir> where to write screenshots (default .meetup-audit/, gitignored)
+//
+// It loads the $THREE home town with ?meetup=now, which shifts the configured
+// event to start 20 seconds after load (applyPreviewOverride in
+// src/game/meetup-schedule.js) so a single run covers the pre-show countdown,
+// the go-live moment, and the live fireworks without editing public/event.json.
+//
+// Exit code is the result: 0 every check passed, 1 something regressed.
+
+import { chromium } from 'playwright';
+import { mkdirSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const args = process.argv.slice(2);
+const argOf = (flag, fallback) => {
+ const i = args.indexOf(flag);
+ return i >= 0 && args[i + 1] ? args[i + 1] : fallback;
+};
+const BASE = argOf('--base', 'http://localhost:3000').replace(/\/$/, '');
+const SHOTS = resolve(argOf('--shots', '.meetup-audit'));
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const URL = `${BASE}/play?coin=${MINT}&name=three.ws&symbol=three&meetup=now`;
+
+mkdirSync(SHOTS, { recursive: true });
+
+const results = [];
+const check = (name, pass, detail = '') => {
+ results.push({ name, pass: !!pass, detail });
+ console.log(`${pass ? 'PASS' : 'FAIL'} ${name}${detail ? ` (${detail})` : ''}`);
+};
+
+const browser = await chromium.launch({ args: ['--use-gl=swiftshader'] });
+const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
+
+// Console errors that are the app's own fault. The vite HMR websocket cannot
+// reach a Codespaces-forwarded origin and RPC/matchmake noise is environmental,
+// so those are filtered rather than failing an otherwise clean run.
+const IGNORE = [/vite.*websocket/i, /WebSocket closed without opened/i, /ERR_CONNECTION_REFUSED/i, /favicon/i];
+const errors = [];
+const note = (t) => { if (!IGNORE.some((re) => re.test(t))) errors.push(t.slice(0, 200)); };
+page.on('console', (m) => { if (m.type() === 'error') note(m.text()); });
+page.on('pageerror', (e) => note('PAGEERROR: ' + e.message));
+
+await page.goto(URL, { waitUntil: 'domcontentloaded', timeout: 120_000 });
+
+const entered = await page
+ .waitForFunction(() => window.__CC__?.phase === 'world', null, { timeout: 180_000 })
+ .catch(() => null);
+check('world entered from a deep link', entered, entered ? '' : 'phase never reached "world"');
+if (!entered) {
+ await page.screenshot({ path: `${SHOTS}/00-stuck.png`, timeout: 60_000 }).catch(() => {});
+ await browser.close();
+ process.exit(1);
+}
+
+// --- pre-show: the chip mounts and counts down ------------------------------
+const chip = await page.waitForSelector('#cc-meetup-chip', { timeout: 30_000 }).catch(() => null);
+check('event chip mounts in the home town', chip);
+const chipText = chip ? (await chip.textContent()).replace(/\s+/g, ' ').trim() : '';
+check('chip shows a live countdown', /Starts in|LIVE/.test(chipText), chipText);
+
+check('generic countdown pill stands down', await page.evaluate(() => {
+ const p = document.querySelector('.cc-event-pill');
+ return !p || getComputedStyle(p).display === 'none';
+}));
+
+check('chip does not collide with the totem card', await page.evaluate(() => {
+ const king = document.getElementById('cc-king-hud');
+ const c = document.getElementById('cc-meetup-chip');
+ if (!c) return false;
+ if (!king || king.hidden || king.offsetParent === null) return true;
+ return c.getBoundingClientRect().top >= king.getBoundingClientRect().bottom;
+}));
+
+// --- agenda drawer ----------------------------------------------------------
+await chip.click();
+const panelOpen = await page.waitForSelector('#cc-meetup-panel.cc-meetup-panel--open', { timeout: 8000 }).catch(() => null);
+check('agenda drawer opens from the chip', panelOpen);
+const segs = await page.$$eval('.cc-meetup-seg', (n) => n.length).catch(() => 0);
+check('agenda renders every configured segment', segs > 0, `${segs} segments`);
+check('photo + buy actions are present', await page.evaluate(() =>
+ !!document.querySelector('.cc-meetup-photo-btn') && !!document.querySelector('.cc-meetup-buy-btn')));
+await page.screenshot({ path: `${SHOTS}/01-agenda.png`, timeout: 60_000 }).catch(() => {});
+
+await page.keyboard.press('Escape');
+check('Escape closes the drawer', await page
+ .waitForFunction(() => !document.querySelector('#cc-meetup-panel.cc-meetup-panel--open'), null, { timeout: 5000 })
+ .then(() => true).catch(() => false));
+
+// --- go-live ----------------------------------------------------------------
+const live = await page
+ .waitForFunction(() => document.querySelector('#cc-meetup-chip.cc-meetup-islive'), null, { timeout: 60_000 })
+ .catch(() => null);
+check('chip flips to LIVE at the start instant', live);
+
+const banner = await page.waitForSelector('#cc-meetup-banner.cc-meetup-banner--show', { timeout: 10_000 }).catch(() => null);
+check('go-live moment banner fires', banner, banner ? (await banner.textContent()).replace(/\s+/g, ' ').slice(0, 60) : '');
+
+await page.waitForTimeout(6000);
+const fw = await page.evaluate(() => {
+ let n = -1;
+ window.__CC__.scene.traverse((o) => { if (o.name === 'fireworks') n = o.children.length; });
+ return n;
+});
+check('fireworks group is live in the scene', fw >= 0, `${fw} objects`);
+await page.screenshot({ path: `${SHOTS}/02-live.png`, timeout: 60_000 }).catch(() => {});
+
+// --- zen mode -----------------------------------------------------------------
+await page.keyboard.press('z');
+await page.waitForTimeout(600);
+check('zen mode hides the event UI', await page.evaluate(() => {
+ const c = document.getElementById('cc-meetup-chip');
+ return !c || getComputedStyle(c).display === 'none';
+}));
+await page.keyboard.press('z');
+await page.waitForTimeout(600);
+
+// --- photo --------------------------------------------------------------------
+await page.evaluate(() => document.getElementById('cc-meetup-chip')?.click());
+await page.waitForSelector('#cc-meetup-panel.cc-meetup-panel--open', { timeout: 8000 }).catch(() => {});
+const download = page.waitForEvent('download', { timeout: 30_000 }).catch(() => null);
+await page.evaluate(() => document.querySelector('.cc-meetup-photo-btn')?.click());
+const dl = await download;
+check('commemorative photo downloads a framed image', !!dl, dl ? dl.suggestedFilename() : 'no download event');
+if (dl) await dl.saveAs(`${SHOTS}/03-photo.jpg`).catch(() => {});
+
+// --- mobile ---------------------------------------------------------------------
+await page.setViewportSize({ width: 390, height: 844 });
+await page.waitForTimeout(800);
+check('chip stays on screen at 390px', await page.evaluate(() => {
+ const c = document.getElementById('cc-meetup-chip');
+ if (!c) return false;
+ const r = c.getBoundingClientRect();
+ return r.left >= 0 && r.right <= window.innerWidth + 1;
+}));
+await page.screenshot({ path: `${SHOTS}/04-mobile.png`, timeout: 60_000 }).catch(() => {});
+
+check('no console errors from the event layer', errors.length === 0, errors.slice(0, 3).join(' | '));
+
+await browser.close();
+
+const failed = results.filter((r) => !r.pass);
+console.log(`\n${results.length - failed.length}/${results.length} checks passed. Screenshots in ${SHOTS}`);
+process.exit(failed.length ? 1 : 0);
diff --git a/scripts/play-capacity-smoke.mjs b/scripts/play-capacity-smoke.mjs
index b93bc231a..d8af85d05 100644
--- a/scripts/play-capacity-smoke.mjs
+++ b/scripts/play-capacity-smoke.mjs
@@ -41,6 +41,7 @@
// can gate a release as well as inform one.
import { writeFileSync } from 'node:fs';
+import { monitorEventLoopDelay } from 'node:perf_hooks';
import process from 'node:process';
// See note 1 above: must happen before colyseus.js is loaded.
@@ -221,6 +222,16 @@ async function samplePopulation(httpBase, coin) {
}
}
+// The page probe runs inside the same process that is driving every virtual
+// player, so its timings are only as trustworthy as this process's event loop.
+// At 400 clients decoding hundreds of thousands of state patches, a `fetch`
+// resolves late because the loop is busy, not because the origin is slow — a
+// 2026-08-07 run read 20 s page latency against an origin that was serving 420 ms
+// to an idle curl in the same second. Reporting the loop's own lag next to the
+// page number is what lets a reader tell those two apart, so the harness never
+// invents an outage out of its own saturation.
+const OBSERVER_LAG_WARN_MS = 250;
+
async function probeHttp(url) {
const started = Date.now();
try {
@@ -241,6 +252,9 @@ async function run() {
console.log(`[capacity] plan ${args.n} players, ${args.ramp}s ramp, ${args.hold}s hold, ${args.rate} moves/s each`);
console.log(`[capacity] baseline ${JSON.stringify(await samplePopulation(httpBase, args.coin))}`);
+ const loopLag = monitorEventLoopDelay({ resolution: 20 });
+ loopLag.enable();
+
const players = Array.from({ length: args.n }, (_, i) => new VirtualPlayer(i, args));
const rampGapMs = args.n > 1 ? (args.ramp * 1000) / args.n : 0;
@@ -285,8 +299,18 @@ async function run() {
failReasons[key] = (failReasons[key] || 0) + 1;
}
+ loopLag.disable();
+ const observerLagMs = {
+ p50: Math.round(loopLag.percentile(50) / 1e6),
+ p95: Math.round(loopLag.percentile(95) / 1e6),
+ max: Math.round(loopLag.max / 1e6),
+ };
+ const observerSaturated = observerLagMs.p95 > OBSERVER_LAG_WARN_MS;
+
const pageMs = httpProbes.filter((p) => p.status >= 200 && p.status < 400).map((p) => p.ms);
const report = {
+ observerLagMs,
+ observerSaturated,
target: args.host,
coin: args.coin,
tier: args.tier || 'general',
@@ -325,6 +349,16 @@ async function run() {
console.log(`moves sent ${report.movesSent}`);
console.log(`state patches ${report.statePatchesReceived}`);
console.log(`page latency p50 ${report.pageLatencyMs.p50}ms · p95 ${report.pageLatencyMs.p95}ms (${report.pageErrors} errors)`);
+ console.log(`observer lag p50 ${observerLagMs.p50}ms · p95 ${observerLagMs.p95}ms · max ${observerLagMs.max}ms`);
+ if (observerSaturated) {
+ console.log(
+ `\n NOTE: this harness's own event loop stalled up to ${observerLagMs.max}ms, so the page latency above\n` +
+ ' measures THIS box, not the origin. Re-measure the page from an idle process\n' +
+ ` (curl -w '%{time_total}' ${pageUrl}) before calling it a server-side regression.\n` +
+ ' The world-server numbers are unaffected: join and drop counts come from the\n' +
+ ' server\'s own accept/close decisions, not from local timing.',
+ );
+ }
if (Object.keys(failReasons).length) console.log(`fail reasons ${JSON.stringify(failReasons)}`);
let pass = true;
diff --git a/scripts/play-desktop-audit.mjs b/scripts/play-desktop-audit.mjs
index 25b7e231c..a068e2c30 100644
--- a/scripts/play-desktop-audit.mjs
+++ b/scripts/play-desktop-audit.mjs
@@ -1,9 +1,19 @@
-// Desktop audit pass for /play: console errors/warnings, failed requests,
-// boot phase timeline, HUD presence, and an interaction sweep (open/close the
-// main panels via their toolbar buttons), ending with a screenshot.
+// Browser verification sweep for /play. Loads the world the way a shared coin
+// link does, waits for the boot loader to clear, then exercises the fixes this
+// harness exists to prove:
+//
+// • no console errors / page errors / failed requests during entry
+// • the boot loader actually clears (it used to be able to strand)
+// • the reconnect helpers exist and prune ghost peers rather than throwing
+// • a coin image cannot inject CSS properties into a lobby card
+// • a malformed ?coin= is refused instead of building a phantom world
+// • the Wheel of Fortune modal has real styles (it shipped with none)
+//
+// node scripts/play-desktop-audit.mjs "<url>" [runMs]
+// SHOT=/path/shot.png node scripts/play-desktop-audit.mjs "<url>"
import { chromium } from 'playwright';
-const TARGET = process.argv[2];
+const TARGET = process.argv[2] || 'http://localhost:3000/play';
const RUN_MS = Number(process.argv[3] || 45000);
const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader'] });
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
@@ -11,63 +21,101 @@ const t0 = Date.now();
const at = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;
const issues = [];
+const note = (line) => { issues.push(line); console.log(at(), line); };
page.on('console', (m) => {
- if (m.type() === 'error' || m.type() === 'warning') {
- const line = `[console.${m.type()}] ${m.text().slice(0, 300)}`;
- issues.push(line); console.log(at(), line);
- }
+ if (m.type() === 'error' || m.type() === 'warning') note(`[console.${m.type()}] ${m.text().slice(0, 300)}`);
});
-page.on('pageerror', (e) => { const l = `[pageerror] ${String(e).slice(0, 400)}`; issues.push(l); console.log(at(), l); });
+page.on('pageerror', (e) => note(`[pageerror] ${String(e).slice(0, 400)}`));
page.on('requestfailed', (r) => {
- const l = `[reqfail] ${r.failure()?.errorText} ${r.url().slice(0, 140)}`;
- if (!/ERR_ABORTED/.test(l)) { issues.push(l); console.log(at(), l); }
+ const err = r.failure()?.errorText || '';
+ if (!/ERR_ABORTED/.test(err)) note(`[reqfail] ${err} ${r.url().slice(0, 140)}`);
});
-page.on('response', (r) => { if (r.status() >= 400) { const l = `[http ${r.status()}] ${r.url().slice(0, 140)}`; issues.push(l); console.log(at(), l); } });
+page.on('response', (r) => { if (r.status() >= 400) note(`[http ${r.status()}] ${r.url().slice(0, 140)}`); });
await page.goto(TARGET, { waitUntil: 'domcontentloaded', timeout: 60000 });
console.log(at(), 'domcontentloaded');
-// Wait for the world (deep link skips lobby): loader hidden.
+let loaderCleared = true;
try {
- await page.waitForFunction(() => {
- const l = document.getElementById('kx-loading');
- return !l || l.classList.contains('kx-hidden');
- }, { timeout: 40000 });
- console.log(at(), 'loader cleared');
-} catch { console.log(at(), 'LOADER NEVER CLEARED'); }
+ await page.waitForFunction(() => {
+ const l = document.getElementById('kx-loading');
+ return !l || l.classList.contains('kx-hidden');
+ }, { timeout: 40000 });
+ console.log(at(), 'boot loader cleared');
+} catch {
+ loaderCleared = false;
+ note('[boot] LOADER NEVER CLEARED');
+}
-// Dismiss onboarding cards.
+// Clear the onboarding cards so the world itself is on screen.
for (let i = 0; i < 5; i++) {
- await page.waitForTimeout(1800);
- const clicked = await page.evaluate(() => {
- const btn = [...document.querySelectorAll('button')]
- .find((b) => /^(continue|enter the world|got it|start|close|skip)$/i.test(b.textContent.trim()) && b.offsetParent);
- if (btn) { btn.click(); return btn.textContent.trim(); }
- return null;
- });
- if (clicked) console.log(at(), '[dismissed]', clicked);
+ await page.waitForTimeout(1500);
+ const clicked = await page.evaluate(() => {
+ const btn = [...document.querySelectorAll('button')]
+ .find((b) => /^(continue|enter the world|got it|start|close|skip)$/i.test(b.textContent.trim()) && b.offsetParent);
+ if (btn) { btn.click(); return btn.textContent.trim(); }
+ return null;
+ });
+ if (clicked) console.log(at(), '[dismissed]', clicked);
}
-// Inventory the visible HUD buttons, then click each one and see what happens.
-const buttons = await page.evaluate(() =>
- [...document.querySelectorAll('button, [role="button"]')]
- .filter((b) => b.offsetParent)
- .map((b) => ({ label: (b.getAttribute('aria-label') || b.title || b.textContent || '').trim().slice(0, 40), cls: b.className.toString().slice(0, 60) }))
-);
-console.log(at(), 'visible buttons:', JSON.stringify(buttons.slice(0, 60)));
+// ── assertions on the shipped fixes ─────────────────────────────────────────
+const checks = await page.evaluate(() => {
+ const out = {};
+ const cc = window.__CC__;
+
+ // Reconnect helpers: these were called on every drop but never defined, so a
+ // reconnect threw and ghost peers accumulated. Prove they run.
+ out.reconnectHelpers = 'absent';
+ if (cc) {
+ const hasBoth = typeof cc._markRemotesStale === 'function' && typeof cc._pruneStaleRemotes === 'function';
+ if (hasBoth) {
+ try { cc._markRemotesStale(); cc._pruneStaleRemotes(); out.reconnectHelpers = 'ok'; }
+ catch (e) { out.reconnectHelpers = 'threw: ' + e.message; }
+ }
+ }
+
+ // A coin image must not be able to inject CSS properties into a card.
+ const card = document.querySelector('.cc-card-img');
+ out.cardStyleProps = card ? [...card.style].join(',') : 'no-card';
+
+ // The wheel modal shipped with no stylesheet at all: prove the rules exist.
+ let spinRules = 0;
+ for (const sheet of document.styleSheets) {
+ try { for (const rule of sheet.cssRules) if (/\.kg-spin-/.test(rule.selectorText || '')) spinRules++; }
+ catch { /* cross-origin sheet */ }
+ }
+ out.spinWheelRules = spinRules;
-const state = await page.evaluate(() => ({
- phase: window.__CC__?.phase || null,
- canvas: !!document.getElementById('kx-canvas'),
- hud: !!document.querySelector('.cc-hud, [class*="hud"]'),
- toasts: [...document.querySelectorAll('[class*="toast"]')].map((n) => n.textContent.trim().slice(0, 80)),
+ out.phase = cc?.phase ?? null;
+ out.canvas = !!document.getElementById('kx-canvas');
+ return out;
+});
+console.log(at(), 'checks:', JSON.stringify(checks));
+
+if (checks.reconnectHelpers !== 'ok') note(`[reconnect] helpers not callable: ${checks.reconnectHelpers}`);
+if (checks.spinWheelRules === 0) note('[spin-wheel] no .kg-spin-* CSS rules loaded');
+if (/position|inset|z-index|content/.test(checks.cardStyleProps)) note(`[css-injection] card carries unexpected props: ${checks.cardStyleProps}`);
+
+// A malformed mint must land in the lobby with an explanation, not a world.
+const bad = new URL(TARGET);
+bad.search = '?coin=notarealmint';
+await page.goto(bad.toString(), { waitUntil: 'domcontentloaded', timeout: 60000 });
+await page.waitForTimeout(6000);
+const badMint = await page.evaluate(() => ({
+ phase: window.__CC__?.phase ?? null,
+ lobbyVisible: !!document.querySelector('#cc-lobby:not([hidden])'),
+ toast: document.querySelector('[class*="toast"]')?.textContent?.trim().slice(0, 120) || '',
}));
-console.log(at(), 'state:', JSON.stringify(state));
+console.log(at(), 'malformed mint:', JSON.stringify(badMint));
+if (badMint.phase === 'world') note('[deep-link] a malformed mint still built a world');
await page.waitForTimeout(Math.max(0, RUN_MS - (Date.now() - t0)));
-await page.screenshot({ path: process.env.SHOT || '/tmp/play-desktop.png' }).catch(() => {});
+if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT }).catch(() => {});
+
console.log('\n=== issue summary (' + issues.length + ') ===');
const counts = new Map();
-for (const i of issues) counts.set(i.replace(/\d+/g, 'N'), (counts.get(i.replace(/\d+/g, 'N')) || 0) + 1);
+for (const i of issues) { const k = i.replace(/\d+/g, 'N'); counts.set(k, (counts.get(k) || 0) + 1); }
for (const [k, c] of [...counts].sort((a, b) => b[1] - a[1])) console.log(' ', String(c).padStart(3), 'x', k);
+console.log(loaderCleared ? 'boot: OK' : 'boot: FAILED');
await browser.close();
diff --git a/scripts/play-economy-audit.mjs b/scripts/play-economy-audit.mjs
new file mode 100644
index 000000000..5af687f34
--- /dev/null
+++ b/scripts/play-economy-audit.mjs
@@ -0,0 +1,206 @@
+// Economy-loop audit for /play. Drives the real gather → sell → bank → spin loop
+// against a live walk_world server with a real Colyseus client, and asserts the
+// arithmetic the player is promised: a payout equals catalog price times
+// quantity, a purchase charges exactly the listed price, a deposit moves the
+// exact purse, an over-withdrawal clamps instead of minting, and progress
+// survives a reconnect.
+//
+// npm run dev:multi # in another shell
+// node scripts/play-economy-audit.mjs # ws://127.0.0.1:2567 by default
+// WS=ws://127.0.0.1:2568 node scripts/play-economy-audit.mjs
+// PID=my-audit-account node scripts/play-economy-audit.mjs
+//
+// Nothing is mocked and nothing is inferred from source: every number checked
+// here came back over the wire from the authoritative handlers, so a clean run
+// is real evidence the loop pays what it says it pays. Exits non-zero on the
+// first failed expectation so it can gate a release.
+
+import { Client } from 'colyseus.js';
+import { TREES } from '../multiplayer/src/world-features.js';
+
+const URL = process.env.WS || 'ws://127.0.0.1:2567';
+// A stable key so the persistence check at the end has something to reclaim.
+// Override to audit against a fresh account.
+const PID = process.env.PID || 'audit-economy-loop';
+const MAX_SWINGS = 25;
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const log = (...a) => console.log(...a);
+
+const results = [];
+function check(name, pass, detail) {
+ results.push({ name, pass });
+ log(`${pass ? ' ok ' : ' FAIL '} ${name}${detail ? ` — ${detail}` : ''}`);
+}
+
+// Every targeted message the economy speaks, captured as it arrives. The room
+// answers each intent with a snapshot, so the latest of each is the truth.
+function collect(room) {
+ const box = { profile: null, inv: null, notices: [], store: null, xp: [], levelups: [], spinInfo: null, denied: null, spin: null };
+ room.onMessage('profile', (m) => { box.profile = m; });
+ room.onMessage('inv', (m) => { box.inv = m; });
+ room.onMessage('notice', (m) => box.notices.push(m));
+ room.onMessage('store', (m) => { box.store = m; });
+ room.onMessage('xpgain', (m) => box.xp.push(m));
+ room.onMessage('levelup', (m) => box.levelups.push(m));
+ room.onMessage('spinInfo', (m) => { box.spinInfo = m; });
+ room.onMessage('spinDenied', (m) => { box.denied = m; });
+ room.onMessage('spinResult', (m) => { box.spin = m; });
+ // The credential that reclaims this device's progression on the next join. A
+ // raw `pid` is deliberately NOT an account key server-side (it would let any
+ // client load and spend any victim's profile), so the audit has to round-trip
+ // the sealed token exactly like the real client does.
+ room.onMessage('guestToken', (m) => { if (m?.token) guestToken = m.token; });
+ return box;
+}
+
+const held = (snap, item) => (snap?.inv || []).filter((s) => s.item === item).reduce((n, s) => n + s.qty, 0);
+const slotOf = (snap, item) => (snap?.inv || []).findIndex((s) => s.item === item);
+// `inv` deltas carry the live purse; `profile` carries purse AND bank.
+const purseOf = (box) => (box.inv?.gold ?? box.profile?.gold ?? 0);
+
+let guestToken = '';
+
+async function join() {
+ const client = new Client(URL);
+ const room = await client.joinOrCreate('walk_world', {
+ coin: '', tier: '', name: 'EconomyAudit', avatar: '', pid: PID,
+ ...(guestToken ? { guestToken } : {}),
+ });
+ const box = collect(room);
+ await sleep(1500);
+ return { room, box };
+}
+
+const { room, box } = await join();
+log(`joined ${URL} as ${room.sessionId} (purse ${box.profile?.gold}, bank ${box.profile?.bank})\n`);
+check('join delivers a full profile snapshot', !!box.profile && Array.isArray(box.profile.inv), `${box.profile?.inv?.length} pack slots`);
+
+// --- gather -------------------------------------------------------------------
+// Walk, don't teleport: the room rejects any step over MAX_STEP_M as a teleport,
+// so a single jump to the tree would silently leave the player at spawn and every
+// chop would come back "move up to a tree". Step there the way a player does.
+async function walkTo(tx, tz) {
+ const STEP = 1.0; // under the server's 1.2m anti-teleport clamp
+ let x = room.state.players?.get?.(room.sessionId)?.x ?? 0;
+ let z = room.state.players?.get?.(room.sessionId)?.z ?? 0;
+ for (let i = 0; i < 400; i += 1) {
+ const dx = tx - x, dz = tz - z;
+ const d = Math.hypot(dx, dz);
+ if (d < 0.6) break;
+ const s = Math.min(STEP, d);
+ x += (dx / d) * s;
+ z += (dz / d) * s;
+ room.send('move', { x, y: 0, z, yaw: Math.atan2(dx, dz), motion: 1 });
+ await sleep(70);
+ }
+ await sleep(300);
+ const me = room.state.players?.get?.(room.sessionId);
+ return { x: me?.x, z: me?.z };
+}
+
+const tree = TREES[0];
+const arrived = await walkTo(tree.x + 0.6, tree.z + 0.6);
+check('the player can walk to a resource node without tripping the anti-teleport clamp',
+ Math.hypot((arrived.x ?? 0) - tree.x, (arrived.z ?? 0) - tree.z) < 2.5,
+ `tree ${tree.id} at (${tree.x}, ${tree.z}), arrived (${arrived.x?.toFixed?.(1)}, ${arrived.z?.toFixed?.(1)})`);
+
+room.send('equip', { slot: (box.profile.hotbar || []).findIndex((s) => s.item === 'axe') });
+await sleep(400);
+
+const woodBefore = held(box.inv || box.profile, 'wood');
+let swings = 0;
+while (held(box.inv || box.profile, 'wood') <= woodBefore && swings < MAX_SWINGS) {
+ room.send('chop');
+ swings += 1;
+ await sleep(1400);
+}
+const woodAfter = held(box.inv || box.profile, 'wood');
+check('chopping a tree yields wood into the pack', woodAfter > woodBefore, `${woodBefore} to ${woodAfter} over ${swings} swings`);
+check('a swing always pays woodcutting XP, hit or miss', box.xp.filter((g) => g.skill === 'woodcutting').length === swings, `${box.xp.length} xp events for ${swings} swings`);
+check('XP events carry exact level boundaries so the bar needs no round trip',
+ box.xp.every((g) => Number.isFinite(g.levelXp) && (g.nextXp === null || Number.isFinite(g.nextXp))), '');
+
+// --- sell ---------------------------------------------------------------------
+room.send('storeReq');
+await sleep(500);
+const woodPrice = box.store?.sell?.find((s) => s.item === 'wood')?.price;
+check('the store catalog arrives priced by the server', Number.isFinite(woodPrice), `wood sells for ${woodPrice} cash`);
+
+const purseBeforeSell = purseOf(box);
+const stack = held(box.inv, 'wood');
+const woodSlot = slotOf(box.inv, 'wood');
+room.send('storeSell', { slot: { zone: 'inv', i: woodSlot } });
+await sleep(800);
+check('a sale pays exactly catalog price times quantity',
+ purseOf(box) === purseBeforeSell + stack * woodPrice,
+ `${purseBeforeSell} + ${stack}x${woodPrice} expected ${purseBeforeSell + stack * woodPrice}, got ${purseOf(box)}`);
+check('the sold stack left the pack', held(box.inv, 'wood') === 0, '');
+
+// Two clicks on a stack that is already gone must pay nothing the second time.
+const purseAfterSell = purseOf(box);
+room.send('storeSell', { slot: { zone: 'inv', i: woodSlot } });
+room.send('storeSell', { slot: { zone: 'inv', i: woodSlot } });
+await sleep(800);
+check('re-selling an emptied slot pays nothing', purseOf(box) === purseAfterSell, `purse held at ${purseOf(box)}`);
+
+// --- buy ----------------------------------------------------------------------
+const potion = box.store.buy.find((b) => b.item === 'healthPotion');
+const purseBeforeBuy = purseOf(box);
+const potionsBefore = held(box.inv, 'healthPotion');
+room.send('storeBuy', { item: 'healthPotion' });
+await sleep(800);
+if (purseBeforeBuy >= potion.price) {
+ check('a purchase charges exactly the listed price',
+ purseOf(box) === purseBeforeBuy - potion.price,
+ `${purseBeforeBuy} - ${potion.price} expected ${purseBeforeBuy - potion.price}, got ${purseOf(box)}`);
+ check('the purchased item landed in the pack', held(box.inv, 'healthPotion') === potionsBefore + potion.qty, '');
+} else {
+ check('an unaffordable purchase is refused and charges nothing',
+ purseOf(box) === purseBeforeBuy,
+ box.notices.at(-1)?.text);
+}
+
+// --- bank ---------------------------------------------------------------------
+const purse = purseOf(box);
+room.send('bank', { amount: purse });
+await sleep(700);
+check('a deposit moves the exact purse into the protected balance',
+ box.profile.bank >= purse && box.profile.gold === 0,
+ `bank ${box.profile.bank}, purse ${box.profile.gold}`);
+
+const bankBefore = box.profile.bank;
+room.send('bank', { amount: -999_999 });
+await sleep(700);
+check('an over-withdrawal clamps to what is banked and never mints cash',
+ box.profile.gold === bankBefore && box.profile.bank === 0,
+ `purse ${box.profile.gold}, bank ${box.profile.bank}`);
+
+// --- the wheel ----------------------------------------------------------------
+room.send('spinInfo');
+await sleep(600);
+check('spinInfo states the real level gate the UI must render',
+ Number.isFinite(box.spinInfo?.minLevel),
+ `minLevel ${box.spinInfo?.minLevel}, this account averages ${box.spinInfo?.avgLevel?.toFixed?.(2)}`);
+check('the published paytable is 20 wedges summing to exactly 100%',
+ box.spinInfo?.segments?.length === 20 && box.spinInfo.segments.reduce((n, s) => n + s.oddsPct, 0) === 100, '');
+room.send('spinFree');
+await sleep(800);
+check('a refused spin comes back with a reason the UI has copy for',
+ box.spin != null || ['level', 'cooldown', 'pack_full', 'not_at_wheel'].includes(box.denied?.reason),
+ box.spin ? `spun: ${box.spin.label}` : `denied: ${box.denied?.reason}`);
+
+// --- persistence ---------------------------------------------------------------
+const goldAtLeave = box.profile.gold;
+const bankAtLeave = box.profile.bank;
+await room.leave();
+await sleep(1500);
+const again = await join();
+check('purse and bank survive a disconnect and rejoin',
+ again.box.profile.gold === goldAtLeave && again.box.profile.bank === bankAtLeave,
+ `left with ${goldAtLeave}/${bankAtLeave}, came back to ${again.box.profile.gold}/${again.box.profile.bank}`);
+await again.room.leave();
+
+const failed = results.filter((r) => !r.pass);
+log(`\n${results.length - failed.length}/${results.length} checks passed`);
+process.exit(failed.length ? 1 : 0);
diff --git a/scripts/play-journey-audit.mjs b/scripts/play-journey-audit.mjs
index d3f89a32f..49d28097a 100644
--- a/scripts/play-journey-audit.mjs
+++ b/scripts/play-journey-audit.mjs
@@ -222,7 +222,7 @@ async function noteState(label, fn) {
// ── 1. cold load into the lobby ────────────────────────────────────────────
console.log(at(), `journey start ${BASE} @ ${width}x${height}${MOBILE ? ' (touch)' : ''}`);
-await page.goto(BASE, { waitUntil: 'domcontentloaded', timeout: 60000 });
+await page.goto(BASE, { waitUntil: 'domcontentloaded', timeout: 150000 });
// The lobby element exists from boot but stays hidden behind the loader, so
// "rendered" means a coin card (or a designed empty/error state) is on screen.
await page.waitForFunction(() => {
@@ -234,18 +234,18 @@ await page.waitForFunction(() => {
await noteState('lobby-first-paint', () => ({
skeletons: document.querySelectorAll('.cc-skeleton').length,
cards: document.querySelectorAll('.cc-card:not(.cc-skeleton)').length,
- empty: !!document.querySelector('.cc-empty'),
+ empty: !!document.querySelector('.cc-state'),
}));
await page.waitForFunction(() => document.querySelectorAll('.cc-card:not(.cc-skeleton)').length > 0
- || document.querySelector('.cc-empty') || document.querySelector('.cc-grid-error'), { timeout: 30000 })
+ || document.querySelector('.cc-state'), { timeout: 30000 })
.catch(() => console.log(at(), 'GRID NEVER RESOLVED (no cards, no empty state, no error state)'));
await noteState('lobby-loaded', () => ({
cards: document.querySelectorAll('.cc-card:not(.cc-skeleton)').length,
skeletons: document.querySelectorAll('.cc-skeleton').length,
- empty: !!document.querySelector('.cc-empty'),
- error: !!document.querySelector('.cc-grid-error'),
+ empty: !!document.querySelector('.cc-state'),
+ stateText: document.querySelector('.cc-state')?.textContent?.trim().slice(0, 140) || null,
presets: document.querySelectorAll('.cc-avatar-chip').length,
}));
@@ -263,14 +263,14 @@ if (search) {
await noteState('search-hits', () => ({
cards: document.querySelectorAll('.cc-card:not(.cc-skeleton)').length,
more: !!document.querySelector('.cc-search-more'),
- empty: !!document.querySelector('.cc-empty'),
+ empty: !!document.querySelector('.cc-state'),
}));
await search.fill('zzzqqqxnotacoin9999');
await page.waitForTimeout(4000);
await noteState('search-no-hits', () => ({
cards: document.querySelectorAll('.cc-card:not(.cc-skeleton)').length,
- empty: !!document.querySelector('.cc-empty'),
- emptyText: document.querySelector('.cc-empty')?.textContent?.trim().slice(0, 120) || null,
+ empty: !!document.querySelector('.cc-state'),
+ emptyText: document.querySelector('.cc-state')?.textContent?.trim().slice(0, 140) || null,
}));
await search.fill('');
await page.waitForTimeout(1500);
@@ -305,7 +305,7 @@ for (const [name, sel] of [['create', '.cc-create-btn'], ['gallery', '.cc-galler
// ── 4. into the $THREE world ───────────────────────────────────────────────
const worldUrl = `${BASE}${BASE.includes('?') ? '&' : '?'}coin=${HOME_COIN}`;
console.log(at(), 'entering world', worldUrl);
-await page.goto(worldUrl, { waitUntil: 'domcontentloaded', timeout: 60000 });
+await page.goto(worldUrl, { waitUntil: 'domcontentloaded', timeout: 150000 });
await page.waitForFunction(() => {
const l = document.getElementById('kx-loading');
return !l || l.classList.contains('kx-hidden') || l.hidden || getComputedStyle(l).display === 'none';
diff --git a/scripts/play-multiplayer-e2e.mjs b/scripts/play-multiplayer-e2e.mjs
index aeb9157ab..d71aba080 100644
--- a/scripts/play-multiplayer-e2e.mjs
+++ b/scripts/play-multiplayer-e2e.mjs
@@ -129,8 +129,21 @@ async function openClient(browser, tag, name) {
console.log(`${at()} [${tag}][ws open] ${ws.url().slice(0, 90)}`);
ws.on('close', () => console.log(`${at()} [${tag}][ws close]`));
});
- await page.goto(WORLD, { waitUntil: 'domcontentloaded', timeout: LOAD_MS });
- return { tag, ctx, page };
+ // A dev origin can restart under you (a config edit reloads the Vite server and
+ // drops the port for a moment), which surfaces as a connection refusal rather
+ // than a slow load. Retry the navigation instead of failing the whole run on it.
+ let lastErr;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try {
+ await page.goto(WORLD, { waitUntil: 'domcontentloaded', timeout: LOAD_MS });
+ return { tag, ctx, page };
+ } catch (err) {
+ lastErr = err;
+ console.log(`${at()} [${tag}][load retry ${attempt + 1}] ${String(err).slice(0, 120)}`);
+ await page.waitForTimeout(5000);
+ }
+ }
+ throw lastErr;
}
// Onboarding cards and the intro sheet sit over the world; clear whatever is up.
diff --git a/scripts/play-profile-check.mjs b/scripts/play-profile-check.mjs
new file mode 100644
index 000000000..101629c47
--- /dev/null
+++ b/scripts/play-profile-check.mjs
@@ -0,0 +1,91 @@
+// Exercises the /play lobby + the in-world profile card in a real browser.
+// The multiplayer server isn't running here, so we drive the inspector
+// directly with the same subject shape CoinCommunities._inspectRemote builds
+// from a peer's synced schema, and stub the profile/follow endpoints the card
+// reads so the render path is the real one.
+import { chromium } from 'playwright';
+
+const BASE = process.env.BASE || 'http://localhost:3002';
+const errors = [];
+const browser = await chromium.launch();
+const page = await browser.newPage();
+
+page.on('console', (m) => {
+ if (m.type() === 'error') errors.push(m.text());
+});
+page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
+
+// Real endpoints the card calls, answered with realistic shapes.
+await page.route('**/api/users/nirholas', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ user: {
+ id: 'u-1',
+ username: 'nirholas',
+ display_name: 'Nick',
+ bio: 'Building three.ws.',
+ location: 'Lisbon',
+ created_at: '2026-01-05T00:00:00Z',
+ avatar_url: null,
+ },
+ stats: { creations: 12, coins: 2 },
+ creations: [
+ { id: 'c1', type: 'model', title: 'Bronze sword', viewerUrl: '/viewer?src=sword', createdAt: '2026-07-01T00:00:00Z' },
+ { id: 'c2', type: 'world', title: 'Cliff village', viewerUrl: '/diorama?id=c2', createdAt: '2026-06-20T00:00:00Z' },
+ ],
+ }),
+ }),
+);
+await page.route('**/api/users/nirholas/follow', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ following: false, followed_by: true, followers_count: 128, following_count: 42 }),
+ }),
+);
+await page.route('**/api/friends', (route) =>
+ route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: { friends: [], incoming: [], outgoing: [] } }) }),
+);
+await page.route('**/api/csrf-token', (route) =>
+ route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ data: { token: 't' } }) }),
+);
+
+await page.goto(`${BASE}/play`, { waitUntil: 'domcontentloaded' });
+await page.waitForSelector('#cc-lobby', { timeout: 30_000 });
+const lobbyOk = await page.isVisible('#cc-lobby .cc-name-input');
+
+// Open the inspector exactly as a nameplate click does, with a verified handle.
+await page.evaluate(async () => {
+ localStorage.setItem('3dagent:auth-hint', JSON.stringify({ authed: true }));
+ const mod = await import('/src/shared/avatar-inspector.js');
+ mod.openAvatarInspector({ kind: 'peer', name: 'Nick', world: 'play', username: 'nirholas' });
+});
+await page.waitForSelector('[data-avi="profile"] .avi-creation', { timeout: 15_000 });
+
+const card = await page.evaluate(() => {
+ const root = document.querySelector('.avi-root');
+ const prof = root.querySelector('[data-avi="profile"]');
+ return {
+ handle: root.querySelector('.avi-subname')?.textContent,
+ bio: prof.querySelector('.avi-bio')?.textContent,
+ counts: [...prof.querySelectorAll('.avi-profile-counts span')].map((s) => s.textContent.trim()),
+ actions: [...prof.querySelectorAll('.avi-profile-actions button')].map((b) => b.textContent),
+ creations: [...prof.querySelectorAll('.avi-creation')].map((a) => a.querySelector('.avi-creation-title')?.textContent),
+ more: prof.querySelector('.avi-more')?.textContent?.trim(),
+ footer: [...root.querySelectorAll('.avi-foot a')].map((a) => a.getAttribute('href')),
+ };
+});
+
+// Guests must get no profile section at all.
+await page.evaluate(async () => {
+ const mod = await import('/src/shared/avatar-inspector.js');
+ mod.closeAvatarInspector();
+ mod.openAvatarInspector({ kind: 'peer', name: 'guest-ab12', world: 'play' });
+});
+await page.waitForTimeout(500);
+const guestHasProfile = await page.evaluate(() => !!document.querySelector('[data-avi="profile"]'));
+
+console.log(JSON.stringify({ lobbyOk, card, guestHasProfile, errors }, null, 2));
+await browser.close();
diff --git a/scripts/verify-event-countdown.mjs b/scripts/verify-event-countdown.mjs
index 38ca16613..87da8d10e 100644
--- a/scripts/verify-event-countdown.mjs
+++ b/scripts/verify-event-countdown.mjs
@@ -114,6 +114,33 @@ const waitForPill = (page) => page.waitForFunction(() => {
const cssAnim = (loc) => loc.evaluate((n) => getComputedStyle(n).animationName);
+// A first visit to /play opens the intro dialog (src/game/play-intro.js), which
+// is modal and sits over the lobby. Skip it the way a player does, so the checks
+// below exercise the lobby a returning player actually sees.
+async function dismissIntro(page) {
+ const close = page.locator('#pi-overlay .pi-close');
+ if (!(await close.count())) return;
+ await close.click({ timeout: 10000 }).catch(() => {});
+ await page.waitForSelector('#pi-overlay', { state: 'detached', timeout: 10000 }).catch(() => {});
+}
+
+// /play renders a full 3D world on a software rasterizer here, which can starve
+// a 1s interval for several seconds at a time. Sampling twice with a fixed sleep
+// reports that jank as a stopped clock, so wait for the value to actually move.
+async function ticks(page, selector, label) {
+ const before = await page.locator(selector).textContent();
+ const moved = await page.waitForFunction(
+ ([sel, prev]) => {
+ const n = document.querySelector(sel);
+ return !!n && n.textContent !== prev;
+ },
+ [selector, before],
+ { timeout: 30000 },
+ ).then(() => true, () => false);
+ const after = await page.locator(selector).textContent().catch(() => '(gone)');
+ check(label, moved, `${before} -> ${after}`);
+}
+
// ── /play lobby banner: upcoming ───────────────────────────────────────────
console.log('\n/play lobby banner, upcoming');
{
@@ -129,11 +156,9 @@ console.log('\n/play lobby banner, upcoming');
const labels = await b.locator('.cc-event-seg span').allTextContents();
check('D/H/M/S segments', JSON.stringify(labels) === '["days","hrs","min","sec"]', JSON.stringify(labels));
- const s1 = await b.locator('.cc-event-seg b').last().textContent();
- await page.waitForTimeout(2100);
- const s2 = await b.locator('.cc-event-seg b').last().textContent();
- check('clock ticks', s1 !== s2, `${s1} -> ${s2}`);
+ await ticks(page, '.cc-event-banner .cc-event-seg:last-child b', 'clock ticks');
+ await dismissIntro(page);
const cta = b.locator('.cc-event-cta');
check('CTA points into the $THREE world', (await cta.getAttribute('href')).includes(COIN));
const rest = await cta.evaluate((n) => getComputedStyle(n).boxShadow);
@@ -206,12 +231,10 @@ console.log('\n/play in-world pill');
await go(page, EVENT_LINK);
await waitForPill(page);
check('pill visible in-world', true);
- const t1 = await page.locator('.cc-event-pill [role="timer"]').textContent();
- await page.waitForTimeout(2100);
- const t2 = await page.locator('.cc-event-pill [role="timer"]').textContent();
- check('pill clock ticks', t1 !== t2, `${t1} -> ${t2}`);
+ await ticks(page, '.cc-event-pill [role="timer"]', 'pill clock ticks');
check('CTA absent while standing in the event world',
(await page.locator('.cc-event-pill a').count()) === 0);
+ await dismissIntro(page);
const x = page.locator('.cc-event-pill-x');
const xRest = await x.evaluate((n) => getComputedStyle(n).backgroundColor);
@@ -248,6 +271,7 @@ console.log('\n/play at 375px');
});
await go(page, EVENT_LINK);
await page.waitForSelector('.cc-event-banner', { timeout: WORLD_TIMEOUT });
+ await dismissIntro(page);
const doc = await page.evaluate(() => ({
scrollW: document.documentElement.scrollWidth,
clientW: document.documentElement.clientWidth,
@@ -295,10 +319,7 @@ console.log('\nhome page strip, upcoming');
return { aboveHero: b.bottom <= hero.top + 1, belowNav: b.top >= nav.bottom - 1 };
});
check('sits between the nav and the hero', place.aboveHero && place.belowNav, JSON.stringify(place));
- const c1 = await bar.locator('.tws-eventbar-clock').textContent();
- await page.waitForTimeout(2100);
- const c2 = await bar.locator('.tws-eventbar-clock').textContent();
- check('clock ticks', c1 !== c2, `${c1} -> ${c2}`);
+ await ticks(page, '.tws-eventbar-clock', 'clock ticks');
const cta = bar.locator('.tws-eventbar-cta');
check('CTA points into the $THREE world', (await cta.getAttribute('href')).includes(COIN));
diff --git a/src/game/a11y.js b/src/game/a11y.js
index f2bda6c6c..9c17f3759 100644
--- a/src/game/a11y.js
+++ b/src/game/a11y.js
@@ -2,9 +2,9 @@
//
// The world chrome is built entirely in JS across ~15 modules (HUD, store,
// bank, jobs board, wheel, cosmetics, wardrobe, friends, buy). Each one had
-// grown its own half of the modal contract — one had `aria-modal` but never
+// grown its own half of the modal contract: one had `aria-modal` but never
// moved focus into the card, another bound Escape to `window` and leaked the
-// listener, a third had neither — so keyboard and screen-reader players could
+// listener, a third had neither, so keyboard and screen-reader players could
// open a panel and then be stranded outside it with no way back.
//
// This module owns that contract once:
@@ -141,7 +141,7 @@ export function trapFocus(root, { initialFocus } = {}) {
if (released) return;
released = true;
root.removeEventListener('keydown', onKey);
- // Only pull focus back if it is still inside the panel we are closing —
+ // Only pull focus back if it is still inside the panel we are closing:
// if the player already clicked elsewhere, stealing it would be worse
// than leaving it.
if (root.contains(document.activeElement) || document.activeElement === document.body) {
@@ -197,6 +197,36 @@ function ensureRegions() {
assertiveEl = make('assertive');
}
+// ── reduced motion ──────────────────────────────────────────────────────────
+// CSS handles the DOM chrome (see the accessibility floor in
+// coincommunities.css). The parts of /play that CSS cannot reach (camera
+// shake, the wheel's spin flourish, ambient idle motion) read this instead.
+// Live-updating: a visitor who flips the OS setting mid-session gets the calm
+// world immediately, without a reload.
+
+const motionQuery = typeof matchMedia === 'function'
+ ? matchMedia('(prefers-reduced-motion: reduce)')
+ : null;
+
+/** True when the visitor has asked the OS for reduced motion. */
+export function prefersReducedMotion() {
+ return !!motionQuery?.matches;
+}
+
+/**
+ * Subscribe to changes. Fires immediately with the current value.
+ * @param {(reduced: boolean) => void} fn
+ * @returns {() => void} unsubscribe
+ */
+export function onReducedMotionChange(fn) {
+ if (typeof fn !== 'function') return () => {};
+ fn(prefersReducedMotion());
+ if (!motionQuery?.addEventListener) return () => {};
+ const handler = (e) => fn(!!e.matches);
+ motionQuery.addEventListener('change', handler);
+ return () => motionQuery.removeEventListener('change', handler);
+}
+
/**
* Announce a transient world event to screen readers.
* @param {string} text
diff --git a/src/game/chart-screen.js b/src/game/chart-screen.js
index c01d43b15..6431fff2d 100644
--- a/src/game/chart-screen.js
+++ b/src/game/chart-screen.js
@@ -32,6 +32,8 @@ const TRADES_URL = (mint, limit = 100) => {
const POLL_MS = 5000;
const REDRAW_MS = 100; // ~10fps: enough for a smooth ticker, cheap on the GPU
const MAX_POINTS = 220; // rolling price history kept across the session
+// Consecutive failed polls before the badge stops claiming the tape is live.
+const STALE_AFTER_MISSES = 3;
const CW = 1280, CH = 720; // 16:9 logical layout grid for the draw code
const SS = 1.5; // supersample: 1920x1080 backing store, crisp text
@@ -175,9 +177,13 @@ export function createChartScreen(scene, coin, opts = {}) {
let seen = new Set(); // trade tx signatures already ingested
let points = []; // [{ ts, price }] ascending by ts
let recent = []; // newest-first trades for the ticker/flow
- let status = 'loading'; // loading | live | empty | error
+ let status = 'loading'; // loading | live | stale | empty | error
let firstFill = true; // suppress the reactor on the initial backlog poll
let lastErr = 0;
+ // Consecutive failed polls. One dropped request on flaky wifi is noise; a run
+ // of them is an outage the viewer deserves to see rather than a green badge
+ // over a frozen price.
+ let misses = 0;
let pollTimer = null;
let destroyed = false;
let acc = 0; // redraw accumulator
@@ -235,9 +241,18 @@ export function createChartScreen(scene, coin, opts = {}) {
// here (not in ingest) so an empty-on-entry coin still reacts to its
// genuine first trade on a later poll.
firstFill = false;
+ misses = 0;
if (status === 'loading') status = trades.length ? 'live' : 'empty';
} catch {
lastErr = Date.now();
+ misses++;
+ // A feed that worked once and then died used to keep pulsing a green
+ // LIVE badge over a frozen price forever, because `status` only ever
+ // became 'error' when the screen had NEVER had data. Three consecutive
+ // misses is a real outage rather than one dropped poll, so say so: the
+ // badge flips to STALE and the drawn age tells the viewer how old the
+ // tape they are looking at actually is.
+ if (misses >= STALE_AFTER_MISSES && status === 'live') status = 'stale';
if (!points.length && !recent.length) status = 'error';
}
}
@@ -326,11 +341,25 @@ export function createChartScreen(scene, coin, opts = {}) {
ctx.strokeStyle = 'rgba(255,255,255,0.12)'; ctx.lineWidth = 1; ctx.stroke();
ctx.beginPath();
ctx.arc(bx + 26, by + badgeH / 2, 6, 0, Math.PI * 2);
- ctx.fillStyle = status === 'live' ? `rgba(95,208,138,${pulse})` : COL.faint;
+ ctx.fillStyle = status === 'live' ? `rgba(95,208,138,${pulse})`
+ : status === 'stale' ? 'rgba(232,178,90,0.9)'
+ : COL.faint;
ctx.fill();
ctx.fillStyle = COL.text;
ctx.font = '700 18px Inter, system-ui, sans-serif';
- ctx.fillText(status === 'live' ? 'LIVE' : status === 'error' ? 'OFFLINE' : '···', bx + 44, by + 26);
+ const badgeLabel = status === 'live' ? 'LIVE'
+ : status === 'stale' ? 'STALE'
+ : status === 'error' ? 'OFFLINE'
+ : '···';
+ ctx.fillText(badgeLabel, bx + 44, by + 26);
+ // How old the tape is, so "STALE" carries a number instead of just a mood.
+ if (status === 'stale' && lastErr) {
+ const ageS = Math.max(0, Math.round((Date.now() - lastErr) / 1000));
+ const age = ageS < 90 ? `${ageS}s` : `${Math.round(ageS / 60)}m`;
+ ctx.font = '600 13px Inter, system-ui, sans-serif';
+ ctx.fillStyle = COL.faint;
+ ctx.fillText(age, bx + 44, by + 34);
+ }
// "↗ pump.fun" affordance, bottom-right of header row
ctx.fillStyle = COL.faint;
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index 3db0cdc1d..cdb90e065 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -147,6 +147,18 @@ function timeAgo(ts) {
const DEFAULT_AVATAR = '/avatars/default.glb';
+// Crossed swords for the Adventure-mode button. Drawn rather than typed: the
+// ⚔️ emoji has no color glyph on most Linux/headless font stacks and the button
+// grayscaled it anyway, so it degraded to a bare monochrome ✕ that read as a
+// close button sitting next to the search field. Two blades on the diagonals
+// with a cross-guard low on each grip; the guards are what keep it from
+// reading as an X.
+const ADVENTURE_MARK =
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" ' +
+ 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">' +
+ '<path d="M21 3 4.5 19.5"/><path d="M7 13 11 17"/>' +
+ '<path d="M3 3 19.5 19.5"/><path d="M13 17 17 13"/></svg>';
+
export class CommunityUI {
/**
* @param {object} h handlers: { onEnter(coin), onLeave(), onChat(text), onEmote(name) }
@@ -273,7 +285,7 @@ export class CommunityUI {
type: 'button', class: 'cc-adventure', title: 'Drop into the home town: gather, fight, level up',
onclick: () => this.h.onDropIn?.(),
}, [
- el('span', { class: 'cc-adventure-ico', text: '⚔️' }),
+ el('span', { class: 'cc-adventure-ico', 'aria-hidden': 'true', html: ADVENTURE_MARK }),
el('span', { html: 'Adventure mode<small>Gather · fight · level up</small>' }),
]),
// Cold-open reopener (see play-intro.js) — the intro auto-shows once
@@ -1293,7 +1305,15 @@ export class CommunityUI {
// ---------------------------------------------------------------- HUD
_buildHud() {
- this.coinImg = el('img', { class: 'cc-coin-img', alt: '' });
+ // The coin art comes from a shared link's ?image= (an /api/img proxy in front
+ // of IPFS), so it can fail on a bad venue connection while everything else
+ // about the world is fine. A blank 40px hole in the corner of the HUD reads
+ // as broken; the monogram below stands in and keeps the banner whole.
+ this.coinImg = el('img', {
+ class: 'cc-coin-img', alt: '', loading: 'eager', decoding: 'async',
+ onerror: () => { this.coinImg.hidden = true; this.coinMono.hidden = false; },
+ });
+ this.coinMono = el('span', { class: 'cc-coin-mono', 'aria-hidden': 'true', hidden: true, text: '' });
this.coinName = el('div', { class: 'cc-coin-name', text: '' });
this.coinSym = el('span', { class: 'cc-coin-sym', text: '' });
this.onlineCount = el('span', { text: '1 online' });
@@ -1359,6 +1379,7 @@ export class CommunityUI {
]);
const banner = el('div', { class: 'cc-coin-banner' }, [
this.coinImg,
+ this.coinMono,
el('div', { class: 'cc-coin-info' }, [
this.coinName,
el('div', { class: 'cc-coin-sub' }, [
@@ -2640,8 +2661,17 @@ export class CommunityUI {
this.coinName.textContent = coin.name || 'Community';
this.coinSym.textContent = coin.symbol ? '$' + coin.symbol : '';
this.buyBtnLabel.textContent = coin.symbol ? 'Buy $' + coin.symbol.toUpperCase() : 'Buy';
- if (coin.image) { this.coinImg.src = coin.image; this.coinImg.style.display = ''; }
- else this.coinImg.style.display = 'none';
+ // Monogram first, art over it: whichever of the two ends up visible, the
+ // banner always has a 40px identity mark and never a hole.
+ this.coinMono.textContent = (coin.symbol || coin.name || '?').replace(/^\$/, '').charAt(0).toUpperCase();
+ if (coin.image) {
+ this.coinMono.hidden = true;
+ this.coinImg.hidden = false;
+ this.coinImg.src = coin.image;
+ } else {
+ this.coinImg.hidden = true;
+ this.coinMono.hidden = false;
+ }
this.refreshTierBadge(coin);
this.chatLog.textContent = '';
this._unread = 0;
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index 98364e602..94815eb37 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -10,14 +10,23 @@
--cc-bg: #060607;
--cc-bg2: #101010;
--cc-bg3: #181818;
- --cc-panel: rgba(12, 12, 14, 0.78);
+ /* Panel fill doubles as the contrast scrim. Every HUD panel floats over a
+ live 3D scene whose brightness we do not control (noon sky, snow biome, a
+ white plaza), so panel opacity is what decides whether the text on it is
+ readable. At the old 0.78 a bright scene composited the fill up to ~rgb(59)
+ and dropped the secondary label colour to 3.3:1, below AA. 0.92 pins the
+ worst case (pure-white scene) at rgb(31), where --cc-dim measures 4.9:1 and
+ --cc-faint 5.1:1. Do not lower it without re-running those numbers. */
+ --cc-panel: rgba(12, 12, 14, 0.92);
--cc-panel-solid: #0c0c0c;
--cc-edge: rgba(255, 255, 255, 0.12);
--cc-edge-soft: rgba(255, 255, 255, 0.07);
--cc-edge-hi: rgba(255, 255, 255, 0.55);
--cc-text: #f5f5f6;
--cc-dim: #8c8c92;
- --cc-faint: #5a5a60;
+ /* Was #5a5a60 at 2.8:1 even against the darkest panel, so timestamps, hint
+ copy and empty-state text failed AA everywhere they appeared. */
+ --cc-faint: #8f8f96;
--cc-accent: #ffffff; /* light is the only "colour" */
--cc-ink: #060607; /* text on white surfaces */
--cc-live: #ffffff; /* presence / live signal */
@@ -27,7 +36,7 @@
--cc-radius: 4px;
--cc-radius-sm: 2px;
/* Home-indicator / notch insets. The page is viewport-fit=cover (see
- pages/play.html), so the canvas correctly fills the display cutout — but
+ pages/play.html), so the canvas correctly fills the display cutout, but
that also means every fixed HUD control anchored with a raw `bottom:` px
lands INSIDE the home-indicator strip on a modern iPhone. There iOS both
draws its indicator over the control and swallows the first touch as a
@@ -77,7 +86,13 @@ html[data-bg="transparent"] #cc-lobby {
transition: opacity 0.5s ease;
}
#kx-loading.kx-hidden, #cc-loading.cc-hidden { opacity: 0; pointer-events: none; }
-.kx-loading-card { text-align: center; display: flex; flex-direction: column; align-items: center; }
+.kx-loading-card {
+ text-align: center; display: flex; flex-direction: column; align-items: center;
+ /* The card is taller than a laptop viewport once browser chrome is subtracted,
+ and it used to overflow silently: the progress hairline fell off the bottom
+ edge. Bound it to the viewport and let the avatar stage take the squeeze. */
+ max-height: 100dvh; padding: 16px 20px; box-sizing: border-box;
+}
.kx-loading-logo {
width: 38px; height: 38px; opacity: 0; margin-bottom: 18px;
filter: drop-shadow(0 0 14px rgba(255, 255, 255, 0.28));
@@ -89,10 +104,57 @@ html[data-bg="transparent"] #cc-lobby {
color: #fff; text-transform: uppercase;
opacity: 0; animation: kx-rise 0.7s ease 0.14s forwards;
}
+
+/* Deep-link identity (filled inline by pages/play.html from ?name/?symbol/?image).
+ When a shared link names a community, that community is the headline and the
+ product wordmark steps back to an eyebrow. */
+.kx-has-coin .kx-loading-logo { width: 30px; height: 30px; margin-bottom: 12px; }
+.kx-has-coin .kx-loading-mark {
+ font-size: 11px; letter-spacing: 0.34em; text-indent: 0.34em;
+ color: var(--cc-faint); font-weight: 700;
+}
+.kx-boot-coin {
+ display: flex; align-items: center; gap: 12px; margin-top: 14px;
+ max-width: min(420px, calc(100vw - 48px));
+ opacity: 0; animation: kx-rise 0.7s ease 0.2s forwards;
+}
+.kx-boot-coin-art {
+ position: relative; flex: none; width: 44px; height: 44px; border-radius: 50%;
+ display: grid; place-items: center; overflow: hidden;
+ background: var(--cc-bg2); border: 1px solid var(--cc-edge);
+ box-shadow: 0 0 22px rgba(255, 255, 255, 0.14);
+}
+.kx-boot-coin-art img {
+ position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;
+ opacity: 0; transition: opacity 0.4s ease;
+}
+.kx-boot-coin-ok .kx-boot-coin-art img { opacity: 1; }
+/* Monogram stand-in under the art: covers the decode window and stays put for
+ good if the gateway fetch fails, so this is never a broken-image glyph. */
+.kx-boot-coin-mono {
+ font-weight: 800; font-size: 18px; color: var(--cc-text); letter-spacing: 0.02em;
+}
+.kx-boot-coin-text {
+ display: flex; flex-direction: column; align-items: flex-start; gap: 2px;
+ min-width: 0; text-align: left;
+}
+.kx-boot-coin-name {
+ font-size: clamp(20px, 3.4vw, 28px); font-weight: 800; line-height: 1.15;
+ color: var(--cc-text); letter-spacing: -0.01em;
+ max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+}
+.kx-boot-coin-sym {
+ font-family: var(--font-mono, ui-monospace, "SF Mono", Menlo, monospace);
+ font-size: 12px; letter-spacing: 0.08em; color: var(--cc-dim);
+}
+.kx-boot-coin-sym:empty { display: none; }
/* The 3D avatar turntable — the loader's hero. Falls back to a soft glyph mark
if WebGL or the avatar asset is unavailable (.kx-boot-noavatar). */
.kx-boot-stage {
- position: relative; width: clamp(200px, 38vw, 264px); height: clamp(248px, 46vw, 320px);
+ position: relative; width: clamp(200px, 38vw, 264px);
+ /* Height yields to a short viewport (see .kx-loading-card) rather than pushing
+ the sub-label and progress bar off screen. */
+ height: min(clamp(248px, 46vw, 320px), 38dvh); min-height: 150px;
margin: 22px 0 14px; opacity: 0; animation: kx-rise 0.8s ease 0.24s forwards;
}
.kx-boot-stage::after {
@@ -101,6 +163,20 @@ html[data-bg="transparent"] #cc-lobby {
background: radial-gradient(ellipse, rgba(0, 0, 0, 0.55), transparent 70%);
filter: blur(2px); pointer-events: none;
}
+/* Lit pedestal. The avatar GLB lands a beat after the card does, and the stage
+ was a plain void until it did. This disc is on screen from the first frame, so
+ the space reads as a stage waiting for its character; it breathes while the
+ model is still downloading and settles the moment it arrives. */
+.kx-boot-stage::before {
+ content: ""; position: absolute; left: 50%; bottom: 9%; transform: translateX(-50%);
+ width: 62%; height: 30px; border-radius: 50%; pointer-events: none;
+ background: radial-gradient(ellipse, rgba(255, 255, 255, 0.16), transparent 72%);
+ animation: kx-pedestal 2.4s ease-in-out infinite;
+}
+.kx-boot-stage.kx-boot-ready::before, .kx-boot-stage.kx-boot-noavatar::before {
+ animation: none; opacity: 0.55;
+}
+@keyframes kx-pedestal { 50% { opacity: 0.45; transform: translateX(-50%) scale(0.92); } }
#kx-boot-avatar {
display: block; width: 100%; height: 100%; position: relative; z-index: 1;
opacity: 0; transition: opacity 0.6s ease;
@@ -141,9 +217,11 @@ html[data-bg="transparent"] #cc-lobby {
}
@keyframes cc-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) {
- .kx-loading-logo, .kx-loading-mark, .kx-boot-stage, .kx-loading-sub, .kx-boot-bar { animation: none; opacity: 1; }
+ .kx-loading-logo, .kx-loading-mark, .kx-boot-stage, .kx-boot-coin, .kx-loading-sub, .kx-boot-bar { animation: none; opacity: 1; }
+ .kx-boot-coin-art img { transition: none; }
.kx-boot-bar span { animation: none; width: 100%; transform: none; opacity: 0.5; }
.kx-boot-stage.kx-boot-noavatar .kx-boot-fallback { animation: none; }
+ .kx-boot-stage::before { animation: none; opacity: 0.55; }
}
/* Boot failure (most often no WebGL): the spinner is swapped for this card so a
player never gets stranded on a loader that can't resolve. */
@@ -663,14 +741,33 @@ html[data-bg="transparent"] #cc-lobby {
.cc-card-name { font-weight: 700; font-size: 15px; letter-spacing: 0.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.cc-card-meta { display: flex; align-items: center; gap: 8px; color: var(--cc-dim); font-size: 12px; font-variant-numeric: tabular-nums; }
.cc-card-sym { color: var(--cc-text); font-weight: 700; }
+/* Always on screen, in one of two weights. Hiding it until hover reserved its
+ full height anyway, so every card carried a card-wide band of dead space
+ under the meta row and the grid read as a wall of unfinished tiles. It also
+ left touch visitors (no hover) with no affordance at all, and the reveal was
+ the only thing that told a mouse user the tile was clickable. Resting state
+ is a quiet ghost button that fills the space and names the action; hover,
+ keyboard focus, and any hover-less pointer promote it to solid white. */
.cc-card-cta {
- margin-top: 11px; padding: 9px 0; text-align: center; border-radius: var(--cc-radius-sm);
- background: #fff; color: var(--cc-ink);
+ margin-top: 11px; padding: 8px 0; text-align: center; border-radius: var(--cc-radius-sm);
+ background: rgba(255, 255, 255, 0.05); color: var(--cc-dim);
+ border: 1px solid var(--cc-edge-soft);
font-weight: 700; font-size: 12px; letter-spacing: 0.06em; text-transform: uppercase;
- transform: translateY(2px); opacity: 0; transition: opacity 0.16s ease, transform 0.16s ease, filter 0.12s ease;
+ transition: background 0.16s ease, color 0.16s ease, border-color 0.16s ease, filter 0.12s ease;
+}
+.cc-card:hover .cc-card-cta,
+/* Keyboard parity: tabbing to a card must promote its call to action, not just
+ hovering it. Without this the card's primary affordance was mouse-only. */
+.cc-card:focus-visible .cc-card-cta,
+.cc-card:focus-within .cc-card-cta {
+ background: #fff; border-color: #fff; color: var(--cc-ink);
}
-.cc-card:hover .cc-card-cta { opacity: 1; transform: translateY(0); }
.cc-card-cta:hover { filter: brightness(0.92); }
+/* Touch devices never hover, so there is no second state to promote into: give
+ them the solid button outright. */
+@media (hover: none) {
+ .cc-card-cta { background: #fff; border-color: #fff; color: var(--cc-ink); }
+}
/* Featured / official town — the pinned flagship. Spans the full first row as a
hero: art on the left, identity on the right, with a bright persistent frame
@@ -751,6 +848,15 @@ html[data-bg="transparent"] #cc-lobby {
backdrop-filter: blur(10px); max-width: 70vw;
}
.cc-coin-img { width: 40px; height: 40px; border-radius: var(--cc-radius-sm); object-fit: cover; background: var(--cc-bg2); flex: none; filter: saturate(1.04) contrast(1.03); }
+/* Stand-in for coin art that failed to load (or was never supplied) so the
+ banner keeps its 40px identity mark instead of a hole. See coinMono in
+ coincommunities-ui.js. */
+.cc-coin-mono {
+ width: 40px; height: 40px; border-radius: var(--cc-radius-sm); flex: none;
+ display: grid; place-items: center;
+ background: var(--cc-bg2); border: 1px solid var(--cc-edge);
+ font-weight: 800; font-size: 17px; color: var(--cc-text); letter-spacing: 0.01em;
+}
.cc-coin-info { min-width: 0; }
.cc-coin-name { font-weight: 800; font-size: 15px; letter-spacing: 0.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.cc-coin-sub { display: flex; align-items: center; gap: 9px; color: var(--cc-dim); font-size: 12px; margin-top: 2px; font-variant-numeric: tabular-nums; }
@@ -1090,7 +1196,7 @@ body.is-zen #cc-photo-btn:hover, body.is-zen #cc-photo-btn:focus-visible { opaci
/* Phone HUD. Keyed on width OR a short touch viewport, not width alone: a
phone rotated to landscape is ~844x390, which sails past a max-width:640px
- query and silently fell back to the DESKTOP HUD mid-session — the exact
+ query and silently fell back to the DESKTOP HUD mid-session: the exact
"rotate and the HUD doesn't reflow" failure. Matching short coarse-pointer
viewports keeps the three-zone touch layout in both orientations. */
@media (max-width: 640px), (pointer: coarse) and (max-height: 520px) {
@@ -1151,11 +1257,13 @@ body.is-zen #cc-photo-btn:hover, body.is-zen #cc-photo-btn:focus-visible { opaci
.cc-adventure:hover { background: rgba(255, 255, 255, 0.06); border-color: var(--cc-edge-hi); transform: translateY(-1px); }
.cc-adventure:active { transform: translateY(1px); }
.cc-adventure:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
-/* Inline SVG mark: the grayscaled ⚔️ emoji collapsed into a bare ✕ glyph on
- most platforms, which read as a close button instead of "adventure". */
-.cc-adventure-ico { display: inline-flex; width: 18px; height: 18px; flex: none; }
-.cc-adventure-ico svg { width: 100%; height: 100%; }
.cc-adventure span { display: flex; flex-direction: column; font-weight: 700; font-size: 13px; line-height: 1.2; letter-spacing: 0.02em; }
+/* Inline SVG mark: the grayscaled ⚔️ emoji collapsed into a bare ✕ glyph on
+ most platforms, which read as a close button instead of "adventure". Selector
+ outranks the `.cc-adventure span` label rule above, which would otherwise
+ turn the icon box into a 13px column flex and squash the mark. */
+.cc-adventure .cc-adventure-ico { display: block; width: 18px; height: 18px; flex: none; color: var(--cc-text); }
+.cc-adventure .cc-adventure-ico svg { display: block; width: 100%; height: 100%; }
.cc-adventure small { font-weight: 500; font-size: 11px; color: var(--cc-dim); }
@media (max-width: 640px) { .cc-adventure small { display: none; } }
@@ -3299,3 +3407,87 @@ body.is-zen.zen-revealed #cc-zen-exit { opacity: 0.85; }
@media (prefers-reduced-motion: reduce) {
#cc-zen-exit { transition: none; }
}
+
+/* ============================================================================
+ Accessibility floor
+ ----------------------------------------------------------------------------
+ /play builds its chrome from ~15 JS modules, each shipping its own
+ stylesheet. Component-level rules cover most of this surface, but "most" is
+ how a keyboard user ends up on an invisible focus ring in the one panel
+ nobody styled. These are the guarantees that hold for the whole page, placed
+ last so they apply wherever a component did not already do better.
+ ========================================================================= */
+
+/* 1. Nothing focusable is invisible.
+ Bare-element specificity on purpose: every bespoke `.cc-x:focus-visible`
+ ring in this file outranks it, so this only fills the gaps. */
+a[href]:focus-visible,
+button:focus-visible,
+input:focus-visible,
+select:focus-visible,
+textarea:focus-visible,
+summary:focus-visible,
+[tabindex]:focus-visible,
+[role="button"]:focus-visible,
+[role="tab"]:focus-visible {
+ outline: 2px solid var(--cc-accent);
+ outline-offset: 2px;
+}
+
+/* 2. Text inputs signalled focus with a 1px border-colour change alone, which
+ is easy to miss against a moving 3D scene. Keep the border tint and add a
+ real ring. `:focus-visible` so a pointer click doesn't draw one. */
+.cc-search input:focus-visible,
+.cc-chat-input input:focus-visible,
+.cc-avatar-custom input:focus-visible,
+.cc-name-input:focus-visible,
+.cc-prop-search:focus-visible,
+.cc-forge-prompt:focus-visible,
+.cc-share-title:focus-visible,
+.npc-svc-input:focus-visible,
+.npc-chat-input:focus-visible {
+ outline: 2px solid var(--cc-accent);
+ outline-offset: 1px;
+}
+
+/* 3. The world canvas is a tab stop (see pages/play.html). Keyboard players
+ have to be able to see when the world, rather than the HUD, has the keys,
+ inset so a full-viewport outline is not clipped by the window edge. */
+#kx-canvas:focus-visible {
+ outline: 3px solid var(--cc-accent);
+ outline-offset: -3px;
+}
+
+/* 4. Text scaling. At 200% browser zoom the HUD has half the room, so the
+ fixed-width panels have to become elastic instead of clipping their labels.
+ Driven off viewport height because that is what browser zoom shrinks. */
+@media (max-height: 560px), (max-width: 900px) {
+ #cc-chat { max-height: min(46vh, 340px); }
+ .cc-coin-banner { flex-wrap: wrap; row-gap: 6px; max-width: calc(100vw - 24px); }
+ #cc-hint { display: none; }
+}
+
+/* 5. Reduced motion, page-wide. Individual components below/above tune their
+ own effects; this is the backstop that catches every decorative animation
+ the /play surface loads from its sibling stylesheets (economy, jobs board,
+ wheel, combat, photo mode) without each of them having to remember. Motion
+ that carries meaning is handled in JS instead: camera shake and the wheel's
+ spin flourish read prefers-reduced-motion directly (src/game/a11y.js). */
+@media (prefers-reduced-motion: reduce) {
+ *, *::before, *::after {
+ animation-duration: 0.01ms !important;
+ animation-iteration-count: 1 !important;
+ transition-duration: 0.01ms !important;
+ scroll-behavior: auto !important;
+ }
+ /* Pulses and sweeps are pure decoration: stop them outright rather than
+ compressing them into a one-frame strobe. */
+ .cc-dot,
+ .cc-live-dot,
+ .kx-boot-bar span,
+ .cc-skel,
+ .ec-skel-line,
+ .cc-avsw-skel {
+ animation: none !important;
+ }
+}
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 7a13c8113..5b59dff90 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -87,6 +87,7 @@ import { clearStoredPass, refreshPlayPass, loadStoredPass, storePass } from './p
import { PlaySystems } from './play-systems.js';
import { PlayActivities } from './play-activities.js';
import { WheelStation } from './wheel-station.js';
+import { WarPortal } from './war-portal.js';
import { PlayOnboard } from './play-onboard.js';
import { log } from '../shared/log.js';
import { openAvatarInspector, isAvatarInspectorOpen, closeAvatarInspector } from '../shared/avatar-inspector.js';
@@ -116,6 +117,19 @@ function clampParam(value, max) {
.slice(0, max);
}
+// A mint we are willing to open a world for: a Solana base58 address (pump.fun
+// mints, including $THREE) or an EVM 0x address (Robinhood Chain coins). Anything
+// else came from a typo or a mangled share link, and building a full world for it
+// is worse than saying so: the player would get a real district, a totem reading
+// "COMMUNITY", a room keyed on garbage, and a build layer no other player will
+// ever see, with nothing anywhere telling them the link was broken.
+const SOLANA_MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const EVM_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
+function isPlausibleMint(mint) {
+ const v = String(mint || '').trim();
+ return SOLANA_MINT_RE.test(v) || EVM_ADDRESS_RE.test(v);
+}
+
// True when the keystroke belongs to an editable surface — a DM input in the
// friends panel, a search box, a modal field. World hotkeys must never fire
// there: `b` would toggle build mode mid-word and Space would be swallowed
@@ -677,13 +691,24 @@ export class CoinCommunities {
// rewrite drops unknown params); _restoreZen() reads it at world entry,
// where the zen preference actually applies.
this._urlUi = (p.get('ui') || '').trim();
+ // Captured for the same reason: a player walking back out of a Coin Wars
+ // battle returns on /play?…&war=<matchKey>, and the war portal echoes that
+ // result into the world. enter() rewrites the URL before the portal is
+ // built, so the key has to be read here or it is gone.
+ this._urlWar = clampParam(p.get('war'), 200);
// Everything past `coin` is decoration a stranger typed into a link they
// shared: it is display-only, never trusted, and clamped to the exact
// lengths the room server clamps to (WalkRoom.onCreate) so what this client
// paints is what every peer will see. Without the clamp a 10 KB `name=`
// tears the HUD apart locally and is silently truncated for everyone else.
const mint = clampParam(p.get('coin'), 64);
- if (mint) {
+ if (mint && !isPlausibleMint(mint)) {
+ // A malformed mint means the link is broken, not that the world is empty.
+ // Say so and leave them in the lobby, where every real world is one tap
+ // away, instead of building a convincing world nobody else can join.
+ log.warn('[coincommunities] ignoring a malformed ?coin= mint:', mint);
+ this.ui.toast('That world link looks broken, so we left you in the lobby. Pick a community below.', 'warn');
+ } else if (mint) {
const tier = p.get('tier') === 'holders' ? 'holders' : 'general';
this.enter({
mint,
@@ -1219,6 +1244,7 @@ export class CoinCommunities {
coin = { ...coin, tier, holderMinUsd, holderMinTokens };
this.coin = coin;
this.ui.enterWorld(coin);
+ this._setTabTitle(coin.symbol ? '$' + coin.symbol.toUpperCase() : (coin.name || 'Community'));
document.body.classList.toggle('cc-holders', tier === 'holders');
// Reflect the community in the URL so it can be shared / refreshed into. A
// holder-world link carries &tier=holders so refreshing re-runs the gate.
@@ -1534,6 +1560,23 @@ export class CoinCommunities {
getPlayer: () => ({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z }),
net: this.net,
});
+ // F18: the War Portal, the door from this world into Coin Wars. Shows this
+ // community's real league standing off /api/wars, queues it for a battle,
+ // and hands the player to the arena at /play/war with a return link back
+ // into this exact world. It runs THIS coin's holder gate before queueing
+ // (the same overlay world entry uses), because ClashRoom only seats a
+ // fighter under the community whose coin they actually hold.
+ this.warPortal = new WarPortal({
+ scene: this.scene,
+ getPlayer: () => ({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z }),
+ coin: this.coin,
+ ui: this.ui,
+ ensureHolderPass: () => this._passHolderGate(this.coin),
+ returningMatchKey: this._urlWar,
+ });
+ // One echo per return: clear the key so re-entering another world from the
+ // lobby does not replay a battle the player already saw.
+ this._urlWar = '';
this.net.on('profile', (snap) => { this.playSystems?.setProfile(snap); this._onCosmeticsProfile(snap); });
this.net.on('inv', (delta) => this.playSystems?.applyInv(delta));
this.net.on('xpgain', (g) => this.playSystems?.onXpGain(g));
@@ -1543,8 +1586,17 @@ export class CoinCommunities {
// /internal/announce) get the centre-screen treatment; every other
// notice stays a play-systems activity toast.
if (n?.kind === 'event') return this._onEventAnnounce(n);
+ // A refused equip sends a notice and NO profile echo, so the wardrobe's
+ // pending spinner had nothing to clear it and span forever on the card.
+ // Hand it the refusal so it can drop the spinner and say why.
+ if (n?.kind === 'cosmetic' && n.ok === false) this._wardrobe?.onRejected?.(n.text);
this.playSystems?.onNotice(n);
});
+ // Event souvenir: the server granted this account a live event's free
+ // commemorative wearable. Sent exactly once, on the join where the unlock
+ // landed (never on a rejoin) so it is a moment to celebrate, not state
+ // to reconcile.
+ this.net.on('souvenir', (m) => this._onSouvenir(m));
// Friends (W09): live DMs + request/accept pushed by the social hub over this
// world's socket. The FriendsClient owns all social state — it updates its
// threads/unread counts and notifies the panel, open or not, so a DM that
@@ -1709,6 +1761,9 @@ export class CoinCommunities {
openQuests: (highlight) => this._toggleQuests(highlight),
},
radius: WORLD_RADIUS - 4,
+ // Selecting an interactive NPC from outside its range opens its profile
+ // in the shared inspector (with a Talk action) instead of doing nothing.
+ onInspectNpc: (npc) => this._inspectNpc(npc),
});
// Everything visual is up; now settle the join. Voice needs the live
// sessionId, and the profile re-request needs an open socket (it is a
@@ -2011,6 +2066,7 @@ export class CoinCommunities {
if (this.playSystems) { this.playSystems.dispose(); this.playSystems = null; }
if (this.playActivities) { this.playActivities.dispose(); this.playActivities = null; }
if (this.wheelStation) { this.wheelStation.dispose(); this.wheelStation = null; }
+ if (this.warPortal) { this.warPortal.dispose(); this.warPortal = null; }
this._disposeFriends();
this._disposeAvatarPanel();
if (this.agentCommerce) { this.agentCommerce.dispose(); this.agentCommerce = null; }
@@ -2020,6 +2076,11 @@ export class CoinCommunities {
// Close the shop + wardrobe and drop the rig binding — the next world rebuilds both.
if (this._shop?.isOpen()) this._shop.close();
if (this._wardrobe?.isOpen()) this._wardrobe.close();
+ // A souvenir card is bound to the world that granted it; leaving mid-linger
+ // must take it with us rather than float it over the lobby.
+ if (this._souvenirDrop) { this._souvenirDrop.dispose(); this._souvenirDrop = null; }
+ this._newCosmeticId = null;
+ this._cosmeticsSnap = null;
this._accessoryMgr = null;
this._previewPresetId = null; this._previewLayers = false; this._previewItem = null;
for (const [, r] of this.remotes) r.dispose();
@@ -2090,6 +2151,7 @@ export class CoinCommunities {
// avatar inspector's World row) stops naming the one we just left.
this.coin = null;
this.phase = 'lobby';
+ this._setTabTitle('');
try { history.replaceState(null, '', location.pathname); } catch { /* non-fatal */ }
this.ui.showLobby();
}
@@ -2769,10 +2831,43 @@ export class CoinCommunities {
onEquip: (id) => { this._equipCosmeticDurable(id); },
onShop: () => { this._wardrobe?.close(); this._toggleShop(); },
});
+ // A souvenir granted before the panel was ever opened still deserves the
+ // "New" highlight: the flag waits here until the panel exists.
+ if (this._newCosmeticId) this._wardrobe.markNew(this._newCosmeticId);
+ if (this._cosmeticsSnap) this._wardrobe.setProfile(this._cosmeticsSnap);
}
this._wardrobe.toggle();
}
+ // A live event just handed this player a free commemorative wearable. Two
+ // halves to the moment: a card that says what landed and offers to put it on,
+ // and a highlight waiting in the wardrobe for whoever dismisses the card and
+ // comes looking later. Both are lazy: the module only loads for the players
+ // who actually earn something.
+ async _onSouvenir(msg) {
+ const id = typeof msg?.id === 'string' ? msg.id : '';
+ if (!id) return;
+ this._newCosmeticId = id;
+ this._wardrobe?.markNew(id);
+ try {
+ if (!this._souvenirModule) this._souvenirModule = import('./event-souvenir.js');
+ const { SouvenirDrop } = await this._souvenirModule;
+ if (!this._souvenirDrop) {
+ this._souvenirDrop = new SouvenirDrop({
+ onEquip: (cid) => this._equipCosmeticDurable(cid),
+ onWardrobe: () => this._toggleWardrobe(),
+ });
+ }
+ this._souvenirDrop.show(msg);
+ } catch (err) {
+ // The item is already granted and persisted server-side; a failed chunk
+ // load costs the announcement, never the souvenir. Say so plainly rather
+ // than letting the grant pass in silence.
+ log.warn('[souvenir] drop card failed to load:', err?.message);
+ this.ui?.toast?.(`Souvenir unlocked: ${msg?.name || 'a commemorative item'}. Find it in My Fits.`, 'success');
+ }
+ }
+
// Open/close the Jobs Board (W08 hooking W05). Lazy-imported so the panel
// chunk stays out of the initial bundle until a player actually walks up to
// a quest-giver or opens Jobs from the HUD. `highlight` scrolls straight to
@@ -2837,6 +2932,10 @@ export class CoinCommunities {
if (!equipped || typeof equipped !== 'object') return;
setPlayCosmetics(equipped);
this._applyLocalCosmetics(equipped);
+ // Keep the latest snapshot so a wardrobe built LATER (the panel is lazy, and
+ // a souvenir card can be the thing that sends a player to it) opens on real
+ // data instead of a loading skeleton that only clears on the next echo.
+ this._cosmeticsSnap = snap;
// Relay the full cosmetics snapshot to the wardrobe panel (if open) so
// it reflects owned + equipped state without a separate API call.
this._wardrobe?.setProfile(snap);
@@ -2844,6 +2943,22 @@ export class CoinCommunities {
// Surface unread chat in the tab title when the page is backgrounded, so a
// new message pulls the user back. Cleared the moment they refocus the tab.
+ // Name the world in the tab. A shared /play link opened into a background tab
+ // (the normal case at an event: paste, keep browsing, come back) read as a
+ // generic "Play · Coin Communities" for every world; now the tab says which
+ // one. pages/play.html sets a provisional title from the URL before the bundle
+ // loads, and this replaces it with the resolved coin. Written through
+ // _baseTitle so an unread-chat badge composes with it instead of fighting it.
+ _setTabTitle(label) {
+ // The lobby title is whatever pages/play.html shipped (localised by i18n.js),
+ // stashed by the same inline script that sets the provisional per-coin title.
+ if (this._lobbyTitle === undefined) {
+ this._lobbyTitle = document.documentElement.dataset.lobbyTitle || document.title;
+ }
+ this._baseTitle = label ? `${label} · Play · three.ws` : this._lobbyTitle;
+ document.title = this._tabUnread ? `(${this._tabUnread}) ${this._baseTitle}` : this._baseTitle;
+ }
+
_bumpTabUnread() {
if (!document.hidden) return;
this._tabUnread = (this._tabUnread || 0) + 1;
@@ -3255,7 +3370,8 @@ export class CoinCommunities {
// Talk to the nearest townsperson (vendor/quest/flavor); if none is
// in range, try the Intel Kiosk, then fall through to the Agent
// Exchange.
- if (!this.worldLife?.interact() && !this.intelKiosk?.interact() && !this.combat?.interact() && !this.wheelStation?.interact()) this.agentCommerce?.interact();
+ if (!this.worldLife?.interact() && !this.intelKiosk?.interact() && !this.combat?.interact()
+ && !this.wheelStation?.interact() && !this.warPortal?.interact()) this.agentCommerce?.interact();
return;
}
// F is contextual: enter/exit a nearby vehicle takes priority (the
@@ -4441,6 +4557,7 @@ export class CoinCommunities {
this.playSystems?.tick(dt);
this.playActivities?.tick(dt);
this.wheelStation?.tick(dt);
+ this.warPortal?.tick(dt);
this.agentCommerce?.tick(dt);
this.intelKiosk?.tick(dt);
if (this.worldLife) { this.worldLife.setRealPeers(this.remotes.size); this.worldLife.tick(dt); }
diff --git a/src/game/community-net.js b/src/game/community-net.js
index a18545999..004c06f4d 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -12,6 +12,7 @@
import { Client, getStateCallbacks } from 'colyseus.js';
import { log } from '../shared/log.js';
import { joinRoomWithTimeout } from '../shared/colyseus-connect.js';
+import { defaultGameServerUrl } from '../shared/game-server-url.js';
const ROOM_NAME = 'walk_world';
const RECONNECT_BASE_MS = 3000;
@@ -40,39 +41,7 @@ const SEND_INTERVAL_MS = 1000 / SEND_HZ;
const POSITION_EPSILON = 0.01;
const YAW_EPSILON = 0.01;
-function defaultServerUrl() {
- if (typeof window !== 'undefined' && window.GAME_SERVER_URL) return window.GAME_SERVER_URL;
- // Local dev always talks to the local Colyseus server (`npm run dev:walk-all`),
- // ignoring the production <meta game-server> baked into the static page.
- const host = typeof location !== 'undefined' ? location.hostname : '';
- if (host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0') {
- return `ws://${host}:2567`;
- }
- if (typeof document !== 'undefined') {
- for (const sel of ['meta[name="game-server"]', 'meta[name="walk-server"]']) {
- const v = document.querySelector(sel)?.getAttribute('content')?.trim();
- if (v) return v;
- }
- }
- try {
- const envUrl = import.meta?.env?.VITE_GAME_SERVER_URL || import.meta?.env?.VITE_WALK_SERVER_URL;
- if (envUrl) return String(envUrl).trim().replace(/\/$/, '');
- } catch (_) {}
- if (typeof location !== 'undefined') {
- const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
- // Codespaces / Gitpod forward each port as its own subdomain (-3000 → -2567).
- const fwd = host.match(/^(.*)-(\d+)\.(app\.github\.dev|githubpreview\.dev|gitpod\.io)$/);
- if (fwd) return `${proto}//${fwd[1]}-2567.${fwd[3]}`;
- // Same-host:2567 is a dev convenience; the public domain doesn't expose
- // :2567. In production with no meta/env configured, return '' so the
- // caller stays single-player instead of looping on a dead socket.
- let isProd = false;
- try { isProd = import.meta?.env?.PROD === true; } catch (_) {}
- if (!isProd) return `${proto}//${host}:2567`;
- return '';
- }
- return '';
-}
+const defaultServerUrl = defaultGameServerUrl;
export class CommunityNet {
/**
diff --git a/src/game/cosmetics-wardrobe.js b/src/game/cosmetics-wardrobe.js
index e35474144..7fa3d86af 100644
--- a/src/game/cosmetics-wardrobe.js
+++ b/src/game/cosmetics-wardrobe.js
@@ -60,6 +60,9 @@ export class CosmeticsWardrobe {
this._cosmetics = null;
// pending equip animation (id being processed by server)
this._pending = null;
+ // Cosmetic id the current session just unlocked (an event souvenir drop),
+ // badged "New" until the player opens the panel and sees it.
+ this._newId = null;
this._build();
}
@@ -110,11 +113,26 @@ export class CosmeticsWardrobe {
// /play panel (src/game/a11y.js).
this._releaseModal = openModal(this.panel, { close: () => this.close(), initialFocus: this.closeBtn });
// If no profile yet show loading skeleton; it fills in when setProfile arrives.
+ // Otherwise repaint: a souvenir may have been granted (markNew) while the
+ // panel was closed, and the stale render wouldn't be showing it.
if (!this._cosmetics) this._renderLoading();
+ else { this._render(); this._scrollToNew(); }
+ }
+
+ // Bring a freshly granted souvenir into view. A wardrobe with five slots of
+ // cards can easily open with the new item below the fold, which would make the
+ // "go look in My Fits" prompt land on an apparently unchanged panel.
+ _scrollToNew() {
+ if (!this._newId) return;
+ const card = this.body.querySelector(`.cw-card[data-id="${CSS.escape(this._newId)}"]`);
+ card?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
close() {
if (!this.isOpen()) return;
+ // The panel has been seen, so the "New" highlight has done its job. Leaving
+ // it up would turn a one-time nudge into permanent noise.
+ this._newId = null;
this.root.classList.remove('cw-in');
this._releaseModal?.();
this._releaseModal = null;
@@ -142,8 +160,45 @@ export class CosmeticsWardrobe {
owned: new Set(Array.isArray(cs.owned) ? cs.owned : []),
equipped: (cs.equipped && typeof cs.equipped === 'object') ? cs.equipped : {},
};
- // Clear any pending indicator — the server responded
+ // Only clear the pending indicator once the equipped loadout actually
+ // reflects the change we asked for. Clearing on ANY profile message meant
+ // an unrelated echo (a gold change from a mob hit, a quest payout) wiped
+ // the spinner while the equip was still in flight, so the card looked
+ // settled before it was.
+ if (this._pending && this._equippedHas(this._pending)) this._pending = null;
+ if (this.isOpen()) this._render();
+ }
+
+ // Is `id` currently worn in any slot of the latest snapshot? An unequip
+ // (pending id '') settles when no slot holds the item any more, which the
+ // caller expresses by passing the emptied slot's id.
+ _equippedHas(id) {
+ const eq = this._cosmetics?.equipped || {};
+ return Object.values(eq).includes(id);
+ }
+
+ /**
+ * The server refused the in-flight equip. There is no profile echo on that
+ * path, so without this the card's pending spinner would run forever.
+ * @param {string} [text] the server's reason, shown on the panel
+ */
+ onRejected(text) {
+ if (!this._pending) return;
this._pending = null;
+ this._rejectNote = text || 'That change did not go through.';
+ if (this.isOpen()) this._render();
+ }
+
+ /**
+ * Flag a cosmetic as freshly unlocked this session, so the panel points at it
+ * when the player gets here. Called by the souvenir drop (src/game/
+ * event-souvenir.js is the toast; this is the other half of the same moment,
+ * for the player who dismisses the toast and comes looking later).
+ * @param {string} id catalog id the server just granted
+ */
+ markNew(id) {
+ if (typeof id !== 'string' || !id) return;
+ this._newId = id;
if (this.isOpen()) this._render();
}
@@ -167,6 +222,12 @@ export class CosmeticsWardrobe {
const { owned, equipped } = this._cosmetics;
this.body.textContent = '';
+ // A refused change explains itself at the top of the panel rather than
+ // leaving the player to guess why nothing happened.
+ if (this._rejectNote) {
+ this.body.appendChild(el('div', { class: 'cw-reject', role: 'status', text: this._rejectNote }));
+ }
+
for (const { slot, label, items } of BY_SLOT) {
const row = el('div', { class: 'cw-slot-row', 'data-slot': slot });
row.appendChild(el('div', { class: 'cw-slot-label', text: label }));
@@ -189,6 +250,14 @@ export class CosmeticsWardrobe {
// The none/default items are special: clicking them unequips the slot.
const isNone = item.id === DEFAULT_LOADOUT[item.slot];
+ // Event souvenirs are granted for being somewhere at some time and have no
+ // purchase path at all, so a locked one must never be dressed up as
+ // something to buy: no price, no shop shortcut, and copy that says why it
+ // is locked instead of implying money would fix it.
+ const isEvent = item.tier === 'event';
+ // The item this session's souvenir drop just granted, highlighted until the
+ // player has actually laid eyes on the panel.
+ const isNew = this._newId === item.id && isOwned;
const thumb = item.thumb
? el('img', {
@@ -197,20 +266,26 @@ export class CosmeticsWardrobe {
})
: this._swatch(item);
+ const lockedReason = isEvent
+ ? 'Event exclusive, granted to everyone in the world while the event was live'
+ : 'Locked · buy in the shop to unlock';
+
const card = el('button', {
class: 'cw-card'
+ (isOwned ? '' : ' cw-locked')
+ (isEquipped ? ' cw-equipped' : '')
- + (isPending ? ' cw-pending' : ''),
+ + (isPending ? ' cw-pending' : '')
+ + (isNew ? ' cw-new' : ''),
type: 'button',
'data-id': item.id,
+ 'data-tier': item.tier,
'aria-pressed': isOwned ? (isEquipped ? 'true' : 'false') : undefined,
'aria-label': isOwned
- ? `${isEquipped ? 'Unequip' : 'Equip'} ${item.name}`
- : `${item.name} — locked, open shop to buy`,
+ ? `${isEquipped ? 'Unequip' : 'Equip'} ${item.name}${isNew ? ', just unlocked' : ''}`
+ : `${item.name}: ${isEvent ? 'event exclusive, not for sale' : 'locked, open shop to buy'}`,
title: isOwned
? (isEquipped ? `Equipped · click to unequip` : `Click to equip ${item.name}`)
- : `Locked · buy in the shop to unlock`,
+ : lockedReason,
onclick: () => this._onCardClick(item, isOwned, isEquipped),
}, [
el('div', { class: 'cw-thumb' }, [
@@ -219,19 +294,23 @@ export class CosmeticsWardrobe {
? el('span', { class: 'cw-check', 'aria-hidden': 'true' },
[el('svg', { viewBox: '0 0 16 16', width: '12', height: '12', fill: 'none', stroke: 'currentColor', 'stroke-width': '2.2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' },
[el('polyline', { points: '2 8 6 12 14 4' })])])
- : (isOwned ? null : el('span', { class: 'cw-lock', 'aria-hidden': 'true', text: '🔒' })),
+ : (isOwned ? null : el('span', { class: 'cw-lock', 'aria-hidden': 'true', text: isEvent ? '🏅' : '🔒' })),
item.rarity !== 'common'
? el('span', { class: 'cw-rarity', 'data-rarity': item.rarity, text: RARITY_LABEL[item.rarity] })
: null,
]),
el('div', { class: 'cw-meta' }, [
el('span', { class: 'cw-name', text: isNone ? 'None' : item.name }),
- !isOwned && item.price
- ? el('span', { class: 'cw-price', text: `${item.price} $THREE` })
- : null,
+ isEvent
+ ? el('span', { class: 'cw-price cw-price-event', text: isOwned ? 'Event souvenir' : 'Not for sale' })
+ : (!isOwned && item.price
+ ? el('span', { class: 'cw-price', text: `${item.price} $THREE` })
+ : null),
isEquipped
? el('span', { class: 'cw-tag cw-tag-on', text: 'Equipped' })
- : (isPending ? el('span', { class: 'cw-tag cw-tag-pending', text: '…' }) : null),
+ : (isPending
+ ? el('span', { class: 'cw-tag cw-tag-pending', text: '…' })
+ : (isNew ? el('span', { class: 'cw-tag cw-tag-new', text: 'New' }) : null)),
]),
]);
@@ -254,14 +333,22 @@ export class CosmeticsWardrobe {
_onCardClick(item, isOwned, isEquipped) {
if (!isOwned) {
+ // A locked event souvenir has no purchase path, so sending this player to
+ // the shop would be a dead end, so the card is simply inert and its
+ // title/aria copy already explains that it had to be earned live.
+ if (item.tier === 'event') return;
// Locked item — shortcut to the shop so the player can buy it.
try { this.h.onShop?.(); } catch { /* ignore */ }
return;
}
+ // Looking at it counts as seeing it: clear the "new" highlight on the item
+ // the souvenir drop flagged, so it doesn't keep shouting after the visit.
+ if (this._newId === item.id) this._newId = null;
// Equip the item, or unequip by equipping the slot's `none` default.
const targetId = isEquipped ? DEFAULT_LOADOUT[item.slot] : item.id;
if (this._pending === targetId) return; // already in flight
this._pending = targetId;
+ this._rejectNote = ''; // a fresh attempt clears the previous refusal
// Optimistic re-render: mark the card pending immediately.
this._refreshCard(item.id, isEquipped);
try { this.h.onEquip?.(targetId); } catch { /* ignore */ }
@@ -335,6 +422,13 @@ export class CosmeticsWardrobe {
/* Per-slot section */
.cw-slot-row { display: flex; flex-direction: column; gap: 9px; }
+.cw-reject {
+ margin: 0 0 12px; padding: 9px 12px;
+ border: 1px solid rgba(224, 108, 117, 0.4);
+ border-radius: 8px;
+ background: rgba(224, 108, 117, 0.1);
+ color: #e8a0a6; font-size: 12px; line-height: 1.45;
+}
.cw-slot-label {
font-size: 10.5px; font-weight: 800; letter-spacing: 0.1em; text-transform: uppercase;
color: var(--cc-faint, #5a5a60);
@@ -433,6 +527,25 @@ export class CosmeticsWardrobe {
}
.cw-tag-on { color: #060607; background: #fff; }
.cw-tag-pending { color: var(--cc-dim, #8c8c92); background: rgba(255,255,255,.08); }
+.cw-tag-new { color: #060607; background: #fff; }
+
+/* Event souvenirs: earned, never sold. A locked one is inert: no hover lift, no
+ pointer, nothing implying a purchase would unlock it. */
+.cw-price-event { font-style: normal; letter-spacing: 0.06em; text-transform: uppercase; font-size: 9px; }
+.cw-card[data-tier="event"].cw-locked { cursor: default; }
+.cw-card[data-tier="event"].cw-locked:hover { transform: none; }
+/* The souvenir just granted this session: a steady ring, plus one attention
+ pulse that settles rather than looping forever. */
+.cw-card.cw-new { border-color: #fff; box-shadow: 0 0 16px rgba(255,255,255,.3); }
+.cw-card.cw-new .cw-thumb::after {
+ content: ''; position: absolute; inset: 0; pointer-events: none;
+ box-shadow: inset 0 0 24px rgba(255,255,255,.32);
+ animation: cw-new-pulse 1.5s ease-out 3;
+}
+@keyframes cw-new-pulse { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } }
+@media (prefers-reduced-motion: reduce) {
+ .cw-card.cw-new .cw-thumb::after { animation: none; opacity: 0.5; }
+}
@media (max-width: 480px) {
.cw-cards { grid-template-columns: repeat(auto-fill, minmax(80px, 1fr)); }
diff --git a/src/game/day-night.js b/src/game/day-night.js
index add8213b6..738a19e0d 100644
--- a/src/game/day-night.js
+++ b/src/game/day-night.js
@@ -29,8 +29,13 @@ function smoothstep(edge0, edge1, x) {
return t * t * (3 - 2 * t);
}
+// Scratch target for the string-hex branch, so a sky crossfade allocates nothing
+// per frame (this runs three times per update, every update, for the whole
+// session). Callers pass pre-built Colors where they can; biome palettes still
+// arrive as hex strings, and those parse into this one reused instance.
+const _lerpScratch = new Color();
function lerpHex(a, b, t, out) {
- return out.set(a).lerp(typeof b === 'string' ? new Color(b) : b, t);
+ return out.set(a).lerp(typeof b === 'string' ? _lerpScratch.set(b) : b, t);
}
/**
diff --git a/src/game/event-countdown.js b/src/game/event-countdown.js
index a3e268901..b48fb993f 100644
--- a/src/game/event-countdown.js
+++ b/src/game/event-countdown.js
@@ -80,6 +80,10 @@ const STYLE = `
font-size: 12.5px; font-variant-numeric: tabular-nums;
transition: opacity 0.25s ease;
}
+/* `display: flex` above outranks the browser's [hidden] { display: none }, so
+ without this the pill kept rendering over the lobby banner while _tick marked
+ it hidden: two countdowns stacked on the one screen that already has one. */
+.cc-event-pill[hidden] { display: none; }
.cc-event-pill[data-state="live"] { border-color: var(--cc-edge-hi, rgba(255,255,255,0.55)); }
.cc-event-pill a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }
.cc-event-pill a:hover { color: #fff; }
diff --git a/src/game/event-souvenir.js b/src/game/event-souvenir.js
new file mode 100644
index 000000000..e31679bb9
--- /dev/null
+++ b/src/game/event-souvenir.js
@@ -0,0 +1,242 @@
+// Event souvenir drop — the in-world moment when a live event hands you a
+// commemorative wearable.
+//
+// The server grants the item (multiplayer/src/event-drop.js →
+// WalkRoom._grantEventSouvenir) and sends ONE `souvenir` message on the join
+// where the unlock actually landed. That message is a moment, not a state sync:
+// it never repeats on a reconnect, so this surface can treat every arrival as
+// "you just earned this".
+//
+// Deliberately NOT a modal. A player mid-conversation, mid-dance-off, or lining
+// up a photo does not want their input stolen for a reward they already have.
+// This is a card that slides in over the corner of the HUD, states what landed,
+// offers to put it on in one click, and leaves on its own. Keyboard and pointer
+// both reach it; nothing traps focus; Escape dismisses.
+//
+// Rendering reads the shared catalog, so the card shows the item's real poster
+// and name rather than re-describing it — an event that swaps its souvenir needs
+// no change here.
+
+import { getCosmetic } from '../../multiplayer/src/cosmetics-catalog.js';
+
+// How long the card lingers before retiring itself. Long enough to read, notice
+// the item, and decide; short enough that it never becomes furniture. The timer
+// pauses while the pointer or keyboard focus is on the card, so it can't vanish
+// mid-decision.
+const LINGER_MS = 14_000;
+const EXIT_MS = 260;
+
+function el(tag, props = {}, kids = []) {
+ const n = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (k === 'class') n.className = v;
+ else if (k === 'text') n.textContent = v;
+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);
+ else if (v !== null && v !== undefined && v !== false) n.setAttribute(k, v === true ? '' : v);
+ }
+ for (const kid of [].concat(kids)) {
+ if (kid != null && kid !== false) n.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);
+ }
+ return n;
+}
+
+const STYLE = `
+.es-card {
+ position: fixed; right: 16px; bottom: 96px; z-index: 60;
+ width: min(340px, calc(100vw - 32px));
+ display: flex; gap: 12px; padding: 13px;
+ background: var(--cc-panel-solid, #0c0c0c);
+ border: 1px solid var(--cc-edge-hi, rgba(255,255,255,.55));
+ border-radius: var(--cc-radius, 4px);
+ box-shadow: var(--cc-shadow, 0 16px 50px rgba(0,0,0,.7)), 0 0 22px rgba(255,255,255,.18);
+ color: var(--cc-text, #f5f5f6);
+ transform: translateY(14px) scale(0.98); opacity: 0;
+ transition: transform ${EXIT_MS}ms cubic-bezier(0.16, 0.84, 0.34, 1), opacity ${EXIT_MS}ms ease;
+}
+.es-card.es-in { transform: none; opacity: 1; }
+
+.es-thumb {
+ flex: none; width: 72px; height: 72px; border-radius: 2px;
+ display: grid; place-items: center; overflow: hidden;
+ background:
+ radial-gradient(120% 120% at 50% 20%, rgba(255,255,255,0.12), rgba(255,255,255,0) 62%),
+ var(--cc-bg3, #181818);
+ border: 1px solid var(--cc-edge-soft, rgba(255,255,255,.07));
+}
+.es-thumb img { width: 100%; height: 100%; object-fit: contain; padding: 4px; }
+.es-thumb-glyph { font-size: 30px; line-height: 1; filter: grayscale(1) brightness(1.4); }
+
+.es-copy { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
+.es-kicker {
+ display: inline-flex; align-items: center; gap: 6px;
+ font-size: 9.5px; font-weight: 800; letter-spacing: 0.16em; text-transform: uppercase;
+ color: var(--cc-dim, #8c8c92);
+}
+.es-spark { width: 6px; height: 6px; border-radius: 50%; background: #fff; }
+.es-name { font-size: 14.5px; font-weight: 800; letter-spacing: 0.01em; line-height: 1.2; }
+.es-sub {
+ font-size: 11.5px; line-height: 1.35; color: var(--cc-dim, #8c8c92);
+ overflow: hidden; text-overflow: ellipsis;
+}
+.es-actions { display: flex; gap: 6px; margin-top: 7px; }
+.es-btn {
+ appearance: none; -webkit-appearance: none; font: inherit; cursor: pointer;
+ padding: 5px 11px; border-radius: 2px;
+ font-size: 11px; font-weight: 800; letter-spacing: 0.04em;
+ transition: background 0.12s ease, color 0.12s ease, border-color 0.12s ease, transform 0.12s ease;
+}
+.es-btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+.es-btn-primary { background: #fff; color: #060607; border: 1px solid #fff; }
+.es-btn-primary:hover { transform: translateY(-1px); }
+.es-btn-primary:active { transform: none; }
+.es-btn-primary[disabled] { cursor: default; opacity: 0.62; transform: none; }
+.es-btn-ghost {
+ background: none; color: var(--cc-dim, #8c8c92);
+ border: 1px solid var(--cc-edge, rgba(255,255,255,.12));
+}
+.es-btn-ghost:hover { color: var(--cc-text, #f5f5f6); border-color: var(--cc-edge-hi, rgba(255,255,255,.55)); }
+
+/* Time-remaining hairline: an honest read on when the card retires itself. */
+.es-timer {
+ position: absolute; left: 0; bottom: 0; height: 2px; width: 100%;
+ transform-origin: left center; background: rgba(255,255,255,0.5);
+ animation: es-drain linear forwards;
+}
+.es-card:hover .es-timer, .es-card:focus-within .es-timer { animation-play-state: paused; }
+@keyframes es-drain { from { transform: scaleX(1); } to { transform: scaleX(0); } }
+
+@media (prefers-reduced-motion: reduce) {
+ .es-card { transition: opacity ${EXIT_MS}ms ease; transform: none; }
+ .es-card.es-in { transform: none; }
+ .es-btn-primary:hover { transform: none; }
+}
+@media (max-width: 560px) {
+ .es-card { right: 8px; left: 8px; bottom: 80px; width: auto; }
+}
+`;
+
+let _styled = false;
+function injectStyles() {
+ if (_styled) return;
+ _styled = true;
+ document.head.appendChild(el('style', { id: 'es-style', text: STYLE }));
+}
+
+export class SouvenirDrop {
+ /**
+ * @param {object} h handlers:
+ * onEquip(id) — player wants to wear it now (scene sends equip-cosmetic)
+ * onWardrobe() — player wants to see it in the wardrobe instead
+ */
+ constructor(h = {}) {
+ this.h = h;
+ this.card = null;
+ this._timer = 0;
+ this._onKey = (e) => { if (e.key === 'Escape' && this.card) this.dismiss(); };
+ }
+
+ /**
+ * Announce a granted souvenir.
+ * @param {object} msg the server's `souvenir` payload: { id, name, eventName }
+ */
+ show(msg) {
+ const id = typeof msg?.id === 'string' ? msg.id : '';
+ const item = getCosmetic(id);
+ // An id this build's catalog doesn't know (a server running ahead of this
+ // client) is still granted and still persists — it just has no poster to
+ // show, so there is no honest moment to render. Staying silent beats a
+ // card describing an item we cannot name.
+ if (!item) return;
+
+ injectStyles();
+ this.dismiss(true);
+
+ const thumb = item.thumb
+ ? el('img', {
+ src: item.thumb, alt: '', loading: 'lazy',
+ onerror: (e) => e.target.replaceWith(el('span', { class: 'es-thumb-glyph', 'aria-hidden': 'true', text: '🏅' })),
+ })
+ : el('span', { class: 'es-thumb-glyph', 'aria-hidden': 'true', text: '🏅' });
+
+ const eventName = String(msg?.eventName || '').slice(0, 90);
+
+ this.equipBtn = el('button', {
+ class: 'es-btn es-btn-primary', type: 'button',
+ onclick: () => this._equip(item),
+ }, ['Wear it']);
+
+ this.card = el('div', {
+ class: 'es-card', role: 'status', 'aria-live': 'polite',
+ 'aria-label': `Souvenir unlocked: ${item.name}`,
+ }, [
+ el('div', { class: 'es-thumb' }, [thumb]),
+ el('div', { class: 'es-copy' }, [
+ el('div', { class: 'es-kicker' }, [
+ el('span', { class: 'es-spark', 'aria-hidden': 'true' }),
+ 'Souvenir unlocked',
+ ]),
+ el('div', { class: 'es-name', text: item.name }),
+ el('div', {
+ class: 'es-sub',
+ text: eventName ? `Yours for being at ${eventName}. Kept forever.` : 'Yours for being here. Kept forever.',
+ }),
+ el('div', { class: 'es-actions' }, [
+ this.equipBtn,
+ el('button', {
+ class: 'es-btn es-btn-ghost', type: 'button',
+ onclick: () => { this.dismiss(); try { this.h.onWardrobe?.(); } catch { /* panel unavailable */ } },
+ }, ['My Fits']),
+ ]),
+ ]),
+ el('div', { class: 'es-timer', 'aria-hidden': 'true', style: `animation-duration:${LINGER_MS}ms` }),
+ ]);
+
+ document.body.appendChild(this.card);
+ requestAnimationFrame(() => this.card?.classList.add('es-in'));
+ document.addEventListener('keydown', this._onKey, true);
+ this._arm();
+ }
+
+ // Retire on a timer, but never out from under someone who is reading or
+ // tabbing through it — the CSS pauses the hairline, and these listeners pause
+ // the real clock with it.
+ _arm() {
+ const start = () => {
+ clearTimeout(this._timer);
+ this._timer = setTimeout(() => this.dismiss(), LINGER_MS);
+ };
+ const stop = () => clearTimeout(this._timer);
+ this.card.addEventListener('mouseenter', stop);
+ this.card.addEventListener('mouseleave', start);
+ this.card.addEventListener('focusin', stop);
+ this.card.addEventListener('focusout', start);
+ start();
+ }
+
+ _equip(item) {
+ if (this.equipBtn) {
+ this.equipBtn.disabled = true;
+ this.equipBtn.textContent = 'Wearing…';
+ }
+ try { this.h.onEquip?.(item.id); } catch { /* net unavailable; card still retires */ }
+ // Leave the confirmation up briefly so the click reads as accepted, then
+ // clear the screen — the avatar itself is the real confirmation.
+ clearTimeout(this._timer);
+ this._timer = setTimeout(() => this.dismiss(), 900);
+ }
+
+ dismiss(immediate = false) {
+ const card = this.card;
+ if (!card) return;
+ this.card = null;
+ clearTimeout(this._timer);
+ document.removeEventListener('keydown', this._onKey, true);
+ if (immediate) { card.remove(); return; }
+ card.classList.remove('es-in');
+ setTimeout(() => card.remove(), EXIT_MS);
+ }
+
+ dispose() {
+ this.dismiss(true);
+ }
+}
diff --git a/src/game/hud/camera-rig.js b/src/game/hud/camera-rig.js
index 0b73cb655..e86c2114f 100644
--- a/src/game/hud/camera-rig.js
+++ b/src/game/hud/camera-rig.js
@@ -10,6 +10,13 @@
// the final transform onto the three camera each frame.
import { Vector3, Raycaster } from 'three';
+import { onReducedMotionChange } from '../a11y.js';
+
+// Camera shake and the speed FOV kick are exactly the vestibular triggers
+// `prefers-reduced-motion` exists to switch off. The rig keeps following and
+// colliding as normal; only the involuntary movement is suppressed.
+let reducedMotion = false;
+onReducedMotionChange((on) => { reducedMotion = on; });
const MODES = {
follow: { distMul: 1.0, height: 1.45, shoulder: 0.0, fov: 0, posLerp: 0.16, lookHeight: 1.4 },
@@ -53,7 +60,10 @@ export class CameraRig {
// Add camera trauma (0..1). Stacks; decays in update(). Use for damage, hard
// landings, explosions — the game-feel layer calls this.
- shake(amount = 0.4) { this._trauma = Math.min(1, this._trauma + amount); }
+ shake(amount = 0.4) {
+ if (reducedMotion) return;
+ this._trauma = Math.min(1, this._trauma + amount);
+ }
/**
* @param {number} dt
@@ -135,7 +145,7 @@ export class CameraRig {
// FOV: base + per-mode bias + a speed/sprint kick, all eased.
const speed = ctx.speed || 0;
- const kickTarget = m.fov + (ctx.sprinting ? 4 : 0) + Math.min(10, speed * 0.7);
+ const kickTarget = m.fov + (reducedMotion ? 0 : (ctx.sprinting ? 4 : 0) + Math.min(10, speed * 0.7));
this._fovKick = lerp(this._fovKick, kickTarget, 1 - Math.pow(0.001, dt));
this.fov = this.baseFov + this._fovKick;
diff --git a/src/game/hud/game-feel.css b/src/game/hud/game-feel.css
index 4fb27b504..fb6dbfb6e 100644
--- a/src/game/hud/game-feel.css
+++ b/src/game/hud/game-feel.css
@@ -83,6 +83,19 @@
.wh-feel-flourish-sub { margin-top: 4px; font-size: 14px; color: var(--cc-dim, #9a9aa2); }
@media (prefers-reduced-motion: reduce) {
- .wh-feel-vignette.is-hit, .wh-feel-flash.is-on, .wh-feel-flourish.is-show { animation-duration: 0.01s; }
+ /* Collapsing these to 0.01s (what this block used to do) turned the
+ full-screen white flash into a single-frame strobe, strictly worse for a
+ photosensitive player than the original fade. So the flash is removed
+ outright, the damage vignette keeps a single soft fade at half intensity
+ (it is the only feedback that you were hit), and the flourish just
+ appears instead of popping. */
+ .wh-feel-flash.is-on { animation: none; opacity: 0; }
+ .wh-feel-vignette { --feel-vig: 0.3; }
+ .wh-feel-flourish.is-show {
+ animation: none;
+ opacity: 1;
+ transform: translate(-50%, -50%) scale(1);
+ }
.wh-feel-money { transition: opacity 0.3s ease; }
+ .wh-feel-money.is-go { transform: translate(-50%, 0); }
}
diff --git a/src/game/npc/citizens.js b/src/game/npc/citizens.js
index 6973950d2..a94349aa0 100644
--- a/src/game/npc/citizens.js
+++ b/src/game/npc/citizens.js
@@ -35,7 +35,7 @@ export function loadCitizenPool() {
if (!_poolPromise) {
_poolPromise = fetch(GALLERY_URL, { headers: { accept: 'application/json' } })
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
- .then(({ avatars }) => (avatars || []).map(toRecord).filter((r) => r.url))
+ .then(({ avatars }) => balancePool((avatars || []).map(toRecord).filter((r) => r.url)))
.catch((e) => {
_poolPromise = null; // allow a retry on the next crowd sync
log.warn('[citizens] gallery pool failed:', e?.message);
@@ -45,6 +45,31 @@ export function loadCitizenPool() {
return _poolPromise;
}
+// Keep the crowd a crowd of individuals.
+//
+// The gallery is dominated by onboarding placeholders: a live sample of the
+// first 96 public avatars was 62 copies of "My First Agent". Drawn straight,
+// two thirds of the plaza would be identically-named clones, which reads as
+// obviously fake the moment anyone looks twice. Every real identity is kept,
+// and the anonymous remainder is capped at ANON_KEEP so those models still add
+// body variety to the background without taking over the cast.
+const ANON_KEEP = 6;
+
+function balancePool(records) {
+ const citizens = records.filter(isCitizen);
+ const anonymous = records.filter((r) => !isCitizen(r));
+ // Drop duplicate models among the anonymous keepers so the cap buys variety.
+ const seen = new Set();
+ const keptAnon = [];
+ for (const r of anonymous) {
+ if (keptAnon.length >= ANON_KEEP) break;
+ if (seen.has(r.url)) continue;
+ seen.add(r.url);
+ keptAnon.push(r);
+ }
+ return [...citizens, ...keptAnon];
+}
+
function toRecord(a) {
return {
url: a.model_url || a.base_model_url || null,
@@ -63,10 +88,33 @@ function toRecord(a) {
};
}
-// A record is a citizen (someone you can meet) when it has at least a name to
-// introduce itself with. Nameless gallery models stay anonymous scenery.
+// Names that are not identities: the onboarding defaults an untouched agent
+// still wears (mirrors PLACEHOLDER_NAMES in api/agents/public.js, which keeps
+// the same rows off the live agent wall) and the raw export filenames that come
+// off the generation lanes. An avatar wearing one of these has told us nothing
+// about who it is, so introducing it by that name would be inventing a
+// character the platform cannot back.
+const PLACEHOLDER_NAMES = new Set([
+ 'my first agent', 'agent', 'avatar', 'my avatar', 'my agent',
+ 'untitled agent', 'new agent', 'untitled', 'character', 'model',
+]);
+
+function looksAnonymous(name) {
+ const n = name.toLowerCase();
+ if (PLACEHOLDER_NAMES.has(n)) return true;
+ if (/^avatar[\s#_-]/.test(n)) return true; // "Avatar #e6f105"
+ if (/^model\s*[({[]?\d+/.test(n)) return true; // "model (11)"
+ if (/_(merged|meshy|biped|animations)/i.test(name)) return true; // export blob
+ if (name.length > 40) return true; // a filename, not a display name
+ return false;
+}
+
+// A record is a citizen (someone you can meet) when it carries a name that
+// actually identifies somebody. Nameless and placeholder-named gallery models
+// stay honest anonymous scenery: they still walk the plaza, but with no
+// nameplate, no profile, and no conversation.
export function isCitizen(record) {
- return !!(record && record.name);
+ return !!(record && record.name && !looksAnonymous(record.name));
}
// ── profile card ──────────────────────────────────────────────────────────────
diff --git a/src/game/play-intro.js b/src/game/play-intro.js
index e1a022770..073c192f4 100644
--- a/src/game/play-intro.js
+++ b/src/game/play-intro.js
@@ -67,18 +67,30 @@ function injectStyles() {
}
#pi-overlay.pi-show .pi-card { transform: none; }
+/* Skip control. The BUTTON is 44x44 (the WCAG 2.5.5 / iOS minimum) while the
+ drawn square stays 30px: the extra 7px on each side is invisible touch slop,
+ so a thumb aiming at "skip" on a phone lands on it without the intro card
+ gaining a chunky close box. Offsets are 6px (13px minus the 7px slop) so the
+ visible square sits exactly where it always did. */
.pi-close {
- position: absolute; top: 13px; right: 13px;
- width: 30px; height: 30px;
+ position: absolute; top: 6px; right: 6px;
+ width: 44px; height: 44px; padding: 0;
+ background: none; border: none; isolation: isolate;
+ color: var(--cc-dim, #8c8c92); font-size: 21px; line-height: 1; cursor: pointer;
+ display: flex; align-items: center; justify-content: center;
+ transition: color 0.12s ease;
+}
+.pi-close::before {
+ content: ""; position: absolute; inset: 7px; z-index: -1;
border-radius: var(--cc-radius-sm, 2px);
background: var(--cc-bg2, #101012);
border: 1px solid var(--cc-edge, rgba(255,255,255,0.12));
- color: var(--cc-dim, #8c8c92); font-size: 21px; line-height: 1; cursor: pointer;
- display: flex; align-items: center; justify-content: center;
- transition: color 0.12s ease, border-color 0.12s ease;
+ transition: border-color 0.12s ease, box-shadow 0.12s ease;
}
-.pi-close:hover { color: var(--cc-text, #f5f5f6); border-color: var(--cc-edge-hi, rgba(255,255,255,0.55)); }
-.pi-close:focus-visible { outline: none; border-color: #fff; box-shadow: 0 0 0 1px #fff; }
+.pi-close:hover { color: var(--cc-text, #f5f5f6); }
+.pi-close:hover::before { border-color: var(--cc-edge-hi, rgba(255,255,255,0.55)); }
+.pi-close:focus-visible { outline: none; }
+.pi-close:focus-visible::before { border-color: #fff; box-shadow: 0 0 0 1px #fff; }
.pi-tag {
font-size: 10px; font-weight: 700; letter-spacing: 0.16em; text-transform: uppercase;
@@ -114,7 +126,10 @@ function injectStyles() {
.pi-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.pi-btn {
appearance: none; font: inherit; cursor: pointer;
- padding: 11px 22px; border-radius: var(--cc-radius-sm, 2px);
+ /* 11px padding on a 13.5px/1 line box measured 40px tall, just under the 44px
+ WCAG 2.5.5 / iOS minimum. min-height carries the target the last 4px without
+ changing the padding rhythm on wider rows. */
+ padding: 11px 22px; min-height: 44px; border-radius: var(--cc-radius-sm, 2px);
font-weight: 700; font-size: 13.5px; letter-spacing: 0.02em;
display: inline-flex; align-items: center; gap: 8px;
transition: filter 0.12s ease, transform 0.1s ease, border-color 0.12s ease, color 0.12s ease, background 0.12s ease;
diff --git a/src/game/play-onboard.js b/src/game/play-onboard.js
index bc9df46f0..6ec763972 100644
--- a/src/game/play-onboard.js
+++ b/src/game/play-onboard.js
@@ -23,29 +23,68 @@ const ONBOARD_KEY = 'cc-onboarded-v1';
// ── Real controls sourced from coincommunities.js _bindInput() / _stepLocal() ─
+// `essential` marks the handful a first-timer needs in the 3-step overlay; the
+// Controls help panel always shows the full reference. Keep both in sync with
+// _bindInput() — a control listed here that no longer exists is worse than one
+// that is missing, because the player trusts it and it silently does nothing.
+
const DESK_CONTROLS = [
- { key: 'W A S D', desc: 'Move' },
+ { group: 'Move' },
+ { key: 'W A S D', desc: 'Move', essential: true },
{ key: '↑ ↓ ← →', desc: 'Move (arrows)' },
- { key: 'Shift', desc: 'Sprint' },
- { key: 'Space', desc: 'Jump' },
- { key: 'Drag', desc: 'Look around' },
+ { key: 'Shift', desc: 'Sprint', essential: true },
+ { key: 'Space', desc: 'Jump (handbrake while driving)', essential: true },
+ { key: 'Drag', desc: 'Look around', essential: true },
{ key: 'Scroll', desc: 'Zoom camera' },
- { key: 'Enter', desc: 'Chat' },
+ { key: 'C', desc: 'Cycle camera: follow, cinematic, first person, top down' },
+
+ { group: 'Interact' },
+ { key: 'E', desc: 'Talk to whoever is near: townsfolk, kiosk, agent exchange', essential: true },
+ { key: 'F', desc: 'Drive a nearby vehicle, work a station, or cast a line', essential: true },
+ { key: 'X', desc: 'Attack with the equipped weapon' },
+ { key: '1 – 6', desc: 'Hotbar slot' },
+ { key: 'I', desc: 'Inspect the nearest avatar' },
+ { key: 'Click', desc: 'Tap a player, agent, vehicle, or screen to use it' },
+
+ { group: 'Social' },
+ { key: 'Enter', desc: 'Chat', essential: true },
+ { key: 'Q', desc: 'Hold for the emote wheel, release to play', essential: true },
+ { key: 'J', desc: 'Friends' },
+ { key: 'V', desc: 'Change your avatar' },
+
+ { group: 'Build' },
{ key: 'B', desc: 'Build mode' },
- { key: 'E', desc: 'Watch agent trade' },
- { key: 'F', desc: 'Fish (near ponds)' },
- { key: 'I', desc: 'Inspect nearest avatar' },
- { key: '1–6', desc: 'Hotbar slot' },
- { key: 'Ctrl/⌘+Z', desc: 'Undo build' },
+ { key: '1 – 0', desc: 'Pick a block (while building)' },
+ { key: 'R', desc: 'Rotate the armed prop or piece' },
+ { key: 'Right-click', desc: 'Break a block (hold also works)' },
+ { key: 'Ctrl/⌘ + Z', desc: 'Undo your last build edit' },
+
+ { group: 'View' },
+ { key: 'P', desc: 'Photo mode', essential: true },
+ { key: 'Z', desc: 'Zen mode: hide every panel' },
+ { key: 'Esc', desc: 'Close the open drawer or panel' },
];
const TOUCH_CONTROLS = [
- { key: 'Joystick', desc: 'Move (bottom-left)' },
- { key: 'Drag', desc: 'Look around' },
- { key: 'Scroll / pinch', desc: 'Zoom camera' },
+ { group: 'Move' },
+ { key: 'Joystick', desc: 'Move (bottom-left)', essential: true },
+ { key: 'Drag', desc: 'Look around', essential: true },
+ { key: 'Pinch', desc: 'Zoom camera' },
+
+ { group: 'Tap to use' },
+ { key: 'A person', desc: 'Talk to townsfolk, agents, and kiosks', essential: true },
+ { key: 'A vehicle', desc: 'Take the wheel', essential: true },
+ { key: 'A player', desc: 'Inspect them' },
+ { key: 'A screen', desc: 'Open the live chart on pump.fun' },
+
+ { group: 'Social' },
+ { key: 'Chat bar', desc: 'Chat', essential: true },
+ { key: 'HUD buttons', desc: 'Emotes, friends, avatar, jobs' },
+
+ { group: 'Build' },
{ key: '⛏ button', desc: 'Build mode' },
- { key: 'Tap agents', desc: 'Watch agent trade' },
- { key: 'Chat bar', desc: 'Chat' },
+ { key: 'Tap', desc: 'Place a block (while building)' },
+ { key: 'Hold', desc: 'Break a block (while building)' },
];
// ── Helpers ───────────────────────────────────────────────────────────────────
@@ -191,7 +230,7 @@ export class PlayOnboard {
// ── Body ──
let body;
if (slide.isControls) {
- body = this._buildControlsGrid(isTouch());
+ body = this._buildControlsGrid(isTouch(), true);
} else {
body = mk('p', { className: 'po-body', textContent: slide.body });
}
@@ -254,10 +293,17 @@ export class PlayOnboard {
// ── Controls grid (used in overlay slide + help panel) ─────────────────────
- _buildControlsGrid(touch) {
- const list = touch ? TOUCH_CONTROLS : DESK_CONTROLS;
+ // `essentialsOnly` trims the list to what a first-timer needs mid-onboarding;
+ // the help panel passes false and gets every binding, grouped.
+ _buildControlsGrid(touch, essentialsOnly = false) {
+ const all = touch ? TOUCH_CONTROLS : DESK_CONTROLS;
+ const list = essentialsOnly ? all.filter((c) => c.essential) : all;
const grid = mk('div', { className: 'po-ctrl-grid' });
- for (const { key, desc } of list) {
+ for (const { group, key, desc } of list) {
+ if (group) {
+ grid.appendChild(mk('div', { className: 'po-ctrl-group', textContent: group }));
+ continue;
+ }
const row = mk('div', { className: 'po-ctrl-row' });
row.appendChild(mk('kbd', { className: 'po-kbd', textContent: key }));
row.appendChild(mk('span', { className: 'po-ctrl-desc', textContent: desc }));
@@ -419,6 +465,14 @@ body.po-onboarding #cc-joystick { z-index: 60; }
.po-ctrl-grid::-webkit-scrollbar { width: 4px; }
.po-ctrl-grid::-webkit-scrollbar-thumb { background: var(--cc-edge, rgba(255,255,255,0.12)); }
.po-ctrl-row { display: contents; }
+.po-ctrl-group {
+ grid-column: 1 / -1;
+ margin-top: 10px; padding-bottom: 3px;
+ border-bottom: 1px solid var(--cc-edge, rgba(255,255,255,0.12));
+ font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase;
+ color: var(--cc-dim, #8c8c92);
+}
+.po-ctrl-group:first-child { margin-top: 0; }
.po-kbd {
display: inline-flex; align-items: center; justify-content: center;
background: rgba(255,255,255,0.06);
diff --git a/src/game/play-systems.css b/src/game/play-systems.css
index cf3729967..de719d12a 100644
--- a/src/game/play-systems.css
+++ b/src/game/play-systems.css
@@ -145,6 +145,16 @@
transition: transform 0.1s ease, filter 0.12s ease, opacity 0.12s ease;
animation: ps-rise 0.18s ease both;
}
+/* Contextual-action stacking contract. Three independent systems mount a
+ `.ps-action` button at the same fixed spot: play-systems (fish/equip rod),
+ play-activities (`.pa-action`: chop/mine/cook/gather) and wheel-station
+ (`.wh-action`: spin). Standing where two are in range used to render them
+ pixel-perfectly on top of each other, so only the last-appended one was
+ clickable. Each modifier claims its own row, bottom-up, in the order a player
+ is most likely to want them. Keep the 52px step in sync with the mobile
+ overrides at the bottom of this file. */
+.ps-action.pa-action { bottom: 184px; }
+.ps-action.wh-action { bottom: 236px; }
.ps-action:hover { filter: brightness(0.9); transform: translateX(-50%) translateY(-2px); }
.ps-action:active { transform: translateX(-50%) scale(0.97); }
.ps-action.is-disabled {
@@ -480,6 +490,10 @@
/* Contextual action button and tool rail ride above the lifted hotbar so the
bottom-left joystick zone stays completely clear. */
.ps-action { bottom: 208px; }
+ /* Same 52px stacking step as the desktop rules above, rebased on the
+ mobile origin so the joystick and hotbar still clear all three. */
+ .ps-action.pa-action { bottom: 260px; }
+ .ps-action.wh-action { bottom: 312px; }
.ps-rail { top: auto; bottom: 232px; transform: none; right: 10px; }
.ps-panel { right: 10px; left: 10px; width: auto; max-width: none; }
}
diff --git a/src/game/spin-wheel-ui.js b/src/game/spin-wheel-ui.js
index cf789c39e..cda1ce1b1 100644
--- a/src/game/spin-wheel-ui.js
+++ b/src/game/spin-wheel-ui.js
@@ -20,7 +20,7 @@
import './spin-wheel.css';
import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';
-import { openModal } from './a11y.js';
+import { openModal, prefersReducedMotion } from './a11y.js';
const NETWORK = 'mainnet';
const SPIN_DECIMALS = 6; // $THREE uses 6 decimals (same as pump.fun mints)
@@ -498,6 +498,10 @@ class SpinWheel {
_startSpin() {
this._stopSpin();
+ // Reduced motion: no idle whirl while we wait. The status line and the
+ // live result region already say a spin is in flight, so nothing is lost
+ // except the part that makes people queasy.
+ if (prefersReducedMotion()) return;
this._spinVel = 0.45; // rad/frame while waiting for the server outcome
const tick = () => {
this.rotation = (this.rotation + this._spinVel) % (Math.PI * 2);
@@ -520,6 +524,14 @@ class SpinWheel {
const cur = ((this.rotation % TAU) + TAU) % TAU;
// Target rotation (mod TAU) that puts segment `index` centre at the top.
const targetMod = ((-index * seg) % TAU + TAU) % TAU;
+ // Reduced motion: land on the server's segment immediately rather than
+ // riding five full turns of flourish. The outcome is identical either way.
+ if (prefersReducedMotion()) {
+ this.rotation = targetMod;
+ this._drawWheel();
+ done && done();
+ return;
+ }
const spins = 5; // full turns of flourish before landing
const delta = spins * TAU + ((targetMod - cur + TAU) % TAU);
const from = this.rotation;
diff --git a/src/game/voice-chat.js b/src/game/voice-chat.js
index 1c0218915..4e87dc93a 100644
--- a/src/game/voice-chat.js
+++ b/src/game/voice-chat.js
@@ -113,10 +113,20 @@ export class VoiceChat {
const Ctx = window.AudioContext || window.webkitAudioContext;
this.ctx = new Ctx();
if (this.ctx.state === 'suspended') await this.ctx.resume();
- this.localStream = await navigator.mediaDevices.getUserMedia({
- audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
- video: false,
- });
+ try {
+ this.localStream = await navigator.mediaDevices.getUserMedia({
+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
+ video: false,
+ });
+ } catch (err) {
+ // A denied or failed mic must not strand the AudioContext we just
+ // opened. Browsers cap concurrent contexts (~6), so leaking one per
+ // refusal made voice permanently unopenable after a few "Block" taps,
+ // long after the user changed their mind.
+ try { await this.ctx.close(); } catch { /* already closed */ }
+ this.ctx = null;
+ throw err;
+ }
this.localTrack = this.localStream.getAudioTracks()[0] || null;
// Meter our own mic so we can show the local "speaking" pulse. This tap is
@@ -165,12 +175,18 @@ export class VoiceChat {
.filter(({ p }) => p.voice)
.sort((a, b) => a.d - b.d);
const keep = new Set(inVoice.slice(0, MAX_VOICE_PEERS).map(({ p }) => p.id));
+ // Rank hysteresis. `keep` decides who we DIAL; dropping used the same
+ // boundary, so in a crowd a peer oscillating around rank N was closed and
+ // re-dialled on consecutive frames, tearing down and re-handshaking WebRTC
+ // continuously and dropping audio for everyone involved. Hold an already
+ // connected peer until they fall two ranks past the cap.
+ const hold = new Set(inVoice.slice(0, MAX_VOICE_PEERS + 2).map(({ p }) => p.id));
for (const { p, d } of inVoice) {
const peer = this.peers.get(p.id);
if (peer) {
this._setPanner(peer, p);
- if (d > DISCONNECT_RANGE || !keep.has(p.id)) this._closePeer(p.id);
+ if (d > DISCONNECT_RANGE || !hold.has(p.id)) this._closePeer(p.id);
} else if (keep.has(p.id) && d < CONNECT_RANGE && this.selfId < p.id) {
// Deterministic initiator: the lower sessionId dials, so two peers
// entering range simultaneously never both offer.
diff --git a/src/game/war-portal.css b/src/game/war-portal.css
new file mode 100644
index 000000000..d138511f8
--- /dev/null
+++ b/src/game/war-portal.css
@@ -0,0 +1,315 @@
+/* War Portal (F18) — the in-world Coin Wars panel and its prompt button.
+ *
+ * Scoped entirely to .wp-* so it can never reach into the rest of the /play HUD.
+ * Colours come from the world's existing dark UI vocabulary; the only accents are
+ * the two sides of a war (us / them) and the win/loss/draw verdicts, which have
+ * to be distinguishable at a glance without relying on colour alone (every one
+ * also carries a text tag). */
+
+.wp-action {
+ /* Inherits the shared .ps-action prompt chip; only the accent differs so the
+ * war prompt is distinguishable from fish/chop/spin at the same glance. */
+ --ps-accent: #8fd0ff;
+}
+
+/* ── overlay ─────────────────────────────────────────────────────────────── */
+
+.wp-root {
+ position: fixed;
+ inset: 0;
+ z-index: 60;
+ display: flex;
+ align-items: flex-end;
+ justify-content: center;
+ pointer-events: none;
+}
+
+.wp-scrim {
+ position: absolute;
+ inset: 0;
+ background: rgba(4, 4, 6, 0.55);
+ backdrop-filter: blur(2px);
+ opacity: 0;
+ transition: opacity 180ms ease;
+ pointer-events: auto;
+}
+
+.wp-panel {
+ position: relative;
+ width: min(560px, calc(100vw - 24px));
+ max-height: min(78vh, 720px);
+ margin: 0 0 max(16px, env(safe-area-inset-bottom));
+ display: flex;
+ flex-direction: column;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 16px;
+ background: linear-gradient(180deg, #141419, #0b0b0e);
+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.6);
+ color: #f5f5f6;
+ font: 400 14px/1.5 Inter, system-ui, sans-serif;
+ transform: translateY(18px);
+ opacity: 0;
+ transition: transform 200ms cubic-bezier(0.2, 0.8, 0.3, 1), opacity 200ms ease;
+ pointer-events: auto;
+}
+
+.wp-root.wp-in .wp-scrim { opacity: 1; }
+.wp-root.wp-in .wp-panel { transform: translateY(0); opacity: 1; }
+
+@media (min-width: 720px) {
+ .wp-root { align-items: center; }
+ .wp-panel { margin: 0; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .wp-scrim,
+ .wp-panel { transition: none; }
+ .wp-panel { transform: none; }
+}
+
+/* ── head / foot ─────────────────────────────────────────────────────────── */
+
+.wp-head {
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+ padding: 16px 16px 12px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.07);
+}
+
+.wp-head h2 {
+ margin: 0;
+ font: 800 19px/1.2 Inter, system-ui, sans-serif;
+ letter-spacing: 0.01em;
+}
+
+.wp-head-sub {
+ margin: 4px 0 0;
+ color: #8c8c92;
+ font-size: 13px;
+}
+
+.wp-head-t { flex: 1 1 auto; min-width: 0; }
+
+.wp-x {
+ flex: 0 0 auto;
+ width: 32px;
+ height: 32px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 9px;
+ background: rgba(255, 255, 255, 0.04);
+ color: #c9c9cf;
+ font-size: 14px;
+ cursor: pointer;
+ transition: background 120ms ease, color 120ms ease, transform 120ms ease;
+}
+
+.wp-x:hover { background: rgba(255, 255, 255, 0.1); color: #fff; }
+.wp-x:active { transform: scale(0.94); }
+.wp-x:focus-visible { outline: 2px solid #8fd0ff; outline-offset: 2px; }
+
+.wp-body {
+ flex: 1 1 auto;
+ overflow-y: auto;
+ padding: 12px 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ overscroll-behavior: contain;
+}
+
+.wp-foot {
+ padding: 12px 16px max(14px, env(safe-area-inset-bottom));
+ border-top: 1px solid rgba(255, 255, 255, 0.07);
+}
+
+.wp-cta {
+ width: 100%;
+ padding: 12px 16px;
+ border: 1px solid rgba(143, 208, 255, 0.5);
+ border-radius: 11px;
+ background: linear-gradient(180deg, rgba(143, 208, 255, 0.22), rgba(143, 208, 255, 0.1));
+ color: #eaf6ff;
+ font: 700 15px/1 Inter, system-ui, sans-serif;
+ cursor: pointer;
+ transition: background 140ms ease, transform 100ms ease, border-color 140ms ease;
+}
+
+.wp-cta:hover:not(:disabled) { background: linear-gradient(180deg, rgba(143, 208, 255, 0.32), rgba(143, 208, 255, 0.16)); }
+.wp-cta:active:not(:disabled) { transform: scale(0.985); }
+.wp-cta:focus-visible { outline: 2px solid #8fd0ff; outline-offset: 2px; }
+.wp-cta:disabled { opacity: 0.55; cursor: default; }
+
+.wp-foot-note {
+ margin: 8px 0 0;
+ color: #7a7a82;
+ font-size: 12px;
+ text-align: center;
+}
+
+/* ── cards ───────────────────────────────────────────────────────────────── */
+
+.wp-card {
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: 12px;
+ background: rgba(255, 255, 255, 0.025);
+ padding: 12px 14px;
+}
+
+.wp-card-t {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0 0 8px;
+ color: #a5a5ad;
+ font: 700 11px/1 Inter, system-ui, sans-serif;
+ letter-spacing: 0.09em;
+ text-transform: uppercase;
+}
+
+.wp-empty-b {
+ margin: 0;
+ color: #9a9aa2;
+ font-size: 13px;
+}
+
+.wp-empty { background: rgba(255, 255, 255, 0.015); }
+.wp-retry { border-color: rgba(224, 108, 117, 0.35); }
+
+.wp-retry-btn {
+ margin-top: 10px;
+ padding: 8px 14px;
+ border: 1px solid rgba(255, 255, 255, 0.16);
+ border-radius: 9px;
+ background: rgba(255, 255, 255, 0.05);
+ color: #eaeaf0;
+ font: 600 13px/1 Inter, system-ui, sans-serif;
+ cursor: pointer;
+ transition: background 120ms ease, transform 100ms ease;
+}
+
+.wp-retry-btn:hover { background: rgba(255, 255, 255, 0.11); }
+.wp-retry-btn:active { transform: scale(0.97); }
+.wp-retry-btn:focus-visible { outline: 2px solid #8fd0ff; outline-offset: 2px; }
+
+/* ── standings ───────────────────────────────────────────────────────────── */
+
+.wp-stats {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 10px 12px;
+ margin: 0;
+}
+
+.wp-stats dt {
+ color: #7a7a82;
+ font: 700 10px/1 Inter, system-ui, sans-serif;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+
+.wp-stats dd {
+ margin: 3px 0 0;
+ font: 800 18px/1.1 Inter, system-ui, sans-serif;
+}
+
+/* ── rows ────────────────────────────────────────────────────────────────── */
+
+.wp-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.wp-row {
+ display: grid;
+ grid-template-columns: auto auto 1fr auto;
+ align-items: baseline;
+ gap: 10px;
+ padding: 6px 8px;
+ border-radius: 8px;
+ font-size: 13px;
+}
+
+.wp-row:nth-child(odd) { background: rgba(255, 255, 255, 0.022); }
+.wp-row-me { background: rgba(143, 208, 255, 0.1) !important; }
+
+.wp-row-tag {
+ font: 800 11px/1 Inter, system-ui, sans-serif;
+ letter-spacing: 0.06em;
+ color: #9a9aa2;
+}
+
+.wp-row-win .wp-row-tag { color: #5fd08a; }
+.wp-row-loss .wp-row-tag { color: #e06c75; }
+.wp-row-draw .wp-row-tag { color: #c9a227; }
+
+.wp-row-score { font: 800 13px/1 Inter, system-ui, sans-serif; }
+.wp-row-vs { color: #d8d8de; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.wp-row-when { color: #6f6f77; font-size: 12px; }
+
+.wp-feed .wp-row { grid-template-columns: 1fr auto; }
+
+/* ── live war ────────────────────────────────────────────────────────────── */
+
+.wp-live { border-color: rgba(143, 208, 255, 0.3); }
+
+.wp-live-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: #ff6b6b;
+ box-shadow: 0 0 0 0 rgba(255, 107, 107, 0.6);
+ animation: wp-pulse 1.8s ease-out infinite;
+}
+
+@keyframes wp-pulse {
+ 0% { box-shadow: 0 0 0 0 rgba(255, 107, 107, 0.55); }
+ 70% { box-shadow: 0 0 0 8px rgba(255, 107, 107, 0); }
+ 100% { box-shadow: 0 0 0 0 rgba(255, 107, 107, 0); }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .wp-live-dot { animation: none; }
+}
+
+.wp-score {
+ display: grid;
+ grid-template-columns: 1fr auto 1fr;
+ align-items: center;
+ gap: 10px;
+ margin-bottom: 8px;
+}
+
+.wp-score-side {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 2px;
+ min-width: 0;
+}
+
+.wp-score-n { font: 900 34px/1 Inter, system-ui, sans-serif; }
+.wp-side-us .wp-score-n { color: #7fd8ff; }
+.wp-side-them .wp-score-n { color: #ff9d7a; }
+
+.wp-score-l {
+ max-width: 100%;
+ font: 700 13px/1.2 Inter, system-ui, sans-serif;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.wp-score-f { color: #6f6f77; font-size: 11px; }
+.wp-score-vs { color: #5a5a60; font: 700 13px/1 Inter, system-ui, sans-serif; }
+
+.wp-live-clock {
+ margin: 0 0 8px;
+ text-align: center;
+ font: 700 14px/1 Inter, system-ui, sans-serif;
+ color: #e6e6ec;
+}
diff --git a/src/game/war-portal.js b/src/game/war-portal.js
new file mode 100644
index 000000000..f513edd11
--- /dev/null
+++ b/src/game/war-portal.js
@@ -0,0 +1,1135 @@
+// War Portal — the Coin Wars door standing in every /play coin world (F18).
+//
+// Coin Wars is a finished game: ClashRoom runs real community-vs-community
+// battles with a countdown, a round clock, sudden death and an Elo league behind
+// it. Until this landed, none of that was reachable from inside a world — a
+// player standing in their coin's plaza had no way to know wars existed. This is
+// the door.
+//
+// Three jobs, one landmark:
+// 1. THE BOARD. An in-world screen (canvas → CanvasTexture, same technique as
+// the chart jumbotron) painted with this community's real league standing,
+// the last battles it fought, and any war running right now. Data comes
+// from /api/wars, which folds the battle ledger through the SAME Elo math
+// the arena uses (multiplayer/src/war-standings.js) — nothing is recomputed
+// here.
+// 2. THE QUEUE. Press E and the portal runs this coin's holder gate (the exact
+// gate the Holders world runs), queues the community for a battle, and the
+// moment a second community is waiting hands the player through to the
+// arena at /play/war with a signed war ticket and a return link that
+// carries the full coin identity — so walking back in lands in this same
+// world, not the lobby.
+// 3. SPECTATING. While a war involving this coin is live, the board becomes a
+// scoreboard: score, round clock, kill feed. Text and numbers off a cheap
+// poll, never a second 3D render.
+//
+// Idle cost is zero. Nothing is fetched until a player walks inside the board's
+// legibility ring (WAR_PORTAL_BOARD_REACH), and every timer stops when they walk
+// back out or the world is torn down.
+
+import {
+ Group, Mesh, MeshStandardMaterial, MeshBasicMaterial,
+ BoxGeometry, CylinderGeometry, PlaneGeometry, RingGeometry, TorusGeometry,
+ DoubleSide,
+} from 'three';
+import { makeScreenCanvas, makeScreenTexture, screenMaterial } from './screen-texture.js';
+import {
+ WAR_PORTAL, warPortalInRange, warPortalBoardInRange,
+} from '../../multiplayer/src/world-features.js';
+import { createLogger } from '../shared/log.js';
+import './war-portal.css';
+
+const log = createLogger('war-portal');
+
+const CW = 640, CH = 400; // logical board layout grid; backed at 2x by makeScreenCanvas
+const SS = 2;
+
+// Poll cadences. The slow one is what a player idling near the board pays; the
+// fast one only applies while a war involving this coin is actually running or
+// the panel is open, which is exactly when a stale number would be noticed.
+const POLL_IDLE_MS = 20_000;
+const POLL_LIVE_MS = 5_000;
+// While queued, the pairing poll has to be brisk or the other community is left
+// standing in their own plaza wondering whether anything happened.
+const POLL_QUEUE_MS = 3_000;
+
+// How long the win takeover holds the board after a battle this community won.
+const HYPE_MS = 9_000;
+
+// Restrained palette matching the world's monochrome UI, with one directional
+// accent pair for the two sides of a war.
+const COL = {
+ bg0: '#0a0a0c', bg1: '#141419',
+ text: '#f5f5f6', dim: '#8c8c92', faint: '#5a5a60',
+ line: 'rgba(255,255,255,0.08)',
+ us: '#7fd8ff', them: '#ff9d7a',
+ win: '#5fd08a', loss: '#e06c75', draw: '#c9a227',
+};
+
+function el(tag, props = {}, kids = []) {
+ const n = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (v == null) continue;
+ if (k === 'class') n.className = v;
+ else if (k === 'text') n.textContent = v;
+ else if (k === 'html') n.innerHTML = v;
+ else if (k === 'hidden') n.hidden = !!v;
+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);
+ else n.setAttribute(k, v);
+ }
+ for (const kid of [].concat(kids)) {
+ if (kid == null) continue;
+ n.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);
+ }
+ return n;
+}
+
+function relTime(ms) {
+ if (!ms) return '';
+ const s = Math.max(0, Math.round((Date.now() - ms) / 1000));
+ if (s < 45) return 'just now';
+ const m = Math.round(s / 60);
+ if (m < 60) return `${m}m ago`;
+ const h = Math.round(m / 60);
+ if (h < 24) return `${h}h ago`;
+ return `${Math.round(h / 24)}d ago`;
+}
+
+function clock(ms) {
+ const s = Math.max(0, Math.round(ms / 1000));
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
+}
+
+function label(side) {
+ return side?.symbol ? `$${side.symbol}` : (side?.name || 'Community');
+}
+
+function roundRect(ctx, x, y, w, h, r) {
+ ctx.beginPath();
+ ctx.moveTo(x + r, y);
+ ctx.arcTo(x + w, y, x + w, y + h, r);
+ ctx.arcTo(x + w, y + h, x, y + h, r);
+ ctx.arcTo(x, y + h, x, y, r);
+ ctx.arcTo(x, y, x + w, y, r);
+ ctx.closePath();
+}
+
+export class WarPortal {
+ /**
+ * @param {object} opts
+ * @param {import('three').Scene} opts.scene
+ * @param {() => ({x:number,y:number,z:number})} opts.getPlayer local avatar pose
+ * @param {{mint:string,name:string,symbol:string,image:string,tier:string}} opts.coin this world's coin
+ * @param {object} opts.ui the world HUD (used for toasts only)
+ * @param {() => Promise<object|null>} opts.ensureHolderPass runs THIS coin's holder
+ * gate and resolves to the verified pass, or null if the player backed out. Injected
+ * rather than imported so the portal reuses the world's existing gate overlay
+ * instead of growing a second one.
+ * @param {string} [opts.network]
+ * @param {string} [opts.returningMatchKey] the ?war= key a player carries back from
+ * the arena, captured before enter() canonicalises the URL
+ */
+ constructor({ scene, getPlayer, coin, ui, ensureHolderPass, network = 'mainnet', returningMatchKey = '' }) {
+ this.scene = scene;
+ this.getPlayer = getPlayer;
+ this.coin = coin || {};
+ this.ui = ui;
+ this.ensureHolderPass = ensureHolderPass;
+ this.network = network;
+
+ this._t = 0;
+ this._near = false; // inside interaction reach
+ this._awake = false; // inside board-legibility reach (drives polling)
+ this._board = null; // last /api/wars payload
+ this._boardError = ''; // last fetch failure, shown on the board + panel
+ this._loading = true;
+ this._queue = null; // { status, waiting, matchKey, ticket, side, opponent }
+ this._queueError = '';
+ this._busy = false; // a queue/gate round trip is in flight
+ this._pollTimer = 0;
+ this._nextPollAt = 0;
+ this._panel = null;
+ this._hype = null; // { until, battle } win takeover on the board
+ this._seenBattles = new Set();
+ this._seenSeeded = false; // first poll seeds history without echoing it
+ this._returning = returningMatchKey || '';
+ this._disposed = false;
+
+ this._buildScene();
+ this._buildPrompt();
+ // A player walking back in from a battle gets their result echoed even if
+ // they land far from the portal, so the war they just fought is never
+ // silently swallowed by the world transition.
+ if (this._returning) this._echoReturn();
+ }
+
+ // ── the landmark ─────────────────────────────────────────────────────────
+
+ _buildScene() {
+ const spot = WAR_PORTAL;
+ const g = new Group();
+ g.position.set(spot.x, 0, spot.z);
+ // Face the plaza centre so the board reads from the middle of the world.
+ g.rotation.y = Math.atan2(-spot.x, -spot.z);
+
+ const stone = new MeshStandardMaterial({ color: 0x23252c, roughness: 0.85, metalness: 0.1 });
+ const trim = new MeshStandardMaterial({ color: 0x3c4049, roughness: 0.6, metalness: 0.35 });
+
+ // A stepped plinth the whole structure stands on.
+ const base = new Mesh(new CylinderGeometry(spot.r, spot.r + 0.4, 0.4, 8), stone);
+ base.position.y = 0.2;
+ base.castShadow = true;
+ base.receiveShadow = true;
+ g.add(base);
+
+ // Two pillars and a lintel: the gate you walk through to go to war.
+ for (const side of [-1, 1]) {
+ const pillar = new Mesh(new BoxGeometry(0.7, 4.2, 0.7), stone);
+ pillar.position.set(side * 1.7, 2.5, 0);
+ pillar.castShadow = true;
+ g.add(pillar);
+ const cap = new Mesh(new BoxGeometry(1.0, 0.25, 1.0), trim);
+ cap.position.set(side * 1.7, 4.7, 0);
+ g.add(cap);
+ }
+ const lintel = new Mesh(new BoxGeometry(4.6, 0.5, 0.9), trim);
+ lintel.position.y = 5.05;
+ lintel.castShadow = true;
+ g.add(lintel);
+
+ // The portal itself: a flat emissive pane between the pillars whose opacity
+ // breathes, so the landmark is alive from across the plaza without costing
+ // a particle system.
+ this._veil = new Mesh(
+ new PlaneGeometry(3.0, 4.0),
+ new MeshBasicMaterial({ color: 0x6fb7ff, transparent: true, opacity: 0.18, side: DoubleSide, fog: false, toneMapped: false }),
+ );
+ this._veil.position.y = 2.5;
+ g.add(this._veil);
+
+ this._ring = new Mesh(
+ new TorusGeometry(1.5, 0.05, 8, 32),
+ new MeshBasicMaterial({ color: 0x8fd0ff, transparent: true, opacity: 0.35, fog: false, toneMapped: false }),
+ );
+ this._ring.position.y = 2.5;
+ g.add(this._ring);
+
+ // The board, mounted beside the arch on its own posts.
+ const boardW = 6.4;
+ const boardH = (boardW * CH) / CW;
+ const screen = makeScreenCanvas(CW, CH, SS);
+ this._canvas = screen.canvas;
+ this._ctx = screen.ctx;
+ this._tex = makeScreenTexture(this._canvas);
+ const face = new Mesh(new PlaneGeometry(boardW, boardH), screenMaterial(this._tex));
+ face.position.set(4.9, 2.9, 0);
+ g.add(face);
+ const frame = new Mesh(new BoxGeometry(boardW + 0.3, boardH + 0.3, 0.16), trim);
+ frame.position.set(4.9, 2.9, -0.1);
+ frame.castShadow = true;
+ g.add(frame);
+ for (const dx of [-2.4, 2.4]) {
+ const post = new Mesh(new CylinderGeometry(0.14, 0.16, 2.0, 8), stone);
+ post.position.set(4.9 + dx, 1.0, -0.1);
+ post.castShadow = true;
+ g.add(post);
+ }
+
+ // Ground marker, same language as the wheel's: a soft ring that brightens
+ // as you come into range so "you can use this" is legible before the prompt.
+ this._marker = new Mesh(
+ new RingGeometry(spot.r + 0.4, spot.r + 0.65, 40),
+ new MeshBasicMaterial({ color: 0x8fd0ff, transparent: true, opacity: 0.16, side: DoubleSide }),
+ );
+ this._marker.rotation.x = -Math.PI / 2;
+ this._marker.position.y = 0.05;
+ g.add(this._marker);
+
+ this.scene.add(g);
+ this._group = g;
+ this._paint();
+ }
+
+ _buildPrompt() {
+ this.btn = el('button', {
+ class: 'ps-action wp-action',
+ hidden: true,
+ text: '⚔ Enter the war',
+ 'aria-label': 'Open the war portal',
+ onclick: () => this.interact(),
+ });
+ document.body.appendChild(this.btn);
+ }
+
+ // ── frame loop ───────────────────────────────────────────────────────────
+
+ tick(dt) {
+ if (this._disposed) return;
+ this._t += dt;
+
+ const p = this.getPlayer?.();
+ const near = !!(p && warPortalInRange(p.x, p.z));
+ const awake = !!(p && warPortalBoardInRange(p.x, p.z));
+
+ if (near !== this._near) {
+ this._near = near;
+ this.btn.hidden = !near || !!this._panel;
+ }
+ // Crossing the legibility ring is what starts (and stops) every network
+ // call this module makes. A world with nobody near the portal is silent.
+ if (awake !== this._awake) {
+ this._awake = awake;
+ if (awake) this._wake();
+ else this._sleep();
+ }
+
+ // Idle animation: the veil breathes, the ring turns, the marker pulses.
+ const breathe = 0.16 + Math.sin(this._t * 1.3) * 0.06;
+ this._veil.material.opacity = this._liveHere() ? breathe + 0.24 : breathe;
+ this._ring.rotation.z = this._t * 0.25;
+ this._marker.material.opacity = near ? breathe + 0.2 : breathe * 0.7;
+
+ // The board only repaints when something on it moves: a running clock, an
+ // active takeover, or a fresh payload (which repaints on arrival).
+ if (this._awake && (this._liveHere() || this._hype)) {
+ if (!this._lastPaint || this._t - this._lastPaint > 0.25) this._paint();
+ }
+ }
+
+ // Public: act if in range. SYNCHRONOUS for the same reason WheelStation's is —
+ // coincommunities' E-key chain calls each system's interact() looking for the
+ // one that consumed the press, and a Promise is always truthy.
+ interact() {
+ if (!this._near) return false;
+ if (!this._panel) this._openPanel();
+ return true;
+ }
+
+ // ── polling ──────────────────────────────────────────────────────────────
+
+ _wake() {
+ this._nextPollAt = 0;
+ this._schedule(0);
+ }
+
+ _sleep() {
+ clearTimeout(this._pollTimer);
+ this._pollTimer = 0;
+ // A player who walks away while queued is taken out of the line, so nobody
+ // is ever paired against a community that left the plaza.
+ if (this._queue && this._queue.status === 'waiting' && !this._panel) this._leaveQueue();
+ }
+
+ _schedule(ms) {
+ clearTimeout(this._pollTimer);
+ if (this._disposed || !this._awake) return;
+ this._pollTimer = setTimeout(() => this._poll(), ms);
+ }
+
+ _pollInterval() {
+ if (this._queue?.status === 'waiting') return POLL_QUEUE_MS;
+ if (this._liveHere() || this._panel) return POLL_LIVE_MS;
+ return POLL_IDLE_MS;
+ }
+
+ async _poll() {
+ if (this._disposed || !this._awake) return;
+ const mint = this.coin?.mint || '';
+ if (!mint) return;
+ try {
+ const q = new URLSearchParams({ network: this.network, coin: mint, limit: '8' });
+ const r = await fetch(`/api/wars?${q}`, { headers: { accept: 'application/json' } });
+ if (!r.ok) throw new Error(`http ${r.status}`);
+ const payload = await r.json();
+ this._board = payload?.data || null;
+ this._boardError = '';
+ this._echoNewResults();
+ } catch (err) {
+ this._boardError = err?.message || 'could not reach the war league';
+ log.warn('board fetch failed', err);
+ }
+ this._loading = false;
+ this._paint();
+ this._renderPanel();
+ // While queued, keep asking the matchmaker whether the other side turned up.
+ if (this._queue?.status === 'waiting') this._pollQueue();
+ this._schedule(this._pollInterval());
+ }
+
+ // The live war this community is in, if any.
+ _liveHere() {
+ const mint = this.coin?.mint;
+ return (this._board?.live || []).find((m) => m.a?.mint === mint || m.b?.mint === mint) || null;
+ }
+
+ // ── results echo ─────────────────────────────────────────────────────────
+
+ // Every poll after the first compares the ledger against what we have already
+ // seen, so a battle that finishes while the player is standing in the world
+ // lands as a toast and (on a win) a takeover on the board.
+ _echoNewResults() {
+ const recent = this._board?.recent || [];
+ if (!this._seenSeeded) {
+ for (const b of recent) this._seenBattles.add(b.matchKey);
+ this._seenSeeded = true;
+ return;
+ }
+ for (const b of recent) {
+ if (this._seenBattles.has(b.matchKey)) continue;
+ this._seenBattles.add(b.matchKey);
+ this._announce(b);
+ }
+ }
+
+ // A player returning from the arena carries ?war=<matchKey>. The ledger write
+ // happens as the room ends, so the row may not be readable for a beat: retry a
+ // few times before giving up quietly (the next poll would surface it anyway).
+ async _echoReturn() {
+ const mint = this.coin?.mint;
+ const key = this._returning;
+ if (!mint || !key) return;
+ for (let attempt = 0; attempt < 5 && !this._disposed; attempt++) {
+ try {
+ const q = new URLSearchParams({ network: this.network, coin: mint, limit: '8' });
+ const r = await fetch(`/api/wars?${q}`, { headers: { accept: 'application/json' } });
+ if (r.ok) {
+ const payload = await r.json();
+ const battle = (payload?.data?.recent || []).find((b) => b.matchKey === key);
+ if (battle) {
+ this._board = payload.data;
+ this._seenSeeded = true;
+ for (const b of payload.data.recent || []) this._seenBattles.add(b.matchKey);
+ this._announce(battle);
+ this._paint();
+ return;
+ }
+ }
+ } catch { /* retry below */ }
+ await new Promise((r) => setTimeout(r, 1200 * (attempt + 1)));
+ }
+ }
+
+ // One finished battle, brought into the world: a toast every time, plus a short
+ // takeover of the board when this community won it.
+ _announce(battle) {
+ const mint = this.coin?.mint;
+ const us = battle.a?.mint === mint ? battle.a : battle.b;
+ const them = battle.a?.mint === mint ? battle.b : battle.a;
+ const won = battle.winner === mint;
+ const drew = battle.winner === 'draw';
+ const line = drew
+ ? `⚔ War drawn with ${label(them)} — ${us.score}:${them.score}`
+ : won
+ ? `⚔ ${label(us)} won the war against ${label(them)} — ${us.score}:${them.score}`
+ : `⚔ ${label(them)} took the war — ${them.score}:${us.score}`;
+ this.ui?.toast?.(line, won ? 'success' : drew ? 'info' : 'warn');
+ if (won) {
+ this._hype = { until: Date.now() + HYPE_MS, battle, us, them };
+ this._paint();
+ }
+ }
+
+ // ── the board ────────────────────────────────────────────────────────────
+
+ _paint() {
+ const ctx = this._ctx;
+ if (!ctx) return;
+ this._lastPaint = this._t;
+ if (this._hype && Date.now() > this._hype.until) this._hype = null;
+
+ const grad = ctx.createLinearGradient(0, 0, 0, CH);
+ grad.addColorStop(0, COL.bg1);
+ grad.addColorStop(1, COL.bg0);
+ ctx.fillStyle = grad;
+ ctx.fillRect(0, 0, CW, CH);
+
+ if (this._hype) this._paintHype(ctx);
+ else if (this._loading && !this._board) this._paintCentred(ctx, 'READING THE LEAGUE', 'Standings load as you walk up.');
+ else if (this._boardError && !this._board) this._paintCentred(ctx, 'LEAGUE UNREACHABLE', this._boardError + ' — press E to retry.');
+ else {
+ const live = this._liveHere();
+ if (live) this._paintLive(ctx, live);
+ else this._paintStandings(ctx);
+ }
+
+ this._tex.needsUpdate = true;
+ }
+
+ _paintHeader(ctx, title, right = '') {
+ ctx.fillStyle = COL.text;
+ ctx.font = '800 26px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'left';
+ ctx.fillText(title, 26, 44);
+ if (right) {
+ ctx.fillStyle = COL.dim;
+ ctx.font = '600 16px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'right';
+ ctx.fillText(right, CW - 26, 42);
+ }
+ ctx.strokeStyle = COL.line;
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ ctx.moveTo(26, 60);
+ ctx.lineTo(CW - 26, 60);
+ ctx.stroke();
+ ctx.textAlign = 'left';
+ }
+
+ _paintCentred(ctx, title, sub) {
+ ctx.textAlign = 'center';
+ ctx.fillStyle = COL.text;
+ ctx.font = '800 28px Inter, system-ui, sans-serif';
+ ctx.fillText(title, CW / 2, CH / 2 - 6);
+ ctx.fillStyle = COL.dim;
+ ctx.font = '500 17px Inter, system-ui, sans-serif';
+ this._wrap(ctx, sub, CW / 2, CH / 2 + 28, CW - 90, 24);
+ ctx.textAlign = 'left';
+ }
+
+ // A war this community won, held on the board for a few seconds. This is the
+ // jumbotron moment: whoever is standing in the plaza sees it without opening
+ // anything.
+ _paintHype(ctx) {
+ const { us, them, battle } = this._hype;
+ const pulse = 0.6 + 0.4 * Math.sin(this._t * 5);
+ ctx.fillStyle = `rgba(95, 208, 138, ${0.10 + 0.06 * pulse})`;
+ ctx.fillRect(0, 0, CW, CH);
+ ctx.textAlign = 'center';
+ ctx.fillStyle = COL.win;
+ ctx.font = '900 60px Inter, system-ui, sans-serif';
+ ctx.fillText('WAR WON', CW / 2, 130);
+ ctx.fillStyle = COL.text;
+ ctx.font = '800 30px Inter, system-ui, sans-serif';
+ ctx.fillText(`${label(us)} ${us.score} — ${them.score} ${label(them)}`, CW / 2, 196);
+ ctx.fillStyle = COL.dim;
+ ctx.font = '600 18px Inter, system-ui, sans-serif';
+ ctx.fillText(reasonLine(battle.reason), CW / 2, 236);
+ if (battle.mvp) {
+ ctx.fillStyle = COL.faint;
+ ctx.font = '600 16px Inter, system-ui, sans-serif';
+ ctx.fillText(`MVP · ${battle.mvp.kills} kills · ${battle.mvp.damage} damage`, CW / 2, 268);
+ }
+ ctx.fillStyle = COL.faint;
+ ctx.font = '600 15px Inter, system-ui, sans-serif';
+ ctx.fillText('Press E to see the league', CW / 2, CH - 30);
+ ctx.textAlign = 'left';
+ }
+
+ // The spectator screen: score, clock, kill feed. No second 3D render, just the
+ // numbers a crowd standing at the portal wants while their side is fighting.
+ _paintLive(ctx, m) {
+ const mint = this.coin?.mint;
+ const usIsA = m.a?.mint === mint;
+ const us = usIsA ? m.a : m.b;
+ const them = usIsA ? m.b : m.a;
+ const phase = m.phase === 'sudden_death' ? 'SUDDEN DEATH' : String(m.phase || '').toUpperCase();
+ this._paintHeader(ctx, 'WAR IN PROGRESS', phase);
+
+ // Scoreline.
+ ctx.textAlign = 'center';
+ ctx.fillStyle = COL.us;
+ ctx.font = '900 54px Inter, system-ui, sans-serif';
+ ctx.fillText(String(us.score ?? 0), CW * 0.28, 132);
+ ctx.fillStyle = COL.them;
+ ctx.fillText(String(them.score ?? 0), CW * 0.72, 132);
+ ctx.fillStyle = COL.faint;
+ ctx.font = '700 26px Inter, system-ui, sans-serif';
+ ctx.fillText('vs', CW / 2, 126);
+
+ ctx.font = '700 17px Inter, system-ui, sans-serif';
+ ctx.fillStyle = COL.text;
+ ctx.fillText(clip(ctx, label(us), 190), CW * 0.28, 160);
+ ctx.fillText(clip(ctx, label(them), 190), CW * 0.72, 160);
+ ctx.fillStyle = COL.faint;
+ ctx.font = '500 14px Inter, system-ui, sans-serif';
+ ctx.fillText(`${us.fighters || 0} fighting`, CW * 0.28, 182);
+ ctx.fillText(`${them.fighters || 0} fighting`, CW * 0.72, 182);
+
+ // Round clock. Rendered from `endsAt` so it ticks smoothly between polls
+ // instead of jumping every time a snapshot lands.
+ const remaining = m.phase === 'countdown'
+ ? (m.countdownEndsAt || 0) - Date.now()
+ : (m.endsAt || 0) - Date.now();
+ ctx.fillStyle = COL.text;
+ ctx.font = '800 22px Inter, system-ui, sans-serif';
+ ctx.fillText(
+ m.phase === 'countdown' ? `starts in ${clock(remaining)}`
+ : m.phase === 'sudden_death' ? 'next kill takes it'
+ : `${clock(remaining)} left · first to ${m.scoreCap || 25}`,
+ CW / 2, 214,
+ );
+ ctx.textAlign = 'left';
+
+ // Kill feed.
+ const kills = (m.kills || []).slice(-4).reverse();
+ if (!kills.length) {
+ ctx.fillStyle = COL.faint;
+ ctx.font = '500 16px Inter, system-ui, sans-serif';
+ ctx.fillText('No knockdowns yet.', 26, 258);
+ } else {
+ let y = 254;
+ ctx.font = '600 15px Inter, system-ui, sans-serif';
+ for (const k of kills) {
+ ctx.fillStyle = k.killerFaction === mint ? COL.us : COL.them;
+ ctx.fillText(`${clipText(k.killer, 16)} → ${clipText(k.victim, 16)}`, 26, y);
+ ctx.fillStyle = COL.faint;
+ ctx.textAlign = 'right';
+ ctx.fillText(relTime(k.ts), CW - 26, y);
+ ctx.textAlign = 'left';
+ y += 26;
+ }
+ }
+
+ ctx.fillStyle = COL.faint;
+ ctx.font = '600 15px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'center';
+ ctx.fillText('Press E to join the fight', CW / 2, CH - 24);
+ ctx.textAlign = 'left';
+ }
+
+ // The resting board: where this community sits in the league, and the last
+ // battles it fought. Both have designed empty states — an unranked community
+ // is told exactly what to do about it.
+ _paintStandings(ctx) {
+ const standing = this._board?.standing || null;
+ const recent = this._board?.recent || [];
+ const waiting = this._board?.queue?.waiting || [];
+ this._paintHeader(ctx, 'COIN WARS', label(this.coin));
+
+ if (!standing) {
+ ctx.fillStyle = COL.text;
+ ctx.font = '800 24px Inter, system-ui, sans-serif';
+ ctx.fillText('Unranked', 26, 104);
+ ctx.fillStyle = COL.dim;
+ ctx.font = '500 16px Inter, system-ui, sans-serif';
+ this._wrapLeft(
+ ctx,
+ 'This community has never gone to war. Press E to queue: the first battle places you on the ladder.',
+ 26, 134, CW - 52, 24,
+ );
+ } else {
+ ctx.fillStyle = COL.text;
+ ctx.font = '900 44px Inter, system-ui, sans-serif';
+ ctx.fillText(String(standing.rating), 26, 116);
+ ctx.fillStyle = COL.dim;
+ ctx.font = '600 16px Inter, system-ui, sans-serif';
+ ctx.fillText('ELO', 26, 138);
+
+ const cells = [
+ ['RANK', `#${standing.rank}`],
+ ['RECORD', `${standing.wins}W ${standing.losses}L${standing.draws ? ` ${standing.draws}D` : ''}`],
+ ['K/D', standing.kd.toFixed(2)],
+ ['STREAK', streakLabel(standing.streak)],
+ ];
+ let x = 170;
+ for (const [k, v] of cells) {
+ ctx.fillStyle = COL.faint;
+ ctx.font = '700 12px Inter, system-ui, sans-serif';
+ ctx.fillText(k, x, 92);
+ ctx.fillStyle = COL.text;
+ ctx.font = '800 22px Inter, system-ui, sans-serif';
+ ctx.fillText(v, x, 120);
+ x += 118;
+ }
+ }
+
+ ctx.strokeStyle = COL.line;
+ ctx.beginPath();
+ ctx.moveTo(26, 162);
+ ctx.lineTo(CW - 26, 162);
+ ctx.stroke();
+
+ ctx.fillStyle = COL.faint;
+ ctx.font = '700 13px Inter, system-ui, sans-serif';
+ ctx.fillText('RECENT WARS', 26, 186);
+
+ if (!this._board?.recentAvailable) {
+ ctx.fillStyle = COL.dim;
+ ctx.font = '500 16px Inter, system-ui, sans-serif';
+ this._wrapLeft(ctx, 'The battle ledger is unreachable right now. Standings will fill in as soon as it answers.', 26, 214, CW - 52, 24);
+ } else if (!recent.length) {
+ ctx.fillStyle = COL.dim;
+ ctx.font = '500 16px Inter, system-ui, sans-serif';
+ this._wrapLeft(
+ ctx,
+ waiting.length
+ ? `${waiting.length} ${waiting.length === 1 ? 'community is' : 'communities are'} queued right now. Press E to take the fight.`
+ : 'No wars fought yet. Press E to queue this community — the arena opens as soon as a second one does.',
+ 26, 214, CW - 52, 24,
+ );
+ } else {
+ let y = 214;
+ for (const b of recent.slice(0, 4)) {
+ const mint = this.coin?.mint;
+ const us = b.a?.mint === mint ? b.a : b.b;
+ const them = b.a?.mint === mint ? b.b : b.a;
+ const won = b.winner === mint;
+ const drew = b.winner === 'draw';
+ ctx.fillStyle = drew ? COL.draw : won ? COL.win : COL.loss;
+ ctx.font = '800 15px Inter, system-ui, sans-serif';
+ ctx.fillText(drew ? 'DRAW' : won ? 'WIN' : 'LOSS', 26, y);
+ ctx.fillStyle = COL.text;
+ ctx.font = '600 15px Inter, system-ui, sans-serif';
+ ctx.fillText(`${us.score}–${them.score} vs ${clipText(label(them), 18)}`, 92, y);
+ ctx.fillStyle = COL.faint;
+ ctx.textAlign = 'right';
+ ctx.fillText(relTime(b.endedAt), CW - 26, y);
+ ctx.textAlign = 'left';
+ y += 26;
+ }
+ }
+
+ ctx.fillStyle = COL.faint;
+ ctx.font = '600 15px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'center';
+ ctx.fillText('Press E — enter the war', CW / 2, CH - 24);
+ ctx.textAlign = 'left';
+ }
+
+ _wrap(ctx, text, cx, y, maxW, lh) {
+ for (const line of wrapLines(ctx, text, maxW)) { ctx.fillText(line, cx, y); y += lh; }
+ }
+
+ _wrapLeft(ctx, text, x, y, maxW, lh) {
+ for (const line of wrapLines(ctx, text, maxW)) { ctx.fillText(line, x, y); y += lh; }
+ }
+
+ // ── the panel ────────────────────────────────────────────────────────────
+
+ _openPanel() {
+ if (this._panel) return;
+ this.btn.hidden = true;
+ const close = () => this._closePanel();
+ const body = el('div', { class: 'wp-body' });
+ const panel = el('div', { class: 'wp-panel', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Coin Wars' }, [
+ el('header', { class: 'wp-head' }, [
+ el('div', { class: 'wp-head-t' }, [
+ el('h2', { text: 'Coin Wars' }),
+ el('p', { class: 'wp-head-sub', text: `${label(this.coin)} · community vs community` }),
+ ]),
+ el('button', { class: 'wp-x', text: '✕', 'aria-label': 'Close', onclick: close }),
+ ]),
+ body,
+ el('footer', { class: 'wp-foot' }, [
+ el('button', { class: 'wp-cta', id: 'wp-cta', onclick: () => this._onCta() }),
+ el('p', { class: 'wp-foot-note', id: 'wp-note' }),
+ ]),
+ ]);
+ const scrim = el('div', { class: 'wp-scrim', onclick: close });
+ const root = el('div', { class: 'wp-root' }, [scrim, panel]);
+ document.body.appendChild(root);
+ this._panel = { root, body, panel };
+ this._onKey = (e) => { if (e.key === 'Escape') { e.stopPropagation(); close(); } };
+ document.addEventListener('keydown', this._onKey, true);
+ requestAnimationFrame(() => root.classList.add('wp-in'));
+ panel.querySelector('.wp-x')?.focus();
+
+ this._renderPanel();
+ // Opening the panel is an explicit ask for fresh numbers.
+ this._schedule(0);
+ }
+
+ _closePanel() {
+ if (!this._panel) return;
+ const { root } = this._panel;
+ root.classList.remove('wp-in');
+ document.removeEventListener('keydown', this._onKey, true);
+ this._onKey = null;
+ setTimeout(() => root.remove(), 200);
+ this._panel = null;
+ this.btn.hidden = !this._near;
+ this._schedule(this._pollInterval());
+ }
+
+ _renderPanel() {
+ if (!this._panel) return;
+ const { body } = this._panel;
+ const d = this._board;
+ const live = this._liveHere();
+ const parts = [];
+
+ if (this._boardError && !d) {
+ parts.push(retryCard(
+ 'The war league did not answer',
+ this._boardError,
+ 'Try again',
+ () => this._poll(),
+ ));
+ }
+
+ if (live) parts.push(this._liveCard(live));
+
+ // This community's league row.
+ if (d) {
+ parts.push(d.standing ? standingCard(d.standing) : emptyCard(
+ 'Unranked',
+ 'This community has not fought a war yet. The first battle puts it on the ladder — win or lose.',
+ ));
+ }
+
+ // Queue state, when there is one.
+ if (this._queue?.status === 'waiting') {
+ parts.push(waitingCard(this._queue.waiting, () => this._leaveQueue()));
+ }
+ if (this._queueError) {
+ parts.push(retryCard('Matchmaking refused', this._queueError, 'Try again', () => this._onCta()));
+ }
+
+ // Recent wars.
+ if (d?.recentAvailable) {
+ parts.push(recentCard(d.recent || [], this.coin?.mint));
+ } else if (d) {
+ parts.push(emptyCard('Battle log unavailable', 'The ledger is not answering right now, so past wars cannot be listed. The league table above is the last good read.'));
+ }
+
+ // The ladder.
+ if (d?.ledgerAvailable) {
+ parts.push(ladderCard(d.standings || [], this.coin?.mint));
+ }
+
+ body.replaceChildren(...parts);
+ this._renderCta();
+ }
+
+ _renderCta() {
+ if (!this._panel) return;
+ const cta = this._panel.panel.querySelector('#wp-cta');
+ const note = this._panel.panel.querySelector('#wp-note');
+ if (!cta) return;
+ const live = this._liveHere();
+ if (this._busy) {
+ cta.textContent = 'Working…';
+ cta.disabled = true;
+ note.textContent = 'Verifying your holding and finding an opponent.';
+ return;
+ }
+ if (this._queue?.status === 'waiting') {
+ cta.textContent = 'Waiting for an opponent…';
+ cta.disabled = true;
+ note.textContent = 'Stay here — the arena opens the moment another community queues.';
+ return;
+ }
+ cta.disabled = false;
+ cta.textContent = live ? '⚔ Join the battle' : '⚔ Enter the war';
+ note.textContent = live
+ ? 'A war is running right now. Joining drops you straight into the arena.'
+ : 'You fight for this coin, so entering verifies you hold it first.';
+ }
+
+ // The spectator card: the same numbers the board paints, in text, so the panel
+ // is useful to a screen reader and to anyone reading it on a phone.
+ _liveCard(m) {
+ const mint = this.coin?.mint;
+ const us = m.a?.mint === mint ? m.a : m.b;
+ const them = m.a?.mint === mint ? m.b : m.a;
+ const remaining = m.phase === 'countdown' ? (m.countdownEndsAt || 0) - Date.now() : (m.endsAt || 0) - Date.now();
+ const status = m.phase === 'countdown' ? `Starts in ${clock(remaining)}`
+ : m.phase === 'sudden_death' ? 'Sudden death — the next kill takes it'
+ : m.phase === 'ended' ? 'Battle over'
+ : `${clock(remaining)} left · first to ${m.scoreCap || 25}`;
+ const kills = (m.kills || []).slice(-6).reverse();
+ return el('section', { class: 'wp-card wp-live', 'aria-live': 'polite' }, [
+ el('h3', { class: 'wp-card-t' }, [
+ el('span', { class: 'wp-live-dot', 'aria-hidden': 'true' }),
+ 'War in progress',
+ ]),
+ el('div', { class: 'wp-score' }, [
+ el('div', { class: 'wp-score-side wp-side-us' }, [
+ el('span', { class: 'wp-score-n', text: String(us.score ?? 0) }),
+ el('span', { class: 'wp-score-l', text: label(us) }),
+ el('span', { class: 'wp-score-f', text: `${us.fighters || 0} fighting` }),
+ ]),
+ el('span', { class: 'wp-score-vs', text: 'vs' }),
+ el('div', { class: 'wp-score-side wp-side-them' }, [
+ el('span', { class: 'wp-score-n', text: String(them.score ?? 0) }),
+ el('span', { class: 'wp-score-l', text: label(them) }),
+ el('span', { class: 'wp-score-f', text: `${them.fighters || 0} fighting` }),
+ ]),
+ ]),
+ el('p', { class: 'wp-live-clock', text: status }),
+ kills.length
+ ? el('ul', { class: 'wp-list wp-feed' }, kills.map((k) => el('li', {
+ class: `wp-row wp-row-${k.killerFaction === mint ? 'win' : 'loss'}`,
+ }, [
+ el('span', { class: 'wp-row-vs', text: `${clipText(k.killer, 18)} → ${clipText(k.victim, 18)}` }),
+ el('span', { class: 'wp-row-when', text: relTime(k.ts) }),
+ ])))
+ : el('p', { class: 'wp-empty-b', text: 'No knockdowns yet — the first one lands here.' }),
+ ]);
+ }
+
+ // ── queueing and handoff ─────────────────────────────────────────────────
+
+ async _onCta() {
+ if (this._busy) return;
+ this._queueError = '';
+ this._busy = true;
+ this._renderCta();
+ try {
+ // The same gate the Holders world runs. A community whose world is open
+ // still gates the war on holding the coin — you cannot wear a
+ // community's colours without holding its coin, which is the rule
+ // ClashRoom.onAuth enforces server-side too.
+ const pass = await this.ensureHolderPass?.();
+ if (!pass || !pass.holderPass) {
+ // Two clean refusals, neither an error. A null means the player
+ // backed out of the gate; the string 'general' means they chose the
+ // open world from inside it, which for a war means declining — you
+ // cannot wear a community's colours without holding its coin, and
+ // ClashRoom.onAuth enforces exactly that server-side.
+ this._busy = false;
+ this._queueError = pass == null ? '' : 'You need to hold this coin to fight for it.';
+ this._renderPanel();
+ return;
+ }
+ this._holderPass = pass.holderPass;
+
+ // Queueing covers both cases: with a war already running, the matchmaker
+ // hands back that same pairing (the entry is still keyed), so joining a
+ // battle in progress and starting a fresh one take one code path.
+ const res = await this._queueRequest();
+ if (res?.status === 'matched') return this._handoff(res);
+ this._queue = res;
+ } catch (err) {
+ this._queueError = err?.message || 'could not queue for a war';
+ }
+ this._busy = false;
+ this._renderPanel();
+ this._schedule(0);
+ }
+
+ async _queueRequest() {
+ const r = await fetch('/api/wars?action=queue', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ coin: this.coin.mint,
+ name: this.coin.name || '',
+ symbol: this.coin.symbol || '',
+ image: this.coin.image || '',
+ network: this.network,
+ }),
+ });
+ const payload = await r.json().catch(() => null);
+ if (!r.ok) {
+ const msg = payload?.error?.message || payload?.message || `http ${r.status}`;
+ throw new Error(msg);
+ }
+ return payload?.data || null;
+ }
+
+ // While queued, poll the matchmaker on its own cadence: the moment the other
+ // side appears we have a key and a signed ticket and can hand off.
+ async _pollQueue() {
+ if (this._disposed || this._queue?.status !== 'waiting') return;
+ try {
+ const res = await this._queueRequest();
+ if (res?.status === 'matched') return this._handoff(res);
+ this._queue = res;
+ this._renderPanel();
+ } catch (err) {
+ this._queueError = err?.message || 'matchmaking stopped answering';
+ this._queue = null;
+ this._renderPanel();
+ }
+ }
+
+ async _leaveQueue() {
+ const mint = this.coin?.mint;
+ this._queue = null;
+ this._renderPanel();
+ if (!mint) return;
+ try {
+ await fetch('/api/wars?action=leave', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ coin: mint, network: this.network }),
+ keepalive: true,
+ });
+ } catch { /* the queue entry expires on its own */ }
+ }
+
+ // Hand the player to the arena. The return link carries the FULL coin identity
+ // plus the match key, so coming back lands in this exact world with the result
+ // already in hand — no lobby detour, no re-picking a community.
+ _handoff(match) {
+ const q = new URLSearchParams({
+ match: match.matchKey,
+ ticket: match.ticket,
+ side: match.side || '',
+ coin: this.coin.mint,
+ network: this.network,
+ return: this._returnUrl(match.matchKey),
+ });
+ if (this.coin.name) q.set('name', this.coin.name);
+ if (this.coin.symbol) q.set('symbol', this.coin.symbol);
+ if (this.coin.image) q.set('image', this.coin.image);
+ if (this._holderPass) q.set('holderPass', this._holderPass);
+ this.ui?.toast?.(`⚔ Matched against ${label(match.opponent)} — entering the arena`, 'success');
+ location.href = `/play/war?${q}`;
+ }
+
+ _returnUrl(matchKey) {
+ const q = new URLSearchParams({ coin: this.coin.mint });
+ if (this.coin.name) q.set('name', this.coin.name);
+ if (this.coin.symbol) q.set('symbol', this.coin.symbol);
+ if (this.coin.image) q.set('image', this.coin.image);
+ if (this.coin.tier === 'holders') q.set('tier', 'holders');
+ q.set('war', matchKey);
+ return `/play?${q}`;
+ }
+
+ // ── teardown ─────────────────────────────────────────────────────────────
+
+ dispose() {
+ this._disposed = true;
+ clearTimeout(this._pollTimer);
+ if (this._queue?.status === 'waiting') this._leaveQueue();
+ this._closePanel();
+ if (this._group) {
+ this.scene.remove(this._group);
+ this._group.traverse((n) => {
+ if (n.isMesh) {
+ n.geometry?.dispose?.();
+ const ms = Array.isArray(n.material) ? n.material : [n.material];
+ ms.forEach((m) => m?.dispose?.());
+ }
+ });
+ this._group = null;
+ }
+ this._tex?.dispose?.();
+ this._tex = null;
+ this.btn?.remove();
+ this.btn = null;
+ }
+}
+
+// ── panel pieces ─────────────────────────────────────────────────────────────
+
+function card(title, kids, extraClass = '') {
+ return el('section', { class: `wp-card ${extraClass}`.trim() }, [
+ el('h3', { class: 'wp-card-t', text: title }),
+ ...[].concat(kids),
+ ]);
+}
+
+function emptyCard(title, body) {
+ return el('section', { class: 'wp-card wp-empty' }, [
+ el('h3', { class: 'wp-card-t', text: title }),
+ el('p', { class: 'wp-empty-b', text: body }),
+ ]);
+}
+
+// The lobby's retry-card shape: what went wrong, in a sentence, and the one
+// button that can fix it.
+function retryCard(title, detail, action, onAction) {
+ return el('section', { class: 'wp-card wp-retry' }, [
+ el('h3', { class: 'wp-card-t', text: title }),
+ el('p', { class: 'wp-empty-b', text: detail }),
+ el('button', { class: 'wp-retry-btn', text: action, onclick: onAction }),
+ ]);
+}
+
+function standingCard(s) {
+ const stats = [
+ ['Elo', String(s.rating)],
+ ['Rank', `#${s.rank}`],
+ ['Record', `${s.wins}W ${s.losses}L${s.draws ? ` ${s.draws}D` : ''}`],
+ ['Win rate', `${Math.round(s.winRate * 100)}%`],
+ ['K/D', s.kd.toFixed(2)],
+ ['Streak', streakLabel(s.streak)],
+ ];
+ return card('League standing', el('dl', { class: 'wp-stats' },
+ stats.flatMap(([k, v]) => [el('dt', { text: k }), el('dd', { text: v })])));
+}
+
+function waitingCard(waiting, onCancel) {
+ const others = Math.max(0, (waiting || 1) - 1);
+ return el('section', { class: 'wp-card wp-waiting' }, [
+ el('h3', { class: 'wp-card-t', text: 'In the queue' }),
+ el('p', {
+ class: 'wp-empty-b',
+ text: others > 0
+ ? `${others} other ${others === 1 ? 'community is' : 'communities are'} queued. Pairing happens within seconds.`
+ : 'No other community is queued yet. The arena opens the moment one is.',
+ }),
+ el('button', { class: 'wp-retry-btn', text: 'Leave the queue', onclick: onCancel }),
+ ]);
+}
+
+function recentCard(recent, mint) {
+ if (!recent.length) {
+ return emptyCard('No wars yet', 'This community has never fought. Be the first: queue below and the arena opens as soon as another community answers.');
+ }
+ const rows = recent.map((b) => {
+ const us = b.a?.mint === mint ? b.a : b.b;
+ const them = b.a?.mint === mint ? b.b : b.a;
+ const drew = b.winner === 'draw';
+ const won = b.winner === mint;
+ return el('li', { class: `wp-row wp-row-${drew ? 'draw' : won ? 'win' : 'loss'}` }, [
+ el('span', { class: 'wp-row-tag', text: drew ? 'DRAW' : won ? 'WIN' : 'LOSS' }),
+ el('span', { class: 'wp-row-score', text: `${us.score}–${them.score}` }),
+ el('span', { class: 'wp-row-vs', text: label(them) }),
+ el('span', { class: 'wp-row-when', text: relTime(b.endedAt) }),
+ ]);
+ });
+ return card('Recent wars', el('ul', { class: 'wp-list' }, rows));
+}
+
+function ladderCard(standings, mint) {
+ if (!standings.length) {
+ return emptyCard('The ladder is empty', 'No community has fought a war yet. The first battle creates the league.');
+ }
+ const rows = standings.slice(0, 10).map((s) => el('li', {
+ class: `wp-row${s.mint === mint ? ' wp-row-me' : ''}`,
+ }, [
+ el('span', { class: 'wp-row-tag', text: `#${s.rank}` }),
+ el('span', { class: 'wp-row-vs', text: s.symbol ? `$${s.symbol}` : s.name }),
+ el('span', { class: 'wp-row-score', text: String(s.rating) }),
+ el('span', { class: 'wp-row-when', text: `${s.wins}W ${s.losses}L` }),
+ ]));
+ return card('The ladder', el('ul', { class: 'wp-list' }, rows));
+}
+
+// ── formatting helpers ───────────────────────────────────────────────────────
+
+function streakLabel(streak) {
+ if (!streak) return '—';
+ return streak > 0 ? `${streak}W` : `${-streak}L`;
+}
+
+function reasonLine(reason) {
+ switch (reason) {
+ case 'score_cap': return 'Kill cap reached';
+ case 'timeout': return 'Round clock ran out';
+ case 'sudden_death': return 'Taken in sudden death';
+ case 'forfeit': return 'The other side withdrew';
+ default: return 'Battle ended';
+ }
+}
+
+function clipText(s, max) {
+ const t = String(s ?? '');
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t;
+}
+
+// Shrink a label until it fits the canvas column rather than bleeding off it —
+// a pump.fun name can be far longer than the space a scoreboard gives it.
+function clip(ctx, text, maxW) {
+ let t = String(text ?? '');
+ while (t.length > 3 && ctx.measureText(t).width > maxW) t = `${t.slice(0, -2)}…`;
+ return t;
+}
+
+function wrapLines(ctx, text, maxW) {
+ const words = String(text ?? '').split(/\s+/);
+ const lines = [];
+ let line = '';
+ for (const w of words) {
+ const next = line ? `${line} ${w}` : w;
+ if (ctx.measureText(next).width > maxW && line) { lines.push(line); line = w; }
+ else line = next;
+ }
+ if (line) lines.push(line);
+ return lines;
+}
diff --git a/src/game/x402-jumbotron.js b/src/game/x402-jumbotron.js
index df111bb73..cc058ce53 100644
--- a/src/game/x402-jumbotron.js
+++ b/src/game/x402-jumbotron.js
@@ -304,6 +304,13 @@ export function createX402Jumbotron(scene, opts = {}) {
: 'No payments yet — be the first to trigger one.';
ctx.fillText(msg, padX, feedTop + 36);
} else {
+ // The slide-in bookkeeping only ever needs the rows currently on screen.
+ // Rows churn every poll, so without this prune the map grew for the whole
+ // session, holding a timestamp for every payment ever rendered.
+ if (firstSeen.size > list.length * 4) {
+ const live = new Set(list.map(rowKey));
+ for (const key of firstSeen.keys()) if (!live.has(key)) firstSeen.delete(key);
+ }
list.forEach((r, i) => {
const key = rowKey(r);
if (!firstSeen.has(key)) firstSeen.set(key, t);
diff --git a/src/play/war-world.js b/src/play/war-world.js
new file mode 100644
index 000000000..ba712e980
--- /dev/null
+++ b/src/play/war-world.js
@@ -0,0 +1,618 @@
+// war-world.js — the 3D arena a Coin Wars battle is fought in.
+//
+// ClashRoom (multiplayer/src/rooms/ClashRoom.js) is fully authoritative: it owns
+// positions, targeting, damage, respawns, the round clock and the score. This
+// module is the eyes and hands for that room and nothing more — it renders the
+// arena and every fighter in it, walks the local fighter around (sending intent,
+// never claiming an outcome), and plays the feedback the server broadcasts.
+//
+// Deliberately lean. Avatars, the canonical clip library and the retargeting all
+// come from the platform's existing animation system via ArenaAvatar, the same
+// class the trading arena uses, so any humanoid GLB a player owns fights with
+// the same idle/walk/celebrate set instead of T-posing.
+
+import {
+ Scene, PerspectiveCamera, WebGLRenderer, Group, Vector3,
+ AmbientLight, DirectionalLight, HemisphereLight,
+ Color, Fog, MathUtils,
+ PlaneGeometry, CircleGeometry, RingGeometry, BoxGeometry, CylinderGeometry, SphereGeometry,
+ MeshStandardMaterial, MeshBasicMaterial, Mesh, DoubleSide,
+ SRGBColorSpace, ACESFilmicToneMapping, AdditiveBlending,
+} from 'three';
+import { clone as cloneSkeleton } from 'three/addons/utils/SkeletonUtils.js';
+import { AnimationManager } from '../animation-manager.js';
+import { gltfLoader } from '../loaders/gltf.js';
+import { ArenaAvatar } from './arena-world.js';
+
+const MANIFEST_URL = '/animations/manifest.json';
+
+// The clip set a battle needs. Same names the trading arena pulls, so the shared
+// library is warm and nothing extra is fetched for a player who came from there.
+const CLIPS = {
+ idle: 'idle',
+ walk: 'walk',
+ run: 'walk',
+ win: 'celebrate',
+ loss: 'defeated',
+};
+const CORE_CLIPS = ['idle', 'walk', 'celebrate', 'defeated'];
+
+// Must match ClashRoom: the server clamps to this square and spawns each faction
+// at ±SPAWN_OFFSET on z. Rendering a floor smaller than the play area would let a
+// fighter walk off the visible world while still being legal.
+export const ARENA_BOUND = 60;
+const SPAWN_OFFSET = 22;
+
+// Local walk speed. Kept under the server's per-move teleport clamp (3 m) at the
+// send rate below with plenty of headroom, so a legitimate sprint is never
+// mistaken for a teleport and pinned.
+const WALK_SPEED = 5.2;
+
+const COL = {
+ bg: 0x05060a,
+ floor: 0x0b0d14,
+ a: 0x7fd8ff,
+ b: 0xff9d7a,
+ line: 0x2a2e3a,
+};
+
+export class WarWorld {
+ constructor(canvas) {
+ this.canvas = canvas;
+ this.fighters = new Map(); // sessionId -> ArenaAvatar (+ .target for lerp)
+ this.localId = '';
+ this.factions = { a: '', b: '' };
+ this._templates = new Map();
+ this._lib = null;
+ this._loopByName = new Map();
+ this._defs = [];
+ this._fx = [];
+ this._running = false;
+ this._raf = 0;
+ this._last = 0;
+ this._onLabels = null;
+
+ this._initRenderer();
+ // The shared GLTF loader is keyed on the renderer (it probes KTX2 support
+ // from it), so it can only be built once the context exists.
+ this.loader = gltfLoader(this.renderer);
+ this._initScene();
+ this._initControls();
+ }
+
+ _initRenderer() {
+ this.renderer = new WebGLRenderer({ canvas: this.canvas, antialias: true, alpha: false, powerPreference: 'high-performance' });
+ this.renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2));
+ this.renderer.outputColorSpace = SRGBColorSpace;
+ this.renderer.toneMapping = ACESFilmicToneMapping;
+ this.renderer.toneMappingExposure = 1.05;
+ this._onResize = () => this._resize();
+ addEventListener('resize', this._onResize);
+ this._resize();
+ }
+
+ _initScene() {
+ this.scene = new Scene();
+ this.scene.background = new Color(COL.bg);
+ this.scene.fog = new Fog(COL.bg, 60, 190);
+ this.camera = new PerspectiveCamera(58, this._aspect(), 0.1, 500);
+
+ this.scene.add(new HemisphereLight(0x9fc6ff, 0x0a0a10, 0.65));
+ this.scene.add(new AmbientLight(0xffffff, 0.25));
+ const key = new DirectionalLight(0xffffff, 1.15);
+ key.position.set(24, 44, 18);
+ this.scene.add(key);
+
+ this._buildArena();
+ }
+
+ // The arena: one flat field, a hard centre line, and each community's half
+ // tinted with its own colour so "which end is mine" reads instantly from any
+ // camera angle. Faction A defends −z, faction B defends +z, matching where
+ // ClashRoom actually spawns them.
+ _buildArena() {
+ const floor = new Mesh(
+ new PlaneGeometry(ARENA_BOUND * 2, ARENA_BOUND * 2),
+ new MeshStandardMaterial({ color: COL.floor, roughness: 0.95, metalness: 0.05 }),
+ );
+ floor.rotation.x = -Math.PI / 2;
+ this.scene.add(floor);
+
+ this._endZones = {};
+ for (const [side, sign, color] of [['a', -1, COL.a], ['b', 1, COL.b]]) {
+ const zone = new Mesh(
+ new CircleGeometry(16, 48),
+ new MeshBasicMaterial({ color, transparent: true, opacity: 0.07, side: DoubleSide }),
+ );
+ zone.rotation.x = -Math.PI / 2;
+ zone.position.set(0, 0.02, sign * SPAWN_OFFSET);
+ this.scene.add(zone);
+ const ring = new Mesh(
+ new RingGeometry(15.6, 16, 64),
+ new MeshBasicMaterial({ color, transparent: true, opacity: 0.3, side: DoubleSide }),
+ );
+ ring.rotation.x = -Math.PI / 2;
+ ring.position.set(0, 0.03, sign * SPAWN_OFFSET);
+ this.scene.add(ring);
+ this._endZones[side] = { zone, ring };
+ }
+
+ const centre = new Mesh(
+ new PlaneGeometry(ARENA_BOUND * 2, 0.35),
+ new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.1 }),
+ );
+ centre.rotation.x = -Math.PI / 2;
+ centre.position.y = 0.03;
+ this.scene.add(centre);
+
+ // A low perimeter wall so the clamp at ARENA_BOUND is something you can see
+ // rather than an invisible shove.
+ const wallMat = new MeshStandardMaterial({ color: COL.line, roughness: 0.7, metalness: 0.2 });
+ for (const [w, d, x, z] of [
+ [ARENA_BOUND * 2, 1, 0, -ARENA_BOUND],
+ [ARENA_BOUND * 2, 1, 0, ARENA_BOUND],
+ [1, ARENA_BOUND * 2, -ARENA_BOUND, 0],
+ [1, ARENA_BOUND * 2, ARENA_BOUND, 0],
+ ]) {
+ const wall = new Mesh(new BoxGeometry(w, 2.2, d), wallMat);
+ wall.position.set(x, 1.1, z);
+ this.scene.add(wall);
+ }
+
+ // Floodlight pylons at the corners: pure silhouette, no extra lights.
+ const poleMat = new MeshStandardMaterial({ color: 0x191c24, roughness: 0.8 });
+ for (const sx of [-1, 1]) {
+ for (const sz of [-1, 1]) {
+ const pole = new Mesh(new CylinderGeometry(0.5, 0.7, 20, 8), poleMat);
+ pole.position.set(sx * (ARENA_BOUND - 3), 10, sz * (ARENA_BOUND - 3));
+ this.scene.add(pole);
+ const lamp = new Mesh(
+ new BoxGeometry(3.6, 0.5, 1.4),
+ new MeshBasicMaterial({ color: 0xdfe9ff, transparent: true, opacity: 0.7, toneMapped: false, fog: false }),
+ );
+ lamp.position.set(sx * (ARENA_BOUND - 3), 20, sz * (ARENA_BOUND - 3));
+ lamp.rotation.y = sx * sz > 0 ? Math.PI / 4 : -Math.PI / 4;
+ this.scene.add(lamp);
+ }
+ }
+ }
+
+ // Recolour the end zones to the actual two communities once the room state
+ // arrives. Called with the mints so the caller does not have to know the
+ // palette.
+ setFactions({ a, b }) {
+ this.factions = { a: a || '', b: b || '' };
+ }
+
+ factionColor(mint) {
+ return mint && mint === this.factions.b ? COL.b : COL.a;
+ }
+
+ // ── animation library ────────────────────────────────────────────────────
+
+ async loadAnimations() {
+ const defs = await fetch(MANIFEST_URL, { cache: 'force-cache' })
+ .then((r) => (r.ok ? r.json() : []))
+ .catch(() => []);
+ this._defs = Array.isArray(defs) ? defs : [];
+ for (const d of this._defs) this._loopByName.set(d.name, d.loop !== false);
+
+ const lib = new AnimationManager();
+ lib.setAnimationDefs(this._defs);
+ await Promise.all(CORE_CLIPS.map((name) => {
+ const def = this._defs.find((d) => d.name === name);
+ return def ? lib.loadAnimation(def.name, def.url, { loop: this._loopByName.get(name) }).catch(() => {}) : null;
+ }));
+ this._lib = lib;
+ }
+
+ _loadTemplate(url) {
+ if (this._templates.has(url)) return this._templates.get(url);
+ const p = this.loader.loadAsync(url);
+ this._templates.set(url, p);
+ return p;
+ }
+
+ // A fighter's body. Any humanoid GLB works: the canonical clip library is
+ // retargeted onto whatever rig it carries. A GLB that fails or stalls falls
+ // back to a known-good rig so nobody ever fights as an invisible body.
+ async _makeAvatar(glbUrl) {
+ let gltf;
+ let loadedUrl = glbUrl || '/avatars/default.glb';
+ try {
+ gltf = await Promise.race([
+ this._loadTemplate(loadedUrl),
+ new Promise((_, rej) => setTimeout(() => rej(new Error('glb timeout')), 20000)),
+ ]);
+ } catch {
+ loadedUrl = '/avatars/default.glb';
+ gltf = await this._loadTemplate(loadedUrl);
+ }
+ const model = cloneSkeleton(gltf.scene);
+ model.traverse((o) => { if (o.isMesh) { o.castShadow = true; o.frustumCulled = false; } });
+ return new ArenaAvatar(model, this._lib, this._loopByName, CLIPS, loadedUrl);
+ }
+
+ // ── roster ───────────────────────────────────────────────────────────────
+
+ /**
+ * Put a fighter on the field. Returns the avatar, or null if the world was
+ * torn down while the GLB was loading (a real race when a battle ends during
+ * a slow avatar fetch).
+ */
+ async spawnFighter(id, { avatarUrl = '', faction = '', name = '', x = 0, y = 0, z = 0, yaw = 0 } = {}) {
+ if (this.fighters.has(id)) return this.fighters.get(id);
+ // Reserve the slot before the await so two state callbacks for the same
+ // fighter cannot both spawn a body.
+ this.fighters.set(id, null);
+ const avatar = await this._makeAvatar(avatarUrl);
+ if (!this._scenePresent()) { avatar.dispose(); this.fighters.delete(id); return null; }
+
+ const root = new Group();
+ root.position.set(x, y, z);
+ root.rotation.y = yaw;
+ root.add(avatar.object);
+ this.scene.add(root);
+
+ avatar.root = root;
+ avatar.id = id;
+ avatar.name = name;
+ avatar.faction = faction;
+ avatar.headHeight = avatar.measureHeadHeight();
+ avatar.target = new Vector3(x, y, z);
+ avatar.targetYaw = yaw;
+ avatar.dead = false;
+ avatar.idle();
+
+ // A ground disc in the fighter's faction colour: at a glance, in a
+ // 16-a-side brawl, that is how you tell friend from enemy.
+ const disc = new Mesh(
+ new RingGeometry(0.5, 0.72, 24),
+ new MeshBasicMaterial({ color: this.factionColor(faction), transparent: true, opacity: 0.75, side: DoubleSide }),
+ );
+ disc.rotation.x = -Math.PI / 2;
+ disc.position.y = 0.04;
+ root.add(disc);
+ avatar.disc = disc;
+
+ this.fighters.set(id, avatar);
+ return avatar;
+ }
+
+ // Apply one authoritative update. Remote fighters lerp toward it; the local
+ // fighter keeps its own predicted position EXCEPT on a respawn, where the
+ // server picks the spawn point and the client must snap to it.
+ updateFighter(id, patch = {}) {
+ const f = this.fighters.get(id);
+ if (!f) return;
+ const isLocal = id === this.localId;
+ const wasDead = f.dead;
+ if (typeof patch.dead === 'boolean') f.dead = patch.dead;
+
+ if (Number.isFinite(patch.x)) f.target.x = patch.x;
+ if (Number.isFinite(patch.y)) f.target.y = patch.y;
+ if (Number.isFinite(patch.z)) f.target.z = patch.z;
+ if (Number.isFinite(patch.yaw)) f.targetYaw = patch.yaw;
+
+ if (isLocal && wasDead && !f.dead) {
+ // Respawned: take the server's spawn point verbatim.
+ f.root.position.copy(f.target);
+ f.root.rotation.y = f.targetYaw;
+ }
+ if (!isLocal && patch.motion) f.setMoving(patch.motion !== 'idle');
+
+ // Downed fighters lie flat and stop animating; the server revives them.
+ if (f.dead !== wasDead) {
+ f.root.rotation.x = f.dead ? -Math.PI / 2.2 : 0;
+ f.object.visible = true;
+ f.disc.material.opacity = f.dead ? 0.2 : 0.75;
+ if (f.dead) f.emote('loss'); else f.idle();
+ }
+ }
+
+ removeFighter(id) {
+ const f = this.fighters.get(id);
+ this.fighters.delete(id);
+ if (!f) return;
+ this.scene.remove(f.root);
+ f.disc?.geometry?.dispose?.();
+ f.disc?.material?.dispose?.();
+ f.dispose();
+ }
+
+ setLocal(id) {
+ this.localId = id;
+ const f = this.fighters.get(id);
+ if (f) this._cam.yaw = f.root.rotation.y;
+ }
+
+ // What the net layer sends to the server each tick. Null before the local
+ // fighter's body exists.
+ localPose() {
+ const f = this.fighters.get(this.localId);
+ if (!f) return null;
+ return {
+ x: f.root.position.x,
+ y: f.root.position.y,
+ z: f.root.position.z,
+ yaw: f.root.rotation.y,
+ motion: this._moving ? 'run' : 'idle',
+ };
+ }
+
+ // ── feedback ─────────────────────────────────────────────────────────────
+
+ // A swing the server resolved. A hit draws a tracer to the target and a burst
+ // on it; a miss draws the tracer alone, so a whiff still reads as an action.
+ swing(fromId, toId, { hit = false, killed = false } = {}) {
+ const from = this.fighters.get(fromId);
+ if (!from) return;
+ const color = this.factionColor(from.faction);
+ const start = from.root.position.clone().setY(1.3);
+ const to = toId && this.fighters.get(toId);
+ const end = to ? to.root.position.clone().setY(1.2) : start.clone().add(
+ new Vector3(Math.sin(from.root.rotation.y), 0, Math.cos(from.root.rotation.y)).multiplyScalar(20),
+ );
+ this._tracer(start, end, color);
+ if (hit && to) this._burst(end, killed ? 0xffd166 : color, killed ? 22 : 10);
+ }
+
+ celebrate(id) {
+ this.fighters.get(id)?.emote('win');
+ }
+
+ _tracer(start, end, color) {
+ const dir = end.clone().sub(start);
+ const len = dir.length() || 0.01;
+ const beam = new Mesh(
+ new CylinderGeometry(0.045, 0.045, len, 6),
+ new MeshBasicMaterial({ color, transparent: true, opacity: 0.85, toneMapped: false, fog: false, blending: AdditiveBlending }),
+ );
+ beam.position.copy(start).add(dir.clone().multiplyScalar(0.5));
+ beam.quaternion.setFromUnitVectors(new Vector3(0, 1, 0), dir.clone().normalize());
+ this.scene.add(beam);
+ this._fx.push({
+ life: 0.16,
+ tick: (dt, fx) => {
+ fx.life -= dt;
+ beam.material.opacity = Math.max(0, fx.life / 0.16) * 0.85;
+ if (fx.life > 0) return false;
+ this.scene.remove(beam);
+ beam.geometry.dispose();
+ beam.material.dispose();
+ return true;
+ },
+ });
+ }
+
+ _burst(at, color, count) {
+ const group = new Group();
+ group.position.copy(at);
+ const parts = [];
+ const geo = new SphereGeometry(0.09, 6, 5);
+ const mat = new MeshBasicMaterial({ color, transparent: true, opacity: 0.95, toneMapped: false, fog: false });
+ for (let i = 0; i < count; i++) {
+ const m = new Mesh(geo, mat);
+ const a = Math.random() * Math.PI * 2;
+ const up = 1.5 + Math.random() * 3;
+ parts.push({ m, vx: Math.cos(a) * (2 + Math.random() * 4), vy: up, vz: Math.sin(a) * (2 + Math.random() * 4) });
+ group.add(m);
+ }
+ this.scene.add(group);
+ this._fx.push({
+ life: 0.8,
+ tick: (dt, fx) => {
+ fx.life -= dt;
+ for (const p of parts) {
+ p.vy -= 12 * dt;
+ p.m.position.x += p.vx * dt;
+ p.m.position.y += p.vy * dt;
+ p.m.position.z += p.vz * dt;
+ }
+ mat.opacity = Math.max(0, fx.life / 0.8);
+ if (fx.life > 0) return false;
+ this.scene.remove(group);
+ geo.dispose();
+ mat.dispose();
+ return true;
+ },
+ });
+ }
+
+ // ── controls ─────────────────────────────────────────────────────────────
+
+ _initControls() {
+ this._cam = { yaw: 0, pitch: 0.28, dist: 8.5 };
+ this._keys = new Set();
+ this._drag = null;
+ this._move = { x: 0, y: 0 };
+ this._moving = false;
+ this._locked = false; // set while the match is not live
+
+ const move = ['w', 'a', 's', 'd', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright'];
+ this._onKeyDown = (e) => {
+ const k = e.key.toLowerCase();
+ if (move.includes(k)) { this._keys.add(k); e.preventDefault(); }
+ };
+ this._onKeyUp = (e) => this._keys.delete(e.key.toLowerCase());
+ addEventListener('keydown', this._onKeyDown);
+ addEventListener('keyup', this._onKeyUp);
+
+ const el = this.canvas;
+ el.addEventListener('pointerdown', (e) => {
+ if (e.target.closest?.('.no-orbit')) return;
+ this._drag = { x: e.clientX, y: e.clientY, id: e.pointerId };
+ el.setPointerCapture?.(e.pointerId);
+ });
+ el.addEventListener('pointermove', (e) => {
+ if (!this._drag || this._drag.id !== e.pointerId) return;
+ this._cam.yaw -= (e.clientX - this._drag.x) * 0.005;
+ this._cam.pitch = MathUtils.clamp(this._cam.pitch + (e.clientY - this._drag.y) * 0.004, -0.1, 0.75);
+ this._drag.x = e.clientX;
+ this._drag.y = e.clientY;
+ });
+ const end = (e) => { if (this._drag?.id === e.pointerId) this._drag = null; };
+ el.addEventListener('pointerup', end);
+ el.addEventListener('pointercancel', end);
+ el.addEventListener('wheel', (e) => {
+ this._cam.dist = MathUtils.clamp(this._cam.dist + Math.sign(e.deltaY) * 0.8, 3.5, 18);
+ }, { passive: true });
+ }
+
+ setJoystick(x, y) { this._move.x = x; this._move.y = y; }
+
+ // Movement is frozen outside the live phases, so nobody wanders the field
+ // during the countdown or after the final whistle.
+ setLocked(locked) { this._locked = !!locked; }
+
+ _updateLocal(dt) {
+ const f = this.fighters.get(this.localId);
+ if (!f) return;
+ if (f.dead || this._locked) { f.setMoving(false); this._moving = false; return; }
+
+ let mx = 0, mz = 0;
+ if (this._keys.has('w') || this._keys.has('arrowup')) mz -= 1;
+ if (this._keys.has('s') || this._keys.has('arrowdown')) mz += 1;
+ if (this._keys.has('a') || this._keys.has('arrowleft')) mx -= 1;
+ if (this._keys.has('d') || this._keys.has('arrowright')) mx += 1;
+ mx += this._move.x;
+ mz -= this._move.y;
+
+ const mag = Math.hypot(mx, mz);
+ this._moving = mag > 0.08;
+ if (this._moving) {
+ const len = Math.max(mag, 1);
+ mx /= len; mz /= len;
+ const cos = Math.cos(this._cam.yaw), sin = Math.sin(this._cam.yaw);
+ const wx = mx * cos - mz * sin;
+ const wz = mx * sin + mz * cos;
+ const step = WALK_SPEED * dt;
+ f.root.position.x = MathUtils.clamp(f.root.position.x + wx * step, -ARENA_BOUND, ARENA_BOUND);
+ f.root.position.z = MathUtils.clamp(f.root.position.z + wz * step, -ARENA_BOUND, ARENA_BOUND);
+ f.root.rotation.y = dampAngle(f.root.rotation.y, Math.atan2(wx, wz), 14 * dt);
+ }
+ f.setMoving(this._moving);
+ }
+
+ // Where the local fighter is aiming, so the HUD can show whether a swing has
+ // any chance of landing before the player burns the cooldown.
+ nearestEnemyDistance() {
+ const me = this.fighters.get(this.localId);
+ if (!me) return null;
+ let best = null;
+ for (const [, f] of this.fighters) {
+ if (!f || f === me || f.dead || f.faction === me.faction) continue;
+ const d = Math.hypot(f.root.position.x - me.root.position.x, f.root.position.z - me.root.position.z);
+ if (best == null || d < best) best = d;
+ }
+ return best;
+ }
+
+ // ── loop ─────────────────────────────────────────────────────────────────
+
+ start() {
+ if (this._running) return;
+ this._running = true;
+ this._last = performance.now();
+ const frame = (t) => {
+ if (!this._running) return;
+ this._raf = requestAnimationFrame(frame);
+ const dt = Math.min(0.05, (t - this._last) / 1000);
+ this._last = t;
+ this._tick(dt);
+ };
+ this._raf = requestAnimationFrame(frame);
+ }
+
+ _tick(dt) {
+ this._updateLocal(dt);
+ for (const [id, f] of this.fighters) {
+ if (!f) continue;
+ if (id !== this.localId) {
+ // Interpolate remotes toward their last authoritative pose. 12/s is
+ // fast enough to track a sprint and slow enough to smooth a 15 Hz
+ // patch rate into continuous motion.
+ f.root.position.lerp(f.target, Math.min(1, 12 * dt));
+ if (!f.dead) f.root.rotation.y = dampAngle(f.root.rotation.y, f.targetYaw, 12 * dt);
+ }
+ f.update(dt);
+ }
+ for (let i = this._fx.length - 1; i >= 0; i--) {
+ if (this._fx[i].tick(dt, this._fx[i])) this._fx.splice(i, 1);
+ }
+ this._updateCamera(dt);
+ this._onLabels?.();
+ this.renderer.render(this.scene, this.camera);
+ }
+
+ _updateCamera(dt) {
+ const f = this.fighters.get(this.localId);
+ const focus = f ? f.root.position : new Vector3(0, 0, 0);
+ const { yaw, pitch, dist } = this._cam;
+ const want = new Vector3(
+ focus.x - Math.sin(yaw) * Math.cos(pitch) * dist,
+ focus.y + 1.6 + Math.sin(pitch) * dist,
+ focus.z - Math.cos(yaw) * Math.cos(pitch) * dist,
+ );
+ this.camera.position.lerp(want, Math.min(1, 9 * dt));
+ this.camera.lookAt(focus.x, focus.y + 1.35, focus.z);
+ }
+
+ // Project a fighter's head into screen space so the page can pin a DOM name
+ // tag over it. Returns null when the head is behind the camera.
+ projectHead(id, out = { x: 0, y: 0 }) {
+ const f = this.fighters.get(id);
+ if (!f) return null;
+ const v = new Vector3().copy(f.root.position);
+ v.y += (f.headHeight || 1.7) + 0.25;
+ v.project(this.camera);
+ if (v.z > 1) return null;
+ out.x = (v.x * 0.5 + 0.5) * this.canvas.clientWidth;
+ out.y = (-v.y * 0.5 + 0.5) * this.canvas.clientHeight;
+ return out;
+ }
+
+ setLabelUpdater(fn) { this._onLabels = fn; }
+
+ // dispose() drops the scene, which is the signal an in-flight avatar load uses
+ // to bail instead of adding a body to a world that is gone.
+ _scenePresent() { return !!this.scene; }
+
+ _aspect() {
+ return (this.canvas.clientWidth || innerWidth) / (this.canvas.clientHeight || innerHeight);
+ }
+
+ _resize() {
+ const w = this.canvas.clientWidth || innerWidth;
+ const h = this.canvas.clientHeight || innerHeight;
+ this.renderer.setSize(w, h, false);
+ if (this.camera) {
+ this.camera.aspect = this._aspect();
+ this.camera.updateProjectionMatrix();
+ }
+ }
+
+ dispose() {
+ this._running = false;
+ cancelAnimationFrame(this._raf);
+ removeEventListener('resize', this._onResize);
+ removeEventListener('keydown', this._onKeyDown);
+ removeEventListener('keyup', this._onKeyUp);
+ for (const id of [...this.fighters.keys()]) this.removeFighter(id);
+ this.scene?.traverse((o) => {
+ if (o.isMesh) {
+ o.geometry?.dispose?.();
+ const m = o.material;
+ if (Array.isArray(m)) m.forEach((x) => x?.dispose?.()); else m?.dispose?.();
+ }
+ });
+ this.renderer?.dispose();
+ this.scene = null;
+ }
+}
+
+function dampAngle(current, target, lambda) {
+ let diff = ((target - current + Math.PI) % (Math.PI * 2)) - Math.PI;
+ if (diff < -Math.PI) diff += Math.PI * 2;
+ return current + diff * Math.min(1, lambda);
+}
diff --git a/src/shared/game-server-url.js b/src/shared/game-server-url.js
new file mode 100644
index 000000000..8c9268c41
--- /dev/null
+++ b/src/shared/game-server-url.js
@@ -0,0 +1,54 @@
+// Where the Colyseus game server lives, as seen from a browser.
+//
+// Every realtime surface on the site has to answer this identically — /play
+// (community-net.js), the Coin Wars arena (src/play/war.js), and anything that
+// joins a room next — because the resolution order is full of environment
+// specifics that are easy to get subtly wrong: a Codespace forwards each port as
+// its own subdomain, a local dev server must ignore the production <meta> baked
+// into the static page, and production with nothing configured must return ''
+// (stay offline) rather than loop forever on a dead socket at :2567.
+//
+// One implementation, imported by all of them.
+
+/**
+ * Resolve the websocket origin for the game server, in priority order:
+ * 1. `window.GAME_SERVER_URL` — a runtime override (ops, embeds)
+ * 2. localhost — always the local server, never the baked meta
+ * 3. `<meta name="game-server">` / `<meta name="walk-server">`
+ * 4. `VITE_GAME_SERVER_URL` / `VITE_WALK_SERVER_URL`
+ * 5. the Codespaces/Gitpod port-forward subdomain, then same-host:2567 in dev
+ * @returns {string} a ws://|wss:// origin, or '' when there is no server to reach
+ */
+export function defaultGameServerUrl() {
+ if (typeof window !== 'undefined' && window.GAME_SERVER_URL) return window.GAME_SERVER_URL;
+ // Local dev always talks to the local Colyseus server (`npm run dev:walk-all`),
+ // ignoring the production <meta game-server> baked into the static page.
+ const host = typeof location !== 'undefined' ? location.hostname : '';
+ if (host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0') {
+ return `ws://${host}:2567`;
+ }
+ if (typeof document !== 'undefined') {
+ for (const sel of ['meta[name="game-server"]', 'meta[name="walk-server"]']) {
+ const v = document.querySelector(sel)?.getAttribute('content')?.trim();
+ if (v) return v;
+ }
+ }
+ try {
+ const envUrl = import.meta?.env?.VITE_GAME_SERVER_URL || import.meta?.env?.VITE_WALK_SERVER_URL;
+ if (envUrl) return String(envUrl).trim().replace(/\/$/, '');
+ } catch (_) { /* import.meta.env is absent outside the bundler */ }
+ if (typeof location !== 'undefined') {
+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
+ // Codespaces / Gitpod forward each port as its own subdomain (-3000 → -2567).
+ const fwd = host.match(/^(.*)-(\d+)\.(app\.github\.dev|githubpreview\.dev|gitpod\.io)$/);
+ if (fwd) return `${proto}//${fwd[1]}-2567.${fwd[3]}`;
+ // Same-host:2567 is a dev convenience; the public domain doesn't expose
+ // :2567. In production with no meta/env configured, return '' so the
+ // caller stays single-player instead of looping on a dead socket.
+ let isProd = false;
+ try { isProd = import.meta?.env?.PROD === true; } catch (_) { /* not bundled */ }
+ if (!isProd) return `${proto}//${host}:2567`;
+ return '';
+ }
+ return '';
+}
diff --git a/src/voice-lab.js b/src/voice-lab.js
index 176f9d740..f88f22789 100644
--- a/src/voice-lab.js
+++ b/src/voice-lab.js
@@ -477,70 +477,163 @@ function timeAgo(ts) {
}
// ── Playground ───────────────────────────────────────────────────────────────
+//
+// One picker over every lane. Options are keyed "<provider>:<voiceId>" so the
+// same select can hold a cloned ElevenLabs voice, a free Edge neural voice and
+// a Gemini prebuilt without the ids ever colliding.
+
+// Voices the browser handed over, in pick order (most recent first). Kept in
+// memory only: the browser re-fetches the catalog on load, so persisting them
+// would risk offering a voice the account no longer has.
+let pickedVoices = [];
+let providerMeta = [];
+
+function voiceKey(provider, id) {
+ return `${provider}:${id}`;
+}
-function renderPlaygroundVoices() {
- const voices = loadVoices();
+function providerFor(id) {
+ return providerMeta.find((p) => p.id === id) || null;
+}
+
+/** Add (or promote) a voice the user selected in the browser, then select it. */
+export function usePlaygroundVoice(voice) {
+ const key = voiceKey(voice.provider, voice.id);
+ pickedVoices = [
+ { key, provider: voice.provider, voiceId: voice.id, name: voice.name },
+ ...pickedVoices.filter((v) => v.key !== key),
+ ].slice(0, 12);
+ renderPlaygroundVoices(key);
+ $('playgroundSection').scrollIntoView({ behavior: 'smooth', block: 'center' });
+}
+
+/** Called once the catalog is known, so the model/direction controls can adapt. */
+export function setProviderMeta(providers) {
+ providerMeta = providers;
+ renderModelOptions();
+}
+
+function renderPlaygroundVoices(preferKey = null) {
+ const cloned = loadVoices();
const sel = $('pgVoice');
const prev = sel.value;
sel.innerHTML = '';
- if (!voices.length) {
- sel.innerHTML = '<option value="" disabled selected>Clone a voice first</option>';
+ if (!cloned.length && !pickedVoices.length) {
+ sel.innerHTML = '<option value="" disabled selected>Pick a voice above</option>';
$('pgSpeak').disabled = true;
+ renderModelOptions();
return;
}
- voices.forEach((v) => {
- const opt = document.createElement('option');
- opt.value = v.voiceId;
- opt.textContent = v.name;
- sel.appendChild(opt);
- });
+ const addGroup = (label, items) => {
+ if (!items.length) return;
+ const group = document.createElement('optgroup');
+ group.label = label;
+ items.forEach((v) => {
+ const opt = document.createElement('option');
+ opt.value = v.key;
+ opt.textContent = v.name;
+ group.appendChild(opt);
+ });
+ sel.appendChild(group);
+ };
- if (lastClonedVoiceId && voices.find((v) => v.voiceId === lastClonedVoiceId)) {
- sel.value = lastClonedVoiceId;
- } else if (prev && voices.find((v) => v.voiceId === prev)) {
- sel.value = prev;
+ addGroup(
+ 'My cloned voices',
+ cloned.map((v) => ({
+ key: voiceKey('elevenlabs', v.voiceId),
+ name: v.name,
+ })),
+ );
+ addGroup('Picked from the browser', pickedVoices);
+
+ const options = [...sel.options].map((o) => o.value);
+ const wanted = [
+ preferKey,
+ lastClonedVoiceId ? voiceKey('elevenlabs', lastClonedVoiceId) : null,
+ prev,
+ ].find((k) => k && options.includes(k));
+ sel.value = wanted || options[0];
+
+ $('pgSpeak').disabled = false;
+ renderModelOptions();
+}
+
+/** Show the model select and the direction field only where the lane has them. */
+function renderModelOptions() {
+ const { provider } = currentSelection();
+ const meta = providerFor(provider);
+ const models = meta?.models || [];
+ const modelField = $('pgModelField');
+ const modelSel = $('pgModel');
+
+ if (!models.length) {
+ modelField.hidden = true;
+ modelSel.innerHTML = '';
} else {
- sel.value = voices[0].voiceId;
+ const prev = modelSel.value;
+ modelSel.innerHTML = models
+ .map((m) => `<option value="${esc(m.id)}" title="${esc(m.note || '')}">${esc(m.label)}</option>`)
+ .join('');
+ if (prev && models.some((m) => m.id === prev)) modelSel.value = prev;
+ modelField.hidden = false;
}
- $('pgSpeak').disabled = false;
+ $('pgDirectionRow').hidden = !meta?.direction;
+}
+
+function currentSelection() {
+ const raw = $('pgVoice').value || '';
+ const idx = raw.indexOf(':');
+ if (idx === -1) return { provider: '', voiceId: '' };
+ return { provider: raw.slice(0, idx), voiceId: raw.slice(idx + 1) };
}
async function speakPlayground() {
- const voiceId = $('pgVoice').value;
+ const { provider, voiceId } = currentSelection();
const text = $('pgText').value.trim();
- if (!voiceId || !text) return;
+ if (!provider || !voiceId || !text) return;
$('pgSpeak').disabled = true;
$('pgHint').textContent = 'Synthesizing...';
+ const payload = { provider, voiceId, text, speed: Number($('pgSpeed').value) || 1 };
+ const modelSel = $('pgModel');
+ if (!$('pgModelField').hidden && modelSel.value) payload.model = modelSel.value;
+ if (!$('pgDirectionRow').hidden) {
+ const direction = $('pgDirection').value.trim();
+ if (direction) payload.direction = direction;
+ }
+
try {
- const r = await fetch('/api/tts/eleven', {
+ const r = await fetch('/api/tts/synthesize', {
method: 'POST',
credentials: 'include',
headers: withElevenKey({ 'content-type': 'application/json' }),
- body: JSON.stringify({ voiceId, text }),
+ body: JSON.stringify(payload),
});
if (!r.ok) {
const errText = await r.text().catch(() => '');
let msg = '';
+ let topUp = '';
try {
const body = JSON.parse(errText);
msg = body.message || body.error_description || body.error || '';
+ if (body.top_up_url) topUp = ` Top up at ${body.top_up_url}.`;
} catch {
msg = errText.slice(0, 200);
}
- throw new Error(msg || `HTTP ${r.status}`);
+ throw new Error((msg || `HTTP ${r.status}`) + topUp);
}
const cacheHit = r.headers.get('x-tts-cache') === 'hit';
const billing = r.headers.get('x-tts-billing');
const chargedUsd = Number(r.headers.get('x-tts-charged-usd') || 0);
+ const contentType = r.headers.get('content-type') || 'audio/mpeg';
const buf = await r.arrayBuffer();
- const blob = new Blob([buf], { type: 'audio/mpeg' });
+ const blob = new Blob([buf], { type: contentType });
const url = URL.createObjectURL(blob);
const audio = $('pgAudio');
@@ -550,7 +643,9 @@ async function speakPlayground() {
audio.play().catch(() => {});
const billingNote =
- billing === 'byok' ? ' · your key'
+ billing === 'byok' ? ' · your ElevenLabs key'
+ : billing === 'gcp' ? ' · free on platform credits'
+ : billing === 'free' ? ' · free lane'
: chargedUsd > 0 ? ` · $${chargedUsd.toFixed(4)} credits`
: '';
$('pgHint').textContent = `${(buf.byteLength / 1024).toFixed(0)} KB · ${cacheHit ? 'cached' : 'generated'}${billingNote}`;
@@ -569,16 +664,20 @@ async function playVoiceSample(voiceId) {
if (btn) { btn.disabled = true; btn.textContent = 'Loading...'; }
try {
- const r = await fetch('/api/tts/eleven', {
+ const r = await fetch('/api/tts/synthesize', {
method: 'POST',
credentials: 'include',
headers: withElevenKey({ 'content-type': 'application/json' }),
body: JSON.stringify({
+ provider: 'elevenlabs',
voiceId,
text: "Hello, I'm your cloned voice. How does this sound?",
}),
});
- if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ if (!r.ok) {
+ const body = await r.json().catch(() => ({}));
+ throw new Error(body.message || body.error_description || `HTTP ${r.status}`);
+ }
const blob = await r.blob();
const audio = new Audio(URL.createObjectURL(blob));
audio.onended = () => URL.revokeObjectURL(audio.src);
@@ -633,6 +732,11 @@ $('voiceLibrary').addEventListener('click', (e) => {
$('pgVoice').addEventListener('change', () => {
$('pgSpeak').disabled = !$('pgVoice').value;
+ renderModelOptions();
+});
+
+$('pgSpeed').addEventListener('input', () => {
+ $('pgSpeedVal').textContent = `${Number($('pgSpeed').value).toFixed(2)}×`;
});
// Keyboard shortcut: Space to toggle record/stop when not in an input
diff --git a/tests/play-deeplink-safety.test.js b/tests/play-deeplink-safety.test.js
new file mode 100644
index 000000000..80b233f42
Binary files /dev/null and b/tests/play-deeplink-safety.test.js differ