Skip to content

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

feat(play): spectate wars from the portal, drop event souvenirs, and open the plaza stage

nirholas015a08513454
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 167a6b635..e8488a1d7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-08-07
- **Docs · The agent runtime and transaction guard** (`/docs/agent-runtime`): The seven-layer policy engine that preflights every fund-moving tool call in chat before the wallet prompts: security blacklist, approval policy, dollar caps with live SOL pricing, spend envelope with a token and destination firewall, MEV slippage clamp, and x402 budgets. Ships as @three-ws/agent-runtime.
-- **Live event** (`/event`): The live three.ws community meetup: when it starts, what is on the agenda, who is in the world right now, and the event leaderboard.
+- **Live event** (`/event`): The live three.ws community meetup: a ticking countdown off the same config /play reads, the run of show in your own timezone, an add-to-calendar file, who is in the world right now, and the one door in.
- **A transaction guard now stands between the chat agent and your wallet**: Every fund-moving tool the chat agent can call (SOL and token transfers, Jupiter and 1inch swaps, pump.fun buys and sells, token launches) is now preflighted through a seven-layer policy engine before the tool even runs: a security blacklist, approval policy, dollar caps with live SOL pricing, a spend envelope with a token and destination firewall, an MEV slippage clamp that automatically tightens risky swap parameters, and an hourly budget for paid agent calls. A blocked call never reaches your wallet, and the approval popup now shows the verdict: what was checked, what was flagged, and what could not be verified. The engine ships as an open building block, @three-ws/agent-runtime, with an agent decision loop and a tamper-evident action ledger, plus a public preflight endpoint at /api/agent/guard for your own agents. (`/docs/agent-runtime`) `[feature, security, sdk]`
- **Agent payments: fresher signatures and a health readout that names the real cause**: Two reliability fixes for the x402 agent economy on Solana. First, autonomous payments are now signed against a fresh blockhash instead of one fetched at the start of a long batch, which eliminates the class of settlement failures where a payment expired before it could reach the chain; a refused payment also retries with a brand-new blockhash. Second, the platform health readout at /api/healthz now cross-checks failed settlements against the settlement engine's own records, so a deliberate spending pause (the daily fee budget protecting the treasury) is reported as exactly that instead of masquerading as a payment-rail outage. Operators and holders watching platform status now see the true cause and the true rail health at a glance. `[fix, infra]`
- **Avatars now save in a clean, neutral stance instead of a frozen animation frame**: Saving an avatar in the Studio used to capture whatever the idle animation happened to be doing at that exact instant, and freeze it into the model permanently. Because the saved file carries no animation of its own, that one arbitrary frame became the avatar's pose everywhere it appeared: arms tucked in at odd angles, one side sitting differently from the other, and a different result each time you saved the same avatar. Avatars are now saved in their proper neutral pose, which is symmetric and identical on every save, so downloads, animation retargeting and clothing all start from the stance the body was actually built around. Your gallery thumbnail still shows the relaxed idle pose it always did. `[fix, improvement]`
@@ -16,10 +16,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Game-Ready export stops charging $THREE holders who connected a wallet**: Exporting a model for Unity or Unreal is free if you hold $THREE, but the export panel only recognised holders who had signed in with a wallet linked to their account. If you had simply connected your wallet to the site, the way most people browse the Forge, the panel could not see what you hold and asked you to pay the per-export fee your holding already covered. It now proves your holding from whichever identity you actually have: a linked account signs silently, and a connected wallet proves ownership with one free signature that never moves funds. That signature is only ever requested when your wallet genuinely clears the tier, so a non-holder is never prompted for something that could not unlock anything. The panel also now tells you your real price before you export: holders read 'free for you', everyone else reads the exact per-export price. (`/forge`) `[fix, improvement]`
- **Holders-world door now tells the truth when the check itself is down**: Trying to enter a coin's holders-only world while our holder-verification service is unavailable used to dump a cryptic internal error ("CoinCommunities is not configured") with a retry button that could never succeed. The gate now says plainly that the holder check is offline on our side, that your tokens are unaffected, and offers a one-click way into the coin's open world instead. That open-world button, in the too-few-tokens screen as well, now actually takes you into the open world rather than kicking you back to the lobby to start over. (`/play`) `[fix]`
- **Meet real people in Play: profiles, follows, and DMs in-world**: Players in Play (and Walk) worlds now carry their real three.ws identity. Signed-in players get a verified @handle on their nameplate, and clicking anyone opens their actual profile card right in the world: bio, followers, their latest 3D creations, and a link to their full profile page. You can follow them, send a friend request, or, if you are already friends, jump straight into a private message thread without leaving the world. The handle is verified server-side, so nobody can pretend to be someone they are not. Signing in also makes the world lobby greet you as your account, with your display name prefilled. (`/play`) `[feature]`
-- **Play now counts down to the next community event**: The Play lobby shows a live banner for the upcoming $THREE Community Day: the event name, when it starts in your own timezone, and a ticking countdown. Once you are inside a world, a small dismissible reminder pill keeps the countdown in view, and when the event goes live both switch to a LIVE marker with a one-click jump into the $THREE world. After the event ends everything quietly disappears on its own. (`/play`) `[feature]`
+- **Play now counts down to the next community event**: The Play lobby shows a live banner for the upcoming $THREE First Holders Meetup: the event name, when it starts in your own timezone, and a ticking countdown. Once you are inside a world, a small dismissible reminder pill keeps the countdown in view, and when the event goes live both switch to a LIVE marker with a one-click jump into the $THREE world. After the event ends everything quietly disappears on its own. (`/play`) `[feature]`
- **Play: phones stop getting dropped out of the world seconds after joining**: Players on phones were being thrown out of /play within seconds of entering a world, seemingly at random. The cause was memory: the decorative crowd drew random models from the public avatar gallery with no size limit, no reuse and no cleanup, and community models there run as large as 24 MB. A phone that happened to draw a few heavy ones pulled tens of megabytes of 3D geometry within seconds of entering, and the browser killed the tab. The crowd now works to a memory budget sized for the device, downloads each model once and reuses it, and releases everything when you leave a world. The lobby's avatar picker also stops downloading full models on phones when it already has a real picture of them. And if a phone does reclaim graphics memory mid-session, the world now pauses rendering and recovers instead of freezing on a dead frame. (`/play`) `[fix, improvement]`
- **The chat no longer refuses questions it was never asked to refuse**: Every message sent to a three.ws chat surface used to pass through a small safety classifier of ours before the actual model saw it, and when that classifier said "unsafe" you got a canned brush-off instead of an answer. It was wrong often enough to be a real problem: it judged one message at a time with no memory of the conversation, so an ordinary follow-up in a security, trading, or fiction discussion could read as alarming on its own and get blocked, and you were left staring at a refusal no model had actually made. That layer is gone from all of it: the main chat, the /chat app, the embeddable concierge, the widget chat on customer sites, and the agent-idea box on /create. Your question now goes to the model as written. If a model declines something, that is the model exercising its own judgment in its own words, and you can switch models or bring your own key. Nothing else changed: the same rate limits still apply, and the separate confirmation step before any wallet action is untouched. The one place a content check still runs is outbound: what our own official Sketchfab account publishes under the three.ws name. (`/chat`) `[improvement, fix]`
- **The embedded avatar brain is now scoped to the sites it was meant for**: Every agent and avatar embed can chat for free because the platform pays for the model behind it, and the agent owner decides which sites may run that embed and which model it uses. Both of those controls only really applied to browsers: a request that simply left out the header a browser always sends slipped past the site allowlist entirely, and any caller could ask for a pricier model than the owner had chosen. Both are closed. A request with no site header now has to sign in (a session or an API key) instead of riding on an agent id anyone could read off our public sitemap, and a model that bills our own provider keys runs only when the owner selected it in the dashboard. There is also a new platform-wide ceiling across all of this traffic combined, so no amount of spreading requests around can drain the shared budget. Nothing changes for a normal embed on an allowlisted site. (`/docs/api-reference`) `[security, fix]`
+- **The event countdown is now on the front page**: You no longer have to open Play to find out when the next live community event starts. The three.ws home page now carries a slim strip above the hero with the event name, the start time in your own timezone, and a countdown ticking down to the second. The moment the event begins it switches to LIVE on its own, without a refresh, and it takes itself off the page once the event is over. One click on it drops you straight into the $THREE world. If you would rather not see it, dismiss it once and it stays gone, in Play as well as on the home page. Every countdown surface across the site reads the same event schedule, so they can never disagree about when things start. (`/`) `[feature]`
## 2026-08-06
diff --git a/STRUCTURE.md b/STRUCTURE.md
index d76cba71d..1fc635711 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -80,14 +80,14 @@ bottom.
| X/Twitter automation toolkit | [nirholas/XActions](https://github.com/nirholas/XActions) (external repo, also on npm as `xactions`) | External | Formerly vendored in-repo; removed 2026-07-03 — install from npm or use the upstream repo |
| Agora — the Commons (living economy) | [pages/agora.html](pages/agora.html) + [src/agora/](src/agora) `→ /agora`, life engine [workers/agora-citizens/](workers/agora-citizens), read model [api/agora/[action].js](api/agora/[action].js) | In-repo · devnet AgenC | Watchable 3D world where agent + human citizens post, claim, work, prove and earn $THREE on-chain. **Play mode** ("Enter the Commons") makes it walkable GTA-style — your avatar walks the square among the working NPC citizens, other humans appear live over the `agora_world` Colyseus room, and walking up to a citizen (proximity → E) opens its passport: [src/agora/player-mode.js](src/agora/player-mode.js), pure math [src/agora/player-logic.js](src/agora/player-logic.js), room [multiplayer/src/rooms/AgoraRoom.js](multiplayer/src/rooms/AgoraRoom.js). Play mode also has an opt-in **"Record on-chain (BNB testnet)"** toggle (OFF by default) that gaslessly commits your moves to the `WorldMoves` contract every ~block via MegaFuel (self-pay fallback) and renders other on-chain players as lightweight ghost markers read back from real `Moved` events: [src/agora/onchain-presence.js](src/agora/onchain-presence.js), sender [src/bnb/move-sender.js](src/bnb/move-sender.js), event reader [src/bnb/world-presence-reader.js](src/bnb/world-presence-reader.js), pure ghost interpolation [src/bnb/onchain-ghosts.js](src/bnb/onchain-ghosts.js), server relay lib [api/_lib/bnb/world-moves.js](api/_lib/bnb/world-moves.js), config endpoint [api/bnb/world-config.js](api/bnb/world-config.js). WorldMoves contract: [contracts/src/WorldMoves.sol](contracts/src/WorldMoves.sol) (code-complete + anvil-fork-proven; public BSC testnet deploy pending a funded deployer key — see `contracts/DEPLOYMENTS.md`). **Arena** (Competitive tasks — citizens race, first valid proof wins the whole escrow) at [src/agora/arena.js](src/agora/arena.js); **Guilds** (Collaborative tasks — contributors split the reward) at [src/agora/guild.js](src/agora/guild.js), both live-driven by [api/agora/task](api/agora/[action].js). Spec: [docs/agora.md](docs/agora.md) |
| `/play` in-game economy (cash, bank/ATM, vendors, $THREE boutique) | Client: [src/game/coincommunities.js](src/game/coincommunities.js) `→ /play`, general-store/bank NPCs [src/game/npc/economy-npcs.js](src/game/npc/economy-npcs.js), store/bank UI [src/game/economy-ui.js](src/game/economy-ui.js), on-chain purchase flow [src/game/boutique-purchase.js](src/game/boutique-purchase.js), wardrobe [src/game/play-systems.js](src/game/play-systems.js). Server: [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) (store/bank/boutique handlers), price tables [multiplayer/src/shop.js](multiplayer/src/shop.js), purse/bank model [multiplayer/src/economy.js](multiplayer/src/economy.js), on-chain settlement [multiplayer/src/game-token.js](multiplayer/src/game-token.js) | In-repo | The GTA-style open world's real economy (W04 of the World Online program, program brief retired to git history). Walk up to a General Store clerk (E) to buy tools/consumables or sell gathered goods for cash, server-priced and validated every time; walk up to the Bank Teller to deposit cash into a protected balance (survives a death drop) or withdraw it. Premium wardrobe cosmetics unlock with a real on-chain `$THREE` payment from the player's connected Solana wallet; the server only grants the item after re-verifying the confirmed transaction on RPC. Distinct from the separate USDC/x402 avatar-shop rail ([api/x402/cosmetic-purchase.js](api/x402/cosmetic-purchase.js)), which sells a different catalog for the standalone character creator. Published publicly at [pages/play/economy.html](pages/play/economy.html) `→ /play/economy` ([src/play-economy.js](src/play-economy.js)), fed by [api/play/economy.js](api/play/economy.js) `→ /api/play/economy`, which serializes the SAME shop/economy/spin-wheel modules the server prices trades with rather than restating them, so the public reference cannot drift from the game. Docs: [docs/in-game-economy.md](docs/in-game-economy.md), tutorial [docs/tutorials/earn-and-spend-in-play.md](docs/tutorials/earn-and-spend-in-play.md). Tests: [tests/api/play-economy.test.js](tests/api/play-economy.test.js) |
-| `/play` character & avatar customization (avatar creator, selfie→3D, wardrobe boutique) | Lobby creator flow [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) `_openCreate()`, selfie SDK wrapper [src/avatar-creator.js](src/avatar-creator.js), shop [src/game/cosmetics-shop.js](src/game/cosmetics-shop.js), wardrobe [src/game/cosmetics-wardrobe.js](src/game/cosmetics-wardrobe.js), boutique NPCs [src/game/npc/npc-catalog.js](src/game/npc/npc-catalog.js) (`npc-tailor`, `npc-fitting-room`), boutique spawn points [src/game/world-zones.js](src/game/world-zones.js) (`type: 'boutique'`) | In-repo | W03 of the World Online program (program brief retired to git history). Before dropping into `/play`, design an avatar from scratch or a selfie (real Avaturn SDK), upload a `.glb`, or sculpt in the full Avatar Studio; no sign-in required. Once in the world, the cosmetics shop/wardrobe (real x402-settled catalog, server-persisted equip) now has a physical home: walk up to Roux · Tailor to browse/buy, or Nell's Fitting Room to equip anything you own. Doc: [docs/character-studio.md](docs/character-studio.md#character-customization-in-play-world-online). |
+| `/play` character & avatar customization (avatar creator, selfie→3D, wardrobe boutique) | Lobby creator flow [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) `_openCreate()`, selfie SDK wrapper [src/avatar-creator.js](src/avatar-creator.js), shop [src/game/cosmetics-shop.js](src/game/cosmetics-shop.js), wardrobe [src/game/cosmetics-wardrobe.js](src/game/cosmetics-wardrobe.js), boutique NPCs [src/game/npc/npc-catalog.js](src/game/npc/npc-catalog.js) (`npc-tailor`, `npc-fitting-room`), boutique spawn points [src/game/world-zones.js](src/game/world-zones.js) (`type: 'boutique'`), in-world avatar switcher [src/game/avatar-switcher.js](src/game/avatar-switcher.js) (HUD Avatar button / `V`, swap applied in [src/game/coincommunities.js](src/game/coincommunities.js) `_applyAvatarSwap()`) | In-repo | W03 of the World Online program (program brief retired to git history). Before dropping into `/play`, design an avatar from scratch or a selfie (real Avaturn SDK), upload a `.glb`, or sculpt in the full Avatar Studio; no sign-in required. Once in the world, press `V` (or the HUD Avatar button) to change avatars without leaving: saved three.ws avatars, quick picks, gallery, paste-a-URL, upload, and the creator, rebuilt live on your rig and broadcast to peers over the room's `avatar` message. The cosmetics shop/wardrobe (real x402-settled catalog, server-persisted equip) also has a physical home: walk up to Roux · Tailor to browse/buy, or Nell's Fitting Room to equip anything you own. Doc: [docs/character-studio.md](docs/character-studio.md#character-customization-in-play-world-online). Tests: [tests/play-avatar-switcher.test.js](tests/play-avatar-switcher.test.js), [tests/walkroom-avatar-swap.test.js](tests/walkroom-avatar-swap.test.js). |
| `/play` combat & weapons (server-authoritative, danger zones, wanted, tombstones) | Client: [src/game/combat-system.js](src/game/combat-system.js) `→ /play` (vitals HUD wiring, danger-zone ground, tombstone loot, hit feedback, the `window.twsCombat` bridge into W08's `MobSystem`), HUD [src/game/hud/world-hud.js](src/game/hud/world-hud.js). Server: [multiplayer/src/combat-handlers.js](multiplayer/src/combat-handlers.js) (mob AI, attack/loot intents, death + respawn), pure math [multiplayer/src/combat.js](multiplayer/src/combat.js), weapon/mob/loot tables [multiplayer/src/items.js](multiplayer/src/items.js), zone geometry [multiplayer/src/world-features.js](multiplayer/src/world-features.js), handlers wired in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W07 of the World Online program (program brief retired to git history). Equip a sword/bat/pistol/bow from the hotbar and press `X` (or tap the touch Attack button) to fight; but only inside one of three named danger zones (Southern Wilds, Northern Wilds, Eastern Marches); town stays lawful by construction. PvE mobs chase and swing back through the same server-side damage path a player's attack uses; a kill (mob or PvP) spills a lootable tombstone, PvP raises the attacker's wanted/heat stars (visible on `WorldHud` and a downed peer's nameplate), and death drops carried cash/pack before an automatic respawn in town. |
| `/play` NPCs & world life (traffic, vendors, quest-givers, mobs) | Manager [src/game/npc/world-life.js](src/game/npc/world-life.js), nav graph [src/game/npc/nav-graph.js](src/game/npc/nav-graph.js), ambient crowd/traffic [src/game/npc/ambient-life.js](src/game/npc/ambient-life.js), quest-giver NPCs [src/game/npc/quest-npcs.js](src/game/npc/quest-npcs.js), quest-zone waypoints [src/game/npc/quest-markers.js](src/game/npc/quest-markers.js), Jobs Board UI [src/game/quests-ui.js](src/game/quests-ui.js), W07-gated mobs [src/game/npc/mobs.js](src/game/npc/mobs.js). Server: quest engine [multiplayer/src/quests.js](multiplayer/src/quests.js), quest zones [multiplayer/src/quest-zones.js](multiplayer/src/quest-zones.js), handlers in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W08 of the World Online program (program brief retired to git history). A deterministic nav graph drives client-side ambient pedestrians + ring-road traffic that read identically for every player without a single packet; real gameplay stays server-authoritative. Five quest-giver NPCs (Dockmaster Reyes, Warden Okoro, Cook Mara, Foreman Dell, The Fixer) front the jobs board the quest engine (W05) already ran server-side but no client ever reached; pressing E opens the real board, accepting a job drops a waypoint at its objective (goto zones auto-complete by walking there, interact zones get their own "press E"), and finishing pays real cash server-side. Hostile mobs are live: W07's `CombatSystem` ([src/game/combat-system.js](src/game/combat-system.js)) installs the `window.twsCombat` contract this module's mobs were built against, so `MobSystem` renders real server-authoritative PvE hostiles with zero changes here. Two jobs; `cross-town-delivery` (North↔South) and `east-west-express` (East↔West); are real driving missions: each `goto` leg is flagged `vehicle: true` and only completes off the authoritative vehicle-driver map ([multiplayer/src/vehicles.js](multiplayer/src/vehicles.js)), so walking through a depot never counts, only driving through it does. Depots sit on the avenue vehicle spawns, so a car is always parked at the start. Tests: [tests/quests-vehicle-delivery.test.js](tests/quests-vehicle-delivery.test.js). |
| Frame governor & power saver (`/play`, `/club`, `/walk`) | [src/shared/frame-governor.js](src/shared/frame-governor.js), wired in [src/game/coincommunities.js](src/game/coincommunities.js), [src/club.js](src/club.js), [src/club-entrance.js](src/club-entrance.js), [src/walk.js](src/walk.js); toggle UI in [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) | Live | Shared frame-rate governor for the heavy 3D surfaces: 60fps while active, 30fps when idle or unfocused, plus a user-facing Power-saver mode (30fps + lighter rendering, "for a cooler, quieter machine") persisted in localStorage `tws-power-saver` and shared across surfaces (`getPowerSaver`/`setPowerSaver`/`onPowerSaverChange`, `trackWindowFocus`). Tests: [tests/frame-governor.test.js](tests/frame-governor.test.js) |
| Cinematic rendering (shared 3D quality bar) | [src/shared/cinematic-render.js](src/shared/cinematic-render.js) — `applyCinematicDefaults()`, `loadEnvironment()`, `detectQualityTier()`, `updateGroundContactShadow()`; curated HDRIs in [public/hdri/](public/hdri) (CC0, Poly Haven) | Live, wired into every three.js viewer on the platform (`/irl`, talk mode, `/play`, `/club`, `/ar`, `/xr`, `/walk`, `/coin3d`, marketplace lobby, demo pages, the `<agent-3d>`/`<page-agent>` embeds, and more) | One module every WebGLRenderer-based viewer calls into instead of re-deriving ACES tone mapping, sRGB output color space, HDRI image-based lighting, and soft VSM shadows per file. `detectQualityTier()` picks high/medium/mobile from real device signals and caps pixel ratio + disables shadows/HDRI accordingly; `loadEnvironment()` fetches a real photographic HDRI (`studio`/`outdoor`/`sunset`) and falls back to a procedural room environment on mobile tier or fetch failure (including cross-origin embed contexts where the absolute `/hdri/*.hdr` URL can't resolve). `/walk` keeps its own richer per-biome HDR system ([src/walk-environments.js](src/walk-environments.js)); surfaces already running a postprocessing tone-mapping pass (`/oracle-graph`, `/club-entrance`) only take the sRGB/HDRI half to avoid double-applying the curve. |
| `/play` Wheel of Fortune (Fortune's Folly; free/paid $THREE spins) | Client: [src/game/wheel-station.js](src/game/wheel-station.js) (the plaza landmark, proximity prompt, `E` to spin; lazy-imports the actual UI on first interact), spin UI [src/game/spin-wheel-ui.js](src/game/spin-wheel-ui.js) (20-segment wheel, free/paid flow, wallet signing). Server: [multiplayer/src/spin-wheel.js](multiplayer/src/spin-wheel.js) (paytable, RNG, level/cooldown/pack gates, handlers), split-payment settlement [multiplayer/src/game-token.js](multiplayer/src/game-token.js) (`buildSpinPayment`/`verifySpinPayment`; the same primitives the $THREE boutique uses), wheel location [multiplayer/src/world-features.js](multiplayer/src/world-features.js) `WHEEL`, persisted cooldown field in [multiplayer/src/economy.js](multiplayer/src/economy.js), handlers wired in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W09 of the World Online program (program brief retired to git history). Walk up to the wheel in the plaza and press `E`: one free spin every 12h (a real persisted cooldown; survives a disconnect, unlike the ephemeral per-action cooldowns everything else on this row's neighbors use), or pay $3 in `$THREE`; split 50% to the holder-rewards pool / 50% to the treasury, verified on-chain before any prize is granted, mirroring the boutique's proven settlement pattern exactly. Gated behind an average skill level of 3 (a light anti-farm floor, not a grind) and never lets a won prize get lost to a full pack; room for at least one possible item prize is checked before a spin is even offered, paid or free. All 20 wedges are equal-odds by design, matching the client's fixed-angle wheel rendering exactly (see the header note in `spin-wheel.js` on why that must never drift). Tests: [tests/spin-wheel.test.js](tests/spin-wheel.test.js). |
| `/play` event countdown (lobby banner + in-world pill) | Self-attaching module [src/game/event-countdown.js](src/game/event-countdown.js) loaded by [pages/play.html](pages/play.html); config [public/event.json](public/event.json) (single source of the event window; the file is the edit surface for scheduling an event). Campaign pack: [prompts/event/](prompts/event/) | In-repo | While `public/event.json` describes an upcoming or live event, the lobby shows a banner (name, tagline, local-time start, ticking countdown, CTA into the event world) and the in-world view gets a dismissible top-center pill (dismissal persisted per event in localStorage). Three explicit states: upcoming, live (pulsing marker, CTA suppressed when already standing in the event world), and over (everything unmounts, the interval stops). Zero edits to `coincommunities*.js` by design (the ambient-crowd pattern): it waits for the lobby DOM and mounts nothing when the config is missing, malformed, or expired. |
-| `/play` friends & presence (drawer, cross-world DMs) | Client: [src/game/friends-panel.js](src/game/friends-panel.js) (shared with `/walk`), mounted in [src/game/coincommunities.js](src/game/coincommunities.js) `_openFriends()`/`_closeFriends()`, HUD button + unread badge in [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js), account-level state/polling in [src/friends.js](src/friends.js). Server: signed ticket verify + `socialHub` registration in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js), hub in [multiplayer/src/social-hub.js](multiplayer/src/social-hub.js) | In-repo | W09 of the World Online program (program brief retired to git history). Press `J` or the HUD `Friends` button to open a right-docked drawer showing your account's friend graph; live online/offline presence per coin world, requests, and DM threads; the same graph and threads `/walk` and the standalone `/friends` page already share. `community-net.js` now carries a signed presence ticket into every `walk_world` join and forwards the server's `social` push onto its own event bus, which is what actually makes a `/play` player visible to friends and able to receive a live DM; previously `/play` joined anonymously to the social graph even when signed in, so every player showed offline and DMs were dropped. Tests: [tests/play-friends-presence.test.js](tests/play-friends-presence.test.js). |
+| `/play` friends, presence & verified profiles (drawer, cross-world DMs, in-world profile cards) | Client: [src/game/friends-panel.js](src/game/friends-panel.js) (shared with `/walk`), mounted in [src/game/coincommunities.js](src/game/coincommunities.js) `_openFriends()`/`_closeFriends()`, HUD button + unread badge in [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js), account-level state/polling in [src/friends.js](src/friends.js), profile card in the shared inspector [src/shared/avatar-inspector.js](src/shared/avatar-inspector.js) (`renderProfile`). Server: signed ticket verify + `socialHub` registration + verified `username` on the Player schema in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) + [multiplayer/src/schemas.js](multiplayer/src/schemas.js), ticket signer [api/_lib/presence-store.js](api/_lib/presence-store.js) / verifier [multiplayer/src/presence-token.js](multiplayer/src/presence-token.js), hub in [multiplayer/src/social-hub.js](multiplayer/src/social-hub.js) | In-repo | W09+W10 of the World Online program (program brief retired to git history). Press `J` or the HUD `Friends` button to open a right-docked drawer showing your account's friend graph; live online/offline presence per coin world, requests, and DM threads; the same graph and threads `/walk` and the standalone `/friends` page already share. `community-net.js` carries a signed presence ticket into every `walk_world` join and forwards the server's `social` push onto its own event bus, which is what makes a `/play` player visible to friends and able to receive a live DM. W10 makes the platform identity first-class in-world: the ticket also carries the account's username + display name (signed, so nobody can wear a handle they don't own), WalkRoom publishes the verified `username` on the Player schema, nameplates show the @handle, the signed-in lobby defaults to the account's display name with an @handle chip, and clicking any verified player (or `I`) opens their real three.ws profile card in the shared avatar inspector: bio, follower counts, follow/unfollow (`/api/users/:username/follow`), the right friends verb (Message → the in-world DM drawer when already friends, Add friend / Accept otherwise), their latest creations, and a link to `/u/<username>`. Works identically in `/walk` (same room, same inspector). Tests: [tests/play-friends-presence.test.js](tests/play-friends-presence.test.js), [tests/play-profile-identity.test.js](tests/play-profile-identity.test.js). |
| Crew HQ (crews, tags, 3D presence room) | Page [pages/crews.html](pages/crews.html) + [src/crews-page.js](src/crews-page.js) + [src/crews.css](src/crews.css) `→ /crews` and `/crews/<TAG>`, data layer [api/_lib/crews-store.js](api/_lib/crews-store.js), endpoints [api/crews/](api/crews) (`index.js`, `[tag].js`, `search.js`, `directory.js`), presence [api/_lib/presence-store.js](api/_lib/presence-store.js), schema `api/_lib/migrations/2026-06-05-crews.sql` | Live | The group half of the social system: a crew is a set of accounts flying one 2-6 character tag, with one owner, one crew per account, and a public headquarters. The HQ renders the roster as a room rather than a list, each member standing as their own agent's 3D avatar (resolved by `standeesFor()`, private models never emitted) and lit by the same Redis presence the friends drawer reads. Crew colour is an FNV-1a hash of the tag, so a crew looks like itself everywhere without stored art. Live `<agent-3d>` figures are capped and lazily mounted so a large crew cannot exhaust the browser's WebGL contexts. The backend shipped with W09 and had no UI at all until this page; the in-world friends drawer now links to it. Docs: [docs/crews.md](docs/crews.md). Tests: [tests/crews-shared.test.js](tests/crews-shared.test.js), [tests/crews-wiring.test.js](tests/crews-wiring.test.js) |
| `/play` Robinhood Chain worlds (NOXA + The Odyssey coins, live-trade animation) | Firehose worker [workers/robinhood-feed/](workers/robinhood-feed) (watches NOXA + Odyssey launchpads + their Uniswap v3 pools, normalizes to the pump-compatible event shape, serves SSE/WS/REST). API bridge: [api/robinhood/coin-trades.js](api/robinhood/coin-trades.js) (the in-world chart-screen's trade feed), [api/robinhood/play-worlds.js](api/robinhood/play-worlds.js) (the `/worlds` lobby's Robinhood Chain tab). Client: chain-flavored biome `hoodchain` in [src/game/world-env.js](src/game/world-env.js) (auto-pinned in [src/game/coincommunities.js](src/game/coincommunities.js) `isRobinhoodCoin()`), trade-feed endpoint routing in [src/game/chart-screen.js](src/game/chart-screen.js), lobby tab + EVM-address support in [src/worlds-lobby.js](src/worlds-lobby.js) (routes Robinhood coins to `/play`, unchanged pump.fun coins stay on `/temporary`) | In-repo | Every Robinhood Chain memecoin (chain 4663) gets the same treatment pump.fun coins already have: a deterministic 3D world seeded by its contract address, in a distinct dark ticker-tape palette, with real launchpad/Uniswap-v3 trades rippling the space live via `MarketReactor`. Multiplayer (`walk_world`, filtered by `coin`+`tier`) needed zero code changes — it already keys rooms by an opaque coin id string. `isValidToken()` in [api/_lib/coin-communities.js](api/_lib/coin-communities.js) was widened to accept EVM addresses (it previously 400'd every EVM-chain world's Town chat, even though the CHAINS list already declared ethereum/base/bsc support). Tests: [workers/robinhood-feed/tests/normalize.test.js](workers/robinhood-feed/tests/normalize.test.js) (against real captured on-chain logs). |
| Sealed wallet gift drops (send/claim) | Client: [src/pages/sealed-drops.js](src/pages/sealed-drops.js) — create + "My drops" sections mounted into [public/vanity-wallet.html](public/vanity-wallet.html) (`#drop-create`/`#drop-mine`, below the vanity grinder — vanity pattern fields are shared), claim flow on its own page [pages/drop.html](pages/drop.html) `→ /drop/:id` (24-hex-char id, routed in [vite.config.js](vite.config.js) dev middleware + [vercel.json](vercel.json)). Crypto: [src/solana/vanity/sealed-envelope.js](src/solana/vanity/sealed-envelope.js) (ECIES seal/open, X25519 keygen — all client-side, three.ws never sees a plaintext key), [src/solana/vanity/drop-protocol.js](src/solana/vanity/drop-protocol.js) (claim-token derivation). Server: [api/vanity/drops.js](api/vanity/drops.js) (create/claim/reveal/reclaim, on-chain funding), OG card [api/og/sealed-drop.js](api/og/sealed-drop.js) | In-repo | Fund a fresh wallet — optionally vanity-ground with the same prefix/suffix grinder above — wrap it in a sealed link, and send it. Two seal modes: a **bearer link** (the claim key rides in the URL fragment, anyone with the full link claims once) or **sealed to a recipient's X25519 key** (only they can ever open it, even with the link). The create fee settles via x402; the gift amount funds on-chain into a fresh wallet server-side. Claiming decrypts entirely in the browser and offers the recovered seed phrase/secret key for import — the server only ever sees the sealed ciphertext. "My drops" (browser-local, by a random sender tag) lists what you've sent so expired-unclaimed gifts can be reclaimed. |
diff --git a/api/_lib/feed.js b/api/_lib/feed.js
index 4bb513a58..f245dabbe 100644
--- a/api/_lib/feed.js
+++ b/api/_lib/feed.js
@@ -27,6 +27,7 @@
// world-join → { coin, coinName }
// jackpot → { reward, coin }
// mission-complete → { mission, gold, coop, coin } — /play job or heist finished
+// war-result → { winner, reason, a, b, matchKey, network } — a Coin Wars battle ended; actor is the winning community
// agora-registered → { citizenId, agentPda, profession, narrative } — a citizen joined Agora (AgenC registerAgent)
// agora-task-posted → { actor, taskPda, profession, rewardLabel, minReputation, cluster } — a bounty was escrowed on the board (createTask)
// agora-hired → { actor, taskPda, profession, rewardLabel, cluster } — a citizen hired a sub-agent (agent-to-agent)
@@ -62,6 +63,7 @@ export const ALLOWED_TYPES = new Set([
'mission-complete', // /play job or co-op heist finished; { mission, gold, coop, coin }
'member-join', // a person signed in to three.ws; { handle } (actor = display name)
'agent-guard', // an autonomous buy was REFUSED by a safety rule; { agentId, mint, reason, label } — trust made visible
+ 'war-result', // a Coin Wars battle ended; { winner, reason, a:{mint,name,symbol,score}, b:{…}, matchKey, network }
// Agora — the living agent economy (workers/agora-citizens). Each is a real
// on-chain AgenC action projected onto the ticker; see docs/agora.md.
'agora-registered', // a citizen registered on AgenC
diff --git a/api/_lib/pump-search.js b/api/_lib/pump-search.js
index a41b53174..ba8ffd6b6 100644
--- a/api/_lib/pump-search.js
+++ b/api/_lib/pump-search.js
@@ -12,7 +12,7 @@
// (returns null) on either source's failure; the caller decides what an
// all-null result means.
//
-// Response item shape: { mint, symbol, name, logo, price_usd, rank }
+// Response item shape: { mint, symbol, name, logo, price_usd, usd_market_cap, rank }
import { normalizeGatewayURL } from '../../src/ipfs.js';
@@ -48,6 +48,7 @@ export async function searchBirdeye(q, limit) {
name: t.name || t.symbol || '',
logo: t.logo_uri || t.logoURI || null,
price_usd: typeof t.price === 'number' ? t.price : null,
+ usd_market_cap: typeof t.marketcap === 'number' ? t.marketcap : (typeof t.market_cap === 'number' ? t.market_cap : null),
rank: null,
}))
.filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
@@ -84,6 +85,7 @@ export async function searchPumpFun(q, limit) {
name: c.name || c.symbol || '',
logo: normalizeGatewayURL(c.image_uri || c.image || '') || null,
price_usd: null,
+ usd_market_cap: typeof c.usd_market_cap === 'number' ? c.usd_market_cap : null,
rank: i + 1,
}))
.filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
diff --git a/api/_lib/pump-trending.js b/api/_lib/pump-trending.js
index 376329192..29e6379fb 100644
--- a/api/_lib/pump-trending.js
+++ b/api/_lib/pump-trending.js
@@ -1,8 +1,8 @@
-// Shared "trending tokens" fetch + cache — the thin
-// { mint, symbol, name, logo, price_usd, rank } projection used by every free
-// trending consumer: GET /api/pump/trending (home card, communities,
-// constellation, dashboard chart picker) and the free GET /api/v1/pump/trending.
-// One fetch+cache+fallback path, two doors.
+// Shared "trending tokens" fetch + cache: the thin
+// { mint, symbol, name, logo, price_usd, usd_market_cap, rank } projection used
+// by every free trending consumer: GET /api/pump/trending (home card,
+// communities, constellation, dashboard chart picker) and the free
+// GET /api/v1/pump/trending. One fetch+cache+fallback path, two doors.
//
// Primary source is Birdeye (BIRDEYE_API_KEY, kept server-side). When Birdeye is
// unconfigured, rate-limited, or down, falls back to pump.fun's public frontend
@@ -88,6 +88,7 @@ async function fetchBirdeye(limit) {
name: t.name || t.symbol || '',
logo: t.logoURI || null,
price_usd: typeof t.price === 'number' ? t.price : null,
+ usd_market_cap: typeof t.marketcap === 'number' ? t.marketcap : null,
rank: typeof t.rank === 'number' ? t.rank : null,
}))
.filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
@@ -121,6 +122,7 @@ async function fetchPumpFun(limit) {
name: c.name || c.symbol || '',
logo: normalizeGatewayURL(c.image_uri || c.image || '') || null,
price_usd: null,
+ usd_market_cap: typeof c.usd_market_cap === 'number' ? c.usd_market_cap : null,
rank: i + 1,
}))
.filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
@@ -131,8 +133,8 @@ async function fetchPumpFun(limit) {
// pump.fun launch continuously (thousands of rows per hour), so when both
// external feeds are down or egress-blocked, the platform's own database still
// knows what is moving. Most-bought coins observed in the last 6 hours, mapped
-// to the same slim shape. price_usd stays null (the recorder stores lamport
-// flows, not USD quotes) — same contract as the pump.fun rung.
+// to the same slim shape. price_usd and usd_market_cap stay null (the recorder
+// stores lamport flows, not USD quotes), the same contract as the pump.fun rung.
async function fetchDbTrending(limit) {
try {
const rows = await sql`
@@ -149,6 +151,7 @@ async function fetchDbTrending(limit) {
name: r.name || r.symbol || '',
logo: normalizeGatewayURL(r.image_uri || '') || null,
price_usd: null,
+ usd_market_cap: null,
rank: i + 1,
}))
.filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.js
index 04db12a6e..0ef1d239b 100644
--- a/api/_lib/solana/connection.js
+++ b/api/_lib/solana/connection.js
@@ -960,6 +960,23 @@ export function shouldRotate(status) {
);
}
+// True when an error is the RPC *infrastructure* failing rather than the caller
+// asking for something impossible: a provider rate-limit/quota (429, -32429
+// "max usage reached"), a gateway 5xx, a network blip, or the whole lane chain
+// running out (`all solana rpc endpoints failed`, thrown by makeRotatingFetch
+// above once every endpoint has refused one request).
+//
+// Callers use this to tell "the chain says no" from "we could not ask". The
+// distinction is load-bearing on money surfaces: on 2026-08-07 every Solana
+// lane was cooling at once, and the treasury top-up cron turned that into a
+// hard 500 while the wallet audit turned it into four fake below-floor
+// emergencies. Neither was a code fault, and neither was a funding fact.
+export function isTransientRpcError(err) {
+ return /\b(429|500|502|503|504)\b|-32429|max usage reached|rate.?limit|quota|exhausted|timed?\s*out|fetch failed|socket hang up|ECONNRESET|ETIMEDOUT|ECONNREFUSED|EAI_AGAIN|all solana rpc endpoints failed|all rpc endpoints exhausted/i.test(
+ String(err && err.message ? err.message : err),
+ );
+}
+
// Rotating fetch backing a Connection. It NEVER surfaces a rotate-worthy status
// (401/403/429/5xx) to @solana/web3.js — it either returns a healthy response or
// throws — so web3.js's internal 429 backoff loop ("Server responded with 429 …
diff --git a/api/_lib/solana/sdk-bridge.js b/api/_lib/solana/sdk-bridge.js
index e24674fae..bd3c3013e 100644
--- a/api/_lib/solana/sdk-bridge.js
+++ b/api/_lib/solana/sdk-bridge.js
@@ -6,6 +6,7 @@
// without try/catch boilerplate.
import { PublicKey } from '@solana/web3.js';
+import { isTransientRpcError } from './connection.js';
let _sdkPromise = null;
async function loadSdk() {
@@ -41,11 +42,9 @@ function isMissingAccount(err) {
// Jupiter price. Re-warning on every swallowed 429 here is what turned one
// quota-exhausted provider into thousands of duplicate "[sdk-bridge] … 429"
// lines. Stay quiet for these; genuine parse/programming errors still warn.
-function isTransientRpc(err) {
- return /\b(429|500|502|503|504)\b|-32429|max usage reached|rate.?limit|quota|exhausted|timed?\s*out|fetch failed|socket hang up|ECONNRESET|ETIMEDOUT|ECONNREFUSED|EAI_AGAIN|all solana rpc endpoints failed|all rpc endpoints exhausted/i.test(
- String(err && err.message ? err.message : err),
- );
-}
+// The test itself lives with the lane manager, so every caller that has to tell
+// "the chain says no" from "we could not ask" shares one definition.
+const isTransientRpc = isTransientRpcError;
async function fetchState(connection, mint) {
const { OnlinePumpSdk } = await loadSdk();
diff --git a/api/_lib/war-store.js b/api/_lib/war-store.js
deleted file mode 100644
index e210b0a2f..000000000
--- a/api/_lib/war-store.js
+++ /dev/null
@@ -1,339 +0,0 @@
-// Coin Wars — persistence for the war league.
-//
-// Three small stores behind one module, all keyed off the coin mint that a
-// community fights under:
-//
-// 1. The BATTLE LEDGER — every finished clash, appended by the game server
-// (multiplayer/src/rooms/ClashRoom.js → war-report.js → POST /api/wars).
-// The Elo standings are recomputed from this list on every read with the
-// shared math in multiplayer/src/war-standings.js, so there is exactly one
-// implementation of "who is winning the war" and nothing to keep in sync.
-// 2. The LIVE REGISTRY — a short-TTL snapshot of every clash currently in
-// progress, refreshed by the room itself. This is what lets a player
-// standing in a coin's world watch a war they are not in without opening a
-// second 3D client.
-// 3. The MATCHMAKING QUEUE — communities waiting for an opponent. Pairing two
-// of them mints the `matchKey` that Colyseus's filterBy(['matchKey']) uses
-// to seat both sides in the same ClashRoom instance.
-//
-// Storage is Upstash Redis, with an in-process fallback that has the same
-// semantics so the whole feature is playable on a laptop with no infra (the
-// pattern clash-store.js established, for the same reason: a Redis blip must
-// degrade the league, never 5xx the world).
-
-import { getRedis } from './redis.js';
-
-const redis = getRedis();
-
-const K = {
- ledger: 'wars:ledger', // capped LIST of battle JSON, newest first
- live: 'wars:live', // HASH matchKey → live-war JSON (self-expiring by field)
- queue: 'wars:queue', // HASH mint → queued-community JSON
- pairing: 'wars:pair', // HASH `${mint}:${wallet}` → pairing JSON
-};
-
-// How many finished battles the ledger keeps. Elo is path-dependent, so a
-// truncated ledger re-bases ratings on the window it can see; 1000 battles is
-// far more history than the standings board ever shows and keeps the recompute
-// on a single Redis read.
-const LEDGER_MAX = 1000;
-
-// A live-war snapshot is stale this long after its last heartbeat. ClashRoom
-// beats every 10s while a match is alive, so three missed beats retire it — a
-// crashed game server can never leave a phantom war on the portal board.
-export const LIVE_TTL_MS = 35_000;
-
-// A community waits this long for an opponent before the queue forgets it. Long
-// enough to walk to the portal and read the board, short enough that a stale
-// entry never pairs someone who has closed the tab.
-export const QUEUE_TTL_MS = 180_000;
-
-// A minted pairing waits this long to be collected by the side that was already
-// queued. Comfortably longer than one poll interval and shorter than the queue
-// window, so a collected pairing is always fresher than a re-queue.
-export const PAIRING_TTL_MS = 120_000;
-
-let _degradedAt = 0;
-function degraded(err) {
- const now = Date.now();
- if (now - _degradedAt > 60_000) {
- _degradedAt = now;
- console.warn('[war-store] redis degraded — serving from in-memory fallback:', err?.message || err);
- }
-}
-
-// ─── In-memory fallback (dev / tests / Redis outage) ─────────────────────────
-
-const mem = {
- ledger: [],
- live: new Map(),
- queue: new Map(),
- pairing: new Map(),
-};
-
-function memHashPrune(map, ttlMs) {
- const now = Date.now();
- for (const [k, v] of map) if (!v || now - (v.at || 0) > ttlMs) map.delete(k);
- return map;
-}
-
-// ─── Battle ledger ───────────────────────────────────────────────────────────
-
-/**
- * Append one finished battle. Returns true when it landed durably, false when it
- * only reached the in-process fallback — the caller reports that honestly rather
- * than claiming a league write it did not make.
- * @param {object} battle the shape ClashMatch.result() emits, plus matchKey/network
- */
-export async function appendBattle(battle) {
- mem.ledger.unshift(battle);
- if (mem.ledger.length > LEDGER_MAX) mem.ledger.length = LEDGER_MAX;
- if (!redis) return false;
- try {
- await redis.lpush(K.ledger, JSON.stringify(battle));
- await redis.ltrim(K.ledger, 0, LEDGER_MAX - 1);
- return true;
- } catch (err) {
- degraded(err);
- return false;
- }
-}
-
-/**
- * The battle ledger, newest first. `limit` bounds the read; the standings
- * recompute wants the whole window, a "recent results" board wants a handful.
- * @returns {Promise<object[]>}
- */
-export async function listBattles(limit = LEDGER_MAX) {
- const n = Math.max(1, Math.min(LEDGER_MAX, limit | 0 || LEDGER_MAX));
- if (redis) {
- try {
- const raw = await redis.lrange(K.ledger, 0, n - 1);
- return (raw || []).map(parseMaybe).filter(Boolean);
- } catch (err) {
- degraded(err);
- }
- }
- return mem.ledger.slice(0, n);
-}
-
-// ─── Live registry ───────────────────────────────────────────────────────────
-
-/**
- * Publish (or refresh) the live snapshot of one clash. `war` carries the two
- * factions, the score, the phase and the clock — everything the portal board
- * renders. Stamped with `at` so readers can retire it without a per-key TTL.
- */
-export async function putLiveWar(war) {
- const record = { ...war, at: Date.now() };
- mem.live.set(record.matchKey, record);
- memHashPrune(mem.live, LIVE_TTL_MS);
- if (!redis) return false;
- try {
- await redis.hset(K.live, { [record.matchKey]: JSON.stringify(record) });
- // The hash itself expires if the game server goes away entirely, so a dead
- // deployment cannot leave a permanent key behind.
- await redis.expire(K.live, Math.ceil((LIVE_TTL_MS * 6) / 1000));
- return true;
- } catch (err) {
- degraded(err);
- return false;
- }
-}
-
-/** Retire one live war (the match ended, or the room disposed). Idempotent. */
-export async function dropLiveWar(matchKey) {
- mem.live.delete(matchKey);
- if (!redis) return;
- try {
- await redis.hdel(K.live, matchKey);
- } catch (err) {
- degraded(err);
- }
-}
-
-/**
- * Every clash currently in progress, freshest first. Stale entries (no heartbeat
- * within LIVE_TTL_MS) are dropped from the result AND swept from the hash, so a
- * crashed room self-cleans on the next read instead of needing a cron.
- * @returns {Promise<object[]>}
- */
-export async function listLiveWars() {
- const now = Date.now();
- if (redis) {
- try {
- const all = (await redis.hgetall(K.live)) || {};
- const live = [];
- const stale = [];
- for (const [key, value] of Object.entries(all)) {
- const war = parseMaybe(value);
- if (!war || now - (war.at || 0) > LIVE_TTL_MS) stale.push(key);
- else live.push(war);
- }
- if (stale.length) await redis.hdel(K.live, ...stale).catch(() => {});
- return live.sort((a, b) => (b.at || 0) - (a.at || 0));
- } catch (err) {
- degraded(err);
- }
- }
- memHashPrune(mem.live, LIVE_TTL_MS);
- return [...mem.live.values()].sort((a, b) => (b.at || 0) - (a.at || 0));
-}
-
-// ─── Matchmaking queue ───────────────────────────────────────────────────────
-
-/**
- * The communities currently waiting for an opponent, freshest first. Expired
- * entries are swept on read for the same reason the live registry sweeps.
- * @returns {Promise<object[]>}
- */
-export async function listQueue() {
- const now = Date.now();
- if (redis) {
- try {
- const all = (await redis.hgetall(K.queue)) || {};
- const waiting = [];
- const stale = [];
- for (const [mint, value] of Object.entries(all)) {
- const entry = parseMaybe(value);
- if (!entry || now - (entry.at || 0) > QUEUE_TTL_MS) stale.push(mint);
- else waiting.push(entry);
- }
- if (stale.length) await redis.hdel(K.queue, ...stale).catch(() => {});
- return waiting.sort((a, b) => (b.at || 0) - (a.at || 0));
- } catch (err) {
- degraded(err);
- }
- }
- memHashPrune(mem.queue, QUEUE_TTL_MS);
- return [...mem.queue.values()].sort((a, b) => (b.at || 0) - (a.at || 0));
-}
-
-/** Seat (or refresh) a community in the queue. */
-export async function enqueue(entry) {
- const record = { ...entry, at: Date.now() };
- mem.queue.set(record.mint, record);
- if (!redis) return record;
- try {
- await redis.hset(K.queue, { [record.mint]: JSON.stringify(record) });
- await redis.expire(K.queue, Math.ceil((QUEUE_TTL_MS * 4) / 1000));
- } catch (err) {
- degraded(err);
- }
- return record;
-}
-
-/**
- * Claim a waiting community out of the queue. The Redis HDEL reply IS the claim
- * token: exactly one concurrent caller sees a 1, so two players queueing at the
- * same instant can never both pair with the same opponent and end up in two
- * different rooms. Returns true when this caller won the claim.
- */
-export async function claimQueued(mint) {
- if (!redis) return mem.queue.delete(mint);
- try {
- const removed = await redis.hdel(K.queue, mint);
- mem.queue.delete(mint);
- return Number(removed) > 0;
- } catch (err) {
- degraded(err);
- return mem.queue.delete(mint);
- }
-}
-
-/** Drop a community from the queue (they walked away, or they just got paired). */
-export async function dequeue(mint) {
- mem.queue.delete(mint);
- if (!redis) return;
- try {
- await redis.hdel(K.queue, mint);
- } catch (err) {
- degraded(err);
- }
-}
-
-// ─── Pairings ────────────────────────────────────────────────────────────────
-//
-// When a fresh challenger pairs with a queued community, only the challenger's
-// request knows the minted matchKey. The queued side is not holding an open
-// request, so the pairing is parked here under their mint+wallet and collected
-// by their next poll. That keeps matchmaking to two plain reads instead of a
-// socket the portal would have to hold open while nobody is even near it.
-
-function pairKey(mint, wallet) {
- return `${mint}:${wallet}`;
-}
-
-export async function putPairing(mint, wallet, pairing) {
- const record = { ...pairing, at: Date.now() };
- mem.pairing.set(pairKey(mint, wallet), record);
- if (!redis) return record;
- try {
- await redis.hset(K.pairing, { [pairKey(mint, wallet)]: JSON.stringify(record) });
- await redis.expire(K.pairing, Math.ceil((PAIRING_TTL_MS * 4) / 1000));
- } catch (err) {
- degraded(err);
- }
- return record;
-}
-
-/**
- * Read the pairing waiting for this wallet, or null. Reads do NOT consume it: a
- * player who reloads mid-handoff must still find the war they were matched into.
- * It lapses on its own after PAIRING_TTL_MS.
- */
-export async function getPairing(mint, wallet) {
- const key = pairKey(mint, wallet);
- const now = Date.now();
- if (redis) {
- try {
- const raw = await redis.hget(K.pairing, key);
- const rec = parseMaybe(raw);
- if (!rec) return null;
- if (now - (rec.at || 0) > PAIRING_TTL_MS) {
- await redis.hdel(K.pairing, key).catch(() => {});
- return null;
- }
- return rec;
- } catch (err) {
- degraded(err);
- }
- }
- const rec = mem.pairing.get(key);
- if (!rec) return null;
- if (now - (rec.at || 0) > PAIRING_TTL_MS) { mem.pairing.delete(key); return null; }
- return rec;
-}
-
-export async function dropPairing(mint, wallet) {
- mem.pairing.delete(pairKey(mint, wallet));
- if (!redis) return;
- try {
- await redis.hdel(K.pairing, pairKey(mint, wallet));
- } catch (err) {
- degraded(err);
- }
-}
-
-// ─── internals ───────────────────────────────────────────────────────────────
-
-// Upstash decodes JSON string values for us on some paths and hands back the raw
-// string on others; accept both rather than guessing which one a given command
-// took.
-function parseMaybe(value) {
- if (value == null) return null;
- if (typeof value === 'object') return value;
- try {
- return JSON.parse(String(value));
- } catch {
- return null;
- }
-}
-
-/** Test seam: clear the in-process fallback between cases. */
-export function __resetWarStoreMemory() {
- mem.ledger.length = 0;
- mem.live.clear();
- mem.queue.clear();
- mem.pairing.clear();
-}
diff --git a/api/cron/treasury-topup.js b/api/cron/treasury-topup.js
index 5f50c39e3..1853baad4 100644
--- a/api/cron/treasury-topup.js
+++ b/api/cron/treasury-topup.js
@@ -50,7 +50,7 @@ export default wrapCron(async (req, res) => {
const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
const { PublicKey } = await import('@solana/web3.js');
- const { solanaConnection } = await import('../_lib/solana/connection.js');
+ const { solanaConnection, isTransientRpcError } = await import('../_lib/solana/connection.js');
const connection = solanaConnection({ url: rpcUrl, network: 'mainnet', commitment: 'confirmed' });
// Read every engine signer's balance; collect the ones under floor as refill
@@ -356,7 +356,39 @@ export default wrapCron(async (req, res) => {
}
}
- const result = await sweepTopUps({ connection, targets, network: 'mainnet', dryRun });
+ // The sweep is the only leg that both reads AND moves SOL, so it is the one
+ // that dies when every RPC lane is cooling at once. Letting it throw took the
+ // whole cron down with a 500 (2026-08-07: ~1 in 15 ticks) — and this cron IS
+ // the self-heal for a starved engine, so the outage disabled its own remedy
+ // exactly when the ring needed it. An exhausted lane chain is upstream
+ // weather, not a bug: report it as a skipped sweep the same way wrapCron
+ // reports an unavailable database, and let the next tick (30 min) retry with
+ // the reclaim, fuel, and USDC legs above already applied. A non-RPC failure
+ // is still a real defect and still throws.
+ let result;
+ try {
+ result = await sweepTopUps({ connection, targets, network: 'mainnet', dryRun });
+ } catch (e) {
+ if (!isTransientRpcError(e)) throw e;
+ const reason = e?.message || 'rpc_unavailable';
+ console.warn(`[cron] treasury-topup sweep skipped — solana rpc unavailable: ${reason}`);
+ return json(res, 200, {
+ ok: false,
+ reason: 'rpc_unavailable',
+ detail: reason,
+ dry_run: dryRun,
+ rpc: rpcUrl,
+ targets: targets.length,
+ swept: false,
+ reclaim,
+ agent_reclaim: agentReclaim,
+ fuel,
+ usdc_topup: usdcTopup,
+ master_aliased: masterAliased,
+ read_errors: errors,
+ run_id: runId,
+ });
+ }
if (dryRun) {
return json(res, 200, {
ok: true,
diff --git a/api/play/population.js b/api/play/population.js
index d56039cbe..6c3af2885 100644
--- a/api/play/population.js
+++ b/api/play/population.js
@@ -1,4 +1,4 @@
-// GET /api/play/population — how many people are standing in the /play worlds
+// GET /api/play/population: how many people are standing in the /play worlds
// right now.
//
// ?coin=<mint> narrow to one community's worlds (the /event landing page
diff --git a/api/pump/search.js b/api/pump/search.js
index ff4cbeae1..c6d032e27 100644
--- a/api/pump/search.js
+++ b/api/pump/search.js
@@ -10,7 +10,7 @@
// versioned /api/v1/pump/search endpoint so neither route forks the upstream
// logic. This handler adds the palette-specific process-local response cache.
//
-// Response: { data: [ { mint, symbol, name, logo, price_usd, rank } ] }
+// Response: { data: [ { mint, symbol, name, logo, price_usd, usd_market_cap, rank } ] }
import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
diff --git a/api/pump/trending.js b/api/pump/trending.js
index 47219e34c..39752fce2 100644
--- a/api/pump/trending.js
+++ b/api/pump/trending.js
@@ -8,7 +8,7 @@
// feed — same response shape — so the market surfaces degrade to live pump.fun
// data instead of a hard error. Only errors when both sources are unavailable.
//
-// Response: { data: [ { mint, symbol, name, logo, price_usd, rank } ] }
+// Response: { data: [ { mint, symbol, name, logo, price_usd, usd_market_cap, rank } ] }
import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
diff --git a/avatar-sdk/src/viewer.js b/avatar-sdk/src/viewer.js
index c14a333f3..262065837 100644
--- a/avatar-sdk/src/viewer.js
+++ b/avatar-sdk/src/viewer.js
@@ -75,8 +75,8 @@ function getDracoLoader() {
let _hdriPromise = null;
function getHdriTexture() {
if (!_hdriPromise) {
- _hdriPromise = import('three/addons/loaders/RGBELoader.js').then(({ RGBELoader }) =>
- new RGBELoader().loadAsync(`${AR_LAUNCH_ORIGIN}/hdri/studio.hdr`),
+ _hdriPromise = import('three/addons/loaders/HDRLoader.js').then(({ HDRLoader }) =>
+ new HDRLoader().loadAsync(`${AR_LAUNCH_ORIGIN}/hdri/studio.hdr`),
);
}
return _hdriPromise;
diff --git a/data/changelog.json b/data/changelog.json
index 865cb51ef..a6eb0e2ff 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-07",
+ "title": "The event countdown is now on the front page",
+ "summary": "You no longer have to open Play to find out when the next live community event starts. The three.ws home page now carries a slim strip above the hero with the event name, the start time in your own timezone, and a countdown ticking down to the second. The moment the event begins it switches to LIVE on its own, without a refresh, and it takes itself off the page once the event is over. One click on it drops you straight into the $THREE world. If you would rather not see it, dismiss it once and it stays gone, in Play as well as on the home page. Every countdown surface across the site reads the same event schedule, so they can never disagree about when things start.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/"
+ },
{
"date": "2026-08-07",
"title": "Meet real people in Play: profiles, follows, and DMs in-world",
@@ -22,7 +31,7 @@
{
"date": "2026-08-07",
"title": "Play now counts down to the next community event",
- "summary": "The Play lobby shows a live banner for the upcoming $THREE Community Day: the event name, when it starts in your own timezone, and a ticking countdown. Once you are inside a world, a small dismissible reminder pill keeps the countdown in view, and when the event goes live both switch to a LIVE marker with a one-click jump into the $THREE world. After the event ends everything quietly disappears on its own.",
+ "summary": "The Play lobby shows a live banner for the upcoming $THREE First Holders Meetup: the event name, when it starts in your own timezone, and a ticking countdown. Once you are inside a world, a small dismissible reminder pill keeps the countdown in view, and when the event goes live both switch to a LIVE marker with a one-click jump into the $THREE world. After the event ends everything quietly disappears on its own.",
"tags": [
"feature"
],
diff --git a/data/pages.json b/data/pages.json
index 5443d96f1..26f9488a6 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -2104,7 +2104,7 @@
{
"path": "/event",
"title": "Live event",
- "description": "The live three.ws community meetup: when it starts, what is on the agenda, who is in the world right now, and the event leaderboard.",
+ "description": "The live three.ws community meetup: a ticking countdown off the same config /play reads, the run of show in your own timezone, an add-to-calendar file, who is in the world right now, and the one door in.",
"added": "2026-08-07",
"priority": 0.6,
"changefreq": "weekly"
diff --git a/docs/avatar-inspector.md b/docs/avatar-inspector.md
index 9b9d4e220..8112ad814 100644
--- a/docs/avatar-inspector.md
+++ b/docs/avatar-inspector.md
@@ -11,7 +11,7 @@ to the full profile.
| World | Open it with | Who you can inspect |
| --- | --- | --- |
-| `/play` (coin communities) | <kbd>I</kbd> nearest avatar · click a player's nameplate or body | Other players, townsperson NPCs, yourself |
+| `/play` (coin communities) | <kbd>I</kbd> nearest avatar · click a player's nameplate or body | Other players, townsperson NPCs, ambient citizens, yourself |
| `/temporary` coin worlds + `/marketplace-walk` | <kbd>I</kbd> nearest player · click a nameplate | Other players, yourself |
| `/city` | <kbd>I</kbd> · click your avatar | Yourself (single-player) — add `?agent=<agent-id>` and the inspector shows that agent's reputation and wallet alongside your session |
| `/agora` | <kbd>I</kbd> hovered/nearest citizen · click a citizen | Citizens — opens their existing [passport](/agora) with trust grade, stake, and earnings |
@@ -45,6 +45,27 @@ A guest with no wallet renders as exactly that — a designed empty state that
says what's missing and how to get it. A real $0 balance shows $0. Nothing is
ever fabricated.
+## Citizens: every walker in /play is someone
+
+The ambient crowd strolling a `/play` plaza wears real community avatars from
+the public gallery (`GET /api/avatars/public`), and most of those avatars
+represent a registered three.ws agent. The world keeps that identity: any
+walker wearing a named gallery avatar shows a nameplate, and clicking the
+nameplate or the body opens this same inspector as a **Citizen** card — the
+real agent's bio, trust score, and wallet, plus a **Talk 1-on-1** action that
+starts a live, streamed, in-character conversation (the same multi-model chat
+the townsperson NPCs use, grounded in the agent's actual public profile).
+While you talk, the citizen stops and faces you, then walks briskly back to
+the shared crowd schedule when you leave.
+
+Interactive townsfolk (the vendors, quest-givers, and clerks) are selectable
+from any distance too: tapped in range they run their role action as always;
+tapped from afar their profile card opens with a Talk action instead of
+nothing. Walkers wearing the bundled default avatar carry no identity and stay
+honest, anonymous scenery — no nameplate, no profile.
+
+The identity layer lives in [`src/game/npc/citizens.js`](../src/game/npc/citizens.js).
+
## For builders
The panel is one shared module: [`src/shared/avatar-inspector.js`](../src/shared/avatar-inspector.js).
diff --git a/multiplayer/deploy-cloudrun.sh b/multiplayer/deploy-cloudrun.sh
index 027f722bf..ae2364228 100755
--- a/multiplayer/deploy-cloudrun.sh
+++ b/multiplayer/deploy-cloudrun.sh
@@ -26,9 +26,17 @@ PROJECT="$(gcloud config get-value project 2>/dev/null)"
# CONCURRENCY is the # of simultaneous connections Cloud Run routes to ONE
# instance. The platform default is 80 — for a WebSocket server that is a hard
# ~80-player ceiling, so we raise it well above the per-instance comfort limit.
+#
+# CPU/MEMORY are the defaults a redeploy applies, so they are not merely a first
+# -deploy convenience: `gcloud run deploy` REPLACES the resource limits every
+# time. Raising them by hand on the live service (as event pre-scaling did on
+# 2026-08-07) survives exactly until the next deploy from this script, and a
+# mid-event hotfix that silently halves the world server's CPU is the worst
+# possible time to discover that. The defaults below are the event-day floor;
+# lower them here, not on the service.
CONCURRENCY="${CONCURRENCY:-1000}"
-CPU="${CPU:-2}"
-MEMORY="${MEMORY:-2Gi}"
+CPU="${CPU:-4}"
+MEMORY="${MEMORY:-8Gi}"
MIN_INSTANCES="${MIN_INSTANCES:-1}"
# Horizontal scaling: a Colyseus fleet only works when the room registry +
diff --git a/multiplayer/src/combat-handlers.js b/multiplayer/src/combat-handlers.js
index c6e121bad..b288a218a 100644
--- a/multiplayer/src/combat-handlers.js
+++ b/multiplayer/src/combat-handlers.js
@@ -21,7 +21,7 @@
// channels. Nothing here trusts a client-sent position, target or damage number.
import {
- addItem, hasRoomFor, removeItem, countItem, dropCarried, reviveProfile,
+ addItem, hasRoomFor, removeItem, countItem, dropCarried, reviveProfile, creditGold,
} from './economy.js';
import { weaponDef, mobStats, rollLoot, itemLabel } from './items.js';
import {
@@ -353,7 +353,7 @@ export function handleAttack(room, client) {
mob.state = 'dead';
const stats = mobStats(mob.kind);
room._grantXp(client, profile, 'combat', 8 + (stats?.xp || 0));
- if (stats?.gold) profile.gold += stats.gold;
+ if (stats?.gold) creditGold(profile, stats.gold);
const loot = rollLoot(mob.kind, Math.random);
spillTombstone(room, mob.x, mob.z, itemLabel(mob.kind), { gold: 0, items: loot });
room._sendInv(client, profile);
@@ -428,7 +428,7 @@ export function handleLoot(room, client, payload) {
// 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);
+ creditGold(profile, goldGained);
drop.gold = 0;
}
const gained = [];
diff --git a/multiplayer/src/cosmetics-catalog.js b/multiplayer/src/cosmetics-catalog.js
index 149373edf..ad2f60856 100644
--- a/multiplayer/src/cosmetics-catalog.js
+++ b/multiplayer/src/cosmetics-catalog.js
@@ -32,6 +32,14 @@ export const SLOT_LABELS = {
// (W04's shop grants it into the account's owned list). `price` is the $THREE
// cost the shop will charge — surfaced here so the wardrobe can show it, but W03
// never sells (it only exposes the unlock hook).
+//
+// A third tier, 'event', is a souvenir: it is GRANTED, never sold. The server
+// hands it to everyone present in the event world during the live window (see
+// multiplayer/src/event-drop.js and the join-time grant in WalkRoom), and after
+// the window closes it is simply never granted again. It carries price 0 and so
+// never appears in the boutique (shop.js filters on tier 'premium' AND price>0),
+// which is what keeps "you had to be there" honest: there is no purchase path,
+// before, during, or after. Like premium, it must be owned to be worn.
export const COSMETICS = [
// ── Body color (dye) ──────────────────────────────────────────────────────
{ id: 'dye-none', name: 'Natural', slot: 'dye', rarity: 'common', tier: 'free', price: 0, visual: null, swatch: '#d8d8e0' },
@@ -46,6 +54,7 @@ export const COSMETICS = [
{ id: 'hat-beanie', name: 'Beanie', slot: 'headwear', rarity: 'common', tier: 'free', price: 0, visual: { prop: '/accessories/hat-beanie.glb', anchor: 'head' }, thumb: '/accessories/thumbs/hat-beanie.png' },
{ id: 'hat-baseball', name: 'Ball cap', slot: 'headwear', rarity: 'common', tier: 'free', price: 0, visual: { prop: '/accessories/hat-baseball.glb', anchor: 'head' }, thumb: '/accessories/thumbs/hat-baseball.png' },
{ id: 'hat-cowboy', name: 'Stetson', slot: 'headwear', rarity: 'rare', tier: 'premium', price: 400, visual: { prop: '/accessories/hat-cowboy.glb', anchor: 'head' }, thumb: '/accessories/thumbs/hat-cowboy.png' },
+ { id: 'laurel-meetup', name: 'Meetup Laurel', slot: 'headwear', rarity: 'legendary', tier: 'event', price: 0, visual: { prop: '/accessories/laurel-meetup.glb', anchor: 'head' }, thumb: '/accessories/thumbs/laurel-meetup.png' },
// ── Eyewear (prop, anchored at the eye line) ──────────────────────────────
{ id: 'eye-none', name: 'None', slot: 'eyewear', rarity: 'common', tier: 'free', price: 0, visual: null },
@@ -87,6 +96,23 @@ export function isFreeCosmetic(id) {
return !!c && c.tier === 'free';
}
+// Is this id an event souvenir — granted for being somewhere at some time, never
+// purchasable? The grant path (event-drop.js → WalkRoom) checks this so a
+// misconfigured event can never hand out a boutique item for nothing, and the
+// wardrobe checks it so a locked souvenir offers no "buy it" shortcut.
+export function isEventCosmetic(id) {
+ const c = getCosmetic(id);
+ return !!c && c.tier === 'event';
+}
+
+// Is this id one an account has to explicitly own to wear (premium or event)?
+// The inverse of isFreeCosmetic for known ids — used by the persistence layer,
+// which must keep every unlocked id regardless of how it was unlocked.
+export function isUnlockableCosmetic(id) {
+ const c = getCosmetic(id);
+ return !!c && c.tier !== 'free';
+}
+
// Can `account` (an owned-id set, or array) wear `id`? Free cosmetics are always
// allowed; premium ones only when explicitly owned. Unknown ids are rejected.
export function canWear(id, owned) {
diff --git a/multiplayer/src/economy.js b/multiplayer/src/economy.js
index 925abfaf5..7f3ada4dd 100644
--- a/multiplayer/src/economy.js
+++ b/multiplayer/src/economy.js
@@ -19,6 +19,7 @@ import {
} from './items.js';
import {
DEFAULT_LOADOUT, SLOTS, getCosmetic, canWear, sanitizeLoadout, freeCosmeticIds,
+ isUnlockableCosmetic,
} from './cosmetics-catalog.js';
export const INV_SIZE = 24;
@@ -102,12 +103,15 @@ export function ownedCosmeticSet(profile) {
return owned;
}
-// Grant a premium cosmetic into an account's owned list (the W04 unlock hook:
-// the shop calls this after a $THREE payment settles). Idempotent; ignores free
-// or unknown ids. Returns true when it newly unlocked something.
+// Grant an unlockable cosmetic into an account's owned list. Two callers: the
+// W04 boutique after a $THREE payment settles (premium tier), and the event-drop
+// grant when a player is in the world during a live meetup (event tier).
+// Idempotent; ignores free or unknown ids — a free cosmetic is implicitly owned
+// and storing it would bloat every save with nothing. Returns true when it newly
+// unlocked something, so the caller can skip a persist that would change nothing.
export function grantCosmetic(profile, id) {
const c = getCosmetic(id);
- if (!c || c.tier !== 'premium') return false;
+ if (!c || !isUnlockableCosmetic(id)) return false;
if (!profile.cosmetics) profile.cosmetics = { owned: [], equipped: { ...DEFAULT_LOADOUT } };
if (!Array.isArray(profile.cosmetics.owned)) profile.cosmetics.owned = [];
if (profile.cosmetics.owned.includes(id)) return false;
@@ -122,10 +126,18 @@ export function grantCosmetic(profile, id) {
// rig can't render — those are ignored, never errored). Idempotent via
// grantCosmetic. Returns the count newly unlocked, so a caller can skip a persist
// when nothing changed.
+//
+// Deliberately PREMIUM-ONLY: this ledger records purchases, and an event
+// souvenir has no purchase path. Filtering here rather than relying on the
+// ledger's contents means a stray write on the x402 side can never mint a
+// "you had to be there" item for someone who wasn't.
export function mergeOwnedFromLedger(profile, ledgerIds) {
if (!Array.isArray(ledgerIds) || !ledgerIds.length) return 0;
let granted = 0;
- for (const id of ledgerIds) if (grantCosmetic(profile, id)) granted++;
+ for (const id of ledgerIds) {
+ if (getCosmetic(id)?.tier !== 'premium') continue;
+ if (grantCosmetic(profile, id)) granted++;
+ }
return granted;
}
@@ -157,8 +169,11 @@ export function restoreProfile(saved, playerId = '') {
if (Array.isArray(saved.inv)) fill(base.inv, saved.inv);
if (Array.isArray(saved.hotbar)) fill(base.hotbar, saved.hotbar);
if (Number.isFinite(saved.activeSlot)) base.activeSlot = Math.max(-1, Math.min(HOTBAR_SIZE - 1, saved.activeSlot | 0));
- if (Number.isFinite(saved.gold)) base.gold = Math.max(0, Math.min(0xffffffff, saved.gold | 0));
- if (Number.isFinite(saved.bank)) base.bank = Math.max(0, Math.min(0xffffffff, saved.bank | 0));
+ // Clamp BEFORE truncating: `| 0` is ToInt32, so applying it first wrapped any
+ // balance past 2^31 negative and then "clamped" it to zero, silently wiping
+ // the richest saves. Floor-then-clamp saturates at the ceiling instead.
+ if (Number.isFinite(saved.gold)) base.gold = Math.max(0, Math.min(0xffffffff, Math.floor(saved.gold)));
+ if (Number.isFinite(saved.bank)) base.bank = Math.max(0, Math.min(0xffffffff, Math.floor(saved.bank)));
if (Number.isFinite(saved.maxHp) && saved.maxHp > 0) base.maxHp = saved.maxHp | 0;
if (Number.isFinite(saved.hp)) base.hp = Math.max(0, Math.min(base.maxHp, saved.hp | 0));
if (Number.isFinite(saved.maxArmor) && saved.maxArmor > 0) base.maxArmor = saved.maxArmor | 0;
@@ -176,8 +191,11 @@ export function restoreProfile(saved, playerId = '') {
// then sanitize the equipped loadout against what this account may actually
// wear (drops anything unowned/renamed to the slot default).
if (saved.cosmetics && typeof saved.cosmetics === 'object') {
+ // Keep every unlockable tier, not just premium: an event souvenir has no
+ // re-grant path once its window closes, so dropping it here would silently
+ // destroy an item the owner can never get back.
const owned = Array.isArray(saved.cosmetics.owned)
- ? saved.cosmetics.owned.filter((id) => { const c = getCosmetic(id); return c && c.tier === 'premium'; })
+ ? saved.cosmetics.owned.filter((id) => isUnlockableCosmetic(id))
: [];
base.cosmetics.owned = [...new Set(owned)];
base.cosmetics.equipped = sanitizeLoadout(saved.cosmetics.equipped, ownedCosmeticSet(base));
@@ -387,6 +405,15 @@ export function dropCarried(profile) {
return { gold, items };
}
+// Saturating gold credit: every reward path adds through here so a balance can
+// approach the 32-bit ceiling but never exceed it (restoreProfile clamps to the
+// same ceiling, so nothing is ever lost to wraparound on reload).
+export function creditGold(profile, amount) {
+ const add = Number.isFinite(amount) ? Math.max(0, Math.floor(amount)) : 0;
+ profile.gold = Math.min(0xffffffff, (profile.gold || 0) + add);
+ return profile.gold;
+}
+
// Restore a player to fighting shape after respawn: full HP and a cleared armor bar
// (you lose your vest on death — re-armor from the pack or a vendor).
export function reviveProfile(profile) {
diff --git a/multiplayer/src/event-drop.js b/multiplayer/src/event-drop.js
new file mode 100644
index 000000000..7561ab192
--- /dev/null
+++ b/multiplayer/src/event-drop.js
@@ -0,0 +1,158 @@
+// Event souvenir drop — the server's read of /event.json.
+//
+// A live community event (the countdown pill, the in-world agenda, the fireworks
+// finale) is configured in ONE file: public/event.json on three.ws. This module
+// is the game server's view of that same file, so the window a player is judged
+// against is byte-for-byte the window they were shown a countdown to. Nothing
+// here duplicates the schedule; drift is impossible by construction.
+//
+// What it adds on top of the shared config is the souvenir: a free commemorative
+// wearable granted to everyone who is in the event world while the event is
+// live. The rules are deliberately narrow:
+//
+// • The window is [startsAt, endsAt) from the config. Before it, nothing is
+// granted. After it, nothing is granted, ever again — that is the whole
+// point of a souvenir, and there is no purchase path to soften it.
+// • The world must be the one the config's `link` points at (its `coin`
+// query param). Standing in an unrelated coin world during the window
+// earns nothing.
+// • The item must be a catalog cosmetic with tier 'event'. A config that
+// names a boutique item grants nothing rather than giving away a paid
+// cosmetic — a misconfiguration must not be able to devalue the shop.
+//
+// The server is a separate deployment from the site (its Docker image carries
+// only multiplayer/src), so the config arrives over HTTP from the same origin
+// the persistence layer already talks to. Reads are cached with a TTL, refreshed
+// in the background, and FAIL OPEN in the safe direction: an unreachable config
+// grants nothing and never blocks or slows a join.
+
+import { getCosmetic } from './cosmetics-catalog.js';
+
+const CONFIG_URL = process.env.EVENT_CONFIG_URL
+ || `${(process.env.WORLD_API_BASE || 'https://three.ws').replace(/\/$/, '')}/event.json`;
+
+// How long a fetched config is trusted before a refresh. Short enough that an
+// operator moving the event window is picked up within a couple of minutes,
+// long enough that a busy world isn't refetching per join.
+const TTL_MS = 120_000;
+// A failed fetch backs off for this long instead of retrying on every join.
+const ERROR_TTL_MS = 30_000;
+// The join path must never wait on the network. Anything slower than this is
+// treated as "no config yet"; the background refresh still completes and warms
+// the cache for the next arrival.
+const FETCH_TIMEOUT_MS = 3000;
+
+// Pull the coin mint out of the config's `link` (e.g.
+// "/play?coin=<mint>&name=…"). The link is what the countdown's CTA sends
+// players to, so reading the world from it means the drop can never target a
+// different world than the one the event advertises. Returns '' for a link with
+// no coin — the Mainland, which every world-scoped drop then declines.
+export function eventCoinFromLink(link) {
+ const raw = String(link ?? '');
+ const q = raw.indexOf('?');
+ if (q < 0) return '';
+ try {
+ const coin = new URLSearchParams(raw.slice(q + 1)).get('coin');
+ return typeof coin === 'string' ? coin.trim().slice(0, 64) : '';
+ } catch {
+ return '';
+ }
+}
+
+// Reduce a raw /event.json document to the drop the server enforces, or null
+// when this config has no souvenir to grant. Pure — every gate below is
+// testable without a network or a clock.
+export function parseEventDrop(doc) {
+ if (!doc || typeof doc !== 'object') return null;
+ const startsAt = Date.parse(doc.startsAt);
+ const endsAt = Date.parse(doc.endsAt);
+ if (!Number.isFinite(startsAt) || !Number.isFinite(endsAt) || endsAt <= startsAt) return null;
+
+ const cosmeticId = String(doc.souvenir?.cosmeticId ?? '').trim().slice(0, 64);
+ if (!cosmeticId) return null;
+ // Only an event-tier catalog item may be dropped. A typo naming a premium
+ // cosmetic yields no drop at all rather than a free Stetson for everyone.
+ const cosmetic = getCosmetic(cosmeticId);
+ if (!cosmetic || cosmetic.tier !== 'event') return null;
+
+ const coin = eventCoinFromLink(doc.link);
+ if (!coin) return null;
+
+ return {
+ eventId: String(doc.id || 'event').slice(0, 64),
+ eventName: String(doc.name || 'Community meetup').slice(0, 120),
+ startsAt,
+ endsAt,
+ coin,
+ cosmeticId,
+ cosmeticName: cosmetic.name,
+ slot: cosmetic.slot,
+ };
+}
+
+// Is `drop` claimable right now, in the world identified by `coin`? Both gates
+// in one call so no caller can accidentally check the window and forget the
+// world. `now` is injected so tests own the clock.
+export function dropClaimable(drop, coin, now) {
+ if (!drop) return false;
+ const t = Number(now);
+ if (!Number.isFinite(t)) return false;
+ if (t < drop.startsAt || t >= drop.endsAt) return false;
+ return String(coin || '') === drop.coin;
+}
+
+// ── Cached config reader ───────────────────────────────────────────────────
+
+let _cache = { drop: null, at: 0, ok: false };
+let _inflight = null;
+
+async function fetchDrop() {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
+ try {
+ const res = await fetch(CONFIG_URL, {
+ headers: { accept: 'application/json' },
+ signal: controller.signal,
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const drop = parseEventDrop(await res.json());
+ _cache = { drop, at: Date.now(), ok: true };
+ return drop;
+ } catch (err) {
+ // Keep serving the last good config while the source is unreachable: an
+ // event already underway should not stop granting because of one bad
+ // response. Only the retry clock moves.
+ _cache = { ..._cache, at: Date.now() - (TTL_MS - ERROR_TTL_MS), ok: false };
+ if (!_cache.drop) console.warn('[event-drop] config unavailable:', err?.message);
+ return _cache.drop;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+// Start a refresh if the cache is stale, without awaiting it. Rooms call this on
+// create so the first arrival of an event reads a warm cache.
+export function warmEventDrop() {
+ if (Date.now() - _cache.at < TTL_MS) return;
+ if (!_inflight) _inflight = fetchDrop().finally(() => { _inflight = null; });
+}
+
+// The current drop, or null. Returns the cached value immediately when fresh;
+// otherwise awaits the refresh (bounded by FETCH_TIMEOUT_MS) so the very first
+// join of a cold process still gets a correct answer instead of a false "no
+// event". Never throws.
+export async function currentEventDrop() {
+ if (Date.now() - _cache.at < TTL_MS) return _cache.drop;
+ if (!_inflight) _inflight = fetchDrop().finally(() => { _inflight = null; });
+ try {
+ return await _inflight;
+ } catch {
+ return _cache.drop;
+ }
+}
+
+// Test seam: drop the cached config so a suite can exercise the fetch path.
+export function resetEventDropCache() {
+ _cache = { drop: null, at: 0, ok: false };
+ _inflight = null;
+}
diff --git a/multiplayer/src/feed.js b/multiplayer/src/feed.js
index 2d0b388f5..7a85b6109 100644
--- a/multiplayer/src/feed.js
+++ b/multiplayer/src/feed.js
@@ -16,7 +16,7 @@ const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || '';
const FEED_KEY = 'feed:events';
const MAX_EVENTS = 200;
-const ALLOWED_TYPES = new Set(['coin-buy', 'agent-deploy', 'level-up', 'world-join', 'jackpot', 'mission-complete']);
+const ALLOWED_TYPES = new Set(['coin-buy', 'agent-deploy', 'level-up', 'world-join', 'jackpot', 'mission-complete', 'war-result']);
// Per-event-kind cooldown so a busy world can't flood the global ticker with a
// hundred near-identical lines. Keyed by `${type}:${dedupeKey}`.
diff --git a/multiplayer/src/rooms/ClashRoom.js b/multiplayer/src/rooms/ClashRoom.js
index 5076d43a6..2b8fd6412 100644
--- a/multiplayer/src/rooms/ClashRoom.js
+++ b/multiplayer/src/rooms/ClashRoom.js
@@ -24,6 +24,9 @@ import { verifyPlayPass } from '../play-pass.js';
import { installUnknownMessageGuard } from '../room-compat.js';
import { cleanAvatarUrl } from '../avatar-url.js';
import { reportBattle } from '../war-report.js';
+import { verifyWarTicket } from '../war-ticket.js';
+import { publishWarLive, clearWarLive, HEARTBEAT_MS } from '../war-live.js';
+import { publishFeedEvent } from '../feed.js';
const PLAY_GATE_MINT = (process.env.PLAY_GATE_MINT || process.env.THREE_MINT || '').trim();
const PLAY_GATE_MIN = Number(process.env.PLAY_GATE_MIN) > 0 ? Number(process.env.PLAY_GATE_MIN) : 1;
@@ -91,13 +94,25 @@ export class ClashRoom extends Room {
// Unknown message types are ignored, never a session kill (room-compat.js).
installUnknownMessageGuard(this, 'clash');
- // The two communities are fixed at creation from the matchKey's options. The
- // engine owns the authoritative match; the schema mirrors it for clients.
- const a = { mint: clean(options?.aMint, 64), name: clean(options?.aName, 48), symbol: clean(options?.aSymbol, 16), image: cleanAvatarUrl(options?.aImage) };
- const b = { mint: clean(options?.bMint, 64), name: clean(options?.bName, 48), symbol: clean(options?.bSymbol, 16), image: cleanAvatarUrl(options?.bImage) };
- this.network = clean(options?.network, 12) || 'mainnet';
- this.matchKey = clean(options?.matchKey, 160);
+ // The two communities come from the SIGNED war ticket, never from the client.
+ // filterBy(['matchKey']) means whoever joins a key first also creates the
+ // room, so trusting client-supplied faction identities here would let one
+ // fighter declare any opponent they liked and post a league result against a
+ // community that never turned up. The API's matchmaker pairs the two
+ // communities and seals them into the ticket (api/_lib/war-ticket.js); a
+ // missing or forged one refuses room creation outright.
+ const ticket = verifyWarTicket(options?.warTicket);
+ if (!ticket) throw new Error('war_ticket_required');
+ if (ticket.matchKey !== clean(options?.matchKey, 160)) throw new Error('war_ticket_mismatch');
+ const a = { mint: ticket.a.mint, name: clean(ticket.a.name, 48), symbol: clean(ticket.a.symbol, 16), image: cleanAvatarUrl(ticket.a.image) };
+ const b = { mint: ticket.b.mint, name: clean(ticket.b.name, 48), symbol: clean(ticket.b.symbol, 16), image: cleanAvatarUrl(ticket.b.image) };
+ this.network = ticket.network || 'mainnet';
+ this.matchKey = ticket.matchKey;
this._reported = false;
+ // Spectator state: the rolling knockdown feed and the heartbeat throttle for
+ // the Redis snapshot the /play war portal polls (war-live.js).
+ this._killFeed = [];
+ this._lastLiveAt = 0;
this.match = new ClashMatch({ factions: [a, b], config: {} });
const s = this.state;
@@ -144,6 +159,9 @@ export class ClashRoom extends Room {
// Arm the countdown the moment both communities have fielded a fighter.
if (this.match.beginCountdown(Date.now())) this._mirror();
+ // A new fighter changes the roster the portal board shows, so refresh the
+ // spectator snapshot immediately rather than waiting out the heartbeat.
+ this._publishLive(true);
}
onLeave(client) {
@@ -222,12 +240,21 @@ export class ClashRoom extends Room {
target.dead = true;
target.deaths = this.match.fighters.get(hit.id)?.deaths ?? target.deaths;
attacker.kills = this.match.fighters.get(client.sessionId)?.kills ?? attacker.kills;
+ // Spectators watching from either world read this line, so it carries
+ // display names and factions, never session ids.
+ this._killFeed.push({
+ ts: now,
+ killer: attacker.name, killerFaction: attacker.faction,
+ victim: target.name, victimFaction: target.faction,
+ });
+ if (this._killFeed.length > 24) this._killFeed.splice(0, this._killFeed.length - 24);
}
this.broadcast('clash:swing', {
id: client.sessionId, hit: true, target: hit.id,
dealt: res.dealt, killed: res.killed,
});
this._mirror();
+ if (res.killed) this._publishLive(true);
this._finishIfEnded();
}
@@ -252,9 +279,50 @@ export class ClashRoom extends Room {
}
if (ev.started || ev.ended || ev.respawns.length) this._mirror();
else this._mirror(true); // cheap clock-only mirror
+ this._publishLive(ev.started || ev.ended);
this._finishIfEnded();
}
+ // --- spectating ---------------------------------------------------------
+
+ // Publish this battle to the live registry the /play war portal polls. Rate-
+ // limited to one write per HEARTBEAT_MS unless `force` (a join, a knockdown, a
+ // phase change) makes the snapshot materially newer than the clock alone.
+ _publishLive(force = false) {
+ const now = Date.now();
+ if (!force && now - this._lastLiveAt < HEARTBEAT_MS) return;
+ this._lastLiveAt = now;
+ publishWarLive(this._liveSnapshot(now));
+ }
+
+ // The spectator's view of this battle: text and numbers only, everything the
+ // portal board renders without joining the room. Deliberately small — it is
+ // written every couple of seconds for the whole length of a war.
+ _liveSnapshot(now = Date.now()) {
+ const s = this.state;
+ let aFighters = 0;
+ let bFighters = 0;
+ for (const [, f] of s.fighters) {
+ if (f.faction === s.aMint) aFighters++;
+ else if (f.faction === s.bMint) bFighters++;
+ }
+ return {
+ matchKey: this.matchKey,
+ network: this.network,
+ roomId: this.roomId,
+ phase: s.phase,
+ scoreCap: s.scoreCap,
+ startedAt: s.startedAt,
+ endsAt: s.endsAt,
+ countdownEndsAt: s.countdownEndsAt,
+ winner: s.winner || '',
+ a: { mint: s.aMint, name: s.aName, symbol: s.aSymbol, image: s.aImage, score: s.aScore, fighters: aFighters },
+ b: { mint: s.bMint, name: s.bName, symbol: s.bSymbol, image: s.bImage, score: s.bScore, fighters: bFighters },
+ kills: this._killFeed,
+ updatedAt: now,
+ };
+ }
+
// Mirror the authoritative engine state onto the wire schema. `clockOnly` skips
// the per-fighter sync (positions ride their own move patches) for the common
// idle tick, writing just the scores, phase and clock.
@@ -288,10 +356,34 @@ export class ClashRoom extends Room {
});
// Fire-and-forget; reportBattle never throws.
reportBattle({ ...result, matchKey: this.matchKey, network: this.network });
+ // One last snapshot so a spectator's poll lands on the finished scoreline
+ // (with the winner set) instead of the last live tick before the end.
+ this._publishLive(true);
+ // Echo the outcome into the site-wide activity feed, which is what carries
+ // the result back into BOTH communities' worlds — the portal board reads the
+ // ledger, the ticker reads this. Best-effort like every feed write.
+ const winnerName = result.winner === this.state.aMint ? this.state.aName
+ : result.winner === this.state.bMint ? this.state.bName : 'Draw';
+ publishFeedEvent({
+ type: 'war-result',
+ actor: winnerName,
+ winner: result.winner || 'draw',
+ reason: result.reason || 'score_cap',
+ a: { mint: this.state.aMint, name: this.state.aName, symbol: this.state.aSymbol, score: this.state.aScore },
+ b: { mint: this.state.bMint, name: this.state.bName, symbol: this.state.bSymbol, score: this.state.bScore },
+ matchKey: this.matchKey,
+ network: this.network,
+ }, this.matchKey);
// Lock further joins; the room auto-disposes once empty.
try { this.lock(); } catch { /* already locked */ }
}
+ // The arena has emptied out. Take the battle off the spectator board now
+ // rather than leaving it advertised until the snapshot TTL expires.
+ onDispose() {
+ clearWarLive(this.matchKey);
+ }
+
// --- helpers ------------------------------------------------------------
// Spawn a fighter on their faction's side of the arena, slightly scattered so two
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index cf83809b9..3acebec74 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -43,7 +43,7 @@ import {
restoreProfile, serializeProfile, profileSnapshot,
addItem, hasRoomFor, resolveSlot, grantXp, consumeSlot,
countItem, removeItem,
- dropCarried, reviveProfile, bankTransfer, grantCosmetic,
+ dropCarried, reviveProfile, creditGold, bankTransfer, grantCosmetic,
equipCosmetic, ownedCosmeticSet, mergeOwnedFromLedger,
HOTBAR_SIZE,
} from '../economy.js';
@@ -1537,7 +1537,7 @@ export class WalkRoom extends Room {
_completeMission(client, profile, mission, dayKey) {
recordCompletion(profile.quests, mission, dayKey);
const reward = missionReward(mission);
- if (reward.gold > 0) profile.gold += reward.gold;
+ if (reward.gold > 0) creditGold(profile, reward.gold);
if (reward.xp) this._grantXp(client, profile, reward.xp.skill, reward.xp.amount);
this._sendInv(client, profile);
client.send('questComplete', {
@@ -1559,7 +1559,7 @@ export class WalkRoom extends Room {
const memberProfile = this.econ.get(sid);
if (!memberProfile) return;
recordCompletion(memberProfile.quests, mission, dayKey);
- if (shares[i] > 0) memberProfile.gold += shares[i];
+ if (shares[i] > 0) creditGold(memberProfile, shares[i]);
const memberClient = this.clients.find((c) => c.sessionId === sid);
if (memberClient) {
try {
@@ -2143,7 +2143,7 @@ export class WalkRoom extends Room {
const removed = removeItem(profile, item, want);
if (removed <= 0) return;
const total = sellPrice(item) * removed;
- profile.gold += total;
+ creditGold(profile, total);
this._sendInv(client, profile);
client.send('notice', { kind: 'store', ok: true, text: `Sold ${removed} ${itemLabel(item).toLowerCase()} for ${total} cash.` });
this._persistEcon(client.sessionId);
diff --git a/multiplayer/src/spin-wheel.js b/multiplayer/src/spin-wheel.js
index f4b182ad5..c9f179074 100644
--- a/multiplayer/src/spin-wheel.js
+++ b/multiplayer/src/spin-wheel.js
@@ -125,6 +125,7 @@ function infoPayload(room, client, profile) {
export function handleSpinInfo(room, client) {
const profile = room.econ.get(client.sessionId);
if (!profile) return;
+ if (!room._actionOk(client.sessionId, 'spinInfo')) return;
client.send('spinInfo', infoPayload(room, client, profile));
}
diff --git a/multiplayer/src/war-live.js b/multiplayer/src/war-live.js
new file mode 100644
index 000000000..cb5b3c3eb
--- /dev/null
+++ b/multiplayer/src/war-live.js
@@ -0,0 +1,105 @@
+// Live war registry — the multiplayer server's spectator half of Coin Wars.
+//
+// A battle runs inside a ClashRoom, which only its fighters are connected to.
+// Players standing in either community's world want to watch it without joining
+// it: the score, the round clock, who just got knocked down. Opening a second
+// websocket per spectator (and a second 3D render) to answer that would be
+// absurd, so the room instead publishes a small JSON snapshot to Redis on a
+// heartbeat and the portal board polls a cheap read (api/_lib/wars-store.js
+// reads exactly these keys).
+//
+// Same writer/reader split as feed.js and presence-store.js: Redis is the bus
+// between the long-running game server and the serverless API. Every write is
+// best-effort — spectating is a delight layer, never on the battle's critical
+// path, so an unreachable Redis means no spectators, never a thrown error inside
+// a room handler.
+
+const REDIS_URL = process.env.UPSTASH_REDIS_REST_URL || '';
+const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || '';
+
+const LIVE_KEY = (matchKey) => `wars:live:${matchKey}`;
+const LIVE_INDEX = 'wars:live:index';
+
+// A snapshot outlives its heartbeat by enough that a slow tick never makes a
+// running war blink out of the board, and expires soon enough that a crashed
+// room stops advertising a battle nobody is fighting.
+const SNAPSHOT_TTL_S = 120;
+
+// Minimum gap between heartbeats for one match. The clock and score are the only
+// things that move between kills, and the board renders its own countdown from
+// `endsAt`, so 2s is plenty and keeps the write rate flat regardless of how
+// furious the fight is.
+export const HEARTBEAT_MS = 2000;
+
+// How many knockdowns ride along for the kill feed. The board shows the last
+// handful; anything older is history the ledger keeps.
+const KILL_FEED_MAX = 12;
+
+let _redis = null;
+let _redisReady = null;
+
+if (REDIS_URL && REDIS_TOKEN) {
+ _redisReady = import('@upstash/redis')
+ .then(async ({ Redis }) => {
+ _redis = new Redis({ url: REDIS_URL, token: REDIS_TOKEN });
+ await _redis.ping();
+ console.log('[war-live] live war registry: writing to Upstash Redis (verified)');
+ })
+ .catch((err) => {
+ _redis = null;
+ console.warn('[war-live] Redis unreachable — wars will not be spectatable:', err?.message);
+ });
+} else {
+ console.log('[war-live] live war registry disabled (no UPSTASH_REDIS_REST_URL/_TOKEN)');
+}
+
+/**
+ * Publish (or refresh) one running battle. Returns the snapshot that was written,
+ * or null when nothing was written (no Redis, bad shape, or a failed command).
+ * @param {object} snapshot see ClashRoom._liveSnapshot() for the fields
+ */
+export function publishWarLive(snapshot) {
+ if (!_redis || !snapshot?.matchKey) return Promise.resolve(null);
+ const record = {
+ ...snapshot,
+ kills: (snapshot.kills || []).slice(-KILL_FEED_MAX),
+ updatedAt: Number.isFinite(snapshot.updatedAt) ? snapshot.updatedAt : Date.now(),
+ };
+ return (async () => {
+ try {
+ await _redis.set(LIVE_KEY(record.matchKey), JSON.stringify(record), { ex: SNAPSHOT_TTL_S });
+ await _redis.zadd(LIVE_INDEX, { score: record.updatedAt, member: record.matchKey });
+ // Sweep index entries whose snapshot has certainly expired, so the set
+ // cannot grow without bound across a long-running process.
+ await _redis.zremrangebyscore(LIVE_INDEX, 0, record.updatedAt - SNAPSHOT_TTL_S * 1000);
+ return record;
+ } catch (err) {
+ console.warn('[war-live] publish failed:', err?.message);
+ return null;
+ }
+ })();
+}
+
+/**
+ * Drop a battle from the registry the moment its room disposes, so the portal
+ * stops showing a war whose arena has already emptied out rather than waiting for
+ * the TTL to expire it.
+ */
+export function clearWarLive(matchKey) {
+ if (!_redis || !matchKey) return Promise.resolve(false);
+ return (async () => {
+ try {
+ await _redis.del(LIVE_KEY(matchKey));
+ await _redis.zrem(LIVE_INDEX, matchKey);
+ return true;
+ } catch (err) {
+ console.warn('[war-live] clear failed:', err?.message);
+ return false;
+ }
+ })();
+}
+
+// Exposed for tests / graceful shutdown sequencing, mirroring feed.js.
+export function warLiveReady() {
+ return _redisReady || Promise.resolve();
+}
diff --git a/multiplayer/src/world-features.js b/multiplayer/src/world-features.js
index 74c09be64..fb4716990 100644
--- a/multiplayer/src/world-features.js
+++ b/multiplayer/src/world-features.js
@@ -151,6 +151,32 @@ export function nearestStage(x, z) { return nearestNode(x, z, [PLAZA_STAGE], STA
export function stageInRange(x, z) { return nodeInRange(x, z, [PLAZA_STAGE], STAGE_ATTEND_REACH); }
export function stageMarqueeInRange(x, z) { return nodeInRange(x, z, [PLAZA_STAGE], STAGE_MARQUEE_REACH); }
+// The War Portal — the Coin Wars door standing in every coin world's plaza
+// (F18). Walking up to it shows this community's league standing, the last
+// battles fought, and any war running right now; interacting with it queues the
+// community for a battle and hands the player through to the arena at /play/war.
+//
+// Sited in the north-west plaza so the three plaza landmarks form a triangle a
+// player can see across rather than a cluster: the wheel at (0,22) is ~21 m
+// away, the stage at (18,26) ~38 m, the west firepit (-22,20) ~10 m, the west
+// pond (-28,16) ~16 m. Comfortably inside the 60 m world disc and well clear of
+// the northern wilds (0,42,r10), so the crowd reading the board is in safe town.
+export const WAR_PORTAL = { id: 'war-portal', x: -20, z: 30, r: 3 };
+
+// How close a player must stand to use the portal (the "E — Enter the war"
+// prompt). Matches the other landmark reaches so every plaza interaction has the
+// same feel underfoot.
+export const WAR_PORTAL_REACH = 3.5;
+
+// How far away the board is still legible. Crossing THIS ring is what wakes the
+// portal's league poll; outside it the portal makes no network calls at all, so
+// a world nobody is standing in costs nothing to keep a war portal in.
+export const WAR_PORTAL_BOARD_REACH = 24;
+
+export function nearestWarPortal(x, z) { return nearestNode(x, z, [WAR_PORTAL], WAR_PORTAL_REACH); }
+export function warPortalInRange(x, z) { return nodeInRange(x, z, [WAR_PORTAL], WAR_PORTAL_REACH); }
+export function warPortalBoardInRange(x, z) { return nodeInRange(x, z, [WAR_PORTAL], WAR_PORTAL_BOARD_REACH); }
+
// Fishing-rod pickups — a spare rod waiting on the bank for anyone without one
// (or anyone who wants a backup to store). Every player already starts with a
// rod in the hotbar and it's never lost on death, so these exist for
diff --git a/page-agent-sdk/src/stage.js b/page-agent-sdk/src/stage.js
index 3c0e2ece2..603ef7cb1 100644
--- a/page-agent-sdk/src/stage.js
+++ b/page-agent-sdk/src/stage.js
@@ -45,8 +45,8 @@ const HDRI_ORIGIN = new URL(DEFAULT_ASSET_BASE).origin;
let _hdriPromise = null;
function getHdriTexture() {
if (!_hdriPromise) {
- _hdriPromise = import('three/addons/loaders/RGBELoader.js').then(({ RGBELoader }) =>
- new RGBELoader().loadAsync(`${HDRI_ORIGIN}/hdri/studio.hdr`),
+ _hdriPromise = import('three/addons/loaders/HDRLoader.js').then(({ HDRLoader }) =>
+ new HDRLoader().loadAsync(`${HDRI_ORIGIN}/hdri/studio.hdr`),
);
}
return _hdriPromise;
diff --git a/pages/event.html b/pages/event.html
index 572153dc1..be74c30a0 100644
--- a/pages/event.html
+++ b/pages/event.html
@@ -67,7 +67,7 @@
font-family: var(--font-mono); font-variant-numeric: tabular-nums;
}
- /* Skeletons — the hero has real shape before /event.json resolves. */
+ /* Skeletons: the hero has real shape before /event.json resolves. */
.ev-skel {
display: inline-block; border-radius: var(--skeleton-radius, 10px);
background: linear-gradient(90deg, var(--skeleton-base) 25%, var(--skeleton-sheen) 37%, var(--skeleton-base) 63%);
diff --git a/pages/play.html b/pages/play.html
index f85b8378c..b0e2745a5 100644
--- a/pages/play.html
+++ b/pages/play.html
@@ -44,8 +44,17 @@
<meta name="twitter:description" content="Play in your coin's 3D community world. Walk, chat, and hang out with fellow holders." data-i18n-attr="content:play.meta_twitter_description"/>
<meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Play&amp;d=Jump+into+a+live+coin+community+world+and+explore+it+with+your+avatar.&amp;p=%2Fplay" />
+ <!--
+ Brand typography. coincommunities.css asks for Inter everywhere, but this
+ page never loaded a face for it, so the whole surface (including the boot
+ wordmark) silently rendered in the OS default. Preload the latin subset so
+ the loader's first paint is already on-brand, no FOUT.
+ See docs/DESIGN-TOKENS.md — standalone pages must load /fonts/fonts.css.
+ -->
+ <link rel="preload" href="/fonts/inter-latin.woff2" as="font" type="font/woff2" crossorigin />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
<link rel="stylesheet" href="/src/game/coincommunities.css" />
-
+
<link rel="canonical" href="https://three.ws/play">
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
<meta property="og:locale" content="en_US">
@@ -57,6 +66,19 @@
<div class="kx-loading-card">
<img class="kx-loading-logo" src="/three.svg" alt="three.ws" width="38" height="38" />
<div class="kx-loading-mark">COIN COMMUNITIES</div>
+ <!--
+ Deep-link identity. A shared /play?coin=…&name=…&symbol=…&image=… link
+ already carries everything needed to say WHICH world is opening, so the
+ inline script below fills this in before the app bundle has even parsed.
+ Stays hidden on a plain /play visit.
+ -->
+ <div class="kx-boot-coin" hidden>
+ <span class="kx-boot-coin-art"><img alt="" width="44" height="44" /><span class="kx-boot-coin-mono" aria-hidden="true"></span></span>
+ <span class="kx-boot-coin-text">
+ <span class="kx-boot-coin-name"></span>
+ <span class="kx-boot-coin-sym"></span>
+ </span>
+ </div>
<div class="kx-boot-stage">
<canvas id="kx-boot-avatar" aria-hidden="true"></canvas>
<div class="kx-boot-fallback" aria-hidden="true"></div>
@@ -66,7 +88,19 @@
</div>
</div>
- <canvas id="kx-canvas"></canvas>
+ <!--
+ The world itself is a keyboard stop, not a decorative image: Tab lands
+ here, the label says what it is and how to drive it, and role=application
+ tells a screen reader to pass keystrokes through instead of intercepting
+ them for its own browse-mode shortcuts.
+ -->
+ <canvas
+ id="kx-canvas"
+ tabindex="0"
+ role="application"
+ aria-label="The 3D coin community world. Walk with W A S D or the arrow keys, hold Shift to run, Space to jump, drag or use the mouse to look around. Press Enter to open chat, Q for emotes, E to talk to whoever is nearby, and Z to hide the panels."
+ data-i18n-attr="aria-label:play.canvas_label"
+ ></canvas>
<script>
/* Boot watchdog: inline on purpose so it works even when the app bundle
@@ -125,22 +159,50 @@
l.replaceChildren(card);
retry.focus();
}
- /* A failed script/stylesheet is unambiguously boot-fatal: fail now.
- Runtime errors and unhandled rejections can also come from benign
- background work racing the boot, so they only arm a short grace
- timer; if boot completes first, bootPending() disarms the card. */
+ /* Which failures are actually boot-fatal.
+
+ This watchdog exists for one thing: a stale cached HTML pointing at
+ chunks a deploy already removed, where nothing will ever finish and
+ only a reload helps. Everything else that reaches these listeners is
+ noise, and covering a world that is loading fine with a full-screen
+ "Couldn't load the world" is a worse failure than the one being
+ guarded against. Two visitors we expect at an event proved the old
+ rules too eager:
+
+ 1. An ad blocker or privacy extension blocks one of the optional
+ extras (/brand.js, /i18n.js) or any third-party script. That is a
+ resource error on a SCRIPT tag, which used to fail instantly even
+ though the game modules were downloading normally. Only a
+ same-origin, non-optional script or stylesheet counts now.
+ 2. Flaky wifi makes a background request reject. Every fetch boundary
+ in the app handles its own failure, so a rejected request is not a
+ boot failure. Network-shaped rejections are ignored outright, and
+ anything else gets a grace long enough for a slow but healthy boot
+ to finish and disarm it (bootPending). */
+ var OPTIONAL_SCRIPTS = /\/(brand|i18n|theme-switcher)\.js(\?|$)/;
+ function isNetworkNoise(v) {
+ var s = (v && (v.message || v.name)) || String(v || '');
+ return /Failed to fetch|NetworkError|Load failed|ERR_BLOCKED|ERR_FAILED|AbortError|network error/i.test(s);
+ }
function failSoon(title, body) {
- setTimeout(function () { fail(title, body); }, 8000);
+ setTimeout(function () { fail(title, body); }, 20000);
}
window.addEventListener('error', function (e) {
var t = e && e.target;
if (t && (t.tagName === 'SCRIPT' || t.tagName === 'LINK')) {
+ var url = t.src || t.href || '';
+ /* Cross-origin scripts and the optional extras are blockable by
+ design; the world does not depend on any of them. */
+ if (url && url.indexOf(location.origin) !== 0) return;
+ if (OPTIONAL_SCRIPTS.test(url)) return;
fail('Couldn’t load the world', 'A file failed to load. This usually fixes itself on a reload; the site may have just been updated.');
} else if (e && (e.error || e.message)) {
+ if (isNetworkNoise(e.error || e.message)) return;
failSoon('Couldn’t load the world', 'Something went wrong while starting Coin Communities. Reload to try again.');
}
}, true);
- window.addEventListener('unhandledrejection', function () {
+ window.addEventListener('unhandledrejection', function (e) {
+ if (isNetworkNoise(e && e.reason)) return;
failSoon('Couldn’t load the world', 'Something went wrong while starting Coin Communities. Reload to try again.');
});
setTimeout(function () {
diff --git a/public/accessories/laurel-meetup.glb b/public/accessories/laurel-meetup.glb
index 07981e961..8a5f8aea8 100644
Binary files a/public/accessories/laurel-meetup.glb and b/public/accessories/laurel-meetup.glb differ
diff --git a/public/changelog.json b/public/changelog.json
index 239195724..7cf6f1656 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-07T09:31:50.187Z",
+ "generated_at": "2026-08-07T09:59:03.491Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -20,7 +20,7 @@
"date": "2026-08-07",
"type": "launch",
"title": "Live event",
- "summary": "The live three.ws community meetup: when it starts, what is on the agenda, who is in the world right now, and the event leaderboard.",
+ "summary": "The live three.ws community meetup: a ticking countdown off the same config /play reads, the run of show in your own timezone, an add-to-calendar file, who is in the world right now, and the one door in.",
"link": "/event",
"tags": [
"launch"
@@ -116,7 +116,7 @@
"date": "2026-08-07",
"type": "update",
"title": "Play now counts down to the next community event",
- "summary": "The Play lobby shows a live banner for the upcoming $THREE Community Day: the event name, when it starts in your own timezone, and a ticking countdown. Once you are inside a world, a small dismissible reminder pill keeps the countdown in view, and when the event goes live both switch to a LIVE marker with a one-click jump into the $THREE world. After the event ends everything quietly disappears on its own.",
+ "summary": "The Play lobby shows a live banner for the upcoming $THREE First Holders Meetup: the event name, when it starts in your own timezone, and a ticking countdown. Once you are inside a world, a small dismissible reminder pill keeps the countdown in view, and when the event goes live both switch to a LIVE marker with a one-click jump into the $THREE world. After the event ends everything quietly disappears on its own.",
"link": "/play",
"tags": [
"feature"
@@ -155,6 +155,16 @@
"fix"
]
},
+ {
+ "date": "2026-08-07",
+ "type": "update",
+ "title": "The event countdown is now on the front page",
+ "summary": "You no longer have to open Play to find out when the next live community event starts. The three.ws home page now carries a slim strip above the hero with the event name, the start time in your own timezone, and a countdown ticking down to the second. The moment the event begins it switches to LIVE on its own, without a refresh, and it takes itself off the page once the event is over. One click on it drops you straight into the $THREE world. If you would rather not see it, dismiss it once and it stays gone, in Play as well as on the home page. Every countdown surface across the site reads the same event schedule, so they can never disagree about when things start.",
+ "link": "/",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-08-06",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index f25abf1ef..78c9c55f4 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -20,7 +20,7 @@
<guid isPermaLink="false">2026-08-07:Live event</guid>
<pubDate>Fri, 07 Aug 2026 12:00:00 GMT</pubDate>
<category>launch</category>
- <description>The live three.ws community meetup: when it starts, what is on the agenda, who is in the world right now, and the event leaderboard.</description>
+ <description>The live three.ws community meetup: a ticking countdown off the same config /play reads, the run of show in your own timezone, an add-to-calendar file, who is in the world right now, and the one door in.</description>
</item>
<item>
<title>A transaction guard now stands between the chat agent and your wallet</title>
@@ -92,7 +92,7 @@
<guid isPermaLink="false">2026-08-07:Play now counts down to the next community event</guid>
<pubDate>Fri, 07 Aug 2026 12:00:00 GMT</pubDate>
<category>feature</category>
- <description>The Play lobby shows a live banner for the upcoming $THREE Community Day: the event name, when it starts in your own timezone, and a ticking countdown. Once you are inside a world, a small dismissible reminder pill keeps the countdown in view, and when the event goes live both switch to a LIVE marker with a one-click jump into the $THREE world. After the event ends everything quietly disappears on its own.</description>
+ <description>The Play lobby shows a live banner for the upcoming $THREE First Holders Meetup: the event name, when it starts in your own timezone, and a ticking countdown. Once you are inside a world, a small dismissible reminder pill keeps the countdown in view, and when the event goes live both switch to a LIVE marker with a one-click jump into the $THREE world. After the event ends everything quietly disappears on its own.</description>
</item>
<item>
<title>Play: phones stop getting dropped out of the world seconds after joining</title>
@@ -118,6 +118,14 @@
<category>security</category>
<description>Every agent and avatar embed can chat for free because the platform pays for the model behind it, and the agent owner decides which sites may run that embed and which model it uses. Both of those controls only really applied to browsers: a request that simply left out the header a browser always sends slipped past the site allowlist entirely, and any caller could ask for a pricier model than the owner had chosen. Both are closed. A request with no site header now has to sign in (a session or an API key) instead of riding on an agent id anyone could read off our public sitemap, and a model that bills our own provider keys runs only when the owner selected it in the dashboard. There is also a new platform-wide ceiling across all of this traffic combined, so no amount of spreading requests around can drain the shared budget. Nothing changes for a normal embed on an allowlisted site.</description>
</item>
+ <item>
+ <title>The event countdown is now on the front page</title>
+ <link>https://three.ws/</link>
+ <guid isPermaLink="false">2026-08-07:The event countdown is now on the front page</guid>
+ <pubDate>Fri, 07 Aug 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>You no longer have to open Play to find out when the next live community event starts. The three.ws home page now carries a slim strip above the hero with the event name, the start time in your own timezone, and a countdown ticking down to the second. The moment the event begins it switches to LIVE on its own, without a refresh, and it takes itself off the page once the event is over. One click on it drops you straight into the $THREE world. If you would rather not see it, dismiss it once and it stays gone, in Play as well as on the home page. Every countdown surface across the site reads the same event schedule, so they can never disagree about when things start.</description>
+ </item>
<item>
<title>Airdrop Checker</title>
<link>https://three.ws/airdrops</link>
diff --git a/public/event.json b/public/event.json
index 1ef8e6ddd..c4afb6a7a 100644
--- a/public/event.json
+++ b/public/event.json
@@ -1,12 +1,16 @@
{
- "$comment": "The live /play event. Single source of truth for BOTH the countdown pill/banner (src/game/event-countdown.js) and the in-world meetup experience layer (src/game/meetup-event.js: agenda drawer, go-live moments, synchronized fireworks, commemorative photo). Times are ISO-8601 UTC. agenda[].atMin is minutes after startsAt. Preview locally with ?meetup=now or ?meetup=<ISO> on /play.",
+ "$comment": "The live /play event. Single source of truth for the countdown pill/banner (src/game/event-countdown.js), the in-world meetup experience layer (src/game/meetup-event.js: agenda drawer, go-live moments, synchronized fireworks, commemorative photo), AND the server-side souvenir grant (multiplayer/src/event-drop.js, which fetches this same file). Times are ISO-8601 UTC. agenda[].atMin is minutes after startsAt. Preview locally with ?meetup=now or ?meetup=<ISO> on /play.",
"id": "three-first-meetup",
"name": "$THREE First Holders Meetup",
"tagline": "The first live gathering in the three.ws world. Drop in, hang out, win prizes.",
- "startsAt": "2026-08-07T17:00:00Z",
- "endsAt": "2026-08-07T19:00:00Z",
+ "startsAt": "2026-08-07T09:36:18Z",
+ "endsAt": "2026-08-07T11:37:18Z",
"link": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
"linkLabel": "Join the $THREE world",
+ "souvenir": {
+ "cosmeticId": "laurel-meetup",
+ "$comment": "Free commemorative wearable granted once to every player in the world named by `link` between startsAt and endsAt. Must be an id in multiplayer/src/cosmetics-catalog.js with tier 'event' — the server refuses to grant anything else, so this field can never hand out a boutique item. Drop the field to run an event with no souvenir."
+ },
"agenda": [
{ "atMin": 0, "title": "Doors open in the plaza", "detail": "Say hi in chat, show off your fit, grab a commemorative photo", "icon": "👋" },
{ "atMin": 20, "title": "King of the Totem showdown", "detail": "Hold the gold ring at the totem to be crowned. Winner takes the round", "icon": "👑" },
diff --git a/public/features.json b/public/features.json
index 981ac7701..571d97281 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-07T09:31:49.914Z",
+ "generated_at": "2026-08-07T09:59:03.483Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -2579,7 +2579,7 @@
{
"path": "/event",
"title": "Live event",
- "description": "The live three.ws community meetup: when it starts, what is on the agenda, who is in the world right now, and the event leaderboard.",
+ "description": "The live three.ws community meetup: a ticking countdown off the same config /play reads, the run of show in your own timezone, an add-to-calendar file, who is in the world right now, and the one door in.",
"added": "2026-08-07",
"auth": null,
"indexable": true,
diff --git a/public/llms-full.txt b/public/llms-full.txt
index ce8f7da9e..b4cf3e868 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -1558,6 +1558,12 @@ URL: https://three.ws/play
Jump into a live coin community world and explore it with your avatar.
+### Live event
+
+URL: https://three.ws/event
+
+The live three.ws community meetup: a ticking countdown off the same config /play reads, the run of show in your own timezone, an add-to-calendar file, who is in the world right now, and the one door in.
+
### Copy Trading
URL: https://three.ws/mirror
diff --git a/public/llms.txt b/public/llms.txt
index 55525104a..81de9ccb7 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -294,6 +294,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [x402 Catalog](https://three.ws/x402): A live catalog of pay-per-call APIs settled on-chain in USDC over the x402 protocol. Search, inspect the schema, and run any endpoint.
- [Coin Communities](https://three.ws/communities): Pick a coin, drop in an avatar, and walk around its world with everyone else holding it. Each coin is its own live 3D community.
- [Play](https://three.ws/play): Jump into a live coin community world and explore it with your avatar.
+- [Live event](https://three.ws/event): The live three.ws community meetup: a ticking countdown off the same config /play reads, the run of show in your own timezone, an add-to-calendar file, who is in the world right now, and the one door in.
- [Copy Trading](https://three.ws/mirror): Follow a high-performing agent and your own agent mirrors its real trades, proportionally and strictly within your spend policy.
- [Trading Swarms](https://three.ws/swarms): Coordinated groups of trading agents working a shared strategy, with live positions and performance.
- [Agent Wallet](https://three.ws/agent-wallet): The wallet surface for your agents: balances, funding, and activity.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 4ef6e564f..c29c0dbd3 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -79,7 +79,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 794 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 795 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -91,7 +91,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 794 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 795 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -99,6 +99,14 @@
<h2 id="sm-new-title">Newest<a class="sm-new-more" href="/changelog">full changelog &rarr;</a></h2>
<p class="sm-section-desc">The 9 most recently launched pages, straight to the live surface.</p>
<ul class="sm-list">
+ <li>
+ <a href="/event">
+ <span class="sm-new-date">Aug 7, 2026</span>
+ <span class="sm-title">Live event</span>
+ <span class="sm-path">/event</span>
+ <span class="sm-desc">The live three.ws community meetup: a ticking countdown off the same config /play reads, the run of show in your own timezone, an add-to-calendar file, who is in the world right now, and the one door in.</span>
+ </a>
+ </li>
<li>
<a href="/docs/agent-runtime">
<span class="sm-new-date">Aug 7, 2026</span>
@@ -163,14 +171,6 @@
<span class="sm-desc">The running catalog of every thread and blog in the Three.ws User Group on IBM Community: authors, dates, activity, and a faithful summary of each post, plus a snapshot of the group's membership and content counts.</span>
</a>
</li>
- <li>
- <a href="/holo">
- <span class="sm-new-date">Aug 2, 2026</span>
- <span class="sm-title">Holo Sticker</span>
- <span class="sm-path">/holo</span>
- <span class="sm-desc">A live holographic foil sticker rendered in your browser: tilt it with your pointer, peel the corner, switch foils, die-cut your own text, and download the frame as a PNG. Fully procedural, no assets.</span>
- </a>
- </li>
</ul>
</section>
<nav class="sm-toc" aria-label="Sections">
@@ -1125,7 +1125,7 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>132</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>133</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
@@ -1997,6 +1997,13 @@
<span class="sm-desc">Jump into a live coin community world and explore it with your avatar.</span>
</a>
</li>
+ <li>
+ <a href="/event">
+ <span class="sm-title">Live event</span>
+ <span class="sm-path">/event</span>
+ <span class="sm-desc">The live three.ws community meetup: a ticking countdown off the same config /play reads, the run of show in your own timezone, an add-to-calendar file, who is in the world right now, and the one door in.</span>
+ </a>
+ </li>
<li>
<a href="/mirror">
<span class="sm-title">Copy Trading</span>
diff --git a/scripts/gcp-triage.mjs b/scripts/gcp-triage.mjs
index 38f99a37c..10e3a69b1 100644
--- a/scripts/gcp-triage.mjs
+++ b/scripts/gcp-triage.mjs
@@ -702,13 +702,29 @@ async function probeServiceWallets() {
if (!existsSync('.env')) return { status: 'skipped', note: 'no .env with signer secrets here' };
const r = await runCommand(['node', '--env-file=.env', 'scripts/audit-service-wallets.mjs'], { timeoutMs: 300000 });
if (r.timedOut) return { status: 'error', note: 'wallet audit timed out' };
- const issues = r.stdout.split('\n').map((l) => l.trim()).filter((l) => l.startsWith('✗'));
- if (r.code === 0 && !issues.length) return { status: 'ok', note: 'service wallets above floors, advertised keys consistent' };
+ const lines = r.stdout.split('\n').map((l) => l.trim());
+ // `✗` = the chain was read and the money is wrong (owner). `‼` = the balance
+ // could not be read at all (investigate). Reporting an unreadable wallet as a
+ // funding emergency is the 2026-08-07 false alarm this split exists to stop.
+ const issues = lines.filter((l) => l.startsWith('✗'));
+ const unread = lines.filter((l) => l.startsWith('‼'));
+ if (r.code === 0 && !issues.length && !unread.length) return { status: 'ok', note: 'service wallets above floors, advertised keys consistent' };
+ const findings = [];
if (issues.length) {
- return { status: 'findings', note: `${issues.length} wallet issue(s)`, findings: [deepFinding('service-wallets', 'owner', 'service wallet balances or advertised keys failing audit', {
+ findings.push(deepFinding('service-wallets', 'owner', 'service wallet balances or advertised keys failing audit', {
count: issues.length, sample: issues.join('\n'),
action: `Money surface; diagnose before concluding the owner must fund. Below-floor balances: run the self-heal first (POST /api/cron/treasury-topup reclaim leg, then /api/cron/economy-rebalance) per ${RUNBOOK} §x402-wallets-dry, or the x402-economy-triage agent. A fee-payer/payTo mismatch is env config on the Cloud Run service, not funding.`,
- })] };
+ }));
+ }
+ if (unread.length) {
+ findings.push(deepFinding('service-wallets-unreadable', 'investigate', 'wallet balances could not be read, so funding state is unverified', {
+ count: unread.length, sample: unread.join('\n'),
+ action: 'NOT a funding verdict: the audit could not reach a working Solana RPC lane for these wallets. Check healthz rpc_lanes for how many lanes are cooling, then re-run the audit once a lane recovers. Do not fund or rebalance anything off an unreadable balance.',
+ }));
+ }
+ if (findings.length) {
+ const parts = [issues.length ? `${issues.length} wallet issue(s)` : '', unread.length ? `${unread.length} unreadable` : ''].filter(Boolean);
+ return { status: 'findings', note: parts.join(', '), findings };
}
return { status: 'error', note: tail(r.stderr || r.stdout, 3) };
}
diff --git a/scripts/lib/console-noise.mjs b/scripts/lib/console-noise.mjs
index f1666f7fb..438d35817 100644
--- a/scripts/lib/console-noise.mjs
+++ b/scripts/lib/console-noise.mjs
@@ -58,6 +58,10 @@ export const IGNORE_CONSOLE = [
/THREE\.BufferGeometry\.computeBoundingSphere/i,
/WebGL.*swiftshader/i,
/Automatic fallback to software WebGL/i,
+ // Headless Chromium's software GL driver narrating its own perf on a CI box.
+ // Emitted by the driver, never by our code, and absent on real GPUs.
+ /GL Driver Message/i,
+ /GPU stall due to ReadPixels/i,
// Content-Security-Policy noise from third-party embeds
/content security policy/i,
/Refused to (load|connect|execute|frame)/i,
diff --git a/scripts/play-capacity-smoke.mjs b/scripts/play-capacity-smoke.mjs
new file mode 100644
index 000000000..b93bc231a
--- /dev/null
+++ b/scripts/play-capacity-smoke.mjs
@@ -0,0 +1,349 @@
+// Drive N concurrent /play sessions at the live multiplayer world and report
+// what bends. Written for event-day readiness: the number that decides whether a
+// community launch survives is not "does one player connect" but "does the
+// world still accept and serve the 400th one while the first 399 are walking".
+//
+// Why not Playwright: a browser costs ~200-300 MB and a CPU share, so a laptop
+// tops out around 20 real pages. As far as the world server is concerned a
+// player is one Colyseus session plus the move traffic it produces, and that is
+// exactly what this opens. Every client here does the real handshake the browser
+// does (HTTP matchmake -> seat reservation -> WS upgrade -> schema handshake),
+// so a broken join contract fails here the same way it fails a real visitor.
+//
+// Two Node-specific details this depends on, both load-bearing:
+// 1. The world server rejects origin-less WS upgrades in production
+// (multiplayer/src/index.js verifyClient). colyseus.js only forwards custom
+// headers when its transport resolves to the `ws` package, and Node >= 22
+// ships a global WebSocket that shadows it and silently drops them. We
+// delete the global before importing colyseus.js so the Origin header
+// actually reaches the server.
+// 2. No root-schema class is passed to joinOrCreate, so state decodes from the
+// server's reflected schema. A harness pinned to a local schema build
+// desyncs the moment the deployed server adds an append-only field.
+//
+// Usage:
+// node scripts/play-capacity-smoke.mjs --n 400 --hold 120
+// node scripts/play-capacity-smoke.mjs --n 50 --host ws://localhost:2567 --origin http://localhost:3000
+// node scripts/play-capacity-smoke.mjs --n 600 --ramp 60 --hold 180 --json report.json
+//
+// Flags:
+// --n <int> concurrent players (default 200)
+// --host <url> multiplayer server ws(s) URL (default prod)
+// --origin <url> Origin header sent on the WS upgrade (default https://three.ws)
+// --coin <mint> community world to join (default $THREE)
+// --tier <t> '' for the open General world, or 'holders' (default '')
+// --ramp <sec> spread the joins over this window (default 30)
+// --hold <sec> keep everyone walking this long (default 120)
+// --rate <hz> move messages per player per second (default 8)
+// --json <path> also write the full report as JSON
+//
+// Exit code is 0 only when every threshold in THRESHOLDS below holds, so this
+// can gate a release as well as inform one.
+
+import { writeFileSync } from 'node:fs';
+import process from 'node:process';
+
+// See note 1 above: must happen before colyseus.js is loaded.
+delete globalThis.WebSocket;
+const { Client } = await import('colyseus.js');
+
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const DEFAULT_HOST = 'wss://three-ws-multiplayer-93741856042.us-central1.run.app';
+
+// Pass/fail bar for the run. These are event-day numbers, not aspirational ones:
+// a join that takes longer than 8 s is a player who has already reloaded, and a
+// world that drops more than 2% of its sessions mid-event looks broken from the
+// inside even when every dashboard is green.
+const THRESHOLDS = {
+ joinFailPct: 2,
+ dropPct: 2,
+ joinP95Ms: 8000,
+ silentPct: 5, // sessions that joined but never received a state patch
+};
+
+function parseArgs(argv) {
+ const out = {
+ n: 200,
+ host: DEFAULT_HOST,
+ origin: 'https://three.ws',
+ coin: THREE_MINT,
+ tier: '',
+ ramp: 30,
+ hold: 120,
+ rate: 8,
+ json: '',
+ };
+ for (let i = 2; i < argv.length; i += 1) {
+ const key = argv[i].replace(/^--/, '');
+ if (!(key in out)) continue;
+ const raw = argv[i + 1];
+ if (raw === undefined || raw.startsWith('--')) continue;
+ out[key] = typeof out[key] === 'number' ? Number(raw) : raw;
+ i += 1;
+ }
+ return out;
+}
+
+const args = parseArgs(process.argv);
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+function percentile(sorted, p) {
+ if (!sorted.length) return null;
+ const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1));
+ return sorted[idx];
+}
+
+function summarize(values) {
+ const sorted = [...values].sort((a, b) => a - b);
+ return {
+ count: sorted.length,
+ p50: percentile(sorted, 50),
+ p95: percentile(sorted, 95),
+ max: sorted.length ? sorted[sorted.length - 1] : null,
+ };
+}
+
+// One virtual player: joins, then walks a slow circle so every move passes the
+// server's MAX_STEP_M teleport clamp (1.2 m) and produces a real state patch
+// broadcast to every other client in the room. A harness that joins and sits
+// idle measures the connection count and nothing about the simulation.
+class VirtualPlayer {
+ constructor(index, opts) {
+ this.index = index;
+ this.opts = opts;
+ this.room = null;
+ this.joinMs = null;
+ this.joinError = null;
+ this.patches = 0;
+ this.moves = 0;
+ this.leftCode = null;
+ this.leftUnexpectedly = false;
+ this.done = false;
+ this.angle = (index / opts.n) * Math.PI * 2;
+ this.radius = 6 + (index % 7);
+ this.timer = null;
+ }
+
+ position() {
+ return {
+ x: Math.cos(this.angle) * this.radius,
+ y: 0,
+ z: Math.sin(this.angle) * this.radius,
+ yaw: this.angle,
+ motion: 'walk',
+ };
+ }
+
+ async join() {
+ const started = Date.now();
+ try {
+ const client = new Client(this.opts.host, { headers: { Origin: this.opts.origin } });
+ this.room = await client.joinOrCreate('walk_world', {
+ coin: this.opts.coin,
+ tier: this.opts.tier,
+ coinName: 'three.ws',
+ coinSymbol: 'three',
+ name: `loadtest-${String(this.index).padStart(4, '0')}`,
+ });
+ this.joinMs = Date.now() - started;
+ // The world broadcasts a wide message vocabulary (tag rounds, floor beats,
+ // king-of-the-hill). A harness that registers none of them floods stderr
+ // with one warning per broadcast per client, which at 400 clients drowns
+ // the numbers we came for. The wildcard handler is the supported way to
+ // say "receive everything, act on nothing".
+ this.room.onMessage('*', () => {});
+ this.room.onStateChange(() => {
+ this.patches += 1;
+ });
+ this.room.onLeave((code) => {
+ this.leftCode = code;
+ if (!this.done) this.leftUnexpectedly = true;
+ this.stop();
+ });
+ this.room.onError((code, message) => {
+ this.joinError = this.joinError || `room_error:${code}:${message || ''}`;
+ });
+ return true;
+ } catch (err) {
+ this.joinMs = Date.now() - started;
+ this.joinError = String(err?.message || err).slice(0, 160);
+ return false;
+ }
+ }
+
+ startWalking() {
+ if (!this.room) return;
+ const stepMs = Math.max(20, Math.round(1000 / this.opts.rate));
+ // 0.5 m per step keeps every move under the server's 1.2 m clamp at any rate.
+ const angularStep = 0.5 / this.radius;
+ this.timer = setInterval(() => {
+ this.angle += angularStep;
+ try {
+ this.room.send('move', this.position());
+ this.moves += 1;
+ } catch {
+ // A send on a socket the server already closed is not a new failure;
+ // onLeave has already recorded the drop.
+ }
+ }, stepMs);
+ }
+
+ stop() {
+ if (this.timer) clearInterval(this.timer);
+ this.timer = null;
+ }
+
+ async leave() {
+ this.done = true;
+ this.stop();
+ try {
+ await this.room?.leave(true);
+ } catch {
+ // Leaving a socket the server already reaped is a no-op, not an error.
+ }
+ }
+}
+
+// The world server's public population count, sampled through the same path the
+// /event landing page reads. Older deployed servers do not expose it; a 404 is
+// reported once rather than treated as an outage, because the count is
+// observability, not the thing under test.
+async function samplePopulation(httpBase, coin) {
+ try {
+ const res = await fetch(`${httpBase}/population?coin=${encodeURIComponent(coin)}`, {
+ signal: AbortSignal.timeout(8000),
+ });
+ if (!res.ok) return { ok: false, status: res.status };
+ return await res.json();
+ } catch (err) {
+ return { ok: false, error: String(err?.message || err).slice(0, 80) };
+ }
+}
+
+async function probeHttp(url) {
+ const started = Date.now();
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(20000), redirect: 'follow' });
+ await res.arrayBuffer();
+ return { ms: Date.now() - started, status: res.status };
+ } catch (err) {
+ return { ms: Date.now() - started, status: 0, error: String(err?.message || err).slice(0, 80) };
+ }
+}
+
+async function run() {
+ const httpBase = args.host.replace(/^ws/, 'http');
+ const pageUrl = `${httpBase.includes('localhost') ? 'http://localhost:3000' : 'https://three.ws'}/play?coin=${args.coin}`;
+
+ console.log(`[capacity] target ${args.host}`);
+ console.log(`[capacity] world coin=${args.coin.slice(0, 12)}… tier=${args.tier || 'general'}`);
+ console.log(`[capacity] plan ${args.n} players, ${args.ramp}s ramp, ${args.hold}s hold, ${args.rate} moves/s each`);
+ console.log(`[capacity] baseline ${JSON.stringify(await samplePopulation(httpBase, args.coin))}`);
+
+ const players = Array.from({ length: args.n }, (_, i) => new VirtualPlayer(i, args));
+ const rampGapMs = args.n > 1 ? (args.ramp * 1000) / args.n : 0;
+
+ const samples = [];
+ const httpProbes = [];
+ const sampler = setInterval(async () => {
+ const live = players.filter((p) => p.room && !p.leftCode).length;
+ const [pop, page] = await Promise.all([samplePopulation(httpBase, args.coin), probeHttp(pageUrl)]);
+ httpProbes.push(page);
+ const sample = { t: new Date().toISOString(), heldSessions: live, population: pop?.players ?? null, pageMs: page.ms, pageStatus: page.status };
+ samples.push(sample);
+ console.log(`[capacity] held=${live} population=${sample.population ?? 'n/a'} page=${page.status} ${page.ms}ms`);
+ }, 10_000);
+
+ const started = Date.now();
+ await Promise.all(
+ players.map(async (player, i) => {
+ await sleep(Math.round(i * rampGapMs));
+ const ok = await player.join();
+ if (ok) player.startWalking();
+ }),
+ );
+ const rampMs = Date.now() - started;
+ const joined = players.filter((p) => p.room).length;
+ console.log(`[capacity] ramp complete in ${(rampMs / 1000).toFixed(1)}s — ${joined}/${args.n} joined`);
+
+ await sleep(args.hold * 1000);
+ clearInterval(sampler);
+
+ const heldAtEnd = players.filter((p) => p.room && !p.leftCode).length;
+ await Promise.all(players.map((p) => p.leave()));
+
+ const joinLatencies = players.filter((p) => p.room).map((p) => p.joinMs);
+ const failures = players.filter((p) => !p.room);
+ const drops = players.filter((p) => p.leftUnexpectedly);
+ const silent = players.filter((p) => p.room && p.patches === 0);
+ const totalMoves = players.reduce((sum, p) => sum + p.moves, 0);
+
+ const failReasons = {};
+ for (const p of failures) {
+ const key = (p.joinError || 'unknown').replace(/\d{3,}/g, 'N').slice(0, 80);
+ failReasons[key] = (failReasons[key] || 0) + 1;
+ }
+
+ const pageMs = httpProbes.filter((p) => p.status >= 200 && p.status < 400).map((p) => p.ms);
+ const report = {
+ target: args.host,
+ coin: args.coin,
+ tier: args.tier || 'general',
+ requested: args.n,
+ joined,
+ heldAtEnd,
+ rampSeconds: Number((rampMs / 1000).toFixed(1)),
+ holdSeconds: args.hold,
+ joinFailures: failures.length,
+ joinFailPct: Number(((failures.length / args.n) * 100).toFixed(2)),
+ failReasons,
+ midRunDrops: drops.length,
+ dropPct: Number(((drops.length / Math.max(1, joined)) * 100).toFixed(2)),
+ silentSessions: silent.length,
+ silentPct: Number(((silent.length / Math.max(1, joined)) * 100).toFixed(2)),
+ joinLatencyMs: summarize(joinLatencies),
+ movesSent: totalMoves,
+ statePatchesReceived: players.reduce((sum, p) => sum + p.patches, 0),
+ pageLatencyMs: summarize(pageMs),
+ pageErrors: httpProbes.filter((p) => !(p.status >= 200 && p.status < 400)).length,
+ samples,
+ };
+
+ const verdicts = [
+ ['join failures', report.joinFailPct, THRESHOLDS.joinFailPct, '%'],
+ ['mid-run drops', report.dropPct, THRESHOLDS.dropPct, '%'],
+ ['join p95', report.joinLatencyMs.p95 ?? 0, THRESHOLDS.joinP95Ms, 'ms'],
+ ['silent sessions', report.silentPct, THRESHOLDS.silentPct, '%'],
+ ];
+
+ console.log('\n=== capacity smoke ===');
+ console.log(`requested ${report.requested}`);
+ console.log(`joined ${report.joined} (${(100 - report.joinFailPct).toFixed(1)}%)`);
+ console.log(`held at end ${report.heldAtEnd}`);
+ console.log(`join latency p50 ${report.joinLatencyMs.p50}ms · p95 ${report.joinLatencyMs.p95}ms · max ${report.joinLatencyMs.max}ms`);
+ console.log(`moves sent ${report.movesSent}`);
+ console.log(`state patches ${report.statePatchesReceived}`);
+ console.log(`page latency p50 ${report.pageLatencyMs.p50}ms · p95 ${report.pageLatencyMs.p95}ms (${report.pageErrors} errors)`);
+ if (Object.keys(failReasons).length) console.log(`fail reasons ${JSON.stringify(failReasons)}`);
+
+ let pass = true;
+ console.log('');
+ for (const [label, value, limit, unit] of verdicts) {
+ const ok = value <= limit;
+ if (!ok) pass = false;
+ console.log(`${ok ? 'PASS' : 'FAIL'} ${label.padEnd(16)} ${value}${unit} (limit ${limit}${unit})`);
+ }
+
+ if (args.json) {
+ writeFileSync(args.json, JSON.stringify(report, null, 2));
+ console.log(`\nreport → ${args.json}`);
+ }
+
+ process.exit(pass ? 0 : 1);
+}
+
+run().catch((err) => {
+ console.error('[capacity] FATAL', err);
+ process.exit(2);
+});
diff --git a/scripts/play-multiplayer-e2e.mjs b/scripts/play-multiplayer-e2e.mjs
index 0a03a3eeb..aeb9157ab 100644
--- a/scripts/play-multiplayer-e2e.mjs
+++ b/scripts/play-multiplayer-e2e.mjs
@@ -129,7 +129,7 @@ async function openClient(browser, tag, name) {
console.log(`${at()} [${tag}][ws open] ${ws.url().slice(0, 90)}`);
ws.on('close', () => console.log(`${at()} [${tag}][ws close]`));
});
- await page.goto(WORLD, { waitUntil: 'domcontentloaded', timeout: 90000 });
+ await page.goto(WORLD, { waitUntil: 'domcontentloaded', timeout: LOAD_MS });
return { tag, ctx, page };
}
@@ -175,7 +175,7 @@ try {
const online = async (c) => until(c.page, () => {
const net = window.__CC__?.net;
return { ok: net?.status === 'online' && window.__CC__?.phase === 'world', status: net?.status, phase: window.__CC__?.phase };
- }, { timeout: 60000 });
+ }, { timeout: JOIN_MS });
const aOnline = await online(a);
const bOnline = await online(b);
check('A joins the world online', aOnline?.ok === true, JSON.stringify(aOnline));
@@ -184,10 +184,10 @@ try {
const sawEachOther = await until(a.page, () => {
const cc = window.__CC__;
return { ok: (cc?.remotes?.size || 0) >= 1, n: cc?.remotes?.size || 0 };
- }, { timeout: 30000 });
- check('A sees B within 30s of load', sawEachOther?.ok === true,
+ }, { timeout: JOIN_MS });
+ check('A sees B after load', sawEachOther?.ok === true,
`${((Date.now() - joinStart) / 1000).toFixed(1)}s to first peer`);
- const bSees = await until(b.page, () => ({ ok: (window.__CC__?.remotes?.size || 0) >= 1, n: window.__CC__?.remotes?.size || 0 }), { timeout: 30000 });
+ const bSees = await until(b.page, () => ({ ok: (window.__CC__?.remotes?.size || 0) >= 1, n: window.__CC__?.remotes?.size || 0 }), { timeout: JOIN_MS });
check('B sees A', bSees?.ok === true, JSON.stringify(bSees));
// ------------------------------------------------------- name + look sync
diff --git a/scripts/shots/results.json b/scripts/shots/results.json
new file mode 100644
index 000000000..69295b19d
--- /dev/null
+++ b/scripts/shots/results.json
@@ -0,0 +1,511 @@
+[
+ {
+ "kind": "upcoming",
+ "theme": "dark",
+ "label": "desktop",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "upcoming",
+ "chip": "Upcoming",
+ "name": "$THREE First Holders Meetup",
+ "clock": "1day02hours04minutes48seconds",
+ "cta": "Join the $THREE world",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": false,
+ "when": "Doors open Saturday, August 8 at 11:41 AM UTC (UTC). Runs until 1:36 PM.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 5,
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "upcoming",
+ "theme": "dark",
+ "label": "mobile",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened.",
+ "error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)"
+ ],
+ "state": "upcoming",
+ "chip": "Upcoming",
+ "name": "$THREE First Holders Meetup",
+ "clock": "1day02hours04minutes53seconds",
+ "cta": "Join the $THREE world",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": false,
+ "when": "Doors open Saturday, August 8 at 11:41 AM UTC (UTC). Runs until 1:36 PM.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 5,
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "upcoming",
+ "theme": "dark",
+ "label": "narrow",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "upcoming",
+ "chip": "Upcoming",
+ "name": "$THREE First Holders Meetup",
+ "clock": "1day02hours04minutes55seconds",
+ "cta": "Join the $THREE world",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": false,
+ "when": "Doors open Saturday, August 8 at 11:41 AM UTC (UTC). Runs until 1:36 PM.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 5,
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "upcoming",
+ "theme": "light",
+ "label": "desktop",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened.",
+ "warning: [.WebGL-0x1a8c0240ac00]GL Driver Message (OpenGL, Performance, GL_CLOSE_PATH_NV, High): GPU stall due to ReadPixels"
+ ],
+ "state": "upcoming",
+ "chip": "Upcoming",
+ "name": "$THREE First Holders Meetup",
+ "clock": "1day02hours04minutes51seconds",
+ "cta": "Join the $THREE world",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": false,
+ "when": "Doors open Saturday, August 8 at 11:41 AM UTC (UTC). Runs until 1:36 PM.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 5,
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "upcoming",
+ "theme": "light",
+ "label": "mobile",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "upcoming",
+ "chip": "Upcoming",
+ "name": "$THREE First Holders Meetup",
+ "clock": "1day02hours04minutes55seconds",
+ "cta": "Join the $THREE world",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": false,
+ "when": "Doors open Saturday, August 8 at 11:42 AM UTC (UTC). Runs until 1:37 PM.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 5,
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "live",
+ "theme": "dark",
+ "label": "desktop",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened.",
+ "error: Failed to load resource: the server responded with a status of 404 (Not Found)"
+ ],
+ "state": "live",
+ "chip": "Live now",
+ "name": "$THREE First Holders Meetup",
+ "clock": "LIVEright now01:12:55left to join",
+ "cta": "Join the $THREE world",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": false,
+ "when": "Running now until 10:50 AM (UTC).",
+ "liveHidden": false,
+ "liveNum": "(hidden)",
+ "liveTitle": "The doors are open",
+ "agendaRows": 5,
+ "nowRow": "Fortune's Folly wheel hournow",
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "live",
+ "theme": "dark",
+ "label": "mobile",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened.",
+ "error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)",
+ "warning: [.WebGL-0x1a8c01868800]GL Driver Message (OpenGL, Performance, GL_CLOSE_PATH_NV, High): GPU stall due to ReadPixels",
+ "warning: [.WebGL-0x1a8c01868800]GL Driver Message (OpenGL, Performance, GL_CLOSE_PATH_NV, High): GPU stall due to ReadPixels",
+ "warning: [.WebGL-0x1a8c01868800]GL Driver Message (OpenGL, Performance, GL_CLOSE_PATH_NV, High): GPU stall due to ReadPixels (this message will no longer repeat)"
+ ],
+ "state": "live",
+ "chip": "Live now",
+ "name": "$THREE First Holders Meetup",
+ "clock": "LIVEright now01:12:31left to join",
+ "cta": "Join the $THREE world",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": false,
+ "when": "Running now until 10:50 AM (UTC).",
+ "liveHidden": false,
+ "liveNum": "(hidden)",
+ "liveTitle": "The doors are open",
+ "agendaRows": 5,
+ "nowRow": "Fortune's Folly wheel hournow",
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "live",
+ "theme": "dark",
+ "label": "narrow",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened.",
+ "error: Failed to load resource: the server responded with a status of 404 (Not Found)"
+ ],
+ "state": "live",
+ "chip": "Live now",
+ "name": "$THREE First Holders Meetup",
+ "clock": "LIVEright now01:12:49left to join",
+ "cta": "Join the $THREE world",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": false,
+ "when": "Running now until 10:51 AM (UTC).",
+ "liveHidden": false,
+ "liveNum": "(hidden)",
+ "liveTitle": "The doors are open",
+ "agendaRows": 5,
+ "nowRow": "Fortune's Folly wheel hournow",
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "live",
+ "theme": "light",
+ "label": "desktop",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened.",
+ "error: Failed to load resource: the server responded with a status of 404 (Not Found)"
+ ],
+ "state": "live",
+ "chip": "Live now",
+ "name": "$THREE First Holders Meetup",
+ "clock": "LIVEright now01:12:51left to join",
+ "cta": "Join the $THREE world",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": false,
+ "when": "Running now until 10:51 AM (UTC).",
+ "liveHidden": false,
+ "liveNum": "(hidden)",
+ "liveTitle": "The doors are open",
+ "agendaRows": 5,
+ "nowRow": "Fortune's Folly wheel hournow",
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "live",
+ "theme": "light",
+ "label": "mobile",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "live",
+ "chip": "Live now",
+ "name": "$THREE First Holders Meetup",
+ "clock": "LIVEright now01:12:54left to join",
+ "cta": "Join the $THREE world",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": false,
+ "when": "Running now until 10:51 AM (UTC).",
+ "liveHidden": false,
+ "liveNum": "(hidden)",
+ "liveTitle": "The doors are open",
+ "agendaRows": 5,
+ "nowRow": "Fortune's Folly wheel hournow",
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "ended",
+ "theme": "dark",
+ "label": "desktop",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "ended",
+ "chip": "This event has ended",
+ "name": "$THREE First Holders Meetup",
+ "clock": "",
+ "cta": "Enter the world anyway",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": true,
+ "when": "It ran on Thursday, August 6, 2026. The world is still open, and the next event will show up here.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 5,
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "ended",
+ "theme": "dark",
+ "label": "mobile",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "ended",
+ "chip": "This event has ended",
+ "name": "$THREE First Holders Meetup",
+ "clock": "",
+ "cta": "Enter the world anyway",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": true,
+ "when": "It ran on Thursday, August 6, 2026. The world is still open, and the next event will show up here.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 5,
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "ended",
+ "theme": "dark",
+ "label": "narrow",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "ended",
+ "chip": "This event has ended",
+ "name": "$THREE First Holders Meetup",
+ "clock": "",
+ "cta": "Enter the world anyway",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": true,
+ "when": "It ran on Thursday, August 6, 2026. The world is still open, and the next event will show up here.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 5,
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "ended",
+ "theme": "light",
+ "label": "desktop",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "ended",
+ "chip": "This event has ended",
+ "name": "$THREE First Holders Meetup",
+ "clock": "",
+ "cta": "Enter the world anyway",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": true,
+ "when": "It ran on Thursday, August 6, 2026. The world is still open, and the next event will show up here.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 5,
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "ended",
+ "theme": "light",
+ "label": "mobile",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "ended",
+ "chip": "This event has ended",
+ "name": "$THREE First Holders Meetup",
+ "clock": "",
+ "cta": "Enter the world anyway",
+ "ctaHref": "/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=three",
+ "calHidden": true,
+ "when": "It ran on Thursday, August 6, 2026. The world is still open, and the next event will show up here.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 5,
+ "scheduleHidden": false,
+ "hScroll": false
+ },
+ {
+ "kind": "none",
+ "theme": "dark",
+ "label": "desktop",
+ "errors": [
+ "error: Failed to load resource: the server responded with a status of 404 (Not Found)",
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "ended",
+ "chip": "No event scheduled",
+ "name": "The world is open anyway.",
+ "clock": "",
+ "cta": "Enter the three.ws world",
+ "ctaHref": "/play",
+ "calHidden": true,
+ "when": "Follow the changelog to hear about the next one before it starts.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 0,
+ "scheduleHidden": true,
+ "hScroll": false
+ },
+ {
+ "kind": "none",
+ "theme": "dark",
+ "label": "mobile",
+ "errors": [
+ "error: Failed to load resource: the server responded with a status of 404 (Not Found)",
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "ended",
+ "chip": "No event scheduled",
+ "name": "The world is open anyway.",
+ "clock": "",
+ "cta": "Enter the three.ws world",
+ "ctaHref": "/play",
+ "calHidden": true,
+ "when": "Follow the changelog to hear about the next one before it starts.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 0,
+ "scheduleHidden": true,
+ "hScroll": false
+ },
+ {
+ "kind": "none",
+ "theme": "dark",
+ "label": "narrow",
+ "errors": [
+ "error: Failed to load resource: the server responded with a status of 404 (Not Found)",
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "ended",
+ "chip": "No event scheduled",
+ "name": "The world is open anyway.",
+ "clock": "",
+ "cta": "Enter the three.ws world",
+ "ctaHref": "/play",
+ "calHidden": true,
+ "when": "Follow the changelog to hear about the next one before it starts.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 0,
+ "scheduleHidden": true,
+ "hScroll": false
+ },
+ {
+ "kind": "none",
+ "theme": "light",
+ "label": "desktop",
+ "errors": [
+ "error: Failed to load resource: the server responded with a status of 404 (Not Found)",
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened."
+ ],
+ "state": "ended",
+ "chip": "No event scheduled",
+ "name": "The world is open anyway.",
+ "clock": "",
+ "cta": "Enter the three.ws world",
+ "ctaHref": "/play",
+ "calHidden": true,
+ "when": "Follow the changelog to hear about the next one before it starts.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 0,
+ "scheduleHidden": true,
+ "hScroll": false
+ },
+ {
+ "kind": "none",
+ "theme": "light",
+ "label": "mobile",
+ "errors": [
+ "error: WebSocket connection to 'wss://fantastic-space-orbit-xrrw6xrjxxjc977j-3000.app.github.dev/?token=GeEzFU7CM6dB' failed: Error during WebSocket handshake: Unexpected response code: 404",
+ "error: Failed to load resource: the server responded with a status of 404 (Not Found)",
+ "error: [vite] failed to connect to websocket (Error: WebSocket closed without opened.). ",
+ "pageerror: WebSocket closed without opened.",
+ "error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)"
+ ],
+ "state": "ended",
+ "chip": "No event scheduled",
+ "name": "The world is open anyway.",
+ "clock": "",
+ "cta": "Enter the three.ws world",
+ "ctaHref": "/play",
+ "calHidden": true,
+ "when": "Follow the changelog to hear about the next one before it starts.",
+ "liveHidden": true,
+ "liveNum": "—",
+ "liveTitle": "In the world right now",
+ "agendaRows": 0,
+ "scheduleHidden": true,
+ "hScroll": false
+ },
+ {
+ "kind": "ics",
+ "file": "/workspaces/three.ws/scripts/shots/three-first-meetup.ics",
+ "note": "Calendar file downloaded. Open it to add the event."
+ },
+ {
+ "kind": "keyboard",
+ "tabsToCta": null
+ }
+]
\ No newline at end of file
diff --git a/scripts/shots/three-first-meetup.ics b/scripts/shots/three-first-meetup.ics
new file mode 100644
index 000000000..fd3234a0c
--- /dev/null
+++ b/scripts/shots/three-first-meetup.ics
@@ -0,0 +1,23 @@
+BEGIN:VCALENDAR
+VERSION:2.0
+PRODID:-//three.ws//Live event//EN
+CALSCALE:GREGORIAN
+METHOD:PUBLISH
+BEGIN:VEVENT
+DTSTAMP:20260807T094038Z
+DTSTART:20260808T114531Z
+DTEND:20260808T134031Z
+SUMMARY:$THREE First Holders Meetup
+DESCRIPTION:The first live gathering in the three.ws world. Drop in\, hang
+ out\, win prizes.\n11:45 AM - Doors open in the plaza\n12:05 PM - King of
+ the Totem showdown\n12:30 PM - Fortune's Folly wheel hour\n12:55 PM - Plaz
+ a dance-off\n1:30 PM - Fireworks finale\nJoin: http://localhost:3000/play?
+ coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&name=three.ws&symbol=thr
+ ee
+LOCATION:http://localhost:3000/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyD
+ CatJVJpump&name=three.ws&symbol=three
+URL:http://localhost:3000/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJV
+ Jpump&name=three.ws&symbol=three
+END:VEVENT
+END:VCALENDAR
diff --git a/src/event-page.js b/src/event-page.js
index 5be66040d..49f84aafe 100644
--- a/src/event-page.js
+++ b/src/event-page.js
@@ -1,4 +1,4 @@
-// /event — the one link the community shares before and during a live event.
+// /event: the one link the community shares before and during a live event.
//
// Everything on this page is derived from ONE file: public/event.json, served at
// /event.json. That is the same config the /play lobby banner and in-world pill
@@ -9,9 +9,9 @@
// surface moves together.
//
// Three states, all designed, all reachable:
-// upcoming — ticking days/hours/minutes/seconds to the doors opening
-// live — a LIVE marker plus the real population of the event world
-// ended — says the event happened and still routes people into the world,
+// upcoming: ticking days/hours/minutes/seconds to the doors opening
+// live: a LIVE marker plus the real population of the event world
+// ended: says the event happened and still routes people into the world,
// because /play is open whether or not an event is running
// A missing or malformed config is a fourth, honest state: "no event scheduled",
// with the same door into the world. The page never invents an event.
@@ -167,7 +167,7 @@ function icsFold(line) {
}
function buildIcs(cfg, absoluteLink) {
- const agendaLines = cfg.agenda.map((a) => `${fmtTimeOnly(cfg.startsAt + a.atMin * 60_000)} — ${a.title}`);
+ const agendaLines = cfg.agenda.map((a) => `${fmtTimeOnly(cfg.startsAt + a.atMin * 60_000)} - ${a.title}`);
const description = [cfg.tagline, ...agendaLines, `Join: ${absoluteLink}`].filter(Boolean).join('\n');
const lines = [
'BEGIN:VCALENDAR',
diff --git a/src/game/agent-commerce.js b/src/game/agent-commerce.js
index 3ce021f00..a6a39ecff 100644
--- a/src/game/agent-commerce.js
+++ b/src/game/agent-commerce.js
@@ -165,6 +165,11 @@ export class AgentCommerce {
this.sessionTotal = 0;
this._inRange = false;
this._manifest = null;
+ this._disposed = false;
+ // One controller covers every fetch this module starts (manifest + the
+ // x402-pay SSE stream) so dispose() can cut them all off at once.
+ this._abort = new AbortController();
+ this._sseReader = null;
this._injectStyles();
@@ -191,7 +196,7 @@ export class AgentCommerce {
// Pull the full clip manifest so gestures can reach any animation (the
// shared emote set is only the first six). Idempotent + cached.
loadManifest();
- fetch(MANIFEST_URL, { cache: 'force-cache' })
+ fetch(MANIFEST_URL, { cache: 'force-cache', signal: this._abort.signal })
.then((r) => (r.ok ? r.json() : []))
.then((m) => { this._manifest = Array.isArray(m) ? m : []; })
.catch(() => { this._manifest = []; });
@@ -434,6 +439,7 @@ export class AgentCommerce {
// tool. /api/x402-pay handles the Solana USDC payment, then dispatches
// the call and returns ORACLE's catalog alongside the settlement.
body: JSON.stringify({ tool: PAID_TOOL, args: {} }),
+ signal: this._abort.signal,
});
if (!res.ok || !res.body) {
const text = await res.text().catch(() => '');
@@ -468,6 +474,7 @@ export class AgentCommerce {
// 'dispatched' carries only timing — no UI beat needed.
}
+ if (this._disposed) return;
if (!intel || !settled) throw new Error('incomplete response from payment service');
// The settlement is on-chain truth; payer/payee/amount live on the result's
@@ -489,6 +496,7 @@ export class AgentCommerce {
// Auto-dismiss the panel after the receipt has been read.
this._scheduleHide(9000);
} catch (err) {
+ if (this._disposed) return; // torn down mid-round — nothing left to render
// `active` already points at the stage that failed.
this.seller.say(LINES.seller.error);
this.buyer.say(LINES.buyer.error);
@@ -567,37 +575,62 @@ export class AgentCommerce {
this.panel.appendChild(msg);
}
- // SSE event reader — same framing /api/x402-pay speaks.
+ // SSE event reader — same framing /api/x402-pay speaks. The reader handle is
+ // kept on the instance so dispose() can cancel a stream still in flight.
async *_sse(res) {
const reader = res.body.getReader();
+ this._sseReader = reader;
const dec = new TextDecoder();
let buf = '';
- while (true) {
- const { value, done } = await reader.read();
- if (done) break;
- buf += dec.decode(value, { stream: true });
- const chunks = buf.split('\n\n');
- buf = chunks.pop();
- for (const chunk of chunks) {
- if (!chunk.trim()) continue;
- let event = 'message', data = {};
- for (const line of chunk.split('\n')) {
- if (line.startsWith('event:')) event = line.slice(6).trim();
- if (line.startsWith('data:')) { try { data = JSON.parse(line.slice(5).trim()); } catch { /* ignore */ } }
+ try {
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += dec.decode(value, { stream: true });
+ const chunks = buf.split('\n\n');
+ buf = chunks.pop();
+ for (const chunk of chunks) {
+ if (!chunk.trim()) continue;
+ let event = 'message', data = {};
+ for (const line of chunk.split('\n')) {
+ if (line.startsWith('event:')) event = line.slice(6).trim();
+ if (line.startsWith('data:')) { try { data = JSON.parse(line.slice(5).trim()); } catch { /* ignore */ } }
+ }
+ yield { event, data };
}
- yield { event, data };
}
+ } finally {
+ this._sseReader = null;
}
}
dispose() {
+ this._disposed = true;
clearTimeout(this._introTimer);
clearTimeout(this._hideTimer);
+ // Kill anything still on the wire: the manifest fetch and a mid-round
+ // x402-pay SSE stream both hang off the shared controller.
+ this._abort.abort();
+ this._sseReader?.cancel().catch(() => {});
+ this._sseReader = null;
this.seller.dispose();
this.buyer.dispose();
this.jumbotron?.dispose(); this.jumbotron = null;
- if (this.marker) { this.scene.remove(this.marker); this.marker = null; }
+ if (this.marker) {
+ this.scene.remove(this.marker);
+ // Ground ring: its own RingGeometry + material.
+ this._ring.geometry.dispose();
+ this._ring.material.dispose();
+ this._ring = null;
+ // Sign: PlaneGeometry, a MeshBasicMaterial, and its CanvasTexture map.
+ this.sign.geometry.dispose();
+ this.sign.material.map?.dispose();
+ this.sign.material.dispose();
+ this.sign = null;
+ this.marker = null;
+ }
this.prompt?.remove();
this.panel?.remove();
+ document.getElementById('ac-styles')?.remove();
}
}
diff --git a/src/game/agent-desk.js b/src/game/agent-desk.js
index b2712fc85..4ee904ed8 100644
--- a/src/game/agent-desk.js
+++ b/src/game/agent-desk.js
@@ -11,8 +11,11 @@
// • An agent avatar seated behind the desk (idle-animated, driven by the
// same retargeting pipeline as every other avatar in the world).
// • Proximity detection: when the local player walks within NEAR_DIST units
-// the monitor "wakes up" (brighter emissive) and a HUD prompt appears
-// offering to open the full 2D watch view.
+// the monitor wakes up (the screen face brightens to full white) and the
+// desk pings watch-intent so the caster pool upgrades it to live frames.
+// Clicking/tapping the monitor opens the full 2D watch view via openWatch()
+// (coincommunities wires the pointer pick; the cursor turns to a pointer
+// over the screen).
//
// Follows chart-screen.js in every structural detail — CanvasTexture updated
// per-frame, update(dt) called from the scene loop, dispose() for cleanup.
@@ -186,7 +189,7 @@ function paintDesk(ctx, tex, actions, status, agentName, t) {
ctx.fillText(`three.ws · ${actions.length || 0} actions`, cX, sbY + 12);
ctx.textAlign = 'right';
ctx.fillStyle = faint;
- ctx.fillText('walk up · press E to watch', winX + winW - 10, sbY + 12);
+ ctx.fillText('walk up · click the screen to watch', winX + winW - 10, sbY + 12);
ctx.textAlign = 'left';
tex.needsUpdate = true;
@@ -275,6 +278,11 @@ export function createAgentDesk(scene, agent, opts = {}) {
const tex = makeScreenTexture(canvas);
const screenMat = screenMaterial(tex);
+ // Idle screens sit slightly dimmed; walking near lifts them to full white.
+ // MeshBasicMaterial.color multiplies the map, so this is a real brightness
+ // change (the material is opaque — opacity would be a no-op without
+ // transparent: true).
+ screenMat.color.setHex(0xbbbbbb);
const screen = new Mesh(new PlaneGeometry(MON_W, MON_H), screenMat);
screen.position.set(0, monCY, -0.35 + 0.07);
screen.userData.agentDesk = true;
@@ -373,8 +381,8 @@ export function createAgentDesk(scene, agent, opts = {}) {
const wasNear = near;
near = dist < NEAR_DIST;
if (near !== wasNear) {
- // Screen emissive boost.
- screenMat.opacity = near ? 1.0 : 0.92;
+ // Wake the screen: full-white map when near, dimmed when far.
+ screenMat.color.setHex(near ? 0xffffff : 0xbbbbbb);
}
if (near) pingWatchIntent();
}
@@ -392,7 +400,7 @@ export function createAgentDesk(scene, agent, opts = {}) {
openWatch() {
const url = `/dashboard-next/watch?agentId=${encodeURIComponent(agent.agentId)}`;
- window.open(url, '_blank');
+ window.open(url, '_blank', 'noopener,noreferrer');
},
dispose() {
diff --git a/src/game/ambient-crowd.js b/src/game/ambient-crowd.js
index d8940e238..85358aecd 100644
--- a/src/game/ambient-crowd.js
+++ b/src/game/ambient-crowd.js
@@ -12,18 +12,19 @@
// rest of the scene is under active development.
import { Group, Vector3 } from 'three';
-import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
-import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
-import { getMeshoptDecoder } from '../viewer/internal.js';
-import { Box3, Mesh, CapsuleGeometry, SphereGeometry, MeshStandardMaterial } from 'three';
import { AnimationManager } from '../animation-manager.js';
import { detectProfile } from '../club-perf.js';
+// The crowd wears the same models the players do, so it loads them through the
+// same shared template cache instead of keeping a second loader and a second
+// copy of every model. That also buys it the Draco + VRM decoders and the
+// refcounted eviction that only lived on the player path before.
+import {
+ buildAvatar as buildRigAvatar, releaseAvatar, hasModelTemplate,
+ loadManifest as loadRigManifest, getAllEmoteDefs,
+ AVATAR_DEFAULT, CLIP_IDLE, CLIP_WALK,
+} from './avatar-rig.js';
import { loadCitizenPool, isCitizen, openCitizenProfile } from './npc/citizens.js';
-const AVATAR_DEFAULT = '/avatars/default.glb';
-const MANIFEST_URL = '/animations/manifest.json';
-const CLIP_IDLE = 'idle';
-const CLIP_WALK = 'av-walk-feminine';
const WORLD_RADIUS = 54; // a touch inside the plaza edge
const AMBIENT_SPEED = 1.7; // gentle stroll, slower than the player
@@ -69,32 +70,21 @@ const BUDGET = crowdBudget();
const NAMES = ['satoshi', 'anon', 'gm_ser', 'degenape', 'moonboy', 'pepe', 'wagmi', 'hodlqueen', 'vibes', 'chad', 'frfr', 'fomo', 'ngmi', 'based_dev', 'gigachad', '0xshill', 'florp'];
const LINES = ['gm ☀️', 'wen moon', 'lfg 🚀', 'wagmi', 'probably nothing', 'few understand', 'based', 'diamond hands 💎', 'ser…', 'this is the way', 'bullish af', 'vibes immaculate', 'we so back', 'iykyk', 'up only 📈'];
-const _gltf = new GLTFLoader();
-// three.ws GLBs may carry EXT_meshopt_compression — decoder required before load
-const _meshoptReady = getMeshoptDecoder().then((d) => _gltf.setMeshoptDecoder(d));
-let _defs = null; // [idle, walk] animation defs
let _emotes = null; // a handful of emote defs
let _avatars = null; // pool of affordable gallery picks ([] once the fetch settles)
-// One download per distinct model, shared by every wanderer that wears it.
-// SkeletonUtils.clone() deep-copies a skinned hierarchy (bones included) while
-// sharing geometry and materials with the template, so the second wanderer in a
-// given model costs no network and almost no memory. Cloned meshes share the
-// template's buffers, so a template must outlive every clone of it. Disposal
-// happens in AmbientCrowd.clear(), once the whole crowd is gone.
-const _templates = new Map(); // url → Promise<Group>
-let _spentBytes = 0; // gallery bytes downloaded this visit
+// Models the crowd has actually worn this visit, and the bytes it charged for
+// them. The models themselves live in avatar-rig's shared template cache (one
+// download per URL across players AND wanderers); this set only exists so the
+// crowd can keep drawing from what it already paid for once its own download
+// budget is spent.
+const _worn = new Set();
+let _spentBytes = 0;
async function loadManifest() {
- if (_defs) return;
- let manifest = [];
- try {
- const r = await fetch(MANIFEST_URL, { cache: 'force-cache' });
- if (r.ok) manifest = await r.json();
- } catch { /* locomotion-only fallback below */ }
- const by = (n) => manifest.find((d) => d.name === n);
- _defs = [by(CLIP_IDLE), by(CLIP_WALK)].filter(Boolean);
- _emotes = manifest.filter((d) => d.name !== CLIP_IDLE && d.name !== CLIP_WALK).slice(0, 6);
+ if (_emotes) return;
+ await loadRigManifest();
+ _emotes = getAllEmoteDefs().slice(0, 6);
}
// Pull a varied set of real avatars from the public gallery so the crowd reads as
@@ -111,72 +101,25 @@ async function loadAvatarPool() {
_avatars = records.filter((p) => p.url && p.bytes > 0 && p.bytes <= BUDGET.maxModelBytes);
}
-// Fetch a model once and hand every later wanderer a clone of it. `bytes` is the
-// published size charged against this visit's download budget; a cache hit costs
-// nothing and is never charged twice.
-function loadTemplate(url, bytes) {
- let pending = _templates.get(url);
- if (!pending) {
- _spentBytes += bytes;
- pending = _meshoptReady.then(() => _gltf.loadAsync(url)).then((gltf) => gltf.scene);
- _templates.set(url, pending);
- // Evict a failed load so one bad model doesn't poison the URL for the rest
- // of the visit, and refund its budget: nothing was actually held.
- pending.catch(() => {
- if (_templates.get(url) === pending) _templates.delete(url);
- _spentBytes = Math.max(0, _spentBytes - bytes);
- });
- }
- return pending;
-}
-
-// Load a gallery avatar (or the default) into a rig + animation manager. Falls
-// back to a simple stand-in so a wanderer is never invisible.
+// Dress a wanderer through the shared avatar pipeline: one download and one
+// parse per distinct model across the whole scene, Draco/meshopt/VRM decoders
+// wired, a capsule stand-in of last resort, and refcounted templates that free
+// themselves once nothing wears them. Only locomotion clips are loaded here; a
+// wanderer's occasional emote fetches its clip on demand.
+//
+// `bytes` is the model's published size, charged against this visit's download
+// budget the first time the crowd asks for a model nothing else already holds.
async function buildAvatar(rig, anim, pick) {
const url = pick?.url || AVATAR_DEFAULT;
- try {
- const template = await loadTemplate(url, pick?.bytes || 0);
- const model = cloneSkinnedScene(template);
- model.traverse((n) => { if (n.isMesh) { n.castShadow = BUDGET.shadows; n.receiveShadow = false; } });
- const box = new Box3().setFromObject(model);
- model.position.y -= box.min.y;
- rig.add(model);
- anim.attach(model);
- if (_defs?.length) { anim.setAnimationDefs(_defs); await anim.loadAll(); await anim.crossfadeTo(CLIP_IDLE, 0); }
- return Math.max(0.5, box.max.y - box.min.y);
- } catch {
- // A gallery model that fails to load shouldn't strand the wanderer on a
- // capsule — fall back to the bundled default once before the stand-in.
- if (url !== AVATAR_DEFAULT) return buildAvatar(rig, anim, null);
- const body = new Mesh(new CapsuleGeometry(0.32, 0.7, 4, 10), new MeshStandardMaterial({ color: 0x9aa3ad }));
- body.position.y = 0.85; body.castShadow = BUDGET.shadows;
- const head = new Mesh(new SphereGeometry(0.28, 14, 10), new MeshStandardMaterial({ color: 0xc9cdd2 }));
- head.position.y = 1.55; head.castShadow = BUDGET.shadows;
- rig.add(body, head);
- return 1.7;
- }
+ if (!hasModelTemplate(url)) _spentBytes += pick?.bytes || 0;
+ const { height } = await buildRigAvatar(rig, url, anim, { clips: 'locomotion' });
+ _worn.add(url);
+ // Shadow casting is the crowd's own budget line: on the low tier five
+ // shadow-casting skinned meshes cost more than a decorative crowd is worth.
+ if (!BUDGET.shadows) rig.traverse((n) => { if (n.isMesh) n.castShadow = false; });
+ return height;
}
-// Release every model this visit downloaded. Safe only once no wanderer is left
-// standing: clones share their template's geometry and materials, so freeing a
-// template while a clone still renders would corrupt it.
-function disposeTemplates() {
- for (const pending of _templates.values()) {
- pending.then((scene) => {
- scene.traverse((n) => {
- if (!n.isMesh) return;
- n.geometry?.dispose?.();
- for (const mat of Array.isArray(n.material) ? n.material : [n.material]) {
- if (!mat) continue;
- for (const value of Object.values(mat)) value?.isTexture && value.dispose();
- mat.dispose?.();
- }
- });
- }).catch(() => { /* never loaded, nothing to free */ });
- }
- _templates.clear();
- _spentBytes = 0;
-}
async function playEmote(anim, motion) {
if (!_emotes?.length) return;
@@ -301,6 +244,10 @@ class Wanderer {
dispose() {
this._disposed = true;
this.scene.remove(this.rig);
+ // Dereference the shared model template and free this clone's own
+ // materials (and any capsule stand-in) before dropping the rig; a bare
+ // rig.clear() drops the JS reference and leaks the GPU buffers.
+ releaseAvatar(this.rig);
this.rig.clear();
// Drop the mixer + its bound clip actions. The clips themselves are shared
// module-wide and stay cached; only this rig's bindings go.
@@ -338,7 +285,7 @@ class AmbientCrowd {
_takeAvatar() {
if (!_avatars?.length) return null;
if (_spentBytes >= BUDGET.sessionBytes) {
- const resident = [..._templates.keys()];
+ const resident = [..._worn];
if (!resident.length) return null;
const url = resident[(Math.random() * resident.length) | 0];
// Keep the identity riding the resident model: same record, zero new
@@ -389,10 +336,13 @@ class AmbientCrowd {
for (const w of this.list) w.dispose();
this.list = [];
this._avatarBag = [];
- // Every clone is gone, so the shared templates can go too. Leaving a world
- // used to keep every model the crowd had ever worn resident for the rest of
- // the page's life; on a phone that alone could outlive the tab.
- disposeTemplates();
+ // Each dispose() above released its template reference; anything no player
+ // still wears is now free to be evicted by the shared cache's memory
+ // budget. Leaving a world used to keep every model the crowd had ever worn
+ // resident for the rest of the page's life; on a phone that alone could
+ // outlive the tab.
+ _worn.clear();
+ _spentBytes = 0;
}
}
diff --git a/src/game/avatar-rig.js b/src/game/avatar-rig.js
index f2b47be7c..89979cb24 100644
--- a/src/game/avatar-rig.js
+++ b/src/game/avatar-rig.js
@@ -188,6 +188,15 @@ function loadTemplate(url) {
return entry;
}
+/**
+ * True when a model is already downloaded (or downloading) into the shared
+ * template cache, so wearing it again costs no network. The ambient crowd reads
+ * this to decide whether picking a gallery model spends its download budget.
+ */
+export function hasModelTemplate(url) {
+ return _templates.has(url);
+}
+
function disposeTemplateScene(scene) {
scene.traverse((n) => {
if (!n.isMesh) return;
diff --git a/src/game/chart-screen.js b/src/game/chart-screen.js
index 06dabb216..c01d43b15 100644
--- a/src/game/chart-screen.js
+++ b/src/game/chart-screen.js
@@ -312,7 +312,10 @@ export function createChartScreen(scene, coin, opts = {}) {
ctx.fillText(nm.length > 22 ? nm.slice(0, 21) + '…' : nm, hx, headY - 4);
ctx.fillStyle = COL.dim;
ctx.font = '600 20px Inter, system-ui, sans-serif';
- const sym = coin.symbol ? '$' + coin.symbol.toUpperCase() : '';
+ // Symbols are arbitrary pump.fun strings; cap it like the name above so a
+ // 60-char symbol can't run through the LIVE badge and the pump.fun affordance.
+ const rawSym = coin.symbol ? String(coin.symbol).toUpperCase() : '';
+ const sym = rawSym ? '$' + (rawSym.length > 14 ? rawSym.slice(0, 13) + '…' : rawSym) : '';
ctx.fillText(`${sym}${sym ? ' · ' : ''}pump.fun`, hx, headY + 24);
// live badge (top-right), pulsing
diff --git a/src/game/combat-system.js b/src/game/combat-system.js
index 99e6846bf..8208585eb 100644
--- a/src/game/combat-system.js
+++ b/src/game/combat-system.js
@@ -33,7 +33,7 @@ import {
Vector3, DoubleSide,
} from 'three';
-import { DANGER_ZONES } from '../../multiplayer/src/world-features.js';
+import { DANGER_ZONES, WORLD_RADIUS } from '../../multiplayer/src/world-features.js';
import { MOB_STATS, WEAPONS } from '../../multiplayer/src/items.js';
import { itemDisplay } from './items.js';
import { WorldHud } from './hud/world-hud.js';
@@ -169,24 +169,34 @@ export class CombatSystem {
* @param {() => ({x,y,z,yaw})} opts.getPlayer local avatar pose
* @param {object} opts.net CommunityNet instance
* @param {object} opts.ui CommunityUI instance (toast)
+ * @param {() => Array<{x:number,z:number,kind?:string,color?:string}>} [opts.blipSource]
+ * optional extra radar blips sampled each radar refresh (e.g. remote
+ * players, which this module has no access to), merged with the
+ * mob/tombstone blips it owns itself.
*/
- constructor({ scene, camera, renderer, getPlayer, net, ui }) {
+ constructor({ scene, camera, renderer, getPlayer, net, ui, blipSource = null }) {
this.scene = scene;
this.camera = camera;
this.renderer = renderer;
this.getPlayer = getPlayer;
this.net = net;
this.ui = ui;
+ this.blipSource = typeof blipSource === 'function' ? blipSource : null;
this.mobs = new Map();
this.tombstones = new Map();
this._nearestTombId = null;
this._weapon = null; // equipped weapon item id, or null
this._dead = false;
+ this._blipsAt = 0; // last radar sample time (10 Hz throttle)
+ this._blipsKey = ''; // change signature of the last pushed blip set
this.hud = new WorldHud();
this.hud.show();
this.hud.setContext('onfoot');
+ // The world is a free-roam disc; draw its real edge as the radar boundary
+ // ring instead of the Minimap default.
+ this.hud.minimap.setBoundary(WORLD_RADIUS);
// Must install before WorldLife constructs its MobSystem (see the module
// doc comment) — coincommunities.js instantiates CombatSystem first.
@@ -324,6 +334,11 @@ export class CombatSystem {
_applyVitals(v) {
if (!v) return;
+ // A 'death' notice hides only on a matching 'respawn' notice, but a reconnect
+ // re-sends the authoritative profile without either notice. If the server says
+ // we're alive, clear any death overlay left pinned from before the drop — else
+ // a player rejoins into a live world stuck behind a full-screen "You died".
+ if (Number.isFinite(v.hp) && v.hp > 0 && this.deathOverlay && !this.deathOverlay.hidden) this._hideDeath();
if (Number.isFinite(v.hp) && Number.isFinite(v.maxHp)) this.hud.setHealth(v.hp, v.maxHp);
if (Number.isFinite(v.armor) && Number.isFinite(v.maxArmor)) this.hud.setArmor(v.armor, v.maxArmor);
if (Number.isFinite(v.heat)) this.hud.setWanted(v.heat);
@@ -499,9 +514,43 @@ export class CombatSystem {
}
this.hud.minimap.setViewer({ x: p.x, z: p.z, yaw: p.yaw || 0 });
+ this._feedRadar();
this.hud.tick(dt);
}
+ // ----------------------------------------------------------------- radar
+ // Feed the minimap real blips: live mobs (hostiles read red, passives grey),
+ // lootable tombstones (same warm yellow as their ground ring), and whatever
+ // the host's optional blipSource adds (remote players). Sampled at ~10 Hz
+ // (radar-scale motion is invisible at 60 fps) and pushed only when the
+ // picture actually changed, so an idle world costs no canvas repaints.
+ _feedRadar() {
+ const now = performance.now();
+ if (now - this._blipsAt < 100) return;
+ this._blipsAt = now;
+ const blips = [];
+ for (const view of this.mobs.values()) {
+ if (view._dead) continue;
+ const hostile = !!MOB_STATS[view.kind]?.hostile;
+ blips.push({ x: view.x, z: view.z, kind: 'peer', color: hostile ? '#ff6b6b' : 'rgba(255,255,255,0.45)' });
+ }
+ for (const t of this.tombstones.values()) blips.push({ x: t.x, z: t.z, kind: 'poi', color: '#ffcf5c' });
+ if (this.blipSource) {
+ // Host boundary: a throwing callback must never take the combat tick down.
+ try {
+ for (const b of this.blipSource() || []) {
+ if (b && Number.isFinite(b.x) && Number.isFinite(b.z)) blips.push(b);
+ }
+ } catch { /* host callback */ }
+ }
+ // Change signature at decimetre resolution, all a 184px radar can show.
+ let key = '';
+ for (const b of blips) key += `${b.kind || ''}${b.color || ''}${b.x.toFixed(1)},${b.z.toFixed(1)};`;
+ if (key === this._blipsKey) return;
+ this._blipsKey = key;
+ this.hud.minimap.setBlips(blips);
+ }
+
dispose() {
for (const off of this._unsub) off?.();
for (const m of this.mobs.values()) m.dispose();
diff --git a/src/game/community-net.js b/src/game/community-net.js
index 8ee04db6e..a18545999 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -358,6 +358,11 @@ export class CommunityNet {
// here (peers never see it). Drives the HUD, inventory, hotbar and toasts.
this.room.onMessage('profile', (msg) => this._emit('profile', msg || {}));
this.room.onMessage('inv', (msg) => this._emit('inv', msg || {}));
+ // Event souvenir: sent once, at the moment the server grants a live
+ // event's commemorative wearable to this account. Never repeated on a
+ // rejoin (the grant is idempotent), so the client can treat it as a
+ // one-time "you just earned this" moment rather than a state sync.
+ this.room.onMessage('souvenir', (msg) => this._emit('souvenir', msg || {}));
this.room.onMessage('xpgain', (msg) => this._emit('xpgain', msg || {}));
this.room.onMessage('levelup', (msg) => this._emit('levelup', msg || {}));
this.room.onMessage('notice', (msg) => this._emit('notice', msg || {}));
diff --git a/src/game/cosmetics-shop.js b/src/game/cosmetics-shop.js
index 8c848e30f..e50ef0165 100644
--- a/src/game/cosmetics-shop.js
+++ b/src/game/cosmetics-shop.js
@@ -17,6 +17,7 @@
import { log } from '../shared/log.js';
import { purchaseCosmetic, resolveShopAccount } from './cosmetics-purchase.js';
+import { openModal } from './a11y.js';
function el(tag, props = {}, kids = []) {
const n = document.createElement(tag);
@@ -95,7 +96,7 @@ export class CosmeticsShop {
this.body = el('div', { class: 'cc-shop-body' }, [this.statusEl, this.grid]);
this.panel = el('div', {
- class: 'cc-shop-panel', role: 'dialog', 'aria-modal': 'false',
+ class: 'cc-shop-panel', role: 'dialog', 'aria-modal': 'true',
'aria-label': 'Cosmetics shop',
}, [
el('div', { class: 'cc-shop-head' }, [
@@ -119,7 +120,9 @@ export class CosmeticsShop {
this.root = el('div', { class: 'cc-shop', id: 'cc-shop', hidden: true }, [this.panel]);
// Backdrop tap closes; panel taps don't bubble out.
this.root.addEventListener('click', (e) => { if (e.target === this.root) this.close(); });
- this._onKey = (e) => { if (e.key === 'Escape' && !this.root.hidden) { e.stopPropagation(); this.close(); } };
+ // World hotkeys live on `window`; keystrokes aimed at the shop must not
+ // also drive the avatar behind it.
+ this.panel.addEventListener('keydown', (e) => e.stopPropagation());
document.body.appendChild(this.root);
this._buildFilters();
@@ -153,8 +156,9 @@ export class CosmeticsShop {
if (this.isOpen()) return;
this.root.hidden = false;
requestAnimationFrame(() => this.root.classList.add('cc-shop-in'));
- document.addEventListener('keydown', this._onKey, true);
- this.closeBtn.focus();
+ // Escape stack + Tab containment + focus restore, shared with every other
+ // /play panel (src/game/a11y.js).
+ this._releaseModal = openModal(this.panel, { close: () => this.close(), initialFocus: this.closeBtn });
// Re-resolve the account in case the player signed in since last open, so a
// fresh wallet sees its owned items rather than the guest's.
const acct = resolveShopAccount(this.h.account);
@@ -169,7 +173,8 @@ export class CosmeticsShop {
close() {
if (!this.isOpen()) return;
this.root.classList.remove('cc-shop-in');
- document.removeEventListener('keydown', this._onKey, true);
+ this._releaseModal?.();
+ this._releaseModal = null;
// Reverting any live preview is the whole point — don't leave a tried-on
// item stuck on the avatar after the shop closes.
this._clearPreview();
@@ -178,7 +183,8 @@ export class CosmeticsShop {
}
dispose() {
- document.removeEventListener('keydown', this._onKey, true);
+ this._releaseModal?.();
+ this._releaseModal = null;
this.root.remove();
}
diff --git a/src/game/cosmetics-wardrobe.js b/src/game/cosmetics-wardrobe.js
index e32a70c24..e35474144 100644
--- a/src/game/cosmetics-wardrobe.js
+++ b/src/game/cosmetics-wardrobe.js
@@ -20,6 +20,7 @@
import {
COSMETICS, SLOTS, SLOT_LABELS, DEFAULT_LOADOUT,
} from '../../multiplayer/src/cosmetics-catalog.js';
+import { openModal } from './a11y.js';
function el(tag, props = {}, kids = []) {
const n = document.createElement(tag);
@@ -75,7 +76,7 @@ export class CosmeticsWardrobe {
this.body = el('div', { class: 'cw-body' });
this.panel = el('div', {
- class: 'cw-panel', role: 'dialog', 'aria-modal': 'false',
+ class: 'cw-panel', role: 'dialog', 'aria-modal': 'true',
'aria-label': 'My Cosmetics wardrobe',
}, [
el('div', { class: 'cw-head' }, [
@@ -90,7 +91,9 @@ export class CosmeticsWardrobe {
this.root = el('div', { class: 'cw-root', id: 'cc-wardrobe', hidden: true }, [this.panel]);
this.root.addEventListener('click', (e) => { if (e.target === this.root) this.close(); });
- this._onKey = (e) => { if (e.key === 'Escape' && !this.root.hidden) { e.stopPropagation(); this.close(); } };
+ // World hotkeys live on `window`; keystrokes aimed at the wardrobe must not
+ // also drive the avatar behind it.
+ this.panel.addEventListener('keydown', (e) => e.stopPropagation());
document.body.appendChild(this.root);
}
@@ -103,8 +106,9 @@ export class CosmeticsWardrobe {
if (this.isOpen()) return;
this.root.hidden = false;
requestAnimationFrame(() => this.root.classList.add('cw-in'));
- document.addEventListener('keydown', this._onKey, true);
- this.closeBtn.focus();
+ // Escape stack + Tab containment + focus restore, shared with every other
+ // /play panel (src/game/a11y.js).
+ this._releaseModal = openModal(this.panel, { close: () => this.close(), initialFocus: this.closeBtn });
// If no profile yet show loading skeleton; it fills in when setProfile arrives.
if (!this._cosmetics) this._renderLoading();
}
@@ -112,12 +116,14 @@ export class CosmeticsWardrobe {
close() {
if (!this.isOpen()) return;
this.root.classList.remove('cw-in');
- document.removeEventListener('keydown', this._onKey, true);
+ this._releaseModal?.();
+ this._releaseModal = null;
setTimeout(() => { this.root.hidden = true; }, 180);
}
dispose() {
- document.removeEventListener('keydown', this._onKey, true);
+ this._releaseModal?.();
+ this._releaseModal = null;
this.root.remove();
}
diff --git a/src/game/economy-ui.css b/src/game/economy-ui.css
index 361cf8033..0b795abba 100644
--- a/src/game/economy-ui.css
+++ b/src/game/economy-ui.css
@@ -104,7 +104,10 @@
flex: 1; padding: 6px 0; font-size: 11px; font-weight: 700; background: transparent; color: var(--cc-dim);
border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm); cursor: pointer; transition: color 0.14s ease, border-color 0.14s ease;
}
-.ec-bank-preset:hover { color: var(--cc-text); border-color: var(--cc-edge-hi); }
+.ec-bank-preset:hover:not(:disabled) { color: var(--cc-text); border-color: var(--cc-edge-hi); }
+.ec-bank-preset:active:not(:disabled) { transform: scale(0.97); }
+.ec-bank-preset:focus-visible { outline: 2px solid var(--cc-edge-hi); outline-offset: 2px; }
+.ec-bank-preset:disabled { opacity: 0.35; cursor: not-allowed; }
.ec-bank-actions { display: flex; gap: 8px; }
.ec-bank-actions .ec-row-btn { flex: 1; }
.ec-bank-actions .ec-row-btn.ec-secondary { background: transparent; color: var(--cc-text); border: 1px solid var(--cc-edge); }
@@ -113,6 +116,50 @@
.ec-status[data-kind="err"] { color: #ff8a8a; }
.ec-status[data-kind="ok"] { color: #9effa6; }
+/* Waiting for the first server snapshot. The placeholder rows are laid out like
+ real ones so the panel does not resize or jump when the catalog arrives. */
+.ec-skel { display: flex; flex-direction: column; gap: 8px; }
+.ec-skel-row {
+ display: flex; align-items: center; gap: 10px; padding: 9px 10px;
+ background: rgba(255, 255, 255, 0.03); border: 1px solid var(--cc-edge-soft); border-radius: var(--cc-radius-sm);
+}
+.ec-skel-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; }
+.ec-skel-glyph, .ec-skel-line, .ec-skel-btn {
+ background: linear-gradient(90deg, rgba(255, 255, 255, 0.05) 25%, rgba(255, 255, 255, 0.12) 37%, rgba(255, 255, 255, 0.05) 63%);
+ background-size: 400% 100%;
+ animation: ec-shimmer 1.4s ease infinite;
+ border-radius: 3px;
+}
+.ec-skel-glyph { width: 24px; height: 18px; flex: none; }
+.ec-skel-line { height: 9px; width: 62%; }
+.ec-skel-line-sm { height: 8px; width: 34%; }
+.ec-skel-btn { width: 52px; height: 26px; flex: none; border-radius: var(--cc-radius-sm); }
+
+@keyframes ec-shimmer {
+ 0% { background-position: 100% 50%; }
+ 100% { background-position: 0 50%; }
+}
+
+/* A balance we have not read yet reads as unknown, never as a confident zero. */
+.ec-pending-val { color: var(--cc-dim); opacity: 0.7; letter-spacing: 0.08em; }
+
+/* The world stopped answering: say so, and give the one button that retries. */
+.ec-error { display: flex; flex-direction: column; align-items: center; gap: 8px; }
+.ec-error-glyph { font-size: 26px; line-height: 1; opacity: 0.75; }
+.ec-error-title { font-size: 13px; font-weight: 700; color: var(--cc-text); }
+.ec-error-retry { margin-top: 4px; }
+
+@media (prefers-reduced-motion: reduce) {
+ .ec-overlay, .ec-card { transition: none; }
+ .ec-skel-glyph, .ec-skel-line, .ec-skel-btn { animation: none; }
+}
+
@media (max-width: 480px) {
.ec-card { width: 100%; }
+ /* Thumb-sized targets on a phone: the WCAG 2.5.5 bar is 44px, and these are
+ the controls a player taps mid-session with one hand. */
+ .ec-x { width: 40px; height: 40px; }
+ .ec-tab { padding: 12px 0; }
+ .ec-row-btn { padding: 11px 14px; }
+ .ec-bank-preset { padding: 11px 0; }
}
diff --git a/src/game/economy-ui.js b/src/game/economy-ui.js
index 61b41a794..55e4fe687 100644
--- a/src/game/economy-ui.js
+++ b/src/game/economy-ui.js
@@ -229,7 +229,11 @@ class StorePanel extends EconPanel {
this.track(net.on('notice', (n) => {
if (n?.kind !== 'store' && n?.kind !== 'full') return;
this.endRequest();
- this.setStatus(n.text || '', n.kind === 'full' ? 'err' : 'ok');
+ // The server stamps every notice with `ok`, so a refusal ("Not enough
+ // cash", "That item isn't for sale") styles as the failure it is. Older
+ // servers omit the flag; fall back to the old kind-based styling.
+ const style = n.ok === true ? 'ok' : n.ok === false ? 'err' : (n.kind === 'full' ? 'err' : 'ok');
+ this.setStatus(n.text || '', style);
}));
this.awaitFirstSnapshot(() => { net.requestStore(); net.requestProfile(); });
@@ -400,7 +404,9 @@ class BankPanel extends EconPanel {
this.track(net.on('notice', (n) => {
if (n?.kind !== 'bank') return;
this.endRequest();
- this.setStatus(n.text || '', 'ok');
+ // "No cash on hand to deposit" is a refusal; style it as one. Undefined
+ // `ok` (older server) keeps the previous success styling.
+ this.setStatus(n.text || '', n.ok === false ? 'err' : 'ok');
}));
this.awaitFirstSnapshot(() => net.requestProfile());
diff --git a/src/game/friends-panel.js b/src/game/friends-panel.js
index 0795b6464..a63f9497f 100644
--- a/src/game/friends-panel.js
+++ b/src/game/friends-panel.js
@@ -11,10 +11,9 @@
import { friendsClient } from '../friends.js';
import panelCss from '../friends-panel.css?inline';
-const HOTKEY_NOTE = 'Press F to toggle this panel.';
-
-// Inject the standalone friends-panel CSS once per document. In /walk the --kg-*
-// vars are absent so .wf-friends provides them; duplicate selectors are idempotent.
+// Inject the standalone friends-panel CSS once per document. The .wf-friends
+// class on the panel root defines the --kg-* token layer (resolving to the
+// host's --cc-* vars on /play, hardcoded fallbacks on /walk).
let _cssInjected = false;
function ensureCss() {
if (_cssInjected || typeof document === 'undefined') return;
@@ -75,9 +74,11 @@ function presenceText(f) {
}
export class FriendsPanel {
- constructor(container, { walkMode = false } = {}) {
+ // Accepts (and ignores) a legacy options bag: /walk still passes
+ // { walkMode: true }, which no longer changes behavior; the token scope is
+ // applied unconditionally in render().
+ constructor(container) {
this.root = container;
- this.walkMode = walkMode;
this.client = friendsClient();
ensureCss();
this.tab = 'friends'; // 'friends' | 'requests' | 'add'
@@ -103,6 +104,7 @@ export class FriendsPanel {
this._mounted = false;
if (this._unsub) this._unsub();
this._unsub = null;
+ clearTimeout(this._searchDebounce);
this.client.closeThread();
this.client.deactivate();
}
@@ -131,8 +133,9 @@ export class FriendsPanel {
if (!this._mounted) return;
this.root.innerHTML = '';
this.root.classList.add('kg-fr');
- // Add token-fallback scope when running outside /play.
- if (this.walkMode) this.root.classList.add('wf-friends');
+ // The token scope every kg-fr-* rule resolves against, required on every
+ // host (on /play the tokens map to the --cc-* vars, on /walk to fallbacks).
+ this.root.classList.add('wf-friends');
const c = this.client;
if (!c.loaded) {
@@ -514,5 +517,3 @@ function relDay(ts) {
if (d.toDateString() === yest.toDateString()) return 'Yesterday';
return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
}
-
-export { HOTKEY_NOTE };
diff --git a/src/game/hud/minimap.js b/src/game/hud/minimap.js
index e81bb905b..cc3047bf4 100644
--- a/src/game/hud/minimap.js
+++ b/src/game/hud/minimap.js
@@ -14,6 +14,8 @@ export class Minimap {
this.viewer = { x: 0, z: 0, yaw: 0 };
this.blips = [];
this.boundary = 58; // world radius ring (0 = none)
+ this._drawn = null; // last-rendered frame state (dirty check in tick)
+ this._blipsDirty = false;
this._build();
}
@@ -44,7 +46,7 @@ export class Minimap {
setBoundary(r) { this.boundary = Number(r) || 0; }
setViewer(v) { if (v) this.viewer = { x: v.x || 0, z: v.z || 0, yaw: v.yaw || 0 }; }
// Blips: [{ x, z, kind:'peer'|'poi'|'waypoint'|'party'|'prop', label?, color? }]
- setBlips(list) { this.blips = Array.isArray(list) ? list : []; }
+ setBlips(list) { this.blips = Array.isArray(list) ? list : []; this._blipsDirty = true; }
// Inverse of _project: a point on the (rotating) map back to world space.
// sx/sy are CSS px relative to the map's top-left, which is what a click handler
@@ -76,6 +78,19 @@ export class Minimap {
}
tick() {
+ // Cheap dirty check: a full canvas repaint every frame is wasted work when
+ // the player is idle and no blip moved. Redraw only when the viewer pose
+ // moved perceptibly, a setter changed the data, or nothing was drawn yet.
+ const v = this.viewer, d = this._drawn;
+ if (
+ d && !this._blipsDirty &&
+ d.range === this.range && d.boundary === this.boundary &&
+ Math.abs(v.x - d.x) < 0.02 && Math.abs(v.z - d.z) < 0.02 &&
+ Math.abs(v.yaw - d.yaw) < 0.002
+ ) return;
+ this._drawn = { x: v.x, z: v.z, yaw: v.yaw, range: this.range, boundary: this.boundary };
+ this._blipsDirty = false;
+
const ctx = this.ctx;
const S = this.size, c = S / 2;
const R = c - 3; // inner radius (clip mask handles the rim)
diff --git a/src/game/hud/world-hud.css b/src/game/hud/world-hud.css
index 8eed1c2c3..412220c01 100644
--- a/src/game/hud/world-hud.css
+++ b/src/game/hud/world-hud.css
@@ -3,6 +3,13 @@
.wh-hud {
--wh-pad: 14px;
+ /* Per-side pads: base padding plus the device safe area (notches, home
+ indicator, curved corners). /play ships viewport-fit=cover, so fixed
+ chrome must budget for env(safe-area-inset-*) itself. */
+ --wh-pad-top: calc(var(--wh-pad) + env(safe-area-inset-top, 0px));
+ --wh-pad-right: calc(var(--wh-pad) + env(safe-area-inset-right, 0px));
+ --wh-pad-bottom: calc(var(--wh-pad) + env(safe-area-inset-bottom, 0px));
+ --wh-pad-left: calc(var(--wh-pad) + env(safe-area-inset-left, 0px));
position: fixed;
inset: 0;
z-index: 30;
@@ -15,8 +22,10 @@
/* ---------------------------------------------------------------- money ---- */
.wh-money {
position: absolute;
- top: calc(var(--wh-pad) + 92px); /* clears the cc status pill / voice button */
- right: var(--wh-pad);
+ /* Clears the whole cc right rail: leave (14), status (58), voice (96),
+ power saver (140), and the Zen button (184, ~34px tall). */
+ top: calc(var(--wh-pad-top) + 220px);
+ right: var(--wh-pad-right);
display: flex;
flex-direction: column;
align-items: flex-end;
@@ -84,7 +93,7 @@
/* ------------------------------------------------------------ objective ---- */
.wh-objective {
position: absolute;
- left: var(--wh-pad);
+ left: var(--wh-pad-left);
top: 50%;
transform: translateY(-50%);
display: flex;
@@ -107,8 +116,8 @@
/* ----------------------------------------------------- vitals + minimap ---- */
.wh-corner-bl {
position: absolute;
- left: var(--wh-pad);
- bottom: var(--wh-pad);
+ left: var(--wh-pad-left);
+ bottom: var(--wh-pad-bottom);
display: flex;
flex-direction: column;
gap: 7px;
@@ -143,7 +152,10 @@
height: 184px;
border-radius: 50%;
overflow: visible;
- pointer-events: auto;
+ /* Purely informational on /play (no tap-to-waypoint handler): let touches
+ fall through to the world so the radar never eats a look-drag or, on
+ phones, the movement joystick's touches. */
+ pointer-events: none;
border: 1.5px solid var(--cc-edge, rgba(255, 255, 255, 0.14));
box-shadow: var(--cc-shadow, 0 16px 50px rgba(0, 0, 0, 0.7)), inset 0 0 0 4px rgba(0, 0, 0, 0.35);
background: rgba(6, 6, 8, 0.5);
@@ -162,8 +174,8 @@
/* --------------------------------------------------------------- speedo ---- */
.wh-speedo {
position: absolute;
- right: var(--wh-pad);
- bottom: var(--wh-pad);
+ right: var(--wh-pad-right);
+ bottom: var(--wh-pad-bottom);
width: 124px;
height: 124px;
pointer-events: none;
@@ -205,7 +217,7 @@
/* On-screen interaction-menu button (touch entry + desktop discoverability). */
.wh-menu-btn {
position: absolute;
- right: var(--wh-pad);
+ right: var(--wh-pad-right);
top: 50%;
transform: translateY(-50%);
width: 44px;
@@ -232,7 +244,11 @@
/* ----------------------------------------------------------- responsive ---- */
@media (max-width: 640px) {
.wh-hud { --wh-pad: 10px; }
- .wh-money { top: calc(var(--wh-pad) + 96px); }
+ /* The movement joystick owns the bottom-left corner on phones (#cc-joystick:
+ left 16px, bottom 20px, 104px tall → up to ~124px from the bottom). Lift
+ the vitals + minimap column clear of it so the radar never sits on top of
+ the stick. */
+ .wh-corner-bl { bottom: calc(var(--wh-pad-bottom) + 140px); }
.wh-vitals { width: 132px; }
.wh-minimap, .wh-minimap-canvas { width: 132px; height: 132px; }
.wh-objective { max-width: 60vw; }
diff --git a/src/game/meetup-event.css b/src/game/meetup-event.css
index 149b9f43e..3abf35389 100644
--- a/src/game/meetup-event.css
+++ b/src/game/meetup-event.css
@@ -136,13 +136,6 @@
.cc-meetup-buy-btn:hover { box-shadow: 0 0 26px rgba(255, 206, 92, 0.45); }
.cc-meetup-buy-btn:active { transform: scale(0.98); }
-/* Photo flash + confetti burst layer. */
-#cc-meetup-flash {
- position: fixed; inset: 0; z-index: 400; pointer-events: none;
- background: #fff; opacity: 0; transition: opacity 0.5s ease;
-}
-#cc-meetup-flash.cc-meetup-flash--on { opacity: 0.85; transition: none; }
-
/* One countdown at a time: while this layer's chip is mounted, the generic
event-countdown pill (same schedule, same event.json) stands down. */
body.cc-meetup-ui .cc-event-pill { display: none; }
diff --git a/src/game/meetup-event.js b/src/game/meetup-event.js
index 2d38ab3ae..020cf90df 100644
--- a/src/game/meetup-event.js
+++ b/src/game/meetup-event.js
@@ -81,7 +81,6 @@ class MeetupEvent {
this.chip = null;
this.panel = null;
this.banner = null;
- this.flashEl = null;
this.fireworks = null;
this.mounted = false;
this._prevPhase = null;
@@ -163,7 +162,6 @@ class MeetupEvent {
this.banner?.remove(); this.banner = null;
this._closePanel(true);
this.panel?.remove(); this.panel = null;
- this.flashEl?.remove(); this.flashEl = null;
this.fireworks?.dispose(); this.fireworks = null;
this._queue = [];
clearInterval(this._signalTimer);
@@ -417,77 +415,15 @@ class MeetupEvent {
}
// ------------------------------------------------------------------ photo
- async _capturePhoto() {
- const cc = this.cc;
- if (!this.flashEl) {
- this.flashEl = el('div', { id: 'cc-meetup-flash', 'aria-hidden': 'true' });
- document.body.appendChild(this.flashEl);
- }
- this.flashEl.classList.add('cc-meetup-flash--on');
- requestAnimationFrame(() => requestAnimationFrame(() => this.flashEl?.classList.remove('cc-meetup-flash--on')));
-
- let dataUrl = null;
- try {
- const shot = cc._captureBuildShot?.(1600);
- if (shot?.dataUrl) dataUrl = shot.dataUrl;
- } catch { /* fall through to the direct read */ }
- if (!dataUrl) {
- try {
- cc.renderer.render(cc.scene, cc.camera);
- dataUrl = cc.renderer.domElement.toDataURL('image/png');
- } catch {
- cc.ui?.toast?.('Couldn’t capture the scene. Try again in a moment.', 'warn');
- return;
- }
- }
-
- const img = new Image();
- await new Promise((resolve, reject) => { img.onload = resolve; img.onerror = reject; img.src = dataUrl; })
- .catch(() => null);
- if (!img.naturalWidth) { cc.ui?.toast?.('Couldn’t capture the scene. Try again in a moment.', 'warn'); return; }
-
- const c = document.createElement('canvas');
- c.width = img.naturalWidth; c.height = img.naturalHeight;
- const ctx = c.getContext('2d');
- ctx.drawImage(img, 0, 0);
-
- // The frame: a quiet bottom gradient with the event title, date and the
- // site, gold-accented. Something a holder wants to post, not a watermark.
- const W = c.width, H = c.height;
- const barH = Math.round(H * 0.20);
- const grad = ctx.createLinearGradient(0, H - barH, 0, H);
- grad.addColorStop(0, 'rgba(4,4,6,0)');
- grad.addColorStop(0.45, 'rgba(4,4,6,0.62)');
- grad.addColorStop(1, 'rgba(4,4,6,0.9)');
- ctx.fillStyle = grad;
- ctx.fillRect(0, H - barH, W, barH);
- const mx = Math.round(W * 0.045);
- ctx.fillStyle = '#ffce5c';
- ctx.fillRect(mx, H - Math.round(barH * 0.52), Math.round(W * 0.055), Math.max(3, Math.round(H * 0.004)));
- ctx.textBaseline = 'alphabetic';
- ctx.fillStyle = '#ffffff';
- ctx.font = `800 ${Math.round(H * 0.038)}px system-ui, -apple-system, sans-serif`;
- ctx.fillText(this.ev.title.toUpperCase(), mx, H - Math.round(barH * 0.28));
- ctx.fillStyle = '#ffce5c';
- ctx.font = `600 ${Math.round(H * 0.024)}px system-ui, -apple-system, sans-serif`;
- const dateLine = new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'long', day: 'numeric' }).format(new Date(this.ev.startsAt));
- ctx.fillText(`${dateLine} · three.ws/play`, mx, H - Math.round(barH * 0.10));
-
- const blob = await new Promise((resolve) => c.toBlob(resolve, 'image/jpeg', 0.92));
- if (!blob) { cc.ui?.toast?.('Couldn’t save the photo.', 'warn'); return; }
- const stamp = new Date(this.ev.startsAt).toISOString().slice(0, 10);
- const file = new File([blob], `three-meetup-${stamp}.jpg`, { type: 'image/jpeg' });
- if (navigator.canShare?.({ files: [file] })) {
- try {
- await navigator.share({ files: [file], title: this.ev.title, text: `${this.ev.title} · three.ws/play` });
- return;
- } catch { /* user cancelled or share failed: fall through to download */ }
- }
- const a = el('a', { href: URL.createObjectURL(blob), download: file.name });
- document.body.appendChild(a);
- a.click();
- setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 1000);
- cc.ui?.toast?.('Photo saved. Post it and tag $THREE.', 'success');
+ // The commemorative photo IS /play's photo mode (src/game/photo-mode.js): the
+ // same offscreen capture, the same monochrome share card, the same download
+ // and clipboard actions. It stamps itself with this event's name on its own,
+ // because it reads the same /event.json this layer does, so there is nothing
+ // event-specific to pass and nothing to keep in sync. Closing the agenda first
+ // keeps the drawer out from behind the preview.
+ _capturePhoto() {
+ this._closePanel();
+ this.cc._openPhotoMode?.();
}
}
diff --git a/src/game/oracle-ribbon.js b/src/game/oracle-ribbon.js
index d99a9e154..de7c5662d 100644
--- a/src/game/oracle-ribbon.js
+++ b/src/game/oracle-ribbon.js
@@ -19,6 +19,7 @@ import {
TubeGeometry,
Vector3,
} from 'three';
+import { log } from '../shared/log.js';
const IBM = {
blueLight: 0x78a9ff,
@@ -148,14 +149,27 @@ export function mountOracleRibbon(scene, opts = {}) {
let t = 0;
const baseY = pivot.position.y;
- (async () => {
+ // Guarded fetch: dispose() aborts an in-flight request so a late response
+ // never builds TubeGeometry into a group already removed from the scene.
+ let disposed = false;
+ let retryTimer = null;
+ const abort = new AbortController();
+ const load = async (isRetry) => {
try {
- const data = await fetch(`/api/ibm/oracle?token=${THREE_MINT}`).then((r) => r.json());
+ const r = await fetch(`/api/ibm/oracle?token=${THREE_MINT}`, { signal: abort.signal });
+ if (!r.ok) throw new Error(`oracle responded ${r.status}`);
+ const data = await r.json();
+ if (disposed) return;
if (data && data.history) buildSeries(series, data);
- } catch {
- /* offline / rate-limited — the world simply renders without the line */
+ } catch (err) {
+ if (disposed || abort.signal.aborted) return;
+ log.warn('[oracle-ribbon] forecast fetch failed:', err?.message);
+ // One retry ~30s later covers a transient blip / rate limit; beyond that
+ // the world simply renders without the line (decorative, not load-bearing).
+ if (!isRetry) retryTimer = setTimeout(() => load(true), 30_000);
}
- })();
+ };
+ load(false);
return {
group: pivot,
@@ -165,6 +179,9 @@ export function mountOracleRibbon(scene, opts = {}) {
pivot.position.y = baseY + Math.sin(t * 0.8) * 0.12;
},
dispose() {
+ disposed = true;
+ clearTimeout(retryTimer);
+ abort.abort();
series.traverse((o) => {
if (o.geometry) o.geometry.dispose();
if (o.material) (Array.isArray(o.material) ? o.material : [o.material]).forEach((m) => m.dispose());
diff --git a/src/game/play-systems.css b/src/game/play-systems.css
index f65052485..cf3729967 100644
--- a/src/game/play-systems.css
+++ b/src/game/play-systems.css
@@ -266,6 +266,17 @@
.ps-skill-lvl { font-size: 11px; color: var(--cc-dim); font-variant-numeric: tabular-nums; }
.ps-skill-bar { height: 5px; background: rgba(255, 255, 255, 0.08); border-radius: 99px; overflow: hidden; }
.ps-skill-fill { display: block; height: 100%; background: #fff; border-radius: 99px; transition: width 0.4s ease; }
+.ps-skill-next { margin-top: 3px; font-size: 10.5px; color: var(--cc-faint); font-variant-numeric: tabular-nums; }
+
+/* What the five bars are working toward. Blank until the server states the gate,
+ so this line is never a guess. */
+.ps-skills-next {
+ margin: 0 12px 12px; padding: 9px 10px; border-radius: var(--cc-radius-sm);
+ font-size: 11px; line-height: 1.45; color: var(--cc-dim);
+ background: rgba(255, 255, 255, 0.04); border: 1px solid var(--cc-edge-soft);
+}
+.ps-skills-next:empty { display: none; }
+.ps-skills-next[data-state="open"] { color: var(--cc-text); border-color: var(--cc-edge); }
/* ---- My Cosmetics (R23) ---- */
.ps-cos { width: 320px; }
@@ -377,6 +388,9 @@
line-height: 1.5;
color: var(--cc-faint);
}
+.ps-cos-hint a { color: var(--cc-text); text-decoration: none; border-bottom: 1px solid var(--cc-edge); white-space: nowrap; }
+.ps-cos-hint a:hover { border-bottom-color: currentColor; }
+.ps-cos-hint a:focus-visible { outline: 2px solid #fff; outline-offset: 3px; border-radius: 2px; }
.ps-cos-state {
display: flex;
flex-direction: column;
diff --git a/src/game/play-systems.js b/src/game/play-systems.js
index 4f87c7625..5ec86624b 100644
--- a/src/game/play-systems.js
+++ b/src/game/play-systems.js
@@ -108,10 +108,22 @@ export class PlaySystems {
this._t = 0; // animation clock
this._invOpen = false;
this._skillsOpen = false;
+ // The wheel's average-level gate, learned from the server's own spinInfo
+ // (see _renderNextUnlock). Undefined until it answers.
+ this._wheelMinLevel = undefined;
this._pondGroup = null;
this._buildScene();
this._buildHud();
+
+ // spinInfo is the only message carrying the wheel's level gate, and the
+ // skills panel is where a player looks to find out what they're working
+ // toward. Listen for it here rather than duplicating the constant.
+ this._offSpinInfo = this.net?.on?.('spinInfo', (m) => {
+ if (!Number.isFinite(m?.minLevel)) return;
+ this._wheelMinLevel = m.minLevel;
+ if (this._skillsOpen) this._renderNextUnlock();
+ }) || null;
}
// ---------------------------------------------------------------- scene
@@ -222,14 +234,18 @@ export class PlaySystems {
el('div', { class: 'ps-inv-hint', text: 'Click a tool to equip it. Click food to eat.' }),
]);
- // Skills panel.
+ // Skills panel. The footer line names what the current skills are working
+ // toward; it stays empty until the server tells us the real gate (see
+ // _renderNextUnlock), so this UI never invents a level requirement.
this.skillsList = el('div', { class: 'ps-skills-list' });
+ this.nextUnlock = el('div', { class: 'ps-skills-next' });
this.skillsPanel = el('div', { class: 'ps-panel ps-skills', hidden: true, role: 'dialog', 'aria-label': 'Skills' }, [
el('div', { class: 'ps-panel-head' }, [
el('span', { class: 'ps-panel-title', text: 'Skills' }),
el('button', { class: 'ps-x', 'aria-label': 'Close', text: '✕', onclick: () => this.toggleSkills(false) }),
]),
this.skillsList,
+ this.nextUnlock,
]);
// My Cosmetics panel (R23): the owned wardrobe. Body is rebuilt per open from
@@ -410,7 +426,16 @@ export class PlaySystems {
const span = s.nextXp != null ? Math.max(1, s.nextXp - s.levelXp) : 1;
const into = s.nextXp != null ? Math.max(0, Math.min(span, s.xp - s.levelXp)) : span;
const pct = Math.round((into / span) * 100);
- const row = el('div', { class: 'ps-skill' }, [
+ // A bare bar tells a player they are progressing but never how much is
+ // left. The server already sends the exact boundaries with every gain, so
+ // spend them: the remaining XP to the next level, on the row.
+ const remaining = s.nextXp == null ? 0 : Math.max(0, s.nextXp - s.xp);
+ const row = el('div', {
+ class: 'ps-skill',
+ title: s.nextXp == null
+ ? `${meta.label} is maxed at level ${s.level}.`
+ : `${remaining.toLocaleString()} XP to ${meta.label} level ${s.level + 1}.`,
+ }, [
el('span', { class: 'ps-skill-glyph', text: meta.glyph }),
el('div', { class: 'ps-skill-body' }, [
el('div', { class: 'ps-skill-top' }, [
@@ -418,10 +443,37 @@ export class PlaySystems {
el('span', { class: 'ps-skill-lvl', text: s.nextXp == null ? `Lv ${s.level} · max` : `Lv ${s.level}` }),
]),
el('div', { class: 'ps-skill-bar' }, [el('span', { class: 'ps-skill-fill', style: `width:${pct}%` })]),
+ el('div', {
+ class: 'ps-skill-next',
+ text: s.nextXp == null ? 'Maxed' : `${remaining.toLocaleString()} XP to Lv ${s.level + 1}`,
+ }),
]),
]);
this.skillsList.appendChild(row);
}
+ this._renderNextUnlock();
+ }
+
+ // The one gated thing a player's skills open up: Fortune's Folly refuses to
+ // spin below an average skill level. That floor is a SERVER constant
+ // (spin-wheel.js MIN_AVG_LEVEL) which rides in on `spinInfo`, so the line
+ // stays blank until the server has stated it rather than hardcoding a number
+ // that could drift. Showing the distance turns five separate bars into a goal,
+ // and it's the only place a player learns the wheel exists before finding it.
+ _renderNextUnlock() {
+ if (!this.nextUnlock) return;
+ const min = this._wheelMinLevel;
+ if (!Number.isFinite(min)) { this.nextUnlock.textContent = ''; this.nextUnlock.removeAttribute('data-state'); return; }
+ const levels = SKILL_ORDER.map((k) => this.skills[k]?.level || 1);
+ const avg = levels.reduce((a, b) => a + b, 0) / (levels.length || 1);
+ if (avg >= min) {
+ this.nextUnlock.textContent = 'Unlocked: the Wheel of Fortune. Spin it at Fortune’s Folly in the plaza.';
+ this.nextUnlock.dataset.state = 'open';
+ return;
+ }
+ const short = Math.round((min - avg) * 10) / 10;
+ this.nextUnlock.textContent = `Next unlock: the Wheel of Fortune at average level ${min} (${short} to go).`;
+ this.nextUnlock.dataset.state = 'locked';
}
// ---------------------------------------------------------------- actions
@@ -482,7 +534,13 @@ export class PlaySystems {
this._skillsOpen = force == null ? !this._skillsOpen : !!force;
this.skillsPanel.hidden = !this._skillsOpen;
this.skillsBtn.classList.toggle('is-on', this._skillsOpen);
- if (this._skillsOpen) this._renderSkills();
+ if (this._skillsOpen) {
+ // Ask for the wheel's gate the first time the panel opens, so the
+ // next-unlock line is populated for a player who has never walked up to
+ // the wheel. Once answered it's cached for the session.
+ if (this._wheelMinLevel === undefined) { try { this.net?.spinInfo?.(); } catch { /* offline */ } }
+ this._renderSkills();
+ }
}
// ---------------------------------------------------------------- cosmetics
@@ -549,9 +607,13 @@ export class PlaySystems {
}
// Footer: an honest pointer. Everyone owns the free pack; premium pieces are
- // earned in the shop. Surface that path so the wardrobe links onward.
+ // bought here with $THREE, so name the currency and where to get it. A card
+ // that quotes a price the player has no way to fund is a dead end.
if (!ownsAnyPremium) {
- body.appendChild(el('p', { class: 'ps-cos-hint', text: 'Unlock premium dyes, hats and auras in the shop — they appear here once you own them.' }));
+ body.appendChild(el('p', { class: 'ps-cos-hint' }, [
+ 'Premium dyes, hats and auras are priced in $THREE and unlock the moment the purchase settles on-chain. ',
+ el('a', { href: '/three-token', target: '_blank', rel: 'noopener', text: 'Get $THREE ↗' }),
+ ]));
}
}
@@ -835,6 +897,8 @@ export class PlaySystems {
// ---------------------------------------------------------------- teardown
dispose() {
+ try { this._offSpinInfo?.(); } catch { /* already torn down */ }
+ this._offSpinInfo = null;
this._clearCast();
if (this._pondGroup) {
this.scene.remove(this._pondGroup);
diff --git a/src/game/plaza-stage.js b/src/game/plaza-stage.js
new file mode 100644
index 000000000..e9bb42dea
--- /dev/null
+++ b/src/game/plaza-stage.js
@@ -0,0 +1,593 @@
+// The Plaza Stage — a Living Stage standing in every /play coin world (F17).
+//
+// The platform already runs real hosted shows: an embodied AI host performs live
+// beats with spatial voice, lip-sync, synced captions, an audience question
+// queue, and a verified on-chain $THREE tip leaderboard where a tip pre-empts the
+// host's next line in about a second (multiplayer/src/rooms/StageRoom.js, served
+// to the browser at /stage). Until now none of it was reachable from the world.
+// This module puts the venue in the plaza: a real structure with a marquee that
+// reads the show's actual state, and a proximity gate that walks the player into
+// the show and back out of it.
+//
+// Two halves, split for cost:
+// • THIS file is always mounted with the world. It is geometry, a canvas
+// marquee, and one distance check per frame — no sockets, no fetches, no
+// audio. A player who never walks over there costs exactly that.
+// • src/game/plaza-stage-show.js is the show client (the stage_world room, the
+// host avatar, TTS + lip-sync, tips, questions). It is dynamically imported
+// the first time the player reaches the venue and fully torn down when they
+// walk away, so its weight and its network traffic exist only for attendees.
+//
+// The stage the world joins is DERIVED from the coin, not looked up: the plaza
+// stage id is uuidv5 of the mint (multiplayer/src/plaza-stage.js), which is both
+// the stage_world filterBy key and the `stages.id` a claim writes. The footprint
+// lives in multiplayer/src/world-features.js, so the marker the player sees and
+// the disc the server protects from being built over are the same coordinates.
+
+import {
+ Group, Mesh, BoxGeometry, CylinderGeometry, RingGeometry, TorusGeometry, PlaneGeometry,
+ MeshStandardMaterial, MeshBasicMaterial, DoubleSide, Color,
+} from 'three';
+import { PLAZA_STAGE, stageInRange, stageMarqueeInRange } from '../../multiplayer/src/world-features.js';
+import { plazaStageId } from '../../multiplayer/src/plaza-stage.js';
+import { makeScreenCanvas, makeScreenTexture, screenMaterial } from './screen-texture.js';
+import { log } from '../shared/log.js';
+
+const CW = 1024; // marquee logical width
+const CH = 512; // marquee logical height
+const SS = 1.5; // supersample for crisp text up close
+const REFRESH_MS = 45_000; // show-state poll while near but not attending
+const REDRAW_MS = 1000; // marquee repaint cadence (a countdown ticks)
+const LEAVE_HYSTERESIS_M = 3; // walk this far past the edge before the show tears down
+
+const COL = {
+ bg0: '#0a0a0c', bg1: '#16121f',
+ text: '#f5f5f6', dim: '#9d97ad', faint: '#5f5a70',
+ accent: '#9b6bff', hot: '#ff5db1', gold: '#ffd24a', ok: '#5fd08a',
+};
+
+const fmtThree = (atomic) => Math.round(Number(atomic || 0) / 1e6).toLocaleString('en-US');
+
+export class PlazaStage {
+ /**
+ * @param {object} opts
+ * @param {import('three').Scene} opts.scene
+ * @param {import('three').Camera} opts.camera the follow camera (spatial audio listener)
+ * @param {() => ({x:number,y:number,z:number})} opts.getPlayer local avatar pose
+ * @param {object} opts.coin the world's coin ({ mint, name, symbol })
+ * @param {object} opts.ui CommunityUI — toasts + the chat bar
+ */
+ constructor({ scene, camera, getPlayer, coin, ui }) {
+ this.scene = scene;
+ this.camera = camera;
+ this.getPlayer = getPlayer;
+ this.coin = coin || {};
+ this.ui = ui;
+ this.stageId = plazaStageId(this.coin.mint);
+
+ this._t = 0;
+ this._sinceFetch = Infinity;
+ this._sinceDraw = Infinity;
+ this._near = false; // inside the marquee ring
+ this._attending = false; // inside the attend ring
+ this._fetching = false;
+ this._show = null; // the lazily-mounted show client
+ this._mounting = false;
+ this._destroyed = false;
+
+ // What the marquee paints. `phase` is the designed state machine:
+ // asleep → loading → (unclaimed | scheduled | dark | live).
+ this.state = {
+ phase: 'asleep',
+ title: '', host: '', format: '',
+ nextShowAt: 0,
+ audience: 0,
+ totalTipsAtomic: 0, tipCount: 0,
+ leaderboard: [],
+ lastLine: '',
+ error: '',
+ };
+
+ this._build();
+ this._buildPrompt();
+ this._draw();
+ }
+
+ // ── the structure ─────────────────────────────────────────────────────────
+ _build() {
+ const g = new Group();
+ g.position.set(PLAZA_STAGE.x, 0, PLAZA_STAGE.z);
+ this._group = g;
+
+ // The performance platform: a low raised disc, in the round, so the ring of
+ // seats StageRoom deals out all face something.
+ const deck = new Mesh(
+ new CylinderGeometry(3.4, 3.7, 0.55, 32),
+ new MeshStandardMaterial({ color: 0x1b1830, roughness: 0.6, metalness: 0.2 }),
+ );
+ deck.position.y = 0.275;
+ deck.castShadow = true;
+ deck.receiveShadow = true;
+ g.add(deck);
+
+ // A lit lip around the deck — the edge that reads as "a stage" from across
+ // the plaza, and the thing that pulses while the host is speaking.
+ const lip = new Mesh(
+ new TorusGeometry(3.45, 0.075, 8, 48),
+ new MeshBasicMaterial({ color: COL.accent }),
+ );
+ lip.rotation.x = Math.PI / 2;
+ lip.position.y = 0.56;
+ g.add(lip);
+ this._lip = lip;
+
+ // The ground ring that tells you where the venue's floor is.
+ this._marker = new Mesh(
+ new RingGeometry(PLAZA_STAGE.r + 0.3, PLAZA_STAGE.r + 0.55, 48),
+ new MeshBasicMaterial({ color: COL.accent, transparent: true, opacity: 0.16, side: DoubleSide }),
+ );
+ this._marker.rotation.x = -Math.PI / 2;
+ this._marker.position.y = 0.04;
+ g.add(this._marker);
+
+ // Everything with a "front" faces the middle of the plaza, so a player
+ // walking up from the totem/wheel meets the backdrop head-on.
+ const facing = new Group();
+ facing.rotation.y = Math.atan2(-PLAZA_STAGE.x, -PLAZA_STAGE.z);
+ g.add(facing);
+ this._facing = facing;
+
+ // Backdrop shell behind the performer.
+ const backdrop = new Mesh(
+ new CylinderGeometry(3.9, 3.9, 3.6, 24, 1, true, Math.PI * 0.62, Math.PI * 0.76),
+ new MeshStandardMaterial({ color: 0x120f1d, roughness: 0.9, side: DoubleSide }),
+ );
+ backdrop.position.y = 1.8;
+ facing.add(backdrop);
+
+ // Two truss masts carrying the marquee above the deck, high enough to read
+ // from anywhere on the seat ring (double-sided, so the back rows see it too).
+ for (const side of [-1, 1]) {
+ const mast = new Mesh(
+ new BoxGeometry(0.22, 6.2, 0.22),
+ new MeshStandardMaterial({ color: 0x2a2740, roughness: 0.6, metalness: 0.5 }),
+ );
+ mast.position.set(side * 2.9, 3.1, -1.9);
+ facing.add(mast);
+ }
+ const beam = new Mesh(
+ new BoxGeometry(6.2, 0.22, 0.22),
+ new MeshStandardMaterial({ color: 0x2a2740, roughness: 0.6, metalness: 0.5 }),
+ );
+ beam.position.set(0, 6.1, -1.9);
+ facing.add(beam);
+
+ // The marquee itself: a canvas texture repainted as the show's state changes.
+ const screen = makeScreenCanvas(CW, CH, SS);
+ this._canvas = screen.canvas;
+ this._ctx = screen.ctx;
+ this._tex = makeScreenTexture(this._canvas);
+ const panel = new Mesh(
+ new PlaneGeometry(5.6, 2.8),
+ screenMaterial(this._tex, { side: DoubleSide }),
+ );
+ panel.position.set(0, 4.5, -1.85);
+ facing.add(panel);
+ this._panel = panel;
+
+ // A dark frame so the panel reads as a mounted screen, not a floating decal.
+ const frame = new Mesh(
+ new BoxGeometry(5.9, 3.1, 0.12),
+ new MeshStandardMaterial({ color: 0x0c0a14, roughness: 0.8 }),
+ );
+ frame.position.set(0, 4.5, -1.95);
+ facing.add(frame);
+
+ this.scene.add(g);
+
+ // Where the show client hangs the host avatar (deck top) and the crowd
+ // (ground level, unrotated so the server's seat coordinates map straight
+ // through without a frame change).
+ this.hostAnchor = new Group();
+ this.hostAnchor.position.set(0, 0.55, 0);
+ this._facing.add(this.hostAnchor);
+ this.audienceAnchor = new Group();
+ g.add(this.audienceAnchor);
+ }
+
+ _buildPrompt() {
+ this.btn = document.createElement('button');
+ this.btn.className = 'ps-action pz-action';
+ this.btn.hidden = true;
+ this.btn.textContent = '🎤 Enter the show';
+ this.btn.addEventListener('click', () => this.interact());
+ document.body.appendChild(this.btn);
+ }
+
+ // ── proximity lifecycle ───────────────────────────────────────────────────
+ tick(dt) {
+ if (this._destroyed) return;
+ this._t += dt;
+ this._sinceFetch += dt * 1000;
+ this._sinceDraw += dt * 1000;
+
+ const p = this.getPlayer?.();
+ if (!p) return;
+ const dist = Math.hypot(p.x - PLAZA_STAGE.x, p.z - PLAZA_STAGE.z);
+ const near = !!stageMarqueeInRange(p.x, p.z);
+ const inside = !!stageInRange(p.x, p.z);
+ // Hysteresis on the way out only: crossing the line once shouldn't flap a
+ // socket open and shut while the player mills around the edge of the crowd.
+ const attending = this._attending
+ ? dist <= PLAZA_STAGE.r + 8 + LEAVE_HYSTERESIS_M
+ : inside;
+
+ if (near !== this._near) {
+ this._near = near;
+ if (near) this._wake();
+ else this._sleep();
+ }
+ if (attending !== this._attending) {
+ this._attending = attending;
+ if (attending) this._mountShow();
+ else this._unmountShow();
+ }
+
+ // One state read while loitering near the marquee; the room feeds it while
+ // attending, so polling stops the moment the socket is up.
+ if (this._near && !this._show && this._sinceFetch >= REFRESH_MS) this._refresh();
+
+ this.btn.hidden = !inside || !!this._show?.panelOpen?.();
+
+ // Idle life: the ground ring breathes, and the deck lip glows brighter while
+ // the host is speaking.
+ const pulse = 0.13 + Math.sin(this._t * 1.5) * 0.05;
+ this._marker.material.opacity = near ? pulse + 0.2 : pulse;
+ const speaking = !!this._show?.isSpeaking?.();
+ const beat = speaking ? 0.5 + Math.abs(Math.sin(this._t * 6)) * 0.5 : 0;
+ this._lip.material.color.copy(new Color(this.state.phase === 'live' ? COL.hot : COL.accent)).multiplyScalar(0.55 + beat * 0.45);
+
+ if (this._sinceDraw >= REDRAW_MS) this._draw();
+ this._show?.tick?.(dt);
+ }
+
+ _wake() {
+ if (this.state.phase === 'asleep') {
+ this.state.phase = 'loading';
+ this._draw();
+ }
+ this._refresh();
+ }
+
+ _sleep() {
+ // Walking out of sight stops the polling. The last known state stays painted
+ // so the marquee is never blank when the player glances back.
+ this._sinceFetch = 0;
+ }
+
+ // The one HTTP read this landmark makes, and only while the player is near it.
+ // `?coin=` derives the same plaza id the client does and answers 200 with
+ // stage:null when nobody has claimed it, so "quiet landmark" is a designed
+ // state rather than a 404 in the console.
+ async _refresh() {
+ if (this._fetching || this._destroyed) return;
+ this._fetching = true;
+ this._sinceFetch = 0;
+ try {
+ const res = await fetch(`/api/stage?coin=${encodeURIComponent(this.coin.mint || '')}`, {
+ headers: { accept: 'application/json' },
+ });
+ if (!res.ok) throw new Error(`http ${res.status}`);
+ const data = await res.json();
+ if (this._destroyed) return;
+ this._applyDetail(data);
+ } catch (err) {
+ if (this._destroyed) return;
+ log.warn('[plaza-stage] show state read failed:', err?.message || err);
+ // Only surface an error when we have nothing better to show; a stale but
+ // real marquee beats an error card.
+ if (this.state.phase === 'loading') {
+ this.state.phase = 'error';
+ this.state.error = 'Marquee offline';
+ }
+ } finally {
+ this._fetching = false;
+ this._draw();
+ }
+ }
+
+ _applyDetail(data) {
+ this._detail = data || null;
+ const stage = data?.stage;
+ if (!stage) {
+ this.state.phase = 'unclaimed';
+ this._unmountShow();
+ return;
+ }
+ this.state.title = stage.title || `${stage.host_name || 'The host'} Live`;
+ this.state.host = stage.host_name || 'AI host';
+ this.state.format = stage.format || '';
+ this.state.nextShowAt = Number(stage.next_show_at) || 0;
+ this.state.hostAvatar = stage.host_avatar || '';
+ this.state.hostWallet = data.hostWallet || null;
+ this.state.hostVoice = stage.voice || 'nova';
+ this.state.leaderboard = data.leaderboard || [];
+ const show = data.currentShow || data.lastShow;
+ this.state.totalTipsAtomic = show?.total_tips_atomic || 0;
+ this.state.tipCount = show?.tip_count || 0;
+ this.state.phase = data.live
+ ? 'live'
+ : (this.state.nextShowAt > Date.now() ? 'scheduled' : 'dark');
+ if (this._show) this._show.setStageDetail(data);
+ // The player may have reached the venue before this read landed (or before a
+ // stage existed at all) — now that there is a real show to join, join it.
+ else if (this._attending) this._mountShow();
+ }
+
+ // ── the show client (lazy) ────────────────────────────────────────────────
+ async _mountShow() {
+ if (this._show || this._mounting || this._destroyed) return;
+ this._mounting = true;
+ try {
+ const { PlazaStageShow } = await import('./plaza-stage-show.js');
+ // The player may have walked back out while the chunk was in flight.
+ if (this._destroyed || !this._attending) return;
+ this._show = new PlazaStageShow({
+ stageId: this.stageId,
+ coin: this.coin,
+ camera: this.camera,
+ hostAnchor: this.hostAnchor,
+ audienceAnchor: this.audienceAnchor,
+ ui: this.ui,
+ detail: this.state.phase === 'unclaimed' ? null : this.state,
+ onShowState: (patch) => this._onShowState(patch),
+ });
+ await this._show.start();
+ if (this._destroyed || !this._attending) { this._unmountShow(); return; }
+ } catch (err) {
+ log.warn('[plaza-stage] could not open the show:', err?.message || err);
+ this.ui?.toast?.('The stage feed could not open. Try walking up again.', 'error');
+ } finally {
+ this._mounting = false;
+ }
+ }
+
+ _unmountShow() {
+ if (!this._show) return;
+ try { this._show.dispose(); } catch (err) { log.warn('[plaza-stage] show dispose:', err?.message || err); }
+ this._show = null;
+ this.btn.hidden = true;
+ // The socket is gone; go back to reading the marquee over HTTP.
+ this._sinceFetch = REFRESH_MS;
+ }
+
+ // Live room state flows back into the marquee so the board a passer-by reads is
+ // the same board the audience is watching.
+ _onShowState(patch) {
+ Object.assign(this.state, patch);
+ this._draw();
+ }
+
+ // ── interaction ───────────────────────────────────────────────────────────
+ // SYNCHRONOUS, like WheelStation.interact(): coincommunities' E-key chain tests
+ // each system's return value to find the one that consumed the press, and a
+ // Promise is always truthy.
+ interact() {
+ const p = this.getPlayer?.();
+ if (!p || !stageInRange(p.x, p.z)) return false;
+ if (this._show) { this._show.togglePanel(); return true; }
+ if (this.state.phase === 'unclaimed') {
+ this.ui?.toast?.('No host has claimed this stage yet. Put an agent on it from /stage.', 'info');
+ return true;
+ }
+ // Attendance is mounting (or about to); tell the player something is happening.
+ this.ui?.toast?.('Taking a seat…', 'info');
+ return true;
+ }
+
+ /** Route a question from the in-world chat bar to the host's queue. */
+ ask(text) {
+ if (!this._show) return 'away';
+ return this._show.ask(text);
+ }
+
+ isAttending() { return !!this._show; }
+
+ // ── the marquee ───────────────────────────────────────────────────────────
+ _draw() {
+ this._sinceDraw = 0;
+ const ctx = this._ctx;
+ const s = this.state;
+
+ // Backdrop: a soft vertical wash so text reads at any angle.
+ const grad = ctx.createLinearGradient(0, 0, 0, CH);
+ grad.addColorStop(0, COL.bg1);
+ grad.addColorStop(1, COL.bg0);
+ ctx.fillStyle = grad;
+ ctx.fillRect(0, 0, CW, CH);
+ ctx.strokeStyle = 'rgba(255,255,255,0.07)';
+ ctx.lineWidth = 2;
+ ctx.strokeRect(8, 8, CW - 16, CH - 16);
+
+ if (s.phase === 'asleep' || s.phase === 'loading') return this._drawSimple('THE PLAZA STAGE', 'Reading the marquee…', COL.dim);
+ if (s.phase === 'error') return this._drawSimple('THE PLAZA STAGE', s.error || 'Marquee offline', COL.dim, 'Walk up again to retry');
+ if (s.phase === 'unclaimed') {
+ return this._drawSimple(
+ 'THE PLAZA STAGE',
+ 'No host has claimed this stage',
+ COL.accent,
+ 'Put your agent on it at three.ws/stage',
+ );
+ }
+
+ const live = s.phase === 'live';
+
+ // Status chip.
+ ctx.font = '700 30px system-ui, -apple-system, Segoe UI, sans-serif';
+ if (live) {
+ ctx.fillStyle = COL.hot;
+ ctx.fillText('● LIVE NOW', 40, 66);
+ } else if (s.phase === 'scheduled') {
+ ctx.fillStyle = COL.accent;
+ ctx.fillText(`NEXT SHOW IN ${countdown(s.nextShowAt)}`, 40, 66);
+ } else {
+ ctx.fillStyle = COL.dim;
+ ctx.fillText('DARK — BETWEEN SHOWS', 40, 66);
+ }
+
+ // Title + host.
+ ctx.fillStyle = COL.text;
+ ctx.font = '800 52px system-ui, -apple-system, Segoe UI, sans-serif';
+ fitText(ctx, s.title || 'Untitled show', 40, 132, CW - 380);
+ ctx.fillStyle = COL.dim;
+ ctx.font = '400 28px system-ui, -apple-system, Segoe UI, sans-serif';
+ fitText(ctx, `${s.host}${s.format ? ` · ${s.format}` : ''}`, 40, 174, CW - 380);
+
+ // The last line the host said — the marquee doubles as a caption board for
+ // anyone standing too far back to hear the spatial audio.
+ if (s.lastLine) {
+ ctx.fillStyle = 'rgba(255,255,255,0.05)';
+ roundRect(ctx, 32, 208, CW - 64, 92, 14);
+ ctx.fill();
+ ctx.fillStyle = COL.text;
+ ctx.font = '400 26px system-ui, -apple-system, Segoe UI, sans-serif';
+ wrapText(ctx, `“${s.lastLine}”`, 50, 244, CW - 100, 34, 2);
+ }
+
+ // Tip leaderboard — the same verified, on-chain board /stage shows.
+ const boardY = s.lastLine ? 330 : 240;
+ ctx.fillStyle = COL.faint;
+ ctx.font = '700 22px system-ui, -apple-system, Segoe UI, sans-serif';
+ ctx.fillText('TOP TIPPERS', 40, boardY);
+ const rows = (s.leaderboard || []).slice(0, 3);
+ if (!rows.length) {
+ ctx.fillStyle = COL.dim;
+ ctx.font = '400 26px system-ui, -apple-system, Segoe UI, sans-serif';
+ ctx.fillText(live ? 'No tips yet — take the top spot' : 'No tips on the last show', 40, boardY + 40);
+ } else {
+ rows.forEach((r, i) => {
+ const y = boardY + 40 + i * 36;
+ ctx.fillStyle = i === 0 ? COL.gold : COL.text;
+ ctx.font = `${i === 0 ? 700 : 400} 26px system-ui, -apple-system, Segoe UI, sans-serif`;
+ fitText(ctx, `${i + 1}. ${r.label}`, 40, y, 380);
+ ctx.textAlign = 'right';
+ ctx.fillText(`${fmtThree(r.total)} $THREE`, 620, y);
+ ctx.textAlign = 'left';
+ });
+ }
+
+ // Right rail: audience + running total.
+ ctx.textAlign = 'right';
+ ctx.fillStyle = COL.faint;
+ ctx.font = '700 22px system-ui, -apple-system, Segoe UI, sans-serif';
+ ctx.fillText('IN THE CROWD', CW - 40, 108);
+ ctx.fillStyle = COL.text;
+ ctx.font = '800 64px system-ui, -apple-system, Segoe UI, sans-serif';
+ ctx.fillText(String(s.audience || 0), CW - 40, 172);
+ ctx.fillStyle = COL.faint;
+ ctx.font = '700 22px system-ui, -apple-system, Segoe UI, sans-serif';
+ ctx.fillText('TIPPED THIS SHOW', CW - 40, 232);
+ ctx.fillStyle = COL.ok;
+ ctx.font = '800 44px system-ui, -apple-system, Segoe UI, sans-serif';
+ ctx.fillText(`${fmtThree(s.totalTipsAtomic)}`, CW - 40, 280);
+ ctx.fillStyle = COL.dim;
+ ctx.font = '400 24px system-ui, -apple-system, Segoe UI, sans-serif';
+ ctx.fillText(`$THREE · ${s.tipCount || 0} tips`, CW - 40, 314);
+ ctx.textAlign = 'left';
+
+ // Footer hint — what the player can actually do from here.
+ ctx.fillStyle = COL.faint;
+ ctx.font = '400 24px system-ui, -apple-system, Segoe UI, sans-serif';
+ ctx.fillText(live ? 'Walk up to take a seat · E opens the show panel' : 'Walk up to check the schedule', 40, CH - 34);
+
+ this._tex.needsUpdate = true;
+ }
+
+ _drawSimple(kicker, headline, color, foot) {
+ const ctx = this._ctx;
+ ctx.textAlign = 'center';
+ ctx.fillStyle = COL.faint;
+ ctx.font = '700 26px system-ui, -apple-system, Segoe UI, sans-serif';
+ ctx.fillText(kicker, CW / 2, CH / 2 - 70);
+ ctx.fillStyle = color;
+ ctx.font = '800 46px system-ui, -apple-system, Segoe UI, sans-serif';
+ fitText(ctx, headline, CW / 2, CH / 2 + 6, CW - 120);
+ if (foot) {
+ ctx.fillStyle = COL.dim;
+ ctx.font = '400 26px system-ui, -apple-system, Segoe UI, sans-serif';
+ ctx.fillText(foot, CW / 2, CH / 2 + 66);
+ }
+ ctx.textAlign = 'left';
+ this._tex.needsUpdate = true;
+ }
+
+ dispose() {
+ this._destroyed = true;
+ this._unmountShow();
+ this.btn?.remove();
+ if (this._group) {
+ this.scene.remove(this._group);
+ this._group.traverse((n) => {
+ if (!n.isMesh) return;
+ n.geometry?.dispose?.();
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ for (const m of mats) m?.dispose?.();
+ });
+ this._group = null;
+ }
+ this._tex?.dispose?.();
+ }
+}
+
+// ── canvas helpers ───────────────────────────────────────────────────────────
+
+// Draw text, shrinking the font until it fits `maxWidth` — a long agent name must
+// never run off the marquee.
+function fitText(ctx, text, x, y, maxWidth) {
+ const original = ctx.font;
+ let size = Number(original.match(/(\d+)px/)?.[1] || 28);
+ while (size > 12 && ctx.measureText(text).width > maxWidth) {
+ size -= 2;
+ ctx.font = original.replace(/\d+px/, `${size}px`);
+ }
+ ctx.fillText(text, x, y);
+ ctx.font = original;
+}
+
+function wrapText(ctx, text, x, y, maxWidth, lineHeight, maxLines) {
+ const words = String(text).split(/\s+/);
+ let line = '';
+ let lines = 0;
+ for (const w of words) {
+ const test = line ? `${line} ${w}` : w;
+ if (ctx.measureText(test).width > maxWidth && line) {
+ ctx.fillText(line, x, y + lines * lineHeight);
+ lines++;
+ if (lines >= maxLines) { ctx.fillText('…', x, y + lines * lineHeight); return; }
+ line = w;
+ } else {
+ line = test;
+ }
+ }
+ if (line) ctx.fillText(line, x, y + lines * lineHeight);
+}
+
+function roundRect(ctx, x, y, w, h, r) {
+ ctx.beginPath();
+ ctx.moveTo(x + r, y);
+ ctx.arcTo(x + w, y, x + w, y + h, r);
+ ctx.arcTo(x + w, y + h, x, y + h, r);
+ ctx.arcTo(x, y + h, x, y, r);
+ ctx.arcTo(x, y, x + w, y, r);
+ ctx.closePath();
+}
+
+function countdown(ms) {
+ const left = Math.max(0, Number(ms || 0) - Date.now());
+ const s = Math.floor(left / 1000);
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = s % 60;
+ if (h >= 24) return `${Math.floor(h / 24)}d ${h % 24}h`;
+ return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`;
+}
diff --git a/src/game/quests-ui.css b/src/game/quests-ui.css
index adb6d338b..d5030c924 100644
--- a/src/game/quests-ui.css
+++ b/src/game/quests-ui.css
@@ -29,3 +29,54 @@
100% { box-shadow: 0 0 0 8px rgba(255, 206, 110, 0); border-color: var(--cc-edge-soft); }
}
.qb-flash { animation: qb-flash-pulse 1.4s ease-out 1; }
+
+/* Live event: the quest line's jobs and the standings they feed. The event tint
+ * is the one warm accent on an otherwise monochrome panel, used only where
+ * "this expires when the event does" is the point. */
+.qb-event-tab { border-color: rgba(255, 206, 110, 0.45); }
+.qb-event-tab:hover { border-color: rgba(255, 206, 110, 0.8); }
+
+.qb-event-row { border-color: rgba(255, 206, 110, 0.35); background: rgba(255, 206, 110, 0.05); }
+.qb-event-badge {
+ display: inline-block; margin-left: 7px; padding: 1px 6px; vertical-align: 1px;
+ font-size: 9px; font-weight: 800; letter-spacing: 0.09em;
+ color: #ffce6e; border: 1px solid rgba(255, 206, 110, 0.55); border-radius: 999px;
+}
+
+.qb-lb-head { padding: 2px 2px 10px; border-bottom: 1px solid var(--cc-edge-soft); margin-bottom: 8px; }
+.qb-lb-title { font-size: 14px; font-weight: 800; color: var(--cc-text); }
+.qb-lb-note { font-size: 11px; color: var(--cc-dim); line-height: 1.5; margin-top: 4px; }
+
+.qb-lb-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }
+.qb-lb-row {
+ display: flex; align-items: center; gap: 10px; padding: 8px 10px;
+ background: rgba(255, 255, 255, 0.03); border: 1px solid var(--cc-edge-soft);
+ border-radius: var(--cc-radius-sm); transition: border-color 0.14s ease, background 0.14s ease;
+}
+.qb-lb-row.is-you { border-color: rgba(255, 206, 110, 0.55); background: rgba(255, 206, 110, 0.07); }
+.qb-lb-rank {
+ flex: none; min-width: 34px; font-size: 12px; font-weight: 800;
+ color: var(--cc-dim); font-variant-numeric: tabular-nums;
+}
+.qb-lb-row.is-you .qb-lb-rank { color: #ffce6e; }
+.qb-lb-name { flex: 1; min-width: 0; font-size: 13px; color: var(--cc-text); overflow-wrap: anywhere; }
+.qb-lb-score { flex: none; font-size: 11px; color: var(--cc-dim); font-variant-numeric: tabular-nums; }
+
+.qb-lb-you-wrap { margin-top: 12px; padding-top: 10px; border-top: 1px solid var(--cc-edge-soft); }
+.qb-lb-prize { margin-top: 12px; font-size: 10px; color: var(--cc-dim); line-height: 1.5; opacity: 0.85; }
+
+/* Skeleton rows while the first read is in flight — the shape of the answer,
+ * so the panel doesn't jump when the real rows land. */
+@keyframes qb-lb-shimmer {
+ 0%, 100% { opacity: 0.35; }
+ 50% { opacity: 0.7; }
+}
+.qb-lb-ghost { height: 35px; animation: qb-lb-shimmer 1.3s ease-in-out infinite; }
+.qb-lb-skeleton .qb-lb-ghost:nth-child(2) { animation-delay: 0.1s; }
+.qb-lb-skeleton .qb-lb-ghost:nth-child(3) { animation-delay: 0.2s; }
+.qb-lb-skeleton .qb-lb-ghost:nth-child(4) { animation-delay: 0.3s; }
+.qb-lb-skeleton .qb-lb-ghost:nth-child(5) { animation-delay: 0.4s; }
+@media (prefers-reduced-motion: reduce) {
+ .qb-lb-ghost { animation: none; opacity: 0.45; }
+ .qb-flash { animation: none; }
+}
diff --git a/src/game/spin-wheel-ui.js b/src/game/spin-wheel-ui.js
index d20beb41b..cf789c39e 100644
--- a/src/game/spin-wheel-ui.js
+++ b/src/game/spin-wheel-ui.js
@@ -20,6 +20,7 @@
import './spin-wheel.css';
import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';
+import { openModal } from './a11y.js';
const NETWORK = 'mainnet';
const SPIN_DECIMALS = 6; // $THREE uses 6 decimals (same as pump.fun mints)
@@ -154,8 +155,11 @@ class SpinWheel {
this.overlay.appendChild(this.card);
document.body.appendChild(this.overlay);
this._setBusy(true, 'Loading the wheel…');
- this._onKey = (e) => { if (e.key === 'Escape') this.close(); };
- window.addEventListener('keydown', this._onKey);
+ // The wheel is a modal: keep Tab inside it, hand Escape to the shared
+ // overlay stack (so a wheel opened over another panel closes only itself),
+ // and stop world hotkeys from driving the avatar behind the card.
+ this.card.addEventListener('keydown', (e) => e.stopPropagation());
+ this._releaseModal = openModal(this.card, { close: () => this.close(), initialFocus: close });
}
focus() { this.card?.classList.remove('kg-spin-flash'); requestAnimationFrame(() => this.card?.classList.add('kg-spin-flash')); }
@@ -168,7 +172,7 @@ class SpinWheel {
this.segments = Array.isArray(m.segments) ? m.segments : [];
this._renderLegend();
this._drawWheel();
- if (this.phase === 'loading' || this.phase === 'error') { this.phase = 'ready'; this._status('', ''); }
+ if (this.phase === 'loading' || this.phase === 'error') { this.phase = 'ready'; this.busy = false; this._status('', ''); }
this._sync();
this._startCountdown();
}
@@ -187,7 +191,6 @@ class SpinWheel {
_onResult(m) {
// Land the wheel on the server's chosen segment, then reveal the prize.
if (m.mode === 'free' && Number.isFinite(m.nextFreeSpinAt) && this.info) this.info.nextFreeSpinAt = m.nextFreeSpinAt;
- this._pendingResult = m;
// Headless (modal already closed mid-settle): skip the flourish and deliver
// the result straight to the background pill.
if (this._headless) { this._reveal(m); return; }
@@ -212,6 +215,37 @@ class SpinWheel {
this.busy = false;
this._stopSpin();
this.phase = 'ready';
+ // A paid denial AFTER the payment broadcast must never read as "pay again":
+ // real $THREE already moved on-chain. Keep the signature and its Solscan
+ // receipt on screen and say plainly that no spin was consumed. The server
+ // re-accepts the exact same txSig+quote for the life of the quote
+ // (handleSpinPaidSettle reserves the nonce only on a successful roll), so
+ // for a not_found that outlived the automatic retries the honest recovery
+ // is re-settling the SAME payment, never signing a new one.
+ const paidSig = m?.mode === 'paid' && m?.reason !== 'already_settled' ? this._sig : null;
+ if (paidSig) {
+ // Headless pills are terminal (the modal is gone), so the retry button is
+ // only offered while the modal is up with a live quote.
+ const canResettle = !this._headless && !!this._prep && m.reason === 'not_found';
+ const receipt = el('a', { href: solanaTxExplorerUrl(NETWORK, paidSig), target: '_blank', rel: 'noopener', text: 'view on Solscan ↗' });
+ this._statusNode(canResettle
+ ? el('span', {}, [
+ 'The server can’t see your confirmed payment yet. It went through on-chain (',
+ receipt,
+ ') and no spin was consumed. ',
+ el('button', { class: 'kg-spin-retry', type: 'button', onclick: () => this._resettle() }, 'Retry settle'),
+ ' re-checks that same payment; it never charges you again.',
+ ])
+ : el('span', {}, [
+ `${this._denyText(m)} Your payment went through on-chain (`,
+ receipt,
+ ') but no spin was consumed. Do not pay again; keep that transaction as your receipt.',
+ ]), 'err');
+ if (this._headless) { this._pillDone(); return; }
+ if (!canResettle) { this._prep = null; this._sig = null; this._paymentLive = false; }
+ this._sync();
+ return;
+ }
this._prep = null;
this._sig = null;
this._paymentLive = false;
@@ -220,6 +254,20 @@ class SpinWheel {
this._sync();
}
+ // Re-submit the SAME txSig+quote after the automatic not_found retries ran
+ // out: no wallet prompt, no new payment. The server accepts the pair until
+ // the quote expires and consumes the nonce only when a roll is granted.
+ _resettle() {
+ if (this._closed || this.busy || !this._prep || !this._sig) return;
+ this._settleAttempts = 0;
+ this.busy = true;
+ this.phase = 'spinning';
+ this._startSpin();
+ this._status('Verifying payment & rolling…', '');
+ this._sync();
+ this._settle();
+ }
+
_denyText(m) {
// The gate is a server constant (spin-wheel.js MIN_AVG_LEVEL) that rides in on
// every spinInfo/spinDenied. Never invent a number for it: a wrong minimum in
@@ -550,7 +598,7 @@ class SpinWheel {
return;
}
this.freeBtn.disabled = !ready || this.busy;
- this.freeBtn.textContent = ready ? 'Free spin' : 'Free spin';
+ this.freeBtn.textContent = ready ? 'Free spin' : `Free spin in ${this._fmtCountdown(next - now)}`;
this.freeSub.textContent = ready ? 'Ready now · 1 per 12h' : `Next free spin in ${this._fmtCountdown(next - now)}`;
this.freeSub.dataset.ready = ready ? '1' : '0';
}
@@ -587,7 +635,13 @@ class SpinWheel {
this._syncFree();
}
- _setBusy(on, text) { if (text != null) this._status(text, ''); }
+ // Track the busy flag for real and reflect it on both spin buttons, which
+ // disable through _sync. Optional text goes to the status line.
+ _setBusy(on, text) {
+ this.busy = !!on;
+ if (text != null) this._status(text, '');
+ this._sync();
+ }
_status(text, kind) {
if (this._headless) { this._pill(text, kind); return; }
this.status.textContent = text || ''; this.status.dataset.kind = kind || '';
@@ -630,7 +684,7 @@ class SpinWheel {
this._headless = true;
this._stopSpin();
if (this._countdownTimer) { clearInterval(this._countdownTimer); this._countdownTimer = null; }
- window.removeEventListener('keydown', this._onKey);
+ this._releaseModal?.();
this.overlay?.remove();
this.overlay = null;
if (_open === this) _open = null;
@@ -651,7 +705,7 @@ class SpinWheel {
if (this._loadTimer) { clearTimeout(this._loadTimer); this._loadTimer = null; }
for (const off of this._offs || []) { try { off(); } catch {} }
this._offs = [];
- window.removeEventListener('keydown', this._onKey);
+ this._releaseModal?.();
this.overlay?.remove();
this.overlay = null;
if (_open === this) _open = null;
diff --git a/tests/event-leaderboard.test.js b/tests/event-leaderboard.test.js
new file mode 100644
index 000000000..723b6fb6c
--- /dev/null
+++ b/tests/event-leaderboard.test.js
@@ -0,0 +1,158 @@
+// Event leaderboard ranking (order 04) — the pure math both the in-world panel and
+// api/play/event-leaderboard.js fold their rows through. Ranking is the thing a
+// player will argue about, so every rule is pinned: runs first, cash as the
+// tiebreak, the earlier finisher ahead on a dead heat, and your own row findable
+// whether or not you made the top ten.
+import { describe, it, expect } from 'vitest';
+import {
+ TOP_LIMIT, emptyEventRecord, applyEventRun, normalizeEventRecord,
+ rankEventBoard, eventBoardView,
+} from '../multiplayer/src/event-leaderboard.js';
+
+function runner(account, { runs = 0, cash = 0, lastAt = 0, name = account } = {}) {
+ return { account, name, runs, cash, lastAt, missions: {} };
+}
+
+describe('applyEventRun', () => {
+ it('counts a run, adds its gold, tracks the mission and stamps the clock', () => {
+ const rec = applyEventRun(emptyEventRecord('acct-1', 'Ada'), {
+ missionId: 'event-plaza-catch', gold: 320, at: 1000,
+ });
+ expect(rec.runs).toBe(1);
+ expect(rec.cash).toBe(320);
+ expect(rec.lastAt).toBe(1000);
+ expect(rec.missions['event-plaza-catch']).toBe(1);
+ });
+
+ it('accumulates repeat runs of the same job', () => {
+ let rec = emptyEventRecord('acct-1', 'Ada');
+ rec = applyEventRun(rec, { missionId: 'event-plaza-catch', gold: 320, at: 1000 });
+ rec = applyEventRun(rec, { missionId: 'event-plaza-catch', gold: 320, at: 2000 });
+ expect(rec.runs).toBe(2);
+ expect(rec.cash).toBe(640);
+ expect(rec.missions['event-plaza-catch']).toBe(2);
+ });
+
+ it('takes the newest display name and never lets the clock go backwards', () => {
+ let rec = applyEventRun(emptyEventRecord('acct-1', 'Ada'), { missionId: 'm', gold: 10, at: 5000 });
+ rec = applyEventRun(rec, { missionId: 'm', gold: 10, at: 100, name: 'Ada Prime' });
+ expect(rec.name).toBe('Ada Prime');
+ expect(rec.lastAt).toBe(5000);
+ });
+
+ it('clamps junk instead of poisoning the score with NaN or a negative', () => {
+ const rec = applyEventRun(emptyEventRecord('acct-1'), { missionId: 'm', gold: -900, at: 'later' });
+ expect(rec.runs).toBe(1);
+ expect(rec.cash).toBe(0);
+ expect(rec.lastAt).toBe(0);
+ });
+});
+
+describe('normalizeEventRecord', () => {
+ it('rebuilds a full record from a partial or legacy blob', () => {
+ const rec = normalizeEventRecord({ runs: 3 }, 'acct-9');
+ expect(rec).toMatchObject({ account: 'acct-9', runs: 3, cash: 0, lastAt: 0 });
+ expect(rec.missions).toEqual({});
+ });
+
+ it('degrades a corrupt blob to a zeroed record rather than throwing', () => {
+ const rec = normalizeEventRecord({ runs: 'many', cash: null, missions: 'nope' }, 'acct-9');
+ expect(rec.runs).toBe(0);
+ expect(rec.cash).toBe(0);
+ expect(rec.missions).toEqual({});
+ });
+});
+
+describe('rankEventBoard', () => {
+ it('ranks by completions first', () => {
+ const rows = rankEventBoard([runner('a', { runs: 2 }), runner('b', { runs: 5 }), runner('c', { runs: 3 })]);
+ expect(rows.map((r) => r.account)).toEqual(['b', 'c', 'a']);
+ expect(rows.map((r) => r.rank)).toEqual([1, 2, 3]);
+ });
+
+ it('breaks a tie on runs with total event cash', () => {
+ const rows = rankEventBoard([
+ runner('a', { runs: 4, cash: 800 }),
+ runner('b', { runs: 4, cash: 1200 }),
+ ]);
+ expect(rows.map((r) => r.account)).toEqual(['b', 'a']);
+ });
+
+ it('breaks a dead heat with the earlier finisher', () => {
+ const rows = rankEventBoard([
+ runner('late', { runs: 4, cash: 800, lastAt: 9000 }),
+ runner('early', { runs: 4, cash: 800, lastAt: 1000 }),
+ ]);
+ expect(rows.map((r) => r.account)).toEqual(['early', 'late']);
+ });
+
+ it('is total and reproducible even when every score is identical', () => {
+ const tied = [runner('z', { runs: 1 }), runner('a', { runs: 1 }), runner('m', { runs: 1 })];
+ expect(rankEventBoard(tied).map((r) => r.account)).toEqual(['a', 'm', 'z']);
+ expect(rankEventBoard([...tied].reverse()).map((r) => r.account)).toEqual(['a', 'm', 'z']);
+ });
+
+ it('leaves out players who never finished an event job', () => {
+ const rows = rankEventBoard([runner('a', { runs: 0 }), runner('b', { runs: 1 })]);
+ expect(rows.map((r) => r.account)).toEqual(['b']);
+ });
+
+ it('survives an empty board', () => {
+ expect(rankEventBoard([])).toEqual([]);
+ expect(rankEventBoard()).toEqual([]);
+ });
+});
+
+describe('eventBoardView', () => {
+ const many = Array.from({ length: 25 }, (_, i) => runner(`acct-${i}`, { runs: 25 - i, cash: (25 - i) * 100 }));
+
+ it('serves the top ten by default with totals for the whole field', () => {
+ const view = eventBoardView(many, { account: 'acct-0' });
+ expect(view.top).toHaveLength(TOP_LIMIT);
+ expect(view.top[0].rank).toBe(1);
+ expect(view.players).toBe(25);
+ expect(view.totalRuns).toBe(many.reduce((n, r) => n + r.runs, 0));
+ });
+
+ it('pins your own row when you are outside the top ten', () => {
+ const view = eventBoardView(many, { account: 'acct-20' });
+ expect(view.you.rank).toBe(21);
+ expect(view.you.inTop).toBe(false);
+ expect(view.top.some((r) => r.rank === 21)).toBe(false);
+ });
+
+ it('marks your row as in-top when you made the cut', () => {
+ const view = eventBoardView(many, { account: 'acct-1' });
+ expect(view.you.rank).toBe(2);
+ expect(view.you.inTop).toBe(true);
+ });
+
+ it('serves an anonymous read with no you row', () => {
+ expect(eventBoardView(many, {}).you).toBeNull();
+ });
+
+ it('answers null for a player who has not run anything yet', () => {
+ expect(eventBoardView(many, { account: 'never-played' }).you).toBeNull();
+ });
+
+ it('never leaks the account key onto the wire', () => {
+ const view = eventBoardView(many, { account: 'acct-0' });
+ for (const row of [...view.top, view.you]) expect(row.account).toBeUndefined();
+ });
+
+ it('names an unnamed runner rather than rendering a blank row', () => {
+ const view = eventBoardView([runner('acct-x', { runs: 1, name: '' })], { account: 'acct-x' });
+ expect(view.top[0].name).toBe('Anonymous');
+ });
+
+ it('honours a custom limit and clamps an absurd one', () => {
+ expect(eventBoardView(many, { limit: 3 }).top).toHaveLength(3);
+ expect(eventBoardView(many, { limit: 9999 }).top).toHaveLength(25);
+ expect(eventBoardView(many, { limit: 0 }).top).toHaveLength(TOP_LIMIT);
+ });
+
+ it('serves the designed empty board, not an error, when nobody has played', () => {
+ const view = eventBoardView([], { account: 'acct-1' });
+ expect(view).toEqual({ top: [], you: null, players: 0, totalRuns: 0 });
+ });
+});
diff --git a/tests/event-quests.test.js b/tests/event-quests.test.js
new file mode 100644
index 000000000..bd5a6b7a8
--- /dev/null
+++ b/tests/event-quests.test.js
@@ -0,0 +1,174 @@
+// Event quest line (order 04) — the gate is the whole feature. An event job must
+// be invisible, unacceptable and unpayable outside the event window, and fully
+// playable inside it, judged from the SERVER's read of public/event.json. These
+// cases pin both halves plus the new `defeat` objective the combat job runs on.
+import { describe, it, expect } from 'vitest';
+import {
+ MISSIONS, EVENT_MISSION_IDS, isEventMission,
+ boardOffers, canAccept, acceptMission, applyEvent, objectiveMatches,
+ newQuestState, questSnapshot, pruneClosedEventRuns, missionReward,
+} from '../multiplayer/src/quests.js';
+import { questZone } from '../multiplayer/src/quest-zones.js';
+import { DANGER_ZONES } from '../multiplayer/src/world-features.js';
+import { parseEventWindow, isEventLive } from '../multiplayer/src/event-window.js';
+
+const LIVE = { eventLive: true };
+const CLOSED = { eventLive: false };
+const DAY = '2026-08-07';
+
+describe('event mission registry', () => {
+ it('registers a quest line of 3 to 5 event jobs, all repeatable solo work', () => {
+ expect(EVENT_MISSION_IDS.length).toBeGreaterThanOrEqual(3);
+ expect(EVENT_MISSION_IDS.length).toBeLessThanOrEqual(5);
+ for (const id of EVENT_MISSION_IDS) {
+ const m = MISSIONS[id];
+ expect(m.event).toBe(true);
+ expect(m.kind).toBe('job');
+ expect(m.repeat).toBe('repeatable');
+ expect(m.party).toBe(1);
+ expect(missionReward(m).gold).toBeGreaterThan(0);
+ }
+ });
+
+ it('spans gathering, vehicle delivery, combat and a landmark tour', () => {
+ const types = EVENT_MISSION_IDS.flatMap((id) => MISSIONS[id].objectives.map((o) => o.type));
+ expect(types).toContain('collect');
+ expect(types).toContain('defeat');
+ expect(types).toContain('goto');
+ const driving = MISSIONS['event-supply-run'].objectives;
+ expect(driving.every((o) => o.type === 'goto' && o.vehicle === true)).toBe(true);
+ });
+
+ it('every event objective points at a real zone the server can resolve', () => {
+ for (const id of EVENT_MISSION_IDS) {
+ for (const obj of MISSIONS[id].objectives) {
+ if (obj.zone) expect(questZone(obj.zone), `${id}:${obj.zone}`).toBeTruthy();
+ if (obj.dangerZone) {
+ expect(DANGER_ZONES.some((z) => z.id === obj.dangerZone), `${id}:${obj.dangerZone}`).toBe(true);
+ }
+ }
+ }
+ });
+
+ it('isEventMission only claims the event jobs', () => {
+ expect(isEventMission('event-plaza-catch')).toBe(true);
+ expect(isEventMission('daily-anglers-haul')).toBe(false);
+ expect(isEventMission('nope')).toBe(false);
+ });
+});
+
+describe('the event window gates the board', () => {
+ it('hides every event job when the window is closed', () => {
+ const offers = boardOffers(newQuestState(DAY), DAY, CLOSED).map((o) => o.id);
+ for (const id of EVENT_MISSION_IDS) expect(offers).not.toContain(id);
+ // The everyday board is untouched by the gate.
+ expect(offers).toContain('harbor-courier');
+ });
+
+ it('offers every event job when the window is open, event jobs first', () => {
+ const offers = boardOffers(newQuestState(DAY), DAY, LIVE);
+ const ids = offers.map((o) => o.id);
+ for (const id of EVENT_MISSION_IDS) expect(ids).toContain(id);
+ expect(offers.slice(0, EVENT_MISSION_IDS.length).every((o) => o.event)).toBe(true);
+ });
+
+ it('defaults to CLOSED when no context is passed at all', () => {
+ const ids = boardOffers(newQuestState(DAY), DAY).map((o) => o.id);
+ for (const id of EVENT_MISSION_IDS) expect(ids).not.toContain(id);
+ });
+
+ it('refuses to accept an event job out of window, and says why', () => {
+ const state = newQuestState(DAY);
+ expect(canAccept(state, MISSIONS['event-plaza-catch'], DAY, CLOSED)).toBe(false);
+ const res = acceptMission(state, 'event-plaza-catch', DAY, CLOSED);
+ expect(res.ok).toBe(false);
+ expect(res.reason).toBe('event-closed');
+ expect(state.active['event-plaza-catch']).toBeUndefined();
+ });
+
+ it('accepts an event job in window', () => {
+ const state = newQuestState(DAY);
+ const res = acceptMission(state, 'event-plaza-catch', DAY, LIVE);
+ expect(res.ok).toBe(true);
+ expect(state.active['event-plaza-catch']).toBeTruthy();
+ });
+
+ it('drops a run left over when the window shuts, and keeps ordinary runs', () => {
+ const state = newQuestState(DAY);
+ acceptMission(state, 'event-plaza-catch', DAY, LIVE);
+ acceptMission(state, 'harbor-courier', DAY, LIVE);
+ expect(pruneClosedEventRuns(state, LIVE)).toEqual([]); // still live: nothing dropped
+ expect(pruneClosedEventRuns(state, CLOSED)).toEqual(['event-plaza-catch']);
+ expect(state.active['event-plaza-catch']).toBeUndefined();
+ expect(state.active['harbor-courier']).toBeTruthy();
+ });
+
+ it('reports the live flag on the snapshot the client renders from', () => {
+ expect(questSnapshot(newQuestState(DAY), DAY, LIVE).eventLive).toBe(true);
+ expect(questSnapshot(newQuestState(DAY), DAY, CLOSED).eventLive).toBe(false);
+ });
+});
+
+describe('the defeat objective (the combat event job)', () => {
+ const obj = MISSIONS['event-wilds-patrol'].objectives[0];
+
+ it('matches a mob kill inside its named danger zone', () => {
+ expect(objectiveMatches(obj, { type: 'defeat', target: 'mob', zone: 'southern-wilds' })).toBe(true);
+ });
+
+ it('ignores a kill in a different danger zone', () => {
+ expect(objectiveMatches(obj, { type: 'defeat', target: 'mob', zone: 'northern-wilds' })).toBe(false);
+ });
+
+ it('ignores a kill with no zone at all (a town kill can never happen, but a null must not count)', () => {
+ expect(objectiveMatches(obj, { type: 'defeat', target: 'mob', zone: null })).toBe(false);
+ });
+
+ it('ignores a player kill when the objective asks for mobs', () => {
+ expect(objectiveMatches(obj, { type: 'defeat', target: 'player', zone: 'southern-wilds' })).toBe(false);
+ });
+
+ it('counts one per kill and completes at the required count', () => {
+ const run = { id: 'event-wilds-patrol', stage: 0, counts: {}, startedAt: 0, day: DAY };
+ const mission = MISSIONS['event-wilds-patrol'];
+ const kill = { type: 'defeat', target: 'mob', zone: 'southern-wilds' };
+ const need = mission.objectives[0].count;
+ for (let i = 1; i < need; i++) {
+ const res = applyEvent(run, mission, kill);
+ expect(res.matched).toBe(true);
+ expect(res.missionComplete).toBe(false);
+ expect(run.counts[0]).toBe(i);
+ }
+ expect(applyEvent(run, mission, kill).missionComplete).toBe(true);
+ });
+});
+
+describe('the window itself is parsed from the config, never hardcoded', () => {
+ const doc = { id: 'e1', name: 'Meetup', startsAt: '2026-08-07T17:00:00Z', endsAt: '2026-08-07T19:00:00Z' };
+ const win = parseEventWindow(doc);
+
+ it('parses id and bounds off the same fields the client reads', () => {
+ expect(win.id).toBe('e1');
+ expect(win.startsAt).toBe(Date.parse(doc.startsAt));
+ expect(win.endsAt).toBe(Date.parse(doc.endsAt));
+ });
+
+ it('is live inside the window and closed on either side of it', () => {
+ expect(isEventLive(win, Date.parse('2026-08-07T16:59:59Z'))).toBe(false);
+ expect(isEventLive(win, Date.parse('2026-08-07T17:00:00Z'))).toBe(true);
+ expect(isEventLive(win, Date.parse('2026-08-07T18:59:59Z'))).toBe(true);
+ expect(isEventLive(win, Date.parse('2026-08-07T19:00:00Z'))).toBe(false);
+ });
+
+ it('defaults a missing end to six hours, matching the client parser', () => {
+ const open = parseEventWindow({ id: 'e2', startsAt: '2026-08-07T17:00:00Z' });
+ expect(open.endsAt - open.startsAt).toBe(6 * 3600 * 1000);
+ });
+
+ it('treats a missing or malformed config as no event, so the gate stays closed', () => {
+ expect(parseEventWindow(null)).toBeNull();
+ expect(parseEventWindow({})).toBeNull();
+ expect(parseEventWindow({ startsAt: 'not a date' })).toBeNull();
+ expect(isEventLive(null, Date.now())).toBe(false);
+ });
+});
diff --git a/tests/play-death-drop.test.js b/tests/play-death-drop.test.js
new file mode 100644
index 000000000..c4a72d395
--- /dev/null
+++ b/tests/play-death-drop.test.js
@@ -0,0 +1,139 @@
+// Death, the drop, and what the dying player is actually told (W07).
+//
+// The bank exists because dying costs you the purse you are carrying. That trade
+// is only legible if the client is told the truth at the moment it happens: the
+// old flow flagged the player dead and then sat on the pre-death purse for the
+// whole respawn delay, so the HUD showed cash that was already lying in a
+// tombstone. These tests pin the drop itself (carried gone, banked untouched,
+// tools kept) and the snapshot + message that report it.
+
+import { describe, it, expect, vi } from 'vitest';
+
+const { killPlayer, PLAYER_RESPAWN_MS } = await import('../multiplayer/src/combat-handlers.js');
+const { newProfile } = await import('../multiplayer/src/economy.js');
+const { SPAWN_POINT } = await import('../multiplayer/src/world-features.js');
+
+// A room with only what killPlayer touches. `clock.setTimeout` collects the
+// pending callbacks so a test can run the respawn deliberately instead of
+// waiting 5.5 real seconds.
+function makeRoom(profile) {
+ const sent = [];
+ const timers = [];
+ const player = { x: 12, z: -4, name: 'Ada', dead: false, tsServer: 0 };
+ const client = { sessionId: 's1', send: (type, msg) => sent.push({ type, msg }) };
+ const room = {
+ state: { players: new Map([['s1', player]]), tombstones: new Map() },
+ econ: new Map([['s1', profile]]),
+ clients: [client],
+ clock: { setTimeout: (fn, ms) => { timers.push({ fn, ms }); return { clear() {} }; } },
+ _tombLoot: new Map(),
+ _sendInv: vi.fn(),
+ _persistEcon: vi.fn(),
+ };
+ return { room, client, player, sent, timers };
+}
+
+// A player mid-run: 240 carried, 500 banked, a stack of gathered goods, tools on
+// the hotbar.
+function loadedProfile() {
+ const p = newProfile('acct-death');
+ p.gold = 240;
+ p.bank = 500;
+ p.inv[2] = { item: 'wood', qty: 30 };
+ p.inv[3] = { item: 'cookedFish', qty: 4 };
+ return p;
+}
+
+describe('killPlayer — the drop', () => {
+ it('drops carried cash and the pack, keeps banked cash and hotbar tools', () => {
+ const profile = loadedProfile();
+ const { room } = makeRoom(profile);
+ killPlayer(room, 's1', 'a goblin');
+
+ expect(profile.gold).toBe(0);
+ expect(profile.bank).toBe(500);
+ expect(profile.inv.every((s) => !s.item)).toBe(true);
+ // The starter kit lives on the hotbar and survives, so a respawn isn't toothless.
+ expect(profile.hotbar.some((s) => s.item === 'sword')).toBe(true);
+ });
+
+ it('spills exactly what was carried into a lootable tombstone where the player fell', () => {
+ const profile = loadedProfile();
+ const { room, player } = makeRoom(profile);
+ killPlayer(room, 's1', 'a goblin');
+
+ expect(room.state.tombstones.size).toBe(1);
+ const tomb = [...room.state.tombstones.values()][0];
+ expect(tomb.gold).toBe(240);
+ expect(tomb.x).toBe(player.x);
+ expect(tomb.z).toBe(player.z);
+ const loot = [...room._tombLoot.values()][0];
+ expect(loot.gold).toBe(240);
+ expect(loot.items).toEqual(
+ expect.arrayContaining([{ item: 'wood', qty: 30 }, { item: 'cookedFish', qty: 4 }]),
+ );
+ });
+});
+
+describe('killPlayer — what the dying player is told', () => {
+ it('pushes the emptied purse immediately, not at respawn', () => {
+ const profile = loadedProfile();
+ const { room, client } = makeRoom(profile);
+ killPlayer(room, 's1', 'a goblin');
+
+ expect(room._sendInv).toHaveBeenCalledWith(client, profile);
+ // The snapshot is taken from the already-emptied profile, so a HUD reading it
+ // can never show cash that is lying in the tombstone.
+ expect(profile.gold).toBe(0);
+ });
+
+ it('names what was lost and what the bank protected', () => {
+ const profile = loadedProfile();
+ const { sent, room } = makeRoom(profile);
+ killPlayer(room, 's1', 'a goblin');
+
+ const deaths = sent.filter((m) => m.type === 'notice' && m.msg.kind === 'death');
+ expect(deaths.length).toBe(2);
+ expect(deaths[0].msg.text).toContain('killed by a goblin');
+ expect(deaths[1].msg.text).toContain('240 cash');
+ expect(deaths[1].msg.text).toContain('2 items');
+ expect(deaths[1].msg.text).toContain('500 cash stayed safe in the bank');
+ });
+
+ it('says so plainly when there was nothing on you to lose', () => {
+ const profile = newProfile('acct-broke');
+ profile.bank = 75;
+ const { sent, room } = makeRoom(profile);
+ killPlayer(room, 's1', null);
+
+ const deaths = sent.filter((m) => m.type === 'notice' && m.msg.kind === 'death');
+ expect(deaths[1].msg.text).toContain('nothing to drop');
+ expect(deaths[1].msg.text).toContain('75 cash is safe in the bank');
+ // Nothing carried means nothing to loot; no empty tombstone litters the world.
+ expect(room.state.tombstones.size).toBe(0);
+ });
+});
+
+describe('killPlayer — respawn', () => {
+ it('revives at full health at the safe spawn and persists the emptied profile', () => {
+ const profile = loadedProfile();
+ const { room, timers, sent } = makeRoom(profile);
+ killPlayer(room, 's1', 'a troll');
+
+ const respawn = timers.find((t) => t.ms === PLAYER_RESPAWN_MS);
+ expect(respawn).toBeTruthy();
+ respawn.fn();
+
+ const player = room.state.players.get('s1');
+ expect(player.dead).toBe(false);
+ expect(player.x).toBe(SPAWN_POINT.x);
+ expect(player.z).toBe(SPAWN_POINT.z);
+ expect(profile.hp).toBe(profile.maxHp);
+ // The vest is gone with the rest of the pack; the armour bar starts empty.
+ expect(profile.armor).toBe(0);
+ expect(room._persistEcon).toHaveBeenCalledWith('s1');
+ const snap = sent.find((m) => m.type === 'profile');
+ expect(snap.msg.gold).toBe(0);
+ expect(snap.msg.bank).toBe(500);
+ });
+});
diff --git a/tests/walkroom-build-perms.test.js b/tests/walkroom-build-perms.test.js
index c85db847a..2be9c805d 100644
--- a/tests/walkroom-build-perms.test.js
+++ b/tests/walkroom-build-perms.test.js
@@ -35,7 +35,20 @@ describe('WalkRoom build permissions (R19)', () => {
expect(room._isProtectedColumn(0, 0)).toBe(true); // spawn
expect(room._isProtectedColumn(0, -8)).toBe(true); // totem (world z=-12 → grid -8)
expect(room._isProtectedColumn(2, -1)).toBe(true); // within the spawn disc
- expect(room._isProtectedColumn(15, 15)).toBe(false); // open plaza
+ expect(room._isProtectedColumn(40, 40)).toBe(false); // open plaza, clear of every disc
+ });
+
+ // The Living Stage is where a show (and the meetup agenda) actually happens, so
+ // its guard disc is derived from world-features.PLAZA_STAGE rather than written
+ // out twice. Pinning the derivation here is what stops a builder walling the
+ // venue off, and stops the two definitions drifting if the venue ever moves.
+ it('protects the plaza stage disc, derived from the venue itself', () => {
+ const cx = Math.round(PLAZA_STAGE.x / BLOCK_SIZE_M);
+ const cz = Math.round(PLAZA_STAGE.z / BLOCK_SIZE_M);
+ const cells = Math.ceil(PLAZA_STAGE.r / BLOCK_SIZE_M);
+ expect(room._isProtectedColumn(cx, cz)).toBe(true);
+ expect(room._isProtectedColumn(cx + cells, cz)).toBe(true); // the disc edge
+ expect(room._isProtectedColumn(cx + cells + 1, cz)).toBe(false); // just outside it
});
it('refuses placement in a protected column', () => {