Skip to content

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

feat: walk.js + walk-embed expansion, avatar action API, app-next, extension content

nirholaseef3297710c3
diff --git a/api/avatars/[id]/[action].js b/api/avatars/[id]/[action].js
index 0318f0603..4e5cbbd28 100644
--- a/api/avatars/[id]/[action].js
+++ b/api/avatars/[id]/[action].js
@@ -41,6 +41,8 @@ export default wrap(async (req, res) => {
switch (action) {
case 'agents':
return handleAgentsByAvatar(req, res);
+ case 'glb':
+ return handleGlb(req, res);
case 'glb-versions':
return handleGlbVersions(req, res);
case 'pin-ipfs':
@@ -555,3 +557,85 @@ function redirect(res, url) {
res.setHeader('cache-control', 'public, max-age=60, s-maxage=300');
res.end();
}
+
+// ── glb (same-origin CORS-friendly proxy) ─────────────────────────────────
+// GET /api/avatars/:id/glb — streams the avatar's GLB through the API so
+// hosts on any origin can fetch it without R2 CORS configuration. The R2
+// public domain serves `Access-Control-Allow-Origin: https://three.ws` only,
+// which breaks the embed SDK when dropped on third-party sites and the
+// /walk-embed page when loaded from a dev host. Routing the bytes through
+// this endpoint side-steps that — we attach `Access-Control-Allow-Origin: *`
+// because the underlying GLBs are already publicly readable on the CDN.
+//
+// Permission rules mirror handleThumbnail:
+// • public + unlisted: anyone
+// • private: owner only (session or bearer with avatars:read)
+// • demo avatars: 302 to the bundled GLB url
+async function handleGlb(req, res) {
+ // Reply with CORS for all origins. Browsers also need the preflight,
+ // which the shared `cors()` helper doesn't open up to wildcard origins,
+ // so we set the headers directly.
+ res.setHeader('access-control-allow-origin', '*');
+ res.setHeader('access-control-allow-methods', 'GET,OPTIONS');
+ res.setHeader('access-control-allow-headers', 'range,accept');
+ res.setHeader('access-control-expose-headers', 'content-length,content-range,etag');
+ if (req.method === 'OPTIONS') { res.statusCode = 204; return res.end(); }
+ if (!method(req, res, ['GET'])) return;
+
+ const id =
+ req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
+ if (!id) return error(res, 400, 'invalid_request', 'avatar id required');
+
+ if (String(id).startsWith('avatar_demo_')) {
+ const demo = DEMO_AVATARS.find((a) => a.avatarId === id);
+ if (!demo?.url) return error(res, 404, 'not_found', 'demo avatar has no glb');
+ // Demo avatars live in /public so the redirect target is same-origin
+ // and already CORS-clean.
+ return redirect(res, demo.url);
+ }
+
+ const avatar = await getAvatar({ id, requesterId: null });
+ if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
+
+ if (avatar.visibility === 'private') {
+ const auth = await resolveVersionsAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ if (auth.userId !== avatar.owner_id) return error(res, 403, 'forbidden', 'not your avatar');
+ }
+
+ // Resolve the same R2 key the canonical avatar URL serves. Streaming
+ // from R2 directly with the S3 SDK avoids a second hop through the
+ // public CDN — and gives us a Node readable stream we can pipe straight
+ // into res with no buffer-the-whole-thing memory blow-up.
+ const key = avatar.baked_storage_key && avatar.appearance_hash
+ ? (avatar.baked_storage_key)
+ : avatar.storage_key;
+ if (!key) return error(res, 404, 'not_found', 'avatar has no glb');
+
+ try {
+ const { Body, ContentLength, ETag } = await r2.send(
+ new GetObjectCommand({ Bucket: env.S3_BUCKET, Key: key }),
+ );
+ res.statusCode = 200;
+ res.setHeader('content-type', 'model/gltf-binary');
+ if (ContentLength != null) res.setHeader('content-length', String(ContentLength));
+ if (ETag) res.setHeader('etag', ETag);
+ // GLBs are content-addressed by key (rotation produces a new key), so
+ // long-cache the bytes — clients revalidate via the avatar metadata
+ // endpoint, not by re-hitting /glb.
+ res.setHeader('cache-control', 'public, max-age=300, s-maxage=86400, immutable');
+ Body.pipe(res);
+ Body.on('error', (err) => {
+ console.error('[avatars/glb] stream error:', err);
+ try { res.destroy(err); } catch {}
+ });
+ } catch (err) {
+ // 404 if R2 doesn't know the key (deleted out-of-band); 502 otherwise.
+ const code = err?.Code || err?.name;
+ if (code === 'NoSuchKey' || code === 'NotFound') {
+ return error(res, 404, 'not_found', 'avatar glb missing from storage');
+ }
+ console.error('[avatars/glb] r2 fetch failed:', err);
+ return error(res, 502, 'upstream_error', 'failed to fetch avatar glb');
+ }
+}
diff --git a/api/discover-detail.js b/api/discover-detail.js
index bda6bc83c..ea969a77a 100644
--- a/api/discover-detail.js
+++ b/api/discover-detail.js
@@ -132,7 +132,7 @@ export default wrap(async (req, res) => {
}
if (item) {
- canonicalUrl = `${origin}/discover/avatar/${id}`;
+ canonicalUrl = `${origin}/avatars/${id}`;
ogImageUrl = `${origin}/api/avatar/${id}/og`;
}
}
diff --git a/extensions/walk-avatar/content.js b/extensions/walk-avatar/content.js
index 6a4238fe2..22b8c118b 100644
--- a/extensions/walk-avatar/content.js
+++ b/extensions/walk-avatar/content.js
@@ -1,6 +1,8 @@
// content.js — injected into pages to mount the walking avatar iframe.
// Handles: mounting, dragging, close, SPA navigation survival, postMessage relay.
+import { Narrator } from './narrator.js';
+
(function () {
'use strict';
@@ -222,13 +224,46 @@
// Avatar survives popstate naturally.
});
+ // ── Narrator ──────────────────────────────────────────────────────────
+ let narrator = null;
+
+ function initNarrator(settings) {
+ if (!settings?.narrationEnabled) return;
+ if (narrator) return;
+ narrator = new Narrator({
+ getIframe: () => iframe,
+ getSession: () => {
+ // Session is accessed async but cached here for sync use
+ return contentSession;
+ },
+ getSettings: () => {
+ return syncSettings;
+ },
+ });
+ narrator.start();
+ }
+
+ // Cache settings/session for narrator access
+ let contentSession = null;
+ let syncSettings = {};
+ chrome.storage.local.get('threews_session', ({ threews_session }) => {
+ contentSession = threews_session || null;
+ });
+ chrome.storage.sync.get(null, (s) => {
+ syncSettings = s || {};
+ });
+
// ── Message listener from background / popup ──────────────────────────
chrome.runtime.onMessage.addListener((msg) => {
if (msg.type === 'walk:mount') {
chrome.storage.sync.get(null, (settings) => {
+ syncSettings = settings;
mount(msg.avatarId || settings.avatarId, settings);
+ initNarrator(settings);
});
} else if (msg.type === 'walk:unmount') {
+ narrator?.stop();
+ narrator = null;
unmount();
} else if (msg.type === 'walk:setAvatar') {
if (iframe) {
@@ -238,6 +273,10 @@
if (iframe) {
iframe.contentWindow?.postMessage({ type: 'walk:config', speed: msg.speed }, THREEWS);
}
+ } else if (msg.type === 'walk:muteNarration') {
+ narrator?.mute();
+ } else if (msg.type === 'walk:unmuteNarration') {
+ narrator?.unmute();
}
});
})();
diff --git a/pages/app-next.html b/pages/app-next.html
index 2bc9aa59f..5cfceb6e1 100644
--- a/pages/app-next.html
+++ b/pages/app-next.html
@@ -3,16 +3,48 @@
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <title>three.ws — app-next (UX preview)</title>
+ <title>three.ws — AI-Powered 3D Model Viewer</title>
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
/>
- <meta name="robots" content="noindex" />
+ <meta name="author" content="nirholas" />
+ <meta
+ name="description"
+ content="The first embodied 3D AI agent. Not a chatbot. A presence — with a body, a place, an identity, and memory."
+ />
+ <meta
+ name="keywords"
+ content="three.ws, AI agent, embodied AI, glTF viewer, GLB viewer, 3D model viewer, WebGL, three.js, ERC-8004, agent identity"
+ />
<meta name="theme-color" content="#06070a" />
- <link rel="canonical" href="https://three.ws/app-next" />
+ <!-- Open Graph -->
+ <meta property="og:type" content="website" />
+ <meta property="og:title" content="three.ws — The First Embodied AI Agent" />
+ <meta
+ property="og:description"
+ content="Agents have always been imagined as present. We made that real."
+ />
+ <meta property="og:url" content="https://three.ws/app" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:image" content="https://three.ws/assets/og-image.png">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+
+ <!-- Twitter / X -->
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="three.ws — Embodied AI" />
+ <meta
+ name="twitter:description"
+ content="The first three.ws with a body, a place, an identity, and memory."
+ />
+ <meta name="twitter:creator" content="@nichxbt" />
+ <meta name="twitter:image" content="https://three.ws/assets/og-image.png">
+
+ <link rel="canonical" href="https://three.ws/app" />
<link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="apple-touch-icon" href="/pwa-192x192.png" />
<link rel="stylesheet" href="/style.css" />
<link rel="stylesheet" href="/fonts/fonts.css" />
<link rel="stylesheet" href="/app-next.css" />
@@ -114,7 +146,7 @@
<a href="/studio" role="menuitem">Studio</a>
<a href="/docs" role="menuitem">Docs</a>
<div class="nxt-more-sep" role="separator"></div>
- <a href="/app" role="menuitem">Open classic viewer</a>
+ <a href="/app-classic" role="menuitem">Classic viewer</a>
</div>
<!-- Auth surface — single pill, swaps to user chip when signed in -->
@@ -145,6 +177,77 @@
<!-- Main viewer surface — full bleed, the avatar IS the page -->
<main class="wrap nxt-main">
+ <!-- Auth gate — shown only to anonymous visitors -->
+ <aside class="auth-gate" id="auth-gate">
+ <div class="auth-gate__inner">
+ <div class="auth-gate__eyebrow">
+ <svg class="auth-gate__lock" aria-hidden="true" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <rect x="3" y="11" width="18" height="11" rx="2" />
+ <path d="M7 11V7a5 5 0 0 1 10 0v4" />
+ </svg>
+ <span>Unlock the agent</span>
+ </div>
+ <h2 class="auth-gate__title">Your agent lives here</h2>
+ <p class="auth-gate__desc">
+ Sign in to access animations, scene controls, and your agent's on-chain
+ identity, memory, and skills.
+ </p>
+ <div class="auth-gate__actions">
+ <a class="auth-gate__btn auth-gate__btn--primary" href="/login">Sign in</a>
+ <a class="auth-gate__btn" href="/register">Create account</a>
+ </div>
+ <ul class="auth-gate__perks">
+ <li>Animations &amp; presence controls</li>
+ <li>Save avatars to your account</li>
+ <li>Register on-chain agent identity</li>
+ <li>Scene, lighting &amp; material editor</li>
+ </ul>
+ </div>
+ </aside>
+
+ <!-- Post-creation onboarding banner — shown once after creating an agent -->
+ <aside
+ class="agent-onboarding"
+ id="agent-onboarding"
+ role="dialog"
+ aria-labelledby="agent-onboarding-title"
+ hidden
+ >
+ <div class="agent-onboarding__inner">
+ <button
+ class="agent-onboarding__close"
+ id="agent-onboarding-close"
+ type="button"
+ aria-label="Dismiss welcome message"
+ >
+ ×
+ </button>
+ <h2 class="agent-onboarding__title" id="agent-onboarding-title">
+ Your agent is ready 🎉
+ </h2>
+ <p class="agent-onboarding__desc">
+ This is your agent's studio. Try an animation from the chips below, drop a
+ new GLB to swap its body, or publish it on-chain so anyone can find and
+ embed it.
+ </p>
+ <div class="agent-onboarding__actions">
+ <a
+ class="agent-onboarding__btn agent-onboarding__btn--primary"
+ href="/deploy"
+ id="agent-onboarding-deploy"
+ >Deploy on-chain →</a
+ >
+ <a
+ class="agent-onboarding__btn"
+ id="agent-onboarding-share"
+ target="_blank"
+ rel="noopener noreferrer"
+ >View public profile</a
+ >
+ </div>
+ </div>
+ </aside>
+
<!-- The 3D viewer (required by app.js) -->
<div class="viewer-container nxt-viewer" id="viewer-container"></div>
diff --git a/pages/home-v3.html b/pages/home-v3.html
index 821bb0049..b649ba143 100644
--- a/pages/home-v3.html
+++ b/pages/home-v3.html
@@ -898,15 +898,16 @@
currentSrc = src;
chipsEl.innerHTML = '';
viewer.loadModel(src, { autoPlay: true }).then(function () {
- var clips = viewer.getClipNames ? viewer.getClipNames() : [];
- clips.forEach(function (name) {
+ var clips = viewer.listAvailableClips();
+ clips.forEach(function (clip) {
var btn = document.createElement('button');
btn.className = 'anim-chip';
- btn.textContent = name;
+ btn.textContent = clip.label || clip.name;
+ btn.dataset.clipName = clip.name;
btn.addEventListener('click', function () {
document.querySelectorAll('.anim-chip').forEach(function (c) { c.classList.remove('active'); });
btn.classList.add('active');
- viewer.playClip(name).catch(function () {});
+ viewer.playClip(clip.name).catch(function () {});
});
chipsEl.appendChild(btn);
});
diff --git a/public/next/index.html b/public/next/index.html
index 2917c34c3..101794894 100644
--- a/public/next/index.html
+++ b/public/next/index.html
@@ -336,7 +336,7 @@
<p class="sec-p">Every piece is open, real, and shipping today. Use one. Use all. They compose.</p>
<div class="stack">
- <a href="/character-studio" class="stack-row">
+ <a href="/studio" class="stack-row">
<div class="n">01</div><div class="t">studio</div>
<div class="d">Selfie to rigged avatar in seconds. Browser-native, GPU-accelerated.</div><div class="a">↗</div>
</a>
@@ -416,7 +416,7 @@
<section class="end">
<div class="big">ship a body.</div>
<div class="cta-row" style="justify-content:center;">
- <a class="cta" href="/character-studio">Open Studio</a>
+ <a class="cta" href="/studio">Open Studio</a>
<a class="cta-ghost" href="/docs">Read Docs</a>
</div>
</section>
@@ -425,7 +425,7 @@
<div>three.ws · the 3d layer · 2026</div>
<div class="links">
<a href="/discover">registry</a>
- <a href="/character-studio">studio</a>
+ <a href="/studio">studio</a>
<a href="/embed/v1/preview">embed</a>
<a href="/docs">docs</a>
<a href="/blog">blog</a>
diff --git a/scripts/build-extension.mjs b/scripts/build-extension.mjs
index f1dfca9fb..485cbb17a 100644
--- a/scripts/build-extension.mjs
+++ b/scripts/build-extension.mjs
@@ -36,7 +36,6 @@ await Promise.all([
minify: isProd,
sourcemap: !isProd,
target: 'chrome109',
- // Exclude chrome API from bundle — it's injected by the browser
external: ['chrome'],
}),
build({
diff --git a/src/account.js b/src/account.js
index 28be4ac9b..9b137727c 100644
--- a/src/account.js
+++ b/src/account.js
@@ -2,98 +2,13 @@
// Keeps the UI code in app.js/avatar-creator.js clean.
import { identifyUser, resetIdentity } from './analytics.js';
+import { apiFetch, consumeCsrfToken } from './api.js';
-const API = ''; // same origin
-
-// Single-use CSRF token: fetched lazily, burned by the server on consumption.
-// Re-issued on the next mutating call. Matches the dashboard's pattern so any
-// page using apiFetch gets CSRF-gated endpoints (PUT/PATCH/DELETE on agents,
-// keys, withdrawals, marketplace, etc.) for free.
-let _csrfToken = null;
-async function getCsrfToken() {
- if (_csrfToken) return _csrfToken;
- const r = await fetch('/api/csrf-token', { credentials: 'include' });
- if (!r.ok) return null;
- const j = await r.json().catch(() => null);
- _csrfToken = j?.data?.token || null;
- return _csrfToken;
-}
-
-const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
-const TRANSIENT_STATUSES = new Set([502, 503, 504]);
-
-// Wrapped fetch that handles expired sessions centrally. A 401 response is
-// treated as a session-expiry signal and redirects to /login?next=<current>
-// with the URL hash preserved (SPAs lose it on a naked location.href hop).
-// Pass allowAnonymous:true for endpoints where a 401 is a legitimate
-// "not signed in" answer the caller wants to inspect itself (e.g. /api/auth/me).
-//
-// Safe-method requests retry once on transient 5xx / network failures —
-// Vercel cold starts and dev-server restarts surface as 502s, and a silent
-// second attempt hides the blip. Mutating methods don't retry: the body is
-// already on the wire and the server may have processed it.
-export async function apiFetch(path, options = {}) {
- const { allowAnonymous = false, ...init } = options;
- const method = (init.method || 'GET').toUpperCase();
- const canRetry = SAFE_METHODS.has(method);
-
- // Mutating same-origin requests need a CSRF token. Skip for bearer-auth
- // callers — the server exempts Authorization: Bearer requests.
- const headers = new Headers(init.headers || {});
- const hasBearer = (headers.get('authorization') || '').startsWith('Bearer ');
- if (!SAFE_METHODS.has(method) && !hasBearer) {
- const token = await getCsrfToken();
- if (token) headers.set('x-csrf-token', token);
- _csrfToken = null;
- }
-
- const doFetch = () =>
- fetch(path, {
- credentials: 'include',
- ...init,
- headers,
- });
-
- // Two retries with 400ms → 1.2s backoff for safe methods. Covers a Vercel
- // cold start (~600ms) plus one transient proxy blip; non-mutating so re-
- // firing is free. Mutating methods (POST/PUT) never retry — the body is
- // already on the wire and the server may have committed it.
- let res;
- let lastErr;
- const maxAttempts = canRetry ? 3 : 1;
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
- if (attempt > 0) {
- await new Promise((r) => setTimeout(r, 400 * attempt * attempt));
- }
- try {
- res = await doFetch();
- } catch (networkErr) {
- lastErr = networkErr;
- res = undefined;
- continue;
- }
- if (canRetry && TRANSIENT_STATUSES.has(res.status)) continue;
- break;
- }
- if (!res) throw lastErr;
-
- if (res.status === 401 && !allowAnonymous) {
- redirectToLogin();
- const err = new Error('session expired');
- err.status = 401;
- err.redirected = true;
- throw err;
- }
- return res;
-}
+// Re-export for back-compat — many modules still `import { apiFetch } from
+// './account.js'`. New code should import from './api.js' directly.
+export { apiFetch };
-function redirectToLogin() {
- if (typeof location === 'undefined') return;
- // Don't loop if we're already on the login page.
- if (/^\/login(\/|$|\?)/.test(location.pathname)) return;
- const next = location.pathname + location.search + location.hash;
- location.href = '/login?next=' + encodeURIComponent(next);
-}
+const API = ''; // same origin
// Optimistic auth hint — non-authoritative, used only for first-paint gating
// on the viewer. The real session cookie is HttpOnly so we can't read it
@@ -564,8 +479,7 @@ async function uploadViaProxy({ blob, contentType, checksum, onProgress, signal
if (signal?.aborted) {
throw stageError('upload', 'Upload aborted', { code: 'upload_aborted' });
}
- const csrf = await getCsrfToken();
- _csrfToken = null; // single-use, like apiFetch
+ const csrf = await consumeCsrfToken();
const qs = new URLSearchParams({ content_type: contentType });
if (checksum) qs.set('sha256', checksum);
const url = `${API}/api/avatars/upload?${qs.toString()}`;
diff --git a/src/agent-edit.js b/src/agent-edit.js
index 11cd3f7eb..ff04ff1ca 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -1,36 +1,10 @@
import { AvatarCreator } from './avatar-creator.js';
import { saveRemoteGlbToAccount } from './account.js';
+import { apiFetch } from './api.js';
const API_BASE = '/api';
const params = new URLSearchParams(location.search);
-// CSRF — server enforces a single-use double-submit token on every session-
-// cookie mutation (PUT/POST/PATCH/DELETE). Fetch a fresh token per request;
-// the server burns it after one use, so caching breaks the next mutation.
-async function _csrfToken() {
- try {
- const r = await fetch(`${API_BASE}/csrf-token`, { credentials: 'include' });
- if (!r.ok) return null;
- const j = await r.json();
- return j?.data?.token || null;
- } catch {
- return null;
- }
-}
-
-// Drop-in replacement for fetch() that auto-attaches the CSRF header on any
-// non-safe method. Every fetch in this module that targets ${API_BASE} should
-// use this helper; raw fetch() bypasses CSRF and the server returns 403.
-async function apiFetch(url, init = {}) {
- const method = (init.method || 'GET').toUpperCase();
- const headers = new Headers(init.headers || {});
- if (method !== 'GET' && method !== 'HEAD') {
- const token = await _csrfToken();
- if (token) headers.set('x-csrf-token', token);
- }
- return fetch(url, { credentials: 'include', ...init, headers });
-}
-
// Resolve agent id from the canonical clean URL /agent/<uuid>(/edit)?, falling
// back to the legacy /agent-edit.html?id=<uuid> querystring form. Kept as a
// `let` so it can be reassigned after the create-from-avatar flow mints a real
diff --git a/src/api.js b/src/api.js
new file mode 100644
index 000000000..f911e8b69
--- /dev/null
+++ b/src/api.js
@@ -0,0 +1,97 @@
+// Shared HTTP client for the three.ws frontend.
+//
+// Single source of truth for:
+// • CSRF token issuance (single-use, server-burned)
+// • session-cookie mutation gating (PUT/POST/PATCH/DELETE auto-carry x-csrf-token)
+// • transient 5xx retry on safe methods
+// • 401 → /login?next=… redirect
+//
+// Every page that talks to /api MUST import apiFetch from here. The ESLint
+// rule no-restricted-syntax in .eslintrc blocks raw `fetch(`${API_BASE}…`)` to
+// prevent the kind of drift that left agent-edit.js without CSRF and silently
+// 403'ing every save until a user complained.
+
+const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
+const TRANSIENT_STATUSES = new Set([502, 503, 504]);
+
+// Single-use CSRF token, refetched after each mutation. The server enforces
+// one-shot consumption (api/_lib/csrf.js), so caching past a single use
+// guarantees the next mutation 403s with csrf_invalid.
+let _csrfToken = null;
+async function getCsrfToken() {
+ if (_csrfToken) return _csrfToken;
+ const r = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!r.ok) return null;
+ const j = await r.json().catch(() => null);
+ _csrfToken = j?.data?.token || null;
+ return _csrfToken;
+}
+
+// Exposed for the rare caller that can't go through apiFetch — e.g. an XHR
+// upload that needs upload-progress events. Hand it the token, attach the
+// x-csrf-token header yourself, and the server will accept it. Token is
+// single-use, so don't reuse the returned string for a second request.
+export async function consumeCsrfToken() {
+ const token = await getCsrfToken();
+ _csrfToken = null;
+ return token;
+}
+
+function redirectToLogin() {
+ if (typeof location === 'undefined') return;
+ if (/^\/login(\/|$|\?)/.test(location.pathname)) return;
+ const next = location.pathname + location.search + location.hash;
+ location.href = '/login?next=' + encodeURIComponent(next);
+}
+
+// Drop-in fetch replacement. Pass allowAnonymous:true on endpoints where a
+// 401 is a legitimate answer the caller wants to inspect itself (e.g.
+// /api/auth/me on first paint).
+export async function apiFetch(path, options = {}) {
+ const { allowAnonymous = false, ...init } = options;
+ const method = (init.method || 'GET').toUpperCase();
+ const canRetry = SAFE_METHODS.has(method);
+
+ const headers = new Headers(init.headers || {});
+ const hasBearer = (headers.get('authorization') || '').startsWith('Bearer ');
+ if (!SAFE_METHODS.has(method) && !hasBearer) {
+ const token = await getCsrfToken();
+ if (token) headers.set('x-csrf-token', token);
+ _csrfToken = null;
+ }
+
+ const doFetch = () =>
+ fetch(path, {
+ credentials: 'include',
+ ...init,
+ headers,
+ });
+
+ let res;
+ let lastErr;
+ const maxAttempts = canRetry ? 3 : 1;
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
+ if (attempt > 0) {
+ await new Promise((r) => setTimeout(r, 400 * attempt * attempt));
+ }
+ try {
+ res = await doFetch();
+ } catch (networkErr) {
+ lastErr = networkErr;
+ res = undefined;
+ continue;
+ }
+ if (canRetry && TRANSIENT_STATUSES.has(res.status)) continue;
+ break;
+ }
+ if (!res) throw lastErr;
+
+ if (res.status === 401 && !allowAnonymous) {
+ redirectToLogin();
+ const err = new Error('session expired');
+ err.status = 401;
+ err.redirected = true;
+ throw err;
+ }
+ return res;
+}
diff --git a/src/walk-embed.js b/src/walk-embed.js
index 4b3dc931a..750287d13 100644
--- a/src/walk-embed.js
+++ b/src/walk-embed.js
@@ -236,6 +236,7 @@ const input = {
keys: { forward: 0, back: 0, left: 0, right: 0, run: false },
joy: { x: 0, y: 0, active: false },
autoplay: { active: false, t: 0 },
+ _speedMultiplier: 1.0,
};
if (CONTROLS === 'keyboard' || CONTROLS === 'joystick') {
@@ -396,7 +397,7 @@ function tick() {
const mag = Math.min(1, Math.hypot(ix, iy));
const wantRun = mag > 0.9 || input.keys.run;
- const speed = mag * (wantRun ? RUN_SPEED : WALK_SPEED);
+ const speed = mag * (wantRun ? RUN_SPEED : WALK_SPEED) * (input._speedMultiplier || 1.0);
if (mag > 0.01 && avatar) {
moveForward.copy(camLookCurrent).sub(camera.position);
@@ -533,9 +534,83 @@ window.addEventListener('message', async (e) => {
avatarYaw = 0;
avatarRig.quaternion.setFromAxisAngle(upY, 0);
applyCameraImmediate();
+ } else if (msg.type === 'walk:narrate' && typeof msg.text === 'string') {
+ // Show a DOM speech bubble above the avatar for the narration text.
+ showSpeechBubble(msg.text);
+ } else if (msg.type === 'walk:narrateEnd') {
+ hideSpeechBubble();
+ } else if (msg.type === 'walk:config') {
+ if (typeof msg.speed === 'number') {
+ // Walk speed multiplier — applied to input magnitude each frame
+ input._speedMultiplier = Math.max(0.3, Math.min(3, msg.speed));
+ }
}
});
+// ── Speech bubble (DOM overlay) ───────────────────────────────────────────
+let bubbleEl = null;
+let bubbleHideTimer = null;
+
+function ensureBubble() {
+ if (bubbleEl) return bubbleEl;
+ bubbleEl = document.createElement('div');
+ bubbleEl.style.cssText = `
+ position: fixed;
+ left: 50%;
+ bottom: 180px;
+ transform: translateX(-50%);
+ max-width: 280px;
+ background: rgba(10,10,10,0.88);
+ color: #fafafa;
+ font-family: Inter, system-ui, sans-serif;
+ font-size: 13px;
+ line-height: 1.45;
+ padding: 10px 14px;
+ border-radius: 14px;
+ border: 1px solid rgba(255,255,255,0.12);
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ pointer-events: none;
+ z-index: 10;
+ opacity: 0;
+ transition: opacity 0.25s ease;
+ word-break: break-word;
+ `;
+ // Pointer triangle
+ const tri = document.createElement('div');
+ tri.style.cssText = `
+ position: absolute;
+ bottom: -7px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 0;
+ height: 0;
+ border-left: 7px solid transparent;
+ border-right: 7px solid transparent;
+ border-top: 7px solid rgba(10,10,10,0.88);
+ `;
+ bubbleEl.appendChild(tri);
+ document.body.appendChild(bubbleEl);
+ return bubbleEl;
+}
+
+function showSpeechBubble(text) {
+ clearTimeout(bubbleHideTimer);
+ const el = ensureBubble();
+ // Set text without the pointer triangle child
+ const tri = el.lastChild;
+ el.textContent = text.slice(0, 220);
+ el.appendChild(tri);
+ el.style.opacity = '1';
+ // Auto-hide after estimated reading time
+ const ms = Math.max(2500, text.length * 55);
+ bubbleHideTimer = setTimeout(hideSpeechBubble, ms);
+}
+
+function hideSpeechBubble() {
+ if (bubbleEl) bubbleEl.style.opacity = '0';
+}
+
// ── Boot ──────────────────────────────────────────────────────────────────
loadAvatar()
.then(() => {
diff --git a/src/walk.js b/src/walk.js
index 0467146da..6e1555b13 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -11,6 +11,7 @@
import {
AmbientLight,
Box3,
+ CanvasTexture,
CircleGeometry,
Clock,
Color,
@@ -18,9 +19,11 @@ import {
Group,
HemisphereLight,
Mesh,
+ MeshBasicMaterial,
MeshStandardMaterial,
PCFSoftShadowMap,
PerspectiveCamera,
+ PlaneGeometry,
PMREMGenerator,
Quaternion,
Scene,
@@ -109,7 +112,8 @@ const pmrem = new PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
// Lights — ambient + hemi for soft fill, directional for shadow cast.
-scene.add(new AmbientLight(0xffffff, 0.55));
+const ambientLight = new AmbientLight(0xffffff, 0.55);
+scene.add(ambientLight);
const hemi = new HemisphereLight(0xbcd6ff, 0x202830, 0.6);
hemi.position.set(0, 5, 0);
scene.add(hemi);
@@ -125,6 +129,8 @@ sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.bias = -0.0005;
scene.add(sun);
+// sun.target must be in the scene for position updates to take effect.
+scene.add(sun.target);
// Ground — opaque disc in non-AR mode, swapped to a shadow-only catcher in AR.
const groundOpaque = new Mesh(
@@ -144,6 +150,27 @@ groundShadowCatcher.receiveShadow = true;
groundShadowCatcher.visible = false;
scene.add(groundShadowCatcher);
+// Blob contact shadow — radial gradient decal that moves with the avatar.
+// Ensures there is always a convincing foot-contact cue even on low-end
+// devices where PCF shadow maps may be coarse or disabled.
+const _blobCanvas = document.createElement('canvas');
+_blobCanvas.width = 64;
+_blobCanvas.height = 64;
+const _blobCtx = _blobCanvas.getContext('2d');
+const _blobGrad = _blobCtx.createRadialGradient(32, 32, 0, 32, 32, 32);
+_blobGrad.addColorStop(0, 'rgba(0,0,0,0.68)');
+_blobGrad.addColorStop(0.45, 'rgba(0,0,0,0.28)');
+_blobGrad.addColorStop(1, 'rgba(0,0,0,0)');
+_blobCtx.fillStyle = _blobGrad;
+_blobCtx.fillRect(0, 0, 64, 64);
+const blobShadow = new Mesh(
+ new PlaneGeometry(1.0, 1.0),
+ new MeshBasicMaterial({ map: new CanvasTexture(_blobCanvas), transparent: true, depthWrite: false, opacity: 0 }),
+);
+blobShadow.rotation.x = -Math.PI / 2;
+blobShadow.position.y = 0.004;
+scene.add(blobShadow);
+
// Camera + follow-rig — avatar lives at scene origin (translated by a group)
// so the camera offset math stays in local space.
const camera = new PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.05, 200);
@@ -338,6 +365,44 @@ async function loadAvatar() {
setStatus('walk it', { sticky: false });
}
+// ── AR depth: light estimation ────────────────────────────────────────────
+// Sample the camera feed at low resolution each second, derive scene
+// brightness and tint, and adapt ambient/directional/hemi lights so the
+// avatar is lit by the real environment instead of a static studio rig.
+const _leSampleCanvas = document.createElement('canvas');
+_leSampleCanvas.width = 8;
+_leSampleCanvas.height = 6;
+const _leSampleCtx = _leSampleCanvas.getContext('2d', { willReadFrequently: true });
+let _leTickCount = 0;
+const _leColor = new Color();
+
+function estimateLighting() {
+ if (!arActive || video.readyState < 2) return;
+ _leTickCount++;
+ if (_leTickCount % 30 !== 0) return;
+ try {
+ _leSampleCtx.drawImage(video, 0, 0, 8, 6);
+ const px = _leSampleCtx.getImageData(0, 0, 8, 6).data;
+ let r = 0, g = 0, b = 0;
+ const n = px.length / 4;
+ for (let i = 0; i < px.length; i += 4) { r += px[i]; g += px[i + 1]; b += px[i + 2]; }
+ r = r / n / 255;
+ g = g / n / 255;
+ b = b / n / 255;
+ const lum = 0.299 * r + 0.587 * g + 0.114 * b;
+ // Smoothly adapt intensities to real scene brightness.
+ ambientLight.intensity += (0.25 + lum * 0.95 - ambientLight.intensity) * 0.12;
+ sun.intensity += (0.4 + lum * 1.6 - sun.intensity) * 0.12;
+ // Tint the hemisphere sky to the dominant scene color.
+ _leColor.setRGB(
+ Math.min(1, 0.55 + r * 0.9),
+ Math.min(1, 0.55 + g * 0.9),
+ Math.min(1, 0.65 + b * 0.9),
+ );
+ hemi.color.lerp(_leColor, 0.12);
+ } catch { /* cross-origin or tainted canvas — skip */ }
+}
+
// ── AR passthrough ───────────────────────────────────────────────────────
let arActive = false;
let mediaStream = null;
@@ -367,9 +432,30 @@ async function enableAR() {
arBtn.setAttribute('aria-pressed', 'true');
groundOpaque.visible = false;
groundShadowCatcher.visible = true;
+ groundShadowCatcher.material.opacity = 0.55;
renderer.setClearColor(0x000000, 0);
scene.background = null;
+ // Match the Three.js camera FOV to the device rear camera so the avatar's
+ // perspective agrees with the real world (phones are typically ~70-75°).
+ {
+ const track = mediaStream?.getVideoTracks?.()[0];
+ const s = track?.getSettings?.() ?? {};
+ const w = s.width ?? window.innerWidth;
+ const h = s.height ?? window.innerHeight;
+ // Estimate horizontal FOV from diagonal FOV ≈ 72° default for rear cameras.
+ const diagFov = 72;
+ const diagPx = Math.hypot(w, h);
+ const hFovRad = 2 * Math.atan((w / diagPx) * Math.tan((diagFov * Math.PI / 180) / 2));
+ const aspect = window.innerWidth / window.innerHeight;
+ const vFovDeg = (2 * Math.atan(Math.tan(hFovRad / 2) / aspect)) * (180 / Math.PI);
+ camera.fov = Math.max(50, Math.min(90, vFovDeg));
+ camera.updateProjectionMatrix();
+ }
+
+ // Show blob contact shadow.
+ blobShadow.material.opacity = 1;
+
setStatus('AR on — point at a floor');
}
@@ -386,8 +472,19 @@ function disableAR() {
arBtn.setAttribute('aria-pressed', 'false');
groundOpaque.visible = true;
groundShadowCatcher.visible = false;
+ groundShadowCatcher.material.opacity = 0.32;
scene.background = null; // CSS gradient on #walk-stage shows through
+ // Restore camera FOV and lighting defaults.
+ camera.fov = 50;
+ camera.updateProjectionMatrix();
+ ambientLight.intensity = 0.55;
+ sun.intensity = 1.4;
+ hemi.color.set(0xbcd6ff);
+
+ // Hide blob shadow.
+ blobShadow.material.opacity = 0;
+
setStatus('AR off');
}
@@ -519,6 +616,18 @@ function tick() {
camLookCurrent.lerp(camLookTarget, CAM_LERP);
camera.lookAt(camLookCurrent);
+ // AR depth: track sun + blob shadow to the avatar each frame so the
+ // grounding shadow always lands under the feet, and estimate real-world
+ // lighting from the camera feed.
+ if (arActive) {
+ const ap = avatarRig.position;
+ sun.position.set(ap.x + 4, ap.y + 8, ap.z + 6);
+ sun.target.position.copy(ap);
+ sun.target.updateMatrixWorld();
+ blobShadow.position.set(ap.x, 0.004, ap.z);
+ estimateLighting();
+ }
+
// 3. Tick the animation mixer.
animationManager.update(dt);
diff --git a/vercel.json b/vercel.json
index 4b743a820..0b4b767e5 100644
--- a/vercel.json
+++ b/vercel.json
@@ -504,7 +504,7 @@
},
{
"src": "/deploy",
- "dest": "/app.html"
+ "dest": "/app-next.html"
},
{
"src": "/dashboard",
@@ -1892,15 +1892,22 @@
},
{
"src": "/app",
- "dest": "/app.html"
+ "dest": "/app-next.html"
},
{
- "src": "/app-demo",
- "dest": "/app-demo.html"
+ "src": "/app-classic",
+ "dest": "/app.html"
},
{
"src": "/app-next",
- "dest": "/app-next.html"
+ "status": 301,
+ "headers": {
+ "Location": "/app"
+ }
+ },
+ {
+ "src": "/app-demo",
+ "dest": "/app-demo.html"
},
{
"src": "/embed-demo",
@@ -2045,7 +2052,7 @@
},
{
"src": "/a/(.*)",
- "dest": "/app.html"
+ "dest": "/app-next.html"
},
{
"src": "/dist-lib/(.*)",
diff --git a/vite.config.js b/vite.config.js
index ec40bd2a9..1563877ee 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -490,11 +490,11 @@ creating: resolve(__dirname, 'pages/creating.html'),
res.setHeader('Location', '/discover/');
return res.end();
}
- // /discover/avatar/:id → canonical marketplace detail page
+ // /discover/avatar/:id → canonical /avatars/:id (avatar studio page)
const discoverAvatarM = path.match(/^\/discover\/avatar\/([^/]+)\/?$/);
if (discoverAvatarM) {
res.statusCode = 301;
- res.setHeader('Location', `/marketplace/agents/${discoverAvatarM[1]}`);
+ res.setHeader('Location', `/avatars/${discoverAvatarM[1]}`);
return res.end();
}
// /widget-studio was a legacy standalone page; /studio is canonical
@@ -578,6 +578,9 @@ creating: resolve(__dirname, 'pages/creating.html'),
// /embed/avatar/:handle → portable avatar embed by handle
else if (!filePath && /^\/embed\/avatar(\/[a-z0-9_-]{3,30})?\/?$/i.test(path))
filePath = resolve(root, 'pages/avatar-embed.html');
+ // /avatars/:id → avatar studio page (mirrors vercel.json rewrite)
+ else if (!filePath && /^\/avatars\/[^/.]+\/?$/.test(path))
+ filePath = resolve(root, 'pages/avatar-page.html');
// /@<handle> → public live profile page
else if (!filePath && /^\/@[a-z0-9_-]{3,30}\/?$/i.test(path))
filePath = resolve(root, 'pages/handle.html');