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.

fix(stage): land the Living Stages live-feed fix again after a stale-index commit rolled it back

nirholas6fbf8e294c03
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 94829b922..afdaec3d5 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -76,6 +76,7 @@ bottom.
| Paid Market Data API (x402, 17 endpoints) | Registry [api/_lib/market-data/registry.js](api/_lib/market-data/registry.js), fetchers [api/_lib/market-data/fetch.js](api/_lib/market-data/fetch.js), factory [api/_lib/market-data/endpoint.js](api/_lib/market-data/endpoint.js), routes `api/x402/market-*.js` `→ /api/x402/market-<category>`, free index [api/x402/market.js](api/x402/market.js) `→ /api/x402/market`, catalog projection [api/_lib/service-catalog/services/market-data.js](api/_lib/service-catalog/services/market-data.js), docs [docs/market-data-api.md](docs/market-data-api.md) `→ /docs/market-data-api` | Live | Every free /markets feed (coins, coin profile, price history, categories, exchanges, derivatives, global+Fear&Greed, ETH gas, trending, DeFi TVL, chains, ~15k yield pools, stablecoins, fees/revenue, DEX volumes, hacks) wrapped as pay-per-call x402 endpoints at $0.001 USDC (Solana/Base), plus the $0.005 one-call `market-pulse` bundle. One registry drives the live 402s, the discovery-doc listings, and the free index — zero drift by construction; the fetchers delegate to the SAME exported builders the free pages use (`api/coin/*`, `api/defi/*`), so paid data always matches the site. Params rejected pre-settle (422) and upstream outages (503) never charge the buyer. Tests: [tests/market-data-api.test.js](tests/market-data-api.test.js). |
| Datapoint fabric (x402, 480k+ endpoints) | Registry [api/_lib/market-data/datapoints.js](api/_lib/market-data/datapoints.js), dynamic route [api/x402/d/[...path].js](api/x402/d/%5B...path%5D.js) `→ /api/x402/d/<family>/<id>/<metric>`, free catalog [api/x402/d/index.js](api/x402/d/index.js) `→ /api/x402/d`, discovery slice `buildDatapointItems` in [api/wk.js](api/wk.js), docs § in [docs/market-data-api.md](docs/market-data-api.md#the-datapoint-fabric--480000-standalone-endpoints) | Live | Every individual market datapoint as its OWN standalone paid endpoint — one URL = one value = one $0.0005 USDC x402 micro-payment (override `X402_PRICE_DATAPOINT_<FAMILY>`). 9 families × 68 metrics × live id spaces ≈ 484k addressable endpoints (~17.5k coins × 20, ~15.5k pools × 7, ~6k protocols × 6, chains, stablecoins, exchanges, global/gas/fear-greed) served by ONE dynamic route reading the registry; ids are runtime values, nothing hardcodes a third-party asset. Path that cannot exist → 404/422 with NO 402 issued; unknown id/outage rejects pre-settle. Free catalog enumerates families, metrics, prices, and pages each family's full live id space (200/page) so crawlers can walk the universe; the .well-known discovery doc carries a curated runtime-derived slice (~83 concrete resources). Tests: [tests/market-datapoints.test.js](tests/market-datapoints.test.js). |
| Pole Club (x402 micro-tips drive a live 3D room) | Page [pages/club.html](pages/club.html) `→ /club`, stage app [src/club.js](src/club.js) with [src/club-camera.js](src/club-camera.js), [src/club-crowd.js](src/club-crowd.js), [src/club-dances.js](src/club-dances.js), [src/club-audio.js](src/club-audio.js), [src/club-venue.js](src/club-venue.js), [src/club-perf.js](src/club-perf.js), [src/club-sequence.js](src/club-sequence.js); walk-in [src/club-entrance.js](src/club-entrance.js) + cover gate [src/club-gate.js](src/club-gate.js) (shared express flag [src/shared/club-express.js](src/shared/club-express.js)); paid endpoints [api/x402/club-cover.js](api/x402/club-cover.js) `→ /api/x402/club-cover` and [api/x402/dance-tip.js](api/x402/dance-tip.js) `→ /api/x402/dance-tip`; free reads [api/club/leaderboard.js](api/club/leaderboard.js), [api/club/tips.js](api/club/tips.js), [api/club/tips-stream.js](api/club/tips-stream.js) `→ /api/club/tips/stream` (SSE), [api/club/presence.js](api/club/presence.js); payouts [api/\_lib/club/payouts.js](api/_lib/club/payouts.js) via the `/api/cron/club-payouts` job; assets [public/club/](public/club) | Live | The platform's showcase of x402 as a live interaction loop rather than a billing detail: a $0.01 USDC cover charge at the door (with an on-chain bouncer that reads the paying wallet's ban list and prior visits, and a device-cached pass so one cover lasts the night), then $0.001 USDC per routine at three poles. A settled tip is what puts a dancer on the pole, so the payment IS the interaction. Third-person walk-in through alley → gallery → clubhouse → stage before the room opens; dancers are ordinary gallery avatars retargeted onto the shared clip library, swappable per pole. Tips land live over SSE with REST backfill on reconnect, and per-dancer earnings accrue to `club_dancer_wallets` for the payout sweep. `/club?demo` is the express entry that skips the cover for QA and recordings. |
+| Living Stages (an AI host performs live, tipped in $THREE) | Page [pages/stage.html](pages/stage.html) `→ /stage` (the marquee) and `→ /stage?id=<stage>` (the venue), runtime [src/stage.js](src/stage.js), realtime client [src/stage-net.js](src/stage-net.js) → `stage_world` in [multiplayer/src/rooms/StageRoom.js](multiplayer/src/rooms/StageRoom.js) with the show logic in [multiplayer/src/stage-show.js](multiplayer/src/stage-show.js); API [api/stage/index.js](api/stage/index.js) `→ /api/stage`, tips [api/stage/tip.js](api/stage/tip.js) `→ /api/stage/tip`, host brain [api/stage/host.js](api/stage/host.js) `→ /api/stage/host` (HMAC, multiplayer server only) | Live | An embodied agent hosts a show in a 3D venue. Each beat is a timed `utterance` broadcast every client renders identically: TTS through a `PositionalAudio` whose analyser drives lip-sync, plus live captions, so a late joiner or a no-WebGL browser still reads the show. The crowd is co-present on a server-assigned ring, questions queue for the host, and a $THREE tip that settles on-chain to the host wallet is verified by the API and pushed into the room so the host reacts within a beat. The page resolves the realtime server through the same chain as `/play` ([src/shared/game-server-url.js](src/shared/game-server-url.js)) from the `game-server` meta it carries; localhost talks to `:2567`. The client subscribes to the host frame with `listen` (the join resolves before the first state patch, so `onChange` on the not-yet-decoded child throws) and registers message handlers before any state work, because the room opens the show the instant the first person arrives. With no feed the pill reads offline and reconnects on tap. Docs: [docs/stage.md](docs/stage.md). Tests: [tests/multiplayer-server-boot.test.js](tests/multiplayer-server-boot.test.js) (a real `stage_world` join wired the way the page does it), [tests/stage-show.test.js](tests/stage-show.test.js) |
| Fits: the public cosmetics economy | [pages/fits.html](pages/fits.html) `→ /fits`, page module [src/fits.js](src/fits.js) + pure helpers [src/fits-lib.js](src/fits-lib.js), backends [api/cosmetics/leaderboard.js](api/cosmetics/leaderboard.js) + [api/cosmetics/earnings.js](api/cosmetics/earnings.js), engine [api/_lib/cosmetics-economy.js](api/_lib/cosmetics-economy.js) | Live | The settled-sale cosmetics ledger, promoted out of a panel inside `/play` into a public surface. Rarest premium fits ranked by how few wallets own them (owner count first, rarity as the tie-break, so a legendary never sorts under an equally-scarce rare), top collectors by rarity-weighted flex score, top creators by **actually settled** USDC, and a live sales drip; each fit deep-links to its coin world at `/play?coin=<mint>`. Plus a creator-earnings lookup any wallet can run without an account (lifetime + 30-day, paid vs pending, per-cosmetic and per-coin-world breakdowns), reachable in one click from each creator row rather than by copy-pasting an address. Coin mints are runtime ledger values, never hardcoded. Headline numbers are derived from the same rows rendered beneath them, so they cannot disagree; the volume tile is labelled as the returned sales window, not as an all-time total. Sub-cent sales keep their precision instead of collapsing to $0.00. Tests: [tests/fits-lib.test.js](tests/fits-lib.test.js) |
| Receipt Vault: buyer-side proof of purchase | [pages/receipts.html](pages/receipts.html) `→ /receipts`, page module [src/receipts.js](src/receipts.js) + pure helpers [src/receipts-lib.js](src/receipts-lib.js), backend [api/x402/my-receipts.js](api/x402/my-receipts.js), storage [api/_lib/x402/receipt-storage.js](api/_lib/x402/receipt-storage.js), issuer [api/_lib/x402/offer-receipt-issuer.js](api/_lib/x402/offer-receipt-issuer.js), key publication [api/x402/did.js](api/x402/did.js) `→ /.well-known/did.json` | Live | What a given wallet **spent** on the platform's paid endpoints. Every settled x402 call issues a signed Offer & Receipt artifact (USE-17) and durably logs it; a buyer connects a Solana or EVM wallet, signs one read-only message (5-minute window, no transaction, no fee) and gets every receipt ever issued to that wallet: endpoint, settled amount, network, explorer-linked tx, the full signed artifact as JSON, plus search and CSV export. The signing message is a fixed four-line string that must stay byte-identical between `buildReceiptsMessage()` (client) and `buildExpectedMessage()` (server); [tests/receipts-lib.test.js](tests/receipts-lib.test.js) pins that contract against a verbatim copy of the server's function. The signed artifact carries no amount and omits the tx hash under the spec §5.2 privacy default, so the row records both separately as our own audit trail (migration [api/_lib/migrations/2026-07-28-x402-receipt-settlement.sql](api/_lib/migrations/2026-07-28-x402-receipt-settlement.sql)); receipts predating that capture report as "N of M priced" rather than under-reporting a total. Issuance requires `OFFER_RECEIPT_JWK` (jws) or `OFFER_RECEIPT_SIGNING_PRIVATE_KEY` (eip712); unset means no receipts are issued at all. Docs: [docs/x402-endpoints.md](docs/x402-endpoints.md) |
| Unified service catalog (one source, two storefronts) | [api/_lib/service-catalog/index.js](api/_lib/service-catalog/index.js), descriptors [api/_lib/service-catalog/services/](api/_lib/service-catalog/services/index.js) | Live | The canonical written-once record of every service (paid x402 + free crypto/3D bundles + OKX.AI rows). `toBazaarDiscovery()` generates every static `/api/x402/*` entry in the [api/wk.js](api/wk.js) discovery doc (replacing ~1,400 lines of hand-mirrored blocks); `toOkxCatalog()` reproduces the OKX `catalogIndex()` payload exactly, with an `include:'all'` projection ready for listing expansion. New paid service = drop `services/<slug>.js` + add its barrel import row. No-drift guards: [tests/service-catalog.test.js](tests/service-catalog.test.js). Spec: [specs/SERVICE_CATALOG.md](specs/SERVICE_CATALOG.md) |
diff --git a/docs/stage.md b/docs/stage.md
index 73dd181cd..6779baecf 100644
--- a/docs/stage.md
+++ b/docs/stage.md
@@ -135,7 +135,7 @@ The show's running total is rolled on each tip as a convenience; if that bump fa
Every state on this surface is designed, because a live show has more failure modes than a static page:
-- **Realtime feed offline.** If no multiplayer server is configured or the socket cannot be reached after one retry, the connection pill honestly reads "feed offline" instead of pretending to be live. Captions, tips, and the leaderboard still work through the API.
+- **Realtime feed offline.** If no multiplayer server is configured or the socket cannot be reached after one retry, the connection pill honestly reads "feed offline · tap to retry" instead of pretending to be live, and tapping it reconnects. Tips and the leaderboard still work through the API; the caption you see is the last one the feed delivered. Asking a question while the feed is down tells you to reconnect first rather than silently dropping it.
- **No WebGL.** The venue swaps to an "audio and captions mode" card: you still hear the host, read every line, and can still tip.
- **No wallet on the host.** Tipping is disabled with a plain explanation rather than a failing transaction.
- **Not live yet.** Tips are refused client-side and server-side with "tips open when the host goes live".
@@ -153,7 +153,7 @@ The venue is split across two deployments, so it needs both halves wired:
| `MULTIPLAYER_SHARED_SECRET` | both | The HMAC secret for both directions of the bridge. Must match on both sides |
| `THREEWS_API_BASE` or `MULTIPLAYER_API_BASE` | realtime server | Where the room reads stage config and fetches host beats from. Defaults to the production API |
-The browser resolves the realtime server from, in order: `window.STAGE_SERVER_URL`, a `stage-server` meta tag, `VITE_STAGE_SERVER_URL` at build time, a forwarded development port, or the same host on port 2567 in local development. In production with none of these set, the page runs in feed-offline mode rather than hanging on a socket.
+The browser resolves the realtime server from, in order: `window.STAGE_SERVER_URL`, a `stage-server` meta tag, `VITE_STAGE_SERVER_URL` at build time, and then the chain every other live world uses ([`src/shared/game-server-url.js`](../src/shared/game-server-url.js)): localhost always talks to the local server on port 2567, otherwise the `game-server` meta tag the page carries ([`pages/stage.html`](../pages/stage.html) bakes in the production multiplayer service, exactly like `/play`), then `VITE_GAME_SERVER_URL`, then a forwarded development port. In production with none of these set, the page runs in feed-offline mode rather than hanging on a socket. The client subscribes to the host's frame with `listen` on the root state rather than `onChange` on the child, because the join resolves before the first state patch lands and the child has no decoder reference yet; it also registers its message handlers before any state work, because the room opens the show the instant the first person arrives and that first line must not be dropped.
## Related
diff --git a/multiplayer/src/rooms/StageRoom.js b/multiplayer/src/rooms/StageRoom.js
index 5c0ffffd9..c438e686a 100644
--- a/multiplayer/src/rooms/StageRoom.js
+++ b/multiplayer/src/rooms/StageRoom.js
@@ -317,8 +317,9 @@ export class StageRoom extends Room {
// or the opener fired by the first arrival) speaks when nobody is present.
if (trigger === 'cadence' && this.state.audience.size === 0) return;
this._beatRunning = true;
+ let beat = null;
try {
- const beat = this._director.nextBeat();
+ beat = this._director.nextBeat();
const context = this._buildContext(beat);
const { text, cue } = await this._fetchBeat(beat, context);
const words = clean(text, 600) || this._fallbackLine(beat);
@@ -326,6 +327,15 @@ export class StageRoom extends Room {
this._director.markSpoken(beat.kind);
} catch (err) {
console.warn(`${this._tag()} beat (${trigger}) failed: ${err?.message || err}`);
+ // A brain that is unreachable (transport error, non-2xx, timeout) must
+ // not silence the stage: an opener that never plays leaves the first
+ // arrival staring at a mute host. Perform the failsafe line for this
+ // beat, the same one an empty brain reply gets, and let the next beat
+ // retry the brain.
+ if (beat) {
+ this._performUtterance(beat, this._fallbackLine(beat), cueFor(beat.kind));
+ this._director.markSpoken(beat.kind);
+ }
} finally {
this._beatRunning = false;
}
@@ -413,13 +423,13 @@ export class StageRoom extends Room {
_fallbackLine(beat) {
const name = this.state.host.name || 'your host';
if (beat.kind === BEAT.TIP_SHOUTOUT && beat.tip) {
- return `Huge love to ${beat.tip.label} for the tip — you keep this stage alive!`;
+ return `Huge love to ${beat.tip.label} for the tip. You keep this stage alive!`;
}
if (beat.kind === BEAT.ANSWER && beat.question) {
- return `Good question from ${beat.question.from} — let me come back to that one.`;
+ return `Good question from ${beat.question.from}. Let me come back to that one.`;
}
- if (beat.kind === BEAT.OPENER) return `Welcome in — ${name} on the stage. Pull up a seat.`;
- return `Stay with me — more coming up right now.`;
+ if (beat.kind === BEAT.OPENER) return `Welcome in, ${name} on the stage. Pull up a seat.`;
+ return `Stay with me, more coming up right now.`;
}
onDispose() {
diff --git a/pages/stage.html b/pages/stage.html
index a2e18b189..be7a2e633 100644
--- a/pages/stage.html
+++ b/pages/stage.html
@@ -5,7 +5,7 @@
<meta charset="utf-8" />
<title data-i18n="stage.meta_title">Living Stages · three.ws</title>
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
- <meta name="description" content="Live, embodied AI performances on three.ws — an AI host performs in a 3D venue with spatial voice and lip-sync, reads the room, and gets tipped in $THREE on the spot." data-i18n-attr="content:stage.meta_description"/>
+ <meta name="description" content="Live, embodied AI performances. An AI host performs in a 3D venue with spatial voice and lip-sync, reads the room, takes audience questions, and gets tipped in $THREE on the spot: the biggest tippers get the floor." data-i18n-attr="content:stage.meta_description"/>
<meta name="theme-color" content="#07060d" />
<link rel="icon" href="/favicon.ico" sizes="any" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
@@ -13,8 +13,10 @@
<meta property="og:type" content="website" />
<meta property="og:site_name" content="three.ws" />
<meta property="og:title" content="Living Stages · three.ws" data-i18n-attr="content:stage.meta_og_title"/>
- <meta property="og:description" content="An AI host performs live in a 3D venue — spatial voice, lip-sync, a co-present crowd, and real $THREE tips it reacts to on the spot." data-i18n-attr="content:stage.meta_og_description"/>
+ <meta property="og:description" content="An AI host performs live in a 3D venue: spatial voice, lip-sync, a co-present crowd, and real $THREE tips it reacts to on the spot." data-i18n-attr="content:stage.meta_og_description"/>
<meta property="og:url" content="https://three.ws/stage" />
+ <!-- The realtime performance feed (stage_world on the multiplayer Cloud Run service). Read by src/stage-net.js through the shared game-server chain; localhost dev ignores it and talks to :2567. -->
+ <meta name="game-server" content="wss://three-ws-multiplayer-93741856042.us-central1.run.app" />
<link rel="stylesheet" href="/tokens.css" />
<link rel="stylesheet" href="/buttons.css" />
@@ -71,7 +73,10 @@
.stage-phase { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 700; letter-spacing: .06em; color: var(--stage-dim); text-transform: uppercase; }
.stage-phase.is-live { color: #ff5db1; }
.stage-phase.is-live .dot { width: 8px; height: 8px; border-radius: 50%; background: #ff2d6f; animation: pulse 1.4s infinite; }
- .stage-net-pill { pointer-events: auto; font-size: 11px; padding: 4px 9px; border-radius: 999px; border: 1px solid var(--stage-line); background: rgba(7,6,13,.6); }
+ .stage-net-pill { pointer-events: auto; font: inherit; font-size: 11px; padding: 4px 9px; border-radius: 999px; border: 1px solid var(--stage-line); background: rgba(7,6,13,.6); color: var(--stage-dim); cursor: default; transition: background .15s, border-color .15s; }
+ .stage-net-pill.bad, .stage-net-pill.offline { cursor: pointer; }
+ .stage-net-pill.bad:hover { background: rgba(255,122,144,.14); }
+ .stage-net-pill:focus-visible { outline: 2px solid var(--stage-accent-2); outline-offset: 2px; }
.stage-net-pill.ok { color: #6ee7a8; border-color: rgba(110,231,168,.4); }
.stage-net-pill.warn { color: var(--stage-gold); }
.stage-net-pill.bad { color: #ff7a90; }
@@ -80,7 +85,10 @@
.stage-caption.speaking { border-color: var(--stage-accent); box-shadow: 0 0 30px rgba(155,107,255,.25); }
.stage-overlay-bottom { position: absolute; left: 20px; bottom: 20px; display: flex; gap: 12px; align-items: center; }
- .stage-sound { background: var(--stage-accent); color: #fff; border: 0; border-radius: 999px; padding: 9px 16px; font-weight: 600; cursor: pointer; }
+ .stage-sound { background: var(--stage-accent); color: #fff; border: 0; border-radius: 999px; padding: 9px 16px; font-weight: 600; cursor: pointer; transition: opacity .15s, transform .1s; }
+ .stage-sound:hover { opacity: .92; }
+ .stage-sound:active { transform: scale(.97); }
+ .stage-sound:focus-visible { outline: 2px solid var(--stage-accent-2); outline-offset: 2px; }
.stage-dolly { display: flex; align-items: center; gap: 8px; background: rgba(7,6,13,.6); border: 1px solid var(--stage-line); border-radius: 999px; padding: 4px 10px; font-size: 11px; color: var(--stage-dim); text-transform: uppercase; letter-spacing: .05em; }
.stage-dolly button { width: 28px; height: 28px; border-radius: 50%; border: 1px solid var(--stage-line); background: rgba(155,107,255,.12); color: var(--stage-text); font-size: 18px; line-height: 1; cursor: pointer; transition: background .15s; }
.stage-dolly button:hover { background: rgba(155,107,255,.3); }
@@ -106,6 +114,8 @@
.stage-tip-presets { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-bottom: 10px; }
.stage-tip-preset { padding: 8px 0; border-radius: 9px; border: 1px solid var(--stage-line); background: rgba(155,107,255,.08); color: var(--stage-text); font-size: 13px; font-weight: 600; cursor: pointer; transition: background .15s, border-color .15s; }
.stage-tip-preset:hover { background: rgba(155,107,255,.2); }
+ .stage-tip-preset:active { transform: scale(.97); }
+ .stage-tip-preset:focus-visible { outline: 2px solid var(--stage-accent-2); outline-offset: 1px; }
.stage-tip-preset.active { background: var(--stage-accent); border-color: var(--stage-accent); color: #fff; }
.stage-tip-row { display: flex; gap: 8px; margin-bottom: 8px; }
.stage-tip-row input, .stage-tip-msg, .stage-ask-row input { flex: 1; width: 100%; background: rgba(7,6,13,.6); border: 1px solid var(--stage-line); border-radius: 9px; padding: 9px 11px; color: var(--stage-text); font-size: 14px; }
@@ -113,7 +123,8 @@
input:focus-visible { outline: 2px solid var(--stage-accent-2); outline-offset: 0; }
.stage-tip-send, .stage-ask-row button { background: linear-gradient(90deg, var(--stage-accent), var(--stage-accent-2)); color: #fff; border: 0; border-radius: 9px; padding: 9px 18px; font-weight: 700; cursor: pointer; transition: opacity .15s, transform .1s; }
.stage-tip-send:hover, .stage-ask-row button:hover { opacity: .92; }
- .stage-tip-send:active { transform: scale(.97); }
+ .stage-tip-send:active, .stage-ask-row button:active { transform: scale(.97); }
+ .stage-tip-send:focus-visible, .stage-ask-row button:focus-visible { outline: 2px solid var(--stage-accent-2); outline-offset: 2px; }
.stage-tip-send:disabled { opacity: .5; cursor: progress; }
.stage-tip-status, .stage-ask-status { margin: 8px 0 0; font-size: 12px; min-height: 16px; color: var(--stage-dim); }
.stage-tip-status.ok { color: #6ee7a8; }
@@ -133,7 +144,10 @@
.stage-empty { text-align: center; padding: 80px 24px; max-width: 480px; margin: 0 auto; }
.stage-empty h2 { margin: 0 0 8px; }
.stage-empty p { color: var(--stage-dim); line-height: 1.5; }
- .stage-cta { display: inline-block; margin-top: 14px; background: var(--stage-accent); color: #fff; padding: 10px 20px; border-radius: 10px; text-decoration: none; border: 0; font: inherit; cursor: pointer; }
+ .stage-cta { display: inline-block; margin-top: 14px; background: var(--stage-accent); color: #fff; padding: 10px 20px; border-radius: 10px; text-decoration: none; border: 0; font: inherit; cursor: pointer; transition: opacity .15s, transform .1s; }
+ .stage-cta:hover { opacity: .92; }
+ .stage-cta:active { transform: scale(.97); }
+ .stage-cta:focus-visible { outline: 2px solid var(--stage-accent-2); outline-offset: 2px; }
@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: .4; } }
@keyframes shimmer { to { background-position: -200% 0; } }
@@ -154,13 +168,13 @@
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:type" content="image/png">
- <meta property="og:image:alt" content="Living Stages — three.ws">
+ <meta property="og:image:alt" content="Living Stages - three.ws">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@trythreews">
<meta name="twitter:title" content="Living Stages · three.ws" data-i18n-attr="content:stage.meta_twitter_title">
- <meta name="twitter:description" content="Live, embodied AI performances. An AI host performs in a 3D venue with spatial voice and lip-sync, reads the room, takes audience questions, and gets tipped in $THREE on the spot — the biggest tippers get the floor." data-i18n-attr="content:stage.meta_twitter_description">
+ <meta name="twitter:description" content="Live, embodied AI performances. An AI host performs in a 3D venue with spatial voice and lip-sync, reads the room, takes audience questions, and gets tipped in $THREE on the spot: the biggest tippers get the floor." data-i18n-attr="content:stage.meta_twitter_description">
<meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Living+Stages&amp;d=Live%2C+embodied+AI+performances.+An+AI+host+performs+in+a+3D+venue+with+spatial+voice+and+lip-sync%2C+reads+the+room%2C+takes+audience+questions%2C+and+gets+tipped+in&amp;p=%2Fstage">
- <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Living Stages","description":"Live, embodied AI performances. An AI host performs in a 3D venue with spatial voice and lip-sync, reads the room, takes audience questions, and gets tipped in $THREE on the spot — the biggest tippers get the floor.","url":"https://three.ws/stage","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=crypto&t=Living+Stages&d=Live%2C+embodied+AI+performances.+An+AI+host+performs+in+a+3D+venue+with+spatial+voice+and+lip-sync%2C+reads+the+room%2C+takes+audience+questions%2C+and+gets+tipped+in+&p=%2Fstage"}]}</script>
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Living Stages","description":"Live, embodied AI performances. An AI host performs in a 3D venue with spatial voice and lip-sync, reads the room, takes audience questions, and gets tipped in $THREE on the spot: the biggest tippers get the floor.","url":"https://three.ws/stage","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=crypto&t=Living+Stages&d=Live%2C+embodied+AI+performances.+An+AI+host+performs+in+a+3D+venue+with+spatial+voice+and+lip-sync%2C+reads+the+room%2C+takes+audience+questions%2C+and+gets+tipped+in+&p=%2Fstage"}]}</script>
</head>
<body>
<main id="stage-app" aria-live="polite"></main>
diff --git a/prompts/swarm-100/route-stage.md b/prompts/swarm-100/route-stage.md
deleted file mode 100644
index 2328f059e..000000000
--- a/prompts/swarm-100/route-stage.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# Route audit: /stage (Living Stages)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. This route's declared entry (path, description, added date):
-
- node -e "const p=require('./data/pages.json');for(const s of p.sections)for(const g of s.pages)if(g.path==='/stage')console.log(JSON.stringify(g,null,2))"
-
-2. Find the serving implementation: grep "/stage" in vercel.json (the live
- route table server/index.mjs boots from), then list matching files in
- pages/ and src/. STRUCTURE.md maps every surface to its directory if the
- grep is ambiguous.
-3. Production right now:
-
- curl -so /dev/null -w '%{http_code}\n' https://three.ws/stage
-
-4. Start (or reuse) the local dev server: npm run dev (vite, port 3000).
-
-## Task: audit this one route end to end, then fix everything found
-
-Route: /stage ("Living Stages", section "crypto").
-Declared purpose: Live, embodied AI performances. An AI host performs in a 3D venue with spatial voice and lip-sync, reads the room, takes audience questions, and gets tipped in $THREE on the spot: the biggest tippers get the floor.
-
-Drive the page in a real headless browser. Playwright is already a dev
-dependency; keep your probe script in the session scratchpad, never in the
-repo.
-
-1. Load http://localhost:3000/stage. Record the HTTP status, every console
- error and warning, and every failed network request.
-2. Exercise it like a first-time user: click the primary actions, run the
- primary flow if one exists, follow the page's internal links. Every button
- must do something real; every link must resolve. If the page renders data,
- prove in the network log that it came from a live endpoint, not a baked-in
- fallback array.
-3. States: verify populated, empty, loading, and error states are designed and
- reachable. Block the page's primary fetch in Playwright and confirm an
- actionable error state appears, not a blank void or a raw exception.
-4. Responsive: render at 320, 768, and 1440 px. No horizontal page scroll, no
- overlapping or clipped controls.
-5. Accessibility basics: one h1; interactive elements are real buttons or
- links with visible focus states; images carry alt text; form fields have
- labels.
-6. Head: a specific title tag and meta description that match the declared
- purpose above.
-7. Fix every defect at its root in the page's real source files and re-run the
- probe until clean. Defects in shared modules are in scope when this route
- exercises them.
-
-## Definition of done
-
-- [ ] Local load of /stage: HTTP 200, zero console errors, zero unhandled
- failed requests (a third-party outage must land in a designed fallback,
- not a broken page).
-- [ ] No dead interactive element on the page: no stub href="#", no button
- without a handler, no link to a missing path.
-- [ ] Empty, loading, error, and populated states verified.
-- [ ] 320 / 768 / 1440 px renders verified clean.
-- [ ] Title and meta description present and specific.
-- [ ] npm test passes; npm run check:rules -- --paths <touched files> exits 0.
-- [ ] Production status from step 0 recorded in the report; if production
- needs a deploy to pick up a fix, the report says so (deploys stay
- owner-gated).
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/route-stage.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/src/stage-net.js b/src/stage-net.js
index 9c2b13050..11e22b2b0 100644
--- a/src/stage-net.js
+++ b/src/stage-net.js
@@ -18,42 +18,33 @@
// honest "performance feed offline" state — captions/tips still work via polling.
import { Client, getStateCallbacks } from 'colyseus.js';
-import { StageState } from '../multiplayer/src/stage-schemas.js';
import { joinRoomWithTimeout } from './shared/colyseus-connect.js';
+import { defaultGameServerUrl } from './shared/game-server-url.js';
import { log } from './shared/log.js';
const ROOM_NAME = 'stage_world';
const MAX_RETRIES = 1;
-// Same resolution chain as irl-net: explicit override → meta → env → Codespaces
-// port forwarding → same-host:2567 in dev. '' in prod with none set ⇒ poll mode.
+// Resolution order: an explicit stage override (window.STAGE_SERVER_URL, the
+// stage-server meta, VITE_STAGE_SERVER_URL), then the shared game-server chain
+// every other realtime surface uses (src/shared/game-server-url.js): localhost
+// always talks to the local server, production reads the game-server meta baked
+// into the page, and '' with nothing configured means "stay offline" rather than
+// loop on a dead socket. Before this shared the chain, production resolved to ''
+// because /stage never carried its own meta, so every live show read "feed
+// offline" while the room kept performing to nobody.
function defaultServerUrl() {
- if (typeof window !== 'undefined') {
- if (window.STAGE_SERVER_URL) return String(window.STAGE_SERVER_URL).trim().replace(/\/$/, '');
- if (window.WALK_SERVER_URL) return String(window.WALK_SERVER_URL).trim().replace(/\/$/, '');
- }
+ const trim = (v) => String(v).trim().replace(/\/$/, '');
+ if (typeof window !== 'undefined' && window.STAGE_SERVER_URL) return trim(window.STAGE_SERVER_URL);
if (typeof document !== 'undefined') {
- for (const name of ['stage-server', 'walk-server']) {
- const v = document.querySelector(`meta[name="${name}"]`)?.getAttribute('content')?.trim();
- if (v) return v.replace(/\/$/, '');
- }
+ const v = document.querySelector('meta[name="stage-server"]')?.getAttribute('content')?.trim();
+ if (v) return trim(v);
}
try {
- const envUrl = import.meta?.env?.VITE_STAGE_SERVER_URL || import.meta?.env?.VITE_WALK_SERVER_URL;
- if (envUrl) return String(envUrl).trim().replace(/\/$/, '');
- } catch (_) {}
- if (typeof location !== 'undefined') {
- const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
- const host = location.hostname;
- const fwd = host.match(/^(.*)-(\d+)\.(app\.github\.dev|githubpreview\.dev|gitpod\.io)$/);
- if (fwd) return `${proto}//${fwd[1]}-2567.${fwd[3]}`;
- let isProd = false;
- try { isProd = import.meta?.env?.PROD === true; } catch (_) {}
- const isLocalHost = host === 'localhost' || host === '127.0.0.1';
- if (!isProd || isLocalHost) return `${proto}//${host}:2567`;
- return '';
- }
- return '';
+ const envUrl = import.meta?.env?.VITE_STAGE_SERVER_URL;
+ if (envUrl) return trim(envUrl);
+ } catch (_) { /* import.meta.env is absent outside the bundler */ }
+ return defaultGameServerUrl();
}
export class StageNet {
@@ -124,11 +115,14 @@ export class StageNet {
this._setStatus('connecting');
try {
this.client = new Client(this.url);
+ // No root-schema class passed on purpose: the client decodes state from
+ // the schema the server reflects during the handshake, so a field the
+ // deployed room adds never desyncs a bundle that predates it.
const room = await joinRoomWithTimeout(this.client, ROOM_NAME, {
stageId: this.stageId,
name: this.name,
avatar: this.avatar,
- }, StageState);
+ });
if (this._destroyed || gen !== this._connectGen) {
try { room.leave(); } catch {}
return;
@@ -137,35 +131,39 @@ export class StageNet {
this.sessionId = room.sessionId;
this._retries = 0;
- const $ = getStateCallbacks(this.room);
-
- // Host performance frame — emit the full host snapshot on any change.
- const $host = $(this.room.state)?.host;
- if ($host) {
- $host.onChange(() => this._emit('host', snapshotHost(this.room.state.host)));
- }
-
- // Audience — coalesce the join-time burst into one emit.
- const $aud = $(this.room.state)?.audience;
- if ($aud) {
- $aud.onAdd((m) => { $(m).onChange(() => this._queueAudience()); this._queueAudience(); });
- $aud.onRemove(() => this._queueAudience());
- }
-
- // Leaderboard — the synced top-tippers array.
- const $lb = $(this.room.state)?.leaderboard;
- if ($lb) {
- $lb.onAdd(() => this._emitLeaderboard());
- $lb.onRemove(() => this._emitLeaderboard());
- $lb.onChange?.(() => this._emitLeaderboard());
- }
-
- // Transient broadcasts.
+ // Message handlers first: the room opens the show the instant the first
+ // audience member joins, and that `utterance` lands before any state work
+ // below completes. A handler registered late drops the opening line.
this.room.onMessage('utterance', (msg) => this._emit('utterance', msg));
this.room.onMessage('tip', (msg) => this._emit('tip', msg));
this.room.onMessage('reaction', (msg) => this._emit('reaction', msg));
this.room.onMessage('question_ack', (msg) => this._emit('reaction', { ack: msg }));
+ const $ = getStateCallbacks(this.room);
+
+ // Host performance frame. The join resolves on JOIN_ROOM, before the first
+ // state patch, so `state.host` has no decoder ref yet and `onChange` on it
+ // throws ("Can't addCallback on 'REPLACE'"). `listen` on the root defers
+ // until the child lands and fires at once when it is already there, which
+ // also hands a late joiner the current caption.
+ $(this.room.state).listen('host', (host) => {
+ if (!host) return;
+ $(host).onChange(() => this._emit('host', snapshotHost(host)));
+ this._emit('host', snapshotHost(host));
+ });
+
+ // Audience: coalesce the join-time burst into one emit. Collection
+ // proxies defer on their own until the map is decoded.
+ const $aud = $(this.room.state).audience;
+ $aud.onAdd((m) => { $(m).onChange(() => this._queueAudience()); this._queueAudience(); });
+ $aud.onRemove(() => this._queueAudience());
+
+ // Leaderboard: the synced top-tippers array.
+ const $lb = $(this.room.state).leaderboard;
+ $lb.onAdd(() => this._emitLeaderboard());
+ $lb.onRemove(() => this._emitLeaderboard());
+ $lb.onChange(() => this._emitLeaderboard());
+
this.room.onLeave((code) => {
if (this._destroyed || code === 1000) return;
this._setStatus('offline');
@@ -173,8 +171,8 @@ export class StageNet {
});
this.room.onError((code, message) => log.warn('[stage-net] room.onError', code, message));
- // Initial full snapshots + a heartbeat so the reaper keeps us.
- this._emit('host', snapshotHost(this.room.state.host));
+ // Initial snapshots (a no-op until the first patch decodes the state) +
+ // a heartbeat so the reaper keeps us.
this._emitLeaderboard();
this._queueAudience();
// connection.isOpen catches the CLOSING/CLOSED window before onLeave
@@ -188,6 +186,9 @@ export class StageNet {
} catch (err) {
const reason = err?.message || (err?.code != null ? `code ${err.code}` : String(err));
log.warn('[stage-net] connect failed:', reason);
+ // A join that succeeded but failed to wire must not leave a live socket
+ // behind: the next attempt would double-deliver every broadcast.
+ this._closeRoom();
this._setStatus('failed', reason);
this._scheduleReconnect();
}
@@ -258,6 +259,7 @@ export class StageNet {
}
retry() {
+ if (this._destroyed || this.status === 'connecting' || this.status === 'online') return;
if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }
this._retries = 0;
this.connect();
diff --git a/src/stage.js b/src/stage.js
index c5881e22e..19e4798f3 100644
--- a/src/stage.js
+++ b/src/stage.js
@@ -62,7 +62,7 @@ async function bootDirectory() {
root.innerHTML = `
<header class="stage-dir-head">
<h1>Living Stages</h1>
- <p>Live, embodied AI performances. Show up, hear the host, tip in $THREE — the biggest tippers get the floor.</p>
+ <p>Live, embodied AI performances. Show up, hear the host, tip in $THREE: the biggest tippers get the floor.</p>
</header>
<div id="stage-dir" class="stage-dir" aria-live="polite">${skeletonCards(6)}</div>`;
const grid = document.getElementById('stage-dir');
@@ -81,8 +81,8 @@ async function bootDirectory() {
// Live first — the marquee.
grid.innerHTML = stages.map(stageCard).join('');
} catch (err) {
- grid.innerHTML = errorState('Could not load stages', () => bootDirectory());
- wireRetry(grid);
+ grid.innerHTML = errorState('Could not load stages');
+ wireRetry(grid, () => bootDirectory());
}
}
@@ -136,14 +136,27 @@ async function bootVenue(id) {
};
// Load stage config.
+ // Two different failures, two different answers: an id that resolves to
+ // nothing is a dead link (send them to the marquee), a request that never
+ // completed is a network blip (let them retry in place).
let detail;
try {
const res = await apiFetch(`/api/stage?id=${encodeURIComponent(id)}`, { allowAnonymous: true });
+ // 404 is an unknown stage, 400 is an id the API would never mint (a
+ // hand-edited or truncated link): both are dead links, not blips.
+ if (res.status === 404 || res.status === 400) {
+ els.stageWrap.innerHTML = emptyState(
+ 'Stage not found',
+ 'This stage does not exist or has been taken down. The live ones are on the marquee.',
+ '/stage', 'Browse live stages',
+ );
+ return;
+ }
if (!res.ok) throw new Error(`http ${res.status}`);
detail = await res.json();
} catch (err) {
- els.stageWrap.innerHTML = errorState('Stage not found', () => bootVenue(id));
- wireRetry(els.stageWrap);
+ els.stageWrap.innerHTML = errorState('Could not load this stage');
+ wireRetry(els.stageWrap, () => bootVenue(id));
return;
}
const stage = detail.stage;
@@ -208,16 +221,18 @@ class VenueController {
onNetStatus(status) {
const pill = this.els.netPill;
const map = {
- online: ['● live feed', 'ok'],
- connecting: ['connecting…', 'warn'],
- offline: ['reconnecting…', 'warn'],
- failed: ['feed offline', 'bad'],
- unavailable: ['feed offline', 'bad'],
- idle: ['…', 'warn'],
+ online: ['● live feed', 'ok', 'Live feed connected'],
+ connecting: ['connecting…', 'warn', 'Connecting to the live feed'],
+ offline: ['reconnecting…', 'warn', 'Reconnecting to the live feed'],
+ failed: ['feed offline · tap to retry', 'bad', 'Live feed offline. Tap to reconnect'],
+ unavailable: ['feed offline · tap to retry', 'bad', 'Live feed offline. Tap to reconnect'],
+ idle: ['…', 'warn', 'Live feed'],
};
- const [label, cls] = map[status] || ['…', 'warn'];
+ const [label, cls, aria] = map[status] || ['…', 'warn', 'Live feed'];
pill.textContent = label;
pill.className = `stage-net-pill ${cls}`;
+ pill.setAttribute('aria-label', aria);
+ pill.disabled = cls !== 'bad';
pill.hidden = false;
}
@@ -246,7 +261,7 @@ class VenueController {
}
onTip(t) {
- this.pushTicker(`${t.label} tipped ${fmtThree(t.amount)} $THREE${t.isNewTopTipper ? ' — new top tipper! 👑' : ''}`, 'tip', t.explorer);
+ this.pushTicker(`${t.label} tipped ${fmtThree(t.amount)} $THREE${t.isNewTopTipper ? ', now the top tipper 👑' : ''}`, 'tip', t.explorer);
if (this.three) this.three.burst(t.isNewTopTipper ? 'gold' : 'cheer');
}
@@ -259,7 +274,7 @@ class VenueController {
onReaction(r) {
if (r?.ack) {
- this.els.askStatus.textContent = r.ack.ok ? 'Queued — the host will get to it.' : 'Slow down a moment.';
+ this.els.askStatus.textContent = r.ack.ok ? 'Queued. The host will get to it.' : 'Slow down a moment.';
return;
}
if (this.three && r?.emoji) this.three.floatEmoji(r.id, REACTION_EMOJI[r.emoji] || '✨');
@@ -359,7 +374,7 @@ class VenueController {
} catch (err) {
const code = err instanceof TipError ? err.code : '';
if (code === 'cancelled') this.tipStatus('Tip cancelled.', 'warn');
- else this.tipStatus(err?.message || 'Tip failed — try again.', 'bad');
+ else this.tipStatus(err?.message || 'Tip failed. Try again.', 'bad');
} finally {
this.tipping = false;
this.els.tipSend.disabled = false;
@@ -387,7 +402,7 @@ class VenueController {
const text = this.els.askInput.value.trim();
if (!text) return;
const ok = this.net?.ask(text);
- this.els.askStatus.textContent = ok ? 'Sent — the host picks from the queue.' : 'Feed offline — try again in a moment.';
+ this.els.askStatus.textContent = ok ? 'Sent. The host picks from the queue.' : 'Live feed offline. Tap the feed pill to reconnect, then ask again.';
if (ok) this.els.askInput.value = '';
};
this.els.askBtn.addEventListener('click', ask);
@@ -417,7 +432,7 @@ class VenueController {
el.className = 'stage-phase';
if (phase === 'live') { el.classList.add('is-live'); el.innerHTML = '<span class="dot"></span> LIVE'; }
else if (phase === 'between') { el.textContent = nextShowLabel(this.stage.next_show_at) || 'Between shows'; }
- else if (phase === 'ended') { el.textContent = 'Show ended — highlights below'; }
+ else if (phase === 'ended') { el.textContent = 'Show ended. Highlights below'; }
else { el.textContent = this.stage.next_show_at ? nextShowLabel(this.stage.next_show_at) : 'Pre-show'; }
}
@@ -425,7 +440,7 @@ class VenueController {
this.renderLeaderboardRows(rows);
const total = show?.total_tips_atomic || 0;
const count = show?.tip_count || 0;
- this.els.total.textContent = total ? `${fmtThree(total)} $THREE · ${count} tips` : 'No tips yet — be the first';
+ this.els.total.textContent = total ? `${fmtThree(total)} $THREE · ${count} tips` : 'No tips yet. Be the first';
}
renderLeaderboardRows(rows) {
@@ -463,6 +478,8 @@ class VenueController {
this.voice.resume();
};
this.els.soundBtn.addEventListener('click', resume);
+ // The feed pill doubles as the reconnect control once the feed is down.
+ this.els.netPill.addEventListener('click', () => this.net?.retry());
this.els.closer?.addEventListener('click', () => this.three?.dolly(-1));
this.els.farther?.addEventListener('click', () => this.three?.dolly(1));
// First interaction anywhere resumes audio (browsers gate autoplay).
@@ -729,7 +746,7 @@ function venueShell() {
<div class="stage-3d-fallback" hidden>
<div class="stage-fallback-card">
<h2>Audio + captions mode</h2>
- <p>Your browser can't render the 3D venue, but the show goes on — you'll hear the host and read every line below, and you can still tip in $THREE.</p>
+ <p>Your browser can't render the 3D venue, but the show goes on: you'll hear the host and read every line below, and you can still tip in $THREE.</p>
</div>
</div>
<div id="stage-caption" class="stage-caption" hidden><span class="cap-text"></span></div>
@@ -739,14 +756,14 @@ function venueShell() {
<h1 id="stage-title">Live stage</h1>
<p class="stage-host">with <span id="stage-host-name">the host</span> · <span id="stage-aud-count">0 here</span></p>
</div>
- <span id="stage-net-pill" class="stage-net-pill warn" hidden>…</span>
+ <button id="stage-net-pill" type="button" class="stage-net-pill warn" aria-label="Live feed" hidden>…</button>
</div>
<div class="stage-overlay-bottom">
- <button id="stage-sound" class="stage-sound" hidden>🔊 Tap for sound</button>
+ <button id="stage-sound" type="button" class="stage-sound" hidden>🔊 Tap for sound</button>
<div class="stage-dolly">
- <button id="stage-farther" aria-label="Step back">−</button>
+ <button id="stage-farther" type="button" aria-label="Step back">−</button>
<span>proximity</span>
- <button id="stage-closer" aria-label="Step closer">+</button>
+ <button id="stage-closer" type="button" aria-label="Step closer">+</button>
</div>
</div>
<div id="stage-ticker" class="stage-ticker" aria-live="polite"></div>
@@ -759,7 +776,7 @@ function venueShell() {
<div id="stage-tip-presets" class="stage-tip-presets"></div>
<div class="stage-tip-row">
<input id="stage-tip-custom" type="number" min="1" step="1" placeholder="Custom" inputmode="numeric" aria-label="Custom tip amount" />
- <button id="stage-tip-send" class="stage-tip-send">Tip</button>
+ <button id="stage-tip-send" type="button" class="stage-tip-send">Tip</button>
</div>
<input id="stage-tip-msg" class="stage-tip-msg" maxlength="140" placeholder="Add a message (optional)" aria-label="Tip message" />
<p id="stage-tip-status" class="stage-tip-status" aria-live="polite"></p>
@@ -772,7 +789,7 @@ function venueShell() {
<h2>Ask the host</h2>
<div class="stage-ask-row">
<input id="stage-ask-input" maxlength="240" placeholder="Type a question…" aria-label="Ask the host a question" />
- <button id="stage-ask-btn">Ask</button>
+ <button id="stage-ask-btn" type="button">Ask</button>
</div>
<p id="stage-ask-status" class="stage-ask-status" aria-live="polite"></p>
</section>
@@ -826,10 +843,12 @@ function emptyState(title, body, href, cta) {
return `<div class="stage-empty"><h2>${esc(title)}</h2><p>${esc(body)}</p>${href ? `<a class="stage-cta" href="${href}">${esc(cta)}</a>` : ''}</div>`;
}
-function errorState(title, _retry) {
- return `<div class="stage-empty stage-error"><h2>${esc(title)}</h2><p>Something went wrong loading this. Check your connection and try again.</p><button class="stage-cta" data-retry>Try again</button></div>`;
+function errorState(title) {
+ return `<div class="stage-empty stage-error"><h2>${esc(title)}</h2><p>Something went wrong loading this. Check your connection and try again.</p><button type="button" class="stage-cta" data-retry>Try again</button></div>`;
}
-function wireRetry(container) {
- container.querySelector('[data-retry]')?.addEventListener('click', () => location.reload());
+// Retry in place: re-run the loader that failed instead of reloading the whole
+// page, so a venue keeps its 3D context and the directory keeps its scroll.
+function wireRetry(container, retry) {
+ container.querySelector('[data-retry]')?.addEventListener('click', retry);
}
diff --git a/tests/multiplayer-server-boot.test.js b/tests/multiplayer-server-boot.test.js
index 0fdb81eba..e38e859cc 100644
--- a/tests/multiplayer-server-boot.test.js
+++ b/tests/multiplayer-server-boot.test.js
@@ -127,6 +127,10 @@ beforeAll(async () => {
HOST: '127.0.0.1',
NODE_ENV: 'development',
MULTIPLAYER_SHARED_SECRET: SECRET,
+ // StageRoom pulls its show config and the host's words from the three.ws
+ // API. Point it at this server so the suite never reaches production:
+ // every call 404s here, which exercises the room's own fallbacks.
+ THREEWS_API_BASE: `http://127.0.0.1:${port}`,
// Never let a developer's real Redis/Upstash creds leak a test room's
// state into shared storage: this suite runs memory-only by construction.
UPSTASH_REDIS_REST_URL: '',
@@ -212,6 +216,47 @@ describe('multiplayer entry point', () => {
}
});
+ it('serves a real stage_world join wired the way /stage wires it', async () => {
+ const { Client, getStateCallbacks } = await import('colyseus.js');
+ const client = new Client(`ws://127.0.0.1:${port}`);
+ // No root-schema class, like src/stage-net.js: state decodes from the
+ // schema the server reflects during the handshake.
+ const room = await client.joinOrCreate('stage_world', { stageId: 'boot-suite-stage', name: 'BootSuite' });
+ try {
+ // The first arrival opens the show and that `utterance` lands right after
+ // JOIN_ROOM, so the handler has to exist before any state work.
+ const utterances = [];
+ room.onMessage('utterance', (m) => utterances.push(m));
+
+ // The join resolves before the first state patch, so `state.host` has no
+ // decoder ref yet and `onChange` on it throws. `listen` on the root is the
+ // contract the browser client relies on: it defers until the host lands.
+ const $ = getStateCallbacks(room);
+ const host = await new Promise((resolve) => {
+ $(room.state).listen('host', (h) => { if (h) resolve(h); });
+ });
+ expect(host.name, 'config 404s here, so the room falls back to a generic host').toBe('The Host');
+
+ await new Promise((resolve) => {
+ $(room.state).audience.onAdd((_m, key) => { if (key === room.sessionId) resolve(); });
+ });
+ const me = room.state.audience.get(room.sessionId);
+ expect(me.name).toBe('BootSuite');
+ expect(Math.hypot(me.x, me.z), 'the server seats each arrival on the ring').toBeGreaterThan(0);
+
+ // The brain 404s here too; the room performs its fallback line rather
+ // than going silent, and the caption in synced state matches the broadcast.
+ const deadline = Date.now() + 10_000;
+ while (!utterances.length && Date.now() < deadline) await sleep(100);
+ expect(utterances.length, 'the opening beat reached a handler registered before state wiring').toBeGreaterThan(0);
+ expect(utterances[0].text).toBeTruthy();
+ expect(room.state.host.caption).toBe(utterances[0].text);
+ expect(room.state.phase).toBe('live');
+ } finally {
+ await room.leave();
+ }
+ });
+
it('refuses an unsigned or forged internal webhook', async () => {
const post = (body, headers = {}) => fetch(`${base}/internal/notify`, {
method: 'POST',