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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(play): keyboard and screen-reader access across the world HUD
nirholase78a3c1a53d8
diff --git a/multiplayer/src/combat-handlers.js b/multiplayer/src/combat-handlers.jsindex 9d58f322a..c6e121bad 100644--- a/multiplayer/src/combat-handlers.js+++ b/multiplayer/src/combat-handlers.js@@ -25,7 +25,7 @@ import {} from './economy.js';import { weaponDef, mobStats, rollLoot, itemLabel } from './items.js';import {- DANGER_ZONES, SPAWN_POINT, isDangerZone, randomPointInZone,+ DANGER_ZONES, SPAWN_POINT, isDangerZone, dangerZoneAt, randomPointInZone,} from './world-features.js';import {selectTarget, rollDamage, applyDamage, addHeat, decayHeat, heatStars,@@ -243,9 +243,34 @@ export function killPlayer(room, sessionId, killerLabel) {player.dead = true;const client = room.clients.find((c) => c.sessionId === sessionId);client?.send('notice', { kind: 'death', ok: false, text: killerLabel ? `You were killed by ${killerLabel}.` : 'You died.' });+ // The purse and pack emptied into the tombstone THIS instant, so push the+ // emptied snapshot now rather than at respawn: the HUD spent the whole death+ // screen showing cash the player no longer had, which reads as the drop having+ // failed. The banked balance rides along, because it is exactly what survived.+ if (client) {+ room._sendInv?.(client, profile);+ const lostItems = drop.items.reduce((n, e) => n + e.qty, 0);+ const lostParts = [];+ if (drop.gold > 0) lostParts.push(`${drop.gold} cash`);+ if (lostItems > 0) lostParts.push(`${lostItems} item${lostItems === 1 ? '' : 's'}`);+ client.send('notice', {+ kind: 'death', ok: false,+ text: lostParts.length+ ? `You dropped ${lostParts.join(' and ')} where you fell. ${profile.bank} cash stayed safe in the bank.`+ : `You were carrying nothing to drop. ${profile.bank} cash is safe in the bank.`,+ });+ }room.clock.setTimeout(() => {- if (!room.state.players.has(sessionId)) return;+ // The profile is revived UNCONDITIONALLY: a player who disconnects inside+ // the respawn window used to skip this whole block, persist hp 0, and come+ // back permanently bricked at zero health (WalkRoom.onJoin also self-heals+ // this on restore, as the second belt). Only the schema/teleport half needs+ // the session to still be present.reviveProfile(profile);+ if (!room.state.players.has(sessionId)) {+ room._persistEcon(sessionId);+ return;+ }player.dead = false;player.x = SPAWN_POINT.x; player.y = 0; player.z = SPAWN_POINT.z;player.tsServer = Date.now();@@ -333,6 +358,15 @@ export function handleAttack(room, client) {spillTombstone(room, mob.x, mob.z, itemLabel(mob.kind), { gold: 0, items: loot });room._sendInv(client, profile);room.clock.setTimeout(() => respawnMob(room, hit.id), MOB_RESPAWN_MS);+ // Quest progress: a real kill advances any active "defeat N foes" objective.+ // The danger zone comes from the MOB's authoritative position at the moment+ // it died, so a zone-pinned bounty can only be filled where it was posted.+ room._questEvent(client, profile, {+ type: 'defeat',+ target: 'mob',+ kind: mob.kind,+ zone: dangerZoneAt(mob.x, mob.z)?.id || null,+ });}room._persistEcon(client.sessionId);return;@@ -387,25 +421,46 @@ export function handleLoot(room, client, payload) {return;}- room.state.tombstones.delete(id);- room._tombLoot.delete(id);-- if (drop.gold > 0) profile.gold += drop.gold;+ // Absorb what fits FIRST, and only remove the tombstone once it is fully+ // drained. Deleting up front destroyed every item that didn't fit a nearly+ // full pack, with no warning: a player looting their own death drop with one+ // free slot lost the rest of their run for good. Whatever doesn't fit stays+ // in the marker for another trip (or another looter).+ const goldGained = drop.gold > 0 ? drop.gold : 0;+ if (goldGained > 0) {+ profile.gold = Math.min(0xffffffff, profile.gold + goldGained);+ drop.gold = 0;+ }const gained = [];+ const remaining = [];for (const { item, qty } of drop.items) {- if (!hasRoomFor(profile, item)) continue;- const leftover = addItem(profile, item, qty);+ const leftover = hasRoomFor(profile, item) ? addItem(profile, item, qty) : qty;const got = qty - leftover;if (got > 0) {gained.push(`${got > 1 ? got + ' ' : ''}${itemLabel(item).toLowerCase()}`);room._questEvent(client, profile, { type: 'collect', item, qty: got });}+ if (leftover > 0) remaining.push({ item, qty: leftover });+ }+ drop.items = remaining;+ const drained = remaining.length === 0;+ if (drained) {+ room.state.tombstones.delete(id);+ room._tombLoot.delete(id);+ } else {+ // Keep the schema marker's count honest so peers see what's left.+ ts.count = remaining.reduce((n, e) => n + e.qty, 0);}room._sendInv(client, profile);const parts = [];- if (drop.gold > 0) parts.push(`$${drop.gold}`);+ if (goldGained > 0) parts.push(`$${goldGained}`);if (gained.length) parts.push(gained.join(' + '));- client.send('notice', { kind: 'loot', ok: parts.length > 0, text: parts.length ? `Looted ${parts.join(' and ')}.` : 'The marker was already picked clean.' });+ const leftBehind = drained ? '' : ' Your pack is full; the rest is still in the marker.';+ client.send('notice', {+ kind: 'loot',+ ok: parts.length > 0,+ text: parts.length ? `Looted ${parts.join(' and ')}.${leftBehind}` : drained ? 'The marker was already picked clean.' : 'Your pack is full. Make room, the marker will wait.',+ });room._persistEcon(client.sessionId);}diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex 88e04c43b..cf83809b9 100644--- a/multiplayer/src/rooms/WalkRoom.js+++ b/multiplayer/src/rooms/WalkRoom.js@@ -58,6 +58,7 @@ import {buildTokenPurchase, verifyTokenPurchase, isWalletAddress, tokenConfigured, TOKEN_DECIMALS,} from '../game-token.js';import { readOwnedCosmetics } from '../cosmetics-ownership.js';+import { currentEventDrop, dropClaimable, warmEventDrop } from '../event-drop.js';import {itemLabel, fishCatchChance, fishDoubleChance,gatherChance, gatherDoubleChance, coalBonusChance, cookBurnChance,@@ -181,6 +182,7 @@ const BALL_AIR_DRAG = 0.12; // per-second speed decay while airborneconst BALL_MAX_IMPULSE = 12; // m/s — cap on a single client kickconst BALL_POST_KICK_CAP = 18; // m/s — absolute total velocity cap post-kickconst BALL_MIN_UPY = 0.8; // minimum upward component on any kick+const BALL_KICK_REACH_M = 3.5; // must stand beside the ball to kick it (mirrors LOOT_REACH_M-style gates)const BALL_WORLD_RADIUS = 54; // keep inside the visible arenaconst BALL_SPAWN_X = 0;const BALL_SPAWN_Y = BALL_RADIUS;@@ -324,6 +326,10 @@ const ACTION_RATES = {// Wheel of Fortune (W09) — deliberate, low-frequency, currency/payment-mutating// actions, throttled like the boutique's above.spinInfo: 4, spinFree: 3, spinPaidPrep: 3, spinPaidSettle: 3,+ // Read-only snapshot requests. profile is cheap but unbounded outbound;+ // questBoard runs boardOffers over the whole mission registry per call, so an+ // unlimited loop was a one-client DoS on the room's single thread.+ profile: 4, questBoard: 4,// Identity mutations. Each write dirties a synced string field that fans out// to every client in the room, so an unthrottled flood is a broadcast// amplifier: 2/s covers every legitimate use (a typo fix, a mid-session@@ -548,6 +554,10 @@ export class WalkRoom extends Room {// ignored, never close the session (Colyseus's default 4002 kill looked// like "session expired" to pre-fix clients). See room-compat.js.installUnknownMessageGuard(this, 'walk_world');+ // Pull the live event config now, off the join path, so the first player+ // through the door during a meetup gets their souvenir from a warm cache+ // instead of waiting on an HTTP round-trip. Non-blocking and fail-open.+ warmEventDrop();// The first client to land in this coin's instance seeds its identity.this.state.coin = cleanCoin(options?.coin);@@ -604,11 +614,11 @@ export class WalkRoom extends Room {// General store, bank/ATM, and the $THREE boutique (W04). Cash trades and// banking settle purely off-schema; the boutique settles a real on-chain// $THREE payment (game-token.js) before granting a premium cosmetic.- this.onMessage('storeReq', (client) => this._sendStore(client));+ this.onMessage('storeReq', (client) => { if (this._actionOk(client.sessionId, 'store')) this._sendStore(client); });this.onMessage('storeBuy', (client, payload) => this._handleStoreBuy(client, payload));this.onMessage('storeSell', (client, payload) => this._handleStoreSell(client, payload));this.onMessage('bank', (client, payload) => this._handleBank(client, payload));- this.onMessage('boutiqueReq', (client) => this._sendBoutique(client));+ this.onMessage('boutiqueReq', (client) => { if (this._actionOk(client.sessionId, 'boutique')) this._sendBoutique(client); });this.onMessage('boutiqueQuote', (client, payload) => this._handleBoutiqueQuote(client, payload));this.onMessage('boutiqueSettle', (client, payload) => this._handleBoutiqueSettle(client, payload));// Equip/unequip a cosmetic from the owned-inventory (R23). Server-authoritative:@@ -618,11 +628,11 @@ export class WalkRoom extends Room {// Full-loadout broadcast (R03): replaces the player's entire equipped state in// one shot, re-validated against ownership — mirrors how `avatar` is sent.this.onMessage('set-cosmetics', (client, payload) => this._handleSetCosmetics(client, payload));- this.onMessage('profileReq', (client) => this._sendProfile(client));+ this.onMessage('profileReq', (client) => { if (this._actionOk(client.sessionId, 'profile')) this._sendProfile(client); });// Quests, jobs & heists (W05, off-schema). The board, accepting/abandoning a// mission, and acting at a quest object all flow through here; the server is the// sole authority for objective progress and reward grants.- this.onMessage('questReq', (client) => this._sendQuests(client));+ this.onMessage('questReq', (client) => { if (this._actionOk(client.sessionId, 'questBoard')) this._sendQuests(client); });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));@@ -848,6 +858,11 @@ export class WalkRoom extends Room {if (!this.state.players.has(client.sessionId)) return;const saved = loadPlayer(playerId);const profile = restoreProfile(saved?.profile, playerId);+ // Second belt on the respawn-window disconnect bug: a profile that somehow+ // persisted at (or drifted to) zero HP would otherwise come back walking+ // but one hit from an instant re-death loop. Death already took its toll+ // when the tombstone spilled; rejoining always means standing back up.+ if (!(profile.hp > 0)) reviveProfile(profile);profile.cd = { fish: 0, consume: 0, chop: 0, mine: 0, cook: 0, attack: 0, pickupRod: 0 }; // per-action cooldown clocks (runtime only)// Quest log (W05): the player's accepted/completed missions + daily state,// persisted alongside the pack/purse. Stale dailies roll over to today on load.@@ -868,6 +883,12 @@ export class WalkRoom extends Room {}// A slower-arriving leave could have fired while we awaited the ledger.if (!this.state.players.has(client.sessionId)) return;+ // Event souvenir: if a community event is live in THIS world right now,+ // everyone who walks in keeps a free commemorative wearable. Runs before+ // the loadout is applied so a player who already owns it can arrive with+ // it equipped from a prior session.+ await this._grantEventSouvenir(client, profile);+ if (!this.state.players.has(client.sessionId)) return;// Cosmetics (W03): apply any loadout the player chose pre-join (in the// character creator) on top of their persisted one, validating each id// against what they own — free cosmetics always pass, premium only when@@ -1903,6 +1924,47 @@ export class WalkRoom extends Room {this._persistEcon(client.sessionId);}+ // Event souvenir grant. When a community event is live in THIS world, every+ // player who joins keeps a free commemorative wearable — a souvenir, not a+ // sale: there is no purchase path for it before, during or after.+ //+ // Server-authoritative and idempotent by construction. The window and the+ // world both come from the platform's single event config (event-drop.js+ // reading /event.json), never from a client option, and the grant itself is+ // grantCosmetic(), which is a no-op on an account that already owns the item.+ // So a reconnect, a room hop, or ten rejoins produce exactly one unlock and+ // exactly one announcement — the `souvenir` message only goes out on the+ // transition from not-owned to owned.+ //+ // Fail-open on every axis: no config, an unreachable config, a closed window,+ // or the wrong world all mean "grant nothing" and never delay the join.+ async _grantEventSouvenir(client, profile) {+ let drop;+ try {+ drop = await currentEventDrop();+ } catch (err) {+ console.warn('[walk_world] event drop config read failed:', err?.message);+ return;+ }+ if (!dropClaimable(drop, this.state.coin, Date.now())) return;+ if (!grantCosmetic(profile, drop.cosmeticId)) return; // already theirs++ // No _sendProfile here: onJoin sends the authoritative snapshot a few lines+ // later, once the loadout has been applied, and the wardrobe reads the new+ // item from that one. A second echo would only re-render it for nothing.+ this._persistEcon(client.sessionId);+ client.send('souvenir', {+ id: drop.cosmeticId,+ name: drop.cosmeticName,+ slot: drop.slot,+ eventId: drop.eventId,+ eventName: drop.eventName,+ });+ console.log(+ `[walk_world ${this.roomId}] souvenir ${drop.cosmeticId} → ${profile.playerId} (${drop.eventId})`,+ );+ }+// Dress the player from a pre-join loadout wire (the character-creator / a// world hand-off in `cosmetics` join option), merged on top of their persisted// loadout and validated per id against what they own — free cosmetics always@@ -2413,10 +2475,19 @@ export class WalkRoom extends Room {const nums = [x, y, z, qx, qy, qz, qw];if (nums.some((n) => typeof n !== 'number' || !Number.isFinite(n))) return false;- // Teleport clamp: reject a step larger than top speed could cover this window.+ // Teleport clamp, derived from REAL elapsed time. The old fixed per-message+ // window multiplied by the vsync rate limit (30/s) let a scripted sender+ // legally cover ~10x top speed by maxing the step on every message, fast+ // enough to farm the repeatable cross-town delivery jobs in seconds. Allow+ // what the type's top speed covers since the last accepted update (with a+ // floor for packet jitter and a cap so a long-parked car can't "bank" a+ // cross-map teleport), and validate the DERIVED speed, not just the+ // self-reported scalar.+ const dtS = Math.max(0.05, Math.min(0.5, (Date.now() - (v.tsServer || 0)) / 1000));const dx = x - v.x, dz = z - v.z;- if (Math.hypot(dx, dz) > vehicleMaxStepM(v.type)) return false;- // Speed-hack clamp on the reported forward speed.+ const stepM = Math.hypot(dx, dz);+ if (stepM > vehicleMaxSpeedMps(v.type) * dtS) return false;+ // Speed-hack clamp on the reported forward speed (peers render from it).const sp = typeof speed === 'number' && Number.isFinite(speed) ? speed : 0;if (Math.abs(sp) > vehicleMaxSpeedMps(v.type)) return false;diff --git a/src/friends-panel.css b/src/friends-panel.cssindex ea0ee3356..f4400a590 100644--- a/src/friends-panel.css+++ b/src/friends-panel.css@@ -1,15 +1,23 @@/* Friends panel — self-contained styles injected once by FriendsPanel.- Works in both /play (where --kg-* tokens are globally defined) and /walk- (where they aren't). The .wf-friends root defines its own token layer so- the panel looks consistent everywhere without polluting the host page. */+ The .wf-friends class on the panel root defines the token layer, so the+ panel looks consistent on /play (inside the .cc-friends-panel drawer) and+ /walk (inside the .wf-friends-overlay card) without polluting the host+ page. On /play the tokens resolve to the --cc-* monochrome design vars;+ on /walk (no --cc-* defined) they fall back to the values below. */.wf-friends {- --kg-bg: #131313;- --kg-panel: rgba(16, 22, 34, 0.96);- --kg-line: rgba(255, 255, 255, 0.12);- --kg-text: #e8edf6;- --kg-dim: #95a1b6;- --kg-accent:#cdd6e6;+ --kg-bg: var(--cc-bg, #131313);+ --kg-panel: var(--cc-panel-solid, #14181f);+ --kg-raise: rgba(255, 255, 255, 0.04);+ --kg-raise2: rgba(255, 255, 255, 0.09);+ --kg-line: var(--cc-edge, rgba(255, 255, 255, 0.12));+ --kg-line-soft: var(--cc-edge-soft, rgba(255, 255, 255, 0.07));+ --kg-text: var(--cc-text, #e8edf6);+ --kg-dim: var(--cc-dim, #95a1b6);+ --kg-accent: var(--cc-edge-hi, #cdd6e6);+ --kg-ink: var(--cc-ink, #0b0d12);+ --kg-radius: var(--cc-radius, 4px);+ --kg-radius-sm: var(--cc-radius-sm, 2px);}/* ── panel shell (walk overlay) ── */@@ -35,8 +43,8 @@pointer-events: auto;width: min(380px, calc(100vw - 24px));max-height: min(70vh, 580px);- background: var(--kg-panel);- border: 1px solid var(--kg-line);+ background: var(--kg-panel, rgba(16, 22, 34, 0.96));+ border: 1px solid var(--kg-line, rgba(255, 255, 255, 0.12));border-radius: 18px;box-shadow: 0 24px 64px rgba(0,0,0,0.6);display: flex;@@ -57,49 +65,515 @@align-items: center;justify-content: space-between;padding: 14px 16px 10px;- border-bottom: 1px solid var(--kg-line);+ border-bottom: 1px solid var(--kg-line, rgba(255, 255, 255, 0.12));flex: none;- background: var(--kg-panel);+ background: var(--kg-panel, rgba(16, 22, 34, 0.96));}.wf-friends-title {margin: 0;font-size: 15px;font-weight: 800;- color: var(--kg-text);+ color: var(--kg-text, #e8edf6);letter-spacing: -0.01em;}.wf-friends-close {+ position: relative;width: 28px;height: 28px;display: inline-flex;align-items: center;justify-content: center;font-size: 14px;- color: var(--kg-dim);+ color: var(--kg-dim, #95a1b6);background: transparent;- border: 1px solid var(--kg-line);+ border: 1px solid var(--kg-line, rgba(255, 255, 255, 0.12));border-radius: 8px;cursor: pointer;transition: color 0.15s, border-color 0.15s;}-.wf-friends-close:hover { color: var(--kg-text); border-color: var(--kg-accent); }+/* Invisible hit-area extender: 44px minimum touch target without growing the+ 28px visual (WCAG 2.5.5). */+.wf-friends-close::after {+ content: "";+ position: absolute;+ left: 50%;+ top: 50%;+ width: 44px;+ height: 44px;+ transform: translate(-50%, -50%);+}+.wf-friends-close:hover { color: var(--kg-text, #e8edf6); border-color: var(--kg-accent, #cdd6e6); }+.wf-friends-close:active { transform: scale(0.94); }+.wf-friends-close:focus-visible { outline: 2px solid var(--kg-accent, #cdd6e6); outline-offset: 2px; }.wf-friends-body {flex: 1;overflow-y: auto;padding: 12px 14px 14px;- color: var(--kg-text);+ color: var(--kg-text, #e8edf6);font-size: 14px;}-/* ── kg-fr component vars scoped to this shell ── */-.wf-friends .kg-fr,-.wf-friends .kg-fr-tabs,-.wf-friends .kg-fr-tab,-.wf-friends .kg-fr-list,-.wf-friends .kg-fr-row,-.wf-friends .kg-fr-thread {- /* inherited from .wf-friends root */+/* ── kg-fr component: the panel FriendsPanel renders (both hosts) ── */+.kg-fr {+ display: flex;+ flex-direction: column;+ flex: 1 1 auto;+ min-height: 0;+ color: var(--kg-text, #e8edf6);+ font-size: 13px;+ line-height: 1.45;+}+/* On /play the drawer body hides its own overflow; the list/thread scroll. */+.cc-friends-panel-body .kg-fr { overflow: hidden; padding: 10px 12px 12px; }++/* tabs */+.kg-fr-tabs {+ display: flex;+ gap: 6px;+ flex: none;+ margin-bottom: 10px;+}+.kg-fr-tab {+ flex: 1;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ padding: 8px 4px;+ font: inherit;+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--kg-dim, #95a1b6);+ background: transparent;+ border: 1px solid var(--kg-line, rgba(255, 255, 255, 0.12));+ border-radius: var(--kg-radius, 4px);+ cursor: pointer;+ transition: color 0.14s ease, border-color 0.14s ease, background 0.14s ease;+}+.kg-fr-tab:hover { color: var(--kg-text, #e8edf6); border-color: var(--kg-accent, #cdd6e6); }+.kg-fr-tab:active { transform: translateY(1px); }+.kg-fr-tab:focus-visible { outline: 2px solid var(--kg-accent, #cdd6e6); outline-offset: 1px; }+.kg-fr-tab.is-active {+ color: var(--kg-ink, #0b0d12);+ background: var(--kg-text, #e8edf6);+ border-color: var(--kg-text, #e8edf6);+}+.kg-fr-pill {+ min-width: 16px;+ height: 16px;+ padding: 0 4px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border-radius: 999px;+ background: #ff7a3a;+ color: #fff;+ font-size: 9px;+ font-weight: 800;+ line-height: 1;+ letter-spacing: 0;+}+.kg-fr-tab.is-active .kg-fr-pill { background: var(--kg-ink, #0b0d12); color: var(--kg-text, #e8edf6); }++/* transient action-error banner */+.kg-fr-banner {+ flex: none;+ margin-bottom: 10px;+ padding: 8px 11px;+ font-size: 12px;+ color: #ffb4b4;+ background: rgba(255, 90, 90, 0.09);+ border: 1px solid rgba(255, 110, 110, 0.35);+ border-radius: var(--kg-radius, 4px);+}++/* rows */+.kg-fr-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 4px;+ overflow-y: auto;+ min-height: 0;+}+.kg-fr-row {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 7px;+ border: 1px solid var(--kg-line-soft, rgba(255, 255, 255, 0.07));+ border-radius: var(--kg-radius, 4px);+ background: var(--kg-raise, rgba(255, 255, 255, 0.04));+ transition: border-color 0.14s ease, background 0.14s ease;+}+.kg-fr-row:hover { border-color: var(--kg-line, rgba(255, 255, 255, 0.12)); background: var(--kg-raise2, rgba(255, 255, 255, 0.09)); }+.kg-fr-rowmain {+ flex: 1;+ min-width: 0;+ display: flex;+ align-items: center;+ gap: 9px;+ padding: 2px;+ font: inherit;+ text-align: left;+ color: inherit;+ background: transparent;+ border: none;+ border-radius: var(--kg-radius-sm, 2px);+ cursor: pointer;+}+.kg-fr-rowmain:focus-visible { outline: 2px solid var(--kg-accent, #cdd6e6); outline-offset: 1px; }+.kg-fr-rowmain--static { cursor: default; }+.kg-fr-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }+.kg-fr-name {+ font-size: 13px;+ font-weight: 600;+ color: var(--kg-text, #e8edf6);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.kg-fr-status {+ font-size: 11px;+ color: var(--kg-dim, #95a1b6);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.kg-fr-status--on { color: #8fe3a8; }+.kg-fr-status--off { color: var(--kg-dim, #95a1b6); opacity: 0.8; }+.kg-fr-unread {+ flex: none;+ min-width: 18px;+ height: 18px;+ padding: 0 5px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border-radius: 999px;+ background: #ff7a3a;+ color: #fff;+ font-size: 10px;+ font-weight: 800;+ line-height: 1;+}+.kg-fr-rowactions { flex: none; display: inline-flex; align-items: center; gap: 5px; }++/* avatars */+.kg-fr-av {+ position: relative;+ flex: none;+ width: 32px;+ height: 32px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border-radius: 50%;+ background: var(--kg-raise2, rgba(255, 255, 255, 0.09));+ border: 1px solid var(--kg-line, rgba(255, 255, 255, 0.12));+}+.kg-fr-av-img { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; display: block; }+.kg-fr-av-ini {+ font-size: 12px;+ font-weight: 800;+ letter-spacing: 0.02em;+ color: var(--kg-dim, #95a1b6);+ user-select: none;+}+.kg-fr-dot {+ position: absolute;+ right: -1px;+ bottom: -1px;+ width: 9px;+ height: 9px;+ border-radius: 50%;+ box-shadow: 0 0 0 2px var(--kg-panel, #14181f);+}+.kg-fr-dot--on { background: #4cd77a; }+.kg-fr-dot--off { background: var(--kg-line, rgba(255, 255, 255, 0.12)); }++/* small per-row icon buttons (message / mute / remove) */+.kg-fr-icon {+ position: relative;+ width: 26px;+ height: 26px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ font-size: 12px;+ line-height: 1;+ color: var(--kg-dim, #95a1b6);+ background: transparent;+ border: 1px solid transparent;+ border-radius: var(--kg-radius-sm, 2px);+ cursor: pointer;+ transition: color 0.13s ease, border-color 0.13s ease, background 0.13s ease;+}+.kg-fr-icon:hover { color: var(--kg-text, #e8edf6); border-color: var(--kg-line, rgba(255, 255, 255, 0.12)); background: var(--kg-raise2, rgba(255, 255, 255, 0.09)); }+.kg-fr-icon:active { transform: translateY(1px); }+.kg-fr-icon:focus-visible { outline: 2px solid var(--kg-accent, #cdd6e6); outline-offset: 1px; }+.kg-fr-icon:disabled { opacity: 0.4; cursor: default; }+.kg-fr-icon--danger:hover { color: #ff9b9b; border-color: rgba(255, 110, 110, 0.4); background: rgba(255, 90, 90, 0.1); }++/* text buttons (Accept / Decline / Add / Sign in / Search to add) */+.kg-fr-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 8px 16px;+ font: inherit;+ font-size: 12px;+ font-weight: 700;+ letter-spacing: 0.03em;+ color: var(--kg-text, #e8edf6);+ background: transparent;+ border: 1px solid var(--kg-line, rgba(255, 255, 255, 0.12));+ border-radius: var(--kg-radius, 4px);+ cursor: pointer;+ text-decoration: none;+ transition: color 0.13s ease, border-color 0.13s ease, background 0.13s ease, filter 0.12s ease;+}+.kg-fr-btn:hover { border-color: var(--kg-accent, #cdd6e6); background: var(--kg-raise, rgba(255, 255, 255, 0.04)); }+.kg-fr-btn:active { transform: translateY(1px); }+.kg-fr-btn:focus-visible { outline: 2px solid var(--kg-accent, #cdd6e6); outline-offset: 2px; }+.kg-fr-btn:disabled { opacity: 0.45; cursor: default; }+.kg-fr-btn--primary {+ background: var(--kg-text, #e8edf6);+ border-color: var(--kg-text, #e8edf6);+ color: var(--kg-ink, #0b0d12);+}+.kg-fr-btn--primary:hover { background: var(--kg-text, #e8edf6); filter: brightness(0.9); }+.kg-fr-btn--ghost { border-color: transparent; color: var(--kg-dim, #95a1b6); }+.kg-fr-btn--ghost:hover { color: var(--kg-text, #e8edf6); border-color: var(--kg-line, rgba(255, 255, 255, 0.12)); }+.kg-fr-btn--sm { padding: 5px 11px; font-size: 11px; }++.kg-fr-tagpending {+ padding: 3px 9px;+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--kg-dim, #95a1b6);+ border: 1px solid var(--kg-line-soft, rgba(255, 255, 255, 0.07));+ border-radius: 999px;+ white-space: nowrap;+}+.kg-fr-tagpending--ok { color: #8fe3a8; border-color: rgba(80, 210, 130, 0.35); }++/* requests tab */+.kg-fr-reqs { display: flex; flex-direction: column; gap: 4px; overflow-y: auto; min-height: 0; }+.kg-fr-subhead {+ margin: 8px 2px 6px;+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--kg-dim, #95a1b6);+}+.kg-fr-subhead:first-child { margin-top: 0; }++/* add / search tab */+.kg-fr-add { display: flex; flex-direction: column; gap: 10px; flex: 1; min-height: 0; }+.kg-fr-searchwrap {+ flex: none;+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 0 10px;+ background: rgba(0, 0, 0, 0.25);+ border: 1px solid var(--kg-line, rgba(255, 255, 255, 0.12));+ border-radius: var(--kg-radius, 4px);+ transition: border-color 0.15s ease;+}+.kg-fr-searchwrap:focus-within { border-color: var(--kg-accent, #cdd6e6); }+.kg-fr-search-ico { flex: none; font-size: 12px; opacity: 0.7; filter: grayscale(1); }+.kg-fr-search {+ flex: 1;+ min-width: 0;+ padding: 9px 0;+ font: inherit;+ font-size: 13px;+ color: var(--kg-text, #e8edf6);+ background: transparent;+ border: none;+ outline: none;+}+.kg-fr-search::placeholder { color: var(--kg-dim, #95a1b6); }+.kg-fr-results { flex: 1; min-height: 0; display: flex; flex-direction: column; overflow-y: auto; }+.kg-fr-hint {+ margin: 14px 4px;+ font-size: 12px;+ color: var(--kg-dim, #95a1b6);+ text-align: center;+}++/* empty states */+.kg-fr-empty {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 6px;+ padding: 26px 18px;+ text-align: center;+}+.kg-fr-empty-glyph { font-size: 30px; line-height: 1; opacity: 0.75; filter: grayscale(0.6); margin-bottom: 4px; }+.kg-fr-empty-title { margin: 0; font-size: 14px; font-weight: 700; color: var(--kg-text, #e8edf6); }+.kg-fr-empty-sub { margin: 0 0 8px; font-size: 12px; line-height: 1.5; color: var(--kg-dim, #95a1b6); max-width: 30ch; }++/* loading skeleton */+.kg-fr-skel { display: flex; flex-direction: column; gap: 6px; padding: 2px 0; }+.kg-fr-skel-row {+ height: 46px;+ border-radius: var(--kg-radius, 4px);+ border: 1px solid var(--kg-line-soft, rgba(255, 255, 255, 0.07));+ background: linear-gradient(90deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.04));+ background-size: 200% 100%;+ animation: kg-fr-shimmer 1.3s infinite;+}+@keyframes kg-fr-shimmer { to { background-position: -200% 0; } }++/* ── DM thread ── */+.kg-fr-thread { display: flex; flex-direction: column; flex: 1; min-height: 0; }+.kg-fr-thread-head {+ flex: none;+ display: flex;+ align-items: center;+ gap: 9px;+ padding: 0 0 9px;+ margin-bottom: 9px;+ border-bottom: 1px solid var(--kg-line-soft, rgba(255, 255, 255, 0.07));+}+.kg-fr-back {+ position: relative;+ flex: none;+ width: 28px;+ height: 28px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ font-size: 18px;+ line-height: 1;+ color: var(--kg-dim, #95a1b6);+ background: transparent;+ border: 1px solid var(--kg-line, rgba(255, 255, 255, 0.12));+ border-radius: var(--kg-radius, 4px);+ cursor: pointer;+ transition: color 0.13s ease, border-color 0.13s ease, background 0.13s ease;+}+.kg-fr-back::after {+ content: "";+ position: absolute;+ left: 50%;+ top: 50%;+ width: 44px;+ height: 44px;+ transform: translate(-50%, -50%);+}+.kg-fr-back:hover { color: var(--kg-text, #e8edf6); border-color: var(--kg-accent, #cdd6e6); background: var(--kg-raise, rgba(255, 255, 255, 0.04)); }+.kg-fr-back:active { transform: translateY(1px); }+.kg-fr-back:focus-visible { outline: 2px solid var(--kg-accent, #cdd6e6); outline-offset: 1px; }++.kg-fr-thread-msgs {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 2px 2px 8px;+}+.kg-fr-thread-empty {+ margin: auto;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 4px;+ padding: 20px 14px;+ text-align: center;+}+.kg-fr-daysep {+ align-self: center;+ margin: 6px 0 2px;+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--kg-dim, #95a1b6);+}+.kg-fr-msg {+ display: flex;+ align-items: baseline;+ gap: 8px;+ max-width: 86%;+ padding: 7px 10px;+ border-radius: var(--kg-radius, 4px);+ border: 1px solid var(--kg-line-soft, rgba(255, 255, 255, 0.07));+ background: var(--kg-raise, rgba(255, 255, 255, 0.04));+ animation: kg-fr-msg-in 0.16s ease;+}+.kg-fr-msg--theirs { align-self: flex-start; }+.kg-fr-msg--mine {+ align-self: flex-end;+ background: var(--kg-raise2, rgba(255, 255, 255, 0.09));+ border-color: var(--kg-line, rgba(255, 255, 255, 0.12));+}+@keyframes kg-fr-msg-in { from { opacity: 0; transform: translateY(5px); } }+.kg-fr-msg-body { font-size: 13px; color: var(--kg-text, #e8edf6); word-break: break-word; }+.kg-fr-msg-time { flex: none; font-size: 10px; color: var(--kg-dim, #95a1b6); font-variant-numeric: tabular-nums; }++/* composer */+.kg-fr-dm-bar {+ flex: none;+ display: flex;+ gap: 7px;+ padding: 7px 8px;+ background: rgba(0, 0, 0, 0.25);+ border: 1px solid var(--kg-line, rgba(255, 255, 255, 0.12));+ border-radius: var(--kg-radius, 4px);+ transition: border-color 0.15s ease;+}+.kg-fr-dm-bar:focus-within { border-color: var(--kg-accent, #cdd6e6); }+.kg-fr-dm-input {+ flex: 1;+ min-width: 0;+ font: inherit;+ font-size: 13px;+ color: var(--kg-text, #e8edf6);+ background: transparent;+ border: none;+ outline: none;+}+.kg-fr-dm-input::placeholder { color: var(--kg-dim, #95a1b6); }+.kg-fr-dm-send {+ flex: none;+ width: 34px;+ height: 30px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ font-size: 13px;+ line-height: 1;+ color: var(--kg-ink, #0b0d12);+ background: var(--kg-text, #e8edf6);+ border: 1px solid var(--kg-text, #e8edf6);+ border-radius: var(--kg-radius, 4px);+ cursor: pointer;+ transition: filter 0.12s ease, transform 0.1s ease;+}+.kg-fr-dm-send:hover { filter: brightness(0.9); }+.kg-fr-dm-send:active { transform: scale(0.95); }+.kg-fr-dm-send:focus-visible { outline: 2px solid var(--kg-accent, #cdd6e6); outline-offset: 2px; }++@media (prefers-reduced-motion: reduce) {+ .wf-friends-card, .kg-fr-msg { transition: none; animation: none; }+ .kg-fr-skel-row { animation: none; background: var(--kg-raise, rgba(255, 255, 255, 0.04)); }}/* ── Friends button in walk HUD ── */diff --git a/src/game/a11y.js b/src/game/a11y.jsnew file mode 100644index 000000000..f2bda6c6c--- /dev/null+++ b/src/game/a11y.js@@ -0,0 +1,214 @@+// Accessibility primitives shared by every /play surface.+//+// 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+// 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+// open a panel and then be stranded outside it with no way back.+//+// This module owns that contract once:+//+// openModal(card, { close }) focus moves in, Tab cycles inside, Escape and+// the overlay stack close the TOP panel only,+// and focus returns to whatever opened it.+// announce(text) one polite live region for transient world+// events (balance changes, incoming chat,+// connection state) that have no visible+// text node a screen reader would land on.+//+// Everything degrades safely: a missing/detached element is a no-op, and every+// registration hands back an idempotent release function.++const FOCUSABLE = [+ 'a[href]',+ 'button:not([disabled])',+ 'input:not([disabled]):not([type="hidden"])',+ 'select:not([disabled])',+ 'textarea:not([disabled])',+ '[tabindex]:not([tabindex="-1"])',+ '[role="button"]:not([aria-disabled="true"])',+].join(',');++function visible(el) {+ if (!el || el.hidden) return false;+ const r = el.getBoundingClientRect();+ if (!r.width && !r.height) return false;+ const s = getComputedStyle(el);+ return s.visibility !== 'hidden' && s.display !== 'none';+}++/** Every keyboard-reachable control inside `root`, in DOM order. */+export function focusableIn(root) {+ if (!root?.querySelectorAll) return [];+ return [...root.querySelectorAll(FOCUSABLE)].filter(visible);+}++// ── overlay stack ───────────────────────────────────────────────────────────+// Escape closes the TOP overlay, never all of them: the shop opened from the+// wardrobe has to hand control back to the wardrobe, not dump the player onto+// the bare world.++const stack = [];+let escBound = false;++function onEscape(e) {+ if (e.key !== 'Escape' || !stack.length) return;+ const top = stack[stack.length - 1];+ e.preventDefault();+ e.stopPropagation();+ try { top.close(); } catch { /* a panel that already tore itself down */ }+}++function bindEscape() {+ if (escBound || typeof document === 'undefined') return;+ // Capture phase so the world's movement/hotkey handler on `window` never+ // sees the Escape that belongs to an open panel.+ document.addEventListener('keydown', onEscape, true);+ escBound = true;+}++/**+ * Put a panel on the Escape stack. Returns a release function; calling it more+ * than once is safe.+ * @param {HTMLElement} el+ * @param {() => void} close+ */+export function registerOverlay(el, close) {+ if (typeof close !== 'function') return () => {};+ bindEscape();+ const entry = { el, close };+ stack.push(entry);+ return () => {+ const i = stack.indexOf(entry);+ if (i >= 0) stack.splice(i, 1);+ };+}++/** Is any panel currently claiming Escape? Used by the world hotkey handler. */+export function hasOpenOverlay() {+ return stack.length > 0;+}++// ── focus trap ──────────────────────────────────────────────────────────────++/**+ * Keep Tab inside `root` while it is open, move focus in on mount, and restore+ * it to the previously focused element on release.+ * @param {HTMLElement} root+ * @param {{ initialFocus?: HTMLElement }} [opts]+ * @returns {() => void} release+ */+export function trapFocus(root, { initialFocus } = {}) {+ if (!root) return () => {};+ const previous = document.activeElement;++ const onKey = (e) => {+ if (e.key !== 'Tab') return;+ const items = focusableIn(root);+ if (!items.length) {+ // Nothing focusable yet (a panel still loading its first snapshot):+ // hold focus on the card rather than letting Tab escape to the page.+ e.preventDefault();+ root.focus?.();+ return;+ }+ const first = items[0];+ const last = items[items.length - 1];+ const active = document.activeElement;+ if (e.shiftKey && (active === first || !root.contains(active))) {+ e.preventDefault();+ last.focus();+ } else if (!e.shiftKey && (active === last || !root.contains(active))) {+ e.preventDefault();+ first.focus();+ }+ };+ root.addEventListener('keydown', onKey);++ // The card itself must be focusable so focus has somewhere to land before+ // the panel's async content arrives; -1 keeps it out of the Tab order.+ if (!root.hasAttribute('tabindex')) root.setAttribute('tabindex', '-1');+ const target = initialFocus || focusableIn(root)[0] || root;+ // Defer one frame: panels focus-trap in their constructor, before the card+ // has been laid out, and focusing a zero-size element is a silent no-op.+ requestAnimationFrame(() => {+ if (root.isConnected) try { target.focus({ preventScroll: true }); } catch { /* detached */ }+ });++ let released = false;+ return () => {+ if (released) return;+ released = true;+ root.removeEventListener('keydown', onKey);+ // 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) {+ try { previous?.focus?.({ preventScroll: true }); } catch { /* gone */ }+ }+ };+}++/**+ * The full modal contract: Escape stack + focus trap + focus restore.+ * @param {HTMLElement} card the dialog element (the thing with role="dialog")+ * @param {{ close: () => void, initialFocus?: HTMLElement }} opts+ * @returns {() => void} release, safe to call from the panel's own close()+ */+export function openModal(card, { close, initialFocus } = {}) {+ const unstack = registerOverlay(card, close);+ const untrap = trapFocus(card, { initialFocus });+ let released = false;+ return () => {+ if (released) return;+ released = true;+ unstack();+ untrap();+ };+}++// ── live announcer ──────────────────────────────────────────────────────────+// A single pair of visually-hidden regions, created lazily. Screen readers only+// announce a live region when its text CHANGES, so repeated identical messages+// get a zero-width marker appended to force a re-read.++let politeEl = null;+let assertiveEl = null;+let flip = false;++function ensureRegions() {+ if (politeEl || typeof document === 'undefined' || !document.body) return;+ const style = document.createElement('style');+ style.textContent =+ '.cc-sr-live{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;' ++ 'clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0}';+ document.head.appendChild(style);+ const make = (live) => {+ const n = document.createElement('div');+ n.className = 'cc-sr-live';+ n.setAttribute('aria-live', live);+ n.setAttribute('aria-atomic', 'true');+ n.setAttribute('role', live === 'assertive' ? 'alert' : 'status');+ document.body.appendChild(n);+ return n;+ };+ politeEl = make('polite');+ assertiveEl = make('assertive');+}++/**+ * Announce a transient world event to screen readers.+ * @param {string} text+ * @param {{ assertive?: boolean }} [opts] assertive interrupts; reserve it for+ * things the player must act on (kicked from the room, gate refusal).+ */+export function announce(text, { assertive = false } = {}) {+ const msg = String(text || '').trim();+ if (!msg) return;+ ensureRegions();+ const node = assertive ? assertiveEl : politeEl;+ if (!node) return;+ flip = !flip;+ node.textContent = flip ? msg : msg + '';+}diff --git a/src/game/boutique-purchase.js b/src/game/boutique-purchase.jsindex f6603bff6..060887136 100644--- a/src/game/boutique-purchase.js+++ b/src/game/boutique-purchase.js@@ -39,8 +39,10 @@ function friendlyBoutiqueError(err) {const raw = (err && (err.message || String(err))) || '';const m = raw.toLowerCase();if (/reject|denied|cancell?ed|user declined/.test(m)) return 'Cancelled in wallet.';+ // End the message on somewhere to go: a player who is short on $THREE can act+ // on this, and /three-token is the platform's own one-click buy for it.if (/insufficient (lamports|funds)|debit an account|custom program error: 0x1\b/.test(m))- return 'Not enough $THREE (or SOL for network fees) to cover this purchase.';+ return 'Not enough $THREE (or SOL for network fees) for this purchase. Get $THREE at three.ws/three-token, then try again.';if (/blockhash not found|block height exceeded|expired|too old/.test(m))return 'The quote expired — try again.';if (/failed to fetch|networkerror|timed out|timeout|fetch failed/.test(m))@@ -48,22 +50,45 @@ function friendlyBoutiqueError(err) {return raw.replace(/\s+/g, ' ').trim().slice(0, 140) || 'Purchase failed. Try again.';}-// Wait for the server's reply to a specific boutiqueQuote request. Times out-// so a dropped connection can't hang the buy action forever.+// Did a 'boutique' notice report success? Modern servers stamp every notice+// with an explicit `ok` boolean; older deployed servers omit it, so fall back+// to the only success texts those servers ever send ("Unlocked …" and+// "Payment verified" grants). "Payment verified, but that item couldn't be+// unlocked" is the one failure sharing that prefix, so it's excluded.+function boutiqueNoticeOk(n) {+ if (n?.ok === true) return true;+ if (n?.ok === false) return false;+ const text = String(n?.text || '');+ if (/couldn.t be unlocked/i.test(text)) return false;+ return text.startsWith('Unlocked') || text.startsWith('Payment verified');+}++// Wait for the server's reply to a specific boutiqueQuote request. A quote-time+// rejection ("not in the boutique", "already own that", "boutique offline")+// arrives as a 'boutique' notice, never a boutiqueQuote reply, so it's raced+// here to surface the real reason instead of stalling into the timeout. Times+// out so a dropped connection can't hang the buy action forever.function waitForQuote(net, id, timeoutMs = 15000) {return new Promise((resolve, reject) => {- const timer = setTimeout(() => { unsub(); reject(new Error('Timed out waiting for a price. Try again.')); }, timeoutMs);- const unsub = net.on('boutiqueQuote', (msg) => {+ const cleanup = () => { clearTimeout(timer); offQuote(); offNotice(); };+ const timer = setTimeout(() => { cleanup(); reject(new Error('Timed out waiting for a price. Try again.')); }, timeoutMs);+ const offQuote = net.on('boutiqueQuote', (msg) => {if (msg?.id !== id) return;- clearTimeout(timer);- unsub();+ cleanup();resolve(msg);});+ const offNotice = net.on('notice', (n) => {+ if (n?.kind !== 'boutique' || boutiqueNoticeOk(n)) return;+ cleanup();+ reject(new Error(n.text || 'Could not price that purchase. Try again.'));+ });});}-// Wait for the settle-outcome notice (success or a specific server-side-// rejection) so the caller reports exactly what happened rather than guessing.+// Wait for the settle-outcome notice. A success resolves; a server-side+// rejection ("Payment didn't verify", "already settled", …) rejects with the+// server's own reason so the caller reports the failure honestly instead of+// painting a rejection green.function waitForSettleNotice(net, timeoutMs = 20000) {return new Promise((resolve, reject) => {const timer = setTimeout(() => { unsub(); reject(new Error('Timed out confirming the purchase. Check your wardrobe in a moment.')); }, timeoutMs);@@ -71,7 +96,8 @@ function waitForSettleNotice(net, timeoutMs = 20000) {if (n?.kind !== 'boutique') return;clearTimeout(timer);unsub();- resolve(n);+ if (boutiqueNoticeOk(n)) resolve(n);+ else reject(new Error(n.text || 'The purchase did not settle.'));});});}@@ -122,10 +148,14 @@ export async function buyBoutiqueItem({ net, item, onStage = () => {} }) {} catch (err) {throw new Error(friendlyBoutiqueError(err));}+ let confirmation = null;try {const latest = await conn.getLatestBlockhash('confirmed');- await conn.confirmTransaction({ signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, 'confirmed');- } catch { /* landed but slow to confirm — settle re-checks the confirmed tx on RPC itself */ }+ confirmation = await conn.confirmTransaction({ signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, 'confirmed');+ } catch { /* landed but slow to confirm; settle re-checks the confirmed tx on RPC itself */ }+ // A confirmed-but-reverted transaction can never settle; fail fast with the+ // truth instead of sending the server a signature it will only reject.+ if (confirmation?.value?.err) throw new Error('Transaction failed on-chain.');onStage('settling');net.boutiqueSettle(quote.quoteToken, sig);diff --git a/src/game/coin-buy.js b/src/game/coin-buy.jsindex 4fe0d6c98..ac1f14acf 100644--- a/src/game/coin-buy.js+++ b/src/game/coin-buy.js@@ -976,13 +976,27 @@ class TradeModal {}async _confirmOnChain(conn, sig) {- const latest = await conn.getLatestBlockhash('confirmed');+ let res = null;try {- await conn.confirmTransaction({ signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, 'confirmed');- } catch { /* landed but slow to confirm — the explorer link is the source of truth */ }+ const latest = await conn.getLatestBlockhash('confirmed');+ res = await conn.confirmTransaction({ signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, 'confirmed');+ } catch { /* landed but slow to confirm; the explorer link is the source of truth */ }+ // A reverted swap must never render as "Bought ✓": surface the on-chain+ // failure so the caller shows the truth (with the Solscan receipt).+ if (res?.value?.err) throw Object.assign(new Error('Transaction failed on-chain.'), { onChainFailure: true, sig });}_handleTradeError(err, mode, retry) {+ // The transaction reached the chain and reverted: no tokens moved, but the+ // signature exists, so link the receipt instead of a bare failure string.+ if (err?.onChainFailure && err.sig) {+ const url = solanaTxExplorerUrl(NETWORK, err.sig);+ this._setStatusNode(el('span', {}, [+ `The ${mode} failed on-chain (reverted); no tokens moved. `,+ el('a', { href: url, target: '_blank', rel: 'noopener', text: 'View on Solscan ↗' }),+ ]), 'err');+ return;+ }if (err?.status === 401) {this._setStatusNode(el('span', {}, ['Sign in to three.ws to trade. ',diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.jsindex 78a0a8a74..91388ad83 100644--- a/src/game/coincommunities-ui.js+++ b/src/game/coincommunities-ui.js@@ -18,6 +18,8 @@ import { PROP_CATALOG, GALLERY_PROP_PREFIX, registerGalleryProp } from './world-import { makeIntroReopener } from './play-intro.js';import { getPowerSaver, setPowerSaver, onPowerSaverChange } from '../shared/frame-governor.js';import { getMe } from '../account.js';+import { threeMarkSvg } from '../shared/brand-mark.js';+import { proxiedImageURL } from '../ipfs.js';import { log } from '../shared/log.js';// localStorage throws in private mode and in third-party iframe contexts where@@ -258,7 +260,7 @@ export class CommunityUI {el('div', { class: 'cc-lobby-inner' }, [el('div', { class: 'cc-lobby-head' }, [el('div', { class: 'cc-brand' }, [- el('a', { class: 'cc-brand-logo', href: '/', 'aria-label': 'three.ws home', title: 'three.ws', html: '<svg viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M11.013 1.011a16 16 0 0 0-3.96 1.39C2.79 4.531.213 8.757.012 13.564c-.16 3.933 1.31 7.62 4.117 10.357l.736.715-.16.46c-.084.249-.13.504-.138.761 0 1.358 1.448 2.218 2.638 1.567.535-.292.879-.748 1.043-1.384.084-.331.092-.462.07-.882-.02-.43-.04-.535-.18-.83-.246-.52-.567-.86-1.087-1.153l-.297-.167.106-.32c.18-.543.79-1.717 1.181-2.276 1.91-2.729 5.066-4.395 8.4-4.434l.43-.005.012-1.19c.006-.654.024-1.19.04-1.19s.252.197.526.438c.71.624 2.296 1.95 2.785 2.328.23.178.41.34.4.36-.01.02-.214.156-.453.303-.926.57-2.265 1.65-3.13 2.524l-.27.273.012 1.064.013 1.064.32.027c1.327.114 2.598.685 3.578 1.607.21.198.39.343.4.323.04-.073.276-1.327.346-1.84.296-2.169-.094-4.317-1.129-6.16l-.19-.34.246-.45c.811-1.485 1.291-3.063 1.456-4.776.04-.42.046-.488.111-.488.111 0 1.327.715 1.94 1.143 2.953 2.057 4.96 5.241 5.579 8.856.21 1.22.234 1.585.234 3.063 0 1.485-.024 1.844-.234 3.064-.811 4.736-4.06 8.732-8.51 10.474-1.04.407-2.504.78-3.578.91l-.32.04v2.395l.41-.046c2.014-.226 4.222-.93 5.98-1.91 4.84-2.688 8.058-7.464 8.696-12.897.105-.892.105-3.063 0-3.956-.638-5.433-3.856-10.21-8.697-12.898C24.083.99 21.875.285 19.86.06 19.322 0 19.27 0 15.752.006c-3.346.006-4.234.02-4.74.105Z"/></svg>' }),+ el('a', { class: 'cc-brand-logo', href: '/', 'aria-label': 'three.ws home', title: 'three.ws', html: threeMarkSvg() }),el('div', {}, [el('div', { class: 'cc-brand-title', text: 'Coin Communities' }),el('div', { class: 'cc-brand-sub', text: 'Every coin is a 3D world. Drop in and hang out.' }),@@ -309,7 +311,7 @@ export class CommunityUI {// (Build / Discover / Embed / Learn / Labs) so links and ordering stay// consistent across the site; styled with the lobby's own dark tokens._buildSiteNav() {- const THREE_MARK = '<svg viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M11.013 1.011a16 16 0 0 0-3.96 1.39C2.79 4.531.213 8.757.012 13.564c-.16 3.933 1.31 7.62 4.117 10.357l.736.715-.16.46c-.084.249-.13.504-.138.761 0 1.358 1.448 2.218 2.638 1.567.535-.292.879-.748 1.043-1.384.084-.331.092-.462.07-.882-.02-.43-.04-.535-.18-.83-.246-.52-.567-.86-1.087-1.153l-.297-.167.106-.32c.18-.543.79-1.717 1.181-2.276 1.91-2.729 5.066-4.395 8.4-4.434l.43-.005.012-1.19c.006-.654.024-1.19.04-1.19s.252.197.526.438c.71.624 2.296 1.95 2.785 2.328.23.178.41.34.4.36-.01.02-.214.156-.453.303-.926.57-2.265 1.65-3.13 2.524l-.27.273.012 1.064.013 1.064.32.027c1.327.114 2.598.685 3.578 1.607.21.198.39.343.4.323.04-.073.276-1.327.346-1.84.296-2.169-.094-4.317-1.129-6.16l-.19-.34.246-.45c.811-1.485 1.291-3.063 1.456-4.776.04-.42.046-.488.111-.488.111 0 1.327.715 1.94 1.143 2.953 2.057 4.96 5.241 5.579 8.856.21 1.22.234 1.585.234 3.063 0 1.485-.024 1.844-.234 3.064-.811 4.736-4.06 8.732-8.51 10.474-1.04.407-2.504.78-3.578.91l-.32.04v2.395l.41-.046c2.014-.226 4.222-.93 5.98-1.91 4.84-2.688 8.058-7.464 8.696-12.897.105-.892.105-3.063 0-3.956-.638-5.433-3.856-10.21-8.697-12.898C24.083.99 21.875.285 19.86.06 19.322 0 19.27 0 15.752.006c-3.346.006-4.234.02-4.74.105Z"/></svg>';+ const THREE_MARK = threeMarkSvg();// [href, title, description, badge?] per menu item.const GROUPS = [@@ -732,7 +734,7 @@ export class CommunityUI {}, [a.thumbnail_url? el('img', {- src: a.thumbnail_url, alt: a.name || 'Avatar', loading: 'lazy',+ src: proxiedImageURL(a.thumbnail_url, a.id || ''), alt: a.name || 'Avatar', loading: 'lazy',// A stale thumbnail (e.g. a legacy OG key that 404s before the// avatar self-heals) shouldn't leave a broken-image icon: drop it// and let _renderChipPreview's live model render stand in. Removing@@ -768,9 +770,14 @@ export class CommunityUI {// Start with the best instantly-available fallback (API thumbnail, else// emoji) so the chip is never empty, then render the real model and swap// it in. The chip carries a loading shimmer until a preview resolves.+ // Avatar art lives on third-party and R2 buckets that answer browser+ // requests with no CORS header, so Chrome's Opaque Response Blocking kills+ // the tile and logs ERR_BLOCKED_BY_ORB. Same-origin through /api/img, which+ // always answers with a valid image, the art actually shows and the console+ // stays clean. Same reason every other art surface on the platform proxies.const fallback = p.thumb? el('img', {- src: p.thumb, alt: p.label, loading: 'lazy',+ src: proxiedImageURL(p.thumb, p.url || ''), alt: p.label, loading: 'lazy',// Broken thumb: drop it and render the real model instead, so the// chip is never left empty (on mobile a live thumbnail is what lets// us skip that render in the first place).@@ -1458,6 +1465,23 @@ export class CommunityUI {]);onPowerSaverChange((on) => this.powerBtn.setAttribute('aria-pressed', on ? 'true' : 'false'));+ // Photo mode — capture the world (never the chrome) onto a share card.+ // Survives zen mode by design (see the zen block in coincommunities.css):+ // a clean world is exactly when someone wants the shot. The host loads+ // src/game/photo-mode.js on the first press, so nothing here costs a+ // player who never uses it.+ this.photoBtn = el('button', {+ id: 'cc-photo-btn', class: 'cc-photo-hud-btn', type: 'button', 'aria-pressed': 'false',+ 'aria-label': 'Take a photo', title: 'Photo mode: capture this world as a share card (P)',+ onclick: () => this.h.onPhoto?.(),+ }, [+ el('span', { class: 'cc-photo-hud-ico', 'aria-hidden': 'true', html:+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">'+ + '<path d="M3 8.2h3.4L8.1 5.4h7.8l1.7 2.8H21v10.4H3z"/><circle cx="12" cy="13.2" r="3.4"/>'+ + '</svg>' }),+ el('span', { class: 'cc-photo-hud-label', text: 'Photo' }),+ ]);+// Zen mode: hide every overlay so the world renders clean. Same// body.is-zen contract as /walk; Z is the hotkey (wired by the host) and// the floating exit pill below is the only control left on screen.@@ -1494,13 +1518,13 @@ export class CommunityUI {]);const hint = el('div', { id: 'cc-hint', html:- '<kbd>W A S D</kbd> / drag-joystick to move · <kbd>drag</kbd> to look · scroll zoom · <kbd>Enter</kbd> chat · <kbd>Q</kbd> emotes · <kbd>I</kbd> inspect · <kbd>Z</kbd> zen' });+ '<kbd>W A S D</kbd> / drag-joystick to move · <kbd>drag</kbd> to look · scroll zoom · <kbd>Enter</kbd> chat · <kbd>Q</kbd> emotes · <kbd>I</kbd> inspect · <kbd>P</kbd> photo · <kbd>Z</kbd> zen' });this.joystick = el('div', { id: 'cc-joystick' });this._buildTagHud();this._buildKingHud();- this.hud = el('div', { id: 'cc-hud', hidden: true }, [banner, leave, this.statusPill, this.voiceBtn, this.powerBtn, this.zenBtn, this.danceBtn, chat, this.emoteTray, this.reactionBar, hint, this.joystick]);+ this.hud = el('div', { id: 'cc-hud', hidden: true }, [banner, leave, this.statusPill, this.voiceBtn, this.powerBtn, this.zenBtn, this.photoBtn, this.danceBtn, chat, this.emoteTray, this.reactionBar, hint, this.joystick]);document.body.appendChild(this.hud);}@@ -1940,7 +1964,7 @@ export class CommunityUI {// show a real thumbnail (falling back to the glyph when a model has no render yet)._propButton(p) {const ico = p.thumbnail- ? el('img', { class: 'cc-prop-thumb', src: p.thumbnail, alt: '', loading: 'lazy', decoding: 'async' })+ ? el('img', { class: 'cc-prop-thumb', src: proxiedImageURL(p.thumbnail, p.id || ''), alt: '', loading: 'lazy', decoding: 'async' }): el('span', { class: 'cc-prop-ico', 'aria-hidden': 'true', text: p.icon || '◆' });const btn = el('button', {class: 'cc-prop', type: 'button',@@ -2263,7 +2287,7 @@ export class CommunityUI {.filter(Boolean).join(' · ');return el('a', { class: 'cc-fb-item', href, title: 'Enter this world' }, [el('div', { class: 'cc-fb-thumb' }, [- b.thumb ? el('img', { src: b.thumb, alt: b.title || 'Featured build', loading: 'lazy' })+ b.thumb ? el('img', { src: proxiedImageURL(b.thumb, b.id || b.coinMint || ''), alt: b.title || 'Featured build', loading: 'lazy' }): el('div', { class: 'cc-fb-thumb-empty', 'aria-hidden': 'true', text: '🧱' }),]),el('div', { class: 'cc-fb-meta' }, [@@ -2310,6 +2334,12 @@ export class CommunityUI {this.zenBtn?.setAttribute('aria-pressed', on ? 'true' : 'false');}+ // Light the camera button while the photo preview is up, so the HUD says+ // where that card came from and pressing P again reads as a retake.+ setPhotoActive(on) {+ this.photoBtn?.setAttribute('aria-pressed', on ? 'true' : 'false');+ }+// Toggle the button's armed state (lit = will dance on next beat).setDancing(on) {if (!this.danceBtn) return;diff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssindex 4aa1c580d..c0e45b078 100644--- a/src/game/coincommunities.css+++ b/src/game/coincommunities.css@@ -26,6 +26,17 @@--cc-glow: 0 0 14px rgba(255, 255, 255, 0.35);--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+ 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+ system edge gesture, so the movement stick and the chat input read as+ half-dead. Anchor bottom-docked controls with these instead of bare px.+ They resolve to 0px on hardware without insets, so desktop is unchanged. */+ --cc-safe-b: env(safe-area-inset-bottom, 0px);+ --cc-safe-l: env(safe-area-inset-left, 0px);+ --cc-safe-r: env(safe-area-inset-right, 0px);}* { box-sizing: border-box; }html, body {@@ -672,11 +683,13 @@ html[data-bg="transparent"] #cc-lobby {background: linear-gradient(115deg, rgba(255, 255, 255, 0.06), transparent 38%);}.cc-card-featured .cc-card-img { aspect-ratio: auto; flex: 0 0 38%; min-height: 168px; }-.cc-card-featured .cc-card-img::after { background: linear-gradient(90deg, transparent 55%, rgba(6, 6, 7, 0.92)); }+/* Ends fully opaque at the panel's composited color: a translucent last stop+ left a hard vertical seam where the artwork stopped and the body began. */+.cc-card-featured .cc-card-img::after { background: linear-gradient(90deg, transparent 45%, rgba(11, 11, 12, 0.72) 80%, #0b0b0c 100%); }.cc-card-featured .cc-card-body { flex: 1; justify-content: center; padding: 20px 22px; gap: 6px; }.cc-card-featured .cc-card-name { font-size: 22px; white-space: normal; }.cc-card-featured .cc-card-meta { font-size: 13px; }-.cc-card-featured .cc-card-cta { opacity: 1; transform: none; align-self: flex-start; padding: 10px 22px; margin-top: 16px; }+.cc-card-featured .cc-card-cta { background: #fff; border-color: #fff; color: var(--cc-ink); align-self: flex-start; padding: 10px 22px; margin-top: 16px; }.cc-card-official {position: absolute; top: 9px; left: 9px; z-index: 1;display: inline-flex; align-items: center; gap: 6px;@@ -688,7 +701,7 @@ html[data-bg="transparent"] #cc-lobby {@media (max-width: 560px) {.cc-card-featured { flex-direction: column; }.cc-card-featured .cc-card-img { flex-basis: auto; aspect-ratio: 16/10; width: 100%; }- .cc-card-featured .cc-card-img::after { background: linear-gradient(180deg, transparent 45%, rgba(6, 6, 7, 0.92)); }+ .cc-card-featured .cc-card-img::after { background: linear-gradient(180deg, transparent 45%, rgba(11, 11, 12, 0.72) 82%, #0b0b0c 100%); }.cc-card-featured .cc-card-name { font-size: 19px; }}@@ -824,9 +837,39 @@ html[data-bg="transparent"] #cc-lobby {.cc-power-ico { line-height: 1; }.cc-power-label { line-height: 1; }+/* photo mode — bottom of the top-right stack (voice · eco · zen · photo).+ The preview sheet it opens is styled in src/game/photo-mode.css, which ships+ with the lazily-imported module; only the trigger lives here. */+.cc-photo-hud-btn {+ position: fixed; top: 228px; right: 14px; z-index: 22;+ display: inline-flex; align-items: center; gap: 8px;+ background: var(--cc-panel); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);+ padding: 8px 13px 8px 11px; color: var(--cc-dim); cursor: pointer;+ font-weight: 600; font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase;+ box-shadow: var(--cc-shadow); backdrop-filter: blur(10px);+ transition: border-color 0.12s ease, color 0.12s ease, background 0.12s ease, opacity 0.3s ease, top 0.3s ease;+}+.cc-photo-hud-btn:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); background: rgba(255, 255, 255, 0.05); }+.cc-photo-hud-btn:active { background: rgba(255, 255, 255, 0.12); }+.cc-photo-hud-btn:focus-visible { outline: none; border-color: var(--cc-edge-hi); box-shadow: 0 0 0 1px var(--cc-edge-hi); }+.cc-photo-hud-btn[aria-pressed="true"] { color: var(--cc-text); border-color: var(--cc-edge-hi); }+.cc-photo-hud-ico { display: inline-flex; }+.cc-photo-hud-ico svg { width: 16px; height: 16px; display: block; }+.cc-photo-hud-label { line-height: 1; }+/* Zen keeps the camera: a world with no chrome on it is exactly the shot people+ want, and the capture is an offscreen render, so this button is never in it.+ It slides up under the "Show UI" pill once the rest of the stack is gone. */+body.is-zen #cc-photo-btn { top: calc(env(safe-area-inset-top, 0px) + 58px); opacity: 0; }+body.is-zen.zen-revealed #cc-photo-btn { opacity: 0.85; }+body.is-zen #cc-photo-btn:hover, body.is-zen #cc-photo-btn:focus-visible { opacity: 1; }+@media (prefers-reduced-motion: reduce) {+ .cc-photo-hud-btn { transition: border-color 0.12s ease, color 0.12s ease, background 0.12s ease; }+}+/* chat sidebar — dockable, minimizable, persistent log */#cc-chat {- position: fixed; right: 14px; bottom: 14px; width: min(340px, 82vw);+ position: fixed; right: calc(14px + var(--cc-safe-r)); bottom: calc(14px + var(--cc-safe-b));+ width: min(340px, 82vw);max-height: min(60vh, 520px); z-index: 23;display: flex; flex-direction: column; overflow: hidden;background: var(--cc-panel); border: 1px solid var(--cc-edge);@@ -896,7 +939,7 @@ html[data-bg="transparent"] #cc-lobby {/* emote tray */#cc-emotes {- position: fixed; left: 50%; bottom: 16px; transform: translateX(-50%); z-index: 22;+ position: fixed; left: 50%; bottom: calc(16px + var(--cc-safe-b)); transform: translateX(-50%); z-index: 22;display: flex; gap: 6px; background: var(--cc-panel); border: 1px solid var(--cc-edge);border-radius: var(--cc-radius); padding: 7px; box-shadow: var(--cc-shadow); backdrop-filter: blur(10px);}@@ -911,7 +954,7 @@ html[data-bg="transparent"] #cc-lobby {/* reaction bar (R04) — sits just above the emote tray */#cc-reactions {- position: fixed; left: 50%; bottom: 82px; transform: translateX(-50%); z-index: 22;+ position: fixed; left: 50%; bottom: calc(82px + var(--cc-safe-b)); transform: translateX(-50%); z-index: 22;display: flex; gap: 4px; background: var(--cc-panel); border: 1px solid var(--cc-edge);border-radius: var(--cc-radius); padding: 5px 6px; box-shadow: var(--cc-shadow); backdrop-filter: blur(10px);}@@ -1018,7 +1061,8 @@ html[data-bg="transparent"] #cc-lobby {/* movement stick — bottom-left, always on (touch + mouse). Subtle on desktop,full strength on touch. Sits opposite the chat (bottom-right) so they never overlap. */#cc-joystick {- position: fixed; left: 22px; bottom: 90px; width: 120px; height: 120px; z-index: 30; touch-action: none;+ position: fixed; left: calc(22px + var(--cc-safe-l)); bottom: calc(90px + var(--cc-safe-b));+ width: 120px; height: 120px; z-index: 30; touch-action: none;opacity: 0.5; transition: opacity 0.2s ease;}#cc-joystick:hover { opacity: 1; }@@ -1040,7 +1084,12 @@ html[data-bg="transparent"] #cc-lobby {}#cc-joystick.cc-joy-active .cc-joy-thumb { transition: none; }-@media (max-width: 640px) {+/* 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+ "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) {#cc-hint { display: none; }.cc-coin-banner { max-width: 60vw; }@@ -1050,17 +1099,24 @@ html[data-bg="transparent"] #cc-lobby {tray on top of the chat input — making both the stick and typing dead. *//* Movement stick: bottom-left, on top of everything, in a clear zone. */- #cc-joystick { left: 16px; bottom: 20px; width: 104px; height: 104px; z-index: 30; opacity: 1; }+ #cc-joystick {+ left: calc(16px + var(--cc-safe-l)); bottom: calc(20px + var(--cc-safe-b));+ width: 104px; height: 104px; z-index: 30; opacity: 1;+ }/* Chat: docked bottom-right, narrower so its left edge clears the joystick.Above the emote tray so the input always receives taps. */- #cc-chat { left: auto; right: 10px; bottom: 10px; width: min(58vw, 280px); max-height: 42vh; z-index: 24; }+ #cc-chat {+ left: auto; right: calc(10px + var(--cc-safe-r)); bottom: calc(10px + var(--cc-safe-b));+ width: min(58vw, 280px); max-height: 42vh; z-index: 24;+ }/* Emotes: compact, horizontally scrollable, pinned bottom-right just above thecollapsed chat pill and clear of the joystick. The expanded chat (higher z)covers it — collapse chat to emote, which is the natural one-or-the-other. */#cc-emotes {- left: auto; right: 10px; bottom: 58px; transform: none; z-index: 23;+ left: auto; right: calc(10px + var(--cc-safe-r)); bottom: calc(58px + var(--cc-safe-b));+ transform: none; z-index: 23;max-width: calc(100vw - 150px); overflow-x: auto; -webkit-overflow-scrolling: touch;padding: 6px; scrollbar-width: none;}@@ -1069,7 +1125,8 @@ html[data-bg="transparent"] #cc-lobby {/* Reactions: row above emotes on mobile, same right-dock zone */#cc-reactions {- left: auto; right: 10px; bottom: 104px; transform: none; z-index: 22;+ left: auto; right: calc(10px + var(--cc-safe-r)); bottom: calc(104px + var(--cc-safe-b));+ transform: none; z-index: 22;max-width: calc(100vw - 150px); overflow-x: auto; -webkit-overflow-scrolling: touch;padding: 4px 5px; scrollbar-width: none;}@@ -1090,7 +1147,10 @@ html[data-bg="transparent"] #cc-lobby {.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; }-.cc-adventure-ico { font-size: 18px; line-height: 1; filter: grayscale(1); }+/* 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; }.cc-adventure small { font-weight: 500; font-size: 11px; color: var(--cc-dim); }@media (max-width: 640px) { .cc-adventure small { display: none; } }@@ -3167,7 +3227,7 @@ select.npc-svc-input { cursor: pointer; appearance: none; -webkit-appearance: nothe driving pedal cluster), and panels the player opens on purpose (buildpalettes, shops, boards, the emote wheel) still show. Same body.is-zencontract as /walk and the marketplace gallery. */-body.is-zen #cc-hud > :not(#cc-joystick),+body.is-zen #cc-hud > :not(#cc-joystick):not(#cc-photo-btn),body.is-zen .cc-nav-toggle,body.is-zen .cc-nav-drawer,body.is-zen #cc-tag-hud,diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex c0c537fa9..634367ae3 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -16,9 +16,10 @@ import {CylinderGeometry, PlaneGeometry,TextureLoader, DoubleSide,PointLight,- Raycaster, Vector2, WebGLRenderTarget,+ Raycaster, Vector2,} from 'three';+import { captureSceneCanvas } from './scene-capture.js';import { AnimationManager } from '../animation-manager.js';import { CommunityNet } from './community-net.js';import { CommunityUI } from './coincommunities-ui.js';@@ -52,7 +53,6 @@ import {MAX_WORLD_OBJECTS, MAX_OBJECTS_PER_PLAYER, OBJ_SCALE_MIN, OBJ_SCALE_MAX,buildClearRadius,} from '../../multiplayer/src/build-limits.js';-import { validatePropModel, uploadPropModel } from './avatar-upload.js';import { proxiedImageURL } from '../ipfs.js';import {loadManifest, getEmoteDefs, getAllEmoteDefs, resolveAvatarUrl, buildAvatar, releaseAvatar, playEmoteClip,@@ -80,9 +80,9 @@ import { isChatPanelOpen } from './npc/npc-chat.js';import { isServicePanelOpen } from './npc/npc-services.js';import { isAixbtPanelOpen } from './npc/npc-aixbt.js';import { isZauthPanelOpen } from './npc/npc-zauth.js';-import { VoiceChat, voiceSupported } from './voice-chat.js';import { requestHolderPass, signInWithX, ensureSolanaWallet, relinkSolanaWallet, getSession, getWorldGate, setWorldGate } from '../community/town-auth.js';import { ensurePlayAccess } from './play-gate.js';+import { hasOpenOverlay, announce } from './a11y.js';import { clearStoredPass, refreshPlayPass, loadStoredPass, storePass } from './play-auth.js';import { PlaySystems } from './play-systems.js';import { PlayActivities } from './play-activities.js';@@ -102,6 +102,20 @@ import { CombatSystem } from './combat-system.js';function lsGet(k) { try { return localStorage.getItem(k); } catch { return null; } }function lsSet(k, v) { try { localStorage.setItem(k, v); } catch { /* storage disabled */ } }+// Normalise one deep-link query parameter for display. A /play link is shared+// between strangers, so `coin`, `name` and `symbol` are arbitrary attacker text.+// They are only ever written with textContent (never innerHTML), so markup in+// them is inert; what still needs handling is shape. Line breaks and control+// characters would rewrap the HUD around a value the sender chose, and an+// unbounded length would push the coin banner off screen, so both are removed+// here and the result is cut to the same limit the room server enforces.+function clampParam(value, max) {+ return String(value ?? '')+ .replace(/[\u0000-\u001f\u007f\u200b-\u200f\u2028\u2029\u202a-\u202e]+/g, ' ')+ .trim()+ .slice(0, max);+}+// 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@@ -114,6 +128,19 @@ function isTypingTarget(t) {return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';}+// Enter and Space are the browser's activation gesture for whatever control has+// focus. Binding them globally to "open chat" and "jump" meant a keyboard-only+// player could Tab to Shop, Friends, or any emote button and press Enter — and+// the world would swallow it, so the button never fired and the HUD was+// reachable but not operable. Every other hotkey (WASD, E, Q, Z…) still runs+// while a control is focused, because movement has to keep working; only the+// two activation keys defer to the focused control.+const ACTIVATION_TARGET = 'button,a[href],select,summary,[role="button"],[role="tab"],[role="menuitem"],[role="switch"],[role="checkbox"],[role="option"]';+function isActivationTarget(t) {+ if (!t || t.nodeType !== 1) return false;+ return !!t.closest?.(ACTIVATION_TARGET);+}+// Reaction bar (R04): the 6 emoji available to all players.const REACTIONS = [{ emoji: '🎉', label: 'Celebrate' },@@ -526,7 +553,7 @@ export class CoinCommunities {this._initScene();this.ui = new CommunityUI({- onEnter: (coin, tier) => this.enter(coin, { tier }),+ onEnter: (coin, tier) => this.enter(coin, { tier }).catch((err) => this._onEnterFailed(err)),// Holder gate overlay → the scene's gate state machine resolves on each// action (sign in, link wallet, buy, recheck, cancel).onHolderAction: (action) => { const r = this._holderGateResolve; this._holderGateResolve = null; r?.(action); },@@ -541,7 +568,11 @@ export class CoinCommunities {// actually reaches peers (the server rejects bare ids / blob: URLs).onAvatarChange: (val) => {if (!this.net || val === GUEST_SENTINEL) return;- resolveAvatarUrl(val).then((u) => this.net?.setAvatar(u));+ resolveAvatarUrl(val)+ .then((u) => this.net?.setAvatar(u))+ // A pick that fails to resolve keeps the current avatar; peers never+ // saw the swap, so there is nothing to roll back.+ .catch((err) => log.warn('[coincommunities] avatar swap failed to resolve:', err?.message));},onRename: (name) => this._rename(name),onBuy: () => this._openBuy(),@@ -575,6 +606,8 @@ export class CoinCommunities {onPublishBuild: (meta) => this._publishBuild(meta),onDance: () => this._triggerDance(),// Zen mode: strip every overlay for a clean view of the world.+ // Photo mode: capture the world (never the chrome) onto a share card.+ onPhoto: () => this._openPhotoMode(),onZen: () => this._setZen(!this._zen),onFeaturedClosed: () => { this._featuredOpen = false; },});@@ -644,13 +677,43 @@ 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();- const mint = p.get('coin');+ // 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) {const tier = p.get('tier') === 'holders' ? 'holders' : 'general';- this.enter({ mint, name: p.get('name') || '', symbol: p.get('symbol') || '', image: proxiedImageURL(p.get('image') || '', mint) }, { tier });+ this.enter({+ mint,+ name: clampParam(p.get('name'), 48),+ symbol: clampParam(p.get('symbol'), 16),+ // proxiedImageURL drops anything that is not a renderable image+ // source (javascript:, data:text/html, an oversized URL), so a hostile+ // `image=` resolves to '' and the world takes its generated art path.+ image: proxiedImageURL(p.get('image') || '', mint),+ }, { tier })+ .catch((err) => this._onEnterFailed(err));}}+ // Both enter() call sites are fire-and-forget, so a throw mid-build would+ // otherwise wedge the phase at 'loading' behind a half-built world with no+ // feedback. Tear down whatever landed and hand back a working lobby.+ _onEnterFailed(err) {+ log.error('[coincommunities] enter() failed:', err);+ try {+ this.leave();+ } catch (e) {+ // leave() is defensive, but a teardown throw must not mask the lobby reset.+ log.warn('[coincommunities] teardown after failed enter():', e?.message);+ this.phase = 'lobby';+ this.ui?.showLobby?.();+ }+ this.ui?.toast?.('Could not open that world. Try again.', 'warn');+ }+// W01: boot the shared Rapier world once. A flat ground collider covers the// whole district (buildings are added per-coin in enter(), once the district// grid is built). Never throws — a WASM failure (unsupported browser, blocked@@ -1304,16 +1367,23 @@ export class CoinCommunities {addEventListener('online', this._onResume);addEventListener('focus', this._onResume);- if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));+ if (isGuest) {+ uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl))+ // Upload failed: peers keep the stand-in they already render; the local+ // avatar is untouched, so there is nothing to recover beyond the log.+ .catch((err) => log.warn('[coincommunities] guest avatar upload failed:', err?.message));+ }this.net.on('status', ({ status, error }) => {this.ui.setStatus(status, error);this._updateOnline();- // Reconnect exhausted: the player is now alone in a local-only world.- // The small status pill alone is easy to miss, so explain the drop once —- // other players, chat and shared building are off, and how to recover.- if (status === 'failed' && !this._failedNotified) {+ // Reconnect exhausted (the net goes terminally 'offline' WITH an error;+ // a plain room drop reports 'offline' without one and retries silently,+ // and each 'failed' attempt is just backoff): the player is now alone in+ // a local-only world. The small status pill alone is easy to miss, so+ // explain the drop once, and how to recover.+ if (status === 'offline' && error && !this._failedNotified) {this._failedNotified = true;- this.ui.toast('Lost the connection to the world — chat and shared builds are paused. Tap the status pill to reconnect.', 'warn');+ this.ui.toast('Lost the connection to the world: chat and shared builds are paused. Tap the status pill to reconnect.', 'warn');}// Retries exhausted: this is a single-player world now, so the peers// frozen mid-stride are a lie. Clear them rather than leave a crowd of@@ -1459,6 +1529,38 @@ export class CoinCommunities {});this.buildHud.root.hidden = false;+ // W02: drivable vehicles, the parked fleet the server seeds every world+ // with (multiplayer/src/vehicles.js VEHICLE_SPAWNS, mirrored from this+ // district's own avenue bays in world-zones.js). Constructed after the+ // physics boot above has resolved, so it can borrow this._physics straight+ // away instead of waiting on it itself, and BEFORE connect() below:+ // Colyseus replays each synced entity exactly once, from the first state+ // patch, and on a warm room that patch can land while the avatar GLB is+ // still downloading. A manager built after it would miss the whole fleet+ // for the session. Torn down in leave().+ this.vehicles = new VehicleManager({ host: this });+ // W07: roaming PvE mobs, lootable tombstones, the danger-zone ground, and+ // the GTA-style vitals HUD (health/armor/wanted). Constructed before the+ // join starts for the same first-patch reason as the vehicles above; it+ // also catches the join-time 'profile' send directly, and the re-request+ // after the join below stays as a backstop. Torn down in leave().+ // Defensive boundary: W07 is still under active concurrent development in+ // this shared worktree (CLAUDE.md "known traps"), and a bug in it must+ // never take down the rest of world entry (NPCs, vehicles, economy) for+ // every player. Fails closed to no combat HUD/mobs, not an unusable world.+ try {+ this.combat = new CombatSystem({+ scene: this.scene,+ camera: this.camera,+ renderer: this.renderer,+ getPlayer: () => ({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z, yaw: this.localYaw, height: this.localHeight || 1.6 }),+ net: this.net,+ ui: this.ui,+ });+ } catch (e) {+ log.error('[coincommunities] CombatSystem failed to init; continuing without it:', e?.message);+ this.combat = null;+ }// Join the room and finish the local avatar in parallel. These used to run// serialized (avatar, then connect), which held the whole world entry on// "connecting" for the length of the avatar download; neither depends on@@ -1490,33 +1592,6 @@ export class CoinCommunities {this._initJoystick();this._restoreZen();this._onboardBuild();- // W02: drivable vehicles — the parked fleet the server seeds every world- // with (multiplayer/src/vehicles.js VEHICLE_SPAWNS, mirrored from this- // district's own avenue bays in world-zones.js). Constructed after the- // physics boot above has resolved, so it can borrow this._physics straight- // away instead of waiting on it itself. Torn down in leave().- this.vehicles = new VehicleManager({ host: this });- // W07: roaming PvE mobs, lootable tombstones, the danger-zone ground, and- // the GTA-style vitals HUD (health/armor/wanted). Subscribed before the- // join settles, so it catches the join-time 'profile' send directly; the- // re-request after the join below stays as a backstop. Torn down in leave().- // Defensive boundary: W07 is still under active concurrent development in- // this shared worktree (CLAUDE.md "known traps") — a bug in it must never- // take down the rest of world entry (NPCs, vehicles, economy) for every- // player. Fails closed to no combat HUD/mobs rather than an unusable world.- try {- this.combat = new CombatSystem({- scene: this.scene,- camera: this.camera,- renderer: this.renderer,- getPlayer: () => ({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z, yaw: this.localYaw, height: this.localHeight || 1.6 }),- net: this.net,- ui: this.ui,- });- } catch (e) {- log.error('[coincommunities] CombatSystem failed to init — continuing without it:', e?.message);- this.combat = null;- }// The legacy gold purse HUD folds into WorldHud's unified money readout.this.playSystems?.setGoldVisible(false);// Every town hosts the live Agent Exchange: two NPC agents who pay each@@ -1550,6 +1625,10 @@ export class CoinCommunities {fetch(`/api/agents/public?sort=live&limit=3`).then((r) => r.ok ? r.json() : null).then((d) => {+ // The player may have left (or hopped coins) while the fetch was in+ // flight: desks (and their SSE monitors) added now would leak into+ // the lobby scene with nothing left to dispose them.+ if (epoch !== this._enterEpoch) return;const agents = d?.agents || d?.data || [];agents.slice(0, 3).forEach((a, i) => {const offsets = [[-14, 0, -10], [14, 0, -10], [0, 0, -14]];@@ -1784,8 +1863,12 @@ export class CoinCommunities {// 'recheck' (or any other) → loop and re-run the on-chain check.}} finally {- // Guarantee the overlay never lingers if we bailed via return.- if (this.phase === 'lobby') this.ui.closeHolderGate();+ // Guarantee the overlay (and its focus trap) never lingers if we bailed+ // via return or a throw. Unconditional on purpose: enter() holds the+ // phase at 'loading' while this gate runs, so a phase check here never+ // fires and a cancel used to strand the modal forever. closeHolderGate()+ // is idempotent, so the paths above that already closed it are unharmed.+ this.ui.closeHolderGate();}}@@ -1798,8 +1881,16 @@ export class CoinCommunities {// Stand up spatial voice for this community. Voice starts OFF (no mic access// until the player opts in); the mic button drives join/mute through here.- _initVoice() {+ //+ // The WebRTC engine is imported here rather than statically, so its peer+ // connection / spatial-panner code is off the first-paint path; nothing in+ // the world reads `this.voice` without optional chaining, and no peer can+ // signal us before we have joined, so arriving a few ms later is safe.+ async _initVoice() {if (this.voice) { this.voice.dispose(); this.voice = null; }+ const epoch = this._enterEpoch;+ const { VoiceChat, voiceSupported } = await import('./voice-chat.js');+ if (epoch !== this._enterEpoch || !this.net) return; // left the world mid-importif (!voiceSupported()) { this.ui.setVoiceState('unsupported'); return; }this.voice = new VoiceChat({selfId: this.net.sessionId,@@ -1936,15 +2027,24 @@ export class CoinCommunities {this.ui.closeFeatured();try { this.localCosmetics?.dispose(); } catch {}this.localCosmetics = null; this._localCosWire = null;- // Tag mini-game (R08): remove local glow ring + label on world exit.+ // Tag mini-game (R08): remove local glow ring + label and drop the HUD+ // (scoreboard + "you're it" alert) on world exit.this._removeLocalGlowRing();this._removeLocalItLabel();this._localIsIt = false;+ this.ui.hideTagHud();// King of the Totem (R07): tear down the zone + crown marker and hide the HUD.this._disposeKingZone();this.ui.hideKingHud();if (this.localRig) { releaseAvatar(this.localRig); this.scene.remove(this.localRig); this.localRig = null; }- if (this._nipple) { this._nipple.destroy(); this._nipple = null; }+ // A joystick vector held at the moment of exit must not drift the avatar+ // in the next world; it belongs to the joystick session leave() just ended.+ this._joy = null;+ // The one-shot disconnect explainer re-arms per world.+ this._failedNotified = false;+ // The lobby has no current world: clear the coin so _worldFacts() (the+ // avatar inspector's World row) stops naming the one we just left.+ this.coin = null;this.phase = 'lobby';try { history.replaceState(null, '', location.pathname); } catch { /* non-fatal */ }this.ui.showLobby();@@ -2080,11 +2180,37 @@ export class CoinCommunities {// ---------------------------------------------------------------- net events_onAdd(player, id) {if (id === this.net.sessionId) return; // that's us+ // A peer we already track (or one re-announced under the same id after a+ // resync) is live, not stale — clear any stale flag rather than doubling it.+ const existing = this.remotes.get(id);+ if (existing) { existing._stale = false; existing.apply?.(player); return; }const rp = new RemotePlayer(this.scene, player);rp.onInspect = () => this._inspectRemote(id, rp.label);this.remotes.set(id, rp);this._updateOnline();}++ // Flag every current peer as stale ahead of a reconnect. A reconnect is a fresh+ // joinOrCreate with new session ids, and the old room's listeners were removed+ // before it left, so `_onRemove` never fires for the peers we had — without+ // this they linger as frozen ghosts and inflate the online count. The fresh+ // room's `add` events clear the flag (above); whatever is still flagged when the+ // snapshot lands (`_pruneStaleRemotes`) genuinely left while we were offline.+ _markRemotesStale() {+ for (const [, rp] of this.remotes) rp._stale = true;+ }++ // Retire peers still flagged stale after a (re)sync: dispose their rig, drop the+ // label, close their voice channel, and correct the headcount.+ _pruneStaleRemotes() {+ for (const [id, rp] of [...this.remotes]) {+ if (!rp._stale) continue;+ rp.dispose();+ this.remotes.delete(id);+ this.voice?.removePeer(id);+ }+ this._updateOnline();+ }_onChange(player, id) {if (id === this.net.sessionId) {// Tag mini-game (R08): the local player isn't a RemotePlayer, so drive@@ -2578,8 +2704,12 @@ export class CoinCommunities {this._urlAvatar = '';if (!isGuest) setPlayAvatar(value);this.ui.reflectAvatar?.(value);- if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));- else this.net?.setAvatar(url);+ if (isGuest) {+ // Fire-and-forget like the world-entry upload: a failure keeps peers on+ // the stand-in they already render, so log it rather than reject unhandled.+ uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl))+ .catch((err) => log.warn('[coincommunities] guest avatar upload failed:', err?.message));+ } else this.net?.setAvatar(url);return { ok: true, downgraded: !!built.downgraded };}@@ -2605,8 +2735,16 @@ export class CoinCommunities {// one mission when a specific giver NPC opened the board.async _toggleQuests(highlight) {if (!this.net) return;- const { openQuestsPanel } = await import('./quests-ui.js');- openQuestsPanel({ ui: this.ui, net: this.net }, highlight);+ // Both callers (the HUD's Jobs button and quest-giver NPCs) fire this+ // without awaiting, so a failed chunk load (stale deploy, offline) must be+ // caught here or it dies as an unhandled rejection with a dead button.+ try {+ const { openQuestsPanel } = await import('./quests-ui.js');+ openQuestsPanel({ ui: this.ui, net: this.net }, highlight);+ } catch (err) {+ log.warn('[coincommunities] jobs board failed to load:', err?.message);+ this.ui.toast('Could not open the jobs board. Refresh the page and try again.', 'warn');+ }}// Equip `id` durably: send to the server (authoritative validation + persistence)@@ -3025,10 +3163,13 @@ export class CoinCommunities {// Esc closes the friends/avatar drawers before anything else claims the key.if (e.key === 'Escape' && this._friendsOpen) { e.preventDefault(); this._closeFriends(); return; }if (e.key === 'Escape' && this._avatarPanelOpen) { e.preventDefault(); this._closeAvatarPanel(); return; }- if (e.key === 'Enter' && this.phase === 'world') { e.preventDefault(); this.ui.focusChat(); return; }+ // Enter/Space belong to a focused button or link (see isActivationTarget)+ // — hijacking them there leaves the whole HUD un-operable by keyboard.+ const onControl = isActivationTarget(e.target);+ if (e.key === 'Enter' && this.phase === 'world' && !onControl) { e.preventDefault(); this.ui.focusChat(); return; }// Space jumps on foot; while driving it's the handbrake instead (held,// released in the keyup handler below) — never scrolls the page either way.- if (e.code === 'Space') {+ if (e.code === 'Space' && !onControl) {e.preventDefault();if (this.vehicles?.isDriving()) { this.vehicles.setHandbrake(true); return; }this._jump();@@ -3090,6 +3231,15 @@ export class CoinCommunities {this._inspectNearest();return;}+ // P photographs the world onto a share card. Deliberately live in+ // every mode — zen, building, driving — because the shot is an+ // offscreen render, so no panel is ever in the frame. Ctrl/Cmd+P+ // stays the browser's print dialog.+ if (k === 'p' && !e.repeat && !e.ctrlKey && !e.metaKey) {+ e.preventDefault();+ this._openPhotoMode();+ return;+ }// J toggles the friends drawer (W09). F — the /walk binding — is already// this world's contextual action key (drive / gather / cast), so /play// takes the next free slot; the HUD button carries the same hint.@@ -3415,6 +3565,9 @@ export class CoinCommunities {this._propUploading = true;this.ui.setPropUploadStatus('Checking your model…');try {+ // The validator pulls in its own GLTF/VRM parsing path; it is only+ // reachable from this file picker, so it loads with the picker's file.+ const { validatePropModel, uploadPropModel } = await import('./avatar-upload.js');const info = await validatePropModel(file);this.ui.setPropUploadStatus('Uploading… 0%');const url = await uploadPropModel(file, (p) => {@@ -4013,43 +4166,41 @@ export class CoinCommunities {// ---------------------------------------------------------------- share builds// Render the current view into an offscreen target and return a JPEG data URL +- // dimensions, or null if capture isn't possible. Uses a render target (not the- // live canvas) so it works regardless of preserveDrawingBuffer, and downscales- // to keep the thumbnail small enough to persist and share.+ // dimensions, or null if capture isn't possible. The offscreen render itself+ // lives in scene-capture.js, shared with photo mode, so the world has exactly+ // one answer to "how do you screenshot this"; the downscale here keeps the+ // thumbnail small enough to persist and share._captureBuildShot(maxW = 720) {- const r = this.renderer;- if (!r || !this.scene || !this.camera) return null;- const size = r.getSize(new Vector2());- if (size.x < 1 || size.y < 1) return null;- const scale = Math.min(1, maxW / size.x);- const w = Math.max(1, Math.round(size.x * scale));- const h = Math.max(1, Math.round(size.y * scale));- let rt = null;+ const shot = captureSceneCanvas(this.renderer, this.scene, this.camera, { maxWidth: maxW });+ if (!shot) return null;+ return { dataUrl: shot.canvas.toDataURL('image/jpeg', 0.72), width: shot.width, height: shot.height };+ }++ // ---------------------------------------------------------------- photo mode+ // Capture the world onto a share card the player can download or paste. The+ // whole feature (compositing, the preview sheet, its CSS) lives in+ // photo-mode.js and is imported on the FIRST press, so a session that never+ // takes a photo never downloads it and never pays a frame for it.+ async _openPhotoMode() {+ if (this.phase !== 'world' || this._photoLoading) return;+ this._photoLoading = true;try {- rt = new WebGLRenderTarget(w, h, { samples: 4 });- rt.texture.colorSpace = SRGBColorSpace;- const prev = r.getRenderTarget();- r.setRenderTarget(rt);- r.render(this.scene, this.camera);- const buf = new Uint8Array(w * h * 4);- r.readRenderTargetPixels(rt, 0, 0, w, h, buf);- r.setRenderTarget(prev);- const c = document.createElement('canvas');- c.width = w; c.height = h;- const ctx = c.getContext('2d');- const img = ctx.createImageData(w, h);- // WebGL's origin is bottom-left; flip rows so the image isn't upside down.- for (let y = 0; y < h; y++) {- const src = (h - 1 - y) * w * 4;- img.data.set(buf.subarray(src, src + w * 4), y * w * 4);- }- ctx.putImageData(img, 0, 0);- return { dataUrl: c.toDataURL('image/jpeg', 0.72), width: w, height: h };+ const { takePhoto } = await import('./photo-mode.js');+ const shown = await takePhoto({+ renderer: this.renderer,+ scene: this.scene,+ camera: this.camera,+ coinLabel: this.coin?.symbol ? '$' + this.coin.symbol : '',+ worldLabel: this.coin?.name || '',+ toast: (msg, kind) => this.ui.toast(msg, kind),+ onClose: () => this.ui.setPhotoActive(false),+ });+ this.ui.setPhotoActive(shown);} catch (err) {- log.warn('[coincommunities] build capture failed:', err?.message);- return null;+ log.warn('[coincommunities] photo mode failed to load:', err?.message);+ this.ui.toast('Photo mode couldn’t load — check your connection and try again.', 'warn');} finally {- rt?.dispose();+ this._photoLoading = false;}}diff --git a/src/game/community-net.js b/src/game/community-net.jsindex 060a0fd0a..8ee04db6e 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -151,8 +151,12 @@ export class CommunityNet {spinPrep: new Set(), // ({tx, tokenAmount, symbol, costUsd, quote}) — unsigned paid-spin tx to signspinResult: new Set(), // ({mode, index, label, got, lost, refunded, nextFreeSpinAt?}) — the server's rollspinDenied: 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+ quests: new Set(), // ({offers, active, day, eventLive}) — jobs board + active runs (W05)+ questComplete: new Set(), // ({id, title, reward, kind, coop, event}) — a mission/heist finished+ // Live event (public/event.json window): the ranked standing for the event+ // quest line, and this player's own running totals after each event job.+ eventBoard: new Set(), // ({ok, event?, top?, you?, players?, totalRuns?, prizes?, reason?})+ eventScore: new Set(), // ({runs, cash, eventId}) — your totals after an event jobcombat: new Set(), // ({role:'attacker'|'victim', target:'mob'|'player', kind?, mobHp?, mobMaxHp?, playerHp, playerMaxHp, dealt, dead, attacker?}) — a swing/shot's result// W07 combat world entities: roaming PvE mobs + lootable death tombstones.// add/change/remove mirror the vehicle callbacks below.@@ -369,6 +373,9 @@ export class CommunityNet {// Quests, jobs & heists (W05): the board + active runs and completion events.this.room.onMessage('quests', (msg) => this._emit('quests', msg || {}));this.room.onMessage('questComplete', (msg) => this._emit('questComplete', msg || {}));+ // Live event: the ranked leaderboard reply, and your own totals after a run.+ this.room.onMessage('eventBoard', (msg) => this._emit('eventBoard', msg || {}));+ this.room.onMessage('eventScore', (msg) => this._emit('eventScore', msg || {}));this.room.onMessage('combat', (msg) => this._emit('combat', msg || {}));// Vehicles: the server's targeted reply to our enter/exit request (grant,// drop point, or denial). World transforms arrive via the state callbacks.@@ -685,6 +692,11 @@ export class CommunityNet {questAccept(id) { this._send('questAccept', { id }); }questAbandon(id) { this._send('questAbandon', { id }); }questInteract() { this._send('questInteract'); }+ // The live event's leaderboard. The room proxies the same public read the web+ // uses (api/play/event-leaderboard) and pins this player's own row from their+ // verified account key, so the client never has to know or send an identity.+ // The reply arrives on the 'eventBoard' event.+ requestEventBoard() { this._send('eventBoardReq'); }// Vehicles. enter/exit take + release the wheel (server-gated by proximity +// occupancy, answered on the 'vehicle' event); vsync streams the driver's// authoritative Rapier transform, which the server validates and relays. vsyncdiff --git a/src/game/economy-ui.css b/src/game/economy-ui.cssindex 80947d40d..361cf8033 100644--- a/src/game/economy-ui.css+++ b/src/game/economy-ui.css@@ -76,8 +76,10 @@}.ec-row-glyph { font-size: 18px; width: 24px; text-align: center; flex: none; }.ec-row-main { flex: 1; min-width: 0; }-.ec-row-name { font-size: 13px; font-weight: 600; }-.ec-row-sub { font-size: 11px; color: var(--cc-dim); margin-top: 2px; }+/* Item labels come from the server's vocabulary, so a long or unbroken name has+ to fold inside the row instead of pushing the price and the button off it. */+.ec-row-name { font-size: 13px; font-weight: 600; overflow-wrap: anywhere; }+.ec-row-sub { font-size: 11px; color: var(--cc-dim); margin-top: 2px; overflow-wrap: anywhere; }.ec-row-btn {flex: none; padding: 7px 12px; font-size: 12px; font-weight: 700; letter-spacing: 0.02em;background: #fff; color: var(--cc-ink); border: none; border-radius: var(--cc-radius-sm); cursor: pointer;diff --git a/src/game/economy-ui.js b/src/game/economy-ui.jsindex 9d1a2c7a9..61b41a794 100644--- a/src/game/economy-ui.js+++ b/src/game/economy-ui.js@@ -9,6 +9,7 @@import './economy-ui.css';import { itemDisplay } from './items.js';+import { openModal, announce } from './a11y.js';function el(tag, props = {}, kids = []) {const n = document.createElement(tag);@@ -33,21 +34,26 @@ export class EconPanel {this._onClose = onClose;this.body = el('div', { class: 'ec-body' });this.status = el('div', { class: 'ec-status', role: 'status', 'aria-live': 'polite' });+ this.closeBtn = el('button', { class: 'ec-x', type: 'button', 'aria-label': 'Close', text: '✕', onclick: () => this.close() });this.card = el('div', { class: 'ec-card', role: 'dialog', 'aria-modal': 'true', 'aria-label': title }, [el('div', { class: 'ec-head' }, [el('span', { class: 'ec-title', text: title }),- el('button', { class: 'ec-x', type: 'button', 'aria-label': 'Close', text: '✕', onclick: () => this.close() }),+ this.closeBtn,]),this.body,this.status,]);this.overlay = el('div', { class: 'ec-overlay', onpointerdown: (e) => { if (e.target === this.overlay) this.close(); } }, [this.card]);- this.card.addEventListener('keydown', (e) => {- if (e.key === 'Escape') this.close();- e.stopPropagation();- });+ // Game hotkeys live on `window`; a keystroke aimed at this card must never+ // also drive the avatar behind it.+ this.card.addEventListener('keydown', (e) => e.stopPropagation());document.body.appendChild(this.overlay);requestAnimationFrame(() => this.overlay.classList.add('ec-on'));+ // `aria-modal` is a promise to keep focus inside; openModal is what makes+ // it true, and it also puts this panel on the shared Escape stack so the+ // top-most panel is the one Escape closes.+ this._releaseModal = openModal(this.card, { close: () => this.close(), initialFocus: this.closeBtn });+ announce(title);}track(unsub) { if (typeof unsub === 'function') this._unsubs.push(unsub); }@@ -57,6 +63,65 @@ export class EconPanel {this.status.setAttribute('data-kind', kind || '');}+ // --- first-snapshot loading state -----------------------------------------+ //+ // Every panel here opens before its data exists: the constructor fires a+ // request and the server answers over the socket a moment later. Rendering+ // the empty state in that gap tells the player "the shelves are bare" when+ // the truth is "we haven't looked yet", and if the reply never lands (the+ // socket dropped between the walk-up and the open) that lie is permanent.+ // So panels start in `loading`, settle on the first snapshot, and fall to an+ // honest, retryable error if nothing arrives.++ /** Begin waiting for the first server snapshot. `retry` re-sends the request. */+ awaitFirstSnapshot(retry, { timeoutMs = 9000 } = {}) {+ this.loading = true;+ this.loadFailed = false;+ this._retry = retry;+ clearTimeout(this._loadTimer);+ this._loadTimer = setTimeout(() => {+ if (!this.loading) return;+ this.loading = false;+ this.loadFailed = true;+ this._render?.();+ }, timeoutMs);+ }++ /** The first snapshot landed: leave the loading state for good. */+ settleFirstSnapshot() {+ if (!this.loading && !this.loadFailed) return;+ clearTimeout(this._loadTimer);+ this._loadTimer = null;+ this.loading = false;+ this.loadFailed = false;+ }++ /** Placeholder rows shaped like the real ones, so nothing jumps on arrival. */+ skeleton(rows = 3) {+ const wrap = el('div', { class: 'ec-skel' });+ for (let i = 0; i < rows; i++) {+ wrap.appendChild(el('div', { class: 'ec-skel-row' }, [+ el('span', { class: 'ec-skel-glyph' }),+ el('div', { class: 'ec-skel-main' }, [el('span', { class: 'ec-skel-line' }), el('span', { class: 'ec-skel-line ec-skel-line-sm' })]),+ el('span', { class: 'ec-skel-btn' }),+ ]));+ }+ return wrap;+ }++ /** The honest dead end: what went wrong, and the one button that fixes it. */+ loadError(what) {+ return el('div', { class: 'ec-empty ec-error' }, [+ el('div', { class: 'ec-error-glyph', 'aria-hidden': 'true', text: '📡' }),+ el('div', { class: 'ec-error-title', text: `Couldn't reach ${what}` }),+ el('div', { text: 'The world stopped answering. Nothing was lost.' }),+ el('button', {+ class: 'ec-row-btn ec-error-retry', type: 'button', text: 'Try again',+ onclick: () => { this.awaitFirstSnapshot(this._retry); this._retry?.(); this._render?.(); },+ }),+ ]);+ }+// --- one in-flight intent per panel ---------------------------------------//// Every trade is priced and applied by the server, which answers each intent@@ -102,6 +167,9 @@ export class EconPanel {}close() {+ if (this._closed) return;+ this._closed = true;+ this._releaseModal?.();this.overlay.classList.remove('ec-on');clearTimeout(this._pendingTimer);for (const u of this._unsubs) { try { u(); } catch { /* ignore */ } }@@ -137,18 +205,23 @@ class StorePanel extends EconPanel {this.catalog = { sell: [], buy: [] };this.profile = { gold: 0, inv: [] };- this.tabs = el('div', { class: 'ec-tabs' }, [- el('button', { class: 'ec-tab ec-on', type: 'button', text: 'Buy', onclick: () => this._setTab('buy') }),- el('button', { class: 'ec-tab', type: 'button', text: 'Sell', onclick: () => this._setTab('sell') }),+ this.tabs = el('div', { class: 'ec-tabs', role: 'tablist', 'aria-label': 'Store mode' }, [+ el('button', { class: 'ec-tab ec-on', type: 'button', role: 'tab', 'data-tab': 'buy', 'aria-selected': 'true', text: 'Buy', onclick: () => this._setTab('buy') }),+ el('button', { class: 'ec-tab', type: 'button', role: 'tab', 'data-tab': 'sell', 'aria-selected': 'false', text: 'Sell', onclick: () => this._setTab('sell') }),]);+ this.purseValue = el('b', { text: '0' });this.purse = el('div', { class: 'ec-purse' }, [el('span', { text: 'Cash on hand' }),- el('b', { text: '0' }),+ this.purseValue,]);this.card.insertBefore(this.purse, this.body);this.card.insertBefore(this.tabs, this.purse);- this.track(net.on('store', (msg) => { this.catalog = { sell: msg?.sell || [], buy: msg?.buy || [] }; this._render(); }));+ this.track(net.on('store', (msg) => {+ this.settleFirstSnapshot();+ this.catalog = { sell: msg?.sell || [], buy: msg?.buy || [] };+ this._render();+ }));this.track(net.on('profile', (snap) => { this.endRequest(); this._applyProfile(snap); }));this.track(net.on('inv', (delta) => { this.endRequest(); this._applyProfile(delta); }));// A refused trade (no cash, pack full, not for sale) answers with a notice@@ -159,6 +232,7 @@ class StorePanel extends EconPanel {this.setStatus(n.text || '', n.kind === 'full' ? 'err' : 'ok');}));+ this.awaitFirstSnapshot(() => { net.requestStore(); net.requestProfile(); });net.requestStore();net.requestProfile();this._render();@@ -166,20 +240,35 @@ class StorePanel extends EconPanel {_applyProfile(snap) {if (!snap) return;+ const before = this.profile.gold;if (Number.isFinite(snap.gold)) this.profile.gold = snap.gold;if (Array.isArray(snap.inv)) this.profile.inv = snap.inv;- this.purse.lastChild.textContent = this.profile.gold.toLocaleString();+ this.purseValue.textContent = this.profile.gold.toLocaleString();+ // The purse is a plain number on screen — nothing a screen reader would+ // revisit after a trade. Announce the delta so the outcome of a buy/sell+ // is audible, not just visible.+ if (Number.isFinite(snap.gold) && snap.gold !== before) {+ const delta = snap.gold - before;+ announce(`${delta > 0 ? 'Gained' : 'Spent'} ${Math.abs(delta).toLocaleString()}. Cash on hand ${this.profile.gold.toLocaleString()}.`);+ }this._render();}_setTab(tab) {this.tab = tab;- for (const b of this.tabs.children) b.classList.toggle('ec-on', b.textContent.toLowerCase() === tab);+ // Keyed on data-tab, never the visible label: the label is translated copy.+ for (const b of this.tabs.children) {+ const on = b.dataset.tab === tab;+ b.classList.toggle('ec-on', on);+ b.setAttribute('aria-selected', on ? 'true' : 'false');+ }this._render();}_render() {this.body.replaceChildren();+ if (this.loading) { this.body.appendChild(this.skeleton(4)); return; }+ if (this.loadFailed) { this.body.appendChild(this.loadError('the store')); return; }if (this.tab === 'buy') this._renderBuy(); else this._renderSell();}@@ -188,7 +277,7 @@ class StorePanel extends EconPanel {_renderBuy() {if (!this.catalog.buy.length) {- this.body.appendChild(el('div', { class: 'ec-empty', text: 'Loading the catalog…' }));+ this.body.appendChild(el('div', { class: 'ec-empty', text: 'The shelves are bare right now. The storekeeper restocks as the world turns over, so check back after a job or two.' }));return;}for (const entry of this.catalog.buy) {@@ -265,13 +354,18 @@ class BankPanel extends EconPanel {this.gold = 0;this.bankBal = 0;+ // Until the server's profile lands, both balances read as unknown rather+ // than as a confident "0" — telling a player they are broke when we have+ // simply not looked yet is the worst thing this panel could say.+ this.purseValue = el('b', { class: 'ec-pending-val', text: '…' });this.purse = el('div', { class: 'ec-purse' }, [el('span', { text: 'Cash on hand' }),- el('b', { text: '0' }),+ this.purseValue,]);+ this.bankValue = el('b', { class: 'ec-pending-val', text: '…' });this.bankLine = el('div', { class: 'ec-purse' }, [el('span', { text: 'Banked (protected)' }),- el('b', { text: '0' }),+ this.bankValue,]);this.card.insertBefore(this.purse, this.body);this.card.insertBefore(this.bankLine, this.body);@@ -282,19 +376,25 @@ class BankPanel extends EconPanel {this.depositBtn = el('button', { class: 'ec-row-btn', type: 'button', text: 'Deposit', onclick: () => this._deposit() });this.withdrawBtn = el('button', { class: 'ec-row-btn ec-secondary', type: 'button', text: 'Withdraw', onclick: () => this._withdraw() });- this.body.appendChild(el('div', { class: 'ec-row-sub', text: 'Deposit — protects cash from a death drop.' }));+ // "Max" fills the field from a balance we may not know yet, so both+ // presets are held with the transfer buttons until the profile lands.+ this.depositMaxBtn = el('button', { class: 'ec-bank-preset', type: 'button', text: 'Max', onclick: () => { this.depositInput.value = String(this.gold); } });+ this.withdrawMaxBtn = el('button', { class: 'ec-bank-preset', type: 'button', text: 'Max', onclick: () => { this.withdrawInput.value = String(this.bankBal); } });++ this.body.appendChild(el('div', { class: 'ec-row-sub', text: 'Deposit: protects cash from a death drop.' }));this.body.appendChild(el('div', { class: 'ec-bank-amount' }, [this.depositInput, this.depositBtn]));- this.body.appendChild(el('div', { class: 'ec-bank-presets' }, [- el('button', { class: 'ec-bank-preset', type: 'button', text: 'Max', onclick: () => { this.depositInput.value = String(this.gold); } }),- ]));+ this.body.appendChild(el('div', { class: 'ec-bank-presets' }, [this.depositMaxBtn]));- this.body.appendChild(el('div', { class: 'ec-row-sub', text: 'Withdraw — moves banked cash back to your purse.' }));+ this.body.appendChild(el('div', { class: 'ec-row-sub', text: 'Withdraw: moves banked cash back to your purse.' }));this.body.appendChild(el('div', { class: 'ec-bank-amount' }, [this.withdrawInput, this.withdrawBtn]));- this.body.appendChild(el('div', { class: 'ec-bank-presets' }, [- el('button', { class: 'ec-bank-preset', type: 'button', text: 'Max', onclick: () => { this.withdrawInput.value = String(this.bankBal); } }),- ]));+ this.body.appendChild(el('div', { class: 'ec-bank-presets' }, [this.withdrawMaxBtn]));- this.track(net.on('profile', (snap) => { this.endRequest(); this._applyProfile(snap); }));+ this.track(net.on('profile', (snap) => {+ this.settleFirstSnapshot();+ this.endRequest();+ this._applyProfile(snap);+ this._render();+ }));// A transfer the server clamped to zero (nothing on hand, nothing banked)// answers with a notice and no snapshot, so release the slot on it too.this.track(net.on('notice', (n) => {@@ -303,29 +403,49 @@ class BankPanel extends EconPanel {this.setStatus(n.text || '', 'ok');}));+ this.awaitFirstSnapshot(() => net.requestProfile());net.requestProfile();+ this._render();+ }++ // The bank's body is static, so "render" here means syncing the two live+ // bits: whether the balances are known yet, and whether a transfer is open.+ _render() {+ if (this.loadFailed) this.setStatus('Could not read your balance. The world stopped answering. Nothing was moved.', 'err');+ this._syncPending();}// Both transfer buttons ride the panel's single in-flight slot, so a// double-tapped Deposit can never send the same amount twice._syncPending() {- const busy = !!this.pending;- this.depositBtn.disabled = busy;- this.withdrawBtn.disabled = busy;+ const blocked = !!this.pending || this.loading || this.loadFailed;+ this.depositBtn.disabled = blocked;+ this.withdrawBtn.disabled = blocked;+ this.depositMaxBtn.disabled = blocked;+ this.withdrawMaxBtn.disabled = blocked;}_applyProfile(snap) {if (!snap) return;+ const before = { gold: this.gold, bank: this.bankBal };if (Number.isFinite(snap.gold)) this.gold = snap.gold;if (Number.isFinite(snap.bank)) this.bankBal = snap.bank;- this.purse.lastChild.textContent = this.gold.toLocaleString();- this.bankLine.lastChild.textContent = this.bankBal.toLocaleString();+ this.purseValue.textContent = this.gold.toLocaleString();+ this.bankValue.textContent = this.bankBal.toLocaleString();+ this.purseValue.classList.remove('ec-pending-val');+ this.bankValue.classList.remove('ec-pending-val');+ // A transfer only changes two numbers on screen; say them out loud so a+ // screen-reader player knows the deposit actually landed.+ if (this.gold !== before.gold || this.bankBal !== before.bank) {+ announce(`Cash on hand ${this.gold.toLocaleString()}. Banked ${this.bankBal.toLocaleString()}.`);+ }}_deposit() {const amount = Math.max(0, Math.floor(Number(this.depositInput.value) || 0));if (!amount) { this.setStatus('Enter an amount to deposit.', 'err'); return; }- this.setStatus('Depositing…');+ if (amount > this.gold) { this.setStatus(`You're only carrying ${this.gold.toLocaleString()}.`, 'err'); return; }+ if (!this.beginRequest('Depositing…')) return;this.net.bank(amount);this.depositInput.value = '';}@@ -333,7 +453,8 @@ class BankPanel extends EconPanel {_withdraw() {const amount = Math.max(0, Math.floor(Number(this.withdrawInput.value) || 0));if (!amount) { this.setStatus('Enter an amount to withdraw.', 'err'); return; }- this.setStatus('Withdrawing…');+ if (amount > this.bankBal) { this.setStatus(`You've only got ${this.bankBal.toLocaleString()} banked.`, 'err'); return; }+ if (!this.beginRequest('Withdrawing…')) return;this.net.bank(-amount);this.withdrawInput.value = '';}diff --git a/src/game/npc/ambient-life.js b/src/game/npc/ambient-life.jsindex 826073e45..6adffbf40 100644--- a/src/game/npc/ambient-life.js+++ b/src/game/npc/ambient-life.js@@ -425,7 +425,9 @@ export class AmbientLife {if (this._impostor) {this.scene.remove(this._impostor.bodies, this._impostor.heads);this._impostor.bodies.geometry.dispose();+ this._impostor.bodies.material.dispose();this._impostor.heads.geometry.dispose();+ this._impostor.heads.material.dispose();this._impostor = null;}}diff --git a/src/game/npc/world-life.js b/src/game/npc/world-life.jsindex d51bf901d..15070acee 100644--- a/src/game/npc/world-life.js+++ b/src/game/npc/world-life.js@@ -57,7 +57,7 @@ export class WorldLife {// "Talk 1-on-1" that starts a live in-character conversation.onInspectPed: (ped) => this._inspectPed(ped),});- this.mobs = new MobSystem({ scene, nav: this.nav });+ this.mobs = new MobSystem({ scene });// Waypoints for the jobs board's active objectives (W08 hooking W05) —// pure client render of the same quest-zones.js the server already// validates goto/interact against; it drives itself off the 'quests'@@ -144,7 +144,6 @@ export class WorldLife {s.id = 'npc-styles';s.textContent = `.npc-name { color: var(--npc-tint, #fff); text-shadow: 0 1px 3px rgba(0,0,0,0.7); }- .npc-bubble { /* inherits .cc-bubble; ambient chatter + NPC dialogue */ }.npc-prompt {position: fixed; left: 0; top: 0; z-index: 16; pointer-events: none;transform: translate(-50%, -100%); white-space: nowrap;@@ -353,9 +352,26 @@ export class WorldLife {this.ambient?.dispose();this.mobs?.dispose();this.questMarkers?.dispose();- for (const npc of this.npcs) { npc.dispose(); if (npc.marker) { this.scene.remove(npc.marker); npc.marker.geometry.dispose(); } }+ for (const npc of this.npcs) {+ npc.dispose();+ if (npc.marker) {+ this.scene.remove(npc.marker);+ npc.marker.geometry.dispose();+ npc.marker.material.dispose();+ }+ }this.npcs = [];- if (this.roadGroup) { this.scene.remove(this.roadGroup); this.roadGroup = null; }+ if (this.roadGroup) {+ this.scene.remove(this.roadGroup);+ // Road band + kerb are one-off RingGeometries with their own materials —+ // free them, this group is rebuilt for every world enter.+ for (const child of this.roadGroup.children) {+ child.geometry.dispose();+ child.material.dispose();+ }+ this.roadGroup = null;+ }this.prompt?.remove();+ document.getElementById('npc-styles')?.remove();}}diff --git a/src/game/quests-ui.js b/src/game/quests-ui.jsindex 70088893b..eb18e6bb5 100644--- a/src/game/quests-ui.js+++ b/src/game/quests-ui.js@@ -27,6 +27,11 @@ function el(tag, props = {}, kids = []) {}const KIND_GLYPH = { job: '🎯', heist: '🤝' };+const EVENT_GLYPH = '🎉';+// How often the standings refresh while the Event tab is open. The room caches the+// upstream read, so this is a cheap way to watch the race move without a manual+// refresh; the interval is cleared with the panel.+const BOARD_POLL_MS = 15_000;function rewardText(reward) {if (!reward) return '';@@ -35,6 +40,13 @@ function rewardText(reward) {return parts.join(' · ');}+// "3 runs · 960 cash" — the two numbers the ranking is actually sorted on, in the+// order it sorts them.+function scoreText(row) {+ const runs = row?.runs | 0;+ return `${runs} ${runs === 1 ? 'run' : 'runs'} · 💰 ${row?.cash | 0}`;+}+let _openQuests = null;/**@@ -58,28 +70,75 @@ class QuestsPanel extends EconPanel {this.net = net;this.tab = 'board';this.board = { offers: [], active: [], day: '' };+ // False until the first server snapshot lands, so an empty board renders as+ // "loading" rather than a premature "no jobs" (the server hasn't spoken yet).+ this._loaded = false;+ // The abandon just sent, confirmed by the next snapshot no longer listing it.+ this._abandoning = null; // { id, title }this._highlight = highlight || null;// One-shot flag: which id to flash/scroll-to on the NEXT render only —// kept separate from _pickForTab's persistent `_highlight` so a later// snapshot re-render (progress ticking in) doesn't keep re-pulsing it.this._flashId = highlight || null;- this.boardTabBtn = el('button', { class: 'ec-tab ec-on', type: 'button', text: 'Board', onclick: () => this._setTab('board') });- this.activeTabBtn = el('button', { class: 'ec-tab', type: 'button', text: 'Active', onclick: () => this._setTab('active') });- this.tabs = el('div', { class: 'ec-tabs' }, [this.boardTabBtn, this.activeTabBtn]);+ // The event leaderboard's own view state. `null` = the first read is still in+ // flight (the loading state); a payload with ok:false is the error state.+ this.eventBoard = null;+ this._boardPoll = null;++ this.boardTabBtn = el('button', { class: 'ec-tab ec-on', type: 'button', role: 'tab', 'aria-selected': 'true', text: 'Board', onclick: () => this._setTab('board') });+ this.activeTabBtn = el('button', { class: 'ec-tab', type: 'button', role: 'tab', 'aria-selected': 'false', text: 'Active', onclick: () => this._setTab('active') });+ // The Event tab only exists when there is an event to show: live right now, or+ // finished with a standing still worth reading. Hidden until then rather than+ // shown empty, so the board doesn't grow a dead tab for 51 weeks of the year.+ this.eventTabBtn = el('button', {+ class: 'ec-tab qb-event-tab', type: 'button', hidden: true, role: 'tab', 'aria-selected': 'false',+ text: `${EVENT_GLYPH} Event`, onclick: () => this._setTab('event'),+ });+ this.tabs = el('div', { class: 'ec-tabs', role: 'tablist', 'aria-label': 'Jobs board sections' }, [this.boardTabBtn, this.activeTabBtn, this.eventTabBtn]);this.card.insertBefore(this.tabs, this.body);this.track(net.on('quests', (snap) => {this.board = snap && typeof snap === 'object' ? snap : this.board;+ this._loaded = true;+ // The server confirms an abandon by sending a snapshot without the run;+ // there's no dedicated notice for it, so this is where the status lands.+ if (this._abandoning && !this.board.active.some((r) => r.id === this._abandoning.id)) {+ this.setStatus(`Abandoned: ${this._abandoning.title}`, 'ok');+ this._abandoning = null;+ }this._pickTabForHighlight();this._render();}));this.track(net.on('questComplete', (c) => this._onComplete(c)));+ // Accept refusals ("You already took that job", prereqs, crew rules) come+ // back as 'quest' notices; without this the status sat on "Accepting…"+ // forever. `ok` styles it; older servers omit the flag, and every quest+ // notice they send is a refusal, so undefined styles as an error too.+ this.track(net.on('notice', (n) => {+ if (n?.kind !== 'quest' || !n.text) return;+ this._abandoning = null;+ this.setStatus(n.text, n.ok === true ? 'ok' : 'err');+ }));+ this.track(net.on('eventBoard', (b) => {+ this.eventBoard = b && typeof b === 'object' ? b : { ok: false, reason: 'unavailable' };+ this._render();+ }));+ // Finishing an event job moves the standings — pull the fresh ranking rather+ // than waiting out the poll, so the panel reacts to the player's own run.+ this.track(net.on('eventScore', () => this.net.requestEventBoard()));net.requestQuests();+ net.requestEventBoard();this._render();}+ close() {+ clearInterval(this._boardPoll);+ this._boardPoll = null;+ super.close();+ }+// Called again if a giver NPC/menu opens the board while it's already up —// jump to whichever tab actually has that mission and flash it once.focusMission(id) {@@ -98,21 +157,43 @@ class QuestsPanel extends EconPanel {_setTab(tab) {this.tab = tab;- this.boardTabBtn.classList.toggle('ec-on', tab === 'board');- this.activeTabBtn.classList.toggle('ec-on', tab === 'active');+ for (const [btn, id] of [[this.boardTabBtn, 'board'], [this.activeTabBtn, 'active'], [this.eventTabBtn, 'event']]) {+ btn.classList.toggle('ec-on', tab === id);+ btn.setAttribute('aria-selected', tab === id ? 'true' : 'false');+ }+ // Poll only while the standings are actually on screen.+ clearInterval(this._boardPoll);+ this._boardPoll = null;+ if (tab === 'event') {+ this.net.requestEventBoard();+ this._boardPoll = setInterval(() => this.net.requestEventBoard(), BOARD_POLL_MS);+ }this._render();}_onComplete(c) {if (!c) return;const crew = c.coop && c.crew > 1 ? ` (crew of ${c.crew})` : '';- this.setStatus(`${c.title} complete${crew} — ${rewardText(c.reward)}`, 'ok');+ const tag = c.event ? `${EVENT_GLYPH} Event job — ` : '';+ this.setStatus(`${tag}${c.title} complete${crew} — ${rewardText(c.reward)}`, 'ok');+ }++ // Is there an event worth surfacing a tab for? Live right now, or finished with a+ // standing still on the board (so winners stay readable after the window shuts).+ _hasEvent() {+ return !!this.board.eventLive || (this.eventBoard?.ok && this.eventBoard.players > 0);}_render() {this.activeTabBtn.textContent = this.board.active.length ? `Active (${this.board.active.length})` : 'Active';+ const showEvent = this._hasEvent();+ this.eventTabBtn.hidden = !showEvent;+ // The tab can vanish under the player when the window closes mid-session.+ if (this.tab === 'event' && !showEvent) this.tab = 'board';this.body.replaceChildren();- if (this.tab === 'board') this._renderBoard(); else this._renderActive();+ if (this.tab === 'event') this._renderEvent();+ else if (this.tab === 'board') this._renderBoard();+ else this._renderActive();// One-shot: flash + scroll to the targeted row, then clear so a later// re-render (progress ticking in) doesn't keep re-pulsing it.if (this._flashId) {@@ -123,16 +204,23 @@ class QuestsPanel extends EconPanel {}_renderBoard() {+ if (!this._loaded) {+ this.body.appendChild(el('div', { class: 'ec-empty ec-loading', text: 'Loading the jobs board…' }));+ return;+ }if (!this.board.offers.length) {this.body.appendChild(el('div', { class: 'ec-empty', text: 'No jobs on the board right now — dailies rotate at UTC midnight, and repeatable work is always open somewhere in town.' }));return;}for (const offer of this.board.offers) {const flash = offer.id === this._flashId;- const row = el('div', { class: 'ec-row qb-row' + (flash ? ' qb-flash' : ''), 'data-mission': offer.id }, [- el('span', { class: 'ec-row-glyph', text: KIND_GLYPH[offer.kind] || '🎯' }),+ const row = el('div', { class: 'ec-row qb-row' + (offer.event ? ' qb-event-row' : '') + (flash ? ' qb-flash' : ''), 'data-mission': offer.id }, [+ el('span', { class: 'ec-row-glyph', text: offer.event ? EVENT_GLYPH : (KIND_GLYPH[offer.kind] || '🎯') }),el('div', { class: 'ec-row-main' }, [- el('div', { class: 'ec-row-name', text: offer.title }),+ el('div', { class: 'ec-row-name' }, [+ offer.title,+ offer.event ? el('span', { class: 'qb-event-badge', text: 'EVENT' }) : null,+ ]),el('div', { class: 'ec-row-sub', text: `${offer.giver} · ${offer.summary}` }),el('div', { class: 'qb-obj-preview', text: offer.objectives.map((o) => o.label).join(' → ') }),el('div', { class: 'qb-reward', text: rewardText(offer.reward) + (offer.kind === 'heist' ? ` · needs a crew of ${offer.party}` : '') }),@@ -148,6 +236,10 @@ class QuestsPanel extends EconPanel {}_renderActive() {+ if (!this._loaded) {+ this.body.appendChild(el('div', { class: 'ec-empty ec-loading', text: 'Loading your jobs…' }));+ return;+ }if (!this.board.active.length) {this.body.appendChild(el('div', { class: 'ec-empty', text: 'No active jobs — accept one from the Board tab or talk to a quest-giver out in the world.' }));return;@@ -164,9 +256,12 @@ class QuestsPanel extends EconPanel {const crewLine = run.kind === 'heist'? el('div', { class: 'qb-reward', text: `Crew: ${run.crew || 1}/${run.party || 2}` }): null;- const row = el('div', { class: 'ec-row qb-row qb-active-row' + (flash ? ' qb-flash' : ''), 'data-mission': run.id }, [+ const row = el('div', { class: 'ec-row qb-row qb-active-row' + (run.event ? ' qb-event-row' : '') + (flash ? ' qb-flash' : ''), 'data-mission': run.id }, [el('div', { class: 'ec-row-main' }, [- el('div', { class: 'ec-row-name', text: run.title }),+ el('div', { class: 'ec-row-name' }, [+ run.title,+ run.event ? el('span', { class: 'qb-event-badge', text: 'EVENT' }) : null,+ ]),el('div', { class: 'ec-row-sub', text: run.giver }),objList,crewLine,@@ -175,10 +270,109 @@ class QuestsPanel extends EconPanel {el('button', {class: 'ec-row-btn ec-secondary', type: 'button', text: 'Abandon','aria-label': `Abandon ${run.title}`,- onclick: () => { this.net.questAbandon(run.id); },+ onclick: () => {+ this._abandoning = { id: run.id, title: run.title };+ this.setStatus('Abandoning…');+ this.net.questAbandon(run.id);+ },}),]);this.body.appendChild(row);}}++ // --- Event leaderboard ----------------------------------------------------+ // Four states, all designed: the first read in flight (skeleton rows), the read+ // failed (a reason plus a retry that actually retries), nobody has run a job yet+ // (an invitation, not a void), and the ranking itself with the player's own row+ // pinned below the top ten whether or not they made it.++ _renderEvent() {+ const b = this.eventBoard;+ if (!b) { this._renderBoardSkeleton(); return; }+ if (!b.ok) { this._renderBoardError(b.reason); return; }++ const ev = b.event || {};+ this.body.appendChild(el('div', { class: 'qb-lb-head' }, [+ el('div', { class: 'qb-lb-title', text: ev.name || 'Live event' }),+ el('div', {+ class: 'qb-lb-note',+ text: ev.live+ ? `Live now · ${b.players} ${b.players === 1 ? 'runner' : 'runners'} · ${b.totalRuns} event ${b.totalRuns === 1 ? 'job' : 'jobs'} finished`+ : 'Final standings — the event has ended',+ }),+ ]));++ if (!b.top?.length) {+ this.body.appendChild(el('div', { class: 'ec-empty' }, [+ el('div', { text: 'No event runs yet — be the first.' }),+ el('div', {+ class: 'qb-lb-note',+ text: 'Take an EVENT job from the Board tab and finish it. Every completed event job is one run.',+ }),+ ]));+ this._renderPrizeNote();+ return;+ }++ const list = el('ol', { class: 'qb-lb-list' });+ for (const row of b.top) {+ list.appendChild(this._leaderRow(row, !!b.you && b.you.rank === row.rank));+ }+ this.body.appendChild(list);++ // Your own rank, pinned. Shown even when you are already in the top ten (as a+ // restatement below the list) so "where am I" is answered in one place, always.+ if (b.you) {+ this.body.appendChild(el('div', { class: 'qb-lb-you-wrap' }, [+ el('div', { class: 'qb-lb-note', text: b.you.inTop ? 'Your standing' : 'Your standing (outside the top ten)' }),+ this._leaderRow(b.you, true),+ ]));+ } else {+ this.body.appendChild(el('div', { class: 'qb-lb-you-wrap' }, [+ el('div', { class: 'qb-lb-note', text: 'You have not finished an event job yet — one run puts you on this board.' }),+ ]));+ }+ this._renderPrizeNote();+ }++ _leaderRow(row, mine) {+ return el('li', { class: 'qb-lb-row' + (mine ? ' is-you' : '') }, [+ el('span', { class: 'qb-lb-rank', text: `#${row.rank}` }),+ el('span', { class: 'qb-lb-name', text: row.name || 'Anonymous' }),+ el('span', { class: 'qb-lb-score', text: scoreText(row) }),+ ]);+ }++ _renderBoardSkeleton() {+ const list = el('div', { class: 'qb-lb-list qb-lb-skeleton', 'aria-hidden': 'true' });+ for (let i = 0; i < 5; i++) list.appendChild(el('div', { class: 'qb-lb-row qb-lb-ghost' }));+ this.body.appendChild(el('div', { class: 'qb-lb-note', role: 'status', text: 'Loading the standings…' }));+ this.body.appendChild(list);+ }++ _renderBoardError(reason) {+ this.body.appendChild(el('div', { class: 'ec-empty' }, [+ el('div', { text: 'The standings could not be read just now.' }),+ el('div', {+ class: 'qb-lb-note',+ text: reason === 'unavailable'+ ? 'Your own progress is safe — every finished job was already paid and recorded. Only this view is offline.'+ : 'Try again in a moment.',+ }),+ el('button', {+ class: 'ec-row-btn', type: 'button', text: 'Retry',+ onclick: () => { this.eventBoard = null; this._render(); this.net.requestEventBoard(); },+ }),+ ]));+ }++ // The one line that has to be on this panel: the board ranks, the team pays.+ // Nothing in this client or the server ever settles a prize automatically.+ _renderPrizeNote() {+ this.body.appendChild(el('div', {+ class: 'qb-lb-prize',+ text: 'Winners are announced from this board and settled by the three.ws team after the event. No prize is paid automatically.',+ }));+ }}diff --git a/src/stage.js b/src/stage.jsindex 560d33fcc..c5881e22e 100644--- a/src/stage.js+++ b/src/stage.js@@ -21,7 +21,7 @@ import {AmbientLight, DirectionalLight, SpotLight, PointLight,Mesh, CylinderGeometry, CircleGeometry, PlaneGeometry,MeshStandardMaterial, MeshBasicMaterial, Group,- AudioListener, PositionalAudio, AudioAnalyser, SRGBColorSpace, ACESFilmicToneMapping,+ AudioListener, PositionalAudio, SRGBColorSpace, ACESFilmicToneMapping,} from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';@@ -237,7 +237,7 @@ class VenueController {this.showCaption(u.text, true);this.renderPhase('live');if (this.three) this.three.setCue(u.cue, true);- await this.speak(u.text, u.voice, u.durationMs);+ await this.speak(u.text, u.voice);}onAudience(a) {@@ -594,10 +594,9 @@ class StageScene {_mountHost(model) {if (this.placeholder) { this.hostGroup.remove(this.placeholder); this.placeholder = null; }// Normalize to ~1.7m tall, feet on the disc.- const box = new (model.constructor === Group ? Group : Group)();model.updateMatrixWorld(true);- const bounds = boundingSize(model);- const scale = bounds.height > 0 ? 1.7 / bounds.height : 1;+ const height = modelHeight(model);+ const scale = height > 0 ? 1.7 / height : 1;model.scale.setScalar(scale);model.position.y = 0.4;this.hostGroup.add(model);@@ -613,22 +612,6 @@ class StageScene {head.add(this.positionalAudio);}- // Wire an <audio> element through the host's PositionalAudio and return an- // AnalyserNode for lip-sync. Returns null when 3D audio isn't ready.- attachVoice(audioEl) {- if (!this.positionalAudio) return null;- this.resumeAudio();- try {- // A MediaElementSource can be created once per element; this element is- // fresh per utterance, so this is safe.- this.positionalAudio.setMediaElementSource(audioEl);- } catch {- return null;- }- const analyser = new AudioAnalyser(this.positionalAudio, 256);- return analyser.analyser;- }-resumeAudio() {const ctx = this.listener?.context;if (ctx && ctx.state === 'suspended') ctx.resume().catch(() => {});@@ -734,41 +717,6 @@ class StageScene {}}-// Maps lip-sync {open,wide,round} onto whatever the GLB rig supports: morph-// targets (visemes / mouthOpen / jawOpen) when present, else a jaw bone, else a-// subtle head scale — so lip-sync is real where the rig allows and degrades-// gracefully where it doesn't (no T-pose, never a hard failure).-class MouthTarget {- constructor(model) {- this.influences = [];- this.jaw = null;- this.head = findHead(model);- const openNames = /(mouthopen|jawopen|viseme_aa|viseme_o|vrc\.v_aa|mouth_open|aa)/i;- model.traverse((o) => {- if (o.isMesh && o.morphTargetDictionary) {- for (const [name, idx] of Object.entries(o.morphTargetDictionary)) {- if (openNames.test(name)) this.influences.push({ mesh: o, idx });- }- }- if (o.isBone && /jaw/i.test(o.name) && !this.jaw) this.jaw = o;- });- }- setMouthShape({ open }) {- const v = Math.max(0, Math.min(1, open));- if (this.influences.length) {- for (const { mesh, idx } of this.influences) mesh.morphTargetInfluences[idx] = v;- } else if (this.jaw) {- this.jaw.rotation.x = v * 0.35;- } else if (this.head) {- this.head.scale.y = 1 + v * 0.03;- }- }- dispose() {- for (const { mesh, idx } of this.influences) if (mesh.morphTargetInfluences) mesh.morphTargetInfluences[idx] = 0;- if (this.jaw) this.jaw.rotation.x = 0;- }-}-// ─────────────────────────────────────────────────────────────────────────────// helpers// ─────────────────────────────────────────────────────────────────────────────@@ -859,24 +807,6 @@ function nextShowLabel(ms) {return `Next show ${d.toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' })}`;}-function boundingSize(model) {- let minY = Infinity, maxY = -Infinity;- model.traverse((o) => {- if (o.isMesh && o.geometry) {- o.geometry.computeBoundingBox?.();- const b = o.geometry.boundingBox;- if (b) { minY = Math.min(minY, b.min.y); maxY = Math.max(maxY, b.max.y); }- }- });- return { height: Number.isFinite(maxY - minY) ? maxY - minY : 0 };-}--function findHead(model) {- let head = null;- model.traverse((o) => { if (!head && o.isBone && /head/i.test(o.name)) head = o; });- return head;-}-function disposeMesh(mesh) {try { mesh.geometry?.dispose(); mesh.material?.dispose?.(); } catch {}}