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): photo mode, and the scene and room wiring the event surfaces need

nirholasa8b75a1a53dc
diff --git a/multiplayer/src/index.js b/multiplayer/src/index.js
index d924d70a5..d3e105027 100644
--- a/multiplayer/src/index.js
+++ b/multiplayer/src/index.js
@@ -239,6 +239,23 @@ const httpServer = http.createServer(app);
const transport = new WebSocketTransport({
server: httpServer,
+ // Phone-tolerant liveness. Colyseus defaults to pingInterval 3000 /
+ // pingMaxRetries 2, which calls `client.terminate()` after roughly SIX
+ // seconds of silence. That budget is fine for a desktop tab and hostile to
+ // a phone: iOS Safari suspends the whole page the instant the user switches
+ // apps, locks the screen, or pulls down a notification, so the socket stops
+ // answering pings and the server reaps it before they have finished reading
+ // the message. Because WalkRoom.onLeave has no allowReconnection window, that
+ // reap is permanent — the client rejoins with a NEW sessionId and respawns at
+ // the world origin, which is exactly the reported "kicked out right after
+ // joining". A terminate() is also an abrupt close with no close frame, so the
+ // player gets no explanation, just a world that resets under them.
+ //
+ // 5s x 6 retries rides out ~30s of suspension (covering the ordinary
+ // app-switch / read-a-notification round trip) while still reaping genuinely
+ // dead sockets long before Cloud Run's own idle handling would.
+ pingInterval: 5000,
+ pingMaxRetries: 6,
verifyClient(info, next) {
const origin = info.req.headers.origin;
// Origin-less upgrades (native clients / scripted probes) must NOT be a free
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index bfdc881cc..88e04c43b 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -36,6 +36,7 @@ import { verifyPresenceTicket } from '../presence-token.js';
import { verifyPlayPass } from '../play-pass.js';
import { containsHateSlur } from '../display-name-safety.js';
import { newGuestId, signGuestToken, verifyGuestToken } from '../guest-token.js';
+import { consumeSettlement } from '../settlement-guard.js';
import { installUnknownMessageGuard, PLAY_PASS_EVICT_CODE } from '../room-compat.js';
import { registerWalkRoom, unregisterWalkRoom } from '../walk-registry.js';
import {
@@ -81,7 +82,10 @@ import {
restoreQuestState, serializeQuestState,
acceptMission, abandonMission, applyEvent, recordCompletion,
missionReward, splitPot, questSnapshot, runView, objectiveMatches,
+ pruneClosedEventRuns,
} from '../quests.js';
+import { eventLiveNow, eventWindow, refreshEventWindow } from '../event-window.js';
+import { reportEventRun, fetchEventBoard } from '../event-score.js';
import { hydratePlayer, loadPlayer, savePlayer, flushPlayer } from '../playerStore.js';
import { publishFeedEvent } from '../feed.js';
import { reportQuestComplete } from '../quest-notify.js';
@@ -307,6 +311,10 @@ const CONSUME_COOLDOWN_MS = 1100; // pace between bites, no instant heal-spam
const ACTION_RATES = {
fish: 6, consume: 6, equip: 30, chop: 6, mine: 6, cook: 8, pickupRod: 4, vsync: PATCH_RATE_HZ * 2,
venter: 4, vexit: 4, quest: 8, questInteract: 6, clear: 2,
+ // The event leaderboard panel: a manual refresh plus its own poll while open.
+ // The room caches the upstream read (event-score.js), so this ceiling bounds the
+ // per-client chatter, not the API load.
+ eventBoard: 4,
// General store, bank/ATM, and the $THREE boutique (W04) — low-frequency,
// currency-mutating actions, throttled tighter than the gather loop.
store: 6, storeBuy: 6, storeSell: 6, bank: 6, boutique: 4, boutiqueQuote: 3, boutiqueSettle: 3,
@@ -486,14 +494,10 @@ export class WalkRoom extends Room {
// stable persistence id + per-action cooldowns). Never synced to peers.
this.econ = new Map();
this._actionCounters = new Map(); // sessionId → { [action]: { windowStart, count } }
- // $THREE boutique (W04) replay guard: settled quote nonces, pruned past the
- // quote TTL so a verified purchase can never re-grant a cosmetic twice, while
- // memory stays bounded (a nonce only needs to outlive its ~90s quote window).
- this._boutiqueNonces = new Map(); // nonce → settledAt (ms)
- // Wheel of Fortune (W09) replay guard — same shape and same reasoning as
- // _boutiqueNonces above: a settled paid-spin nonce can never roll a second
- // prize, and only needs to outlive its ~90s quote TTL.
- this._spinNonces = new Map(); // nonce → settledAt (ms)
+ // On-chain settlement replay protection lives in settlement-guard.js — one
+ // durable, process-wide (and Redis-backed, when configured) consumption
+ // ledger shared by the boutique and the paid wheel, replacing the per-room
+ // nonce Maps that let one payment re-grant across rooms and restarts.
// Build permissions & anti-grief (R19). Ownership and density are tracked
// off-schema (peers don't render them) but persisted with the build so they
// survive a restart. blockOwners: key → owner id. blockCounts: owner id → how
@@ -622,6 +626,9 @@ export class WalkRoom extends Room {
this.onMessage('questAccept', (client, payload) => this._handleQuestAccept(client, payload));
this.onMessage('questAbandon', (client, payload) => this._handleQuestAbandon(client, payload));
this.onMessage('questInteract', (client) => this._handleQuestInteract(client));
+ // The live event's leaderboard, proxied for the in-world panel so the client
+ // reads the SAME ranking the web endpoint serves (api/play/event-leaderboard).
+ this.onMessage('eventBoardReq', (client) => this._sendEventBoard(client));
// Vehicles. The driver streams 'vsync' (the Rapier-simulated transform); the
// server validates per-type speed/bounds and relays. 'venter'/'vexit' take and
// release the wheel, gated by proximity and single-occupancy.
@@ -683,6 +690,11 @@ export class WalkRoom extends Room {
console.warn(`[walk_world ${this.roomId}] object restore failed:`, err?.message);
}
+ // Warm the event-window cache before the first player asks for the jobs board.
+ // The gate fails closed on a cold miss, so priming it here is the difference
+ // between a live event's jobs appearing instantly and appearing a minute late.
+ refreshEventWindow().catch(() => { /* the gate stays closed until it reads */ });
+
// Tell builders, honestly, whether this world survives a server restart.
// load() above already awaited the store's readiness probe, so durability
// is settled by now.
@@ -812,6 +824,12 @@ export class WalkRoom extends Room {
// their id. Legacy `guest-…` pids migrate once (see _resolveIdentity).
const identity = await this._resolveIdentity(client, options);
const playerId = identity.playerId;
+ // Bind the verified persistence key to the session, then retire this same
+ // player's superseded session if they are reconnecting into a socket the
+ // transport has not reaped yet. Keyed on the identity resolved above, never
+ // on a raw client-asserted pid, so it can't be aimed at anyone else.
+ client.userData = { ...(client.userData || {}), playerKey: playerId };
+ this._evictPriorSession(client, playerId, clean(options?.prevSession, 32));
if (identity.wallet && !client.userData?.account) {
// The play pass proved this wallet even though the platform gate is off —
// bind it as the session account so ownership + moderation checks and the
@@ -1338,15 +1356,35 @@ export class WalkRoom extends Room {
// rewards through the same purse/XP idioms the activities use, and manages the
// co-op heist instances that live on the room (this.heists), not on a profile.
- // Send the owning client its jobs board + active runs ({offers, active, day} —
- // the shape community-net.js documents). Solo runs come straight from the
- // engine's snapshot (which also rolls stale daily state over to today); a heist
+ // The quest engine's event context: is the platform event running right now?
+ // Read from the server's own cached copy of public/event.json (event-window.js),
+ // never from anything a client sent, so the event jobs appear, pay and vanish on
+ // the real clock. A stale or unreadable config answers "closed".
+ _questCtx() {
+ return { eventLive: eventLiveNow() };
+ }
+
+ // Send the owning client its jobs board + active runs ({offers, active, day,
+ // eventLive} — the shape community-net.js documents). Solo runs come straight from
+ // the engine's snapshot (which also rolls stale daily state over to today); a heist
// run is overlaid with the crew's SHARED instance so every member's tracker
// shows the same live progress, plus the current crew size.
_sendQuests(client) {
const profile = this.econ.get(client.sessionId);
if (!profile) return;
- const snap = questSnapshot(profile.quests, utcDayKey());
+ const ctx = this._questCtx();
+ // An event job cannot advance or pay once the window shuts, so a run left over
+ // from it is dropped here rather than left in the tracker as a task that will
+ // never complete. Told once, not silently.
+ const dropped = pruneClosedEventRuns(profile.quests, ctx);
+ if (dropped.length) {
+ this._persistEcon(client.sessionId);
+ client.send('notice', {
+ kind: 'quest', ok: false,
+ text: 'The event has ended — its jobs have closed for now.',
+ });
+ }
+ const snap = questSnapshot(profile.quests, utcDayKey(), ctx);
for (let i = 0; i < snap.active.length; i++) {
const inst = this.heists.get(snap.active[i].id);
if (inst) {
@@ -1367,11 +1405,12 @@ export class WalkRoom extends Room {
const id = typeof payload?.id === 'string' ? payload.id.slice(0, 64) : '';
const mission = missionDef(id);
if (!mission) return;
- const res = acceptMission(profile.quests, id, utcDayKey());
+ const res = acceptMission(profile.quests, id, utcDayKey(), this._questCtx());
if (!res.ok) {
const text = res.reason === 'active' ? 'You already took that job.'
: res.reason === 'daily-done' ? 'That job is done for today — check back tomorrow.'
: res.reason === 'done' ? 'You’ve already completed that job.'
+ : res.reason === 'event-closed' ? 'That job only runs during the live event.'
: 'That job isn’t available to you yet.';
client.send('notice', { kind: 'quest', ok: false, text });
return;
@@ -1433,10 +1472,14 @@ export class WalkRoom extends Room {
// assembly (the whole crew at the door, judged from server positions).
_questEvent(client, profile, event) {
const dayKey = utcDayKey();
+ const eventLive = eventLiveNow();
let changed = false;
for (const [id, run] of Object.entries(profile.quests.active)) {
const mission = missionDef(id);
if (!mission || mission.kind === 'heist') continue; // heists advance via the shared instance below
+ // An event job is frozen the moment its window shuts: no progress, no
+ // payout. The run itself is dropped on the next board read (_sendQuests).
+ if (mission.event && !eventLive) continue;
const res = applyEvent(run, mission, event);
if (!res.matched) continue;
changed = true;
@@ -1476,8 +1519,11 @@ export class WalkRoom extends Room {
if (reward.gold > 0) profile.gold += reward.gold;
if (reward.xp) this._grantXp(client, profile, reward.xp.skill, reward.xp.amount);
this._sendInv(client, profile);
- client.send('questComplete', { id: mission.id, title: mission.title, reward, kind: mission.kind, coop: false });
+ client.send('questComplete', {
+ id: mission.id, title: mission.title, reward, kind: mission.kind, coop: false, event: !!mission.event,
+ });
this._publishMissionComplete(client, mission, reward.gold, false);
+ if (mission.event) this._scoreEventRun(client, profile, mission, reward.gold);
}
// Pay out a finished heist to the LIVE crew: the pot splits evenly (remainder to
@@ -1590,6 +1636,52 @@ export class WalkRoom extends Room {
}
}
+ // --- Live event: quest line + leaderboard ----------------------------------
+ // The event jobs pay ordinary in-world gold through the same path as every other
+ // mission (above); this section only RANKS them. Nothing here pays a prize: the
+ // board names the winners and the owner settles them by hand after the event.
+
+ // Score one finished event quest on the durable leaderboard. Keyed to the same
+ // verified account the profile persists under (never a client-asserted id), and
+ // fire-and-forget: the player has already been paid in-world, so a slow or down
+ // API costs a ranking update, never the reward. The player's own updated totals
+ // come back on the reply and are pushed straight to their panel.
+ _scoreEventRun(client, profile, mission, gold) {
+ const account = profile?.playerId;
+ if (!account) return;
+ const player = this.state.players.get(client.sessionId);
+ const win = eventWindow();
+ reportEventRun({
+ eventId: win?.id || '',
+ account,
+ name: player?.name || '',
+ missionId: mission.id,
+ gold,
+ }).then((result) => {
+ if (!result?.ok) return;
+ try { client.send('eventScore', { runs: result.runs, cash: result.cash, eventId: result.eventId }); } catch { /* client left */ }
+ }).catch(() => { /* reported inside the bridge */ });
+ }
+
+ // Serve the in-world leaderboard panel. Proxies the same public endpoint the web
+ // reads (cached in event-score.js so a crowded plaza is one upstream read per few
+ // seconds) and pins the caller's own row by their verified account key, which
+ // never leaves the server. An unreachable board answers { ok: false } so the panel
+ // renders its error state instead of an invented ranking.
+ async _sendEventBoard(client) {
+ if (!this._actionOk(client.sessionId, 'eventBoard')) return;
+ const profile = this.econ.get(client.sessionId);
+ if (!profile) return;
+ const board = await fetchEventBoard({ account: profile.playerId || '', limit: 10 });
+ try {
+ if (!board) {
+ client.send('eventBoard', { ok: false, reason: 'unavailable' });
+ return;
+ }
+ client.send('eventBoard', { ok: true, ...board });
+ } catch { /* client left mid-read */ }
+ }
+
_handleRename(client, payload) {
const player = this.state.players.get(client.sessionId);
if (!player) return;
@@ -2077,7 +2169,10 @@ export class WalkRoom extends Room {
buyerWallet: wallet,
amountRaw,
purpose: 'boutique',
- extra: { cosmeticId: id },
+ // cosmeticId rides to settle; forAccount seals the quote to THIS
+ // session's profile so a leaked settled quote can't be redeemed by
+ // another account (verifyTokenPurchase enforces it).
+ extra: { cosmeticId: id, forAccount: profile.playerId },
});
} catch (err) {
console.warn('[walk_world] boutique quote failed:', err?.message);
@@ -2102,7 +2197,7 @@ export class WalkRoom extends Room {
let result;
try {
- result = await verifyTokenPurchase({ quoteToken, txSig, purpose: 'boutique' });
+ result = await verifyTokenPurchase({ quoteToken, txSig, purpose: 'boutique', forAccount: profile.playerId });
} catch (err) {
console.warn('[walk_world] boutique settle failed:', err?.message);
client.send('notice', { kind: 'boutique', ok: false, text: 'Could not verify that payment — try again.' });
@@ -2112,12 +2207,15 @@ export class WalkRoom extends Room {
client.send('notice', { kind: 'boutique', ok: false, text: `Payment didn’t verify (${result?.reason || 'unknown'}).` });
return;
}
- this._pruneBoutiqueNonces();
- if (this._boutiqueNonces.has(result.nonce)) {
+ // Durable, process-wide replay guard (settlement-guard.js). The old
+ // per-room Map let the same settled payment re-grant in every other coin
+ // world and after a restart; consumeSettlement is one atomic consumption
+ // across rooms, restarts, and instances (when Redis is configured).
+ const fresh = await consumeSettlement({ nonce: result.nonce, txSig, purpose: 'boutique' });
+ if (!fresh) {
client.send('notice', { kind: 'boutique', ok: false, text: 'That purchase already settled.' });
return;
}
- this._boutiqueNonces.set(result.nonce, Date.now());
const cosmeticId = result.quote?.cosmeticId;
if (ownedCosmeticSet(profile).has(cosmeticId)) {
client.send('notice', { kind: 'boutique', ok: true, text: 'Payment verified — you already owned this.' });
@@ -2133,20 +2231,6 @@ export class WalkRoom extends Room {
this._persistEcon(client.sessionId);
}
- // Replay-guard nonces only need to outlive the quote's own TTL (~90s); prune
- // with a generous margin so memory never grows unbounded across a long-lived
- // room while staying well clear of any in-flight settle.
- _pruneBoutiqueNonces() {
- const cutoff = Date.now() - 5 * 60_000;
- for (const [nonce, ts] of this._boutiqueNonces) if (ts < cutoff) this._boutiqueNonces.delete(nonce);
- }
-
- // Same reasoning as _pruneBoutiqueNonces above, for paid-spin settlement.
- _pruneSpinNonces() {
- const cutoff = Date.now() - 5 * 60_000;
- for (const [nonce, ts] of this._spinNonces) if (ts < cutoff) this._spinNonces.delete(nonce);
- }
-
// Resolve the stable persistence identity for a joining session. Trust order:
// 1. The wallet onAuth verified (platform gate on).
// 2. A wallet sealed in a valid play pass the client sent voluntarily —
diff --git a/multiplayer/src/spin-wheel.js b/multiplayer/src/spin-wheel.js
index a77013edd..f4b182ad5 100644
--- a/multiplayer/src/spin-wheel.js
+++ b/multiplayer/src/spin-wheel.js
@@ -18,6 +18,7 @@ import { nearestWheel, wheelInRange } from './world-features.js';
import {
buildSpinPayment, verifySpinPayment, isWalletAddress, tokenConfigured, TOKEN_DECIMALS, TOKEN_SYMBOL,
} from './game-token.js';
+import { consumeSettlement } from './settlement-guard.js';
export const FREE_SPIN_COOLDOWN_MS = 12 * 60 * 60 * 1000;
export const SPIN_COST_USD = 3;
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 7b13e69d0..c0c537fa9 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -62,13 +62,10 @@ import { GUEST_SENTINEL, uploadPendingGuestAvatar, getPlayCosmetics, setPlayCosm
import { AvatarSwitcher } from './avatar-switcher.js';
import { getPresenceTicket, friendsClient } from '../friends.js';
import { getMe } from '../account.js';
-import { FriendsPanel } from './friends-panel.js';
import { showPlayIntro, makeIntroReopener } from './play-intro.js';
import { applyLoadout } from './cosmetics-loadout.js';
import { serializeLoadout, getCosmetic } from '../../multiplayer/src/cosmetics-catalog.js';
import { AccessoryManager } from '../agent-accessories.js';
-import { CosmeticsShop } from './cosmetics-shop.js';
-import { CosmeticsWardrobe } from './cosmetics-wardrobe.js';
import { HOME_TOWN, isHomeTown } from './home-town.js';
// A Robinhood Chain coin is an EVM address (pump.fun mints are Solana base58).
@@ -1835,6 +1832,25 @@ export class CoinCommunities {
}
}
+ // Deep-free an Object3D built by this module: dispose every mesh's geometry,
+ // its materials, and any textures those materials hold. Used on the totem,
+ // jumbotron and dance floor at leave(), which previously were only detached
+ // from the scene graph (`world.remove`), leaking their GPU buffers on every
+ // world switch. Never called on shared/instanced world-env or district objects
+ // — those own their own disposal.
+ _disposeObject3D(obj) {
+ if (!obj) return;
+ obj.traverse((n) => {
+ if (!n.isMesh && !n.isLine && !n.isPoints) return;
+ n.geometry?.dispose?.();
+ for (const mat of Array.isArray(n.material) ? n.material : [n.material]) {
+ if (!mat) continue;
+ for (const value of Object.values(mat)) if (value?.isTexture) value.dispose();
+ mat.dispose?.();
+ }
+ });
+ }
+
leave() {
// Invalidate any in-flight enter() so a connect/avatar continuation that
// resolves after this teardown bails instead of rebuilding the world.
@@ -1874,8 +1890,9 @@ export class CoinCommunities {
this.remotes.clear();
this._pendingStale = null;
closeAvatarInspector(); // whoever it showed just left the world with us
- if (this._totem) { this.world.remove(this._totem); this._totem = null; this._coinSpin = null; }
+ if (this._totem) { this._disposeObject3D(this._totem); this.world.remove(this._totem); this._totem = null; this._coinSpin = null; }
if (this._screen) {
+ this._disposeObject3D(this._screen); // bezel/panel/pulse geometry + coin-art texture
this.world.remove(this._screen);
this._screenTex?.dispose();
this._screen = null; this._screenCanvas = null; this._screenTex = null;
@@ -1887,7 +1904,7 @@ export class CoinCommunities {
for (const desk of this._agentDesks) desk.dispose();
this._agentDesks = [];
}
- if (this._danceFloor) { this.world.remove(this._danceFloor); this._danceFloor = null; }
+ if (this._danceFloor) { this._disposeObject3D(this._danceFloor); this.world.remove(this._danceFloor); this._danceFloor = null; }
this._floorLights = null; this._floorTiles = null; this._floorCenterMat = null;
this._danceFloorPos = null; this._onFloor = false; this._wantsDance = false;
this.ui.setOnFloor(false);
@@ -2251,8 +2268,16 @@ export class CoinCommunities {
// Open/close the cosmetics shop (R21 browse/preview + R22 buy). Lazy-built;
// previews route to the local rig hooks above, and a settled purchase records
// ownership server-side. Reverts any preview when it closes.
- _toggleShop() {
+ //
+ // The module itself is lazy-imported too: a first-time visitor walking into
+ // the plaza should not pay for the shop's catalog rendering and checkout code
+ // before the first frame. Concurrent opens share one in-flight import so a
+ // double-click can't build two shops.
+ async _toggleShop() {
if (!this._shop) {
+ if (!this._shopModule) this._shopModule = import('./cosmetics-shop.js');
+ const { CosmeticsShop } = await this._shopModule;
+ if (this._shop) { this._shop.toggle(); return; }
this._shop = new CosmeticsShop({
// Key ownership + purchases on the verified wallet when we have one;
// the shop falls back to the persisted guest id otherwise.
@@ -2323,9 +2348,16 @@ export class CoinCommunities {
else this._openFriends();
}
- _openFriends() {
+ // The drawer's view module (roster, DM threads, presence rendering) is only
+ // needed once someone opens it, so it is imported on demand; the unread badge
+ // is fed by `friendsClient` and never waits on this.
+ async _openFriends() {
if (this._friendsOpen) return;
+ // Shares the right edge with the avatar switcher; never stack the drawers.
+ this._closeAvatarPanel();
if (!this._friendsEl) {
+ if (!this._friendsModule) this._friendsModule = import('./friends-panel.js');
+ const { FriendsPanel } = await this._friendsModule;
// Right-docked drawer. The panel renders its own tabs/list/threads into
// `body`; we own only the frame, the close affordance and the hotkey hint.
const close = document.createElement('button');
@@ -2425,6 +2457,8 @@ export class CoinCommunities {
_openAvatarPanel() {
if (this._avatarPanelOpen || this.phase !== 'world') return;
+ // The two right-docked drawers share the same edge; never stack them.
+ this._closeFriends();
if (!this._avatarPanelEl) {
// Same right-docked drawer frame as the friends panel: head, scrolling
// body, hotkey hint. The panel content itself lives in avatar-switcher.js.
@@ -2552,8 +2586,11 @@ export class CoinCommunities {
// Open/close the "My Cosmetics" wardrobe panel (R23). Lazy-built on first open;
// each profile echo from the server keeps it fresh so the equipped state always
// reflects the server-authoritative result.
- _toggleWardrobe() {
+ async _toggleWardrobe() {
if (!this._wardrobe) {
+ if (!this._wardrobeModule) this._wardrobeModule = import('./cosmetics-wardrobe.js');
+ const { CosmeticsWardrobe } = await this._wardrobeModule;
+ if (this._wardrobe) { this._wardrobe.toggle(); return; }
this._wardrobe = new CosmeticsWardrobe({
onEquip: (id) => { this._equipCosmeticDurable(id); },
onShop: () => { this._wardrobe?.close(); this._toggleShop(); },
diff --git a/src/game/community-net.js b/src/game/community-net.js
index f31a3f750..060a0fd0a 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -149,7 +149,7 @@ export class CommunityNet {
// Wheel of Fortune (W09) — Fortune's Folly, the Mainland casino wheel.
spinInfo: new Set(), // ({segments, now, nextFreeSpinAt, avgLevel, minLevel, eligible, atWheel, paidAvailable, symbol, costUsd})
spinPrep: new Set(), // ({tx, tokenAmount, symbol, costUsd, quote}) — unsigned paid-spin tx to sign
- spinResult: new Set(), // ({mode, index, label, got, overflow, nextFreeSpinAt?}) — the server's roll
+ spinResult: new Set(), // ({mode, index, label, got, lost, refunded, nextFreeSpinAt?}) — the server's roll
spinDenied: new Set(), // ({reason, ...}) — a spin request refused
quests: new Set(), // ({offers, active, day}) — jobs board + active runs (W05)
questComplete: new Set(), // ({id, title, reward, kind, coop}) — a mission/heist finished
@@ -202,6 +202,13 @@ export class CommunityNet {
this._connectGen = 0;
}
+ // The server-minted guest credential (HMAC-sealed guest id) persisted by the
+ // 'guestToken' message handler in connect(). Empty until the first join has
+ // sealed this device's guest id, or when storage is blocked.
+ _guestToken() {
+ try { return localStorage.getItem('tws-guest-token') || ''; } catch { return ''; }
+ }
+
on(event, fn) {
const bucket = this._handlers[event];
if (!bucket) throw new Error(`CommunityNet: unknown event "${event}"`);
diff --git a/src/game/event-countdown.js b/src/game/event-countdown.js
index 309cabe0c..a3e268901 100644
--- a/src/game/event-countdown.js
+++ b/src/game/event-countdown.js
@@ -209,16 +209,21 @@ async function boot() {
if (!cfg) return;
// The lobby is built by coincommunities.js at boot; wait for it to exist so
- // the banner has somewhere to mount. If it never shows up (boot failure),
- // give up quietly after 20s; the watchdog in play.html owns that story.
- const started = Date.now();
- (function waitForLobby() {
- if (document.querySelector('#cc-lobby .cc-lobby-inner')) {
- new EventCountdown(cfg);
- } else if (Date.now() - started < 20000) {
- setTimeout(waitForLobby, 250);
- }
- })();
+ // the banner has somewhere to mount. No deadline: a cold dev server can take
+ // minutes to serve the world bundle, and a countdown that quietly skips slow
+ // boots is a countdown that misses exactly the overloaded event-day machines.
+ // The observer is inert until the lobby lands and disconnects the moment it
+ // does; if boot dies outright, the watchdog in play.html owns that story.
+ if (document.querySelector('#cc-lobby .cc-lobby-inner')) {
+ new EventCountdown(cfg);
+ return;
+ }
+ const obs = new MutationObserver(() => {
+ if (!document.querySelector('#cc-lobby .cc-lobby-inner')) return;
+ obs.disconnect();
+ new EventCountdown(cfg);
+ });
+ obs.observe(document.body, { childList: true, subtree: true });
}
boot();
diff --git a/src/game/meetup-event.js b/src/game/meetup-event.js
index 6509645df..2d38ab3ae 100644
--- a/src/game/meetup-event.js
+++ b/src/game/meetup-event.js
@@ -29,7 +29,7 @@ import './meetup-event.css';
import { isHomeTown } from './home-town.js';
import { getPowerSaver } from '../shared/frame-governor.js';
import {
- parseEvent, eventState, formatCountdown, fireworkPlan, PHASE, BUCKET_MS,
+ parseEvent, eventState, formatCountdown, fireworkPlan, applyPreviewOverride, PHASE, BUCKET_MS,
} from './meetup-schedule.js';
const CONFIG_URL = '/event.json';
@@ -502,17 +502,9 @@ async function boot() {
} catch { /* no event, mount nothing */ }
// Local preview: ?meetup=now starts the event 20s from load; ?meetup=<ISO>
- // shifts the whole window to that start. Duration and agenda are preserved.
- try {
- const want = new URLSearchParams(location.search).get('meetup');
- if (want && cfg) {
- const start = want === 'now' ? Date.now() + 20_000 : Date.parse(want);
- if (Number.isFinite(start)) {
- const span = cfg.endsAt - cfg.startsAt;
- cfg = { ...cfg, startsAt: start, endsAt: start + span };
- }
- }
- } catch { /* bad override, keep the real schedule */ }
+ // shifts the whole window to that start (applyPreviewOverride, shared with
+ // every other surface that reads the event).
+ cfg = applyPreviewOverride(cfg, location.search);
if (!cfg) return;
if (eventState(cfg, Date.now()).phase === PHASE.ENDED) return;
diff --git a/src/game/meetup-schedule.js b/src/game/meetup-schedule.js
index 21b49c47a..b812aa1a2 100644
--- a/src/game/meetup-schedule.js
+++ b/src/game/meetup-schedule.js
@@ -92,6 +92,26 @@ export function eventState(event, now) {
};
}
+// Local preview: `?meetup=now` shifts the window to start 20 seconds from the
+// given clock, `?meetup=<ISO>` shifts it to that instant. Duration and agenda
+// are preserved, so every surface that reads the event (the in-world layer, the
+// photo-mode stamp) previews the SAME shifted schedule instead of each one
+// re-implementing the shift and drifting. Pure so it is unit-testable: callers
+// pass the query string, not `location`.
+export function applyPreviewOverride(event, search, now = Date.now()) {
+ if (!event || !search) return event;
+ let want = null;
+ try {
+ want = new URLSearchParams(search).get('meetup');
+ } catch {
+ return event;
+ }
+ if (!want) return event;
+ const start = want === 'now' ? now + 20_000 : Date.parse(want);
+ if (!Number.isFinite(start)) return event;
+ return { ...event, startsAt: start, endsAt: start + (event.endsAt - event.startsAt) };
+}
+
// "2h 14m", "14m 09s", "0:07": a countdown that reads naturally at every
// distance instead of one fixed format that is wrong at most of them.
export function formatCountdown(ms) {
diff --git a/src/game/npc/ambient-life.js b/src/game/npc/ambient-life.js
index 17bf03bc3..826073e45 100644
--- a/src/game/npc/ambient-life.js
+++ b/src/game/npc/ambient-life.js
@@ -20,7 +20,7 @@ import {
BoxGeometry, CylinderGeometry, MeshBasicMaterial,
} from 'three';
import { AnimationManager } from '../../animation-manager.js';
-import { buildAvatar, CLIP_IDLE, CLIP_WALK } from '../avatar-rig.js';
+import { buildAvatar, releaseAvatar, CLIP_IDLE, CLIP_WALK } from '../avatar-rig.js';
import { mulberry32 } from './nav-graph.js';
import { loadCitizenPool, isCitizen } from './citizens.js';
@@ -97,7 +97,10 @@ class Pedestrian {
// AnimationManager would otherwise fetch the entire clip library.
buildAvatar(this.rig, record?.url || DEFAULT_AVATAR, this.anim, { clips: 'locomotion' })
.then(({ height }) => {
- if (this._disposed) return;
+ // Disposed mid-download: release the clone buildAvatar just added, else
+ // its shared-template ref leaks. Peds churn on every peer join/leave,
+ // so this path is hot in a busy world.
+ if (this._disposed) { releaseAvatar(this.rig); return; }
this.height = height;
// Loaded into idle by buildAvatar — set them strolling.
if (!this._held) this.anim.crossfadeTo(CLIP_WALK, 0.2).catch(() => {});
@@ -165,6 +168,10 @@ class Pedestrian {
dispose() {
this._disposed = true;
+ // Free the shared-template clone (geometry/textures), not just the scene
+ // reference. Pedestrians are constructed and disposed on every peer churn,
+ // so a leak here compounds within a single busy world session.
+ releaseAvatar(this.rig);
this.scene.remove(this.rig);
this.bubble?.remove();
clearTimeout(this._bubbleTimer);
diff --git a/src/game/npc/mobs.js b/src/game/npc/mobs.js
index b91adca05..5016b4d2e 100644
--- a/src/game/npc/mobs.js
+++ b/src/game/npc/mobs.js
@@ -2,11 +2,12 @@
//
// Mobs are consequential — they deal damage and drop loot — so unlike the
// ambient crowd they are NOT client-authoritative. Their existence, health,
-// damage, and rewards belong to the combat system (W07). This module is the
-// *visual + navigation* half: given an authoritative hostile from W07, it puts a
-// body in the world and walks it toward its target along the nav graph; contact
-// is only ever *reported* to W07, which decides the outcome. Nothing here can be
-// spoofed from the client because nothing here grants an effect.
+// damage, movement, and rewards belong to the combat system (W07). This module
+// is the *visual* half: given an authoritative hostile from W07, it puts a body
+// in the world at the position W07 streams every frame and turns it to face the
+// way it is actually moving; contact is only ever *reported* to W07, which
+// decides the outcome. Nothing here can be spoofed from the client because
+// nothing here grants an effect.
//
// W07 isn't merged yet, so this system is fully gated: with no `window.twsCombat`
// contract present it spawns nothing and fakes no combat — it simply sleeps until
@@ -28,19 +29,27 @@ const MOB_TINT = {
dummy: 0x9aa3b2, goblin: 0x5f8a3a, ogre: 0x8a6a3a, troll: 0x4a6a6a,
};
const CONTACT_RANGE = 1.6; // metres — when we tell W07 the mob is in melee
-const REPATH_INTERVAL = 0.6; // s between navmesh queries while chasing
+const YAW_EPSILON_M = 0.005; // per-frame moves smaller than this don't steer
+const YAW_LERP = 10; // 1/s — how fast the body turns into its heading
+
+function shortestAngle(a, b) {
+ let d = b - a;
+ while (d > Math.PI) d -= Math.PI * 2;
+ while (d < -Math.PI) d += Math.PI * 2;
+ return d;
+}
-// A single hostile body — a menacing capsule until W07 supplies a model. It walks
-// toward a target the server owns; it never decides anything.
+// A single hostile body — a menacing capsule until W07 supplies a model. The
+// server (via W07's per-frame setPos stream) owns where it stands; this class
+// only makes the body face the way it is actually moving and reports melee
+// contact. It never decides anything.
class Mob {
- constructor(scene, nav, spec) {
+ constructor(scene, spec) {
this.scene = scene;
- this.nav = nav;
this.id = spec.id;
this.speed = spec.speed || 2.4;
this.target = new Vector3(spec.target?.x || 0, 0, spec.target?.z || 0);
- this._path = [];
- this._repathIn = 0;
+ this._yaw = 0;
this._contacted = false;
this.rig = new Group();
@@ -54,29 +63,24 @@ class Mob {
scene.add(this.rig);
}
- setTarget(pos) { if (pos) { this.target.set(pos.x || 0, 0, pos.z || 0); this._repathIn = 0; } }
- setPos(pos) { if (pos) this.rig.position.set(pos.x || 0, 0, pos.z || 0); }
-
- async _repath() {
- this._path = await this.nav.findPath(this.rig.position, this.target);
+ setTarget(pos) { if (pos) this.target.set(pos.x || 0, 0, pos.z || 0); }
+
+ // W07 hard-sets the position every frame; derive the facing from the delta of
+ // consecutive updates so the body looks where it is going instead of frozen at
+ // its spawn heading. Sub-epsilon deltas (idle jitter) leave the yaw alone.
+ setPos(pos) {
+ if (!pos) return;
+ const p = this.rig.position;
+ const nx = pos.x || 0, nz = pos.z || 0;
+ const dx = nx - p.x, dz = nz - p.z;
+ if (Math.hypot(dx, dz) > YAW_EPSILON_M) this._yaw = Math.atan2(dx, dz);
+ p.set(nx, 0, nz);
}
update(dt, onContact) {
- this._repathIn -= dt;
- if (this._repathIn <= 0) { this._repathIn = REPATH_INTERVAL; this._repath(); }
-
- const wp = this._path[0];
- if (wp) {
- const p = this.rig.position;
- const dx = wp.x - p.x, dz = wp.z - p.z;
- const dist = Math.hypot(dx, dz);
- if (dist < 0.4) { this._path.shift(); }
- else {
- const step = Math.min(dist, this.speed * dt);
- p.x += dx / dist * step; p.z += dz / dist * step;
- this.rig.rotation.y = Math.atan2(dx, dz);
- }
- }
+ // Ease the body toward its latest heading — a small lerp keeps turns smooth
+ // even though the heading itself updates in discrete per-frame steps.
+ this.rig.rotation.y += shortestAngle(this.rig.rotation.y, this._yaw) * Math.min(1, dt * YAW_LERP);
// Reached melee range of its target: report once and let W07 rule on it.
const tx = this.target.x - this.rig.position.x, tz = this.target.z - this.rig.position.z;
@@ -88,13 +92,23 @@ class Mob {
}
}
- dispose() { this.scene.remove(this.rig); }
+ // Mobs respawn continuously all session — free the GPU resources, not just the
+ // scene-graph node, or every kill leaks a capsule + sphere + two materials.
+ dispose() {
+ this.scene.remove(this.rig);
+ this.rig.traverse((o) => {
+ if (o.isMesh) {
+ o.geometry.dispose();
+ if (Array.isArray(o.material)) o.material.forEach((m) => m.dispose());
+ else o.material.dispose();
+ }
+ });
+ }
}
export class MobSystem {
- constructor({ scene, nav }) {
+ constructor({ scene }) {
this.scene = scene;
- this.nav = nav;
this.mobs = new Map();
this._unsub = [];
@@ -110,7 +124,7 @@ export class MobSystem {
_spawn(spec) {
if (!spec?.id || this.mobs.has(spec.id)) return;
- this.mobs.set(spec.id, new Mob(this.scene, this.nav, spec));
+ this.mobs.set(spec.id, new Mob(this.scene, spec));
}
_state(s) {
const m = this.mobs.get(s?.id);
diff --git a/src/game/photo-mode.js b/src/game/photo-mode.js
new file mode 100644
index 000000000..594c05cdb
--- /dev/null
+++ b/src/game/photo-mode.js
@@ -0,0 +1,419 @@
+// Photo mode for /play — the screenshot people post.
+//
+// Press the HUD camera button or P and the world is captured, composited onto a
+// share card, and offered back as a download or a clipboard image. Everything
+// happens in the browser: one offscreen render, one 2D canvas, no upload, no
+// server round trip, nothing leaves the machine unless the player saves it.
+//
+// Three things make the shot postable rather than merely saved:
+//
+// 1. It is the WORLD, not the screen. The capture is an offscreen render
+// (scene-capture.js), so the HUD, chat, name tags and this very card are
+// never in the frame, and the classic black-screenshot bug (reading a
+// canvas whose drawing buffer the compositor already took) cannot happen.
+// 2. It is signed. A quiet monochrome bar carries the three.ws mark, the coin
+// the world belongs to, and the date, in the platform's own type.
+// 3. During a live event it is stamped with the event's own name, read from
+// /event.json, so a photo taken at the meetup says so forever.
+//
+// This module is imported lazily on the first press, with its CSS, so a player
+// who never takes a photo downloads none of it and pays no frame cost.
+
+import './photo-mode.css';
+import { captureSceneCanvas } from './scene-capture.js';
+import { threeMarkPath2D, THREE_MARK_VIEWBOX } from '../shared/brand-mark.js';
+import { parseEvent, eventState, applyPreviewOverride, PHASE } from './meetup-schedule.js';
+import { log } from '../shared/log.js';
+
+const EVENT_URL = '/event.json';
+// Wide enough for a 1440p desktop capture, small enough that the PNG stays
+// pasteable and the render target stays cheap on a phone GPU.
+const MAX_CAPTURE_WIDTH = 2560;
+// The event doc is normally already in the HTTP cache (the countdown pill and
+// the in-world meetup layer both read it on boot). If it is not, the photo
+// still lands: the stamp is the only thing that waits on it.
+const EVENT_WAIT_MS = 1200;
+
+const CARD_INK = '#08080a';
+const CARD_TEXT = '#f5f5f6';
+const CARD_DIM = '#8c8c92';
+const CARD_FAINT = '#5a5a60';
+const FONT_STACK = 'system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';
+
+// The phases where a photo is part of the event rather than merely near it: the
+// stage is already lit, the show is on, or the afterglow is still running.
+const STAMPED_PHASES = new Set([PHASE.PRESHOW, PHASE.LIVE, PHASE.AFTERGLOW]);
+
+let preview = null; // the mounted preview card, or null
+let capturing = false; // guards a double press mid-capture
+let eventDoc; // Promise<event|null>, resolved once per session
+
+function reducedMotion() {
+ return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+}
+
+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.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);
+ else n.setAttribute(k, v);
+ }
+ for (const c of [].concat(kids)) if (c) n.appendChild(c);
+ return n;
+}
+
+// ── the event stamp ─────────────────────────────────────────────────────────
+
+function loadEvent() {
+ if (eventDoc) return eventDoc;
+ eventDoc = fetch(EVENT_URL, { cache: 'no-cache' })
+ .then((res) => (res.ok ? res.json() : null))
+ .then((doc) => applyPreviewOverride(parseEvent(doc), location.search))
+ .catch(() => null);
+ return eventDoc;
+}
+
+// Start the fetch as soon as the module lands so the first press rarely waits.
+loadEvent();
+
+/** The event's own name while its window is open, else null. */
+async function eventStamp(now = Date.now()) {
+ const event = await Promise.race([
+ loadEvent(),
+ new Promise((resolve) => setTimeout(() => resolve(null), EVENT_WAIT_MS)),
+ ]);
+ if (!event) return null;
+ return STAMPED_PHASES.has(eventState(event, now).phase) ? event.title : null;
+}
+
+// ── the share card ──────────────────────────────────────────────────────────
+
+/** Trim `text` with an ellipsis until it fits `maxWidth` in the current font. */
+function fitText(ctx, text, maxWidth) {
+ if (!text) return '';
+ if (maxWidth <= 0) return '';
+ if (ctx.measureText(text).width <= maxWidth) return text;
+ let cut = text;
+ while (cut.length > 1 && ctx.measureText(cut + '…').width > maxWidth) cut = cut.slice(0, -1);
+ return cut + '…';
+}
+
+function roundRect(ctx, x, y, w, h, r) {
+ const radius = Math.min(r, w / 2, h / 2);
+ ctx.beginPath();
+ ctx.moveTo(x + radius, y);
+ ctx.arcTo(x + w, y, x + w, y + h, radius);
+ ctx.arcTo(x + w, y + h, x, y + h, radius);
+ ctx.arcTo(x, y + h, x, y, radius);
+ ctx.arcTo(x, y, x + w, y, radius);
+ ctx.closePath();
+}
+
+/**
+ * Composite the world shot onto the share card: full-bleed world, hairline, and
+ * a signature bar. Every dimension is derived from the shot, so the same code
+ * produces a balanced card for a 2560x1440 desktop frame and a 1170x2532 phone
+ * frame without a second layout.
+ */
+function composeCard(shot, { coinLabel, worldLabel, stamp, when }) {
+ const W = shot.width;
+ const shotH = shot.height;
+ // The bar tracks the shot's height (a tall portrait frame can afford more)
+ // but is clamped at both ends so it never dominates a short landscape frame
+ // nor disappears on a tiny one.
+ const barH = Math.round(Math.min(Math.max(shotH * 0.078, 54), 148));
+ const u = barH / 84; // design unit: every offset below is authored at u = 1
+ const H = shotH + barH;
+
+ const canvas = document.createElement('canvas');
+ canvas.width = W;
+ canvas.height = H;
+ const ctx = canvas.getContext('2d');
+
+ // Paint the ground first: the world can render with alpha (the transparent
+ // embed), and a PNG with holes punched in it is not a photo anyone posts.
+ ctx.fillStyle = CARD_INK;
+ ctx.fillRect(0, 0, W, H);
+ ctx.drawImage(shot.canvas, 0, 0);
+
+ const barY = shotH;
+ ctx.fillStyle = CARD_INK;
+ ctx.fillRect(0, barY, W, barH);
+ ctx.fillStyle = 'rgba(255, 255, 255, 0.14)';
+ ctx.fillRect(0, barY, W, Math.max(1, Math.round(u)));
+
+ const pad = Math.round(26 * u);
+ const midY = barY + barH / 2;
+ ctx.textBaseline = 'alphabetic';
+
+ // Right block first: it is fixed-width, and the left block gets what is left.
+ let rightWidth = 0;
+ const pillH = Math.round(30 * u);
+ const pillPad = Math.round(13 * u);
+ const dotR = Math.max(1.5, 3.2 * u);
+ let stampText = '';
+ if (stamp) {
+ ctx.font = `600 ${Math.round(13 * u)}px ${FONT_STACK}`;
+ stampText = fitText(ctx, stamp.toUpperCase(), W * 0.42 - pillPad * 2 - dotR * 2);
+ rightWidth = Math.ceil(ctx.measureText(stampText).width + pillPad * 2 + dotR * 2 + Math.round(8 * u));
+ }
+ ctx.font = `500 ${Math.round(13 * u)}px ${FONT_STACK}`;
+ const whenWidth = Math.ceil(ctx.measureText(when).width);
+ rightWidth = Math.max(rightWidth, whenWidth);
+
+ // Left block: the mark, the wordmark, and the world this shot came from.
+ const markSize = Math.round(30 * u);
+ const mark = threeMarkPath2D();
+ if (mark) {
+ ctx.save();
+ ctx.fillStyle = CARD_TEXT;
+ ctx.translate(pad, midY - markSize / 2);
+ ctx.scale(markSize / THREE_MARK_VIEWBOX, markSize / THREE_MARK_VIEWBOX);
+ ctx.fill(mark);
+ ctx.restore();
+ }
+ const textX = pad + (mark ? markSize + Math.round(13 * u) : 0);
+ const leftRoom = W - textX - pad - rightWidth - Math.round(24 * u);
+
+ ctx.fillStyle = CARD_TEXT;
+ ctx.font = `700 ${Math.round(23 * u)}px ${FONT_STACK}`;
+ ctx.fillText(fitText(ctx, 'three.ws', leftRoom), textX, midY - Math.round(3 * u));
+
+ ctx.fillStyle = CARD_DIM;
+ ctx.font = `500 ${Math.round(14 * u)}px ${FONT_STACK}`;
+ const subline = [coinLabel, worldLabel].filter(Boolean).join(' · ');
+ ctx.fillText(fitText(ctx, subline, leftRoom), textX, midY + Math.round(20 * u));
+
+ // Right block, right-aligned against the same padding as the left.
+ ctx.textAlign = 'right';
+ const rightX = W - pad;
+ if (stampText) {
+ ctx.font = `600 ${Math.round(13 * u)}px ${FONT_STACK}`;
+ const pillW = Math.ceil(ctx.measureText(stampText).width + pillPad * 2 + dotR * 2 + Math.round(8 * u));
+ const pillY = Math.round(midY - pillH - Math.round(3 * u));
+ roundRect(ctx, rightX - pillW, pillY, pillW, pillH, pillH / 2);
+ ctx.fillStyle = 'rgba(255, 255, 255, 0.06)';
+ ctx.fill();
+ ctx.strokeStyle = 'rgba(255, 255, 255, 0.24)';
+ ctx.lineWidth = Math.max(1, u);
+ ctx.stroke();
+
+ ctx.beginPath();
+ ctx.arc(rightX - pillW + pillPad + dotR, pillY + pillH / 2, dotR, 0, Math.PI * 2);
+ ctx.fillStyle = CARD_TEXT;
+ ctx.fill();
+
+ ctx.fillStyle = CARD_TEXT;
+ ctx.fillText(stampText, rightX - pillPad, pillY + pillH / 2 + Math.round(4.5 * u));
+
+ ctx.fillStyle = CARD_FAINT;
+ ctx.font = `500 ${Math.round(13 * u)}px ${FONT_STACK}`;
+ ctx.fillText(when, rightX, midY + Math.round(22 * u));
+ } else {
+ ctx.fillStyle = CARD_FAINT;
+ ctx.font = `500 ${Math.round(13 * u)}px ${FONT_STACK}`;
+ ctx.fillText(when, rightX, midY + Math.round(5 * u));
+ }
+ ctx.textAlign = 'left';
+
+ return canvas;
+}
+
+// ── shutter ─────────────────────────────────────────────────────────────────
+
+function shutter() {
+ if (reducedMotion()) return;
+ const flash = el('div', { class: 'cc-photo-flash', 'aria-hidden': 'true' });
+ const drop = () => flash.remove();
+ flash.addEventListener('animationend', drop, { once: true });
+ // A tab backgrounded mid-animation never fires animationend; the timer makes
+ // sure a white sheet can never be left over the world.
+ setTimeout(drop, 900);
+ document.body.appendChild(flash);
+}
+
+// ── preview card ────────────────────────────────────────────────────────────
+
+function canCopyImages() {
+ return typeof ClipboardItem !== 'undefined' && typeof navigator?.clipboard?.write === 'function';
+}
+
+/** True while the preview card is on screen. */
+export function photoPreviewOpen() {
+ return !!preview;
+}
+
+/** Dismiss the preview and release the object URL behind it. */
+export function closePhotoPreview() {
+ if (!preview) return;
+ const { root, url, onClose, restoreFocus, onKeydown } = preview;
+ preview = null;
+ document.removeEventListener('keydown', onKeydown, true);
+ root.classList.remove('cc-on');
+ const drop = () => {
+ root.remove();
+ URL.revokeObjectURL(url);
+ };
+ if (reducedMotion()) drop();
+ else setTimeout(drop, 220);
+ if (restoreFocus?.isConnected) restoreFocus.focus();
+ onClose?.();
+}
+
+function showPreview({ blob, width, height, stamp, filename, onClose }) {
+ const url = URL.createObjectURL(blob);
+ const restoreFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+
+ const status = el('p', { class: 'cc-photo-status', role: 'status', 'aria-live': 'polite' });
+ const setStatus = (msg, kind) => {
+ status.textContent = msg || '';
+ if (kind) status.setAttribute('data-kind', kind);
+ else status.removeAttribute('data-kind');
+ };
+
+ const downloadBtn = el('a', {
+ class: 'cc-photo-btn cc-photo-primary', href: url, download: filename,
+ title: `Save ${filename} to your device`,
+ onclick: () => setStatus('Saved to your downloads.', 'ok'),
+ }, [el('span', { 'aria-hidden': 'true', text: '⬇' }), document.createTextNode('Download')]);
+
+ const copyable = canCopyImages();
+ const copyBtn = el('button', {
+ class: 'cc-photo-btn', type: 'button',
+ 'aria-disabled': copyable ? null : 'true',
+ title: copyable
+ ? 'Copy the image to your clipboard'
+ : 'This browser cannot put images on the clipboard — Download saves the same file',
+ }, [el('span', { 'aria-hidden': 'true', text: '⧉' }), document.createTextNode('Copy image')]);
+ copyBtn.addEventListener('click', async () => {
+ // Honest rather than hidden: browsers without the async clipboard image
+ // API keep the button and get told exactly what to do instead.
+ if (!copyable) {
+ setStatus('This browser cannot put images on the clipboard. Download saves the same file.', 'warn');
+ return;
+ }
+ setStatus('Copying…');
+ try {
+ // The blob is already in hand, so the ClipboardItem is built inside the
+ // click: Safari rejects a write whose data was resolved after the gesture.
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
+ setStatus('Copied. Paste it straight into a post.', 'ok');
+ } catch (err) {
+ log.warn('[photo-mode] clipboard write failed:', err?.message);
+ setStatus('The browser blocked the copy. Download saves the same file.', 'warn');
+ }
+ });
+
+ const card = el('div', {
+ class: 'cc-photo-card', role: 'dialog', 'aria-modal': 'false', 'aria-label': 'Your photo',
+ onclick: (e) => e.stopPropagation(),
+ }, [
+ el('button', {
+ class: 'cc-photo-close', type: 'button', 'aria-label': 'Close photo', title: 'Close (Esc)',
+ onclick: () => closePhotoPreview(),
+ }, ['✕']),
+ el('span', { class: 'cc-photo-kicker', text: stamp ? 'Event photo' : 'Photo ready' }),
+ el('h3', { class: 'cc-photo-h', text: stamp || 'Your shot of the world' }),
+ el('p', { class: 'cc-photo-sub', text: `${width} × ${height} · PNG` }),
+ el('img', { class: 'cc-photo-shot', src: url, alt: 'Preview of the photo you just took', decoding: 'async' }),
+ el('div', { class: 'cc-photo-actions' }, [downloadBtn, copyBtn]),
+ status,
+ el('p', { class: 'cc-photo-hint', html: 'The world keeps running behind this card. <kbd>P</kbd> takes another.' }),
+ ]);
+
+ const root = el('div', { id: 'cc-photo', onclick: () => closePhotoPreview() }, [card]);
+
+ // Keys pressed inside the card must not also drive the avatar: /play listens
+ // on window, so Space would jump the player instead of pressing the focused
+ // button. Escape closes from anywhere except a text field.
+ const onKeydown = (e) => {
+ const typing = e.target instanceof HTMLElement
+ && (/^(input|textarea|select)$/i.test(e.target.tagName) || e.target.isContentEditable);
+ if (e.key === 'Escape' && !typing) {
+ e.preventDefault();
+ e.stopPropagation();
+ closePhotoPreview();
+ return;
+ }
+ if (card.contains(e.target)) e.stopPropagation();
+ };
+ document.addEventListener('keydown', onKeydown, true);
+
+ document.body.appendChild(root);
+ preview = { root, url, onClose, restoreFocus, onKeydown };
+ if (reducedMotion()) root.classList.add('cc-on');
+ else requestAnimationFrame(() => preview?.root.classList.add('cc-on'));
+ downloadBtn.focus();
+ return preview;
+}
+
+// ── the press ───────────────────────────────────────────────────────────────
+
+function stampedName(symbol) {
+ const now = new Date();
+ const pad2 = (n) => String(n).padStart(2, '0');
+ const when = `${now.getFullYear()}-${pad2(now.getMonth() + 1)}-${pad2(now.getDate())}`
+ + `_${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}`;
+ const slug = (symbol || 'play').toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 16) || 'play';
+ return `threews-${slug}-${when}.png`;
+}
+
+/**
+ * Take a photo: shutter, capture, composite, preview.
+ *
+ * @param {object} ctx
+ * @param {import('three').WebGLRenderer} ctx.renderer
+ * @param {import('three').Scene} ctx.scene
+ * @param {import('three').Camera} ctx.camera
+ * @param {string} [ctx.coinLabel] the coin, e.g. "$THREE"
+ * @param {string} [ctx.worldLabel] the world's display name
+ * @param {(msg: string, kind?: string) => void} [ctx.toast]
+ * @param {() => void} [ctx.onClose] fired when the preview is dismissed
+ * @returns {Promise<boolean>} whether a photo reached the preview
+ */
+export async function takePhoto({ renderer, scene, camera, coinLabel, worldLabel, toast, onClose }) {
+ if (capturing) return false;
+ capturing = true;
+ // A second press while a card is up is a retake, not a second card.
+ if (preview) closePhotoPreview();
+
+ try {
+ shutter();
+ const shot = captureSceneCanvas(renderer, scene, camera, { maxWidth: MAX_CAPTURE_WIDTH });
+ if (!shot) {
+ toast?.('Couldn’t photograph the world just now — try again in a moment.', 'warn');
+ return false;
+ }
+
+ const now = Date.now();
+ const stamp = await eventStamp(now);
+ const when = new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
+ .format(new Date(now));
+ const card = composeCard(shot, { coinLabel, worldLabel, stamp, when });
+
+ const blob = await new Promise((resolve) => card.toBlob(resolve, 'image/png'));
+ if (!blob) {
+ toast?.('Couldn’t save that photo — try again in a moment.', 'warn');
+ return false;
+ }
+
+ showPreview({
+ blob,
+ width: card.width,
+ height: card.height,
+ stamp,
+ filename: stampedName(coinLabel),
+ onClose,
+ });
+ return true;
+ } catch (err) {
+ log.warn('[photo-mode] photo failed:', err?.message);
+ toast?.('Couldn’t photograph the world just now — try again in a moment.', 'warn');
+ return false;
+ } finally {
+ capturing = false;
+ }
+}
diff --git a/src/walk.js b/src/walk.js
index c0837ae18..9ffadc3cb 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -3068,6 +3068,9 @@ function inspectRemotePlayer(rp) {
world: COIN_PARAMS.coin ? 'coin world' : 'walk',
agentId: rp.agent || '',
wallet: rp.account || '',
+ // Verified three.ws profile (W10) off the signed presence ticket — unlocks
+ // the real profile card: follow, friend/DM, creations.
+ username: rp.username || '',
avatarUrl: rp._avatarUrl,
facts: worldInspectFacts(),
}, { trigger: canvas });
@@ -3249,6 +3252,9 @@ class RemotePlayer {
// Verified account wallet bound at sign-in (server-authoritative; empty for
// guests). Feeds the avatar inspector alongside the piloted agent.
this.account = initial?.account || '';
+ // Verified three.ws username (W10) — bound server-side from the signed
+ // presence ticket, so the inspector can open the real profile card.
+ this.username = initial?.username || '';
this.name = initial?.name || sessionId.slice(0, 6);
this._avatarLoadToken = 0;
this._heldTemplateUrl = null; // remote-template URL this player currently clones
@@ -3333,6 +3339,9 @@ class RemotePlayer {
if (player.account !== undefined && player.account !== this.account) {
this.account = player.account || '';
}
+ if (player.username !== undefined && (player.username || '') !== this.username) {
+ this.username = player.username || '';
+ }
if (player.emote && player.emoteTs !== this._lastEmoteTs) {
this._lastEmoteTs = player.emoteTs;
this._playRemoteEmote(player.emote);
@@ -3622,6 +3631,7 @@ function startNet() {
avatar: player.avatar,
agent: player.agent,
account: player.account,
+ username: player.username,
cosmetics: player.cosmetics,
}),
);
diff --git a/tests/meetup-schedule.test.js b/tests/meetup-schedule.test.js
index 244bd8b31..bd895bf78 100644
--- a/tests/meetup-schedule.test.js
+++ b/tests/meetup-schedule.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import {
- parseEvent, eventState, formatCountdown, fireworkPlan,
+ parseEvent, eventState, formatCountdown, fireworkPlan, applyPreviewOverride,
PHASE, SOON_MS, PRESHOW_MS, AFTERGLOW_MS, BUCKET_MS,
} from '../src/game/meetup-schedule.js';
@@ -101,6 +101,30 @@ describe('eventState phases', () => {
});
});
+describe('applyPreviewOverride', () => {
+ const ev = parseEvent(DOC);
+
+ it('shifts the window to now + 20s for ?meetup=now, preserving duration', () => {
+ const now = 1_000_000_000;
+ const shifted = applyPreviewOverride(ev, '?meetup=now', now);
+ expect(shifted.startsAt).toBe(now + 20_000);
+ expect(shifted.endsAt - shifted.startsAt).toBe(ev.endsAt - ev.startsAt);
+ expect(shifted.agenda).toBe(ev.agenda);
+ });
+
+ it('shifts to an explicit ISO instant', () => {
+ const shifted = applyPreviewOverride(ev, '?meetup=2026-08-07T12:00:00Z');
+ expect(shifted.startsAt).toBe(Date.parse('2026-08-07T12:00:00Z'));
+ });
+
+ it('leaves the event alone without an override or with a bad one', () => {
+ expect(applyPreviewOverride(ev, '')).toBe(ev);
+ expect(applyPreviewOverride(ev, '?coin=abc')).toBe(ev);
+ expect(applyPreviewOverride(ev, '?meetup=garbage')).toBe(ev);
+ expect(applyPreviewOverride(null, '?meetup=now')).toBeNull();
+ });
+});
+
describe('formatCountdown', () => {
it('formats each distance naturally', () => {
expect(formatCountdown(2 * 3600000 + 14 * 60000)).toBe('2h 14m');
diff --git a/tests/play-avatar-switcher.test.js b/tests/play-avatar-switcher.test.js
new file mode 100644
index 000000000..97cf433c1
--- /dev/null
+++ b/tests/play-avatar-switcher.test.js
@@ -0,0 +1,190 @@
+// @vitest-environment jsdom
+//
+// In-world avatar switcher (/play). The lobby's avatar bar is unreachable once
+// a world opens, so avatar-switcher.js puts saved avatars, quick picks and the
+// bring-your-own tools in a HUD drawer. These tests pin the panel's data states
+// (signed-out, empty, populated, fetch failure) and the pick contract with the
+// scene: every chosen value flows through onPick, an ok result marks the chip
+// active, a load failure reports the avatar unchanged, and a pick in flight
+// blocks a second one instead of firing two rig rebuilds.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { AvatarSwitcher } from '../src/game/avatar-switcher.js';
+
+const flush = () => new Promise((r) => setTimeout(r, 0));
+
+function jsonResponse(status, body) {
+ return { ok: status >= 200 && status < 300, status, json: async () => body };
+}
+
+// Route the two list fetches the panel makes; anything unrouted fails loudly.
+function mockFetch(routes) {
+ return vi.fn(async (url) => {
+ for (const [prefix, resp] of Object.entries(routes)) {
+ if (String(url).startsWith(prefix)) return typeof resp === 'function' ? resp() : resp;
+ }
+ throw new Error(`unrouted fetch: ${url}`);
+ });
+}
+
+describe('AvatarSwitcher (/play in-world avatar change)', () => {
+ let host;
+
+ beforeEach(() => {
+ host = document.createElement('div');
+ document.body.appendChild(host);
+ });
+
+ afterEach(() => {
+ host.remove();
+ vi.unstubAllGlobals();
+ });
+
+ function make(h = {}, routes = {}) {
+ vi.stubGlobal('fetch', mockFetch({
+ '/api/avatars/mine': jsonResponse(200, { avatars: [] }),
+ '/api/explore': jsonResponse(200, { items: [] }),
+ ...routes,
+ }));
+ const sw = new AvatarSwitcher(host, { current: () => '', ...h });
+ sw.mount();
+ return sw;
+ }
+
+ it('renders saved avatars and routes a chip click through onPick, marking it active on ok', async () => {
+ const onPick = vi.fn(async () => ({ ok: true }));
+ make({ onPick }, {
+ '/api/avatars/mine': jsonResponse(200, {
+ avatars: [
+ { id: 'av-1', name: 'Knight', thumb_url: '/api/avatars/av-1/thumb' },
+ { id: 'av-2', name: 'Astronaut', thumb_url: '/api/avatars/av-2/thumb' },
+ ],
+ }),
+ });
+ await flush();
+
+ const chips = [...host.querySelectorAll('.cc-avsw-chip')].filter((c) => c.dataset.value);
+ const knight = chips.find((c) => c.dataset.value === 'av-1');
+ expect(knight).toBeTruthy();
+ expect(knight.textContent).toContain('Knight');
+
+ knight.click();
+ await flush();
+ expect(onPick).toHaveBeenCalledWith('av-1', { label: 'Knight' });
+ expect(knight.classList.contains('is-active')).toBe(true);
+ const status = host.querySelector('.cc-avsw-status');
+ expect(status.hidden).toBe(false);
+ expect(status.getAttribute('data-state')).toBe('done');
+ });
+
+ it('keeps the current avatar and reports the failure when the scene cannot load the pick', async () => {
+ const onPick = vi.fn(async () => ({ ok: false, reason: 'load-failed' }));
+ make({ onPick }, {
+ '/api/avatars/mine': jsonResponse(200, { avatars: [{ id: 'av-9', name: 'Broken', thumb_url: '/t' }] }),
+ });
+ await flush();
+
+ const chip = host.querySelector('.cc-avsw-chip[data-value="av-9"]');
+ chip.click();
+ await flush();
+ expect(chip.classList.contains('is-active')).toBe(false);
+ const status = host.querySelector('.cc-avsw-status');
+ expect(status.getAttribute('data-state')).toBe('error');
+ expect(status.textContent).toContain('unchanged');
+ });
+
+ it('shows a sign-in path when the saved-avatars API says unauthorized', async () => {
+ make({}, { '/api/avatars/mine': jsonResponse(401, { error: 'unauthorized' }) });
+ await flush();
+
+ const link = host.querySelector('.cc-avsw-note a');
+ expect(link).toBeTruthy();
+ expect(link.getAttribute('href')).toBe('/login?next=/play');
+ });
+
+ it('shows a create path when the account has no saved avatars yet', async () => {
+ make({}, { '/api/avatars/mine': jsonResponse(200, { avatars: [] }) });
+ await flush();
+
+ const note = host.querySelector('.cc-avsw-note');
+ expect(note.textContent).toContain('No saved avatars yet');
+ expect(note.querySelector('a[href="/create"]')).toBeTruthy();
+ });
+
+ it('offers a retry when the saved-avatars fetch fails outright', async () => {
+ let calls = 0;
+ make({}, {
+ '/api/avatars/mine': () => {
+ calls++;
+ if (calls === 1) return jsonResponse(500, {});
+ return jsonResponse(200, { avatars: [{ id: 'av-3', name: 'Back', thumb_url: '/t' }] });
+ },
+ });
+ await flush();
+
+ const retry = host.querySelector('.cc-avsw-retry');
+ expect(retry).toBeTruthy();
+ retry.click();
+ await flush();
+ expect(host.querySelector('.cc-avsw-chip[data-value="av-3"]')).toBeTruthy();
+ });
+
+ it('always offers the default avatar and adds community quick picks from explore', async () => {
+ make({}, {
+ '/api/explore': jsonResponse(200, {
+ items: [
+ { name: 'Community One', glbUrl: 'https://three.ws/m/one.glb', image: '/img/one.png' },
+ { name: 'No model, skipped', image: '/img/two.png' },
+ ],
+ }),
+ });
+ await flush();
+
+ const values = [...host.querySelectorAll('.cc-avsw-chip')].map((c) => c.dataset.value);
+ expect(values).toContain('/avatars/default.glb');
+ expect(values).toContain('https://three.ws/m/one.glb');
+ expect(values.filter(Boolean)).toHaveLength(2); // default + one explore pick; nothing for the model-less item
+ });
+
+ it('sends a pasted URL through onPick and rejects an empty paste with guidance', async () => {
+ const onPick = vi.fn(async () => ({ ok: true }));
+ make({ onPick });
+ await flush();
+
+ const input = host.querySelector('.cc-avsw-paste-input');
+ const wear = [...host.querySelectorAll('.cc-avsw-btn')].find((b) => b.textContent.includes('Wear it'));
+
+ wear.click();
+ await flush();
+ expect(onPick).not.toHaveBeenCalled();
+ expect(host.querySelector('.cc-avsw-status').getAttribute('data-state')).toBe('error');
+
+ input.value = ' https://three.ws/avatars/hero.glb ';
+ wear.click();
+ await flush();
+ expect(onPick).toHaveBeenCalledWith('https://three.ws/avatars/hero.glb', { label: 'your pasted avatar' });
+ });
+
+ it('blocks a second pick while one is in flight so the rig never rebuilds twice at once', async () => {
+ let resolveFirst;
+ const onPick = vi.fn(() => new Promise((r) => { resolveFirst = r; }));
+ make({ onPick }, {
+ '/api/avatars/mine': jsonResponse(200, {
+ avatars: [
+ { id: 'av-1', name: 'One', thumb_url: '/t1' },
+ { id: 'av-2', name: 'Two', thumb_url: '/t2' },
+ ],
+ }),
+ });
+ await flush();
+
+ host.querySelector('.cc-avsw-chip[data-value="av-1"]').click();
+ host.querySelector('.cc-avsw-chip[data-value="av-2"]').click();
+ expect(onPick).toHaveBeenCalledTimes(1);
+
+ resolveFirst({ ok: true });
+ await flush();
+ host.querySelector('.cc-avsw-chip[data-value="av-2"]').click();
+ expect(onPick).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/tests/play-profile-identity.test.js b/tests/play-profile-identity.test.js
new file mode 100644
index 000000000..200cf00a7
--- /dev/null
+++ b/tests/play-profile-identity.test.js
@@ -0,0 +1,261 @@
+// @vitest-environment jsdom
+//
+// Verified three.ws identity in the world servers (W10).
+//
+// A signed-in player's platform profile now rides the multiplayer stack end to
+// end: the presence ticket carries the username + display name (signed, so a
+// client can never wear a handle it doesn't own), WalkRoom publishes the
+// verified username on the Player schema, and the shared avatar inspector
+// renders the real profile card — follow, friend/DM, creations — for any peer
+// whose ticket verified. These tests pin the three seams that make that
+// trustworthy:
+// 1. the multiplayer ticket verifier: profile fields round-trip, legacy
+// tickets (no u/dn) still verify, tampering and expiry still fail;
+// 2. the Player schema: `username` exists, defaults empty, and stays the
+// LAST field (append-only binary protocol — reordering breaks live
+// clients against older servers);
+// 3. the inspector profile card: renders real profile data, wires follow
+// and message actions, and stays completely absent for guests.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import crypto from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+// ── 1. ticket verifier ───────────────────────────────────────────────────────
+
+process.env.MULTIPLAYER_SHARED_SECRET = 'test-shared-secret';
+const { verifyPresenceTicket } = await import('../multiplayer/src/presence-token.js');
+
+function mintTicket(payload, secret = 'test-shared-secret') {
+ const body = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
+ const sig = crypto.createHmac('sha256', secret).update(body).digest('base64url');
+ return `${body}.${sig}`;
+}
+
+describe('presence ticket carries the verified profile (W10)', () => {
+ const exp = Math.floor(Date.now() / 1000) + 600;
+
+ it('round-trips uid + username + display name', () => {
+ const t = mintTicket({ uid: 'u-123', exp, u: 'nick', dn: 'Nick Builder', crew: 'ABC', crewName: 'Alpha' });
+ expect(verifyPresenceTicket(t)).toEqual({
+ uid: 'u-123',
+ username: 'nick',
+ displayName: 'Nick Builder',
+ crew: 'ABC',
+ crewName: 'Alpha',
+ });
+ });
+
+ it('still verifies a legacy ticket without profile fields', () => {
+ const t = mintTicket({ uid: 'u-123', exp });
+ const out = verifyPresenceTicket(t);
+ expect(out.uid).toBe('u-123');
+ expect(out.username).toBe('');
+ expect(out.displayName).toBe('');
+ });
+
+ it('rejects a tampered payload', () => {
+ const t = mintTicket({ uid: 'u-123', exp, u: 'nick' });
+ const [, sig] = t.split('.');
+ const forged = Buffer.from(JSON.stringify({ uid: 'u-123', exp, u: 'someone-else' }), 'utf8').toString('base64url');
+ expect(verifyPresenceTicket(`${forged}.${sig}`)).toBeNull();
+ });
+
+ it('rejects a wrong secret and an expired ticket', () => {
+ expect(verifyPresenceTicket(mintTicket({ uid: 'u-1', exp, u: 'nick' }, 'other-secret'))).toBeNull();
+ expect(verifyPresenceTicket(mintTicket({ uid: 'u-1', exp: Math.floor(Date.now() / 1000) - 5, u: 'nick' }))).toBeNull();
+ });
+
+ it('coerces non-string profile fields to empty strings', () => {
+ const t = mintTicket({ uid: 'u-1', exp, u: { evil: true }, dn: 42 });
+ const out = verifyPresenceTicket(t);
+ expect(out.username).toBe('');
+ expect(out.displayName).toBe('');
+ });
+});
+
+// ── 2. Player schema ─────────────────────────────────────────────────────────
+
+describe('Player schema username field (W10)', () => {
+ it('exists and defaults to empty (guests stay anonymous)', async () => {
+ const { Player } = await import('../multiplayer/src/schemas.js');
+ const p = new Player();
+ expect(p.username).toBe('');
+ });
+
+ it('is declared after every pre-existing field (append-only wire protocol)', () => {
+ const src = readFileSync(path.join(__dirname, '../multiplayer/src/schemas.js'), 'utf8');
+ const defBlock = src.slice(src.indexOf('defineTypes(Player'), src.indexOf('export class Block'));
+ const usernameAt = defBlock.indexOf("username: 'string'");
+ expect(usernameAt).toBeGreaterThan(-1);
+ // Every other Player field must be declared before it — inserting a field
+ // mid-schema shifts the positional indices and desyncs live clients.
+ for (const field of ['id:', 'name:', 'account:', 'cosmetics:', 'it:', 'itSince:']) {
+ const at = defBlock.indexOf(field);
+ expect(at).toBeGreaterThan(-1);
+ expect(at).toBeLessThan(usernameAt);
+ }
+ });
+});
+
+// ── 3. inspector profile card ────────────────────────────────────────────────
+
+const apiFetchMock = vi.fn();
+const fakeFriends = {
+ loaded: true,
+ loadError: null,
+ friends: [],
+ incoming: [],
+ outgoing: [],
+ friend(id) { return this.friends.find((f) => f.id === id) || null; },
+ refresh: vi.fn(async () => {}),
+ sendRequest: vi.fn(async () => {}),
+ accept: vi.fn(async () => {}),
+};
+
+vi.mock('../src/api.js', () => ({ apiFetch: (...args) => apiFetchMock(...args) }));
+vi.mock('../src/friends.js', () => ({ friendsClient: () => fakeFriends }));
+vi.mock('../src/shared/agent-reputation.js', () => ({
+ reputationPanelEl: () => document.createElement('div'),
+ ensureReputationStyles: () => {},
+}));
+
+const { openAvatarInspector, closeAvatarInspector } = await import('../src/shared/avatar-inspector.js');
+
+const PROFILE_FIXTURE = {
+ user: {
+ id: 'u-1',
+ username: 'nick',
+ display_name: 'Nick',
+ bio: 'I build tiny worlds.',
+ avatar_url: '',
+ location: 'Lisbon',
+ created_at: '2026-01-05T00:00:00Z',
+ },
+ stats: { creations: 2, coins: 1 },
+ creations: [
+ { id: 'c1', type: 'model', title: 'Bronze sword', viewerUrl: 'https://three.ws/viewer?src=sword', createdAt: '2026-02-01T00:00:00Z' },
+ { id: 'c2', type: 'world', title: 'Cliff village', viewerUrl: 'https://three.ws/diorama?id=c2', createdAt: '2026-03-01T00:00:00Z' },
+ ],
+};
+
+function routeApi({ following = false, followPost } = {}) {
+ apiFetchMock.mockImplementation(async (pathname, init = {}) => {
+ const method = (init.method || 'GET').toUpperCase();
+ if (pathname === '/api/users/nick' && method === 'GET') {
+ return { ok: true, status: 200, json: async () => PROFILE_FIXTURE };
+ }
+ if (pathname === '/api/users/nick/follow' && method === 'GET') {
+ return { ok: true, status: 200, json: async () => ({ following, followed_by: false, followers_count: 3, following_count: 2 }) };
+ }
+ if (pathname === '/api/users/nick/follow' && (method === 'POST' || method === 'DELETE')) {
+ if (followPost) return followPost(method);
+ return { ok: true, status: 200, json: async () => ({ following: method === 'POST', followed_by: false, followers_count: method === 'POST' ? 4 : 3, following_count: 2 }) };
+ }
+ // Anything else (agents, balances) — a clean 404 keeps those sections quiet.
+ return { ok: false, status: 404, json: async () => ({}) };
+ });
+}
+
+async function settle() {
+ // The card paints across a few chained microtasks + fetch mocks.
+ for (let i = 0; i < 8; i++) await new Promise((r) => setTimeout(r, 0));
+}
+
+describe('avatar inspector profile card (W10)', () => {
+ beforeEach(() => {
+ closeAvatarInspector();
+ document.body.innerHTML = '';
+ apiFetchMock.mockReset();
+ fakeFriends.friends = [];
+ fakeFriends.incoming = [];
+ fakeFriends.outgoing = [];
+ fakeFriends.loadError = null;
+ fakeFriends.sendRequest.mockClear();
+ });
+
+ it('renders the verified profile: handle, bio, counts, creations, view-profile link', async () => {
+ routeApi();
+ openAvatarInspector({ kind: 'peer', name: 'nick-in-game', world: 'play', username: 'nick' });
+ await settle();
+
+ const root = document.querySelector('.avi-root');
+ expect(root).toBeTruthy();
+ expect(root.querySelector('.avi-subname')?.textContent).toBe('@nick');
+ const profile = root.querySelector('[data-avi="profile"]');
+ expect(profile).toBeTruthy();
+ expect(profile.textContent).toContain('I build tiny worlds.');
+ expect(profile.textContent).toContain('followers');
+ const rows = [...profile.querySelectorAll('.avi-creation')];
+ expect(rows.map((r) => r.getAttribute('href'))).toEqual([
+ 'https://three.ws/viewer?src=sword',
+ 'https://three.ws/diorama?id=c2',
+ ]);
+ const viewProfile = [...root.querySelectorAll('.avi-foot a')].find((a) => a.getAttribute('href') === '/u/nick');
+ expect(viewProfile).toBeTruthy();
+ });
+
+ it('shows no profile section at all for a guest without a verified username', async () => {
+ routeApi();
+ openAvatarInspector({ kind: 'peer', name: 'guest-ab12', world: 'play' });
+ await settle();
+ expect(document.querySelector('[data-avi="profile"]')).toBeNull();
+ expect(apiFetchMock).not.toHaveBeenCalledWith('/api/users/guest-ab12', expect.anything());
+ });
+
+ it('follow button posts the edge and flips to Following', async () => {
+ routeApi();
+ openAvatarInspector({ kind: 'peer', name: 'nick', username: 'nick' });
+ await settle();
+
+ const row = document.querySelector('.avi-profile-actions');
+ const followBtn = [...row.querySelectorAll('button')].find((b) => b.textContent === 'Follow');
+ expect(followBtn).toBeTruthy();
+ followBtn.click();
+ await settle();
+
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/users/nick/follow', expect.objectContaining({ method: 'POST' }));
+ expect([...row.querySelectorAll('button')].some((b) => b.textContent === 'Following')).toBe(true);
+ });
+
+ it('offers Message for an existing friend and routes through onOpenDM', async () => {
+ routeApi();
+ fakeFriends.friends = [{ id: 'u-1', name: 'Nick' }];
+ const onOpenDM = vi.fn();
+ openAvatarInspector({ kind: 'peer', name: 'nick', username: 'nick' }, { onOpenDM });
+ await settle();
+
+ const msgBtn = [...document.querySelectorAll('.avi-profile-actions button')].find((b) => b.textContent === 'Message');
+ expect(msgBtn).toBeTruthy();
+ msgBtn.click();
+ expect(onOpenDM).toHaveBeenCalledWith('u-1');
+ // The panel closes so the DM surface takes the stage.
+ expect(document.querySelector('.avi-root.avi-in')).toBeNull();
+ });
+
+ it('offers Add friend for a stranger and sends the request', async () => {
+ routeApi();
+ openAvatarInspector({ kind: 'peer', name: 'nick', username: 'nick' });
+ await settle();
+
+ const addBtn = [...document.querySelectorAll('.avi-profile-actions button')].find((b) => b.textContent === 'Add friend');
+ expect(addBtn).toBeTruthy();
+ addBtn.click();
+ await settle();
+ expect(fakeFriends.sendRequest).toHaveBeenCalledWith('u-1');
+ });
+
+ it('hides the friends verb (but keeps follow) for an anonymous viewer', async () => {
+ routeApi();
+ fakeFriends.loadError = 'signin';
+ openAvatarInspector({ kind: 'peer', name: 'nick', username: 'nick' });
+ await settle();
+
+ const buttons = [...document.querySelectorAll('.avi-profile-actions button')];
+ expect(buttons.map((b) => b.textContent)).toEqual(['Follow']);
+ });
+});
diff --git a/tests/walkroom-avatar-swap.test.js b/tests/walkroom-avatar-swap.test.js
new file mode 100644
index 000000000..f9277a7dc
--- /dev/null
+++ b/tests/walkroom-avatar-swap.test.js
@@ -0,0 +1,70 @@
+// Mid-session avatar swap, server side. The `avatar` message has been wired in
+// WalkRoom all along but until the in-world switcher (/play HUD Avatar button)
+// no client used it mid-session; these tests pin the contract the switcher now
+// depends on: an allow-listed URL updates the Player schema field peers
+// re-render from, junk (bare ids, blob: URLs, foreign hosts) is dropped
+// without touching the player, and the per-second rate budget holds so a
+// malicious client can't turn the swap into a broadcast amplifier. The full
+// WalkRoom needs the Colyseus runtime, so the handler runs against a minimal
+// stand-in (Object.create skips the Room constructor), same as the tag tests.
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import { WalkRoom } from '../multiplayer/src/rooms/WalkRoom.js';
+
+function makeRoom() {
+ const room = Object.create(WalkRoom.prototype);
+ room.state = { players: new Map() };
+ room._actionCounters = new Map();
+ return room;
+}
+
+function seat(room, id) {
+ const player = { avatar: 'https://three.ws/avatars/original.glb', agent: '' };
+ room.state.players.set(id, player);
+ return player;
+}
+
+const client = (sessionId) => ({ sessionId });
+
+describe('WalkRoom mid-session avatar swap', () => {
+ let room;
+ beforeEach(() => { room = makeRoom(); });
+
+ it('updates the schema avatar for an allow-listed URL so peers re-render it', () => {
+ const p = seat(room, 'a');
+ room._handleAvatar(client('a'), { avatar: 'https://three.ws/m/knight.glb' });
+ expect(p.avatar).toBe('https://three.ws/m/knight.glb');
+
+ room._actionCounters.clear();
+ room._handleAvatar(client('a'), { avatar: '/avatars/default.glb' });
+ expect(p.avatar).toBe('/avatars/default.glb');
+ });
+
+ it('drops values the clients could never load: bare ids, blob: URLs, foreign hosts', () => {
+ const p = seat(room, 'a');
+ for (const bad of ['av_12345', 'blob:https://three.ws/xyz', 'https://evil.example/model.glb']) {
+ room._actionCounters.clear();
+ room._handleAvatar(client('a'), { avatar: bad });
+ expect(p.avatar).toBe('https://three.ws/avatars/original.glb');
+ }
+ });
+
+ it('ignores a swap from a session with no seated player', () => {
+ expect(() => room._handleAvatar(client('ghost'), { avatar: '/avatars/default.glb' })).not.toThrow();
+ });
+
+ it('enforces the per-second rate budget so swaps cannot amplify broadcasts', () => {
+ const p = seat(room, 'a');
+ room._handleAvatar(client('a'), { avatar: '/avatars/one.glb' });
+ room._handleAvatar(client('a'), { avatar: '/avatars/two.glb' });
+ room._handleAvatar(client('a'), { avatar: '/avatars/three.glb' });
+ // Budget is 2/s (ACTION_RATES.avatar): the third swap in the window is dropped.
+ expect(p.avatar).toBe('/avatars/two.glb');
+ });
+
+ it('carries the optional agent label through, truncated to the wire cap', () => {
+ const p = seat(room, 'a');
+ room._handleAvatar(client('a'), { avatar: '/avatars/default.glb', agent: 'x'.repeat(200) });
+ expect(p.agent.length).toBeLessThanOrEqual(64);
+ });
+});