Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add walk voice chat, frames and share endpoints, and marketplace gallery
nirholasa5f8ea0a3963
diff --git a/api/frames/walk.js b/api/frames/walk.jsnew file mode 100644index 000000000..a1981a464--- /dev/null+++ b/api/frames/walk.js@@ -0,0 +1,137 @@+/**+ * Farcaster Frame for a Walk capture+ * ----------------------------------+ * GET /api/frames/walk?avatar=<id>&handle=<handle>+ *+ * Returns an HTML document carrying both the Farcaster Frames v2 (`fc:frame`,+ * version "next") embed and the legacy v1 frame meta, plus Open Graph + Twitter+ * Card tags. Cast this URL in Warpcast and it renders a rich card whose button+ * launches the live /walk experience for that avatar.+ *+ * The frame image reuses the platform's existing 1.91:1 Walk OG card+ * (/api/walk-og) — the same card agent-share frames use — so there is one+ * source of truth for the social artwork.+ */++import { getAvatar } from '../_lib/avatars.js';+import { cors, wrap, text } from '../_lib/http.js';+import { env } from '../_lib/env.js';++const CACHE = 'public, max-age=300, s-maxage=3600';++function esc(s) {+ return String(s).replace(+ /[<>&"']/g,+ (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' })[c],+ );+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;++ const origin = env.APP_ORIGIN || 'https://three.ws';+ const url = new URL(req.url, origin);+ const avatarId = (url.searchParams.get('avatar') || '').trim().slice(0, 64);+ let handle = (url.searchParams.get('handle') || '').trim().slice(0, 40);++ let avatarName = '';+ if (avatarId) {+ try {+ const avatar = await getAvatar({ id: avatarId });+ if (avatar?.name) avatarName = String(avatar.name).slice(0, 48);+ } catch {+ // degrade to generic copy+ }+ }++ const ogParams = new URLSearchParams();+ if (avatarId) ogParams.set('avatar', avatarId);+ if (handle) ogParams.set('handle', handle);+ const imageUrl = `${origin}/api/walk-og${ogParams.toString() ? `?${ogParams}` : ''}`;++ const walkUrl = avatarId+ ? `${origin}/walk?avatar=${encodeURIComponent(avatarId)}`+ : `${origin}/walk`;++ const title = avatarName+ ? `Walk ${avatarName} on three.ws`+ : handle+ ? `Walk @${handle}'s avatar on three.ws`+ : 'Walk your avatar on three.ws';+ const description = 'A third-person stroll for your 3D agent. Tap to walk yours.';++ // Frames v2 embed — single JSON meta. Button launches the live /walk app.+ const frameV2 = {+ version: 'next',+ imageUrl,+ button: {+ title: 'Walk this avatar',+ action: {+ type: 'launch_frame',+ name: 'three.ws Walk',+ url: walkUrl,+ splashImageUrl: `${origin}/icon-512.png`,+ splashBackgroundColor: '#0a0a0a',+ },+ },+ };++ const html = `<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>${esc(title)}</title>+ <meta name="description" content="${esc(description)}">++ <meta property="og:type" content="website">+ <meta property="og:title" content="${esc(title)}">+ <meta property="og:description" content="${esc(description)}">+ <meta property="og:image" content="${esc(imageUrl)}">+ <meta property="og:url" content="${esc(walkUrl)}">++ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="${esc(title)}">+ <meta name="twitter:description" content="${esc(description)}">+ <meta name="twitter:image" content="${esc(imageUrl)}">++ <!-- Farcaster Frames v2 -->+ <meta name="fc:frame" content="${esc(JSON.stringify(frameV2))}">++ <!-- Farcaster Frames v1 (legacy clients) -->+ <meta property="fc:frame" content="vNext">+ <meta property="fc:frame:image" content="${esc(imageUrl)}">+ <meta property="fc:frame:image:aspect_ratio" content="1.91:1">+ <meta property="fc:frame:button:1" content="Walk this avatar →">+ <meta property="fc:frame:button:1:action" content="link">+ <meta property="fc:frame:button:1:target" content="${esc(walkUrl)}">+ <meta property="fc:frame:button:2" content="Make your own">+ <meta property="fc:frame:button:2:action" content="link">+ <meta property="fc:frame:button:2:target" content="${esc(origin)}/walk">++ <link rel="canonical" href="${esc(walkUrl)}">+ <style>+ html,body{margin:0;height:100%;background:#0a0a0a;color:#fff;font-family:system-ui,-apple-system,sans-serif}+ .wrap{height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;text-align:center;padding:24px}+ img{max-width:min(560px,92vw);width:100%;border-radius:16px;border:1px solid rgba(255,255,255,0.1)}+ a.cta{display:inline-block;background:#7c5cff;color:#fff;text-decoration:none;font-weight:600;padding:12px 22px;border-radius:999px}+ p{color:rgba(255,255,255,0.6);font-size:14px;margin:0}+ </style>+</head>+<body>+ <div class="wrap">+ <img src="${esc(imageUrl)}" alt="${esc(title)}">+ <a class="cta" href="${esc(walkUrl)}">Walk this avatar →</a>+ <p>${esc(description)}</p>+ </div>+ <script>+ // Real browsers (not social crawlers) go straight to the live experience.+ if (!/bot|crawler|spider|facebookexternalhit|warpcast|farcaster|twitterbot|slackbot|discordbot/i.test(navigator.userAgent)) {+ location.replace(${JSON.stringify(walkUrl)});+ }+ </script>+</body>+</html>`;++ text(res, 200, html, { 'content-type': 'text/html; charset=utf-8', 'cache-control': CACHE });+});diff --git a/api/share/x.js b/api/share/x.jsnew file mode 100644index 000000000..46f4c29dc--- /dev/null+++ b/api/share/x.js@@ -0,0 +1,113 @@+/**+ * Share a Walk capture to X+ * --------------------------+ * POST /api/share/x?avatar=<id>&text=<optional caption>+ *+ * Body: the raw media bytes (image/png for a screenshot, video/mp4 for a clip).+ * The Content-Type header carries the media type. Authenticated with the+ * caller's three.ws session; the post is published through their connected X+ * account using the real X API v2 (media chunked-upload → create tweet with the+ * media attached). See api/_lib/x-post.js for the upload + publish plumbing.+ *+ * No connected X account → 409 not_connected with a connect_url the client can+ * route the user to (/api/auth/x/connect). The OAuth scope requested there+ * includes media.write so the upload is authorized.+ */++import { cors, method, wrap, error, json, readBody } from '../_lib/http.js';+import { getSessionUser, isSameSiteOrigin } from '../_lib/auth.js';+import { env } from '../_lib/env.js';+import { publishTweet, XPostError, MAX_TWEET_LEN } from '../_lib/x-post.js';++// X media ceilings we enforce up front so an oversized body fails fast with a+// clear message instead of deep inside the chunked upload.+const MAX_IMAGE_BYTES = 5 * 1024 * 1024; // 5 MB (X still image limit)+const MAX_VIDEO_BYTES = 64 * 1024 * 1024; // 64 MB — generous for a ≤10s 1080p clip+const ALLOWED = {+ 'image/png': { kind: 'image', max: MAX_IMAGE_BYTES },+ 'image/jpeg': { kind: 'image', max: MAX_IMAGE_BYTES },+ 'image/gif': { kind: 'image', max: MAX_IMAGE_BYTES },+ 'video/mp4': { kind: 'video', max: MAX_VIDEO_BYTES },+};++// Dev convenience: the vite dev server runs on localhost, so allow it past the+// same-site CSRF guard outside production (mirrors the CORS allowlist policy).+function isTrustedOrigin(req) {+ if (isSameSiteOrigin(req)) return true;+ if (process.env.NODE_ENV === 'production') return false;+ const origin = req.headers.origin || '';+ return /^https?:\/\/localhost(:\d+)?$/.test(origin);+}++function captionFor(avatarId, override) {+ if (override) return override.slice(0, MAX_TWEET_LEN);+ const url = avatarId+ ? `three.ws/walk?avatar=${avatarId}`+ : 'three.ws/walk';+ return `I walked my avatar around three.ws — try yours: ${url}`;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ if (!isTrustedOrigin(req)) {+ return error(res, 403, 'forbidden', 'cross-site request rejected');+ }++ const user = await getSessionUser(req, res);+ if (!user) {+ return json(res, 401, {+ error: 'auth_required',+ error_description: 'sign in to three.ws to share to X',+ login_url: '/login',+ });+ }++ const contentType = (req.headers['content-type'] || '').split(';')[0].trim().toLowerCase();+ const spec = ALLOWED[contentType];+ if (!spec) {+ return error(res, 415, 'unsupported_media_type', 'body must be image/png, image/jpeg, image/gif or video/mp4');+ }++ let buffer;+ try {+ buffer = await readBody(req, spec.max);+ } catch (err) {+ if (err?.status === 413) {+ const mb = Math.round(spec.max / (1024 * 1024));+ return error(res, 413, 'too_large', `${spec.kind} exceeds the ${mb} MB limit`);+ }+ throw err;+ }+ if (!buffer || buffer.length === 0) {+ return error(res, 400, 'empty_body', 'no media in request body');+ }++ const url = new URL(req.url, env.APP_ORIGIN);+ const avatarId = (url.searchParams.get('avatar') || '').trim().slice(0, 64);+ const text = captionFor(avatarId, (url.searchParams.get('text') || '').trim());++ try {+ const result = await publishTweet({+ userId: user.id,+ text,+ mediaBuffer: buffer,+ mediaMimeType: contentType,+ });+ return json(res, 200, { ok: true, ...result });+ } catch (err) {+ if (err instanceof XPostError) {+ const extra = { ...err.extra };+ if (err.code === 'not_connected') {+ extra.connect_url = '/api/auth/x/connect';+ }+ return json(res, err.code === 'not_connected' ? 409 : err.status, {+ error: err.code,+ error_description: err.message,+ ...extra,+ });+ }+ throw err;+ }+});diff --git a/pages/avatar-edit.html b/pages/avatar-edit.htmlindex 02da49581..89cbd9c18 100644--- a/pages/avatar-edit.html+++ b/pages/avatar-edit.html@@ -716,6 +716,53 @@.ae-rig-bar { width: 100%; height: 6px; border-radius: 999px; background: var(--panel-2); overflow: hidden; }.ae-rig-bar-fill { height: 100%; background: var(--text); border-radius: 999px; transition: width 0.4s ease; }.ae-rig-done { display: flex; flex-direction: column; gap: 14px; padding: 8px 2px; }++ /* ── Walk preview panel ─────────────────────────────────── */+ .ae-walk { display: flex; flex-direction: column; gap: 16px; padding: 4px 2px; }+ .ae-walk-lede { margin: 0; font-size: 13px; line-height: 1.6; color: var(--text-2); }+ .ae-walk-lede kbd {+ display: inline-block;+ min-width: 18px;+ padding: 1px 5px;+ margin: 0 1px;+ font-family: ui-monospace, 'SF Mono', monospace;+ font-size: 11px;+ text-align: center;+ color: var(--text);+ background: var(--panel-2);+ border: 1px solid var(--border-2);+ border-bottom-width: 2px;+ border-radius: 5px;+ }+ .ae-walk-field { display: flex; flex-direction: column; gap: 6px; }+ .ae-walk-field-label {+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.07em;+ color: var(--text-3);+ }+ .ae-walk-select {+ width: 100%;+ background: var(--panel-2);+ border: 1px solid var(--border-2);+ border-radius: 8px;+ color: var(--text);+ padding: 9px 12px;+ font-size: 13px;+ font-family: inherit;+ outline: none;+ cursor: pointer;+ transition: border-color 0.15s;+ }+ .ae-walk-select:focus { border-color: var(--accent); }+ .ae-walk-open { align-self: flex-start; }+ .ae-walk-note {+ margin: 0;+ font-size: 12px;+ line-height: 1.5;+ color: var(--text-3);+ min-height: 16px;+ }</style></head><body>diff --git a/pages/irl.html b/pages/irl.htmlindex a3471b97e..d92d5c165 100644--- a/pages/irl.html+++ b/pages/irl.html@@ -1207,6 +1207,74 @@#irl-caption-cancel { width: 44px; height: 44px; padding: 0; border-radius: 12px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.06); color: #9ca3af; font: 600 18px inherit; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: background 0.15s; }#irl-caption-cancel:hover { background: rgba(255,255,255,0.12); color: #e5e7eb; }+ /* Placement chip (H4) — how this pin will be stored; taps re-open the consent sheet */+ .irl-caption-placement {+ display: flex; align-items: center; justify-content: space-between; gap: 10px;+ width: 100%; margin: 0 0 12px; padding: 9px 12px;+ background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.12);+ border-radius: 11px; color: #cbd5e1; font: 600 13px inherit; cursor: pointer;+ transition: border-color 0.15s, background 0.15s;+ }+ .irl-caption-placement:hover { background: rgba(255,255,255,0.07); border-color: rgba(255,255,255,0.2); }+ .irl-caption-placement:focus-visible { outline: 2px solid rgba(96,165,250,0.6); outline-offset: 2px; }+ .irl-caption-placement.is-approx { border-color: rgba(96,165,250,0.4); background: rgba(96,165,250,0.1); color: #93c5fd; }+ .irl-caption-place-badge { font-variant-numeric: tabular-nums; }+ .irl-caption-place-i { font-size: 12px; color: #8a94a6; white-space: nowrap; }+ .irl-caption-placement.is-approx .irl-caption-place-i { color: #93c5fd; }++ /* Placement consent sheet (H4) — equal-weight choice + safer "approximate" default */+ #irl-consent-sheet {+ position: fixed; bottom: 0; left: 0; right: 0; z-index: 23;+ background: rgba(12,14,20,0.97);+ border-top: 1px solid rgba(255,255,255,0.12);+ border-radius: 18px 18px 0 0;+ padding: 20px 22px 32px;+ backdrop-filter: blur(22px); -webkit-backdrop-filter: blur(22px);+ transform: translateY(100%);+ transition: transform 0.28s cubic-bezier(0.32,0.72,0,1);+ pointer-events: none;+ max-height: 90vh; overflow-y: auto;+ }+ #irl-consent-sheet.is-open { transform: translateY(0); pointer-events: all; }+ #irl-consent-sheet .irl-sheet-handle { margin-bottom: 14px; }+ #irl-consent-sheet h3 { font-size: 16px; font-weight: 700; color: #e5e7eb; margin: 0 0 8px; }+ #irl-consent-body { font-size: 13.5px; line-height: 1.55; color: var(--text-2, #9ca3af); margin: 0 0 16px; }+ .irl-consent-radius { border: 0; padding: 0; margin: 0 0 14px; }+ .irl-consent-radius legend { font-size: 12px; color: #8a94a6; padding: 0; margin: 0 0 8px; }+ .irl-consent-seg { display: flex; gap: 8px; }+ .irl-consent-seg button {+ flex: 1; display: flex; flex-direction: column; align-items: center; gap: 2px;+ padding: 9px 6px; border-radius: 11px;+ border: 1px solid rgba(255,255,255,0.13); background: rgba(255,255,255,0.04);+ color: #cbd5e1; font: 600 13px inherit; cursor: pointer;+ transition: border-color 0.15s, background 0.15s, color 0.15s;+ }+ .irl-consent-seg button small { font-size: 10.5px; font-weight: 500; color: #8a94a6; }+ .irl-consent-seg button:hover { background: rgba(255,255,255,0.07); }+ .irl-consent-seg button.on { border-color: rgba(96,165,250,0.5); background: rgba(96,165,250,0.16); color: #93c5fd; }+ .irl-consent-seg button.on small { color: #93c5fd; }+ .irl-consent-seg button:focus-visible { outline: 2px solid rgba(96,165,250,0.6); outline-offset: 2px; }+ .irl-consent-actions { display: flex; gap: 10px; margin-bottom: 14px; }+ .irl-consent-btn {+ flex: 1; padding: 13px 14px; border-radius: 12px; cursor: pointer;+ font: 600 14px inherit; transition: background 0.15s, border-color 0.15s;+ border: 1px solid rgba(52,211,153,0.4); background: rgba(52,211,153,0.16); color: #34d399;+ }+ .irl-consent-btn:hover { background: rgba(52,211,153,0.26); }+ .irl-consent-btn:active { transform: scale(0.98); }+ .irl-consent-btn:focus-visible { outline: 2px solid rgba(52,211,153,0.6); outline-offset: 2px; }+ /* "Approximately" is styled identically to "exactly" — equal weight, no dark pattern */+ #irl-consent-approx { border-color: rgba(96,165,250,0.4); background: rgba(96,165,250,0.16); color: #93c5fd; }+ #irl-consent-approx:hover { background: rgba(96,165,250,0.26); }+ .irl-consent-dontshow { display: flex; align-items: center; gap: 8px; font-size: 13px; color: #9ca3af; cursor: pointer; margin-bottom: 14px; }+ .irl-consent-dontshow input { width: 16px; height: 16px; accent-color: #60a5fa; cursor: pointer; }+ .irl-consent-cancel {+ display: block; width: 100%; padding: 11px; border-radius: 12px;+ border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.05);+ color: #9ca3af; font: 600 13.5px inherit; cursor: pointer; transition: background 0.15s;+ }+ .irl-consent-cancel:hover { background: rgba(255,255,255,0.1); color: #e5e7eb; }+/* Designed guidance sheet — motion permission, GPS-not-ready, etc. (A4) */#irl-error-sheet {position: fixed;@@ -2172,6 +2240,12 @@<div id="irl-caption-panel" role="dialog" aria-modal="true" aria-labelledby="irl-caption-title"><div class="irl-sheet-handle" aria-hidden="true"></div><h3 id="irl-caption-title">Pin your agent here</h3>+ <!-- Placement chip (H4) — shows how this pin will be stored (exact vs approximate)+ and re-opens the consent sheet to change it. -->+ <button id="irl-caption-placement" class="irl-caption-placement" type="button">+ <span class="irl-caption-place-badge">📍 Exact</span>+ <span class="irl-caption-place-i" aria-hidden="true">Change ⓘ</span>+ </button><textarea id="irl-caption-input" rows="3" placeholder="Add a caption… e.g. 'P2P trades here — DM me on Telegram' (optional)"></textarea><div class="irl-caption-row"><button id="irl-caption-confirm" type="button">Pin it</button>@@ -2179,6 +2253,29 @@</div></div>+<!-- Placement consent sheet (H4) — disclose what placing means + offer approximate.+ Both choices are equally weighted; "don't show every time" suppresses the sheet+ on later placements while keeping the remembered choice. -->+<div id="irl-consent-sheet" role="dialog" aria-modal="true" aria-labelledby="irl-consent-title" aria-describedby="irl-consent-body">+ <div class="irl-sheet-handle" aria-hidden="true"></div>+ <h3 id="irl-consent-title">Heads up — this is a real-world spot</h3>+ <p id="irl-consent-body">Your agent will be visible to anyone who physically walks within ~40 m of here. We never show a list or map of locations, and we never reveal who placed it — but the spot itself is public. Want to place it exactly here, or approximately?</p>+ <fieldset class="irl-consent-radius">+ <legend>If approximate, blur within</legend>+ <div class="irl-consent-seg" role="group" aria-label="Approximate blur radius">+ <button type="button" data-fuzz="30" aria-pressed="false">~30 m<small>same block</small></button>+ <button type="button" data-fuzz="100" class="on" aria-pressed="true">~100 m<small>this street</small></button>+ <button type="button" data-fuzz="250" aria-pressed="false">~250 m<small>nearby</small></button>+ </div>+ </fieldset>+ <div class="irl-consent-actions">+ <button id="irl-consent-exact" type="button" class="irl-consent-btn">Place exactly here</button>+ <button id="irl-consent-approx" type="button" class="irl-consent-btn">Place approximately</button>+ </div>+ <label class="irl-consent-dontshow"><input type="checkbox" id="irl-consent-dontshow" /> Don’t show this every time</label>+ <button id="irl-consent-cancel" type="button" class="irl-consent-cancel">Cancel</button>+</div>+<!-- Designed guidance sheet — recoverable motion/GPS permission states (A4) --><div id="irl-error-sheet" role="dialog" aria-modal="true" aria-labelledby="irl-error-title"><div class="irl-sheet-handle" aria-hidden="true"></div>@@ -2241,6 +2338,8 @@</div><!-- Honest GPS-accuracy line (A3) — never imply a centimetre-perfect pinpoint --><p id="irl-sheet-accuracy" class="irl-sheet-accuracy" hidden></p>+ <!-- Placement exposure badge (H4) — owner-only: exact spot vs deliberately blurred -->+ <p id="irl-sheet-placement" class="irl-sheet-placement" hidden></p><div class="irl-sheet-actions"><button id="irl-sheet-pay" class="irl-sheet-btn irl-sheet-btn-primary" type="button" hidden>Pay via x402</button><button id="irl-sheet-calibrate" class="irl-sheet-btn" type="button" hidden>Calibrate position</button>@@ -2342,6 +2441,9 @@/* Honest accuracy line inside the inspect sheet (A3). */.irl-sheet-accuracy { margin: 0 0 12px; font-size: 12px; line-height: 1.5; color: #8a94a6; }.irl-sheet-accuracy.is-low { color: #fbbf73; }+ /* Placement exposure badge (H4) — owner-only line in the inspect sheet */+ .irl-sheet-placement { margin: 0 0 12px; font-size: 12px; line-height: 1.5; color: #6ee7b7; }+ .irl-sheet-placement.is-approx { color: #93c5fd; }/* Room align (R2) reuses the calibrate panel; a whole-room slide/twist has noper-agent floor-height step, so hide it and show the room-scale hint instead. */body.is-room-cal #irl-calibrate-panel .irl-cal-height { display: none; }diff --git a/pages/temporary.html b/pages/temporary.htmlindex cc19650e9..005a154e8 100644--- a/pages/temporary.html+++ b/pages/temporary.html@@ -985,6 +985,152 @@.walk-chat-messages { max-height: 120px; }}+ /* ── Voice chat: push-to-talk mic ───────────────────────────────+ Bottom-center column so it clears the chat box (left) and the+ look joystick / action buttons (right). The mic is the anchor; the+ waveform, status, and any error stack above it. */+ .walk-voice {+ position: fixed;+ left: 50%;+ bottom: calc(28px + env(safe-area-inset-bottom, 0));+ transform: translateX(-50%);+ z-index: 4;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 8px;+ pointer-events: none;+ }+ .walk-voice > * { pointer-events: auto; }+ .walk-voice-status {+ font-size: 12px;+ color: var(--text-2);+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 999px;+ padding: 3px 12px;+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ transition: color 0.2s ease, opacity 0.2s ease;+ }+ .walk-voice[data-state="listening"] .walk-voice-status { color: var(--text); }+ .walk-voice[data-state="thinking"] .walk-voice-status,+ .walk-voice[data-state="transcribing"] .walk-voice-status,+ .walk-voice[data-state="speaking"] .walk-voice-status { color: var(--accent); }+ .walk-voice-wave {+ width: 120px;+ height: 28px;+ opacity: 0;+ transform: scaleY(0.6);+ transition: opacity 0.2s ease, transform 0.2s ease;+ }+ .walk-voice[data-state="listening"] .walk-voice-wave {+ opacity: 1;+ transform: scaleY(1);+ }+ .walk-voice-mic {+ position: relative;+ width: 64px;+ height: 64px;+ border-radius: 50%;+ border: 1px solid var(--border);+ background: var(--panel);+ color: var(--text);+ display: grid;+ place-items: center;+ cursor: pointer;+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ touch-action: none;+ -webkit-user-select: none;+ user-select: none;+ transition: transform 0.12s ease, background 0.2s ease, border-color 0.2s ease, color 0.2s ease;+ }+ .walk-voice-mic:hover { background: color-mix(in srgb, var(--accent) 12%, var(--panel)); }+ .walk-voice-mic:active { transform: scale(0.94); }+ .walk-voice-mic.is-recording {+ background: var(--danger);+ border-color: var(--danger);+ color: #fff;+ }+ .walk-voice-mic.is-busy {+ color: var(--accent);+ cursor: progress;+ }+ .walk-voice-mic:disabled {+ opacity: 0.45;+ cursor: not-allowed;+ }+ /* Pulsing ring while recording. */+ .walk-voice-ring {+ position: absolute;+ inset: -4px;+ border-radius: 50%;+ border: 2px solid var(--danger);+ opacity: 0;+ pointer-events: none;+ }+ .walk-voice-mic.is-recording .walk-voice-ring {+ animation: walk-voice-pulse 1.4s ease-out infinite;+ }+ @keyframes walk-voice-pulse {+ 0% { opacity: 0.7; transform: scale(1); }+ 100% { opacity: 0; transform: scale(1.45); }+ }+ .walk-voice-key {+ font-size: 11px;+ color: var(--text-2);+ display: inline-flex;+ align-items: center;+ gap: 4px;+ }+ .walk-voice-key kbd {+ font: inherit;+ background: rgba(255,255,255,0.08);+ border: 1px solid var(--border);+ border-radius: 4px;+ padding: 0 5px;+ color: var(--text);+ }+ .walk-voice-error {+ max-width: min(320px, calc(100vw - 32px));+ font-size: 12px;+ line-height: 1.4;+ color: var(--text);+ background: var(--panel);+ border: 1px solid rgba(248, 113, 113, 0.5);+ border-radius: 12px;+ padding: 8px 12px;+ display: flex;+ flex-direction: column;+ gap: 8px;+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ text-align: center;+ }+ .walk-voice-retry {+ align-self: center;+ font: inherit;+ font-size: 11px;+ color: var(--text);+ background: rgba(255,255,255,0.08);+ border: 1px solid var(--border);+ border-radius: 8px;+ padding: 4px 14px;+ cursor: pointer;+ transition: background 0.2s ease;+ }+ .walk-voice-retry:hover { background: rgba(255,255,255,0.14); }+ /* Touch devices have no T key — promote the key hint to hidden and+ rely on the large mic button, which is already touch-sized. */+ @media (hover: none) {+ .walk-voice-key { display: none; }+ .walk-voice { bottom: calc(96px + env(safe-area-inset-bottom, 0)); }+ }+ @media (prefers-reduced-motion: reduce) {+ .walk-voice-mic.is-recording .walk-voice-ring { animation: none; opacity: 0.5; }+ }+/* ── Chat bubble above remote players ───────────────────────────── */.walk-remote-bubble {position: fixed;@@ -1028,6 +1174,8 @@.walk-emote-btn:focus-visible,.walk-avatar-opt:focus-visible,.walk-chat-send:focus-visible,+ .walk-voice-mic:focus-visible,+ .walk-voice-retry:focus-visible,#walk-online:focus-visible,#walk-zen-exit:focus-visible,.walk-players-header button:focus-visible,@@ -1078,6 +1226,7 @@body.is-zen #walk-help,body.is-zen #walk-status,body.is-zen #walk-chat,+ body.is-zen #walk-voice,body.is-zen #walk-emote-tray,body.is-zen #walk-players-panel,body.is-zen #walk-avatar-picker,@@ -1238,6 +1387,23 @@</form></div>+ <!-- Voice chat: push-to-talk with the avatar (mic → STT → LLM → TTS) -->+ <div id="walk-voice" class="walk-voice" data-state="idle">+ <div class="walk-voice-error" data-voice-error hidden role="alert"></div>+ <div class="walk-voice-status" data-voice-status aria-live="polite">Hold to talk</div>+ <canvas class="walk-voice-wave" data-voice-wave width="120" height="28" aria-hidden="true"></canvas>+ <button type="button" class="walk-voice-mic" data-voice-mic+ aria-pressed="false" aria-label="Hold to talk to your avatar (T)" title="Hold to talk (T)">+ <span class="walk-voice-ring" aria-hidden="true"></span>+ <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <rect x="9" y="2" width="6" height="11" rx="3"/>+ <path d="M5 10v1a7 7 0 0 0 14 0v-1"/>+ <path d="M12 18v3"/>+ </svg>+ </button>+ <span class="walk-voice-key" aria-hidden="true">Hold <kbd>T</kbd></span>+ </div>+<!-- Friends panel (Task 15) --><div id="walk-friends-overlay" class="wf-friends-overlay" hidden aria-label="Friends"><div class="wf-friends-card" role="dialog" aria-modal="true" aria-labelledby="walk-friends-title">diff --git a/src/dashboard-next/pages/monetize.js b/src/dashboard-next/pages/monetize.jsindex 53b159b55..f869dfd23 100644--- a/src/dashboard-next/pages/monetize.js+++ b/src/dashboard-next/pages/monetize.js@@ -309,10 +309,10 @@ function renderSkillPricing(prices, agentId, host, me, agents, feeBps = 250) {panel.innerHTML = `<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px"><div>- <div class="dn-panel-title">Skill Pricing</div>- <div class="dn-panel-sub" style="margin:2px 0 0">Set per-call prices for your agent's skills. Callers pay in USDC — the platform takes ${esc(feePercent)}% per payment.</div>+ <div class="dn-panel-title">Skill Pricing & Access</div>+ <div class="dn-panel-sub" style="margin:2px 0 0">Charge USDC per call (platform takes ${esc(feePercent)}%) or gate a skill to holders of an NFT collection.</div></div>- <button class="dn-btn primary" data-action="add-price">+ Add Pricing</button>+ <button class="dn-btn primary" data-action="add-price">+ Add Skill</button></div><div data-slot="prices-list"></div>`;@@ -322,8 +322,8 @@ function renderSkillPricing(prices, agentId, host, me, agents, feeBps = 250) {if (!skillPrices.length) {listHost.innerHTML = `<div class="dn-empty">- <h3>No skills priced yet</h3>- <p>Set a price on your agent's skills to start earning USDC on every call.</p>+ <h3>No skills gated yet</h3>+ <p>Charge USDC per call or restrict a skill to NFT holders to start monetizing your agent.</p></div>`;} else {listHost.innerHTML = `@@ -340,9 +340,36 @@ function renderSkillPricing(prices, agentId, host, me, agents, feeBps = 250) {<tbody>${skillPrices.map((p, idx) => {const active = p.active !== false;+ const isNft = p.gate_type === 'nft';+ const skillName = esc(p.skill_name || p.skill || p.name || 'Unnamed');+ if (isNft) {+ const mint = String(p.nft_collection_mint || '');+ const shortMint = mint.length > 14 ? `${mint.slice(0, 6)}…${mint.slice(-6)}` : mint;+ return `+ <tr data-idx="${idx}">+ <td style="font-weight:500">${skillName}+ <span class="dn-tag" style="margin-left:6px;font-size:10px;vertical-align:middle">🔒 NFT gated</span>+ </td>+ <td style="text-align:right">+ <span class="mon-mono" style="font-size:12px" title="${esc(mint)}">${esc(shortMint)}</span>+ <div class="mon-fee-note">Holders of this collection only</div>+ </td>+ <td style="text-align:center">+ <label class="mon-toggle" title="${active ? 'Active' : 'Inactive'}">+ <input type="checkbox" ${active ? 'checked' : ''} data-field="active" data-idx="${idx}" disabled />+ <span class="mon-toggle-track"></span>+ </label>+ </td>+ <td style="text-align:right">+ <div style="display:flex;gap:6px;justify-content:flex-end">+ <button class="dn-btn danger" data-action="delete-price" data-idx="${idx}" style="padding:5px 10px;font-size:12px">Delete</button>+ </div>+ </td>+ </tr>`;+ }return `<tr data-idx="${idx}">- <td style="font-weight:500">${esc(p.skill_name || p.skill || p.name || 'Unnamed')}</td>+ <td style="font-weight:500">${skillName}</td><td style="text-align:right"><input type="number" min="0" step="0.000001" class="mon-input mon-input-sm"value="${esc(String(p.price_usdc ?? p.price ?? 0))}"@@ -375,7 +402,7 @@ function renderSkillPricing(prices, agentId, host, me, agents, feeBps = 250) {openAddPriceModal(agentId, feeBps, (saved) => {skillPrices.push(saved);paint();- toastMonetize('Skill price added');+ toastMonetize(saved?.gate_type === 'nft' ? 'NFT-gated skill added' : 'Skill price added');});});@@ -456,7 +483,7 @@ function openAddPriceModal(agentId, feeBps, onSaved) {overlay.className = 'mon-overlay';overlay.innerHTML = `<div role="dialog" aria-modal="true" aria-label="Add skill price" class="mon-modal">- <div style="font-size:16px;font-weight:600;margin-bottom:18px">Add Skill Pricing</div>+ <div style="font-size:16px;font-weight:600;margin-bottom:18px">Add Skill Access</div><label class="mon-field"><span class="mon-label">Skill name</span>@@ -464,11 +491,25 @@ function openAddPriceModal(agentId, feeBps, onSaved) {</label><label class="mon-field">+ <span class="mon-label">How is it unlocked?</span>+ <select data-slot="gate" class="mon-select">+ <option value="price">Pay per call (USDC)</option>+ <option value="nft">NFT gate — holders only</option>+ </select>+ </label>++ <label class="mon-field" data-slot="price-field"><span class="mon-label">Price per call (USDC)</span><input data-slot="price" type="number" min="0" step="0.000001" placeholder="0.001" class="mon-input" /><span data-slot="fee-note" class="mon-fee-note">Platform fee: ${esc(feePercent)}% — set a price to see your net take.</span></label>+ <label class="mon-field" data-slot="nft-field" hidden>+ <span class="mon-label">NFT collection mint</span>+ <input data-slot="collection" type="text" maxlength="44" placeholder="Collection mint address (base58)" class="mon-input mon-mono" />+ <span class="mon-fee-note">Only wallets holding an NFT from this collection can use the skill — verified on-chain on every call.</span>+ </label>+<label style="display:flex;align-items:center;gap:10px;margin-bottom:18px;cursor:pointer"><input data-slot="active" type="checkbox" checked style="width:16px;height:16px;cursor:pointer;accent-color:var(--nxt-accent)" /><span style="font-size:13px;color:var(--nxt-ink)">Active (visible to callers)</span>@@ -478,20 +519,31 @@ function openAddPriceModal(agentId, feeBps, onSaved) {<div style="display:flex;gap:8px;justify-content:flex-end"><button class="dn-btn ghost" data-action="cancel">Cancel</button>- <button class="dn-btn primary" data-action="submit">Add pricing</button>+ <button class="dn-btn primary" data-action="submit">Add</button></div></div>`;document.body.appendChild(overlay);const skillEl = overlay.querySelector('[data-slot="skill"]');+ const gateEl = overlay.querySelector('[data-slot="gate"]');+ const priceFieldEl = overlay.querySelector('[data-slot="price-field"]');+ const nftFieldEl = overlay.querySelector('[data-slot="nft-field"]');const priceEl = overlay.querySelector('[data-slot="price"]');+ const collectionEl = overlay.querySelector('[data-slot="collection"]');const activeEl = overlay.querySelector('[data-slot="active"]');const errorEl = overlay.querySelector('[data-slot="error"]');const feeNoteEl = overlay.querySelector('[data-slot="fee-note"]');const submitBtn = overlay.querySelector('[data-action="submit"]');skillEl.focus();+ gateEl.addEventListener('change', () => {+ const isNft = gateEl.value === 'nft';+ priceFieldEl.hidden = isNft;+ nftFieldEl.hidden = !isNft;+ errorEl.textContent = '';+ });+priceEl.addEventListener('input', () => {const val = parseFloat(priceEl.value);feeNoteEl.textContent = Number.isFinite(val) && val > 0@@ -507,25 +559,37 @@ function openAddPriceModal(agentId, feeBps, onSaved) {submitBtn.addEventListener('click', async () => {const name = skillEl.value.trim();- const price = parseFloat(priceEl.value);+ const isNft = gateEl.value === 'nft';if (!name) { errorEl.textContent = 'Skill name is required.'; return; }- if (!Number.isFinite(price) || price < 0) { errorEl.textContent = 'Enter a valid price.'; return; }++ let payload;+ let saved;+ if (isNft) {+ const collection = collectionEl.value.trim();+ if (!SOLANA_ADDR_RE.test(collection)) {+ errorEl.textContent = 'Enter a valid collection mint address.';+ return;+ }+ payload = { agent_id: agentId, skill_name: name, gate_type: 'nft', nft_collection_mint: collection };+ saved = { skill_name: name, gate_type: 'nft', nft_collection_mint: collection, price_usdc: 0, active: activeEl.checked };+ } else {+ const price = parseFloat(priceEl.value);+ if (!Number.isFinite(price) || price < 0) { errorEl.textContent = 'Enter a valid price.'; return; }+ payload = { agent_id: agentId, skill_name: name, gate_type: 'price', price_usdc: price };+ saved = { skill_name: name, gate_type: 'price', price_usdc: price, active: activeEl.checked };+ }+errorEl.textContent = '';submitBtn.disabled = true;submitBtn.textContent = 'Adding...';try {- const r = await put('/api/monetization/prices', {- agent_id: agentId,- skill_name: name,- price_usdc: price,- active: activeEl.checked,- });+ const r = await put('/api/monetization/prices', payload);close();- onSaved(r?.price || { skill_name: name, price_usdc: price, active: activeEl.checked });+ onSaved(r?.price || saved);} catch (err) {- errorEl.textContent = err?.body?.error || err?.message || 'Failed to add price';+ errorEl.textContent = err?.body?.error || err?.message || 'Failed to add';submitBtn.disabled = false;- submitBtn.textContent = 'Add pricing';+ submitBtn.textContent = 'Add';}});}diff --git a/src/irl.js b/src/irl.jsindex baf864128..61d1a4607 100644--- a/src/irl.js+++ b/src/irl.js@@ -4534,7 +4534,7 @@ function renderMyPins(pins, listEl) {if (!list) return;list.innerHTML = pins.map(p => `<div class="irl-pin-row" data-pid="${_escHtml(p.id)}"><div class="irl-pin-info">- <div class="irl-pin-name">${_escHtml(p.avatar_name || 'Agent')}${_placementBadgeHTML(p)}</div>+ <div class="irl-pin-name"><span class="irl-pin-name-txt">${_escHtml(p.avatar_name || 'Agent')}</span>${_placementBadgeHTML(p)}</div>${p.caption ? `<div class="irl-pin-caption">${_escHtml(p.caption)}</div>` : ''}<div class="irl-pin-meta">${_pinMetaLine(p)}</div></div>diff --git a/src/marketplace-gallery.js b/src/marketplace-gallery.jsnew file mode 100644index 000000000..e0f5dc62a--- /dev/null+++ b/src/marketplace-gallery.js@@ -0,0 +1,825 @@+/**+ * Walk-Browse — the marketplace as a 3D gallery you stroll through.+ *+ * Activated only on /marketplace-walk (walk.js boots with ?gallery=marketplace).+ * Every marketplace listing — agents, avatars, skills — becomes a lit plinth in+ * a procedurally generated hall: artwork on a vertical billboard, title + price+ * floating above. Walk within two metres and the full listing slides in from the+ * right; press E (or tap) to open its detail page.+ *+ * The hall is endless. The walk engine pins the avatar inside a bounded ground+ * disc, so rather than march the avatar down an infinite corridor we run a+ * treadmill: the player's forward travel scrolls a belt of plinths past a fixed+ * anchor while the avatar stays centred. A pool of plinth meshes recycles from+ * back to front — when one slides behind you it leaps to the far end carrying the+ * next listing — so memory is constant no matter how far you browse. Listings+ * stream in page-by-page from the real marketplace APIs; once every page is in,+ * the hall loops the full catalogue so it never dead-ends.+ *+ * Everything rendered is real: agents from /api/marketplace/agents, avatars from+ * /api/explore, skills from /api/skills — same data, prices, and detail routes+ * the 2D grid uses, so a number never disagrees across surfaces.+ */++import {+ Group,+ Mesh,+ PlaneGeometry,+ CylinderGeometry,+ BoxGeometry,+ RingGeometry,+ MeshBasicMaterial,+ MeshStandardMaterial,+ CanvasTexture,+ TextureLoader,+ SRGBColorSpace,+ DoubleSide,+ Color,+ MathUtils,+} from 'three';++// ── Layout (metres) ─────────────────────────────────────────────────────────+const SPACING = 4; // a plinth every 4m down the hall+const START_Z = 4; // first plinth sits 4m ahead of the anchor+const SLOT_COUNT = 10; // recycled plinth pool — covers the full visible span+const SIDE_X = 3; // plinths stand 3m off the centre line, alternating sides+const ANCHOR_Z = 0; // world-z the avatar is pinned to (treadmill centre)+const LATERAL_LIMIT = 7.5; // how far the player may strafe off the centre line+const RECYCLE_BEHIND = 6; // once a plinth is this far behind, recycle it forward+const ENTER_RANGE = 2.0; // step within 2m → reveal the listing+const RELEASE_RANGE = 3.4; // step past this → dismiss (hysteresis stops flicker)+const REBASE_AT = 500; // fold belt offset back near 0 to preserve float precision++const PAGE_SIZE = 18;+const TYPE_ACCENT = { agent: '#8b5cf6', avatar: '#22d3ee', skill: '#34d399' };+const TYPE_LABEL = { agent: 'Agent', avatar: 'Avatar', skill: 'Skill' };++const FILTERS = [+ { key: 'all', label: 'All' },+ { key: 'agent', label: 'Agents' },+ { key: 'avatar', label: 'Avatars' },+ { key: 'skill', label: 'Skills' },+];++const STYLE_ID = 'marketplace-gallery-styles';++function ensureStyles() {+ if (document.getElementById(STYLE_ID)) return;+ const s = document.createElement('style');+ s.id = STYLE_ID;+ s.textContent = `+.mwg-chips{position:fixed;top:calc(env(safe-area-inset-top,0) + 116px);left:50%;+ transform:translateX(-50%);z-index:6;display:flex;gap:6px;padding:5px;border-radius:999px;+ background:rgba(10,10,12,.72);border:1px solid rgba(255,255,255,.1);+ backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);box-shadow:0 8px 28px rgba(0,0,0,.4);}+.mwg-chip{appearance:none;border:0;background:transparent;color:#a1a1aa;font:inherit;font-size:13px;+ font-weight:600;padding:7px 15px;border-radius:999px;cursor:pointer;white-space:nowrap;+ transition:background .15s ease,color .15s ease;}+.mwg-chip:hover{color:#fafafa;background:rgba(255,255,255,.06);}+.mwg-chip[aria-pressed="true"]{color:#0a0a0a;background:#fafafa;}+.mwg-chip:focus-visible{outline:2px solid rgba(255,255,255,.6);outline-offset:2px;}++.mwg-panel{position:fixed;top:50%;right:max(16px,env(safe-area-inset-right,0));+ transform:translate(calc(100% + 32px),-50%);z-index:7;width:min(340px,calc(100vw - 32px));+ max-height:min(78vh,640px);overflow:hidden auto;border-radius:18px;+ background:rgba(12,12,14,.86);border:1px solid rgba(255,255,255,.12);+ backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px);+ box-shadow:0 24px 70px rgba(0,0,0,.55);color:#fafafa;+ transition:transform .32s cubic-bezier(.22,1,.36,1),opacity .26s ease;opacity:0;+ scrollbar-width:thin;}+.mwg-panel[data-show="1"]{transform:translate(0,-50%);opacity:1;}+.mwg-panel-media{position:relative;width:100%;aspect-ratio:16/10;background:#17171b;overflow:hidden;}+.mwg-panel-media img{width:100%;height:100%;object-fit:cover;display:block;}+.mwg-panel-fallback{width:100%;height:100%;display:flex;align-items:center;justify-content:center;+ font-size:64px;font-weight:800;color:rgba(255,255,255,.9);}+.mwg-panel-badge{position:absolute;top:12px;left:12px;font-size:11px;font-weight:700;+ letter-spacing:.04em;text-transform:uppercase;padding:5px 10px;border-radius:999px;+ color:#0a0a0a;}+.mwg-panel-body{padding:16px 18px 18px;}+.mwg-panel-title{margin:0 0 4px;font-size:18px;font-weight:700;line-height:1.25;}+.mwg-panel-author{margin:0 0 10px;font-size:12px;color:#a1a1aa;}+.mwg-panel-desc{margin:0 0 14px;font-size:13px;line-height:1.5;color:#c8c8d0;+ display:-webkit-box;-webkit-line-clamp:5;-webkit-box-orient:vertical;overflow:hidden;}+.mwg-panel-meta{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:14px;}+.mwg-panel-price{font-size:17px;font-weight:700;}+.mwg-panel-cat{font-size:11px;font-weight:600;color:#a1a1aa;text-transform:capitalize;+ padding:4px 9px;border-radius:999px;background:rgba(255,255,255,.06);}+.mwg-panel-cta{display:flex;align-items:center;justify-content:center;gap:8px;width:100%;+ appearance:none;border:0;border-radius:12px;padding:12px 16px;font:inherit;font-size:14px;+ font-weight:700;color:#0a0a0a;cursor:pointer;transition:filter .15s ease,transform .1s ease;}+.mwg-panel-cta:hover{filter:brightness(1.08);}+.mwg-panel-cta:active{transform:scale(.98);}+.mwg-panel-cta:focus-visible{outline:2px solid #fff;outline-offset:2px;}+.mwg-panel-hint{margin:9px 0 0;text-align:center;font-size:11px;color:#71717a;}+.mwg-panel-hint kbd{font-family:ui-monospace,Menlo,monospace;font-size:10.5px;padding:1px 5px;+ border-radius:4px;background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.14);}++.mwg-prompt{position:fixed;left:50%;bottom:calc(86px + env(safe-area-inset-bottom,0));+ transform:translateX(-50%) translateY(8px);z-index:6;display:none;align-items:center;gap:9px;+ padding:9px 16px;border-radius:999px;background:rgba(10,10,12,.82);+ border:1px solid rgba(255,255,255,.14);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);+ color:#fafafa;font-size:13px;font-weight:600;cursor:pointer;box-shadow:0 8px 26px rgba(0,0,0,.45);+ transition:opacity .2s ease,transform .2s ease;opacity:0;}+.mwg-prompt[data-show="1"]{display:inline-flex;opacity:1;transform:translateX(-50%) translateY(0);}+.mwg-prompt kbd{font-family:ui-monospace,Menlo,monospace;font-size:11px;padding:2px 7px;border-radius:5px;+ background:rgba(255,255,255,.14);border:1px solid rgba(255,255,255,.2);}++.mwg-toast{position:fixed;left:50%;top:calc(env(safe-area-inset-top,0) + 168px);+ transform:translateX(-50%);z-index:6;display:none;align-items:center;gap:12px;+ padding:12px 18px;border-radius:14px;background:rgba(12,12,14,.9);+ border:1px solid rgba(255,255,255,.12);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);+ color:#fafafa;font-size:13px;box-shadow:0 12px 40px rgba(0,0,0,.5);max-width:min(420px,calc(100vw - 32px));}+.mwg-toast[data-show="1"]{display:inline-flex;}+.mwg-toast a,.mwg-toast button{color:#8b5cf6;font-weight:700;text-decoration:none;background:none;+ border:0;font:inherit;cursor:pointer;padding:0;white-space:nowrap;}++@media (hover:none),(max-width:640px){+ .mwg-chips{top:calc(env(safe-area-inset-top,0) + 104px);}+ .mwg-panel{top:auto;bottom:calc(150px + env(safe-area-inset-bottom,0));right:50%;+ transform:translate(50%,calc(100% + 40px));width:min(360px,calc(100vw - 24px));max-height:46vh;}+ .mwg-panel[data-show="1"]{transform:translate(50%,0);}+ .mwg-prompt{bottom:calc(150px + env(safe-area-inset-bottom,0));}+}+@media (prefers-reduced-motion:reduce){+ .mwg-panel,.mwg-prompt,.mwg-chip,.mwg-panel-cta{transition:none;}+}+body.is-zen .mwg-chips,body.is-zen .mwg-panel,body.is-zen .mwg-prompt,body.is-zen .mwg-toast{display:none !important;}+`;+ document.head.appendChild(s);+}++// ── Listing normalisation ───────────────────────────────────────────────────+function fmtTokenPrice(price) {+ if (!price || price.amount == null) return 'Free';+ const dec = Number(price.mint_decimals ?? 6);+ const v = Number(price.amount) / Math.pow(10, dec);+ if (!Number.isFinite(v) || v <= 0) return 'Free';+ return `$${v >= 1 ? v.toLocaleString(undefined, { maximumFractionDigits: 2 }) : v.toFixed(2)}`;+}++function normalizeAgent(a) {+ return {+ type: 'agent',+ name: a.name || 'Untitled agent',+ description: a.description || '',+ image: a.thumbnail_url || null,+ price: fmtTokenPrice(a.price),+ category: a.category || '',+ author: null,+ href: `/marketplace/agents/${encodeURIComponent(a.id)}`,+ };+}++function normalizeAvatar(a) {+ return {+ type: 'avatar',+ name: a.name || 'Untitled avatar',+ description: a.description || '',+ image: a.image || null,+ price: fmtTokenPrice(a.price),+ category: a.modelCategory || 'avatar',+ author: a.author?.displayName || a.author?.handle || null,+ href: `/marketplace/avatars/${encodeURIComponent(a.avatarId)}`,+ };+}++function normalizeSkill(s) {+ const usd = Number(s.price_per_call_usd);+ return {+ type: 'skill',+ name: s.name || 'Untitled skill',+ description: s.description || '',+ image: null,+ price: usd > 0 ? `$${usd}/call` : 'Free',+ category: s.category || '',+ author: s.author?.display_name || null,+ href: `/marketplace/skills/${encodeURIComponent(s.slug || s.id)}`,+ };+}++/**+ * @param {object} cfg+ * @param {import('three').Scene} cfg.scene+ * @param {() => {x:number,y:number,z:number}} cfg.getLocalPosition+ */+export function createMarketplaceGallery({ scene, getLocalPosition }) {+ ensureStyles();++ const texLoader = new TextureLoader();+ texLoader.setCrossOrigin('anonymous');++ // ── Static hall: a runner + side bases anchored under the avatar so the+ // scrolling plinths always have a floor (the engine's ground disc is+ // only 12m wide; the hall reaches far past it). ─────────────────────────+ const hall = new Group();+ hall.name = 'mwg-hall';+ const runner = new Mesh(+ new PlaneGeometry(7, 80),+ new MeshStandardMaterial({ color: 0xd9d5cc, roughness: 0.95, metalness: 0 }),+ );+ runner.rotation.x = -Math.PI / 2;+ runner.position.set(0, 0.02, ANCHOR_Z - 28);+ runner.receiveShadow = true;+ hall.add(runner);+ const centerLine = new Mesh(+ new PlaneGeometry(0.12, 80),+ new MeshBasicMaterial({ color: 0xb8b2a6 }),+ );+ centerLine.rotation.x = -Math.PI / 2;+ centerLine.position.set(0, 0.03, ANCHOR_Z - 28);+ hall.add(centerLine);+ for (const sx of [-3.5, 3.5]) {+ const base = new Mesh(+ new BoxGeometry(0.5, 0.5, 80),+ new MeshStandardMaterial({ color: 0xf2efe9, roughness: 0.9, metalness: 0 }),+ );+ base.position.set(sx, 0.25, ANCHOR_Z - 28);+ base.castShadow = true;+ base.receiveShadow = true;+ hall.add(base);+ }+ scene.add(hall);++ // ── Plinth pool (recycled) ─────────────────────────────────────────────────+ const belt = new Group();+ belt.name = 'mwg-belt';+ scene.add(belt);++ /** @type {Array<ReturnType<typeof buildSlot>>} */+ const slots = [];++ function makeFallbackTexture(name, accentHex) {+ const c = document.createElement('canvas');+ c.width = 512;+ c.height = 640;+ const ctx = c.getContext('2d');+ const g = ctx.createLinearGradient(0, 0, 0, 640);+ g.addColorStop(0, accentHex);+ g.addColorStop(1, '#0c0c0e');+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, 512, 640);+ ctx.fillStyle = 'rgba(255,255,255,.92)';+ ctx.font = '800 240px Inter, system-ui, sans-serif';+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.fillText((name || '?').trim().charAt(0).toUpperCase() || '?', 256, 320);+ const tex = new CanvasTexture(c);+ tex.colorSpace = SRGBColorSpace;+ return tex;+ }++ function drawLabel(canvas, listing, accentHex) {+ const ctx = canvas.getContext('2d');+ const W = canvas.width;+ const H = canvas.height;+ ctx.clearRect(0, 0, W, H);+ const r = 26;+ ctx.fillStyle = 'rgba(10,10,12,.92)';+ ctx.beginPath();+ ctx.moveTo(r, 0);+ ctx.arcTo(W, 0, W, H, r);+ ctx.arcTo(W, H, 0, H, r);+ ctx.arcTo(0, H, 0, 0, r);+ ctx.arcTo(0, 0, W, 0, r);+ ctx.fill();+ ctx.fillStyle = accentHex;+ ctx.fillRect(0, 0, 12, H);+ // name (truncate to fit one line)+ ctx.fillStyle = '#fafafa';+ ctx.font = '700 52px Inter, system-ui, sans-serif';+ ctx.textBaseline = 'middle';+ ctx.textAlign = 'left';+ let name = listing.name || '';+ while (ctx.measureText(name).width > W - 60 && name.length > 1) {+ name = name.slice(0, -2);+ }+ if (name !== (listing.name || '')) name = name.trimEnd() + '…';+ ctx.fillText(name, 36, H * 0.36);+ // price + type+ ctx.font = '700 44px Inter, system-ui, sans-serif';+ ctx.fillStyle = accentHex;+ ctx.fillText(listing.price, 36, H * 0.74);+ ctx.font = '600 32px Inter, system-ui, sans-serif';+ ctx.fillStyle = '#a1a1aa';+ ctx.textAlign = 'right';+ ctx.fillText(TYPE_LABEL[listing.type] || '', W - 36, H * 0.74);+ }++ function coverFit(tex, imgW, imgH, planeAspect) {+ const imgAspect = imgW / imgH;+ tex.center.set(0.5, 0.5);+ if (imgAspect > planeAspect) {+ tex.repeat.set(planeAspect / imgAspect, 1);+ } else {+ tex.repeat.set(1, imgAspect / planeAspect);+ }+ }++ function buildSlot(index) {+ const side = index % 2 === 0 ? -1 : 1;+ const group = new Group();+ group.position.set(side * SIDE_X, 0, -(START_Z + index * SPACING));+ const faceYaw = side < 0 ? Math.PI / 2 : -Math.PI / 2;++ const pedestal = new Mesh(+ new CylinderGeometry(0.5, 0.66, 1.0, 28),+ new MeshStandardMaterial({ color: 0xeceae4, roughness: 0.85, metalness: 0.05 }),+ );+ pedestal.position.y = 0.5;+ pedestal.castShadow = true;+ pedestal.receiveShadow = true;+ group.add(pedestal);++ const frame = new Mesh(+ new BoxGeometry(1.78, 2.18, 0.08),+ new MeshStandardMaterial({ color: 0x18181b, roughness: 0.6, metalness: 0.1 }),+ );+ frame.position.set(0, 2.1, -0.04);+ frame.rotation.y = faceYaw;+ frame.castShadow = true;+ group.add(frame);++ const billboardMat = new MeshBasicMaterial({ side: DoubleSide, toneMapped: false });+ const billboard = new Mesh(new PlaneGeometry(1.6, 2.0), billboardMat);+ billboard.position.set(0, 2.1, 0);+ billboard.rotation.y = faceYaw;+ group.add(billboard);++ const labelCanvas = document.createElement('canvas');+ labelCanvas.width = 512;+ labelCanvas.height = 176;+ const labelTex = new CanvasTexture(labelCanvas);+ labelTex.colorSpace = SRGBColorSpace;+ const label = new Mesh(+ new PlaneGeometry(1.7, 0.58),+ new MeshBasicMaterial({ map: labelTex, transparent: true, toneMapped: false, side: DoubleSide }),+ );+ label.position.set(0, 3.5, 0);+ label.rotation.y = faceYaw;+ group.add(label);++ const ring = new Mesh(+ new RingGeometry(0.74, 0.92, 40),+ new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.9, side: DoubleSide }),+ );+ ring.rotation.x = -Math.PI / 2;+ ring.position.y = 0.05;+ ring.visible = false;+ group.add(ring);++ group.visible = false;+ belt.add(group);++ return {+ index,+ side,+ group,+ billboard,+ billboardMat,+ label,+ labelTex,+ labelCanvas,+ ring,+ listing: null,+ imgToken: 0,+ };+ }++ function assignListing(slot, listing) {+ slot.listing = listing;+ slot.group.visible = true;+ const accent = TYPE_ACCENT[listing.type] || '#8b5cf6';+ slot.ring.material.color.set(accent);+ drawLabel(slot.labelCanvas, listing, accent);+ slot.labelTex.needsUpdate = true;++ // Swap artwork. Dispose the previous map so a long browse never leaks GPU.+ const token = ++slot.imgToken;+ const setMap = (tex) => {+ if (token !== slot.imgToken) {+ tex.dispose();+ return;+ }+ const prev = slot.billboardMat.map;+ slot.billboardMat.map = tex;+ slot.billboardMat.needsUpdate = true;+ if (prev) prev.dispose();+ };+ if (listing.image) {+ texLoader.load(+ listing.image,+ (tex) => {+ tex.colorSpace = SRGBColorSpace;+ coverFit(tex, tex.image?.width || 1, tex.image?.height || 1, 1.6 / 2.0);+ setMap(tex);+ },+ undefined,+ () => setMap(makeFallbackTexture(listing.name, accent)),+ );+ } else {+ setMap(makeFallbackTexture(listing.name, accent));+ }+ }++ // ── Listing stream (real APIs, paged, then looped) ──────────────────────────+ const sources = {+ agent: { cursor: null, done: false, fetch: fetchAgents },+ avatar: { cursor: null, done: false, fetch: fetchAvatars },+ skill: { cursor: null, done: false, fetch: fetchSkills },+ };+ let filter = 'all';+ let buffer = []; // normalised listings waiting for a plinth+ let served = []; // everything seen this filter — replayed once pages run out+ let loading = false;+ let loadError = false;+ let loadedAny = false;++ async function fetchAgents(cursor) {+ const u = new URL('/api/marketplace/agents', location.origin);+ u.searchParams.set('limit', String(PAGE_SIZE));+ u.searchParams.set('sort', 'recommended');+ if (cursor) u.searchParams.set('cursor', cursor);+ const r = await fetch(u);+ if (!r.ok) throw new Error(`agents ${r.status}`);+ const j = await r.json();+ const items = (j?.data?.items || []).map(normalizeAgent);+ return { items, next: j?.data?.next_cursor || null };+ }++ async function fetchAvatars(cursor) {+ const u = new URL('/api/explore', location.origin);+ u.searchParams.set('source', 'avatar');+ u.searchParams.set('quality', 'high');+ u.searchParams.set('limit', String(PAGE_SIZE));+ if (cursor) u.searchParams.set('cursor', cursor);+ const r = await fetch(u);+ if (!r.ok) throw new Error(`avatars ${r.status}`);+ const j = await r.json();+ const items = (j?.items || []).map(normalizeAvatar);+ return { items, next: j?.nextCursor || null };+ }++ async function fetchSkills(cursor) {+ const u = new URL('/api/skills', location.origin);+ u.searchParams.set('limit', String(PAGE_SIZE));+ u.searchParams.set('sort', 'popular');+ if (cursor) u.searchParams.set('cursor', cursor);+ const r = await fetch(u);+ if (!r.ok) throw new Error(`skills ${r.status}`);+ const j = await r.json();+ const items = (j?.skills || []).map(normalizeSkill);+ return { items, next: j?.next_cursor || null };+ }++ function activeSources() {+ return filter === 'all'+ ? ['agent', 'avatar', 'skill']+ : [filter];+ }++ function allDone() {+ return activeSources().every((k) => sources[k].done);+ }++ async function loadPage() {+ if (loading || allDone()) return;+ loading = true;+ const want = activeSources().filter((k) => !sources[k].done);+ try {+ const results = await Promise.all(+ want.map((k) => sources[k].fetch(sources[k].cursor).then((res) => ({ k, res }))),+ );+ // Interleave across sources so "All" reads as a varied hall, not three blocks.+ const lanes = results.map(({ k, res }) => {+ sources[k].cursor = res.next;+ if (!res.next) sources[k].done = true;+ return res.items;+ });+ const merged = [];+ for (let i = 0; lanes.some((l) => i < l.length); i++) {+ for (const lane of lanes) if (i < lane.length) merged.push(lane[i]);+ }+ if (merged.length) {+ loadedAny = true;+ buffer.push(...merged);+ served.push(...merged);+ }+ loadError = false;+ hideToast();+ } catch (err) {+ loadError = true;+ showToast(`Couldn't load listings`, 'Retry', () => {+ loadError = false;+ loadPage().then(fillEmptySlots);+ });+ } finally {+ loading = false;+ }+ }++ function nextListing() {+ if (buffer.length) return buffer.shift();+ // Pages exhausted but we have a catalogue → loop it so the hall never ends.+ if (allDone() && served.length) {+ buffer = served.slice();+ return buffer.shift();+ }+ return null;+ }++ function fillEmptySlots() {+ for (const slot of slots) {+ if (slot.listing) continue;+ const listing = nextListing();+ if (!listing) break;+ assignListing(slot, listing);+ }+ maybeShowEmpty();+ }++ // ── Treadmill + recycling ───────────────────────────────────────────────────+ let anchored = false;+ let beltBaseZ = 0; // accumulated forward travel folded out of belt.position for precision++ function recycleAndFill() {+ // A plinth that has slid behind the player leaps to the front of the hall.+ let minLocalZ = Infinity;+ for (const s of slots) minLocalZ = Math.min(minLocalZ, s.group.position.z);+ for (const slot of slots) {+ const worldZ = slot.group.position.z + belt.position.z;+ if (worldZ > ANCHOR_Z + RECYCLE_BEHIND) {+ slot.group.position.z = minLocalZ - SPACING;+ minLocalZ = slot.group.position.z;+ const listing = nextListing();+ if (listing) assignListing(slot, listing);+ else {+ slot.listing = null;+ slot.group.visible = false;+ }+ }+ }+ }++ let activeSlot = null;+ let navigating = false;++ function pickNearest(px, pz) {+ let best = null;+ let bestD = Infinity;+ for (const slot of slots) {+ if (!slot.listing || !slot.group.visible) continue;+ const dx = slot.group.position.x - px;+ const dz = slot.group.position.z + belt.position.z - pz;+ const d = Math.hypot(dx, dz);+ if (d < bestD) {+ bestD = d;+ best = slot;+ }+ }+ return { best, bestD };+ }++ let ringPulse = 0;++ function update(dt) {+ const pos = getLocalPosition?.();+ if (!pos) return;++ if (!anchored) {+ pos.z = ANCHOR_Z;+ anchored = true;+ }+ // Transfer the avatar's forward travel into the belt, then re-anchor it so+ // the engine's ground-disc clamp is never reached. Net effect: the player+ // walks forever while standing still in world space.+ const dz = pos.z - ANCHOR_Z;+ if (dz !== 0) {+ belt.position.z -= dz;+ pos.z = ANCHOR_Z;+ }+ // Keep the player on the carpet.+ if (pos.x < -LATERAL_LIMIT) pos.x = -LATERAL_LIMIT;+ else if (pos.x > LATERAL_LIMIT) pos.x = LATERAL_LIMIT;++ // Fold large offsets back toward zero to keep float precision crisp on a+ // very long stroll (shift belt + every plinth together — no visible jump).+ if (belt.position.z > REBASE_AT) {+ const k = belt.position.z;+ belt.position.z = 0;+ beltBaseZ += k;+ for (const s of slots) s.group.position.z += k;+ }++ // Stream the next page well before the hall runs dry (≈ a screen ahead).+ if (!loading && !loadError && !allDone() && buffer.length < SLOT_COUNT) {+ loadPage().then(fillEmptySlots);+ }++ fillEmptySlots();+ recycleAndFill();++ // Proximity — reveal the nearest listing within reach, with hysteresis.+ const { best, bestD } = pickNearest(pos.x, ANCHOR_Z);+ if (activeSlot) {+ const ax = activeSlot.group.position.x - pos.x;+ const az = activeSlot.group.position.z + belt.position.z - ANCHOR_Z;+ const ad = Math.hypot(ax, az);+ if (!activeSlot.listing || ad > RELEASE_RANGE) {+ setActive(best && bestD <= ENTER_RANGE ? best : null);+ } else if (best && best !== activeSlot && bestD <= ENTER_RANGE && bestD < ad - 0.6) {+ setActive(best);+ }+ } else if (best && bestD <= ENTER_RANGE) {+ setActive(best);+ }++ // Gentle ring pulse + lift on the active plinth.+ ringPulse += dt;+ for (const slot of slots) {+ const target = slot === activeSlot ? 1 : 0;+ const cur = slot.group.scale.x;+ const next = MathUtils.lerp(cur, 1 + target * 0.06, 0.18);+ slot.group.scale.setScalar(next);+ if (slot.ring.visible) {+ slot.ring.material.opacity = 0.55 + Math.sin(ringPulse * 3) * 0.35;+ }+ }+ }++ function setActive(slot) {+ if (slot === activeSlot) return;+ if (activeSlot) {+ activeSlot.ring.visible = false;+ }+ activeSlot = slot;+ if (slot) {+ slot.ring.visible = true;+ showPanel(slot.listing);+ } else {+ hidePanel();+ }+ }++ function navigateActive() {+ if (!activeSlot?.listing || navigating) return;+ navigating = true;+ location.href = activeSlot.listing.href;+ }++ // ── DOM: chips, panel, prompt, toast ────────────────────────────────────────+ const chips = document.createElement('div');+ chips.className = 'mwg-chips';+ chips.setAttribute('role', 'tablist');+ chips.setAttribute('aria-label', 'Filter gallery listings');+ for (const f of FILTERS) {+ const b = document.createElement('button');+ b.className = 'mwg-chip';+ b.type = 'button';+ b.textContent = f.label;+ b.dataset.filter = f.key;+ b.setAttribute('aria-pressed', String(f.key === filter));+ b.addEventListener('click', () => setFilter(f.key));+ chips.appendChild(b);+ }+ document.body.appendChild(chips);++ const panel = document.createElement('aside');+ panel.className = 'mwg-panel';+ panel.setAttribute('aria-live', 'polite');+ document.body.appendChild(panel);++ const prompt = document.createElement('button');+ prompt.className = 'mwg-prompt';+ prompt.type = 'button';+ prompt.innerHTML = `<kbd>E</kbd><span class="mwg-prompt-text">Open listing</span>`;+ prompt.addEventListener('click', navigateActive);+ document.body.appendChild(prompt);++ const toast = document.createElement('div');+ toast.className = 'mwg-toast';+ toast.setAttribute('role', 'status');+ document.body.appendChild(toast);++ function showToast(message, actionLabel, onAction) {+ toast.innerHTML = '';+ const span = document.createElement('span');+ span.textContent = message;+ toast.appendChild(span);+ if (actionLabel) {+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.textContent = actionLabel;+ btn.addEventListener('click', onAction);+ toast.appendChild(btn);+ }+ toast.setAttribute('data-show', '1');+ }+ function hideToast() {+ toast.removeAttribute('data-show');+ }++ function maybeShowEmpty() {+ if (loadedAny || loading || !allDone()) return;+ const label = FILTERS.find((f) => f.key === filter)?.label || 'listings';+ showToast(`No ${label.toLowerCase()} listed yet.`, 'Browse the grid →', () => {+ location.href = '/marketplace';+ });+ }++ function showPanel(listing) {+ const accent = TYPE_ACCENT[listing.type] || '#8b5cf6';+ const media = listing.image+ ? `<img src="${escapeAttr(listing.image)}" alt="" loading="lazy" />`+ : `<div class="mwg-panel-fallback" style="background:linear-gradient(160deg,${accent},#0c0c0e)">${escapeHtml((listing.name || '?').charAt(0).toUpperCase())}</div>`;+ panel.innerHTML = `+ <div class="mwg-panel-media">+ ${media}+ <span class="mwg-panel-badge" style="background:${accent}">${TYPE_LABEL[listing.type] || ''}</span>+ </div>+ <div class="mwg-panel-body">+ <h2 class="mwg-panel-title">${escapeHtml(listing.name)}</h2>+ ${listing.author ? `<p class="mwg-panel-author">by ${escapeHtml(listing.author)}</p>` : ''}+ ${listing.description ? `<p class="mwg-panel-desc">${escapeHtml(listing.description)}</p>` : ''}+ <div class="mwg-panel-meta">+ <span class="mwg-panel-price" style="color:${accent}">${escapeHtml(listing.price)}</span>+ ${listing.category ? `<span class="mwg-panel-cat">${escapeHtml(listing.category)}</span>` : ''}+ </div>+ <button class="mwg-panel-cta" type="button" style="background:${accent}">View listing →</button>+ <p class="mwg-panel-hint">Press <kbd>E</kbd> to open</p>+ </div>`;+ panel.querySelector('.mwg-panel-cta')?.addEventListener('click', navigateActive);+ panel.setAttribute('data-show', '1');+ prompt.querySelector('.mwg-prompt-text').textContent = listing.name;+ prompt.setAttribute('data-show', '1');+ }++ function hidePanel() {+ panel.removeAttribute('data-show');+ prompt.removeAttribute('data-show');+ }++ async function setFilter(next) {+ if (next === filter) return;+ filter = next;+ for (const b of chips.children) b.setAttribute('aria-pressed', String(b.dataset.filter === filter));+ // Reset the stream and the hall, then rebuild from the live position.+ buffer = [];+ served = [];+ loadedAny = false;+ loadError = false;+ for (const k of Object.keys(sources)) {+ sources[k].cursor = null;+ sources[k].done = false;+ }+ setActive(null);+ for (let i = 0; i < slots.length; i++) {+ slots[i].listing = null;+ slots[i].group.visible = false;+ slots[i].group.position.z = -(START_Z + i * SPACING);+ slots[i].group.scale.setScalar(1);+ }+ belt.position.z = 0;+ hideToast();+ await loadPage();+ fillEmptySlots();+ }++ // ── Key intercept — E opens the active listing (capture phase so it wins over+ // the engine's snap-turn binding, but only while a listing is in reach). ──+ function onKeyDown(e) {+ if (!activeSlot) return;+ if (e.target?.tagName === 'INPUT' || e.target?.tagName === 'TEXTAREA') return;+ if (e.code === 'KeyE' || e.code === 'Enter') {+ e.preventDefault();+ e.stopImmediatePropagation();+ navigateActive();+ }+ }+ window.addEventListener('keydown', onKeyDown, true);++ // ── Boot ────────────────────────────────────────────────────────────────────+ for (let i = 0; i < SLOT_COUNT; i++) slots.push(buildSlot(i));+ loadPage().then(fillEmptySlots);++ return {+ update,+ destroy() {+ window.removeEventListener('keydown', onKeyDown, true);+ chips.remove();+ panel.remove();+ prompt.remove();+ toast.remove();+ scene.remove(belt);+ scene.remove(hall);+ },+ };+}++function escapeHtml(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]),+ );+}+function escapeAttr(s) {+ return escapeHtml(s);+}diff --git a/src/walk-voice-chat.js b/src/walk-voice-chat.jsnew file mode 100644index 000000000..64a1d821a--- /dev/null+++ b/src/walk-voice-chat.js@@ -0,0 +1,637 @@+// Two-way voice chat for the /walk avatar.+//+// Push-to-talk → the avatar listens, thinks, and talks back out loud:+//+// hold T / mic button ─▶ MicCapture (getUserMedia → 16 kHz WAV)+// release ─▶ POST /api/asr (NVIDIA Riva STT → transcript)+// ─▶ POST /api/chat (SSE) (persona + history → LLM reply)+// ─▶ POST /api/tts/speak (NVIDIA Magpie / OpenAI → audio)+// ─▶ Audio playback + LipsyncDriver (amplitude → jaw/visemes)+// + the `talking` gesture from the WalkGestures layer.+//+// Every leg is a real network call — no stubs, no fake audio. The class is+// self-contained: it builds nothing it can't tear down, holds the last ten+// turns so the conversation has memory, and degrades gracefully at every+// boundary (no mic, blocked permission, empty transcript, dead TTS lane).+//+// Wiring lives in walk.js (setupVoiceChat): it hands us closures onto the+// page's speech-bubble, chat-log, talking-overlay, persona, and multiplayer+// broadcast so this module never reaches into walk.js internals directly.++import { MicCapture } from './voice/mic-capture.js';+import { LipsyncDriver, tapAudioElement } from './voice/lipsync-driver.js';+import { AvatarMouthTarget } from './voice/avatar-morph-target.js';+import { log } from './shared/log.js';++const MAX_TURNS = 10; // user+assistant pairs retained for LLM context+const MAX_RECORD_MS = 20_000; // hard cap on a single push-to-talk hold+const MIN_RECORD_MS = 250; // ignore accidental taps shorter than this+const TTS_MAX_CHARS = 600; // keep spoken replies snappy; bubble shows the rest+const SPEAK_TIMEOUT_MS = 30_000; // safety net so the talking gesture always clears++// State → user-facing microcopy. The status line under the mic button reads+// each phase so the user always knows whether to keep talking or wait.+const STATUS = {+ idle: 'Hold to talk',+ listening: 'Listening…',+ transcribing: 'Hearing you…',+ thinking: 'Thinking…',+ speaking: 'Speaking…',+};++export class WalkVoiceChat {+ /**+ * @param {object} opts+ * @param {HTMLElement} opts.root Container holding the mic UI (#walk-voice).+ * @param {() => any} opts.getAvatar Returns the live avatar Object3D (for lipsync).+ * @param {() => object} opts.getPersona Returns { agentId, name, description, env }.+ * @param {() => string} opts.getUserName Returns the local player's display name.+ * @param {(text:string)=>void} opts.showBubble Float a speech bubble over the avatar.+ * @param {(on:boolean)=>void} opts.setTalking Toggle the looping talking gesture.+ * @param {(name:string,text:string,opts?:object)=>void} opts.addChatLog Append to the chat log.+ * @param {(text:string)=>void} [opts.broadcast] Mirror the avatar's line to other players.+ */+ constructor(opts = {}) {+ this.root = opts.root || null;+ this.getAvatar = opts.getAvatar || (() => null);+ this.getPersona = opts.getPersona || (() => ({}));+ this.getUserName = opts.getUserName || (() => 'you');+ this.showBubble = opts.showBubble || (() => {});+ this.setTalking = opts.setTalking || (() => {});+ this.addChatLog = opts.addChatLog || (() => {});+ this.broadcast = opts.broadcast || (() => {});++ this.voice = 'nova';+ this.history = []; // [{ role:'user'|'assistant', content }] — capped to MAX_TURNS pairs+ this.state = 'idle';+ this._busy = false; // a turn is mid-flight (STT→LLM→TTS)+ this._recordStart = 0;+ this._recordCap = null;+ this._mic = null;+ this._lipCtx = null; // shared AudioContext for TTS playback + lipsync analyser+ this._mouthTarget = null;+ this._mouthAttached = null; // last avatar we bound the mouth target to+ this._levelRaf = 0;+ this._levels = new Array(28).fill(0); // rolling waveform history+ this._destroyed = false;++ // DOM handles (resolved in mount()).+ this.btn = null;+ this.statusEl = null;+ this.waveCanvas = null;+ this.waveCtx = null;+ this.errorEl = null;+ }++ /** Build behavior over the markup in #walk-voice. No-op if it's absent. */+ mount() {+ if (!this.root) return;+ this.btn = this.root.querySelector('[data-voice-mic]');+ this.statusEl = this.root.querySelector('[data-voice-status]');+ this.waveCanvas = this.root.querySelector('[data-voice-wave]');+ this.errorEl = this.root.querySelector('[data-voice-error]');+ if (this.waveCanvas) this.waveCtx = this.waveCanvas.getContext('2d');++ if (!MicCapture.isSupported()) {+ // No mic path at all (insecure origin / unsupported browser). Surface it+ // once and disable the control rather than letting a press throw.+ this._showError(+ 'Voice chat needs a microphone on a secure (https) connection. Use the chat box instead.',+ false,+ );+ if (this.btn) {+ this.btn.disabled = true;+ this.btn.setAttribute('aria-disabled', 'true');+ }+ return;+ }++ this._setState('idle');+ this._bindButton();+ }++ // ── Push-to-talk plumbing ────────────────────────────────────────────────++ _bindButton() {+ if (!this.btn) return;+ // Pointer events cover mouse, touch, and pen with one path. We capture the+ // pointer so a release outside the button still ends the recording.+ const down = (e) => {+ if (this.btn.disabled) return;+ e.preventDefault();+ try {+ this.btn.setPointerCapture?.(e.pointerId);+ } catch {+ /* capture is best-effort */+ }+ this.startListening();+ };+ const up = (e) => {+ e.preventDefault();+ this.stopListening();+ };+ this.btn.addEventListener('pointerdown', down);+ this.btn.addEventListener('pointerup', up);+ this.btn.addEventListener('pointercancel', up);+ // Holding space/enter on a focused <button> would also fire click — swallow+ // it so keyboard users get push-to-talk via the global T key instead.+ this.btn.addEventListener('click', (e) => e.preventDefault());+ }++ /** Begin capturing. Idempotent; ignored while a turn is still processing. */+ async startListening() {+ if (this._destroyed || this._busy || this.state === 'listening') return;+ this._clearError();++ // Create + resume the playback context now, inside the user gesture, so the+ // reply can play later even though that happens after async STT/LLM.+ this._ensureAudioContext();++ this._mic = new MicCapture();+ try {+ await this._mic.start();+ } catch (err) {+ this._mic?.dispose();+ this._mic = null;+ this._handleMicError(err);+ return;+ }+ if (this._destroyed) {+ this._mic.dispose();+ this._mic = null;+ return;+ }++ this._recordStart = performance.now();+ this._setState('listening');+ this._startLevelMeter();+ // Auto-release on the hard cap so a stuck key never records forever.+ this._recordCap = setTimeout(() => this.stopListening(), MAX_RECORD_MS);+ }++ /** Stop capturing and run the turn. Safe to call when not recording. */+ async stopListening() {+ if (this.state !== 'listening' || !this._mic) return;+ clearTimeout(this._recordCap);+ this._recordCap = null;+ this._stopLevelMeter();++ const heldMs = performance.now() - this._recordStart;+ let wav = null;+ try {+ wav = await this._mic.stop();+ } catch (err) {+ log.warn('[voice-chat] mic stop failed:', err?.message);+ }+ this._mic.dispose();+ this._mic = null;++ if (heldMs < MIN_RECORD_MS || !wav || wav.size < 1024) {+ // A tap, not a phrase — quietly return to idle.+ this._setState('idle');+ return;+ }++ this._runTurn(wav).catch((err) => {+ log.warn('[voice-chat] turn failed:', err?.message);+ this._busy = false;+ this.setTalking(false);+ this._showError(err?.message || 'Something went wrong. Try again.', true);+ this._setState('idle');+ });+ }++ // ── The turn: STT → LLM → TTS ────────────────────────────────────────────++ async _runTurn(wav) {+ this._busy = true;+ this._setState('transcribing');++ const transcript = await this._transcribe(wav);+ if (this._destroyed) return;+ if (!transcript) {+ this._busy = false;+ this._showError("Didn't catch that — hold the button and speak again.", true);+ this._setState('idle');+ return;+ }++ // Echo what we heard into the chat log so the conversation has a transcript.+ this.addChatLog(this.getUserName() || 'you', transcript);+ this._pushHistory('user', transcript);++ this._setState('thinking');+ const reply = await this._chat(transcript);+ if (this._destroyed) return;+ if (!reply) {+ this._busy = false;+ this._showError('No reply came back. Try again.', true);+ this._setState('idle');+ return;+ }+ this._pushHistory('assistant', reply);++ await this.speak(reply);+ this._busy = false;+ if (this.state !== 'listening') this._setState('idle');+ }++ /** POST the captured WAV to the Riva ASR lane; returns trimmed transcript. */+ async _transcribe(wav) {+ const res = await fetch('/api/asr?language=en-US', {+ method: 'POST',+ headers: { 'content-type': 'audio/wav' },+ body: wav,+ });+ if (!res.ok) {+ if (res.status === 503) throw new Error('Speech-to-text is not available right now.');+ if (res.status === 429) throw new Error('Too many voice messages — give it a moment.');+ throw new Error(`Transcription failed (HTTP ${res.status}).`);+ }+ const data = await res.json().catch(() => ({}));+ return typeof data.text === 'string' ? data.text.trim() : '';+ }++ /**+ * Stream a reply from /api/chat using the avatar's persona + conversation+ * history. Reads the SSE body, accumulates chunks, and returns the final+ * `reply` (or the accumulated text if the stream ends without a done event).+ */+ async _chat(message) {+ const persona = this.getPersona() || {};+ const body = {+ message,+ history: this.history.slice(0, -1).slice(-MAX_TURNS * 2), // exclude the just-pushed turn+ context: persona.env ? { currentEnvironment: persona.env } : {},+ };+ if (persona.agentId) body.agentId = persona.agentId;+ else {+ const sys = buildPersonaPrompt(persona);+ if (sys) body.system_prompt = sys;+ }++ const res = await fetch('/api/chat', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ if (!res.ok || !res.body) {+ if (res.status === 429) throw new Error('Too many messages — give it a moment.');+ throw new Error(`Chat failed (HTTP ${res.status}).`);+ }++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ let accumulated = '';+ let finalReply = '';+ let streamError = '';++ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ // SSE frames are separated by a blank line.+ let sep;+ while ((sep = buffer.indexOf('\n\n')) !== -1) {+ const frame = buffer.slice(0, sep);+ buffer = buffer.slice(sep + 2);+ const line = frame.split('\n').find((l) => l.startsWith('data:'));+ if (!line) continue;+ const payload = line.slice(5).trim();+ if (!payload) continue;+ let evt;+ try {+ evt = JSON.parse(payload);+ } catch {+ continue;+ }+ if (evt.type === 'chunk' && typeof evt.text === 'string') {+ accumulated += evt.text;+ } else if (evt.type === 'done') {+ finalReply = (evt.reply || accumulated || '').trim();+ } else if (evt.type === 'error') {+ streamError = evt.message || 'stream error';+ }+ }+ }++ if (streamError && !finalReply && !accumulated) throw new Error(streamError);+ return (finalReply || accumulated).trim();+ }++ /**+ * Speak a line: bubble + chat log + talking gesture + real TTS with+ * audio-driven lipsync. Public so walk.say() can drive it directly+ * (the contract from the speech task: walk.say(text, { voice, gesture })).+ *+ * @param {string} text+ * @param {{voice?:boolean, gesture?:string|null}} [opts]+ */+ async speak(text, opts = {}) {+ const clean = String(text || '').trim();+ if (!clean) return;+ const useVoice = opts.voice !== false;+ const useGesture = opts.gesture !== null;++ const persona = this.getPersona() || {};+ this.showBubble(clean);+ this.addChatLog(persona.name || 'Avatar', clean, { self: true });+ this.broadcast(clean);+ if (useGesture) this.setTalking(true);+ this._setState('speaking');++ let spoke = false;+ if (useVoice) {+ try {+ await this._speakAloud(clean);+ spoke = true;+ } catch (err) {+ log.warn('[voice-chat] tts failed:', err?.message);+ }+ }+ // No audio (TTS down or muted)? Hold the bubble + gesture for a read-length+ // beat so the avatar still reacts — never a fake progress bar, just timing.+ if (!spoke) await wait(Math.min(6000, Math.max(1500, clean.length * 45)));++ if (useGesture) this.setTalking(false);+ }++ /** Fetch TTS audio and play it through the lipsync graph. */+ async _speakAloud(text) {+ const res = await fetch('/api/tts/speak', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ text: text.slice(0, TTS_MAX_CHARS), voice: this.voice, format: 'mp3' }),+ });+ if (!res.ok) throw new Error(`TTS failed (HTTP ${res.status})`);+ const blob = await res.blob();+ if (!blob || blob.size === 0) throw new Error('TTS returned no audio');+ const url = URL.createObjectURL(blob);+ try {+ await this._playWithLipsync(url);+ } finally {+ URL.revokeObjectURL(url);+ }+ }++ /**+ * Play a same-origin audio URL. When the rig can show mouth motion we route+ * playback through an AnalyserNode and drive { open, wide, round } onto its+ * morphs / jaw bone; otherwise we just play to the default output.+ */+ async _playWithLipsync(url) {+ const ctx = this._ensureAudioContext();+ const audio = new Audio();+ audio.src = url;+ audio.crossOrigin = 'anonymous';++ this._ensureMouthTarget();+ const canLipsync = ctx && this._mouthTarget?.hasAnyMouthDriver();+ let lip = null;+ let tap = null;++ try {+ if (canLipsync) {+ tap = tapAudioElement(audio, ctx);+ lip = new LipsyncDriver({ analyser: tap.analyser, target: this._mouthTarget });+ }+ await audio.play();+ lip?.start();+ } catch (err) {+ // MediaElementSource / autoplay can fail; fall back to a bare element so+ // the user still hears the reply.+ tap?.disconnect();+ tap = null;+ lip = null;+ try {+ await audio.play();+ } catch (playErr) {+ throw new Error(playErr?.message || 'audio playback blocked');+ }+ }++ await new Promise((resolve) => {+ let settled = false;+ const finish = () => {+ if (settled) return;+ settled = true;+ clearTimeout(safety);+ resolve();+ };+ const safety = setTimeout(finish, SPEAK_TIMEOUT_MS);+ audio.onended = finish;+ audio.onerror = finish;+ });++ lip?.stop();+ tap?.disconnect();+ }++ // ── Audio / lipsync helpers ──────────────────────────────────────────────++ _ensureAudioContext() {+ if (this._lipCtx) {+ if (this._lipCtx.state === 'suspended') this._lipCtx.resume().catch(() => {});+ return this._lipCtx;+ }+ const AC = window.AudioContext || window.webkitAudioContext;+ if (!AC) return null;+ try {+ this._lipCtx = new AC();+ if (this._lipCtx.state === 'suspended') this._lipCtx.resume().catch(() => {});+ } catch {+ this._lipCtx = null;+ }+ return this._lipCtx;+ }++ // Bind the mouth target to the current avatar, rebinding after a GLB swap.+ _ensureMouthTarget() {+ const av = this.getAvatar();+ if (!av) return;+ if (!this._mouthTarget) this._mouthTarget = new AvatarMouthTarget();+ if (this._mouthAttached !== av) {+ this._mouthTarget.attach(av);+ this._mouthAttached = av;+ }+ }++ // ── Live mic level meter (waveform) ──────────────────────────────────────++ _startLevelMeter() {+ this._levels.fill(0);+ const draw = () => {+ if (this.state !== 'listening') return;+ const level = this._mic ? this._mic.getLevel() : 0;+ this._levels.push(level);+ this._levels.shift();+ this._renderWave();+ this._levelRaf = requestAnimationFrame(draw);+ };+ this._levelRaf = requestAnimationFrame(draw);+ }++ _stopLevelMeter() {+ if (this._levelRaf) cancelAnimationFrame(this._levelRaf);+ this._levelRaf = 0;+ this._levels.fill(0);+ this._renderWave();+ }++ _renderWave() {+ const c = this.waveCanvas;+ const ctx = this.waveCtx;+ if (!c || !ctx) return;+ // Match the backing store to the displayed size (DPR-aware) once it's laid out.+ const dpr = Math.min(2, window.devicePixelRatio || 1);+ const w = c.clientWidth || 120;+ const h = c.clientHeight || 28;+ if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) {+ c.width = Math.round(w * dpr);+ c.height = Math.round(h * dpr);+ }+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.clearRect(0, 0, w, h);+ const n = this._levels.length;+ const gap = 2;+ const barW = Math.max(1.5, (w - gap * (n - 1)) / n);+ const mid = h / 2;+ ctx.fillStyle = '#fafafa';+ for (let i = 0; i < n; i++) {+ const lvl = this._levels[i];+ const bh = Math.max(2, lvl * (h - 2));+ const x = i * (barW + gap);+ const r = Math.min(barW / 2, 2);+ roundBar(ctx, x, mid - bh / 2, barW, bh, r);+ }+ }++ // ── State + error surface ────────────────────────────────────────────────++ _setState(state) {+ this.state = state;+ if (this.root) this.root.dataset.state = state;+ if (this.btn) {+ const recording = state === 'listening';+ this.btn.classList.toggle('is-recording', recording);+ const busy = state === 'transcribing' || state === 'thinking' || state === 'speaking';+ this.btn.classList.toggle('is-busy', busy);+ this.btn.setAttribute('aria-pressed', recording ? 'true' : 'false');+ }+ if (this.statusEl) this.statusEl.textContent = STATUS[state] || STATUS.idle;+ }++ _handleMicError(err) {+ const code = err?.code || '';+ if (code === 'permission-denied') {+ this._showError(+ 'Microphone blocked. Click the camera/mic icon in your address bar and choose Allow, then hold to talk again.',+ true,+ );+ } else if (code === 'no-mic') {+ this._showError('No microphone found. Plug one in, or use the chat box.', false);+ } else if (code === 'unsupported') {+ this._showError('Voice chat needs a secure (https) connection. Use the chat box instead.', false);+ } else {+ this._showError(err?.message || 'Could not start the microphone.', true);+ }+ this._setState('idle');+ }++ _showError(message, retryable) {+ if (!this.errorEl) {+ // Last resort if markup is missing — never swallow the failure silently.+ log.warn('[voice-chat]', message);+ return;+ }+ this.errorEl.innerHTML = '';+ const msg = document.createElement('span');+ msg.textContent = message;+ this.errorEl.appendChild(msg);+ if (retryable) {+ const retry = document.createElement('button');+ retry.type = 'button';+ retry.className = 'walk-voice-retry';+ retry.textContent = 'Try again';+ retry.addEventListener('click', () => {+ this._clearError();+ this.startListening();+ });+ this.errorEl.appendChild(retry);+ }+ this.errorEl.hidden = false;+ }++ _clearError() {+ if (this.errorEl) {+ this.errorEl.hidden = true;+ this.errorEl.innerHTML = '';+ }+ }++ // ── Conversation memory ──────────────────────────────────────────────────++ _pushHistory(role, content) {+ this.history.push({ role, content });+ // Keep the last MAX_TURNS exchanges (×2 messages).+ const max = MAX_TURNS * 2;+ if (this.history.length > max) this.history = this.history.slice(-max);+ }++ clearHistory() {+ this.history = [];+ }++ destroy() {+ this._destroyed = true;+ clearTimeout(this._recordCap);+ this._stopLevelMeter();+ try {+ this._mic?.dispose();+ } catch {+ /* already gone */+ }+ this._mic = null;+ this._mouthTarget?.dispose?.();+ this._mouthTarget = null;+ if (this._lipCtx && this._lipCtx.state !== 'closed') this._lipCtx.close().catch(() => {});+ this._lipCtx = null;+ }+}++// Build a system prompt for avatars that have no linked agent identity, so even+// a plain GLB answers in character instead of as a generic assistant.+function buildPersonaPrompt(persona) {+ const name = (persona?.name || '').trim();+ const desc = (persona?.description || '').trim();+ if (!name && !desc) {+ return (+ 'You are a friendly, expressive 3D avatar walking around a virtual world on three.ws, ' ++ 'talking with a visitor by voice. Keep replies warm, in-character, and short — one or ' ++ 'two sentences, spoken aloud, no markdown or lists.'+ );+ }+ let p = `You are ${name || 'an avatar'}, a 3D character a visitor is talking to by voice in a virtual world on three.ws.`;+ if (desc) p += ` Here is who you are: ${desc}.`;+ p +=+ ' Stay fully in character. Keep replies warm and short — one or two spoken sentences, ' ++ 'no markdown, no lists, no stage directions.';+ return p;+}++function roundBar(ctx, x, y, w, h, r) {+ const rad = Math.min(r, w / 2, h / 2);+ ctx.beginPath();+ ctx.moveTo(x + rad, y);+ ctx.arcTo(x + w, y, x + w, y + h, rad);+ ctx.arcTo(x + w, y + h, x, y + h, rad);+ ctx.arcTo(x, y + h, x, y, rad);+ ctx.arcTo(x, y, x + w, y, rad);+ ctx.closePath();+ ctx.fill();+}++function wait(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}diff --git a/src/walk.js b/src/walk.jsindex 3bd59dfd7..1cfba7d0c 100644--- a/src/walk.js+++ b/src/walk.js@@ -42,6 +42,7 @@ import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js'import nipplejs from 'nipplejs';import { AnimationManager } from './animation-manager.js';+import { AccessoryManager } from './agent-accessories.js';import { WalkGestures, GESTURE_ORDER } from './walk-gestures.js';import { WalkNet } from './walk-net.js';import { applyLoadout } from './game/cosmetics-loadout.js';@@ -74,6 +75,20 @@ const AVATAR_URL_DEFAULT = '/avatars/default.glb';// avatar — and (b) short-circuit remote avatar loads that match ours.let resolvedAvatarUrl = AVATAR_URL_DEFAULT;+// The resolved avatar record (id, name, description, agent_id) from+// /api/avatars/<id>, captured by resolveAvatarUrl so the voice-chat layer can+// answer in the avatar's persona. Null for the default avatar or a direct URL.+let avatarMeta = null;++// When the page is opened as an avatar-editor draft preview+// (?avatar=<draftId>&preview=true), the unsaved appearance to apply on top of+// the base GLB once it loads. Stashed by resolveAvatarUrl, consumed in loadAvatar.+let pendingDraftAppearance = null;+// True for a draft preview — run solo (no multiplayer broadcast of a throwaway+// presigned URL) and skip the player's own equipped cosmetics so the creator+// sees exactly the look they're editing.+let isDraftPreview = false;+async function resolveAvatarUrl() {const params = new URLSearchParams(location.search);// A direct GLB/VRM URL wins — this is what the /communities lobby passes when@@ -88,10 +103,23 @@ async function resolveAvatarUrl() {resolvedAvatarUrl = AVATAR_URL_DEFAULT;return AVATAR_URL_DEFAULT;}+ // Editor draft preview: resolve the unsaved look through the draft endpoint —+ // the base (unbaked) GLB plus an appearance overlay we apply client-side.+ if (params.get('preview') === 'true' || params.get('preview') === '1') {+ isDraftPreview = true;+ const dres = await fetch(`/api/avatars/draft/${encodeURIComponent(id)}`);+ if (!dres.ok) throw new Error(`draft ${id} not found (HTTP ${dres.status})`);+ const { draft } = await dres.json();+ if (!draft?.base_model_url) throw new Error(`draft ${id} has no model URL`);+ pendingDraftAppearance = draft.appearance || null;+ resolvedAvatarUrl = draft.base_model_url;+ return draft.base_model_url;+ }const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`);if (!res.ok) throw new Error(`avatar ${id} not found (HTTP ${res.status})`);const { avatar } = await res.json();if (!avatar?.url) throw new Error(`avatar ${id} has no GLB URL`);+ avatarMeta = avatar;resolvedAvatarUrl = avatar.url;return avatar.url;}@@ -1416,11 +1444,24 @@ async function loadAvatar() {initialStyle: trailSetting.get(),});+ // Editor draft preview: dress the base GLB in the unsaved appearance the+ // creator is editing (outfit, accessories, sculpt morphs, garment layers).+ // Shares the AccessoryManager the editor uses, so the look is pixel-identical.+ if (pendingDraftAppearance) {+ try {+ const draftAccessories = new AccessoryManager({ content: avatar, invalidate: () => {} });+ await draftAccessories.hydrateFromAppearance(pendingDraftAppearance);+ } catch (err) {+ log.warn('[walk] draft appearance apply failed:', err?.message);+ }+ }+// Dress the local avatar in the loadout the player last equipped (R23). The// equipped fit is persisted to their account in /play and mirrored to the// cross-world cc-cosmetics store, so the same wardrobe rides into /walk. Reuses// the shared applyLoadout, so a hat or aura renders identically in both worlds.- applyLocalCosmetics(getPlayCosmetics());+ // Skipped in draft preview so the creator sees only the look they're editing.+ if (!isDraftPreview) applyLocalCosmetics(getPlayCosmetics());animationManager.attach(avatar);@@ -3215,6 +3256,9 @@ function setOnlineStatus(status) {}function startNet() {+ // Draft previews run solo — never broadcast a throwaway, soon-to-expire+ // presigned GLB into a live room where peers would fail to load it.+ if (isDraftPreview) return;if (!avatarTemplate || !animationDefs) return;if (net) return;const stored = getStoredName();diff --git a/src/widget-types.js b/src/widget-types.jsindex fa358b03a..ede17c484 100644--- a/src/widget-types.js+++ b/src/widget-types.js@@ -62,8 +62,35 @@ export const WIDGET_TYPES = {status: 'ready',icon: '◭',},+ 'walking-avatar': {+ label: 'Walking Avatar',+ desc: 'A roaming 3D avatar visitors can walk around your page — joystick or keyboard.',+ status: 'ready',+ icon: '🚶',+ },};+// Size presets for the walking-avatar embed frame. Shared by the Studio editor+// and the widget client so the published snippet matches the preview. Walking+// needs horizontal room, so presets lean landscape.+export const WALK_SIZE_PRESETS = Object.freeze({+ S: { width: 360, height: 320 },+ M: { width: 480, height: 420 },+ L: { width: 720, height: 560 },+});++// The environments the walk-embed runtime can actually render (mirrors ENV_IDS+// in src/walk-embed-events.js). Kept here so the Studio picker only offers+// environments the embed understands.+export const WALK_ENVIRONMENTS = Object.freeze([+ ['studio', 'Studio'],+ ['void', 'Void'],+ ['beach', 'Beach'],+ ['sunset', 'Sunset'],+ ['night', 'Night'],+ ['grid', 'Grid'],+]);+export const WIDGET_TYPE_KEYS = Object.keys(WIDGET_TYPES);export const BRAND_DEFAULTS = Object.freeze({